code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class Project(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> description = models.CharField(max_length=5000, blank=True) <NEW_LINE> svn_path = models.CharField(max_length=500) <NEW_LINE> version = models.CharField(max_length=20) <NEW_LINE> public_time = models.DateTimeField() <NEW_LINE> build_file_name = models.CharField(max_length=200) <NEW_LINE> release_note_file_name = models.CharField(max_length=200) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name | 项目,用来定义所有项目信息 | 6259906963d6d428bbee3e6f |
class IotHubDescriptionListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[IotHubDescription]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["IotHubDescription"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(IotHubDescriptionListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None | The JSON-serialized array of IotHubDescription objects with a next link.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: The array of IotHubDescription objects.
:vartype value: list[~azure.mgmt.iothub.v2016_02_03.models.IotHubDescription]
:ivar next_link: The next link.
:vartype next_link: str | 62599069a219f33f346c7fd4 |
class JSONEncoderForHTML(json.JSONEncoder): <NEW_LINE> <INDENT> def encode(self, o): <NEW_LINE> <INDENT> chunks = self.iterencode(o) <NEW_LINE> if self.ensure_ascii: <NEW_LINE> <INDENT> return ''.join(chunks) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return u''.join(chunks) <NEW_LINE> <DEDENT> <DEDENT> def iterencode(self, o): <NEW_LINE> <INDENT> chunks = super(JSONEncoderForHTML, self).iterencode(o) <NEW_LINE> for chunk in chunks: <NEW_LINE> <INDENT> chunk = chunk.replace('&', '\\u0026') <NEW_LINE> chunk = chunk.replace('<', '\\u003c') <NEW_LINE> chunk = chunk.replace('>', '\\u003e') <NEW_LINE> yield chunk | An encoder that produces JSON safe to embed in HTML.
To embed JSON content in, say, a script tag on a web page, the
characters &, < and > should be escaped. They cannot be escaped
with the usual entities (e.g. &) because they are not expanded
within <script> tags.
Originally from the simplejson project:
https://github.com/simplejson/simplejson | 625990692c8b7c6e89bd4fb2 |
class ChatsSlice(TLObject): <NEW_LINE> <INDENT> __slots__ = ["count", "chats"] <NEW_LINE> ID = 0x9cd81144 <NEW_LINE> QUALNAME = "types.messages.ChatsSlice" <NEW_LINE> def __init__(self, *, count: int, chats: list): <NEW_LINE> <INDENT> self.count = count <NEW_LINE> self.chats = chats <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "ChatsSlice": <NEW_LINE> <INDENT> count = Int.read(b) <NEW_LINE> chats = TLObject.read(b) <NEW_LINE> return ChatsSlice(count=count, chats=chats) <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.count)) <NEW_LINE> b.write(Vector(self.chats)) <NEW_LINE> return b.getvalue() | Attributes:
LAYER: ``112``
Attributes:
ID: ``0x9cd81144``
Parameters:
count: ``int`` ``32-bit``
chats: List of either :obj:`ChatEmpty <pyrogram.api.types.ChatEmpty>`, :obj:`Chat <pyrogram.api.types.Chat>`, :obj:`ChatForbidden <pyrogram.api.types.ChatForbidden>`, :obj:`Channel <pyrogram.api.types.Channel>` or :obj:`ChannelForbidden <pyrogram.api.types.ChannelForbidden>`
See Also:
This object can be returned by :obj:`messages.GetChats <pyrogram.api.functions.messages.GetChats>`, :obj:`messages.GetCommonChats <pyrogram.api.functions.messages.GetCommonChats>`, :obj:`messages.GetAllChats <pyrogram.api.functions.messages.GetAllChats>`, :obj:`channels.GetChannels <pyrogram.api.functions.channels.GetChannels>`, :obj:`channels.GetAdminedPublicChannels <pyrogram.api.functions.channels.GetAdminedPublicChannels>`, :obj:`channels.GetLeftChannels <pyrogram.api.functions.channels.GetLeftChannels>` and :obj:`channels.GetGroupsForDiscussion <pyrogram.api.functions.channels.GetGroupsForDiscussion>`. | 62599069796e427e5384ff43 |
class ModeratorRegisterView(CreateView): <NEW_LINE> <INDENT> template_name = "moderators/signup.html" <NEW_LINE> form_class = ModeratorRegisterForm <NEW_LINE> def get_success_url(self) -> str: <NEW_LINE> <INDENT> return reverse_lazy('moderators:login') | Provides moderators the ability to register | 6259906991f36d47f2231a75 |
class TracCommon(Stats): <NEW_LINE> <INDENT> def __init__(self, option, name=None, parent=None): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> Stats.__init__(self, option, name, parent) | Common Trac Stats object for saving prefix & proxy | 6259906932920d7e50bc7813 |
class ClaimCoverage(backboneelement.BackboneElement): <NEW_LINE> <INDENT> resource_name = "ClaimCoverage" <NEW_LINE> def __init__(self, jsondict=None): <NEW_LINE> <INDENT> self.businessArrangement = None <NEW_LINE> self.claimResponse = None <NEW_LINE> self.coverage = None <NEW_LINE> self.focal = None <NEW_LINE> self.originalRuleset = None <NEW_LINE> self.preAuthRef = None <NEW_LINE> self.relationship = None <NEW_LINE> self.sequence = None <NEW_LINE> super(ClaimCoverage, self).__init__(jsondict) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(ClaimCoverage, self).elementProperties() <NEW_LINE> js.extend([ ("businessArrangement", "businessArrangement", str, False, None, False), ("claimResponse", "claimResponse", fhirreference.FHIRReference, False, None, False), ("coverage", "coverage", fhirreference.FHIRReference, False, None, True), ("focal", "focal", bool, False, None, True), ("originalRuleset", "originalRuleset", coding.Coding, False, None, False), ("preAuthRef", "preAuthRef", str, True, None, False), ("relationship", "relationship", coding.Coding, False, None, True), ("sequence", "sequence", int, False, None, True), ]) <NEW_LINE> return js | Insurance or medical plan.
Financial instrument by which payment information for health care. | 62599069a8370b77170f1b91 |
class BatteryReader(object): <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.stat_fin = open(os.path.join(self.path, 'status')) <NEW_LINE> self.now_fin = open(os.path.join(self.path, 'energy_now')) <NEW_LINE> self.full_fin = open(os.path.join(self.path, 'energy_full')) <NEW_LINE> <DEDENT> def stat(self): <NEW_LINE> <INDENT> self.stat_fin.seek(0) <NEW_LINE> return self.stat_fin.read().strip() <NEW_LINE> <DEDENT> def percent(self): <NEW_LINE> <INDENT> self.now_fin.seek(0) <NEW_LINE> self.full_fin.seek(0) <NEW_LINE> return 100 * float(self.now_fin.read())/float(self.full_fin.read()) | Battery using functions eats 80% of cpu see if you hold a file
handle if it improves | 62599069091ae356687063fe |
class Data: <NEW_LINE> <INDENT> def __init__(self, train_x, train_y, dev_x, dev_y, test_x, test_y, timesteps=None, data_dim=200, vocab_size=0): <NEW_LINE> <INDENT> self.train_x = train_x <NEW_LINE> self.train_y = train_y <NEW_LINE> self.dev_x = dev_x <NEW_LINE> self.dev_y = dev_y <NEW_LINE> self.test_x = test_x <NEW_LINE> self.test_y = test_y <NEW_LINE> self.timesteps = timesteps <NEW_LINE> self.data_dim = data_dim <NEW_LINE> self.vocab_size = vocab_size | Data representation:
separates train, dev, and test sets
holds meta data about data properties | 62599069460517430c432c3b |
class FooItemAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ("title",) <NEW_LINE> prepopulated_fields = {"slug": ("title",)} <NEW_LINE> fieldsets = ( (None, {"fields": ("title", "slug", "body")}), ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = _("Foo item") | Foo item admin. | 625990694f88993c371f1105 |
class ExampleError(Exception): <NEW_LINE> <INDENT> def __init__(self, msg, code): <NEW_LINE> <INDENT> self.msg = msg <NEW_LINE> self.code = code | Exceptions are documented in the same way as classes.
The __init__ method may be documented in either the class level
docstring, or as a docstring on the __init__ method itself.
Either form is acceptable, but the two should not be mixed. Choose one
convention to document the __init__ method and be consistent with it.
Note:
Do not include the `self` parameter in the ``Args`` section.
Args:
msg (str):
Human readable string describing the exception.
code (Optional[int]):
Error code.
Attributes:
msg (str):
Human readable string describing the exception.
code (int):
Exception error code. | 62599069cc0a2c111447c6b6 |
class FloatField(BaseField): <NEW_LINE> <INDENT> def parse(self, xml, namespace): <NEW_LINE> <INDENT> value = self._fetch_by_xpath(xml, namespace) <NEW_LINE> if value: <NEW_LINE> <INDENT> return float(value) <NEW_LINE> <DEDENT> return self._default | Returns the single value found by the xpath expression, as a float | 6259906992d797404e389742 |
class Block: <NEW_LINE> <INDENT> sizew = 40 <NEW_LINE> sizeh = 20 <NEW_LINE> x,y = 0, 0 <NEW_LINE> colour = 'red' <NEW_LINE> newc = 'black' <NEW_LINE> value = 1 <NEW_LINE> hits = 3 <NEW_LINE> broken = True | A Blocks represent blocks in the game | 62599069379a373c97d9a7eb |
class TestUnInstallation(CMFNotificationTestCase): <NEW_LINE> <INDENT> def afterSetUp(self): <NEW_LINE> <INDENT> qtool = getToolByName(self.portal, 'portal_quickinstaller') <NEW_LINE> self.setRoles(['Manager']) <NEW_LINE> qtool.uninstallProducts(['CMFNotification']) <NEW_LINE> <DEDENT> def testToolIsNotThere(self): <NEW_LINE> <INDENT> tool = getToolByName(self.portal, TOOL_ID, None) <NEW_LINE> self.failUnless(tool is None) <NEW_LINE> <DEDENT> def testSkinLayerIsNotThere(self): <NEW_LINE> <INDENT> stool = getToolByName(self.portal, 'portal_skins') <NEW_LINE> for skin, layers in stool._getSelections().items(): <NEW_LINE> <INDENT> layers = layers.split(',') <NEW_LINE> self.failUnless (LAYER_NAME not in layers) <NEW_LINE> <DEDENT> self.failUnless(LAYER_NAME not in stool.objectIds()) <NEW_LINE> <DEDENT> def testPortletDoNoExist(self): <NEW_LINE> <INDENT> base_url = self.portal.absolute_url() <NEW_LINE> for name in ('plone.leftcolumn', 'plone.rightcolumn'): <NEW_LINE> <INDENT> manager = getUtility(IPortletManager, name=name, context=self.portal) <NEW_LINE> titles = [p.title for p in manager.getAddablePortletTypes()] <NEW_LINE> self.failUnless(PORTLET_NAME not in titles) <NEW_LINE> <DEDENT> manager = getUtility(IPortletManager, name='plone.rightcolumn', context=self.portal) <NEW_LINE> right_portlets = getMultiAdapter((self.portal, manager), IPortletAssignmentMapping, context=self.portal) <NEW_LINE> right_portlets = right_portlets.keys() <NEW_LINE> self.failUnless(PORTLET_NAME not in right_portlets) <NEW_LINE> <DEDENT> def testConfigletDoNotExist(self): <NEW_LINE> <INDENT> cptool = getToolByName(self.portal, 'portal_controlpanel') <NEW_LINE> configlets = [c.getId() for c in cptool.listActions()] <NEW_LINE> self.failUnless('cmfnotification_configuration' not in configlets) | Test that the product has been properly uninstalled. | 625990697d43ff2487427ff7 |
class OvertimeCredit(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="overtime_credits", ) <NEW_LINE> comment = models.CharField(max_length=255, blank=True) <NEW_LINE> date = models.DateField() <NEW_LINE> duration = models.DurationField(default=timedelta(0)) <NEW_LINE> transfer = models.BooleanField(default=False) | Overtime credit model.
An overtime credit is a transferred overtime from the last year. This is
added to the worktime of a user. | 6259906921bff66bcd724433 |
class Upper_Lip_pt(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.upper_lip_pt" <NEW_LINE> bl_label = "Upper Lip" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> found = 'Upper Lip' in bpy.data.objects <NEW_LINE> if found == False: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if found == True: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> CriaPontoDef('Upper Lip', 'Anatomical Points - Soft Tissue') <NEW_LINE> TestaPontoCollDef() <NEW_LINE> return {'FINISHED'} | Tooltip | 62599069435de62698e9d5d8 |
class TestMigrateToSplit(ModuleStoreTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestMigrateToSplit, self).setUp() <NEW_LINE> self.course = CourseFactory(default_store=ModuleStoreEnum.Type.mongo) <NEW_LINE> <DEDENT> def test_user_email(self): <NEW_LINE> <INDENT> call_command( "migrate_to_split", str(self.course.id), str(self.user.email), ) <NEW_LINE> split_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.split) <NEW_LINE> new_key = split_store.make_course_key(self.course.id.org, self.course.id.course, self.course.id.run) <NEW_LINE> self.assertTrue( split_store.has_course(new_key), "Could not find course" ) <NEW_LINE> <DEDENT> def test_user_id(self): <NEW_LINE> <INDENT> call_command( "migrate_to_split", str(self.course.id), str(self.user.id), ) <NEW_LINE> <DEDENT> def test_locator_string(self): <NEW_LINE> <INDENT> call_command( "migrate_to_split", str(self.course.id), str(self.user.id), org="org.dept", course="name", run="run", ) <NEW_LINE> split_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.split) <NEW_LINE> locator = split_store.make_course_key("org.dept", "name", "run") <NEW_LINE> course_from_split = split_store.get_course(locator) <NEW_LINE> self.assertIsNotNone(course_from_split) <NEW_LINE> mongo_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.mongo) <NEW_LINE> mongo_locator = mongo_store.make_course_key(self.course.id.org, self.course.id.course, self.course.id.run) <NEW_LINE> course_from_mongo = mongo_store.get_course(mongo_locator) <NEW_LINE> self.assertIsNotNone(course_from_mongo) <NEW_LINE> split_locator = split_store.make_course_key(self.course.id.org, self.course.id.course, self.course.id.run) <NEW_LINE> with self.assertRaises(ItemNotFoundError): <NEW_LINE> <INDENT> mongo_store.get_course(split_locator) | Unit tests for migrating a course from old mongo to split mongo | 62599069097d151d1a2c283a |
class Symmetric(Kernpart): <NEW_LINE> <INDENT> def __init__(self,k,transform=None): <NEW_LINE> <INDENT> if transform is None: <NEW_LINE> <INDENT> transform = np.eye(k.input_dim)*-1. <NEW_LINE> <DEDENT> assert transform.shape == (k.input_dim, k.input_dim) <NEW_LINE> self.transform = transform <NEW_LINE> self.input_dim = k.input_dim <NEW_LINE> self.num_params = k.num_params <NEW_LINE> self.name = k.name + '_symm' <NEW_LINE> self.k = k <NEW_LINE> self.add_parameter(k) <NEW_LINE> <DEDENT> def K(self,X,X2,target): <NEW_LINE> <INDENT> AX = np.dot(X,self.transform) <NEW_LINE> if X2 is None: <NEW_LINE> <INDENT> X2 = X <NEW_LINE> AX2 = AX <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> AX2 = np.dot(X2, self.transform) <NEW_LINE> <DEDENT> self.k.K(X,X2,target) <NEW_LINE> self.k.K(AX,X2,target) <NEW_LINE> self.k.K(X,AX2,target) <NEW_LINE> self.k.K(AX,AX2,target) <NEW_LINE> <DEDENT> def _param_grad_helper(self,dL_dK,X,X2,target): <NEW_LINE> <INDENT> AX = np.dot(X,self.transform) <NEW_LINE> if X2 is None: <NEW_LINE> <INDENT> X2 = X <NEW_LINE> ZX2 = AX <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> AX2 = np.dot(X2, self.transform) <NEW_LINE> <DEDENT> self.k._param_grad_helper(dL_dK,X,X2,target) <NEW_LINE> self.k._param_grad_helper(dL_dK,AX,X2,target) <NEW_LINE> self.k._param_grad_helper(dL_dK,X,AX2,target) <NEW_LINE> self.k._param_grad_helper(dL_dK,AX,AX2,target) <NEW_LINE> <DEDENT> def gradients_X(self,dL_dK,X,X2,target): <NEW_LINE> <INDENT> AX = np.dot(X,self.transform) <NEW_LINE> if X2 is None: <NEW_LINE> <INDENT> X2 = X <NEW_LINE> ZX2 = AX <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> AX2 = np.dot(X2, self.transform) <NEW_LINE> <DEDENT> self.k.gradients_X(dL_dK, X, X2, target) <NEW_LINE> self.k.gradients_X(dL_dK, AX, X2, target) <NEW_LINE> self.k.gradients_X(dL_dK, X, AX2, target) <NEW_LINE> self.k.gradients_X(dL_dK, AX ,AX2, target) <NEW_LINE> <DEDENT> def Kdiag(self,X,target): <NEW_LINE> <INDENT> foo = np.zeros((X.shape[0],X.shape[0])) <NEW_LINE> self.K(X,X,foo) <NEW_LINE> target += np.diag(foo) <NEW_LINE> <DEDENT> def dKdiag_dX(self,dL_dKdiag,X,target): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def dKdiag_dtheta(self,dL_dKdiag,X,target): <NEW_LINE> <INDENT> raise NotImplementedError | Symmetrical kernels
:param k: the kernel to symmetrify
:type k: Kernpart
:param transform: the transform to use in symmetrification (allows symmetry on specified axes)
:type transform: A numpy array (input_dim x input_dim) specifiying the transform
:rtype: Kernpart | 62599069e5267d203ee6cfa4 |
class DiffResultDescriptor: <NEW_LINE> <INDENT> def __init__(self, diff_function): <NEW_LINE> <INDENT> self.diff_function = diff_function <NEW_LINE> self.instances = WeakKeyDictionary() <NEW_LINE> <DEDENT> def __get__(self, obj, objtype=None): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> if self.instances.setdefault(obj, None) is None: <NEW_LINE> <INDENT> diff = getattr(obj, self.diff_function) <NEW_LINE> diff() <NEW_LINE> <DEDENT> return self.instances[obj] <NEW_LINE> <DEDENT> def __set__(self, obj, value): <NEW_LINE> <INDENT> self.instances[obj] = value <NEW_LINE> <DEDENT> def __delete__(self, obj): <NEW_LINE> <INDENT> self.instances[obj] = None | Descriptor for managing diff results. | 62599069ac7a0e7691f73cb4 |
class ViewDebate(DetailView): <NEW_LINE> <INDENT> context_object_name = 'debate' <NEW_LINE> template_name = 'debate/debate_view.html' <NEW_LINE> def get_object(self): <NEW_LINE> <INDENT> key = self.kwargs['debate_id'] <NEW_LINE> debate = get_or_insert_object_in_cache(Debate, key, pk=key) <NEW_LINE> if datetime.date.today() >= debate.end_date or datetime.date.today() < debate.start_date: <NEW_LINE> <INDENT> self.template_name = 'debate/debate_outdated.html' <NEW_LINE> <DEDENT> return debate <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(ViewDebate, self).get_context_data(**kwargs) <NEW_LINE> columns = Column.objects.filter(debate=self.kwargs['debate_id']) <NEW_LINE> rows = Row.objects.filter(debate=self.kwargs['debate_id']) <NEW_LINE> space_key = self.kwargs['space_url'] <NEW_LINE> current_space = get_or_insert_object_in_cache(Space, space_key, url=space_key) <NEW_LINE> debate_key = self.kwargs['debate_id'] <NEW_LINE> current_debate = get_or_insert_object_in_cache(Debate, debate_key, pk=debate_key) <NEW_LINE> notes = Note.objects.filter(debate=current_debate.pk) <NEW_LINE> try: <NEW_LINE> <INDENT> last_note = Note.objects.latest('id') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> last_note = 0 <NEW_LINE> <DEDENT> context['get_place'] = current_space <NEW_LINE> context['notes'] = notes <NEW_LINE> context['columns'] = columns <NEW_LINE> context['rows'] = rows <NEW_LINE> if last_note == 0: <NEW_LINE> <INDENT> context['lastnote'] = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context['lastnote'] = last_note.pk <NEW_LINE> <DEDENT> return context | View a debate.
:context: get_place, notes, columns, rows | 6259906944b2445a339b7546 |
class AverageMeter(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.clear() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.avg = 0 <NEW_LINE> self.val = 0 <NEW_LINE> self.sum = 0 <NEW_LINE> self.count = 0 <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.reset() <NEW_LINE> self.history = [] <NEW_LINE> <DEDENT> def update(self, val, n=1): <NEW_LINE> <INDENT> self.val = val <NEW_LINE> self.sum += val * n <NEW_LINE> self.count += n <NEW_LINE> if self.count > 0: <NEW_LINE> <INDENT> self.avg = self.sum / self.count <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.avg = 'nan' <NEW_LINE> <DEDENT> <DEDENT> def new_epoch(self): <NEW_LINE> <INDENT> self.history.append(self.avg) <NEW_LINE> self.reset() | Computes and stores the average and current value | 625990692c8b7c6e89bd4fb3 |
class Dropout3d(Module): <NEW_LINE> <INDENT> def __init__(self, p=0.5, inplace=False): <NEW_LINE> <INDENT> super(Dropout3d, self).__init__() <NEW_LINE> if p < 0 or p > 1: <NEW_LINE> <INDENT> raise ValueError("dropout probability has to be between 0 and 1, " "but got {}".format(p)) <NEW_LINE> <DEDENT> self.p = p <NEW_LINE> self.inplace = inplace <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> return F.dropout3d(input, self.p, self.training, self.inplace) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> inplace_str = ', inplace' if self.inplace else '' <NEW_LINE> return self.__class__.__name__ + '(' + 'p=' + str(self.p) + inplace_str + ')' | Randomly zeroes whole channels of the input tensor.
The channels to zero are randomized on every forward call.
*Usually the input comes from Conv3d modules.*
As described in the paper
`Efficient Object Localization Using Convolutional Networks`_ ,
if adjacent pixels within feature maps are strongly correlated
(as is normally the case in early convolution layers) then iid dropout
will not regularize the activations and will otherwise just result
in an effective learning rate decrease.
In this case, :func:`nn.Dropout3d` will help promote independence between
feature maps and should be used instead.
Args:
p (float, optional): probability of an element to be zeroed.
inplace (bool, optional): If set to True, will do this operation
in-place
Shape:
- Input: :math:`(N, C, D, H, W)`
- Output: :math:`(N, C, D, H, W)` (same shape as input)
Examples::
>>> m = nn.Dropout3d(p=0.2)
>>> input = autograd.Variable(torch.randn(20, 16, 4, 32, 32))
>>> output = m(input)
.. _Efficient Object Localization Using Convolutional Networks:
http://arxiv.org/abs/1411.4280 | 625990697047854f46340b83 |
class Extender(Super): <NEW_LINE> <INDENT> def method(self): <NEW_LINE> <INDENT> print('starting Extender.method') <NEW_LINE> Super.method(self) <NEW_LINE> print('ending Extender.method') | Failed to make an instance unless action is defined. | 6259906945492302aabfdca5 |
class AlgorithmRunner(object): <NEW_LINE> <INDENT> def __init__(self, renderRefreshMethod=None): <NEW_LINE> <INDENT> self.algorithm = None <NEW_LINE> self.thread = None <NEW_LINE> self.forcedToStop = False <NEW_LINE> self.threadExceptionBucket = Queue() <NEW_LINE> self.renderRefreshMethod = renderRefreshMethod <NEW_LINE> self.sleepTime = 0.1 <NEW_LINE> <DEDENT> def SetAlgorithm(self, algorithm): <NEW_LINE> <INDENT> if not isinstance(algorithm, Algorithm): <NEW_LINE> <INDENT> raise NotAnAlgorithmException(algorithm) <NEW_LINE> <DEDENT> self.algorithm = algorithm <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.forcedToStop = False <NEW_LINE> self.threadExceptionBucket = Queue() <NEW_LINE> self.thread = AlgorithmThread(self._run, self.threadExceptionBucket) <NEW_LINE> self.thread.daemon = True <NEW_LINE> self.thread.start() <NEW_LINE> <DEDENT> def _run(self): <NEW_LINE> <INDENT> while not self.forcedToStop: <NEW_LINE> <INDENT> self.step() <NEW_LINE> time.sleep(self.sleepTime) <NEW_LINE> <DEDENT> <DEDENT> def isRunning(self): <NEW_LINE> <INDENT> return not self.thread is None and self.thread.isAlive() <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> if not self.algorithm.endCondition(): <NEW_LINE> <INDENT> for sleepMultiplier in self.algorithm.step(): <NEW_LINE> <INDENT> multiplier = 1.0 <NEW_LINE> if sleepMultiplier is not None: <NEW_LINE> <INDENT> multiplier = sleepMultiplier <NEW_LINE> <DEDENT> self.renderRefreshMethod() <NEW_LINE> time.sleep(multiplier * self.sleepTime) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.forcedToStop = True <NEW_LINE> <DEDENT> def getThreadException(self): <NEW_LINE> <INDENT> if self.threadExceptionBucket.empty(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.threadExceptionBucket.get()[1] | This class should have the following features | 6259906926068e7796d4e107 |
class MembersGetInfoArgs(bb.Struct): <NEW_LINE> <INDENT> __slots__ = [ '_members_value', '_members_present', ] <NEW_LINE> _has_required_fields = True <NEW_LINE> def __init__(self, members=None): <NEW_LINE> <INDENT> self._members_value = None <NEW_LINE> self._members_present = False <NEW_LINE> if members is not None: <NEW_LINE> <INDENT> self.members = members <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def members(self): <NEW_LINE> <INDENT> if self._members_present: <NEW_LINE> <INDENT> return self._members_value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError("missing required field 'members'") <NEW_LINE> <DEDENT> <DEDENT> @members.setter <NEW_LINE> def members(self, val): <NEW_LINE> <INDENT> val = self._members_validator.validate(val) <NEW_LINE> self._members_value = val <NEW_LINE> self._members_present = True <NEW_LINE> <DEDENT> @members.deleter <NEW_LINE> def members(self): <NEW_LINE> <INDENT> self._members_value = None <NEW_LINE> self._members_present = False <NEW_LINE> <DEDENT> def _process_custom_annotations(self, annotation_type, field_path, processor): <NEW_LINE> <INDENT> super(MembersGetInfoArgs, self)._process_custom_annotations(annotation_type, field_path, processor) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'MembersGetInfoArgs(members={!r})'.format( self._members_value, ) | :ivar team.MembersGetInfoArgs.members: List of team members. | 625990695166f23b2e244ba0 |
class AbstractFormBuilder(object, metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.constructed_object = None <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def add_text_field(self, field_dict): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def add_checkbox(self, checkbox_dict): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def add_button(self, button_dict): <NEW_LINE> <INDENT> pass | Builder interface specifying methods to create input, checkbox and button fields | 6259906999cbb53fe68326b4 |
class SaleOrder(geo_model.GeoModel): <NEW_LINE> <INDENT> _inherit = "sale.order" <NEW_LINE> geo_point = fields.GeoPoint( 'Addresses coordinate', related='partner_invoice_id.geo_point') | Add geo_point to sale.order | 62599069009cb60464d02d07 |
class WindowRateLimiter(RateLimiter): <NEW_LINE> <INDENT> def __init__(self, backend, key, *, limit=1, window=1): <NEW_LINE> <INDENT> assert limit >= 1, "limit must be positive" <NEW_LINE> assert window >= 1, "window must be positive" <NEW_LINE> super().__init__(backend, key) <NEW_LINE> self.limit = limit <NEW_LINE> self.window = window <NEW_LINE> self.window_millis = window * 1000 <NEW_LINE> <DEDENT> def _get_keys(self): <NEW_LINE> <INDENT> timestamp = int(time.time()) <NEW_LINE> return ["%s@%s" % (self.key, timestamp - i) for i in range(self.window)] <NEW_LINE> <DEDENT> def _acquire(self): <NEW_LINE> <INDENT> keys = self._get_keys() <NEW_LINE> return self.backend.incr_and_sum(keys[0], self._get_keys, 1, maximum=self.limit, ttl=self.window_millis) <NEW_LINE> <DEDENT> def _release(self): <NEW_LINE> <INDENT> pass | A rate limiter that ensures that only `limit` operations may
happen over some sliding window.
Note:
Windows are in seconds rather that milliseconds. This is
different from most durations and intervals used in Remoulade,
because keeping metadata at the millisecond level is far too
expensive for most use cases.
Parameters:
backend(RateLimiterBackend): The backend to use.
key(str): The key to rate limit on.
limit(int): The maximum number of operations per window per key.
window(int): The window size in *seconds*. The wider the
window, the more expensive it is to maintain. | 6259906991f36d47f2231a76 |
class AjouterSalle(forms.Form): <NEW_LINE> <INDENT> nom = forms.CharField(required=True, max_length=30, label="", widget=forms.TextInput(attrs={'placeholder': 'Nom', 'class':'form-control input-perso'})) <NEW_LINE> capacite = forms.IntegerField(required=False, label="", widget=forms.TextInput(attrs={'placeholder': 'Capacite', 'class':'form-control input-perso'})) <NEW_LINE> type = forms.ChoiceField(label="", choices=SALLES, initial=INCONNU_STATUT_SALLE) <NEW_LINE> def clean(self): <NEW_LINE> <INDENT> if models.Salle.objects.filter(nom=self.cleaned_data.get('nom')).exists(): <NEW_LINE> <INDENT> raise ValidationError( "Le nom de la salle est deja utlise" ) <NEW_LINE> <DEDENT> return self.cleaned_data <NEW_LINE> <DEDENT> def save(self, p): <NEW_LINE> <INDENT> data = self.cleaned_data <NEW_LINE> nom = data['nom'] <NEW_LINE> capacite = data['capacite'] <NEW_LINE> typee = data['type'] <NEW_LINE> addData.addSalle(p, nom, capacite, typee) | A Form to add a classroom to the database.
:Exemples:
>> form=AjouterSalle()
>> form
return html code of the form
>> form=AjouterSalle(request.POST)
>> form.cleaned_data['nom']
returns the name of the classroom that the user wants to add
>> form=AjouterSalle(request.POST)
>> if form.is_valid():
>> form.save()
save in the database the classroom
| 62599069091ae35668706400 |
class RandomTranslate(object): <NEW_LINE> <INDENT> def __init__(self, translate=0.2, diff=False): <NEW_LINE> <INDENT> self.translate = translate <NEW_LINE> if type(self.translate) == tuple: <NEW_LINE> <INDENT> assert len(self.translate) == 2, "Invalid range" <NEW_LINE> assert self.translate[0] > 0 & self.translate[0] < 1 <NEW_LINE> assert self.translate[1] > 0 & self.translate[1] < 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert self.translate > 0 and self.translate < 1 <NEW_LINE> self.translate = (-self.translate, self.translate) <NEW_LINE> <DEDENT> self.diff = diff <NEW_LINE> <DEDENT> def __call__(self, img, bboxes): <NEW_LINE> <INDENT> img_shape = img.shape <NEW_LINE> translate_factor_x = random.uniform(*self.translate) <NEW_LINE> translate_factor_y = random.uniform(*self.translate) <NEW_LINE> if not self.diff: <NEW_LINE> <INDENT> translate_factor_y = translate_factor_x <NEW_LINE> <DEDENT> canvas = np.zeros(img_shape).astype(np.uint8) <NEW_LINE> corner_x = int(translate_factor_x * img.shape[1]) <NEW_LINE> corner_y = int(translate_factor_y * img.shape[0]) <NEW_LINE> orig_box_cords = [max(0, corner_y), max(corner_x, 0), min( img_shape[0], corner_y + img.shape[0]), min(img_shape[1], corner_x + img.shape[1])] <NEW_LINE> mask = img[max(-corner_y, 0):min(img.shape[0], -corner_y + img_shape[0]), max(-corner_x, 0):min(img.shape[1], -corner_x + img_shape[1]), :] <NEW_LINE> canvas[orig_box_cords[0]:orig_box_cords[2], orig_box_cords[1]:orig_box_cords[3], :] = mask <NEW_LINE> img = canvas <NEW_LINE> bboxes[:, :4] += [corner_x, corner_y, corner_x, corner_y] <NEW_LINE> bboxes = clip_box(bboxes, [0, 0, img_shape[1], img_shape[0]], 0.25) <NEW_LINE> return img, bboxes | Randomly Translates the image
Bounding boxes which have an area of less than 25% in the remaining in the
transformed image is dropped. The resolution is maintained, and the remaining
area if any is filled by black color.
Parameters
----------
translate: float or tuple(float)
if **float**, the image is translated by a factor drawn
randomly from a range (1 - `translate` , 1 + `translate`). If **tuple**,
`translate` is drawn randomly from values specified by the
tuple
Returns
-------
numpy.ndaaray
Translated image in the numpy format of shape `HxWxC`
numpy.ndarray
Tranformed bounding box co-ordinates of the format `n x 4` where n is
number of bounding boxes and 4 represents `x1,y1,x2,y2` of the box | 6259906992d797404e389743 |
class Pais(models.Model): <NEW_LINE> <INDENT> nombre = models.CharField(max_length=100) | Guarda los paises | 625990695fc7496912d48e4f |
class ChargeSpecError(SpecError): <NEW_LINE> <INDENT> pass | Charge specification error. | 625990693539df3088ecda6e |
class TeraSort(luigi.hadoop_jar.HadoopJarJobTask): <NEW_LINE> <INDENT> terasort_in = luigi.Parameter(default=DEFAULT_TERASORT_IN, description="directory to store terasort input into.") <NEW_LINE> terasort_out = luigi.Parameter(default=DEFAULT_TERASORT_OUT, description="directory to store terasort output into.") <NEW_LINE> def requires(self): <NEW_LINE> <INDENT> return TeraGen(terasort_in=self.terasort_in) <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> return luigi.hdfs.HdfsTarget(self.terasort_out) <NEW_LINE> <DEDENT> def jar(self): <NEW_LINE> <INDENT> return hadoop_examples_jar() <NEW_LINE> <DEDENT> def main(self): <NEW_LINE> <INDENT> return "terasort" <NEW_LINE> <DEDENT> def args(self): <NEW_LINE> <INDENT> return [self.input(), self.output()] | Runs TeraGent, by default using | 6259906971ff763f4b5e8f75 |
class _IRandomGeneratorProxy: <NEW_LINE> <INDENT> __jsii_type__: typing.ClassVar[str] = "@aws-cdk/aws-autoscaling-common.IRandomGenerator" <NEW_LINE> @jsii.member(jsii_name="nextBoolean") <NEW_LINE> def next_boolean(self) -> builtins.bool: <NEW_LINE> <INDENT> return jsii.invoke(self, "nextBoolean", []) <NEW_LINE> <DEDENT> @jsii.member(jsii_name="nextInt") <NEW_LINE> def next_int(self, min: jsii.Number, max: jsii.Number) -> jsii.Number: <NEW_LINE> <INDENT> return jsii.invoke(self, "nextInt", [min, max]) | :stability: experimental | 62599069cb5e8a47e493cd6b |
class ICouponCreatedEvent(BaseWebhookEvent): <NEW_LINE> <INDENT> pass | describes a coupon - Occurs whenever a coupon is created. | 625990693d592f4c4edbc6af |
class V1VolumeError(object): <NEW_LINE> <INDENT> openapi_types = { 'message': 'str', 'time': 'datetime' } <NEW_LINE> attribute_map = { 'message': 'message', 'time': 'time' } <NEW_LINE> def __init__(self, message=None, time=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._message = None <NEW_LINE> self._time = None <NEW_LINE> self.discriminator = None <NEW_LINE> if message is not None: <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> if time is not None: <NEW_LINE> <INDENT> self.time = time <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def message(self): <NEW_LINE> <INDENT> return self._message <NEW_LINE> <DEDENT> @message.setter <NEW_LINE> def message(self, message): <NEW_LINE> <INDENT> self._message = message <NEW_LINE> <DEDENT> @property <NEW_LINE> def time(self): <NEW_LINE> <INDENT> return self._time <NEW_LINE> <DEDENT> @time.setter <NEW_LINE> def time(self, time): <NEW_LINE> <INDENT> self._time = time <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1VolumeError): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1VolumeError): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 6259906963d6d428bbee3e71 |
class EnrollmentFrame(Frame): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> Frame.__init__(self, parent) <NEW_LINE> Label(self, text="Enrollment Frame").grid(row=0, column=0, sticky="w") | Frame container for Enrollment screen | 6259906999cbb53fe68326b6 |
class RandomGaussianBlurring(object): <NEW_LINE> <INDENT> def __init__(self, sigma, p=0.2, random_state=np.random): <NEW_LINE> <INDENT> self.sigma = sigma <NEW_LINE> self.p = p <NEW_LINE> self.random_state = random_state <NEW_LINE> <DEDENT> def __call__(self, image): <NEW_LINE> <INDENT> if isinstance(self.sigma, collections.Sequence): <NEW_LINE> <INDENT> sigma = random_num_generator( self.sigma, random_state=self.random_state) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sigma = self.sigma <NEW_LINE> <DEDENT> if random.random() < self.p: <NEW_LINE> <INDENT> image = gaussian_filter(image, sigma=(sigma, sigma, 0)) <NEW_LINE> <DEDENT> return image | Apply gaussian blur to a numpy.ndarray (H x W x C)
| 625990690a50d4780f7069a8 |
class ResultChannelHelper(QtCore.QObject): <NEW_LINE> <INDENT> _testStarted = QtCore.Signal(TestResultBase, DeviceExecResult) <NEW_LINE> _testStopped = QtCore.Signal(TestResultBase, DeviceExecResult) <NEW_LINE> _stopped = QtCore.Signal() <NEW_LINE> def __init__(self, resultView): <NEW_LINE> <INDENT> QtCore.QObject.__init__(self) <NEW_LINE> self._resultTab = None <NEW_LINE> self._resultView = resultView <NEW_LINE> self._testStarted.connect(self._update, QtCore.Qt.QueuedConnection) <NEW_LINE> self._testStopped.connect(self._update, QtCore.Qt.QueuedConnection) <NEW_LINE> <DEDENT> def _update(self, result, device): <NEW_LINE> <INDENT> self._resultTab.update(result) <NEW_LINE> <DEDENT> def getTab(self): <NEW_LINE> <INDENT> return self._resultTab <NEW_LINE> <DEDENT> def start(self, result): <NEW_LINE> <INDENT> self._resultTab = self._resultView.addTab(result, str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")), select=True, closable=False) <NEW_LINE> self._stopped.connect(self._resultTab.expandItems, QtCore.Qt.QueuedConnection) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self._resultTab.setClosable(True) <NEW_LINE> self._stopped.emit() <NEW_LINE> self._stopped.disconnect(self._resultTab.expandItems, QtCore.Qt.QueuedConnection) <NEW_LINE> <DEDENT> def startTest(self, result, device): <NEW_LINE> <INDENT> self._testStarted.emit(result, device) <NEW_LINE> <DEDENT> def stopTest(self, result, device): <NEW_LINE> <INDENT> self._testStopped.emit(result, device) | A helper class to interact with a result channel.
It maintains a tab in the Result view. | 6259906932920d7e50bc7817 |
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(self.restaurant_name.title() + " serves " + self.cuisine_type + ".") <NEW_LINE> <DEDENT> def open_restaurant(self): <NEW_LINE> <INDENT> print(self.restaurant_name.title() + " is open.") | Simple model for a restaurant. | 625990695166f23b2e244ba2 |
class IS_LOWER(Validator): <NEW_LINE> <INDENT> def __call__(self, value): <NEW_LINE> <INDENT> return (to_bytes(to_unicode(value).lower()), None) | Converts to lowercase::
>>> IS_LOWER()('ABC')
('abc', None)
>>> IS_LOWER()('Ñ')
('\xc3\xb1', None) | 62599069f548e778e596cd5c |
class WFDataArrEver(RadiationField): <NEW_LINE> <INDENT> glossary_name = 'data/arrEver' <NEW_LINE> def __init__(self, wf): <NEW_LINE> <INDENT> super(WFDataArrEver, self).__init__(wf) <NEW_LINE> self.attributes.update( {'units': 'see params/wEFieldUnit', 'limits': '[FLOAT_MIN:FLOAT_MAX]', 'alias': 'arEy' }) <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> res = np.array(self._wf._srwl_wf.arEy, dtype='float32', copy=False) <NEW_LINE> correct_shape = (self._wf.params.Mesh.ny, self._wf.params.Mesh.nx, self._wf.params.Mesh.nSlices, self._wf.params.nval) <NEW_LINE> if not res.shape: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif np.prod(res.shape) == np.prod(correct_shape): <NEW_LINE> <INDENT> res.shape = correct_shape <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(res.shape, correct_shape) <NEW_LINE> raise ValueError('Alarm') <NEW_LINE> res = np.zeros(shape= (correct_shape), dtype='float32') <NEW_LINE> <DEDENT> if not res.flags['C_CONTIGUOUS']: <NEW_LINE> <INDENT> res = np.ascontiguousarray(res) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, val): <NEW_LINE> <INDENT> n_total = self._wf._get_total_elements() * self._wf.params.nval <NEW_LINE> self._wf._allocate_srw_moments() <NEW_LINE> if type(val) == array.array: <NEW_LINE> <INDENT> if not val.count() == n_total: <NEW_LINE> <INDENT> warnings.warn( 'New array size not equal to wavefront size. You must set it by yourself.') <NEW_LINE> <DEDENT> <DEDENT> val = np.array(val, dtype='float32') <NEW_LINE> if not val.flags['C_CONTIGUOUS']: <NEW_LINE> <INDENT> val = np.ascontiguousarray(val) <NEW_LINE> <DEDENT> if not np.prod(val.shape) == n_total: <NEW_LINE> <INDENT> warnings.warn( 'New array size not equal to wavefront size. It will set automaticaly to array size.') <NEW_LINE> self._wf.params.nx = val.shape[1] <NEW_LINE> self._wf.params.ny = val.shape[0] <NEW_LINE> self._wf.params.nSlices = val.shape[2] <NEW_LINE> <DEDENT> val.shape = (np.prod(val.shape),) <NEW_LINE> self._wf._srwl_wf.arEy = val | EM field (Re, Im) pairs written in 3D array, slice number changes first.
Vertical polarization | 625990694e4d562566373bd7 |
class CanvasWriter(object): <NEW_LINE> <INDENT> def __init__(self, canvas): <NEW_LINE> <INDENT> self.canvas = canvas <NEW_LINE> self.filename = '' <NEW_LINE> <DEDENT> def set_filename(self, filename): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> <DEDENT> def write(self): <NEW_LINE> <INDENT> with open(self.filename, 'w') as output: <NEW_LINE> <INDENT> for row in self.canvas.canvas: <NEW_LINE> <INDENT> for column in row: <NEW_LINE> <INDENT> output.write(column) <NEW_LINE> <DEDENT> output.write("\n") <NEW_LINE> <DEDENT> output.close() | This class is used to write a canvas object into a file | 6259906916aa5153ce401caa |
class Request(Message): <NEW_LINE> <INDENT> def __init__(self, method=None, params=None, msg_id=None): <NEW_LINE> <INDENT> self.method = method <NEW_LINE> self.params = params <NEW_LINE> self.msg_id = msg_id <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse(data): <NEW_LINE> <INDENT> if 'method' not in data: <NEW_LINE> <INDENT> raise ProtocolError('Request from server does not contain method') <NEW_LINE> <DEDENT> method = data.get('method') <NEW_LINE> params = data.get('params') <NEW_LINE> msg_id = data.get('id') <NEW_LINE> if not isinstance(params, list) and not isinstance(params, dict) and params is not None: <NEW_LINE> <INDENT> raise ProtocolError('Parameters must either be a positional list or named dict.') <NEW_LINE> <DEDENT> return Request(method, params, msg_id) <NEW_LINE> <DEDENT> @property <NEW_LINE> def response_id(self): <NEW_LINE> <INDENT> return self.msg_id <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> data = {'jsonrpc': '2.0', 'method': self.method} <NEW_LINE> if self.params: <NEW_LINE> <INDENT> data['params'] = self.params <NEW_LINE> <DEDENT> if self.msg_id: <NEW_LINE> <INDENT> data['id'] = self.msg_id <NEW_LINE> <DEDENT> return json.dumps(data) <NEW_LINE> <DEDENT> def parse_response(self, data): <NEW_LINE> <INDENT> if self.msg_id is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if not isinstance(data, dict): <NEW_LINE> <INDENT> raise ProtocolError('Response is not a dictionary') <NEW_LINE> <DEDENT> if 'error' in data: <NEW_LINE> <INDENT> code = data['error'].get('code', '') <NEW_LINE> message = data['error'].get('message', '') <NEW_LINE> raise ProtocolError(code, message, data) <NEW_LINE> <DEDENT> elif 'result' not in data: <NEW_LINE> <INDENT> raise ProtocolError('Response without a result field') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return data['result'] <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def transport_error_text(self): <NEW_LINE> <INDENT> return 'Error calling method %r' % self.method | Request a method call on the server. | 62599069435de62698e9d5db |
class BspScene(): <NEW_LINE> <INDENT> @property <NEW_LINE> def tris(self): <NEW_LINE> <INDENT> for face_idx, face in enumerate(self._bsp.faces): <NEW_LINE> <INDENT> if len(face.verts) < 3: <NEW_LINE> <INDENT> warn("{} (idx = {}) has < 3 " "verts".format(face, face_idx)) <NEW_LINE> continue <NEW_LINE> <DEDENT> first_vert = face.verts[0] <NEW_LINE> for vert_idx in range(2, len(face.verts)): <NEW_LINE> <INDENT> comment = "Face = {}\n".format(face) <NEW_LINE> comment += "Face idx {} Tri idx {}\n".format( face_idx, vert_idx) <NEW_LINE> yield _BspTri( first_vert, face.verts[vert_idx - 1], face.verts[vert_idx], material=self.materials[face.texture.name], comment=comment) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def lights(self): <NEW_LINE> <INDENT> for light_ent in (ent for ent in self._bsp.entities if ent['classname'] == 'light'): <NEW_LINE> <INDENT> if not "_color" in light_ent: <NEW_LINE> <INDENT> color = (1.0, 1.0, 1.0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> color = light_ent["_color"] <NEW_LINE> <DEDENT> yield _BspLight(location=light_ent['origin'], color=color, intensity=light_ent['light']) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def camera(self): <NEW_LINE> <INDENT> return _BspCamera(self._bsp) <NEW_LINE> <DEDENT> def _make_material(self, tex): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> color = loadcolors.calculate_color(self._fs, tex.name) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> color = (0., 1., 0.) <NEW_LINE> <DEDENT> return _BspMaterial(name=tex.name, color=color) <NEW_LINE> <DEDENT> def __init__(self, bsp, fs): <NEW_LINE> <INDENT> self._bsp = bsp <NEW_LINE> self._fs = fs <NEW_LINE> self.materials = { tex.name: self._make_material(tex) for tex in self._bsp.textures } | An SDL scene, constructed from a `q3.bsp.Bsp` instance.
This satifies the definition of a scene, described in `povray.sdl`. | 62599069097d151d1a2c283e |
class Id_Val(Val): <NEW_LINE> <INDENT> def __init__(self, value: str, value_type: types.Type = types.Unresolved()): <NEW_LINE> <INDENT> super().__init__(value, value_type) <NEW_LINE> self.cached_eval_result_val = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> if self.value_val is not None: <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise error.AST_Error("name attribute does not exist") <NEW_LINE> <DEDENT> <DEDENT> @name.setter <NEW_LINE> def name(self, value: str): <NEW_LINE> <INDENT> self.value(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def cached_eval_result(self): <NEW_LINE> <INDENT> if self.cached_eval_result is not None: <NEW_LINE> <INDENT> return self.cached_eval_result_val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise error.AST_Error("cached_eval_result attribute does not exist") <NEW_LINE> <DEDENT> <DEDENT> @cached_eval_result.setter <NEW_LINE> def cached_eval_result(self, cached_eval_result: Val): <NEW_LINE> <INDENT> self.cached_eval_result_val = cached_eval_result <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> sb = String_Builder() <NEW_LINE> sb.append("Id_Val: ( ") <NEW_LINE> sb.append(self.name) <NEW_LINE> sb.append(" )") <NEW_LINE> return str(sb) <NEW_LINE> <DEDENT> def eval(self, eval_context, embedded = False): <NEW_LINE> <INDENT> local_begin_time: Optional[Int_Val] = None <NEW_LINE> local_end_time: Optional[Int_Val] = None <NEW_LINE> if eval_context.has_id(Id_Val("local_begin_time")) and eval_context.has_id(Id_Val("local_end_time")): <NEW_LINE> <INDENT> local_begin_time = eval_context.lookup(Id_Val("local_begin_time")) <NEW_LINE> local_end_time = eval_context.lookup(Id_Val("local_end_time")) <NEW_LINE> <DEDENT> result: list = eval_context.lookup_signal(self, begin_time=local_begin_time, end_time=local_end_time) <NEW_LINE> return result <NEW_LINE> <DEDENT> def type_check(self, type_context): <NEW_LINE> <INDENT> return types.Float() <NEW_LINE> <DEDENT> def to_py_obj(self) -> Any: <NEW_LINE> <INDENT> if self.cached_eval_result: <NEW_LINE> <INDENT> return Eval_Result_Transformer(self.cached_eval_result).transform() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | stores identifier of the variable, variable expression
stores
type signature
variable identifier signature
and STL formula operator | 625990693539df3088ecda70 |
class Normalize(object): <NEW_LINE> <INDENT> def __init__(self, mean, std): <NEW_LINE> <INDENT> self.mean = mean <NEW_LINE> self.std = std <NEW_LINE> <DEDENT> def __call__(self, tensors, points): <NEW_LINE> <INDENT> if isinstance(tensors, list): is_list = True <NEW_LINE> else: is_list, tensors = False, [tensors] <NEW_LINE> for tensor in tensors: <NEW_LINE> <INDENT> for t, m, s in zip(tensor, self.mean, self.std): <NEW_LINE> <INDENT> t.sub_(m).div_(s) <NEW_LINE> <DEDENT> <DEDENT> if is_list == False: tensors = tensors[0] <NEW_LINE> return tensors, points | Normalize an tensor image with mean and standard deviation.
Given mean: (R, G, B) and std: (R, G, B),
will normalize each channel of the torch.*Tensor, i.e.
channel = (channel - mean) / std
Args:
mean (sequence): Sequence of means for R, G, B channels respecitvely.
std (sequence): Sequence of standard deviations for R, G, B channels
respecitvely. | 625990690c0af96317c57947 |
class Comment(models.Model): <NEW_LINE> <INDENT> content = models.TextField(max_length=150) <NEW_LINE> date_posted = models.DateTimeField(default=timezone.now) <NEW_LINE> author = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> post_connected = models.ForeignKey(Post, on_delete=models.CASCADE) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f'{str(self.author.account_name)}:{str(self.date_posted)}' <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "comment" <NEW_LINE> verbose_name_plural = "PostComment" | コメントの管理 | 62599069ac7a0e7691f73cb8 |
class Model372DigitalOutputRegister(RegisterBase): <NEW_LINE> <INDENT> bit_names = [ "d_1", "d_2", "d_3", "d_4", "d_5", ] <NEW_LINE> def __init__(self, d_1, d_2, d_3, d_4, d_5): <NEW_LINE> <INDENT> self.d_1 = d_1 <NEW_LINE> self.d_2 = d_2 <NEW_LINE> self.d_3 = d_3 <NEW_LINE> self.d_4 = d_4 <NEW_LINE> self.d_5 = d_5 | Class representing the digital output register. | 6259906971ff763f4b5e8f77 |
class Yum2(Model): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> with Vectorize(1): <NEW_LINE> <INDENT> cake = Cake() <NEW_LINE> <DEDENT> y = cake.y <NEW_LINE> self.cost = sum(y) <NEW_LINE> constraints = ConstraintSet([cake]) <NEW_LINE> return constraints | Total dessert system model containing 1 Cake | 62599069d486a94d0ba2d790 |
class StartTask(ActionIntent): <NEW_LINE> <INDENT> required_fields = [ 'student_id', 'task_id', ] <NEW_LINE> auto_fields = [ ('task_session_id', new_id), ('session_id', get_current_session_id, 'student_id'), ] <NEW_LINE> def check_duplicate(self, state): <NEW_LINE> <INDENT> student_id = self.data['student_id'] <NEW_LINE> task_id = self.data['task_id'] <NEW_LINE> session_id = get_current_session_id(state, student_id, new_if_none=False) <NEW_LINE> if session_id is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> session = state.sessions[session_id] <NEW_LINE> task_session = state.task_sessions .filter(student_id=student_id, task_id=task_id).order_by('start').last() <NEW_LINE> if task_session and task_session.start >= session.start: <NEW_LINE> <INDENT> self.raise_duplicate_action(task_session_id=task_session.task_session_id) | Student starts working on a task
| 62599069b7558d5895464b19 |
class StatsViewSet(GenericViewSet): <NEW_LINE> <INDENT> permission_classes = [AllowAny] <NEW_LINE> def list(self, request): <NEW_LINE> <INDENT> now = datetime.now() <NEW_LINE> current_month = (now.year, now.month) <NEW_LINE> user_count = auth_models.User.objects.filter( is_active=True, account__is_disabled=False).count() <NEW_LINE> accounts = Account.objects.all() <NEW_LINE> accounts_sum = sum([a.balance for a in accounts]) <NEW_LINE> transactions_count = Transaction.objects.all().count() <NEW_LINE> transactions_months = Transaction.objects.grouped_month() <NEW_LINE> transactions_current_count = len(transactions_months.get(current_month, [])) <NEW_LINE> donations = Transaction.objects.donations() <NEW_LINE> donations_total = sum(abs(d.amount) for d in donations) <NEW_LINE> donations_grouped = Transaction.objects.donations_grouped_months() <NEW_LINE> donations_current_sum = sum( abs(d.amount) for d in donations_grouped.get(current_month, [])) <NEW_LINE> stats = { 'money_gauge': accounts_sum, 'donations': { 'total': donations_total, 'current_month': donations_current_sum, }, 'transactions': { 'total': transactions_count, 'current_month': transactions_current_count, }, 'users': user_count, 'backend_version': BACKEND_VERSION, } <NEW_LINE> serialized_stats = serializers.StatsSerializer(stats) <NEW_LINE> return Response(serialized_stats.data) | Handle stats:
show: transactions, cash position, amount of
donations. Overall and for the current month.
This view set is public and can be viewed without being logged in. | 62599069442bda511e95d941 |
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.screen = screen <NEW_LINE> self.image = pygame.image.load('images/alien.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect) <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) <NEW_LINE> self.rect.x = self.x | 表示单个外星人的类 | 62599069d6c5a102081e38fa |
class VirtualDeviceNeVnSectionGridRemote(RemoteModel): <NEW_LINE> <INDENT> properties = ("DeviceID", "Collector", "DeviceIPDotted", "DeviceIPNumeric", "VirtualNetworkID", "Network", "DeviceName", "count", "DeviceModel", "DeviceVersion", "DeviceType", "DeviceMAC", "DeviceVendor", "DeviceContextName", ) | | ``DeviceID:`` none
| ``attribute type:`` string
| ``Collector:`` none
| ``attribute type:`` string
| ``DeviceIPDotted:`` none
| ``attribute type:`` string
| ``DeviceIPNumeric:`` none
| ``attribute type:`` string
| ``VirtualNetworkID:`` none
| ``attribute type:`` string
| ``Network:`` none
| ``attribute type:`` string
| ``DeviceName:`` none
| ``attribute type:`` string
| ``count:`` none
| ``attribute type:`` string
| ``DeviceModel:`` none
| ``attribute type:`` string
| ``DeviceVersion:`` none
| ``attribute type:`` string
| ``DeviceType:`` none
| ``attribute type:`` string
| ``DeviceMAC:`` none
| ``attribute type:`` string
| ``DeviceVendor:`` none
| ``attribute type:`` string
| ``DeviceContextName:`` none
| ``attribute type:`` string | 62599069aad79263cf42ff88 |
class Ins_MOVE(Instruction): <NEW_LINE> <INDENT> def __init__(self, order): <NEW_LINE> <INDENT> super(Ins_MOVE, self).__init__(order) <NEW_LINE> self.opcode = "MOVE" <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> self.printExecuting() <NEW_LINE> var1 = self.ops_list[0].toVar() <NEW_LINE> var2 = self.ops_list[1].toVar() <NEW_LINE> var1.var_type = var2.var_type <NEW_LINE> if var2.getValue() is None: <NEW_LINE> <INDENT> if var1.var_type == "string": <NEW_LINE> <INDENT> var1.value = "" <NEW_LINE> <DEDENT> elif var1.var_type == "int": <NEW_LINE> <INDENT> var1.value = 0 <NEW_LINE> <DEDENT> elif var1.var_type == "bool": <NEW_LINE> <INDENT> var1.value = "false" <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> var1.value = var2.getValue() | MOVE instruction | 62599069cc0a2c111447c6b9 |
class ComputeManagementClientConfiguration(Configuration): <NEW_LINE> <INDENT> def __init__( self, credential: "TokenCredential", subscription_id: str, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> super(ComputeManagementClientConfiguration, self).__init__(**kwargs) <NEW_LINE> if credential is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'credential' must not be None.") <NEW_LINE> <DEDENT> if subscription_id is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'subscription_id' must not be None.") <NEW_LINE> <DEDENT> self.credential = credential <NEW_LINE> self.subscription_id = subscription_id <NEW_LINE> self.api_version = "2019-07-01" <NEW_LINE> self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) <NEW_LINE> kwargs.setdefault('sdk_moniker', 'mgmt-compute/{}'.format(VERSION)) <NEW_LINE> self._configure(**kwargs) <NEW_LINE> <DEDENT> def _configure( self, **kwargs ): <NEW_LINE> <INDENT> self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) <NEW_LINE> self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) <NEW_LINE> self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) <NEW_LINE> self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) <NEW_LINE> self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) <NEW_LINE> self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) <NEW_LINE> self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) <NEW_LINE> self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) <NEW_LINE> self.authentication_policy = kwargs.get('authentication_policy') <NEW_LINE> if self.credential and not self.authentication_policy: <NEW_LINE> <INDENT> self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) | Configuration for ComputeManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.
:type subscription_id: str | 6259906938b623060ffaa43b |
class RequestError(Exception): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.value) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.value | 请求异常
| 625990697d43ff2487427ffa |
class ToScriptHash(list): <NEW_LINE> <INDENT> pass | just for some plugin do not generate syntax check error. | 6259906916aa5153ce401cac |
class Solution: <NEW_LINE> <INDENT> def maxPathSum(self, root): <NEW_LINE> <INDENT> maxSum, _ = self.maxPathHelper(root) <NEW_LINE> return maxSum <NEW_LINE> <DEDENT> def maxPathHelper(self, root): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return None, 0 <NEW_LINE> <DEDENT> left = self.maxPathHelper(root.left) <NEW_LINE> right = self.maxPathHelper(root.right) <NEW_LINE> single = max(left[1] + root.val, right[1] + root.val, 0) <NEW_LINE> maxpath = max(left[0], right[0], root.val + left[1] + right[1]) <NEW_LINE> return maxpath, single | @param: root: The root of binary tree.
@return: An integer | 6259906956b00c62f0fb40a2 |
class NetInfo(models.Model): <NEW_LINE> <INDENT> host_uid = models.CharField(max_length=10, verbose_name='随机码') <NEW_LINE> insert_datetime = models.DateTimeField(default=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') , verbose_name='插入时间戳') <NEW_LINE> net_io_counters = models.IntegerField(verbose_name='网络的 I/O 情况') | 记录主机网络动态性能信息 | 62599069adb09d7d5dc0bd3d |
class Benchmark(EndPoint): <NEW_LINE> <INDENT> argparse_noflag = "benchmark_code" <NEW_LINE> schema = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "required": ["benchmark_code", "language"], "properties": { "language": { "type": "string", "title": "l", "description": "性能检验针对的语言", "enum": ["py", "go"] }, "benchmark_code": { "type": "string", "description": "指定要测的测试代码" }, "mem": { "type": "boolean", "title": "m", "description": "是否测试内存性能", }, "cwd": { "type": "string", "description": "性能检验执行的位置", "default": "." } } } | 对指定语言的源码做性能检验. | 625990690c0af96317c57948 |
class kalman_circular(kalman_jc.KalmanFilter): <NEW_LINE> <INDENT> def __init__(self, q, r): <NEW_LINE> <INDENT> self._last_value = 0 <NEW_LINE> super().__init__(q, r) <NEW_LINE> <DEDENT> def _enrollar(self, x): <NEW_LINE> <INDENT> while (x - self._last_value) > 180: <NEW_LINE> <INDENT> x -= 360 <NEW_LINE> <DEDENT> while (x - self._last_value) <= -180: <NEW_LINE> <INDENT> x += 360 <NEW_LINE> <DEDENT> return x <NEW_LINE> <DEDENT> def _desenrollar(self): <NEW_LINE> <INDENT> x = int(self._last_value) <NEW_LINE> while x >= 360: <NEW_LINE> <INDENT> x -= 360 <NEW_LINE> <DEDENT> while x < 0: <NEW_LINE> <INDENT> x += 360 <NEW_LINE> <DEDENT> return x <NEW_LINE> <DEDENT> def predict_and_correct(self, x): <NEW_LINE> <INDENT> self.predict() <NEW_LINE> x_con_vueltas = self._enrollar(x) <NEW_LINE> self._last_value = self.correct(x_con_vueltas) <NEW_LINE> return self._desenrollar() | Filtro de kalman para usar con grados sexagesimales, que tiene en cuenta que 0-360 es la misma cosa | 625990693539df3088ecda72 |
class SplitEvent(DemographicEvent): <NEW_LINE> <INDENT> def __init__(self, sizes=[], names=[], ops=[], output='', begin=0, end=-1, step=1, at=[], reps=ALL_AVAIL, subPops=ALL_AVAIL, infoFields=[]): <NEW_LINE> <INDENT> self.sizes = sizes <NEW_LINE> self.names = names <NEW_LINE> DemographicEvent.__init__(self, ops, output, begin, end, step, at, reps, subPops, infoFields) <NEW_LINE> <DEDENT> def apply(self, pop): <NEW_LINE> <INDENT> if not DemographicEvent.apply(self, pop): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self._applicable(pop): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> subPops = self._identifySubPops(pop) <NEW_LINE> if len(subPops) != 1: <NEW_LINE> <INDENT> raise ValueError('Please specify one and only one subpopulation for event CopyEvent.') <NEW_LINE> <DEDENT> subPop = subPops[0] <NEW_LINE> if '_expected_size' in pop.vars(): <NEW_LINE> <INDENT> pop.resize(pop.vars().pop('_expected_size')) <NEW_LINE> <DEDENT> sz = [] <NEW_LINE> for x in self.sizes: <NEW_LINE> <INDENT> if isinstance(x, int): <NEW_LINE> <INDENT> sz.append(x) <NEW_LINE> <DEDENT> elif isinstance(x, float): <NEW_LINE> <INDENT> sz.append(int(round(x * pop.subPopSize(subPop)))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Elements of parameter sizes can only be interger (number' 'of individuals) or float numbers (proportions relative to the size of ' 'subpopulation being split)') <NEW_LINE> <DEDENT> <DEDENT> if sum(sz) != pop.subPopSize(subPop): <NEW_LINE> <INDENT> new_sz = list(pop.subPopSizes()) <NEW_LINE> new_sz[subPop] = sum(sz) <NEW_LINE> pop.resize(new_sz, propagate=True) <NEW_LINE> <DEDENT> pop.splitSubPop(subPop, sz, self.names) <NEW_LINE> return True | A demographic event that splits a specified population into two or
more subpopulations. | 6259906997e22403b383c6e0 |
class GELU(df.Module): <NEW_LINE> <INDENT> def symb_forward(self, x): <NEW_LINE> <INDENT> return 0.5 * x * (1 + df.T.tanh(0.79788456 * (x + 0.044715 * x*x*x))) | Gaussian Error Linear Unit (https://arxiv.org/abs/1606.08415) | 62599069dd821e528d6da56a |
@square <NEW_LINE> @symmetric <NEW_LINE> class EigendecompositionOperator(CompositionOperator): <NEW_LINE> <INDENT> def __init__(self, A=None, v=None, w=None, **kwargs): <NEW_LINE> <INDENT> if v is None or w is None: <NEW_LINE> <INDENT> w, v = eigsh(A, return_eigenvectors=True, **kwargs) <NEW_LINE> <DEDENT> W = DiagonalOperator(w) <NEW_LINE> V = DenseOperator(v) <NEW_LINE> V.set_rule('T,.', '1', CompositionOperator) <NEW_LINE> self.eigenvalues = w <NEW_LINE> self.eigenvectors = v <NEW_LINE> CompositionOperator.__init__(self, [V, W, V.T], **kwargs) <NEW_LINE> self.set_rule('I', lambda s: s ** -1) <NEW_LINE> <DEDENT> @property <NEW_LINE> def nbytes(self): <NEW_LINE> <INDENT> return self.eigenvalues.nbytes + self.eigenvectors.nbytes <NEW_LINE> <DEDENT> def det(self): <NEW_LINE> <INDENT> return np.prod(self.eigenvalues) <NEW_LINE> <DEDENT> def logdet(self): <NEW_LINE> <INDENT> return np.sum(np.log(self.eigenvalues)) <NEW_LINE> <DEDENT> def __pow__(self, n): <NEW_LINE> <INDENT> return EigendecompositionOperator(v=self.eigenvectors, w=self.eigenvalues ** n) <NEW_LINE> <DEDENT> def trace(self): <NEW_LINE> <INDENT> return np.sum(self.eigenvalues) <NEW_LINE> <DEDENT> def cond(self): <NEW_LINE> <INDENT> nze = self.eigenvalues[self.eigenvalues != 0] <NEW_LINE> return nze.max() / nze.min() | Define a symmetric Operator from the eigendecomposition of another
symmetric Operator. This can be used as an approximation for the
operator.
Inputs
-------
A: Operator (default: None)
The linear operator to approximate.
v: 2d ndarray (default: None)
The eigenvectors as given by arpack.eigsh
w: 1d ndarray (default: None)
The eigenvalues as given by arpack.eigsh
**kwargs: keyword arguments
Passed to the arpack.eigsh function.
You need to specify either A or v and w.
Returns
-------
An EigendecompositionOperator instance, which is a subclass of
Operator.
Notes
-----
This is really a wrapper for
scipy.sparse.linalg.eigen.arpack.eigsh | 625990697b25080760ed88cb |
class Solve: <NEW_LINE> <INDENT> def __init__(self, input, equation): <NEW_LINE> <INDENT> input = int(input) <NEW_LINE> self.equation = equation <NEW_LINE> out = eval(equation) <NEW_LINE> self.out = out | docstring for Solve. | 62599069fff4ab517ebcefee |
class Solution: <NEW_LINE> <INDENT> def topKFrequentWords(self, words, k): <NEW_LINE> <INDENT> count = {} <NEW_LINE> for word in words: <NEW_LINE> <INDENT> count[word] = count.get(word, 0) + 1 <NEW_LINE> <DEDENT> heap = [] <NEW_LINE> for word in count: <NEW_LINE> <INDENT> item = Item(count[word], word) <NEW_LINE> heappush(heap, item) <NEW_LINE> if len(heap) > k: <NEW_LINE> <INDENT> heappop(heap) <NEW_LINE> <DEDENT> <DEDENT> results = [] <NEW_LINE> while heap: <NEW_LINE> <INDENT> item = heappop(heap) <NEW_LINE> results.append(item.word) <NEW_LINE> <DEDENT> return results[::-1] | @param words: an array of string
@param k: An integer
@return: an array of string | 6259906966673b3332c31bd1 |
class HandlerSignUp(HandlerBase): <NEW_LINE> <INDENT> def add_user(self, username, password, email): <NEW_LINE> <INDENT> hashed_password = session.hash_password(username, password) <NEW_LINE> new_user = User( parent = session.user_key(), username = username, password = hashed_password, email = email ) <NEW_LINE> u_key = new_user.put() <NEW_LINE> hash_cookie = str(u_key.id()) + "|" + hashed_password <NEW_LINE> self.response.headers['Content-Type'] = 'text/plain' <NEW_LINE> self.response.headers.add_header( 'Set-Cookie', 'users=%s; Path=/' % hash_cookie) <NEW_LINE> self.redirect("/" ) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> last_10_wikis = self.get_last_10_wikis() <NEW_LINE> username_session = session.get_username(self) <NEW_LINE> self.render('signup.html', last_10_wikis=last_10_wikis, username_session=username_session) <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> last_10_wikis = self.get_last_10_wikis() <NEW_LINE> username = self.request.get( 'username' ) <NEW_LINE> password = self.request.get('password') <NEW_LINE> verify = self.request.get('verify') <NEW_LINE> email = self.request.get('email') <NEW_LINE> valid_username, valid_password, valid_verify, valid_email = True, True, True, True <NEW_LINE> error_username, error_password, error_verify, error_email = "", "", "", "" <NEW_LINE> if not session.is_valid_username(username): <NEW_LINE> <INDENT> username = cgi.escape(username, quote=True) <NEW_LINE> valid_username = False <NEW_LINE> error_username = "That's not a valid username." <NEW_LINE> <DEDENT> if not session.is_valid_password(password): <NEW_LINE> <INDENT> valid_password = False <NEW_LINE> error_password = "That wasn't a valid password." <NEW_LINE> <DEDENT> elif password != verify: <NEW_LINE> <INDENT> valid_verify = False <NEW_LINE> error_verify = "Your passwords didn't match." <NEW_LINE> <DEDENT> if email and not session.is_valid_email(email): <NEW_LINE> <INDENT> email = cgi.escape(email, quote=True) <NEW_LINE> valid_email = False <NEW_LINE> error_email = "That's not a valid email." <NEW_LINE> <DEDENT> if session.does_user_exist(username): <NEW_LINE> <INDENT> username = cgi.escape(username, quote=True) <NEW_LINE> valid_username = False <NEW_LINE> error_username = "Username already exists." <NEW_LINE> <DEDENT> if not(valid_username and valid_password and valid_verify and valid_email): <NEW_LINE> <INDENT> self.render('signup.html', last_10_wikis=last_10_wikis, username = username, email = email, error_username = error_username, error_password = error_password, error_verify = error_verify, error_email = error_email) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.add_user(username, password, email) | Shows singup info for user who'd like to register
| 625990691f037a2d8b9e5454 |
class DocumentInformation(DictionaryObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> DictionaryObject.__init__(self) <NEW_LINE> <DEDENT> def getText(self, key): <NEW_LINE> <INDENT> retval = self.get(key, None) <NEW_LINE> if isinstance(retval, TextStringObject): <NEW_LINE> <INDENT> return retval <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> title = property(lambda self: self.getText("/Title")) <NEW_LINE> title_raw = property(lambda self: self.get("/Title")) <NEW_LINE> author = property(lambda self: self.getText("/Author")) <NEW_LINE> author_raw = property(lambda self: self.get("/Author")) <NEW_LINE> subject = property(lambda self: self.getText("/Subject")) <NEW_LINE> subject_raw = property(lambda self: self.get("/Subject")) <NEW_LINE> creator = property(lambda self: self.getText("/Creator")) <NEW_LINE> creator_raw = property(lambda self: self.get("/Creator")) <NEW_LINE> producer = property(lambda self: self.getText("/Producer")) <NEW_LINE> producer_raw = property(lambda self: self.get("/Producer")) <NEW_LINE> keywords = property(lambda self: self.getText("/Keywords")) <NEW_LINE> keywords_raw = property(lambda self: self.get("/Keywords")) | A class representing the basic document metadata provided in a PDF File.
This class is accessible through
:meth:`documentInfo()<pypdf.PdfFileReader.documentInfo()>`
All text properties of the document metadata have
*two* properties, e.g. author and author_raw. The non-raw property will
always return a ``TextStringObject``, making it ideal for a case where
the metadata is being displayed. The raw property can sometimes return
a ``ByteStringObject``, if PyPDF was unable to decode the string's
text encoding; this requires additional safety in the caller and
therefore is not as commonly accessed. | 6259906921bff66bcd72443a |
class DynamodbEncryptionSdkError(Exception): <NEW_LINE> <INDENT> pass | Base class for all custom exceptions. | 6259906963d6d428bbee3e73 |
class MCellFloatVectorProperty(bpy.types.PropertyGroup): <NEW_LINE> <INDENT> vec: FloatVectorProperty(name="Float Vector") <NEW_LINE> def remove_properties ( self, context ): <NEW_LINE> <INDENT> pass | Generic PropertyGroup to hold float vector for a CollectionProperty | 625990698e7ae83300eea862 |
class FuzzLoggerCsv(ifuzz_logger_backend.IFuzzLoggerBackend): <NEW_LINE> <INDENT> def __init__(self, file_handle=sys.stdout, bytes_to_str=DEFAULT_HEX_TO_STR): <NEW_LINE> <INDENT> self._file_handle = file_handle <NEW_LINE> self._format_raw_bytes = bytes_to_str <NEW_LINE> self._csv_handle = csv.writer(self._file_handle) <NEW_LINE> <DEDENT> def open_test_step(self, description): <NEW_LINE> <INDENT> self._print_log_msg(["open step", "", "", description]) <NEW_LINE> <DEDENT> def log_check(self, description): <NEW_LINE> <INDENT> self._print_log_msg(["check", "", "", description]) <NEW_LINE> <DEDENT> def log_error(self, description): <NEW_LINE> <INDENT> self._print_log_msg(["error", "", "", description]) <NEW_LINE> <DEDENT> def log_recv(self, data): <NEW_LINE> <INDENT> self._print_log_msg(["recv", len(data), self._format_raw_bytes(data), data]) <NEW_LINE> <DEDENT> def log_send(self, data): <NEW_LINE> <INDENT> self._print_log_msg(["send", len(data), self._format_raw_bytes(data), data]) <NEW_LINE> <DEDENT> def log_info(self, description): <NEW_LINE> <INDENT> self._print_log_msg(["info", "", "", description]) <NEW_LINE> <DEDENT> def open_test_case(self, test_case_id, name, index, *args, **kwargs): <NEW_LINE> <INDENT> self._print_log_msg(["open test case", "", "", "Test case " + str(test_case_id)]) <NEW_LINE> <DEDENT> def log_fail(self, description=""): <NEW_LINE> <INDENT> self._print_log_msg(["fail", "", "", description]) <NEW_LINE> <DEDENT> def log_pass(self, description=""): <NEW_LINE> <INDENT> self._print_log_msg(["pass", "", "", description]) <NEW_LINE> <DEDENT> def close_test_case(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def close_test(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _print_log_msg(self, msg): <NEW_LINE> <INDENT> time_stamp = get_time_stamp() <NEW_LINE> self._csv_handle.writerow([time_stamp] + msg) | This class formats FuzzLogger data for pcap file. It can be
configured to output to a named file. | 62599069aad79263cf42ff8a |
class MyScrollBar(QScrollBar): <NEW_LINE> <INDENT> def __init__(self, orientation, parent=None): <NEW_LINE> <INDENT> super().__init__(orientation, parent) <NEW_LINE> self.equation = None <NEW_LINE> self.prev_max = None <NEW_LINE> <DEDENT> def mouseReleaseEvent(self, event): <NEW_LINE> <INDENT> QScrollBar.mouseReleaseEvent(self, event) <NEW_LINE> self.equation.setFocus() <NEW_LINE> <DEDENT> def setFocusTo(self, widget): <NEW_LINE> <INDENT> self.equation = widget <NEW_LINE> <DEDENT> def sliderChange(self, change): <NEW_LINE> <INDENT> QScrollBar.sliderChange(self, change) <NEW_LINE> if change == QAbstractSlider.SliderRangeChange and self.orientation() == Qt.Horizontal: <NEW_LINE> <INDENT> if self.prev_max is not None: <NEW_LINE> <INDENT> self.setValue(self.value() + self.maximum() - self.prev_max) <NEW_LINE> <DEDENT> self.prev_max = self.maximum() | Class to set focus in equation when moving the scroll bars.
It also moves the equation correctly when inserting new elements. | 625990694e4d562566373bdb |
class ImporterMain(HasTraits): <NEW_LINE> <INDENT> _last_open_path = File() <NEW_LINE> _files_path = List(File) <NEW_LINE> _notice_shown = Bool(False) <NEW_LINE> def import_data(self, file_path, have_variable_names = True, have_object_names = True, sep='\t'): <NEW_LINE> <INDENT> importer = self._make_importer(file_path) <NEW_LINE> importer.have_var_names = have_variable_names <NEW_LINE> importer.have_obj_names = have_object_names <NEW_LINE> importer.delimiter = sep <NEW_LINE> ds = importer.import_data() <NEW_LINE> return ds <NEW_LINE> <DEDENT> def dnd_import_data(self, path): <NEW_LINE> <INDENT> importer = self._make_importer(path) <NEW_LINE> importer.edit_traits() <NEW_LINE> ds = importer.import_data() <NEW_LINE> return ds <NEW_LINE> <DEDENT> def dialog_multi_import(self, parent_window=None): <NEW_LINE> <INDENT> self._last_open_path = conf.get_option('work_dir') <NEW_LINE> logger.debug('Last imported file: %s', self._last_open_path) <NEW_LINE> if not self._notice_shown: <NEW_LINE> <INDENT> notice = ImportNotice() <NEW_LINE> notice.edit_traits() <NEW_LINE> self._notice_shown = True <NEW_LINE> <DEDENT> status = self._show_file_selector() <NEW_LINE> if status == CANCEL: <NEW_LINE> <INDENT> logger.info('Cancel file imports') <NEW_LINE> return [] <NEW_LINE> <DEDENT> datasets = [] <NEW_LINE> logger.debug('File(s) to import: \n%s', '\n'.join(self._files_path)) <NEW_LINE> for file_n in self._files_path: <NEW_LINE> <INDENT> importer = self._make_importer(file_n) <NEW_LINE> logger.info('Attempting to import %s with %s', file_n, type(importer)) <NEW_LINE> ui = importer.edit_traits() <NEW_LINE> if ui.result: <NEW_LINE> <INDENT> ds = importer.import_data() <NEW_LINE> if ds.values.dtype.type is _np.object_: <NEW_LINE> <INDENT> logger.warning('Importing matrix with non-numeric values: {}'.format(ds.display_name)) <NEW_LINE> if parent_window is not None: <NEW_LINE> <INDENT> warning(parent_window, 'This matrix contains non-numeric values. The statistical methods is not able to handle non-numeric categorical variables') <NEW_LINE> <DEDENT> <DEDENT> datasets.append(ds) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> conf.set_option('work_dir', file_n) <NEW_LINE> return datasets <NEW_LINE> <DEDENT> def _show_file_selector(self): <NEW_LINE> <INDENT> dlg = FileDialog( action='open files', default_path=self._last_open_path, title='Import data') <NEW_LINE> status = dlg.open() <NEW_LINE> if status == OK: <NEW_LINE> <INDENT> self._files_path = dlg.paths <NEW_LINE> <DEDENT> elif status == CANCEL: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return status <NEW_LINE> <DEDENT> def _make_importer(self, path): <NEW_LINE> <INDENT> fext = self._identify_filetype(path) <NEW_LINE> if fext in ['txt', 'csv']: <NEW_LINE> <INDENT> return ImporterTextFile(file_path=path) <NEW_LINE> <DEDENT> elif fext in ['xls', 'xlsx', 'xlsm']: <NEW_LINE> <INDENT> return ImporterXlsFile(file_path=path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ImporterTextFile(file_path=path) <NEW_LINE> <DEDENT> <DEDENT> def _identify_filetype(self, path): <NEW_LINE> <INDENT> fn = os.path.basename(path) <NEW_LINE> return fn.partition('.')[2].lower() | Importer class | 62599069091ae35668706406 |
class HowItWorks(Section): <NEW_LINE> <INDENT> _subheading_locator = (By.CSS_SELECTOR, 'h2') <NEW_LINE> _box_locator = (By.CSS_SELECTOR, '.blurb-table .blurb') <NEW_LINE> @property <NEW_LINE> def subheading(self): <NEW_LINE> <INDENT> return self.find_element(*self._subheading_locator) <NEW_LINE> <DEDENT> @property <NEW_LINE> def how_it_works(self): <NEW_LINE> <INDENT> return self.subheading.text.strip() <NEW_LINE> <DEDENT> @property <NEW_LINE> def boxes(self): <NEW_LINE> <INDENT> return [self.Box(self, box) for box in self.find_elements(*self._box_locator)] <NEW_LINE> <DEDENT> class Box(Region): <NEW_LINE> <INDENT> _icon_locator = (By.CSS_SELECTOR, 'img') <NEW_LINE> _title_locator = (By.CSS_SELECTOR, 'h3') <NEW_LINE> _description_locator = (By.CSS_SELECTOR, '.smaller') <NEW_LINE> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return self.find_element(*self._icon_locator) <NEW_LINE> <DEDENT> @property <NEW_LINE> def title(self): <NEW_LINE> <INDENT> return self.find_element(*self._title_locator).text.strip() <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return (self.find_element(*self._description_locator) .text.strip()) | The 'How It Works' section. | 6259906938b623060ffaa43c |
class Solution: <NEW_LINE> <INDENT> def searchBST(self, root, val): <NEW_LINE> <INDENT> if not root or root.val == val: return root <NEW_LINE> if val < root.val: return self.searchBST(root.left, val) <NEW_LINE> else: return self.searchBST(root.right, val) | @param root: the tree
@param val: the val which should be find
@return: the node | 62599069009cb60464d02d0e |
class BasicLSTMCell(RNNCell): <NEW_LINE> <INDENT> def __init__(self, num_units, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None): <NEW_LINE> <INDENT> super(BasicLSTMCell, self).__init__(_reuse=reuse) <NEW_LINE> if not state_is_tuple: <NEW_LINE> <INDENT> logging.warn("%s: Using a concatenated state is slower and will soon be " "deprecated. Use state_is_tuple=True.", self) <NEW_LINE> <DEDENT> self._num_units = num_units <NEW_LINE> self._forget_bias = forget_bias <NEW_LINE> self._state_is_tuple = state_is_tuple <NEW_LINE> self._activation = activation or math_ops.tanh <NEW_LINE> <DEDENT> @property <NEW_LINE> def state_size(self): <NEW_LINE> <INDENT> return (LSTMStateTuple(self._num_units, self._num_units) if self._state_is_tuple else 2 * self._num_units) <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_size(self): <NEW_LINE> <INDENT> return self._num_units <NEW_LINE> <DEDENT> def call(self, inputs, state): <NEW_LINE> <INDENT> sigmoid = math_ops.sigmoid <NEW_LINE> if self._state_is_tuple: <NEW_LINE> <INDENT> c, h = state <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c, h = array_ops.split(value=state, num_or_size_splits=2, axis=1) <NEW_LINE> <DEDENT> concat = _linear([inputs, h], 4 * self._num_units, True) <NEW_LINE> i, j, f, o = array_ops.split(value=concat, num_or_size_splits=4, axis=1) <NEW_LINE> new_c = (c * sigmoid(f + self._forget_bias) + sigmoid(i) * self._activation(j)) <NEW_LINE> new_h = self._activation(new_c) * sigmoid(o) <NEW_LINE> if self._state_is_tuple: <NEW_LINE> <INDENT> new_state = LSTMStateTuple(new_c, new_h) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_state = array_ops.concat([new_c, new_h], 1) <NEW_LINE> <DEDENT> return new_h, new_state | Basic LSTM recurrent network cell.
The implementation is based on: http://arxiv.org/abs/1409.2329.
We add forget_bias (default: 1) to the biases of the forget gate in order to
reduce the scale of forgetting in the beginning of the training.
It does not allow cell clipping, a projection layer, and does not
use peep-hole connections: it is the basic baseline.
For advanced models, please use the full @{tf.nn.rnn_cell.LSTMCell}
that follows. | 625990694527f215b58eb58a |
class TextWrapperWithNewLines: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def wrap(text, width=70, **kw): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for line in text.split("\n"): <NEW_LINE> <INDENT> result.extend(textwrap.wrap(line, width, **kw)) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def fill(text, width=70, **kw): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for line in text.split("\n"): <NEW_LINE> <INDENT> result.append(textwrap.fill(line, width, **kw)) <NEW_LINE> <DEDENT> return "\n".join(result) | TextWrapper that keeps newline characters. | 62599069379a373c97d9a7f4 |
class SynplaBootstrap(object): <NEW_LINE> <INDENT> def __init__(self, app=None): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> if self.app: <NEW_LINE> <INDENT> self.init_app(self.app) <NEW_LINE> <DEDENT> <DEDENT> def init_app(self, app): <NEW_LINE> <INDENT> blueprint = Blueprint( 'synpla_bootstrap', __name__, template_folder='templates') <NEW_LINE> app.register_blueprint(blueprint) | Bootstrap templates for SynPla. | 625990694428ac0f6e659d07 |
class FloatType(FloatBaseType): <NEW_LINE> <INDENT> __slots__ = ['name', 'nbits', 'nmant', 'nexp'] <NEW_LINE> _construct_nbits = _construct_nmant = _construct_nexp = Integer <NEW_LINE> @property <NEW_LINE> def max_exponent(self): <NEW_LINE> <INDENT> return two**(self.nexp - 1) <NEW_LINE> <DEDENT> @property <NEW_LINE> def min_exponent(self): <NEW_LINE> <INDENT> return 3 - self.max_exponent <NEW_LINE> <DEDENT> @property <NEW_LINE> def max(self): <NEW_LINE> <INDENT> return (1 - two**-(self.nmant+1))*two**self.max_exponent <NEW_LINE> <DEDENT> @property <NEW_LINE> def tiny(self): <NEW_LINE> <INDENT> return two**(self.min_exponent - 1) <NEW_LINE> <DEDENT> @property <NEW_LINE> def eps(self): <NEW_LINE> <INDENT> return two**(-self.nmant) <NEW_LINE> <DEDENT> @property <NEW_LINE> def dig(self): <NEW_LINE> <INDENT> from sympy.functions import floor, log <NEW_LINE> return floor(self.nmant * log(2)/log(10)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def decimal_dig(self): <NEW_LINE> <INDENT> from sympy.functions import ceiling, log <NEW_LINE> return ceiling((self.nmant + 1) * log(2)/log(10) + 1) <NEW_LINE> <DEDENT> def cast_nocheck(self, value): <NEW_LINE> <INDENT> if value == oo: <NEW_LINE> <INDENT> return float(oo) <NEW_LINE> <DEDENT> elif value == -oo: <NEW_LINE> <INDENT> return float(-oo) <NEW_LINE> <DEDENT> return Float(str(sympify(value).evalf(self.decimal_dig)), self.decimal_dig) <NEW_LINE> <DEDENT> def _check(self, value): <NEW_LINE> <INDENT> if value < -self.max: <NEW_LINE> <INDENT> raise ValueError("Value is too small: %d < %d" % (value, -self.max)) <NEW_LINE> <DEDENT> if value > self.max: <NEW_LINE> <INDENT> raise ValueError("Value is too big: %d > %d" % (value, self.max)) <NEW_LINE> <DEDENT> if abs(value) < self.tiny: <NEW_LINE> <INDENT> raise ValueError("Smallest (absolute) value for data type bigger than new value.") | Represents a floating point type with fixed bit width.
Base 2 & one sign bit is assumed.
Parameters
==========
name : str
Name of the type.
nbits : integer
Number of bits used (storage).
nmant : integer
Number of bits used to represent the mantissa.
nexp : integer
Number of bits used to represent the mantissa.
Examples
========
>>> from sympy import S, Float
>>> from sympy.codegen.ast import FloatType
>>> half_precision = FloatType('f16', nbits=16, nmant=10, nexp=5)
>>> half_precision.max
65504
>>> half_precision.tiny == S(2)**-14
True
>>> half_precision.eps == S(2)**-10
True
>>> half_precision.dig == 3
True
>>> half_precision.decimal_dig == 5
True
>>> half_precision.cast_check(1.0)
1.0
>>> half_precision.cast_check(1e5) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Maximum value for data type smaller than new value. | 6259906916aa5153ce401cae |
class Crawler: <NEW_LINE> <INDENT> def __init__(self, keywords, db, timeout=3): <NEW_LINE> <INDENT> self.keywords = keywords <NEW_LINE> self.item = ItemCrawler(self.keywords, db, timeout) <NEW_LINE> self.rate = RateCrawler(db, timeout) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.item.run() <NEW_LINE> self.rate.run() | 淘宝商品及评论爬虫 | 62599069097d151d1a2c2843 |
class Sound(EventDispatcher): <NEW_LINE> <INDENT> source = StringProperty(None) <NEW_LINE> volume = NumericProperty(1.) <NEW_LINE> state = OptionProperty('stop', options=('stop', 'play')) <NEW_LINE> def _get_status(self): <NEW_LINE> <INDENT> return self.state <NEW_LINE> <DEDENT> status = AliasProperty(_get_status, None, bind=('state', )) <NEW_LINE> def _get_filename(self): <NEW_LINE> <INDENT> return self.source <NEW_LINE> <DEDENT> filename = AliasProperty(_get_filename, None, bind=('source', )) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.register_event_type('on_play') <NEW_LINE> self.register_event_type('on_stop') <NEW_LINE> super(Sound, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def on_source(self, instance, filename): <NEW_LINE> <INDENT> self.unload() <NEW_LINE> if filename is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.load() <NEW_LINE> <DEDENT> def get_pos(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def _get_length(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> length = property(lambda self: self._get_length(), doc='Get length of the sound (in seconds)') <NEW_LINE> def load(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def unload(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def play(self): <NEW_LINE> <INDENT> self.state = 'play' <NEW_LINE> self.dispatch('on_play') <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.state = 'stop' <NEW_LINE> self.dispatch('on_stop') <NEW_LINE> <DEDENT> def seek(self, position): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_play(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_stop(self): <NEW_LINE> <INDENT> pass | Represent a sound to play. This class is abstract, and cannot be used
directly.
Use SoundLoader to load a sound !
:Events:
`on_play` : None
Fired when the sound is played
`on_stop` : None
Fired when the sound is stopped | 625990692ae34c7f260ac8bd |
class Meta: <NEW_LINE> <INDENT> model = Servicios <NEW_LINE> fields = ('nombre', 'precio', 'descripcion',) | Meta. | 62599069a17c0f6771d5d792 |
class TestFaults(test.TestCase): <NEW_LINE> <INDENT> def test_fault_exception(self): <NEW_LINE> <INDENT> fault = faults.Fault(webob.exc.HTTPBadRequest( explanation='test')) <NEW_LINE> self.assertTrue(isinstance(fault.wrapped_exc, webob.exc.HTTPBadRequest)) <NEW_LINE> <DEDENT> def test_fault_exception_status_int(self): <NEW_LINE> <INDENT> fault = faults.Fault(webob.exc.HTTPNotFound(explanation='test')) <NEW_LINE> self.assertEquals(fault.wrapped_exc.status_int, 404) <NEW_LINE> <DEDENT> def test_fault_call(self): <NEW_LINE> <INDENT> message = 'test message' <NEW_LINE> ex = webob.exc.HTTPNotFound(explanation=message) <NEW_LINE> fault = faults.Fault(ex) <NEW_LINE> req = Request.blank('/test') <NEW_LINE> req.GET['AWSAccessKeyId'] = "test_user_id:test_project_id" <NEW_LINE> self.mox.StubOutWithMock(faults, 'ec2_error_response') <NEW_LINE> faults.ec2_error_response(mox.IgnoreArg(), 'HTTPNotFound', message=message, status=ex.status_int) <NEW_LINE> self.mox.ReplayAll() <NEW_LINE> fault(req) | Tests covering ec2 Fault class. | 625990691b99ca4002290120 |
class StructuralSectionRoundBar(StructuralSectionRound,IDisposable): <NEW_LINE> <INDENT> def Dispose(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReleaseUnmanagedResources(self,*args): <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> @staticmethod <NEW_LINE> def __new__(self,diameter,centroidHorizontal,centroidVertical,principalAxesAngle,sectionArea,perimeter,nominalWeight,momentOfInertiaStrongAxis,momentOfInertiaWeakAxis,elasticModulusStrongAxis,elasticModulusWeakAxis,plasticModulusStrongAxis,plasticModulusWeakAxis,torsionalMomentOfInertia,torsionalModulus,warpingConstant,shearAreaStrongAxis,shearAreaWeakAxis): <NEW_LINE> <INDENT> pass | Defines parameters for Round Bar structural section.
StructuralSectionRoundBar(diameter: float,centroidHorizontal: float,centroidVertical: float,principalAxesAngle: float,sectionArea: float,perimeter: float,nominalWeight: float,momentOfInertiaStrongAxis: float,momentOfInertiaWeakAxis: float,elasticModulusStrongAxis: float,elasticModulusWeakAxis: float,plasticModulusStrongAxis: float,plasticModulusWeakAxis: float,torsionalMomentOfInertia: float,torsionalModulus: float,warpingConstant: float,shearAreaStrongAxis: float,shearAreaWeakAxis: float) | 62599069a8370b77170f1b9a |
class Environment: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._running = False <NEW_LINE> self._simulation_sleep = 0.1 <NEW_LINE> self._dtime = 0.1 <NEW_LINE> self.current_date_time = datetime.datetime(year=2017, month=11, day=16, hour=8) <NEW_LINE> self.ambient_air_temperature = 20.0 <NEW_LINE> self.dambient_air_temperature_dsecond = ( lambda date_time: math.sin((date_time.hour - 6) / 24 * math.pi * 2) / 4 / SECONDS_PER_HOUR ) <NEW_LINE> self.ambient_air_pressure = 1000.0 <NEW_LINE> self.ambient_air_specific_humidity = 0.006 <NEW_LINE> self.kit_air_temperature = 24.0 <NEW_LINE> self.kit_air_pressure = 1000.0 <NEW_LINE> self.kit_air_specific_humidity = 0.008 <NEW_LINE> self.kit_heating = {} <NEW_LINE> <DEDENT> def simulate(self): <NEW_LINE> <INDENT> while self._running: <NEW_LINE> <INDENT> self.current_date_time += datetime.timedelta(seconds=self._dtime) <NEW_LINE> self.simulate_step(self._dtime) <NEW_LINE> time.sleep(self._simulation_sleep) <NEW_LINE> <DEDENT> <DEDENT> def simulate_step(self, dtime): <NEW_LINE> <INDENT> self.simulate_ambient_factors(dtime) <NEW_LINE> self.simulate_kit(dtime) <NEW_LINE> <DEDENT> def simulate_ambient_factors(self, dtime): <NEW_LINE> <INDENT> self.ambient_air_temperature += ( self.dambient_air_temperature_dsecond(self.current_date_time) * dtime ) <NEW_LINE> <DEDENT> def set_kit_heating(self, name, wattage): <NEW_LINE> <INDENT> self.kit_heating[name] = wattage <NEW_LINE> <DEDENT> def simulate_kit(self, dtime): <NEW_LINE> <INDENT> dkit_air_temperature_dtime = 0 <NEW_LINE> dkit_air_temperature_dtime += ( (self.ambient_air_temperature - self.kit_air_temperature) / 2 / SECONDS_PER_HOUR ) <NEW_LINE> for wattage in self.kit_heating.values(): <NEW_LINE> <INDENT> dkit_air_temperature_dtime += wattage / (KIT_AIR_MASS * AIR_SPECIFIC_HEAT) <NEW_LINE> <DEDENT> self.kit_air_temperature += dkit_air_temperature_dtime * dtime <NEW_LINE> if self.ambient_air_specific_humidity > dew_point(self.ambient_air_temperature): <NEW_LINE> <INDENT> self.ambient_air_specific_humidity = dew_point(self.ambient_air_temperature) <NEW_LINE> <DEDENT> self.kit_air_pressure = self.ambient_air_pressure <NEW_LINE> self.kit_air_specific_humidity = self.ambient_air_specific_humidity <NEW_LINE> <DEDENT> @property <NEW_LINE> def kit_air_humidity(self): <NEW_LINE> <INDENT> return relative_humidity( self.kit_air_specific_humidity, self.kit_air_temperature ) <NEW_LINE> <DEDENT> def get_dval_dtime_from_list(self, dval_dtimes): <NEW_LINE> <INDENT> current_time = self.current_date_time.time() <NEW_LINE> for time, val in dval_dtimes: <NEW_LINE> <INDENT> if time >= current_time: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> <DEDENT> return val | Class to simulate a controlled environment. | 62599069e1aae11d1e7cf3f7 |
class SpliterInterfaceException(SpliterException): <NEW_LINE> <INDENT> pass | Interface exception. | 62599069be8e80087fbc0861 |
class MCP_Input: <NEW_LINE> <INDENT> address = 0 <NEW_LINE> num_gpios = 0 <NEW_LINE> mcp = None <NEW_LINE> buttons = [] <NEW_LINE> debug_states = [] <NEW_LINE> def __init__(self, address = 0x20, num_gpios = 16): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> self.num_gpios = num_gpios <NEW_LINE> self.mcp = Adafruit_MCP230XX(address, num_gpios) <NEW_LINE> self.pullup_all_pins() <NEW_LINE> <DEDENT> def pullup_all_pins(self): <NEW_LINE> <INDENT> for x in range(0,num_gpios): <NEW_LINE> <INDENT> self.mcp.pullup(x, 1) <NEW_LINE> <DEDENT> <DEDENT> def readU16(self): <NEW_LINE> <INDENT> return mcp.readU16() <NEW_LINE> <DEDENT> def new_button_append( self, button ): <NEW_LINE> <INDENT> self.buttons.append(button) <NEW_LINE> return len(self.buttons) <NEW_LINE> <DEDENT> def remove_button(self, index=-1): <NEW_LINE> <INDENT> self.buttons.pop(index) <NEW_LINE> <DEDENT> def set_all_button_states(self): <NEW_LINE> <INDENT> states = self.readU16() <NEW_LINE> self.debug_states = [(states>>x)&1 for x in range(0,num_gpios)] <NEW_LINE> [ b.set_button_state(s) for (b,s) in zip(self.buttons, self.debug_states) ] | Gather, via I2C protocol, the state of buttons hooked up to a MCP23017 IC. Convert it into something useful and pass the state info on to associaton Button objects. | 625990698da39b475be049c1 |
class RemoveShapeKeyOperator(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "tsk.remove_shape_keys" <NEW_LINE> bl_label = "Remove Shape Keys in src" <NEW_LINE> bl_description = 'Remove all Shape Keys in source mesh' <NEW_LINE> bl_context = 'objectmode' <NEW_LINE> bl_options = {'REGISTER', 'INTERNAL','UNDO'} <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> skt = bpy.context.scene.shapekeytransferSettings <NEW_LINE> return (skt.src_mesh is not None) <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> global SKT <NEW_LINE> skt = bpy.context.scene.shapekeytransferSettings <NEW_LINE> if(skt.src_mesh): <NEW_LINE> <INDENT> ob = get_parent(skt.src_mesh) <NEW_LINE> if(ob.data.shape_keys): <NEW_LINE> <INDENT> basis = None <NEW_LINE> for x in ob.data.shape_keys.key_blocks: <NEW_LINE> <INDENT> if(basis): <NEW_LINE> <INDENT> ob.shape_key_remove(x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> basis = x <NEW_LINE> <DEDENT> <DEDENT> ob.shape_key_remove(basis) <NEW_LINE> <DEDENT> self.report({'INFO'}, "Removed all shape keys in source mesh!") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.report({'ERROR'}, "Select a valid source mesh!") <NEW_LINE> <DEDENT> return {'FINISHED'} | Remove all Shape Keys in source mesh | 625990693cc13d1c6d466f1b |
class UnsupportedCurrencyError(Exception): <NEW_LINE> <INDENT> def __init__(self, currency): <NEW_LINE> <INDENT> super().__init__(currency) | A currency is currently not supported by the API | 6259906921bff66bcd72443c |
class MedianFilter(AbstractBGModel): <NEW_LINE> <INDENT> def __init__(self, imageBuffer, thresh=20, soft_thresh = False): <NEW_LINE> <INDENT> AbstractBGModel.__init__(self, imageBuffer, thresh, soft_thresh) <NEW_LINE> <DEDENT> def _getMedianVals(self): <NEW_LINE> <INDENT> self._imageStack = self._imageBuffer.asStackBW() <NEW_LINE> medians = sp.median(self._imageStack, axis=0) <NEW_LINE> return medians <NEW_LINE> <DEDENT> def _computeBGDiff(self): <NEW_LINE> <INDENT> imgGray = self._imageBuffer.getLast().asMatrix2D() <NEW_LINE> imgBG = self._getMedianVals() <NEW_LINE> return (imgGray - imgBG) | Uses median pixel values of the images in a buffer to
approximate a background model. | 6259906976e4537e8c3f0d58 |
class SpecCounter: <NEW_LINE> <INDENT> def __init__(self, specName = None, specVersion = None, timeout = None): <NEW_LINE> <INDENT> self.channelName = '' <NEW_LINE> self.connection = None <NEW_LINE> self.type = UNKNOWN <NEW_LINE> if specName is not None and specVersion is not None: <NEW_LINE> <INDENT> self.connectToSpec(specName, specVersion, timeout) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.specName = None <NEW_LINE> self.specVersion = None <NEW_LINE> <DEDENT> <DEDENT> def connectToSpec(self, specName, specVersion, timeout = None): <NEW_LINE> <INDENT> self.specName = specName <NEW_LINE> self.specVersion = specVersion <NEW_LINE> self.connection = SpecConnectionsManager.SpecConnectionsManager().getConnection(specVersion) <NEW_LINE> w = SpecWaitObject.SpecWaitObject(self.connection) <NEW_LINE> w.waitConnection(timeout) <NEW_LINE> c = self.connection.getChannel('var/%s' % self.specName) <NEW_LINE> index = c.read() <NEW_LINE> if index == 0: <NEW_LINE> <INDENT> self.type = TIMER <NEW_LINE> <DEDENT> elif index == 1: <NEW_LINE> <INDENT> self.type = MONITOR <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.type = SCALER <NEW_LINE> <DEDENT> <DEDENT> def count(self, time): <NEW_LINE> <INDENT> if self.connection is not None: <NEW_LINE> <INDENT> c1 = self.connection.getChannel('scaler/.all./count') <NEW_LINE> c2 = self.connection.getChannel('scaler/%s/value' % self.specName) <NEW_LINE> if self.type == MONITOR: <NEW_LINE> <INDENT> time = -time <NEW_LINE> <DEDENT> c1.write(time) <NEW_LINE> w = SpecWaitObject.SpecWaitObject(self.connection) <NEW_LINE> w.waitChannelUpdate('scaler/.all./count', waitValue = 0) <NEW_LINE> return c2.read() <NEW_LINE> <DEDENT> <DEDENT> def getValue(self): <NEW_LINE> <INDENT> if self.connection is not None: <NEW_LINE> <INDENT> c = self.connection.getChannel('scaler/%s/value' % self.specName) <NEW_LINE> return c.read() | SpecCounter class | 625990693d592f4c4edbc6b5 |
class FileFinder(finders.FileSystemFinder): <NEW_LINE> <INDENT> def __init__(self, locations): <NEW_LINE> <INDENT> self.locations = [] <NEW_LINE> self.prefixes = set() <NEW_LINE> self.storages = OrderedDict() <NEW_LINE> if not isinstance(locations, (list, tuple)): <NEW_LINE> <INDENT> raise TypeError("locations argument is not a tuple or list") <NEW_LINE> <DEDENT> for root in locations: <NEW_LINE> <INDENT> prefix, root = root <NEW_LINE> if not prefix: <NEW_LINE> <INDENT> raise ValueError( "Cannot use unprefixed locations for dynamic locations" ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prefix = prefix.rstrip("/") <NEW_LINE> <DEDENT> if (prefix, root) not in self.locations: <NEW_LINE> <INDENT> self.locations.append((prefix, root)) <NEW_LINE> <DEDENT> self.prefixes.add(prefix) <NEW_LINE> <DEDENT> for prefix, root in self.locations: <NEW_LINE> <INDENT> filesystem_storage = FileSystemStorage(location=root) <NEW_LINE> filesystem_storage.prefix = prefix <NEW_LINE> self.storages[root] = filesystem_storage <NEW_LINE> <DEDENT> <DEDENT> def find_location(self, root, path, prefix=None): <NEW_LINE> <INDENT> if prefix: <NEW_LINE> <INDENT> prefix = prefix + "/" <NEW_LINE> if not path.startswith(prefix): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> path = path[len(prefix) :] <NEW_LINE> <DEDENT> path = safe_join(root, path) <NEW_LINE> if os.path.exists(path): <NEW_LINE> <INDENT> return path | A modified version of the Django FileSystemFinder class
which allows us to pass in arbitrary locations to find files | 62599069e76e3b2f99fda1d7 |
class Hook(GitHubCore): <NEW_LINE> <INDENT> def __init__(self, hook, session=None): <NEW_LINE> <INDENT> super(Hook, self).__init__(hook, session) <NEW_LINE> self._api = hook.get('url', '') <NEW_LINE> self.updated_at = None <NEW_LINE> if hook.get('updated_at'): <NEW_LINE> <INDENT> self.updated_at = self._strptime(hook.get('updated_at')) <NEW_LINE> <DEDENT> self.created_at = self._strptime(hook.get('created_at')) <NEW_LINE> self.name = hook.get('name') <NEW_LINE> self.events = hook.get('events') <NEW_LINE> self.active = hook.get('active') <NEW_LINE> self.config = hook.get('config') <NEW_LINE> self.id = hook.get('id') <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Hook [{0}]>'.format(self.name) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.id == other.id <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return self.id != other.id <NEW_LINE> <DEDENT> def _update_(self, hook): <NEW_LINE> <INDENT> self.__init__(hook, self._session) <NEW_LINE> <DEDENT> @requires_auth <NEW_LINE> def delete(self): <NEW_LINE> <INDENT> return self._boolean(self._delete(self._api), 204, 404) <NEW_LINE> <DEDENT> @requires_auth <NEW_LINE> def delete_subscription(self): <NEW_LINE> <INDENT> url = self._build_url('subscription', base_url=self._api) <NEW_LINE> return self._boolean(self._delete(url), 204, 404) <NEW_LINE> <DEDENT> @requires_auth <NEW_LINE> def edit(self, name, config, events=[], add_events=[], rm_events=[], active=True): <NEW_LINE> <INDENT> json = None <NEW_LINE> if name and config and isinstance(config, dict): <NEW_LINE> <INDENT> data = {'name': name, 'config': config, 'active': active} <NEW_LINE> if events: <NEW_LINE> <INDENT> data['events'] = events <NEW_LINE> <DEDENT> if add_events: <NEW_LINE> <INDENT> data['add_events'] = add_events <NEW_LINE> <DEDENT> if rm_events: <NEW_LINE> <INDENT> data['remove_events'] = rm_events <NEW_LINE> <DEDENT> json = self._json(self._patch(self._api, data=dumps(data)), 200) <NEW_LINE> <DEDENT> if json: <NEW_LINE> <INDENT> self._update_(json) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> @requires_auth <NEW_LINE> def test(self): <NEW_LINE> <INDENT> url = self._build_url('tests', base_url=self._api) <NEW_LINE> return self._boolean(self._post(url), 204, 404) | The :class:`Hook <Hook>` object. This handles the information returned
by GitHub about hooks set on a repository.
See also: http://developer.github.com/v3/repos/hooks/ | 62599069aad79263cf42ff8b |
class Generator(tf.keras.Model): <NEW_LINE> <INDENT> def __init__(self, output_dim=28 * 28): <NEW_LINE> <INDENT> super(Generator, self).__init__() <NEW_LINE> self.output_dim = output_dim <NEW_LINE> self.dense_G_1 = tf.layers.Dense(128, activation=tf.nn.relu) <NEW_LINE> self.dense_G_2 = tf.layers.Dense(256, activation=tf.nn.relu) <NEW_LINE> self.fake = tf.layers.Dense(self.output_dim, activation=tf.nn.tanh) <NEW_LINE> <DEDENT> def generate(self, Z): <NEW_LINE> <INDENT> gen = self.dense_G_1(Z) <NEW_LINE> gen = self.dense_G_2(gen) <NEW_LINE> gen = self.fake(gen) <NEW_LINE> return gen <NEW_LINE> <DEDENT> def call(self, Z): <NEW_LINE> <INDENT> return self.generate(Z) | Generator Module for GAN
Args:
noise_dim: dimension of noise z. basically 10 is used
output_dim: dimension of output image. 28 * 28 for MNIST | 625990698e7ae83300eea864 |
class Imu(object): <NEW_LINE> <INDENT> def __init__(self, imu_file): <NEW_LINE> <INDENT> self.file = imu_file <NEW_LINE> self.rows = 0 <NEW_LINE> self.info = np.array(["", 0, 0]) <NEW_LINE> self.a, self.w, self.timestamp = np.array([0, 0, 0]), np.array([0, 0, 0]), np.array([0]) <NEW_LINE> self.end_info = np.array([0, 0, 0]) <NEW_LINE> self.get_data() <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for line in linecache.getlines(self.file): <NEW_LINE> <INDENT> self.info = np.vstack((self.info, line.split(",")[0:3])) <NEW_LINE> self.timestamp = np.vstack((self.timestamp, line.split(",")[-1])) <NEW_LINE> self.a = np.vstack((self.a, line.split(",")[3:6])) <NEW_LINE> self.w = np.vstack((self.w, line.split(",")[6:9])) <NEW_LINE> self.end_info = np.vstack((self.end_info, line.strip("\n").split(",")[9:12])) <NEW_LINE> <DEDENT> self.rows = self.a.shape[0] - 1 <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> logging.error("please check the input file, it has the wrong format") <NEW_LINE> <DEDENT> <DEDENT> def normal(self, mean, variance): <NEW_LINE> <INDENT> return np.random.normal(mean, variance, self.rows) <NEW_LINE> <DEDENT> def add_noise(self, bias_list, mean_list, variance_list, affect_range=None): <NEW_LINE> <INDENT> self.w[1:, 0]=0 <NEW_LINE> <DEDENT> def change_timestamp(self, area, affect_range=None): <NEW_LINE> <INDENT> if affect_range: <NEW_LINE> <INDENT> self.timestamp[affect_range[0] + 1:affect_range[1] + 2] = self.timestamp[ affect_range[0] + 1:affect_range[1] + 2].astype( int) + area <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.timestamp = self.timestamp.astype(int) + area <NEW_LINE> <DEDENT> <DEDENT> def save(self, tag): <NEW_LINE> <INDENT> data = np.hstack((self.info[1:, ], self.a[1:, ], self.w[1:, ], self.end_info[1:, ], self.timestamp[1:, ])) <NEW_LINE> new_imu = os.path.splitext(self.file)[0] + "_" + str(tag) + '.imu' <NEW_LINE> np.savetxt(new_imu, data, delimiter=',', fmt='%s') <NEW_LINE> return data | the class that parse the input imu and adds noise to imu | 62599069d6c5a102081e38fe |
class BoxTransfer(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _("box transfer") <NEW_LINE> verbose_name_plural = _("box transfers") <NEW_LINE> <DEDENT> from_box = models.ForeignKey( Box, verbose_name=_("debtor box"), related_name='debits') <NEW_LINE> to_box = models.ForeignKey( Box, verbose_name=_("creditor box"), related_name='credits') <NEW_LINE> amount = models.DecimalField( verbose_name=_("amount"), max_digits=13, decimal_places=2, validators=[ MinValueValidator(0), ]) <NEW_LINE> date = models.DateField( verbose_name=_("transaction date"), default=timezone.now) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{date}: {frm} > {amount}€ > {to} ".format( date=self.date, frm=self.from_box, amount=abs(self.amount), to=self.to_box ) | Represent a tranfer of money from a box to another. | 6259906932920d7e50bc781d |
class IsolatedTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def run(self, result=None): <NEW_LINE> <INDENT> if result is None: result = self.defaultTestResult() <NEW_LINE> run_isolated(unittest.TestCase, self, result) | A TestCase which executes in a forked process.
Each test gets its own process, which has a performance overhead but will
provide excellent isolation from global state (such as django configs,
zope utilities and so on). | 625990697b180e01f3e49c4f |
class Directory(object): <NEW_LINE> <INDENT> def __init__(self, abspath, relpath, parent): <NEW_LINE> <INDENT> self._abspath = abspath <NEW_LINE> self._relpath = relpath <NEW_LINE> self._name = os.path.basename(abspath) <NEW_LINE> self._parent = parent <NEW_LINE> self._rawdoc = None <NEW_LINE> self._module = None <NEW_LINE> self._is_test_dir = False <NEW_LINE> if parent and parent.is_test_directory() or self._name in ('tests', 'legacytests'): <NEW_LINE> <INDENT> self._is_test_dir = True <NEW_LINE> <DEDENT> self._is_external = False <NEW_LINE> if parent and parent.is_external() or self._name == 'external': <NEW_LINE> <INDENT> self._is_external = True <NEW_LINE> <DEDENT> self._subdirs = set() <NEW_LINE> if parent: <NEW_LINE> <INDENT> parent._subdirs.add(self) <NEW_LINE> <DEDENT> self._files = set() <NEW_LINE> self._has_installed_files = None <NEW_LINE> <DEDENT> def set_doc_xml(self, rawdoc, sourcetree): <NEW_LINE> <INDENT> assert self._rawdoc is None <NEW_LINE> assert rawdoc.get_path().rstrip('/') in (self._abspath, self._relpath) <NEW_LINE> self._rawdoc = rawdoc <NEW_LINE> <DEDENT> def set_module(self, module): <NEW_LINE> <INDENT> assert self._module is None <NEW_LINE> self._module = module <NEW_LINE> <DEDENT> def add_file(self, fileobj): <NEW_LINE> <INDENT> self._files.add(fileobj) <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def get_reporter_location(self): <NEW_LINE> <INDENT> return reporter.Location(self._abspath, None) <NEW_LINE> <DEDENT> def get_abspath(self): <NEW_LINE> <INDENT> return self._abspath <NEW_LINE> <DEDENT> def get_relpath(self): <NEW_LINE> <INDENT> return self._relpath <NEW_LINE> <DEDENT> def is_test_directory(self): <NEW_LINE> <INDENT> return self._is_test_dir <NEW_LINE> <DEDENT> def is_external(self): <NEW_LINE> <INDENT> return self._is_external <NEW_LINE> <DEDENT> def has_installed_files(self): <NEW_LINE> <INDENT> if self._has_installed_files is None: <NEW_LINE> <INDENT> self._has_installed_files = False <NEW_LINE> for subdir in self._subdirs: <NEW_LINE> <INDENT> if subdir.has_installed_files(): <NEW_LINE> <INDENT> self._has_installed_files = True <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> for fileobj in self._files: <NEW_LINE> <INDENT> if fileobj.is_installed(): <NEW_LINE> <INDENT> self._has_installed_files = True <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self._has_installed_files <NEW_LINE> <DEDENT> def get_module(self): <NEW_LINE> <INDENT> if self._module: <NEW_LINE> <INDENT> return self._module <NEW_LINE> <DEDENT> if self._parent: <NEW_LINE> <INDENT> return self._parent.get_module() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_subdirectories(self): <NEW_LINE> <INDENT> return self._subdirs <NEW_LINE> <DEDENT> def get_files(self): <NEW_LINE> <INDENT> for subdir in self._subdirs: <NEW_LINE> <INDENT> for fileobj in subdir.get_files(): <NEW_LINE> <INDENT> yield fileobj <NEW_LINE> <DEDENT> <DEDENT> for fileobj in self._files: <NEW_LINE> <INDENT> yield fileobj <NEW_LINE> <DEDENT> <DEDENT> def contains(self, fileobj): <NEW_LINE> <INDENT> dirobj = fileobj.get_directory() <NEW_LINE> while dirobj: <NEW_LINE> <INDENT> if dirobj == self: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> dirobj = dirobj._parent <NEW_LINE> <DEDENT> return False | (Sub)directory in the GROMACS tree. | 625990694a966d76dd5f06cb |
class CacheBackend(KeyValueStoreBackend): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CacheBackend, self).__init__(*args, **kwargs) <NEW_LINE> self.serializer = 'pickle' <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> return self.cache_backend.get(key) <NEW_LINE> <DEDENT> def set(self, key, value): <NEW_LINE> <INDENT> self.cache_backend.set(key, value, self.expires) <NEW_LINE> <DEDENT> def delete(self, key): <NEW_LINE> <INDENT> self.cache_backend.delete(key) <NEW_LINE> <DEDENT> def encode(self, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> def decode(self, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> @property <NEW_LINE> def cache_backend(self): <NEW_LINE> <INDENT> backend = self.app.conf.cache_backend <NEW_LINE> return caches[backend] if backend else default_cache | Backend using the Django cache framework to store task metadata. | 625990698e7ae83300eea865 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.