code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
class SoundFileError(Exception): <NEW_LINE> <INDENT> pass
|
Class to report sound file failed to load
|
6259902ad6c5a102081e30f5
|
class SharedRMSprop(optim.Optimizer): <NEW_LINE> <INDENT> def __init__(self, params, lr=7e-4, alpha=0.99, eps=0.1, weight_decay=0, momentum=0, centered=False): <NEW_LINE> <INDENT> defaults = defaultdict( lr=lr, alpha=alpha, eps=eps, weight_decay=weight_decay, momentum=momentum, centered=centered) <NEW_LINE> super(SharedRMSprop, self).__init__(params, defaults) <NEW_LINE> for group in self.param_groups: <NEW_LINE> <INDENT> for p in group['params']: <NEW_LINE> <INDENT> state = self.state[p] <NEW_LINE> state['step'] = torch.zeros(1) <NEW_LINE> state['grad_avg'] = p.data.new().resize_as_(p.data).zero_() <NEW_LINE> state['square_avg'] = p.data.new().resize_as_(p.data).zero_() <NEW_LINE> state['momentum_buffer'] = p.data.new().resize_as_( p.data).zero_() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def share_memory(self): <NEW_LINE> <INDENT> for group in self.param_groups: <NEW_LINE> <INDENT> for p in group['params']: <NEW_LINE> <INDENT> state = self.state[p] <NEW_LINE> state['square_avg'].share_memory_() <NEW_LINE> state['step'].share_memory_() <NEW_LINE> state['grad_avg'].share_memory_() <NEW_LINE> state['momentum_buffer'].share_memory_() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def step(self, closure=None): <NEW_LINE> <INDENT> loss = None <NEW_LINE> if closure is not None: <NEW_LINE> <INDENT> loss = closure() <NEW_LINE> <DEDENT> for group in self.param_groups: <NEW_LINE> <INDENT> for p in group['params']: <NEW_LINE> <INDENT> if p.grad is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> grad = p.grad.data <NEW_LINE> if grad.is_sparse: <NEW_LINE> <INDENT> raise RuntimeError( 'RMSprop does not support sparse gradients') <NEW_LINE> <DEDENT> state = self.state[p] <NEW_LINE> square_avg = state['square_avg'] <NEW_LINE> alpha = group['alpha'] <NEW_LINE> state['step'] += 1 <NEW_LINE> if group['weight_decay'] != 0: <NEW_LINE> <INDENT> grad = grad.add(group['weight_decay'], p.data) <NEW_LINE> <DEDENT> square_avg.mul_(alpha).addcmul_(1 - alpha, grad, grad) <NEW_LINE> if group['centered']: <NEW_LINE> <INDENT> grad_avg = state['grad_avg'] <NEW_LINE> grad_avg.mul_(alpha).add_(1 - alpha, grad) <NEW_LINE> avg = square_avg.addcmul(-1, grad_avg, grad_avg).sqrt().add_( group['eps']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> avg = square_avg.sqrt().add_(group['eps']) <NEW_LINE> <DEDENT> if group['momentum'] > 0: <NEW_LINE> <INDENT> buf = state['momentum_buffer'] <NEW_LINE> buf.mul_(group['momentum']).addcdiv_(grad, avg) <NEW_LINE> p.data.add_(-group['lr'], buf) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p.data.addcdiv_(-group['lr'], grad, avg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return loss
|
Implements RMSprop algorithm with shared states.
|
6259902a66673b3332c313be
|
class BanchiFlask(Flask): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.endpoints = {} <NEW_LINE> self.__dict__.update({ method: self.__shorthand(methods=[method.upper()]) for method in ["get", "post", "put"]}) <NEW_LINE> return Flask.__init__(self, *args, **kwargs) <NEW_LINE> <DEDENT> def endpoint(self, *args, **kwargs): <NEW_LINE> <INDENT> def decorator(f): <NEW_LINE> <INDENT> self.endpoints[f.__name__] = { 'url': args[0] } <NEW_LINE> return self.route(*args, **kwargs)(f) <NEW_LINE> <DEDENT> return decorator <NEW_LINE> <DEDENT> def __shorthand(self, **defaults): <NEW_LINE> <INDENT> def new_route(*args, **kwargs): <NEW_LINE> <INDENT> kwargs.update(defaults) <NEW_LINE> return lambda f: self.route(*args, **kwargs)(f) <NEW_LINE> <DEDENT> return new_route
|
BanchiFlask:
This is just an expansion on the Flask app class to add fancier decorators
to the app
|
6259902a26238365f5fadb21
|
class GetParamDescriptionForNonManufacturerPid(ParamDescriptionTestFixture): <NEW_LINE> <INDENT> CATEGORY = TestCategory.ERROR_CONDITIONS <NEW_LINE> PID = 'PARAMETER_DESCRIPTION' <NEW_LINE> REQUIRES = ['manufacturer_parameters'] <NEW_LINE> def Test(self): <NEW_LINE> <INDENT> device_info_pid = self.LookupPid('DEVICE_INFO') <NEW_LINE> results = [ self.NackGetResult(RDMNack.NR_UNKNOWN_PID), self.NackGetResult( RDMNack.NR_DATA_OUT_OF_RANGE, advisory='Parameter Description appears to be supported but no' 'manufacturer PIDs were declared'), ] <NEW_LINE> if self.Property('manufacturer_parameters'): <NEW_LINE> <INDENT> results = self.NackGetResult(RDMNack.NR_DATA_OUT_OF_RANGE) <NEW_LINE> <DEDENT> self.AddExpectedResults(results) <NEW_LINE> self.SendGet(ROOT_DEVICE, self.pid, [device_info_pid.value])
|
GET parameter description for a non-manufacturer pid.
|
6259902a8e05c05ec3f6f643
|
class Dummy_x(basebehavior.behaviorimplementation.BehaviorImplementation): <NEW_LINE> <INDENT> def implementation_init(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def implementation_update(self): <NEW_LINE> <INDENT> pass
|
this is a behavior implementation template
|
6259902aa4f1c619b294f5c4
|
class ResourceSkuZoneDetails(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name': {'readonly': True}, 'capabilities': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'name', 'type': '[str]'}, 'capabilities': {'key': 'capabilities', 'type': '[SKUCapability]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ResourceSkuZoneDetails, self).__init__(**kwargs) <NEW_LINE> self.name = None <NEW_LINE> self.capabilities = None
|
Describes The zonal capabilities of a SKU.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: The set of zones that the SKU is available in with the specified capabilities.
:vartype name: list[str]
:ivar capabilities: A list of capabilities that are available for the SKU in the specified list
of zones.
:vartype capabilities: list[~azure.mgmt.machinelearningservices.models.SKUCapability]
|
6259902a63f4b57ef008655a
|
class DesignateQuotas(object): <NEW_LINE> <INDENT> QUOTAS_SCHEMA = { "type": "object", "additionalProperties": False, "properties": { "domains": { "type": "integer", "minimum": 1 }, "domain_recordsets": { "type": "integer", "minimum": 1 }, "domain_records": { "type": "integer", "minimum": 1 }, "recordset_records": { "type": "integer", "minimum": 1 }, } } <NEW_LINE> def __init__(self, clients): <NEW_LINE> <INDENT> self.clients = clients <NEW_LINE> <DEDENT> def update(self, tenant_id, **kwargs): <NEW_LINE> <INDENT> self.clients.designate().quotas.update(tenant_id, kwargs) <NEW_LINE> <DEDENT> def delete(self, tenant_id): <NEW_LINE> <INDENT> self.clients.designate().quotas.reset(tenant_id)
|
Management of Designate quotas.
|
6259902a8c3a8732951f7528
|
class Renderer(base.Renderer): <NEW_LINE> <INDENT> _template = ViewPageTemplateFile('projectOverview.pt') <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> base.Renderer.__init__(self, *args) <NEW_LINE> try: <NEW_LINE> <INDENT> self.project = aq_inner(self.context).getProjectRoot() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.project = None <NEW_LINE> <DEDENT> <DEDENT> def render(self): <NEW_LINE> <INDENT> return self._template() <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self): <NEW_LINE> <INDENT> if not self.project: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def projectInfo(self): <NEW_LINE> <INDENT> projectUrl = self.project.absolute_url() <NEW_LINE> return {'url' : projectUrl, 'projectUrl' : projectUrl + '/project_view', 'iterationsUrl' : projectUrl + '/project_iterations', 'storiesUrl' : projectUrl + '/project_stories', 'useCasesUrl' : projectUrl + '/project_useCases', 'title' : self.project.title or self.project.id, 'svnUrl' : self.project.xppm_repo_url, 'viewUrl' : self.project.xppm_browse_code_url, }
|
returns the HTML for this portlet.
|
6259902a21bff66bcd723c33
|
class ProcessReportGenerator(object): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> return pm.ProcessModel(psutil.Process(os.getpid()))
|
A Process Data Generator
This generator returns a
:class:`openstack.common.report.models.process.ProcessModel`
based on the current process (which will also include
all subprocesses, recursively) using the :class:`psutil.Process` class`.
|
6259902a30c21e258be997dc
|
class InvitationForm(forms.Form): <NEW_LINE> <INDENT> email = forms.EmailField( validators=[validate_free_email], widget=forms.TextInput(attrs={'max_length': 75}), label=strings.INVITATION_EMAIL ) <NEW_LINE> def clean_email(self): <NEW_LINE> <INDENT> email = self.cleaned_data['email'] <NEW_LINE> email = multiple_whitespace_to_single_space(email).strip() <NEW_LINE> if Invitation.objects.filter(email=email).exists(): <NEW_LINE> <INDENT> raise forms.ValidationError(strings.ALREADY_USED_FOR_INVITATION) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return email <NEW_LINE> <DEDENT> <DEDENT> def save(self, ipaddr=None): <NEW_LINE> <INDENT> invitation = Invitation.create_invitation( email=self.cleaned_data['email'], ipaddr=ipaddr ) <NEW_LINE> return invitation
|
Form must check if the email is unique
|
6259902ac432627299fa3fc4
|
class PowerRating(models.Model): <NEW_LINE> <INDENT> power = models.FloatField('The ammount of power') <NEW_LINE> minRpm = models.IntegerField('How many RPMs for this rating', null = True) <NEW_LINE> maxRpm = models.IntegerField('Maximum RPMs for this rating', null = True)
|
Meansures how powerful the engine is
|
6259902a5166f23b2e2443a6
|
class Room(object): <NEW_LINE> <INDENT> def __init__(self, name, description1): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.description1 = description1 <NEW_LINE> self.description2 = '' <NEW_LINE> self.visited = False <NEW_LINE> self.exits = {} <NEW_LINE> self.items = {} <NEW_LINE> <DEDENT> def setDescription2(self, description2): <NEW_LINE> <INDENT> self.description2 = description2 <NEW_LINE> <DEDENT> def setVisited(self): <NEW_LINE> <INDENT> self.visited = True <NEW_LINE> <DEDENT> def addItem(self, item): <NEW_LINE> <INDENT> self.items[item.getName()] = item <NEW_LINE> <DEDENT> def rmItem(self, name): <NEW_LINE> <INDENT> del self.items[name] <NEW_LINE> <DEDENT> def listItems(self): <NEW_LINE> <INDENT> itemList = '' <NEW_LINE> for item in self.items: <NEW_LINE> <INDENT> itemList += ' | ' + str(item) <NEW_LINE> <DEDENT> return 'Itens: ' + itemList + ' |' <NEW_LINE> <DEDENT> def hasItems(self): <NEW_LINE> <INDENT> if(len(self.items.keys()) == 0): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def getItem(self, name): <NEW_LINE> <INDENT> return self.items[name] <NEW_LINE> <DEDENT> def getItems(self): <NEW_LINE> <INDENT> return self.items.keys() <NEW_LINE> <DEDENT> def getDescription(self): <NEW_LINE> <INDENT> if(not self.visited): <NEW_LINE> <INDENT> return self.description1 <NEW_LINE> <DEDENT> return self.description2 <NEW_LINE> <DEDENT> def getName(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def getFullDescription(self): <NEW_LINE> <INDENT> return 'Você está nos(as)/no(a) ' + self.name + ', ' + self.getDescription() <NEW_LINE> <DEDENT> def setExits(self, exit, room): <NEW_LINE> <INDENT> self.exits[exit] = room <NEW_LINE> <DEDENT> def hasExit(self): <NEW_LINE> <INDENT> if(len(self.exits.keys()) > 0): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def getExits(self): <NEW_LINE> <INDENT> return self.exits.keys() <NEW_LINE> <DEDENT> def getExitsDict(self): <NEW_LINE> <INDENT> return self.exits <NEW_LINE> <DEDENT> def getExitString(self): <NEW_LINE> <INDENT> exitString = '' <NEW_LINE> for exit in self.exits: <NEW_LINE> <INDENT> exitString += ' | ' + exit <NEW_LINE> <DEDENT> return 'Saídas: ' + exitString + ' |' <NEW_LINE> <DEDENT> def goExit(self, exit): <NEW_LINE> <INDENT> return self.exits[exit]
|
Classe que define uma sala dentro do jogo
|
6259902a56b00c62f0fb3891
|
class TestOptionalViews(ViewCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestOptionalViews, self).setUp() <NEW_LINE> self.v0 = self.create({ 'model': 'a', 'arch': '<qweb><base/></qweb>', }) <NEW_LINE> self.v1 = self.create({ 'model': 'a', 'inherit_id': self.v0, 'application': 'always', 'priority': 10, 'arch': '<xpath expr="//base" position="after"><v1/></xpath>', }) <NEW_LINE> self.v2 = self.create({ 'model': 'a', 'inherit_id': self.v0, 'application': 'enabled', 'priority': 9, 'arch': '<xpath expr="//base" position="after"><v2/></xpath>', }) <NEW_LINE> self.v3 = self.create({ 'model': 'a', 'inherit_id': self.v0, 'application': 'disabled', 'priority': 8, 'arch': '<xpath expr="//base" position="after"><v3/></xpath>' }) <NEW_LINE> <DEDENT> def test_applied(self): <NEW_LINE> <INDENT> arch = self.read_combined(self.v0)['arch'] <NEW_LINE> self.assertEqual( ET.fromstring(arch), E.qweb( E.base(), E.v1(), E.v2(), ) ) <NEW_LINE> <DEDENT> def test_applied_state_toggle(self): <NEW_LINE> <INDENT> self.browse(self.v2).write({'application': 'disabled'}) <NEW_LINE> arch = self.read_combined(self.v0)['arch'] <NEW_LINE> self.assertEqual( ET.fromstring(arch), E.qweb( E.base(), E.v1(), ) ) <NEW_LINE> self.browse(self.v3).write({'application': 'enabled'}) <NEW_LINE> arch = self.read_combined(self.v0)['arch'] <NEW_LINE> self.assertEqual( ET.fromstring(arch), E.qweb( E.base(), E.v1(), E.v3(), ) ) <NEW_LINE> self.browse(self.v2).write({'application': 'enabled'}) <NEW_LINE> arch = self.read_combined(self.v0)['arch'] <NEW_LINE> self.assertEqual( ET.fromstring(arch), E.qweb( E.base(), E.v1(), E.v2(), E.v3(), ) )
|
Tests ability to enable/disable inherited views, formerly known as
inherit_option_id
|
6259902a5e10d32532ce40ec
|
class DummyQualitySupplier(object): <NEW_LINE> <INDENT> implements(IScaledImageQuality) <NEW_LINE> def getQuality(self): <NEW_LINE> <INDENT> return 1
|
fake utility for plone.app.imaging's scaling quality
|
6259902a23e79379d538d4dc
|
class LocalizedDescription(ClientValue): <NEW_LINE> <INDENT> def __init__(self, language_tag=None, description=None): <NEW_LINE> <INDENT> super(LocalizedDescription, self).__init__() <NEW_LINE> self.languageTag = language_tag <NEW_LINE> self.description = description
|
Represents the localized description used to describe a term in the term store.
|
6259902ad10714528d69ee75
|
class ApiMethodInfo(messages.Message): <NEW_LINE> <INDENT> relative_path = messages.StringField(1) <NEW_LINE> method_id = messages.StringField(2) <NEW_LINE> http_method = messages.StringField(3) <NEW_LINE> path_params = messages.StringField(4, repeated=True) <NEW_LINE> query_params = messages.StringField(5, repeated=True) <NEW_LINE> ordered_params = messages.StringField(6, repeated=True) <NEW_LINE> description = messages.StringField(7) <NEW_LINE> request_type_name = messages.StringField(8) <NEW_LINE> response_type_name = messages.StringField(9) <NEW_LINE> request_field = messages.StringField(10, default='') <NEW_LINE> upload_config = messages.MessageField(ApiUploadInfo, 11) <NEW_LINE> supports_download = messages.BooleanField(12, default=False)
|
Configuration info for an API method.
All fields are strings unless noted otherwise.
Fields:
relative_path: Relative path for this method.
method_id: ID for this method.
http_method: HTTP verb to use for this method.
path_params: (repeated) path parameters for this method.
query_params: (repeated) query parameters for this method.
ordered_params: (repeated) ordered list of parameters for
this method.
description: description of this method.
request_type_name: name of the request type.
response_type_name: name of the response type.
request_field: if not null, the field to pass as the body
of this POST request. may also be the REQUEST_IS_BODY
value below to indicate the whole message is the body.
upload_config: (ApiUploadInfo) Information about the upload
configuration supported by this method.
supports_download: (boolean) If True, this method supports
downloading the request via the `alt=media` query
parameter.
|
6259902a8c3a8732951f752a
|
class MainHandler(BaseHandler, TemplateRendering): <NEW_LINE> <INDENT> def get(self, *args): <NEW_LINE> <INDENT> variables = {'message':'Hello, Tornado!', 'page_title': self.settings["page_title"], 'page_description': '', 'page_author': 'The author of the page.', 'sourcecode_stylesheet': self.settings["sourcecode_stylesheet"], 'HTTPFUNCTION':'GET'} <NEW_LINE> content = self.render_template('hello_world.html', variables) <NEW_LINE> self.write(content) <NEW_LINE> <DEDENT> def post(self, *args): <NEW_LINE> <INDENT> markup_type = self.get_argument('markup_type', default=u"rst") <NEW_LINE> raw_input = self.get_argument('markup_raw', default=u"") <NEW_LINE> if markup_type: <NEW_LINE> <INDENT> if markup_type == 'rst': <NEW_LINE> <INDENT> html_output = self.render_rst(raw_input) <NEW_LINE> html_output_esc = html_output.encode('iso-8859-1') <NEW_LINE> html_output_esc = ''.join(unicode(html_output_esc, 'utf-8').splitlines()) <NEW_LINE> html_output_esc = ".. sourcecode:: html\n\n "+html_output_esc+" \n " <NEW_LINE> html_output_esc = self.render_rst(html_output_esc) <NEW_LINE> <DEDENT> elif markup_type == 'textile': <NEW_LINE> <INDENT> html_output = self.render_textile(raw_input) <NEW_LINE> html_output_esc = html_output.encode('iso-8859-1') <NEW_LINE> html_output_esc = ''.join(unicode(html_output_esc, 'utf-8').splitlines()) <NEW_LINE> html_output_esc = ".. sourcecode:: html\n\n "+html_output_esc+" \n " <NEW_LINE> html_output_esc = self.render_rst(html_output_esc) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> html_output = self.render_md(raw_input) <NEW_LINE> html_output_esc = html_output.encode('iso-8859-1') <NEW_LINE> html_output_esc = ''.join(unicode(html_output_esc, 'utf-8').splitlines()) <NEW_LINE> html_output_esc = ".. sourcecode:: html\n\n "+html_output_esc+" \n " <NEW_LINE> html_output_esc = self.render_rst(html_output_esc) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> html_output = u"" <NEW_LINE> html_output_esc = u"" <NEW_LINE> <DEDENT> variables = { 'message':'Hello, Tornado!', 'page_title': self.settings["page_title"], 'page_description': '', 'page_author': 'The author of the page.', 'raw_input':raw_input, 'html_output':html_output, 'html_output_esc': html_output_esc, 'sourcecode_stylesheet': self.settings["sourcecode_stylesheet"], 'HTTPFUNCTION':'POST', 'markup_type': markup_type } <NEW_LINE> content = self.render_template('hello_world.html', variables) <NEW_LINE> self.write(content)
|
MainHandler
Extends from both BaseHandler and
|
6259902ad99f1b3c44d06675
|
class WebsocketError(AmbientError): <NEW_LINE> <INDENT> pass
|
Define an error related to generic websocket errors.
|
6259902ad6c5a102081e30f9
|
class RelancementAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('applicant', 'content', 'approval_status', 'creation_time') <NEW_LINE> list_filter = ('creation_time', 'approval_status') <NEW_LINE> ordering = ('-creation_time',) <NEW_LINE> search_fields = ('applicant',)
|
公告管理
|
6259902ac432627299fa3fc6
|
class NumericColumnRowFormat(BaseRowFormat): <NEW_LINE> <INDENT> def __init__(self, args): <NEW_LINE> <INDENT> super(NumericColumnRowFormat, self).__init__(args) <NEW_LINE> self.base_headers = ['Name', 'ID', 'Genomic region coordinates'] <NEW_LINE> up = args.get_upstream() <NEW_LINE> down = args.get_downstream() <NEW_LINE> self.size = up + down + 1 <NEW_LINE> self.extra_headers = [str(i) for i in range(-1*up, down+1)] <NEW_LINE> <DEDENT> def make_values(self, prediction): <NEW_LINE> <INDENT> values = self.make_base_values(prediction) <NEW_LINE> return values + get_all_values(prediction, self.size)
|
Adds numeric columns with individual prediction values to 6 base columns
|
6259902a0a366e3fb87dd9ba
|
class Item: <NEW_LINE> <INDENT> nom = "" <NEW_LINE> description = "" <NEW_LINE> quantity = 0 <NEW_LINE> def __init__(self, nom, quantity, texturedir, description=""): <NEW_LINE> <INDENT> self.nom = nom <NEW_LINE> self.description = description <NEW_LINE> self.texture = pygame.image.load(texturedir).convert_alpha() <NEW_LINE> self.quantity = quantity <NEW_LINE> self.textures = [] <NEW_LINE> self.framequantity = self.texture.get_width() // 32 <NEW_LINE> for n in range (self.framequantity): <NEW_LINE> <INDENT> self.textures.append(self.texture.subsurface(pygame.rect.Rect(n*32, 0, 32, 32))) <NEW_LINE> <DEDENT> self.frame = 0 <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> surface = pygame.Surface((32, 32)) <NEW_LINE> surface.blit(self.texture, (0, 0)) <NEW_LINE> return surface <NEW_LINE> <DEDENT> def use(self, user): <NEW_LINE> <INDENT> return(self, "0")
|
Classe Item permettant de base pour tout item de l'inventaire
|
6259902a5e10d32532ce40ed
|
class ExpressRouteCircuitAuthorization(SubResource): <NEW_LINE> <INDENT> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'}, 'authorization_use_status': {'key': 'properties.authorizationUseStatus', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, etag: Optional[str] = None, authorization_key: Optional[str] = None, authorization_use_status: Optional[Union[str, "AuthorizationUseStatus"]] = None, provisioning_state: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(ExpressRouteCircuitAuthorization, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.etag = etag <NEW_LINE> self.authorization_key = authorization_key <NEW_LINE> self.authorization_use_status = authorization_use_status <NEW_LINE> self.provisioning_state = provisioning_state
|
Authorization in an ExpressRouteCircuit resource.
:param id: Resource Identifier.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param authorization_key: The authorization key.
:type authorization_key: str
:param authorization_use_status: AuthorizationUseStatus. Possible values are: 'Available' and
'InUse'. Possible values include: "Available", "InUse".
:type authorization_use_status: str or
~azure.mgmt.network.v2015_06_15.models.AuthorizationUseStatus
:param provisioning_state: Gets the provisioning state of the public IP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
|
6259902a8e05c05ec3f6f645
|
class ObservedPeriod(ParameterPanel): <NEW_LINE> <INDENT> get_default_start_date = None <NEW_LINE> get_default_end_date = None <NEW_LINE> def __init__(self, **kw): <NEW_LINE> <INDENT> kw.update( start_date=models.DateField( _("Period from"), blank=True, null=True, default=self.get_default_start_date, help_text="""Start date of observed period"""), end_date=models.DateField( _("until"), blank=True, null=True, default=self.get_default_end_date, help_text="""End date of observed period"""), ) <NEW_LINE> super(ObservedPeriod, self).__init__(**kw)
|
Parameter panel which defines two fields `start_date`
and `end_date` which default to empty
|
6259902a73bcbd0ca4bcb265
|
class value_t(object): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> return <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return value_t(self.value) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return type(other) == value_t and self.value == other.value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<value %u>' % self.value <NEW_LINE> <DEDENT> def get_string(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return idc.GetString(self.value) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.value is None: <NEW_LINE> <INDENT> return '<none!>' <NEW_LINE> <DEDENT> s = self.get_string() <NEW_LINE> if s: <NEW_LINE> <INDENT> return '%s' % (repr(s), ) <NEW_LINE> <DEDENT> names = dict(idautils.Names()) <NEW_LINE> if self.value in names: <NEW_LINE> <INDENT> return names[self.value] <NEW_LINE> <DEDENT> if self.value < 16: <NEW_LINE> <INDENT> return '%u' % self.value <NEW_LINE> <DEDENT> return '0x%x' % self.value <NEW_LINE> <DEDENT> def iteroperands(self): <NEW_LINE> <INDENT> yield self <NEW_LINE> return
|
any literal value
|
6259902a3eb6a72ae038b638
|
class SupplierViewSet(PermissionHelperMixin, viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = Supplier.objects.all() <NEW_LINE> serializer_class = SupplierSerializer <NEW_LINE> def get_view_name(self): <NEW_LINE> <INDENT> return _("Suppliers") <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_help_text(cls): <NEW_LINE> <INDENT> return _("Suppliers can be listed and fetched and stock can be updated.") <NEW_LINE> <DEDENT> @schema_serializer_class(StockAdjustmentSerializer) <NEW_LINE> @detail_route(methods=['get', 'post']) <NEW_LINE> def stock(self, request, pk=None): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> return self._adjust_stock(request, pk) <NEW_LINE> <DEDENT> supplier = self.get_object() <NEW_LINE> if getattr(self.request.user, 'is_superuser', False): <NEW_LINE> <INDENT> products_qs = Product.objects.all_except_deleted() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> products_qs = Product.objects.listed( customer=self.request.customer, shop=self.request.shop ) <NEW_LINE> <DEDENT> products_qs = products_qs.filter(shop_products__suppliers=supplier) <NEW_LINE> product_id = int(parse_decimal_string(request.query_params.get("product", 0))) <NEW_LINE> if product_id: <NEW_LINE> <INDENT> products_qs = products_qs.filter(pk=product_id) <NEW_LINE> <DEDENT> product_sku = request.query_params.get("sku") <NEW_LINE> if product_sku: <NEW_LINE> <INDENT> products_qs = products_qs.filter(sku=product_sku) <NEW_LINE> <DEDENT> page = self.paginate_queryset(products_qs) <NEW_LINE> context = {'request': request, 'supplier': supplier} <NEW_LINE> serializer = ProductStockSerializer((page or products_qs), many=True, context=context) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def _adjust_stock(self, request, pk=None): <NEW_LINE> <INDENT> supplier = self.get_object() <NEW_LINE> serializer = StockAdjustmentSerializer(data=request.data) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> serializer.save(supplier=supplier) <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED)
|
retrieve: Fetches a supplier by its ID.
list: Lists all available suppliers.
|
6259902ad10714528d69ee76
|
class TestPost(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self) -> None: <NEW_LINE> <INDENT> self.session = requests.session() <NEW_LINE> self.token = get_main_page_token(self.session) <NEW_LINE> self.token_id = get_login_token_id(self.session) <NEW_LINE> <DEDENT> def tearDown(self) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_post_sucess_01(self): <NEW_LINE> <INDENT> logger.info("执行发帖模块第一个案例:登录授权后进行发贴") <NEW_LINE> login_auth(self.session) <NEW_LINE> post_req01= post_info(self.session, title = "ljl0709发帖"+ time.strftime('%Y-%m-%d-%H-%M-%S'), content = "ljl0709发帖"+time.strftime('%Y-%m-%d-%H-%M-%S'), token = self.token) <NEW_LINE> post_rep01 = post_req01.content.decode('utf-8') <NEW_LINE> self.assertEqual(post_req01.json()['state'], "success") <NEW_LINE> <DEDENT> def test_post_no_auth_fail_02(self): <NEW_LINE> <INDENT> logger.info("执行发帖模块第二个案例:登录后不进行授权进行发贴") <NEW_LINE> post_req02= post_info(self.session, title = "ljl0709发帖"+ time.strftime('%Y-%m-%d-%H-%M-%S'), content = "ljl0709发帖"+time.strftime('%Y-%m-%d-%H-%M-%S'), token = self.token) <NEW_LINE> post_rep02 = post_req02.content.decode('utf-8') <NEW_LINE> self.assertEqual(post_req02.json()['state'], "fail") <NEW_LINE> <DEDENT> def test_post_wrong_token_fail_03(self): <NEW_LINE> <INDENT> logger.info("执行发帖模块第三个案例:发贴接口上送错误的token") <NEW_LINE> post_req03= post_info(self.session, title = "ljl0709发帖"+ time.strftime('%Y-%m-%d-%H-%M-%S'), content = "ljl0709发帖"+time.strftime('%Y-%m-%d-%H-%M-%S'), token = "111111") <NEW_LINE> post_rep03 = post_req03.content.decode('utf-8') <NEW_LINE> self.assertEqual(post_req03.json()['state'], "fail") <NEW_LINE> <DEDENT> def test_post_title_null_fail_04(self): <NEW_LINE> <INDENT> logger.info("执行发帖模块第四个案例:发贴接口标题送None") <NEW_LINE> post_req04= post_info(self.session, title = None, content = "ljl0709发帖"+time.strftime('%Y-%m-%d-%H-%M-%S'), token = self.token) <NEW_LINE> post_rep04 = post_req04.content.decode('utf-8') <NEW_LINE> self.assertEqual(post_req04.json()['state'], "fail")
|
发帖模块测试用例
|
6259902abe8e80087fbc004d
|
class ELOIndex(indexes.SearchIndex, indexes.Indexable): <NEW_LINE> <INDENT> text = indexes.CharField(document=True, use_template=True) <NEW_LINE> author = indexes.CharField(model_attr='author') <NEW_LINE> create_date = indexes.DateTimeField(model_attr='create_date') <NEW_LINE> update_date = indexes.DateTimeField(model_attr='update_date') <NEW_LINE> def get_model(self): <NEW_LINE> <INDENT> return ELO
|
Index of ELO
|
6259902a9b70327d1c57fd56
|
class k_means(object): <NEW_LINE> <INDENT> def __init__(self, m, data): <NEW_LINE> <INDENT> self.m = m <NEW_LINE> self.data = data <NEW_LINE> <DEDENT> def cluster_centroid_initialization(self, K): <NEW_LINE> <INDENT> cluster_centroids = random.sample(self.data, K) <NEW_LINE> return cluster_centroids <NEW_LINE> <DEDENT> def clustering(self, K, cluster_centroids): <NEW_LINE> <INDENT> clusters_dictionary = {k+1 : cluster_centroids[k] for k in range(0,K)} <NEW_LINE> assignment_dictionary = {} <NEW_LINE> for x in range(0, self.m): <NEW_LINE> <INDENT> temp_0 = 1000000 <NEW_LINE> for k in range(1, K+1): <NEW_LINE> <INDENT> distance = np.linalg.norm((self.data[x] - clusters_dictionary[k]), ord=2) <NEW_LINE> if distance <= temp_0: <NEW_LINE> <INDENT> assignment_dictionary.update({x : k}) <NEW_LINE> temp_0 = distance <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for k in range(1, K+1): <NEW_LINE> <INDENT> list_of_points = [] <NEW_LINE> for x, cluster in assignment_dictionary.iteritems(): <NEW_LINE> <INDENT> if cluster == k: <NEW_LINE> <INDENT> list_of_points.append(self.data[x]) <NEW_LINE> <DEDENT> <DEDENT> average_point = sum(list_of_points)/len(list_of_points) <NEW_LINE> clusters_dictionary[k] = average_point <NEW_LINE> <DEDENT> cluster_centroid_output = np.arange(K) <NEW_LINE> for k in range(0,K): <NEW_LINE> <INDENT> cluster_centroid_output[k] = clusters_dictionary[k+1] <NEW_LINE> <DEDENT> return cluster_centroid_output <NEW_LINE> <DEDENT> def find_clusters(self, K): <NEW_LINE> <INDENT> init = self.cluster_centroid_initialization(K) <NEW_LINE> iterations = 100 <NEW_LINE> for i in range(0,iterations): <NEW_LINE> <INDENT> temp0 = self.clustering(K, init) <NEW_LINE> init = temp0 <NEW_LINE> <DEDENT> return temp0 <NEW_LINE> <DEDENT> def distorsion_function(self, K, cluster_centroids): <NEW_LINE> <INDENT> clusters_dictionary = {k+1 : cluster_centroids[k] for k in range(0,K)} <NEW_LINE> assignment_dictionary = {} <NEW_LINE> for x in range(0, self.m): <NEW_LINE> <INDENT> temp_0 = 1000000 <NEW_LINE> for k in range(1,K+1): <NEW_LINE> <INDENT> distance = np.linalg.norm((self.data[x] - clusters_dictionary[k]), ord=2) <NEW_LINE> if distance <= temp_0: <NEW_LINE> <INDENT> assignment_dictionary.update({x : k}) <NEW_LINE> temp_0 = distance <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> total_distorsion = 0.0 <NEW_LINE> for x in range(0, self.m): <NEW_LINE> <INDENT> associated_cluster = assignment_dictionary[x] <NEW_LINE> distance2 = self.data[x] - clusters_dictionary[associated_cluster] <NEW_LINE> total_distorsion += np.linalg.norm(distance2, ord=2) <NEW_LINE> <DEDENT> total_distorsion = total_distorsion / self.m <NEW_LINE> return total_distorsion <NEW_LINE> <DEDENT> def robust_centroids(self, K): <NEW_LINE> <INDENT> init_cost = pow(10,100) <NEW_LINE> for i in range(0,100): <NEW_LINE> <INDENT> temp_clusters = self.find_clusters(K) <NEW_LINE> temp_cost = self.distorsion_function(K, temp_clusters) <NEW_LINE> if temp_cost < init_cost: <NEW_LINE> <INDENT> optimal_centroids = temp_clusters <NEW_LINE> init_cost = temp_cost <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return init_cost
|
K-means clustering algorithm, unsupervised learning. Most of code assumes only one feature.
|
6259902a8c3a8732951f752c
|
@pytest.mark.usefixtures('psql_settings', 'settings', scope='class') <NEW_LINE> class TestServicePostgresql(): <NEW_LINE> <INDENT> def test_postgresl(self, psql_settings): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logger.info("connecting to postgres with user {user}".format(user=psql_settings['user'])) <NEW_LINE> with psycopg2.connect(host=psql_settings['host'], user=psql_settings['user'], password=psql_settings['password']) as con: <NEW_LINE> <INDENT> with con.cursor() as cur: <NEW_LINE> <INDENT> username = "test_postgresql" <NEW_LINE> cur.execute("CREATE USER {user};".format(user=username)) <NEW_LINE> logger.debug("CREATE USER {user}".format(user=username)) <NEW_LINE> cur.execute("SELECT 1 FROM pg_roles WHERE rolname='{user}'".format(user=username)) <NEW_LINE> assert cur.rowcount == 1 <NEW_LINE> cur.execute("DROP USER {user};".format(user=username)) <NEW_LINE> logger.debug("DROP USER {user};".format(user=username)) <NEW_LINE> cur.execute("SELECT 1 FROM pg_roles WHERE rolname='{user}'".format(user=username)) <NEW_LINE> assert cur.rowcount == 0 <NEW_LINE> con.commit() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.debug(e) <NEW_LINE> if con: <NEW_LINE> <INDENT> con.rollback() <NEW_LINE> <DEDENT> pytest.fail("Error {error}".format(error=e)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if con: <NEW_LINE> <INDENT> con.close() <NEW_LINE> logger.info("closed connection to postgresql")
|
Class to test the posgresql service.
|
6259902a1d351010ab8f4aec
|
class PrivateLinkServiceConnection(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'request_message': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'private_link_service_id': {'key': 'properties.privateLinkServiceId', 'type': 'str'}, 'group_ids': {'key': 'properties.groupIds', 'type': '[str]'}, 'request_message': {'key': 'properties.requestMessage', 'type': 'str'}, 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkConnectionState'}, } <NEW_LINE> def __init__( self, *, private_link_service_id: Optional[str] = None, group_ids: Optional[List[str]] = None, private_link_service_connection_state: Optional["PrivateLinkConnectionState"] = None, **kwargs ): <NEW_LINE> <INDENT> super(PrivateLinkServiceConnection, self).__init__(**kwargs) <NEW_LINE> self.private_link_service_id = private_link_service_id <NEW_LINE> self.group_ids = group_ids <NEW_LINE> self.request_message = None <NEW_LINE> self.private_link_service_connection_state = private_link_service_connection_state
|
A grouping of information about the connection to the remote resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar private_link_service_id: The resource id of the private link service. Required on PUT
(CreateOrUpdate) requests.
:vartype private_link_service_id: str
:ivar group_ids: The ID(s) of the group(s) obtained from the remote resource that this private
endpoint should connect to. Required on PUT (CreateOrUpdate) requests.
:vartype group_ids: list[str]
:ivar request_message: A message passed to the owner of the remote resource with this
connection request. Restricted to 140 chars.
:vartype request_message: str
:ivar private_link_service_connection_state: A collection of read-only information about the
state of the connection to the private remote resource.
:vartype private_link_service_connection_state:
~stream_analytics_management_client.models.PrivateLinkConnectionState
|
6259902a23e79379d538d4e0
|
class IndexItemsView(abc.ItemsView): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def __iter__(self): <NEW_LINE> <INDENT> return zip(self._mapping._variables, self._mapping._data.flat)
|
Faster read access to the numpy array
|
6259902aec188e330fdf9868
|
class MaxMinPriceMethod(LPMethod): <NEW_LINE> <INDENT> def __init__(self, valuations, verbosity=1): <NEW_LINE> <INDENT> super().__init__(valuations, verbosity) <NEW_LINE> <DEDENT> def solve_prices(self): <NEW_LINE> <INDENT> c = np.zeros((self.n + 1, 1)) <NEW_LINE> c[-1, 0] = -1 <NEW_LINE> all_G = [] <NEW_LINE> all_h = [] <NEW_LINE> for agent_id in range(self.n): <NEW_LINE> <INDENT> assigned_room = self.assignments[agent_id] <NEW_LINE> g = np.zeros(self.n + 1) <NEW_LINE> g[-1] = 1 <NEW_LINE> g[assigned_room] = -1 <NEW_LINE> h = 0 <NEW_LINE> all_G.append(g) <NEW_LINE> all_h.append(h) <NEW_LINE> <DEDENT> for agent_id in range(self.n): <NEW_LINE> <INDENT> assigned_room = self.assignments[agent_id] <NEW_LINE> for other_room in range(self.n): <NEW_LINE> <INDENT> if other_room == assigned_room: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> g = np.zeros(self.n + 1) <NEW_LINE> g[assigned_room] = 1.0 <NEW_LINE> g[other_room] = -1.0 <NEW_LINE> h = (self.valuations[agent_id, assigned_room] - self.valuations[agent_id, other_room]) <NEW_LINE> all_G.append(g) <NEW_LINE> all_h.append(h) <NEW_LINE> <DEDENT> <DEDENT> G = np.stack(all_G, axis=0) <NEW_LINE> h = np.stack(all_h, axis=0) <NEW_LINE> A = np.ones((1, self.n + 1)) <NEW_LINE> A[0, -1] = 0 <NEW_LINE> b = np.ones((1, 1)) <NEW_LINE> solution = lp(matrix(c, tc='d'), matrix(G, tc='d'), matrix(h, tc='d'), matrix(A, tc='d'), matrix(b, tc='d'), solver='glpk') <NEW_LINE> self.prices = np.array(solution['x']).squeeze()[:self.n] <NEW_LINE> return self.prices
|
Implementation of the fairness splitting algorithm.
Example usage:
valuations = get_valuations()
method = FairnessMethod(valuations)
self.assignemnts, self.prices = method.solve()
|
6259902a5166f23b2e2443ac
|
class NotebookIntrospector(Mapping): <NEW_LINE> <INDENT> def __init__(self, path, literal_eval=True, to_df=False): <NEW_LINE> <INDENT> self.nb = nbformat.read(path, nbformat.NO_CONVERT) <NEW_LINE> self.tag2output_raw = self._tag2output() <NEW_LINE> self.literal_eval = literal_eval <NEW_LINE> self.tag2output = { k: _parse_output(v, literal_eval=literal_eval, to_df=to_df, text_only=False) for k, v in self.tag2output_raw.items() } <NEW_LINE> <DEDENT> def _tag2output(self): <NEW_LINE> <INDENT> cells = [ _process_cell(c) for c in self.nb.cells if c.cell_type == 'code' ] <NEW_LINE> cells = {c[0]: c[1] for c in cells if c is not None} <NEW_LINE> cells = { k: _filter_and_process_outputs(outputs) for k, outputs in cells.items() } <NEW_LINE> return cells <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.tag2output[key] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for k in self.tag2output: <NEW_LINE> <INDENT> yield k <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.tag2output) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{} with {}'.format(type(self).__name__, set(self.tag2output)) <NEW_LINE> <DEDENT> def _ipython_key_completions_(self): <NEW_LINE> <INDENT> return self.tag2output.keys() <NEW_LINE> <DEDENT> def to_json_serializable(self): <NEW_LINE> <INDENT> return { k: _parse_output(v, literal_eval=self.literal_eval, to_df=False, text_only=True) for k, v in self.tag2output_raw.items() } <NEW_LINE> <DEDENT> def get_injected_parameters(self): <NEW_LINE> <INDENT> return parse_injected_parameters_cell(self.nb.cells)
|
Retrieve output from a notebook file with tagged cells.
For instructions on tagging cells,
`see this <https://papermill.readthedocs.io/en/latest/usage-parameterize.html>`_.
Notes
-----
Ignores untagged cells, if a cell has more than one tag, it uses the first
one as identifier. If a cell has more than one output, it uses the last
one and discards the rest.
|
6259902a0a366e3fb87dd9be
|
class SimpleTestTopology(unittest.TestCase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.net = None <NEW_LINE> self.api = None <NEW_LINE> self.s = [] <NEW_LINE> self.h = [] <NEW_LINE> self.d = [] <NEW_LINE> self.dc = [] <NEW_LINE> self.docker_cli = None <NEW_LINE> super(SimpleTestTopology, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def createNet( self, nswitches=0, ndatacenter=0, nhosts=0, ndockers=0, autolinkswitches=False, controller=Controller, **kwargs): <NEW_LINE> <INDENT> self.net = DCNetwork(controller=controller, **kwargs) <NEW_LINE> self.api = RestApiEndpoint("127.0.0.1", 5001) <NEW_LINE> for i in range(1, nswitches+1): <NEW_LINE> <INDENT> self.s.append(self.net.addSwitch('s%d' % i)) <NEW_LINE> <DEDENT> if autolinkswitches: <NEW_LINE> <INDENT> for i in range(0, len(self.s) - 1): <NEW_LINE> <INDENT> self.net.addLink(self.s[i], self.s[i + 1]) <NEW_LINE> <DEDENT> <DEDENT> for i in range(0, ndatacenter): <NEW_LINE> <INDENT> self.dc.append( self.net.addDatacenter( 'datacenter%d' % i, metadata={"unittest_dc": i})) <NEW_LINE> <DEDENT> for i in range(0, ndatacenter): <NEW_LINE> <INDENT> self.api.connectDatacenter(self.dc[i]) <NEW_LINE> <DEDENT> for i in range(0, nhosts): <NEW_LINE> <INDENT> self.h.append(self.net.addHost('h%d' % i)) <NEW_LINE> <DEDENT> for i in range(0, ndockers): <NEW_LINE> <INDENT> self.d.append(self.net.addDocker('d%d' % i, dimage="ubuntu:trusty")) <NEW_LINE> <DEDENT> <DEDENT> def startApi(self): <NEW_LINE> <INDENT> self.api.start() <NEW_LINE> <DEDENT> def startNet(self): <NEW_LINE> <INDENT> self.net.start() <NEW_LINE> <DEDENT> def stopNet(self): <NEW_LINE> <INDENT> self.net.stop() <NEW_LINE> <DEDENT> def getDockerCli(self): <NEW_LINE> <INDENT> if self.docker_cli is None: <NEW_LINE> <INDENT> self.docker_cli = docker.APIClient( base_url='unix://var/run/docker.sock') <NEW_LINE> <DEDENT> return self.docker_cli <NEW_LINE> <DEDENT> def getContainernetContainers(self): <NEW_LINE> <INDENT> return self.getDockerCli().containers(filters={"label": "com.containernet"}) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def setUp(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def tearDown(): <NEW_LINE> <INDENT> cleanup() <NEW_LINE> with open(os.devnull, 'w') as devnull: <NEW_LINE> <INDENT> subprocess.call( "sudo docker rm -f $(sudo docker ps --filter 'label=com.containernet' -a -q)", stdout=devnull, stderr=devnull, shell=True)
|
Helper class to do basic test setups.
s1 -- s2 -- s3 -- ... -- sN
|
6259902a6fece00bbaccc986
|
class RemoteExploitableVerifier(PythonTemplateVerifier): <NEW_LINE> <INDENT> tmp_file = "/tmp/triage.pkl" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> path_to_this_file = os.path.split(os.path.realpath(__file__))[0] <NEW_LINE> super(RemoteExploitableVerifier, self).__init__( config_path=os.path.join(path_to_this_file, 'verifier.cfg')) <NEW_LINE> <DEDENT> def _cleanup_tmp_file(self): <NEW_LINE> <INDENT> if os.path.exists(self.tmp_file): <NEW_LINE> <INDENT> os.remove(self.tmp_file) <NEW_LINE> <DEDENT> <DEDENT> def _create_queue_host_channel(self): <NEW_LINE> <INDENT> conn = pika.BlockingConnection(pika.ConnectionParameters( self.config['DEFAULT']['queue_host'])) <NEW_LINE> channel = conn.channel() <NEW_LINE> return channel, conn <NEW_LINE> <DEDENT> def _send_to_remote_client(self, data): <NEW_LINE> <INDENT> channel, conn = self._create_queue_host_channel() <NEW_LINE> channel.basic_publish(exchange='luckycat', routing_key=self.config['DEFAULT']['remote_queue'], body=data) <NEW_LINE> channel.basic_ack() <NEW_LINE> conn.close() <NEW_LINE> print('Sent crash data: %s' % data) <NEW_LINE> <DEDENT> def _call_exploitable(self, inferior_cmd, crash): <NEW_LINE> <INDENT> self._send_to_remote_client(crash) <NEW_LINE> target = GdbTarget("Some_Router", "127.0.0.1", "1234", "i386", "little") <NEW_LINE> cmd_file_data = GdbCommandFileGenerator(target, self.tmp_file).generate() <NEW_LINE> cmd_file = tempfile.NamedTemporaryFile(delete=False) <NEW_LINE> cmd_file.write(cmd_file_data.encode()) <NEW_LINE> cmd_file.close() <NEW_LINE> self._cleanup_tmp_file() <NEW_LINE> call = self.config['REMOTEEXPLOITABLEVERIFIER']['gdb_cmd'] + cmd_file.name <NEW_LINE> subprocess.call(call, shell=True) <NEW_LINE> try: <NEW_LINE> <INDENT> classification = pickle.load(open(self.tmp_file, "rb")) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> classification = None <NEW_LINE> print('[RemoteExploitableVerifier] verification failed (%s), call=%s' % (e, call)) <NEW_LINE> <DEDENT> self._cleanup_tmp_file() <NEW_LINE> os.unlink(cmd_file.name) <NEW_LINE> return classification <NEW_LINE> <DEDENT> def _verify_one_crash(self, crash_info): <NEW_LINE> <INDENT> print('[LocalExploitableVerifier] Got job with ID %s' % crash_info['crash_id']) <NEW_LINE> result = self._call_exploitable(crash_info['program'], crash_info['data']) <NEW_LINE> if result: <NEW_LINE> <INDENT> return {'crash_hash': "{}.{}".format(result.hash.major, result.hash.minor), 'classification': result.category, 'short_desc': str(result.tags[0]), 'crash_id': crash_info['crash_id'], 'verified': True} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return {'crash_id': crash_info['crash_id'], 'verified': False}
|
This is a remote exploitable verifier for Lucky CAT.
It is based on the triage.py script of exploitable
(https://github.com/jfoote/exploitable).
|
6259902ad53ae8145f91943a
|
class SelectiveProxyMiddleware(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.proxy = self.parse_proxy(settings.get('HTTP_PROXY'), 'http') <NEW_LINE> self.proxy_spiders = set(settings.getlist('PROXY_SPIDERS', [])) <NEW_LINE> <DEDENT> def parse_proxy(self, url, orig_type): <NEW_LINE> <INDENT> proxy_type, user, password, hostport = _parse_proxy(url) <NEW_LINE> proxy_url = urlunparse((proxy_type or orig_type, hostport, '', '', '', '')) <NEW_LINE> if user and password: <NEW_LINE> <INDENT> user_pass = '%s:%s' % (unquote(user), unquote(password)) <NEW_LINE> creds = base64.b64encode(user_pass).strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> creds = None <NEW_LINE> <DEDENT> return creds, proxy_url <NEW_LINE> <DEDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> if spider.name in self.proxy_spiders: <NEW_LINE> <INDENT> creds, proxy = self.proxy <NEW_LINE> request.meta['proxy'] = proxy <NEW_LINE> if creds: <NEW_LINE> <INDENT> request.headers['Proxy-Authorization'] = 'Basic ' + creds
|
A middleware to enable http proxy to selected spiders only.
Settings:
HTTP_PROXY -- proxy uri. e.g.: http://user:pass@proxy.host:port
PROXY_SPIDERS -- all requests from these spiders will be routed
through the proxy
|
6259902a26238365f5fadb29
|
class TokenAuth(object, metaclass=Singleton): <NEW_LINE> <INDENT> _handler = None <NEW_LINE> def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> cls._handler = get_token_auth() <NEW_LINE> return cls._handler
|
Singleton for accessing the Bearer Token
|
6259902a8e05c05ec3f6f647
|
class TestSmartServerBzrDirRequestGetBranches( tests.TestCaseWithMemoryTransport): <NEW_LINE> <INDENT> def test_simple(self): <NEW_LINE> <INDENT> backing = self.get_transport() <NEW_LINE> branch = self.make_branch('.') <NEW_LINE> request_class = smart_dir.SmartServerBzrDirRequestGetBranches <NEW_LINE> request = request_class(backing) <NEW_LINE> local_result = bencode.bencode( {b"": (b"branch", branch._format.network_name())}) <NEW_LINE> expected = smart_req.SuccessfulSmartServerResponse( (b"success", ), local_result) <NEW_LINE> self.assertEqual(expected, request.execute(b'')) <NEW_LINE> <DEDENT> def test_ref(self): <NEW_LINE> <INDENT> backing = self.get_transport() <NEW_LINE> dir = self.make_controldir('foo') <NEW_LINE> b = self.make_branch('bar') <NEW_LINE> dir.set_branch_reference(b) <NEW_LINE> request_class = smart_dir.SmartServerBzrDirRequestGetBranches <NEW_LINE> request = request_class(backing) <NEW_LINE> local_result = bencode.bencode( {b"": (b"ref", b'../bar/')}) <NEW_LINE> expected = smart_req.SuccessfulSmartServerResponse( (b"success", ), local_result) <NEW_LINE> self.assertEqual(expected, request.execute(b'foo')) <NEW_LINE> <DEDENT> def test_empty(self): <NEW_LINE> <INDENT> backing = self.get_transport() <NEW_LINE> self.make_controldir('.') <NEW_LINE> request_class = smart_dir.SmartServerBzrDirRequestGetBranches <NEW_LINE> request = request_class(backing) <NEW_LINE> local_result = bencode.bencode({}) <NEW_LINE> expected = smart_req.SuccessfulSmartServerResponse( (b'success',), local_result) <NEW_LINE> self.assertEqual(expected, request.execute(b''))
|
Tests for BzrDir.get_branches.
|
6259902a8c3a8732951f7530
|
class NewsListView(ListView): <NEW_LINE> <INDENT> model = News <NEW_LINE> template_name = "list.html" <NEW_LINE> context_object_name = "post_list" <NEW_LINE> paginate_by = 3
|
List view for model list.
|
6259902a1d351010ab8f4aef
|
class CaesarSubstitution(object): <NEW_LINE> <INDENT> def __init__(self, pt_data, key, to_path): <NEW_LINE> <INDENT> self.pt_data = pt_data <NEW_LINE> self.new_alphabet = [] <NEW_LINE> self.key = key <NEW_LINE> self.to_path = to_path <NEW_LINE> <DEDENT> def sub_mapping(self, key): <NEW_LINE> <INDENT> new_alphabet = [''] * 26 <NEW_LINE> alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] <NEW_LINE> for i in range(0, 26): <NEW_LINE> <INDENT> new_alphabet[i] = alphabet[(i + key) % 26] <NEW_LINE> <DEDENT> dict_sub_map = dict(zip(alphabet, new_alphabet)) <NEW_LINE> return dict_sub_map <NEW_LINE> <DEDENT> def encryption(self): <NEW_LINE> <INDENT> arbitary_mapping_sub(self.pt_data, self.sub_mapping(self.key), self.to_path) <NEW_LINE> <DEDENT> def analysis(self, to_path_csv): <NEW_LINE> <INDENT> enc = read_file_from(self.to_path) <NEW_LINE> cra = CryptAnalysis(enc) <NEW_LINE> cra.exec(1, to_path_csv) <NEW_LINE> <DEDENT> def execution(self, to_path_csv): <NEW_LINE> <INDENT> self.encryption() <NEW_LINE> self.analysis(to_path_csv)
|
Caesar substitution
|
6259902a1f5feb6acb163bc8
|
class Metric(collections.namedtuple('Metric', 'type labels')): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> @classmethod <NEW_LINE> def _from_dict(cls, info): <NEW_LINE> <INDENT> return cls( type=info['type'], labels=info.get('labels', {}), ) <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> return { 'type': self.type, 'labels': self.labels, }
|
A specific metric identified by specifying values for all labels.
The preferred way to construct a metric object is using the
:meth:`~google.cloud.monitoring.client.Client.metric` factory method
of the :class:`~google.cloud.monitoring.client.Client` class.
:type type: string
:param type: The metric type name.
:type labels: dict
:param labels: A mapping from label names to values for all labels
enumerated in the associated :class:`MetricDescriptor`.
|
6259902a30c21e258be997e4
|
class _BaseColumnFormat(str): <NEW_LINE> <INDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not other: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if isinstance(other, str): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> other = self.__class__(other) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.canonical == other.canonical <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.canonical) <NEW_LINE> <DEDENT> @lazyproperty <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> return np.dtype(self.recformat) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_column_format(cls, format): <NEW_LINE> <INDENT> return cls.from_recformat(format.recformat)
|
Base class for binary table column formats (just called _ColumnFormat)
and ASCII table column formats (_AsciiColumnFormat).
|
6259902a50485f2cf55dbf53
|
class VersionR: <NEW_LINE> <INDENT> allow_origin, rest_url = get_allowed.get_allowed() <NEW_LINE> def GET(self): <NEW_LINE> <INDENT> web.header("Content-Type","text/plain") <NEW_LINE> web.header('Access-Control-Allow-Origin', self.allow_origin) <NEW_LINE> version = {} <NEW_LINE> file_path = None <NEW_LINE> try: <NEW_LINE> <INDENT> import pkg_resources <NEW_LINE> file_path = pkg_resources.resource_filename('vcontrol', 'VERSION') <NEW_LINE> with open(file_path) as f: version = f.read().strip() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open('VERSION', 'r') as f: version['version'] = f.read().strip() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> with open('../VERSION', 'r') as f: version['version'] = f.read().strip() <NEW_LINE> <DEDENT> <DEDENT> if not file_path: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cmd = 'git -C ../vcontrol rev-parse HEAD' <NEW_LINE> commit_id = subprocess.check_output(cmd, shell=True) <NEW_LINE> cmd = 'git -C ../vcontrol diff-index --quiet HEAD --' <NEW_LINE> dirty = subprocess.call(cmd, shell=True) <NEW_LINE> if dirty != 0: <NEW_LINE> <INDENT> version['commit'] = commit_id.strip() + '-dirty' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> version['commit'] = commit_id.strip() <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> if 'HOSTNAME' in os.environ: <NEW_LINE> <INDENT> version['runtime'] = os.environ['HOSTNAME'] <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return json.dumps(version)
|
This endpoint is for returning the current running version of vcontrol
|
6259902a0a366e3fb87dd9c0
|
class matrixTile: <NEW_LINE> <INDENT> def __init__(self,dim): <NEW_LINE> <INDENT> self.tiles_matrix = configShisen.load('tiles-matrix') <NEW_LINE> self.tiles_list = {} <NEW_LINE> self.matrix_board= None <NEW_LINE> self.initTilesPos() <NEW_LINE> self.createMatrix(dim) <NEW_LINE> <DEDENT> def initTilesPos(self): <NEW_LINE> <INDENT> self.tiles_list = {} <NEW_LINE> row_count = 0 <NEW_LINE> for row in self.tiles_matrix: <NEW_LINE> <INDENT> col_count=0 <NEW_LINE> for tile in row: <NEW_LINE> <INDENT> self.tiles_list[tile] = (row_count,col_count) <NEW_LINE> col_count += 1 <NEW_LINE> <DEDENT> row_count += 1 <NEW_LINE> <DEDENT> <DEDENT> def getPosTile(self,tilename): <NEW_LINE> <INDENT> return self.tiles_list[tilename] <NEW_LINE> <DEDENT> def getTilePos(self,position): <NEW_LINE> <INDENT> return self.tiles_matrix[position[1]][position[0]] <NEW_LINE> <DEDENT> def createMatrix(self,dim,shuffle=True): <NEW_LINE> <INDENT> (dimx,dimy) = dim <NEW_LINE> matrix = [[ None for x in range(dimx)] for x in range(dimy)] <NEW_LINE> list_avail = [] <NEW_LINE> for posx in range(1,dimy+1): <NEW_LINE> <INDENT> for posy in range(1,dimx+1): <NEW_LINE> <INDENT> list_avail.append([posx - 1,posy - 1]) <NEW_LINE> <DEDENT> <DEDENT> if shuffle: <NEW_LINE> <INDENT> random.shuffle(list_avail) <NEW_LINE> <DEDENT> subgroup_list = self.getSubgroup(dim) <NEW_LINE> item=0 <NEW_LINE> for item_rand in list_avail: <NEW_LINE> <INDENT> x_t=item_rand[0] <NEW_LINE> y_t=item_rand[1] <NEW_LINE> matrix[x_t][y_t] = subgroup_list[item] <NEW_LINE> item += 1 <NEW_LINE> <DEDENT> self.matrix_board = matrix <NEW_LINE> <DEDENT> def getSubgroup(self,dim): <NEW_LINE> <INDENT> list_size = dim[0] * dim[1] <NEW_LINE> tiles = configShisen.load('tiles') <NEW_LINE> for item in tiles : <NEW_LINE> <INDENT> dimitem= item['dim'] <NEW_LINE> if dimitem[0] * dimitem[1] == list_size : <NEW_LINE> <INDENT> list_uniq = item['list'] <NEW_LINE> list = list_uniq * (list_size // len(list_uniq)) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ShisenException("The size '" + str(list_size) + "' of board is not configured in config file") <NEW_LINE> <DEDENT> return list
|
manage resolving algorithms to validate for example
if game could be won or if a movement is valid in rules game.
Changed by:
Manage the matrix of tiles used to fill the board
|
6259902a23e79379d538d4e4
|
class TestSpecificationSerializer(APITestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> maturity = self.create( Maturity, slug='WD', name={'en': 'Working Draft'}) <NEW_LINE> self.spec = self.create( Specification, maturity=maturity, slug="css3-animations", mdn_key='CSS3 Animations', name={'en': "CSS Animations"}, uri={'en': 'http://dev.w3.org/csswg/css-animations/'}) <NEW_LINE> self.s46 = self.create( Section, specification=self.spec, name={'en': "The 'animation-direction' property"}, subpath={'en': "#animation-direction"}) <NEW_LINE> self.s45 = self.create( Section, specification=self.spec, name={'en': "The 'animation-iteration-count' property"}, subpath={'en': "#animation-iteration-count"}) <NEW_LINE> self.url = reverse('specification-detail', kwargs={'pk': self.spec.pk}) <NEW_LINE> <DEDENT> def test_update_without_sections(self): <NEW_LINE> <INDENT> data = { 'specifications': { 'name': {'en': 'CSS3 Animations'} } } <NEW_LINE> self.update_via_json_api(self.url, data) <NEW_LINE> spec = Specification.objects.get(id=self.spec.id) <NEW_LINE> self.assertEqual({'en': 'CSS3 Animations'}, spec.name) <NEW_LINE> <DEDENT> def test_sections_change_order(self): <NEW_LINE> <INDENT> data = { 'specifications': { 'links': { 'sections': [str(self.s45.pk), str(self.s46.pk)] } } } <NEW_LINE> response = self.update_via_json_api(self.url, data) <NEW_LINE> expected_sections = [self.s45.pk, self.s46.pk] <NEW_LINE> actual_sections = response.data['sections'] <NEW_LINE> self.assertEqual(expected_sections, actual_sections) <NEW_LINE> <DEDENT> def test_sections_same_order(self): <NEW_LINE> <INDENT> data = { 'specifications': { 'links': { 'sections': [str(self.s46.pk), str(self.s45.pk)] } } } <NEW_LINE> response = self.update_via_json_api(self.url, data) <NEW_LINE> expected_sections = [self.s46.pk, self.s45.pk] <NEW_LINE> actual_sections = response.data['sections'] <NEW_LINE> self.assertEqual(expected_sections, actual_sections)
|
Test SpecificationSerializer through the view.
|
6259902ad10714528d69ee79
|
class ExtensionError(SphinxError): <NEW_LINE> <INDENT> def __init__(self, message: str, orig_exc: Exception = None, modname: str = None) -> None: <NEW_LINE> <INDENT> super().__init__(message) <NEW_LINE> self.message = message <NEW_LINE> self.orig_exc = orig_exc <NEW_LINE> self.modname = modname <NEW_LINE> <DEDENT> @property <NEW_LINE> def category(self) -> str: <NEW_LINE> <INDENT> if self.modname: <NEW_LINE> <INDENT> return 'Extension error (%s)' % self.modname <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Extension error' <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> if self.orig_exc: <NEW_LINE> <INDENT> return '%s(%r, %r)' % (self.__class__.__name__, self.message, self.orig_exc) <NEW_LINE> <DEDENT> return '%s(%r)' % (self.__class__.__name__, self.message) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> parent_str = super().__str__() <NEW_LINE> if self.orig_exc: <NEW_LINE> <INDENT> return '%s (exception: %s)' % (parent_str, self.orig_exc) <NEW_LINE> <DEDENT> return parent_str
|
Extension error.
|
6259902a8a349b6b43687213
|
class GenerateSpin1StatesTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_some_generated_spin1_states(self): <NEW_LINE> <INDENT> gs = generate_spin1_states(4, 2) <NEW_LINE> self.assertEqual(np.size(gs), 10) <NEW_LINE> self.assertEqual(gs[0], 5) <NEW_LINE> self.assertEqual(gs[1], 17) <NEW_LINE> self.assertEqual(gs[2], 20) <NEW_LINE> self.assertEqual(gs[3], 65) <NEW_LINE> self.assertEqual(gs[4], 68) <NEW_LINE> self.assertEqual(gs[6], 86) <NEW_LINE> self.assertEqual(gs[7], 89) <NEW_LINE> self.assertEqual(gs[9], 149) <NEW_LINE> gs = generate_spin1_states(4, 1) <NEW_LINE> self.assertEqual(np.size(gs), 16) <NEW_LINE> self.assertEqual(gs[0], 1) <NEW_LINE> self.assertEqual(gs[2], 16) <NEW_LINE> self.assertEqual(gs[4], 25) <NEW_LINE> self.assertEqual(gs[7], 70) <NEW_LINE> self.assertEqual(gs[9], 82) <NEW_LINE> self.assertEqual(gs[15], 148)
|
Tests for the generate spin 1 states function.
|
6259902a63f4b57ef008655f
|
class FtdiEepromError(FtdiError): <NEW_LINE> <INDENT> pass
|
FTDI EEPROM error.
|
6259902a15baa72349462f73
|
@register_resource <NEW_LINE> class v1_BuildConfigList(Resource): <NEW_LINE> <INDENT> __kind__ = 'v1.BuildConfigList' <NEW_LINE> __fields__ = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata', } <NEW_LINE> __types__ = { 'items': 'v1.BuildConfig', 'metadata': 'unversioned.ListMeta', } <NEW_LINE> __required__ = set([ 'items', ]) <NEW_LINE> api_version = None <NEW_LINE> items = None <NEW_LINE> kind = None <NEW_LINE> metadata = None <NEW_LINE> def __init__(self, *, items, **_kwargs_): <NEW_LINE> <INDENT> self.kind = 'BuildConfigList' <NEW_LINE> self.api_version = 'v1' <NEW_LINE> self.items = items <NEW_LINE> super().__init__(**_kwargs_)
|
BuildConfigList is a collection of BuildConfigs.
|
6259902a1d351010ab8f4af2
|
class OpenThread(Threader): <NEW_LINE> <INDENT> def __exit__(self,type,value,traceback): <NEW_LINE> <INDENT> pass
|
Same as above, but lets a thread keep running
after exiting the `with` statement.
|
6259902a26238365f5fadb2d
|
class ShardedDB(object): <NEW_LINE> <INDENT> def __init__(self, filebase, num_shards, create_if_missing): <NEW_LINE> <INDENT> self.filebase = filebase <NEW_LINE> self.num_shards = num_shards <NEW_LINE> self._shards = [] <NEW_LINE> os.system('mkdir -p "%s"' % filebase) <NEW_LINE> for i in range(num_shards): <NEW_LINE> <INDENT> shard_file = '%s/shard-%05d-of-%05d.db' % (filebase, i, num_shards) <NEW_LINE> self._shards.append(leveldb.LevelDB(shard_file, create_if_missing=create_if_missing)) <NEW_LINE> <DEDENT> logging.info('Opened DB with %s files', num_shards) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create(filebase, num_shards): <NEW_LINE> <INDENT> return ShardedDB(filebase, num_shards, True) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def open(filebase): <NEW_LINE> <INDENT> files = glob.glob('%s/*.db' % filebase) <NEW_LINE> return ShardedDB(filebase, len(files), False) <NEW_LINE> <DEDENT> def _shard_for(self, key): <NEW_LINE> <INDENT> return self._shards[hash(key) % self.num_shards] <NEW_LINE> <DEDENT> def put(self, key, value): <NEW_LINE> <INDENT> self._shard_for(key).Put(key, cPickle.dumps(value, -1)) <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> return cPickle.loads(self._shard_for(key).Get(key)) <NEW_LINE> <DEDENT> def range_iter(self, start_key, end_key): <NEW_LINE> <INDENT> iters = [db.RangeIter(start_key, end_key) for db in self._shards] <NEW_LINE> for i in iters: <NEW_LINE> <INDENT> for key, value in i: <NEW_LINE> <INDENT> yield key, cPickle.loads(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for shard in self._shards: <NEW_LINE> <INDENT> for key, value in shard.RangeIter(): <NEW_LINE> <INDENT> yield key, cPickle.loads(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> return dict(self.range_iter(None, None))
|
Manages a number of leveldb "shards" (partitions).
LevelDB does not support concurrent writers, so we create a separate output
shard for each reducer. `ShardedDB` provides a unified interface to
multiple shards.
|
6259902abe8e80087fbc0055
|
class ConfigurableWrapper(object): <NEW_LINE> <INDENT> def __init__(self, cls): <NEW_LINE> <INDENT> self._cls = cls <NEW_LINE> <DEDENT> def setup(self, *args, **kwargs): <NEW_LINE> <INDENT> instance = self._cls(*args, **kwargs) <NEW_LINE> self.__class__ = instance.__class__ <NEW_LINE> self.__dict__ = instance.__dict__
|
This is a little trick I just made up.
Allow a reference to the object you want to create to be created later all while referencing the object before hand
This is mostly useful when creating web applications that need access to something like the db object, but the db object isn't configured until later in the application startup procedure.
Basicly this object holds onto the reference to the cls you want to create and replaces itself with a class instance of the cls you specified once you have called setup
|
6259902a8a349b6b43687215
|
class SelectWidget(BaseSelectWidget): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def render_option(cls, value, label, mixed): <NEW_LINE> <INDENT> if isinstance(label, (list, tuple)): <NEW_LINE> <INDENT> children = [] <NEW_LINE> for item_value, item_label in label: <NEW_LINE> <INDENT> item_html = cls.render_option(item_value, item_label, mixed) <NEW_LINE> children.append(item_html) <NEW_LINE> <DEDENT> html = '<optgroup label="%s">%s</optgroup>' <NEW_LINE> data = (escape(value), '\n'.join(children)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> coerce_func, data = mixed <NEW_LINE> selected = coerce_func(value) == data <NEW_LINE> options = {'value': value} <NEW_LINE> if selected: <NEW_LINE> <INDENT> options['selected'] = 'selected' <NEW_LINE> <DEDENT> html = '<option %s>%s</option>' <NEW_LINE> data = (html_params(**options), escape(label)) <NEW_LINE> <DEDENT> return HTMLString(html % data)
|
Add support of choices with 'optgroup' to the 'Select' widget.
|
6259902a796e427e5384f759
|
class ReportGenerationError(object): <NEW_LINE> <INDENT> pass
|
The coverage report cannot be generated.
|
6259902a5166f23b2e2443b2
|
class Mailbox(Drawable): <NEW_LINE> <INDENT> def __init__(self, flagUp=False, doorOpen=False, color='white'): <NEW_LINE> <INDENT> Drawable.__init__(self) <NEW_LINE> self._post = Rectangle(16, 80, Point(0,-40)) <NEW_LINE> self._post.setFillColor('brown') <NEW_LINE> self._box = Rectangle(50, 30, Point(-3,-95)) <NEW_LINE> self._box.setFillColor(color) <NEW_LINE> self._door = Rectangle(6, 30, Point(25,-95)) <NEW_LINE> self._door.setFillColor(color) <NEW_LINE> self._door.adjustReference(-3, 15) <NEW_LINE> self._doorOpen = doorOpen <NEW_LINE> if doorOpen: <NEW_LINE> <INDENT> self._door.rotate(90) <NEW_LINE> <DEDENT> self._flag = Polygon(Point(15,-100), Point(15,-106), Point(-15,-106), Point(-15,-90), Point(-5,-90), Point(-5,-100)) <NEW_LINE> self._flag.setFillColor('red') <NEW_LINE> self._flag.adjustReference(-3,-3) <NEW_LINE> self._flagUp = flagUp <NEW_LINE> if flagUp: <NEW_LINE> <INDENT> self._flag.rotate(90) <NEW_LINE> <DEDENT> <DEDENT> def _draw(self): <NEW_LINE> <INDENT> self._beginDraw() <NEW_LINE> self._post._draw() <NEW_LINE> self._box._draw() <NEW_LINE> self._door._draw() <NEW_LINE> self._flag._draw() <NEW_LINE> self._completeDraw() <NEW_LINE> <DEDENT> def setColor(self, color): <NEW_LINE> <INDENT> self._box.setFillColor(color) <NEW_LINE> self._door.setFillColor(color) <NEW_LINE> <DEDENT> def doorIsOpen(self): <NEW_LINE> <INDENT> return self._doorOpen <NEW_LINE> <DEDENT> def openDoor(self): <NEW_LINE> <INDENT> if not self._doorOpen: <NEW_LINE> <INDENT> for i in range(90): <NEW_LINE> <INDENT> self._door.rotate(1) <NEW_LINE> <DEDENT> self._doorOpen = True <NEW_LINE> <DEDENT> <DEDENT> def closeDoor(self): <NEW_LINE> <INDENT> if self._doorOpen: <NEW_LINE> <INDENT> for i in range(90): <NEW_LINE> <INDENT> self._door.rotate(-1) <NEW_LINE> <DEDENT> self._doorOpen = False <NEW_LINE> <DEDENT> <DEDENT> def flagIsUp(self): <NEW_LINE> <INDENT> return self._flagUp <NEW_LINE> <DEDENT> def toggleFlag(self): <NEW_LINE> <INDENT> if self._flagUp: <NEW_LINE> <INDENT> increment = -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> increment = 1 <NEW_LINE> <DEDENT> for i in range(90): <NEW_LINE> <INDENT> self._flag.rotate(increment) <NEW_LINE> <DEDENT> self._flagUp = not self._flagUp
|
A graphical primitive representing a Mailbox.
The user can choose the color, open and close the door, and raise and lower the flag.
|
6259902a8a43f66fc4bf3160
|
class UserBodyweightTestCase(WgerTestCase): <NEW_LINE> <INDENT> def test_bodyweight_new(self): <NEW_LINE> <INDENT> user = User.objects.get(pk=2) <NEW_LINE> count_before = WeightEntry.objects.filter(user=user).count() <NEW_LINE> entry = user.userprofile.user_bodyweight(80) <NEW_LINE> count_after = WeightEntry.objects.filter(user=user).count() <NEW_LINE> self.assertEqual(count_before, count_after - 1) <NEW_LINE> self.assertEqual(entry.date, datetime.date.today()) <NEW_LINE> <DEDENT> def test_bodyweight_new_2(self): <NEW_LINE> <INDENT> user = User.objects.get(pk=2) <NEW_LINE> count_before = WeightEntry.objects.filter(user=user).count() <NEW_LINE> last_entry = WeightEntry.objects.filter(user=user).latest() <NEW_LINE> last_entry.date = datetime.date.today() - datetime.timedelta(weeks=1) <NEW_LINE> last_entry.save() <NEW_LINE> entry = user.userprofile.user_bodyweight(80) <NEW_LINE> count_after = WeightEntry.objects.filter(user=user).count() <NEW_LINE> self.assertEqual(count_before, count_after - 1) <NEW_LINE> self.assertEqual(entry.date, datetime.date.today()) <NEW_LINE> <DEDENT> def test_bodyweight_no_entries(self): <NEW_LINE> <INDENT> user = User.objects.get(pk=2) <NEW_LINE> WeightEntry.objects.filter(user=user).delete() <NEW_LINE> count_before = WeightEntry.objects.filter(user=user).count() <NEW_LINE> entry = user.userprofile.user_bodyweight(80) <NEW_LINE> count_after = WeightEntry.objects.filter(user=user).count() <NEW_LINE> self.assertEqual(count_before, count_after - 1) <NEW_LINE> self.assertEqual(entry.date, datetime.date.today()) <NEW_LINE> <DEDENT> def test_bodyweight_edit(self): <NEW_LINE> <INDENT> user = User.objects.get(pk=2) <NEW_LINE> last_entry = WeightEntry.objects.filter(user=user).latest() <NEW_LINE> last_entry.date = datetime.date.today() - datetime.timedelta(days=3) <NEW_LINE> last_entry.save() <NEW_LINE> count_before = WeightEntry.objects.filter(user=user).count() <NEW_LINE> entry = user.userprofile.user_bodyweight(100) <NEW_LINE> count_after = WeightEntry.objects.filter(user=user).count() <NEW_LINE> self.assertEqual(count_before, count_after) <NEW_LINE> self.assertEqual(entry.pk, last_entry.pk) <NEW_LINE> self.assertEqual(entry.date, last_entry.date) <NEW_LINE> self.assertEqual(entry.weight, 100) <NEW_LINE> <DEDENT> def test_bodyweight_edit_2(self): <NEW_LINE> <INDENT> user = User.objects.get(pk=2) <NEW_LINE> last_entry = WeightEntry.objects.filter(user=user).latest() <NEW_LINE> last_entry.date = datetime.date.today() <NEW_LINE> last_entry.save() <NEW_LINE> count_before = WeightEntry.objects.filter(user=user).count() <NEW_LINE> entry = user.userprofile.user_bodyweight(100) <NEW_LINE> count_after = WeightEntry.objects.filter(user=user).count() <NEW_LINE> self.assertEqual(count_before, count_after) <NEW_LINE> self.assertEqual(entry.pk, last_entry.pk) <NEW_LINE> self.assertEqual(entry.date, last_entry.date) <NEW_LINE> self.assertEqual(entry.weight, 100)
|
Tests the body weight generation/update function
|
6259902a3eb6a72ae038b642
|
class stack_node: <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.key = data <NEW_LINE> self.next = None
|
create the node for stack
|
6259902a8a349b6b43687217
|
class Shiftexp(object): <NEW_LINE> <INDENT> def __init__(self, parameter): <NEW_LINE> <INDENT> assert 0 < parameter < math.inf <NEW_LINE> self.parameter = parameter <NEW_LINE> return <NEW_LINE> <DEDENT> def pdf(self, value): <NEW_LINE> <INDENT> assert 0 <= value <= math.inf <NEW_LINE> if value < self.parameter: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 1 / self.parameter * math.exp(-(value / self.parameter - 1)) <NEW_LINE> <DEDENT> <DEDENT> def cdf(self, value): <NEW_LINE> <INDENT> assert 0 <= value <= math.inf <NEW_LINE> if value < self.parameter: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 1 - math.exp(-(value / self.parameter - 1)) <NEW_LINE> <DEDENT> <DEDENT> def icdf(self, value): <NEW_LINE> <INDENT> assert 0 <= value < 1, 'Value must be <= 0 and < 1.' <NEW_LINE> return self.parameter * (1 - math.log(1 - value)) <NEW_LINE> <DEDENT> def mean(self): <NEW_LINE> <INDENT> return self.parameter
|
Shifted exponential distributed random variable.
|
6259902a1f5feb6acb163bce
|
class ajaxSetRemarks(BrowserView): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> plone.protect.CheckAuthenticator(self.request) <NEW_LINE> field = self.context.Schema()["Remarks"] <NEW_LINE> value = self.request['value'].strip() + "\n\n" <NEW_LINE> existing = self.context.getRemarks(mimetype='text/x-web-intelligent').strip() <NEW_LINE> date = self.ulocalized_time(DateTime, long_format=True) <NEW_LINE> user = getSecurityManager().getUser() <NEW_LINE> divider = "=== %s (%s)\n" % (date, user) <NEW_LINE> remarks = convertWebIntelligentPlainTextToHtml(divider) + convertWebIntelligentPlainTextToHtml(value) + convertWebIntelligentPlainTextToHtml(existing) <NEW_LINE> self.context.setRemarks(divider + value + existing, mimetype='text/x-web-intelligent') <NEW_LINE> return remarks.strip()
|
Modify Remarks field and return new rendered field value
|
6259902aa8ecb033258721fc
|
class TableFlavors(_ui.Table): <NEW_LINE> <INDENT> columns = {'name': 2} <NEW_LINE> row_cls = RowFlavor
|
Flavors table.
|
6259902a6fece00bbaccc98d
|
class Monitor(object): <NEW_LINE> <INDENT> def __init__(self, log_file_name): <NEW_LINE> <INDENT> self.log_file = open(log_file_name, 'w') <NEW_LINE> self.pop_name = "" <NEW_LINE> <DEDENT> def write(self, tag, msg): <NEW_LINE> <INDENT> self.log_file.write("%s\t%s\t%s\n" % (self.pop_name, tag, msg)) <NEW_LINE> self.log_file.flush() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.log_file.close()
|
A class to record events in the course of evolution.
|
6259902bd6c5a102081e3105
|
class TestParse(unittest.TestCase): <NEW_LINE> <INDENT> def testParse(self): <NEW_LINE> <INDENT> adag = parse(DAX33TEST_DAX) <NEW_LINE> <DEDENT> def testParseString(self): <NEW_LINE> <INDENT> txt = open(DAX33TEST_DAX).read() <NEW_LINE> adag = parseString(txt)
|
This doesn't really do a thorough job of testing the parser
|
6259902bbf627c535bcb2496
|
class ModuleTest(TestCase): <NEW_LINE> <INDENT> fixtures = ['users'] <NEW_LINE> def test_update_module_using_save(self): <NEW_LINE> <INDENT> author = User.objects.get(username='john') <NEW_LINE> mod = Module.objects.create( filename='test_filename', author=author ) <NEW_LINE> self.assertRaises(UpdateDeniedException, mod.save) <NEW_LINE> <DEDENT> def test_create_module_with_utf_content(self): <NEW_LINE> <INDENT> author = User.objects.get(username='john') <NEW_LINE> Module.objects.create( filename='test_filename', author=author, code=u'ą') <NEW_LINE> eq_(Module.objects.get(author=author).code, u'ą') <NEW_LINE> <DEDENT> def test_illegal_filename(self): <NEW_LINE> <INDENT> mod = Module(filename='.../...///foo.js', author=User.objects.get(username='john')) <NEW_LINE> self.assertRaises(IllegalFilenameException, mod.save)
|
Testing module methods
|
6259902b50485f2cf55dbf5a
|
class Ring(Graph): <NEW_LINE> <INDENT> def __init__(self, N=64, k=1, **kwargs): <NEW_LINE> <INDENT> self.k = k <NEW_LINE> if 2*k > N: <NEW_LINE> <INDENT> raise ValueError('Too many neighbors requested.') <NEW_LINE> <DEDENT> if 2*k == N: <NEW_LINE> <INDENT> num_edges = N * (k - 1) + k <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> num_edges = N * k <NEW_LINE> <DEDENT> i_inds = np.zeros((2 * num_edges)) <NEW_LINE> j_inds = np.zeros((2 * num_edges)) <NEW_LINE> tmpN = np.arange(N, dtype=int) <NEW_LINE> for i in range(min(k, (N - 1) // 2)): <NEW_LINE> <INDENT> i_inds[2*i * N + tmpN] = tmpN <NEW_LINE> j_inds[2*i * N + tmpN] = np.remainder(tmpN + i + 1, N) <NEW_LINE> i_inds[(2*i + 1)*N + tmpN] = np.remainder(tmpN + i + 1, N) <NEW_LINE> j_inds[(2*i + 1)*N + tmpN] = tmpN <NEW_LINE> <DEDENT> if 2*k == N: <NEW_LINE> <INDENT> i_inds[2*N*(k - 1) + tmpN] = tmpN <NEW_LINE> i_inds[2*N*(k - 1) + tmpN] = np.remainder(tmpN + k + 1, N) <NEW_LINE> <DEDENT> W = sparse.csc_matrix((np.ones((2*num_edges)), (i_inds, j_inds)), shape=(N, N)) <NEW_LINE> plotting = {'limits': np.array([-1, 1, -1, 1])} <NEW_LINE> super(Ring, self).__init__(W=W, plotting=plotting, **kwargs) <NEW_LINE> self.set_coordinates('ring2D') <NEW_LINE> <DEDENT> def _get_extra_repr(self): <NEW_LINE> <INDENT> return dict(k=self.k)
|
K-regular ring graph.
Parameters
----------
N : int
Number of vertices.
k : int
Number of neighbors in each direction.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> G = graphs.Ring(N=10)
>>> fig, axes = plt.subplots(1, 2)
>>> _ = axes[0].spy(G.W)
>>> G.plot(ax=axes[1])
|
6259902b1d351010ab8f4af6
|
class itkLog10ImageFilterIF3IF3_Superclass(itkInPlaceImageFilterAPython.itkInPlaceImageFilterIF3IF3): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkLog10ImageFilterPython.itkLog10ImageFilterIF3IF3_Superclass___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def GetFunctor(self, *args): <NEW_LINE> <INDENT> return _itkLog10ImageFilterPython.itkLog10ImageFilterIF3IF3_Superclass_GetFunctor(self, *args) <NEW_LINE> <DEDENT> def SetFunctor(self, *args): <NEW_LINE> <INDENT> return _itkLog10ImageFilterPython.itkLog10ImageFilterIF3IF3_Superclass_SetFunctor(self, *args) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkLog10ImageFilterPython.delete_itkLog10ImageFilterIF3IF3_Superclass <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkLog10ImageFilterPython.itkLog10ImageFilterIF3IF3_Superclass_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkLog10ImageFilterPython.itkLog10ImageFilterIF3IF3_Superclass_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkLog10ImageFilterIF3IF3_Superclass.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
|
Proxy of C++ itkLog10ImageFilterIF3IF3_Superclass class
|
6259902be76e3b2f99fd99ec
|
class Control: <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> if len(args) > 0: <NEW_LINE> <INDENT> raise DeprecationWarning( 'p0 and epsilon now live in config') <NEW_LINE> <DEDENT> self.gold_getter = GoldGetter() <NEW_LINE> self.swap = None <NEW_LINE> <DEDENT> def run(self, amount=None): <NEW_LINE> <INDENT> if amount is None: <NEW_LINE> <INDENT> amount = DB().classifications.get_stats() <NEW_LINE> amount = amount['first_classifications'] <NEW_LINE> <DEDENT> self.init_swap() <NEW_LINE> cursor = self.get_classifications() <NEW_LINE> logger.info('Start: SWAP Processing %d classifications', amount) <NEW_LINE> count = 0 <NEW_LINE> with progressbar.ProgressBar(max_value=amount) as bar: <NEW_LINE> <INDENT> bar.update(count) <NEW_LINE> for cl in cursor: <NEW_LINE> <INDENT> cl = Classification.generate(cl) <NEW_LINE> self._delegate(cl) <NEW_LINE> bar.update(count) <NEW_LINE> count += 1 <NEW_LINE> if config.control.debug and count > config.control.amount: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if config.back_update: <NEW_LINE> <INDENT> logger.info('back_update active: processing changes') <NEW_LINE> self.swap.process_changes() <NEW_LINE> <DEDENT> logger.info('done') <NEW_LINE> <DEDENT> def _delegate(self, cl): <NEW_LINE> <INDENT> self.swap.classify(cl) <NEW_LINE> <DEDENT> def init_swap(self): <NEW_LINE> <INDENT> logger.debug('Initializing SWAP') <NEW_LINE> if self.swap is None: <NEW_LINE> <INDENT> swap = SWAP() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> swap = self.swap <NEW_LINE> <DEDENT> golds = self.get_gold_labels() <NEW_LINE> swap.set_gold_labels(golds) <NEW_LINE> self.swap = swap <NEW_LINE> return swap <NEW_LINE> <DEDENT> def get_gold_labels(self): <NEW_LINE> <INDENT> return self.gold_getter.golds <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_classifications(): <NEW_LINE> <INDENT> return DB().classifications.getClassifications() <NEW_LINE> <DEDENT> def getSWAP(self): <NEW_LINE> <INDENT> return self.swap <NEW_LINE> <DEDENT> def setSWAP(self, swap): <NEW_LINE> <INDENT> self.swap = swap <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.swap = None <NEW_LINE> self.gold_getter.reset()
|
Gets classifications from database and feeds them to SWAP
|
6259902b8c3a8732951f7537
|
class CalendarManager(models.Manager): <NEW_LINE> <INDENT> def get_calendar_for_object(self, obj, distinction=None): <NEW_LINE> <INDENT> calendar_list = self.get_calendars_for_object(obj, distinction) <NEW_LINE> if len(calendar_list) == 0: <NEW_LINE> <INDENT> raise Calendar.DoesNotExist("Calendar does not exist.") <NEW_LINE> <DEDENT> elif len(calendar_list) > 1: <NEW_LINE> <INDENT> raise AssertionError("More than one calendars were found.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return calendar_list[0] <NEW_LINE> <DEDENT> <DEDENT> def get_or_create_calendar_for_object(self, obj, distinction=None, name=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.get_calendar_for_object(obj, distinction) <NEW_LINE> <DEDENT> except Calendar.DoesNotExist: <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> calendar = Calendar(name=unicode(obj)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> calendar = Calendar(name=name) <NEW_LINE> <DEDENT> calendar.slug = slugify(calendar.name) <NEW_LINE> calendar.save() <NEW_LINE> calendar.create_relation(obj, distinction) <NEW_LINE> return calendar <NEW_LINE> <DEDENT> <DEDENT> def get_calendars_for_object(self, obj, distinction=None): <NEW_LINE> <INDENT> ct = ContentType.objects.get_for_model(type(obj)) <NEW_LINE> if distinction: <NEW_LINE> <INDENT> dist_q = Q(calendarrelation__distinction=distinction) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dist_q = Q() <NEW_LINE> <DEDENT> return self.filter(dist_q, Q(calendarrelation__object_id=obj.id, calendarrelation__content_type=ct))
|
>>> user1 = User(username='tony')
>>> user1.save()
|
6259902b30c21e258be997ec
|
class Movies(object): <NEW_LINE> <INDENT> def __init__(self, name, rate, cate, loca, info_link, cover_link): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.rate = rate <NEW_LINE> self.cate = cate <NEW_LINE> self.loca = loca <NEW_LINE> self.info_link = info_link <NEW_LINE> self.cover_link = cover_link <NEW_LINE> <DEDENT> def OutPut(self): <NEW_LINE> <INDENT> out = [self.name, self.rate, self.cate, self.rate, self.info_link, self.cover_link] <NEW_LINE> return out
|
create the instance of movies
|
6259902b6e29344779b0162f
|
class equalizeContrast(CVwrapped): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(equalizeContrast, self).__init__(cv2.equalizeHist)
|
Automatic contrast correction.
Note: Only works for grayscale images!
|
6259902b50485f2cf55dbf5b
|
class Light(DefaultInstance): <NEW_LINE> <INDENT> def __init__(self, lightpos=(10, -10, 20), lightcol=(1.0, 1.0, 1.0), lightamb=(0.1, 0.1, 0.2), is_point=False): <NEW_LINE> <INDENT> super(Light, self).__init__() <NEW_LINE> self.lightpos = lightpos <NEW_LINE> self.lightcol = lightcol <NEW_LINE> self.lightamb = lightamb <NEW_LINE> self.is_point = 1.0 if is_point else 0.0 <NEW_LINE> <DEDENT> def position(self, lightpos): <NEW_LINE> <INDENT> self.lightpos = lightpos <NEW_LINE> <DEDENT> def color(self, lightcol): <NEW_LINE> <INDENT> self.lightcol = lightcol <NEW_LINE> <DEDENT> def ambient(self, lightamb): <NEW_LINE> <INDENT> self.lightamb = lightamb <NEW_LINE> <DEDENT> def make_point(self): <NEW_LINE> <INDENT> self.is_point = 1.0 <NEW_LINE> <DEDENT> def make_directional(self): <NEW_LINE> <INDENT> self.is_point = 0.0 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _default_instance(): <NEW_LINE> <INDENT> return Light()
|
Holds information about lighting to be used in shaders
|
6259902bd6c5a102081e3107
|
class ContainerTraverser(Traverser): <NEW_LINE> <INDENT> component.adapts(IContainer, IHTTPRequest) <NEW_LINE> def traverse(self, name): <NEW_LINE> <INDENT> traverse = getattr(self.context, 'traverse', None) <NEW_LINE> if traverse: <NEW_LINE> <INDENT> result = traverse(name) <NEW_LINE> if result is not None: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> <DEDENT> return self.context.get(name)
|
Base class for container traversers in Grok applications.
A container traverser is like a normal `grok.Traverser` but, instead
of supplying its own ``traverse()`` method, Grok will either call
the ``traverse()`` method on the context itself, if any, else call
``get()`` on the container (a getitem-style lookup) in order to
resolve the next name in the URL.
|
6259902b8c3a8732951f7539
|
class Nauru(DstTzInfo): <NEW_LINE> <INDENT> _zone = 'Pacific/Nauru' <NEW_LINE> _utc_transition_times = [ d(1,1,1,0,0,0), d(1921,1,14,12,52,20), d(1942,3,14,12,30,0), d(1944,8,14,15,0,0), d(1979,4,30,12,30,0), ] <NEW_LINE> _transition_info = [ i(40080,0,'LMT'), i(41400,0,'NRT'), i(32400,0,'JST'), i(41400,0,'NRT'), i(43200,0,'NRT'), ]
|
Pacific/Nauru timezone definition. See datetime.tzinfo for details
|
6259902b6fece00bbaccc990
|
class ZipPkgReader(object): <NEW_LINE> <INDENT> _CONTENT_TYPES_MEMBERNAME = '[Content_Types].xml' <NEW_LINE> def __init__(self, pkg_file): <NEW_LINE> <INDENT> super(ZipPkgReader, self).__init__() <NEW_LINE> self._zipf = ZipFile(pkg_file, 'r') <NEW_LINE> <DEDENT> def blob_for(self, pack_uri): <NEW_LINE> <INDENT> return self._zipf.read(pack_uri.membername) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._zipf.close() <NEW_LINE> <DEDENT> @property <NEW_LINE> def content_types_xml(self): <NEW_LINE> <INDENT> return self._zipf.read(self._CONTENT_TYPES_MEMBERNAME) <NEW_LINE> <DEDENT> def rels_xml_for(self, source_uri): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rels_xml = self._zipf.read(source_uri.rels_uri.membername) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> rels_xml = None <NEW_LINE> <DEDENT> return rels_xml
|
Implements |PhysPkgReader| interface for a zip file OPC package.
|
6259902b30c21e258be997ee
|
class RobotArm(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pfrp = PiFaceRelayPlus(RELAY) <NEW_LINE> <DEDENT> def set_direction(self, direction): <NEW_LINE> <INDENT> self.pfrp.relays[DIRECTION_INDEX].value = direction <NEW_LINE> <DEDENT> def set_relay_for_period(self, index, delay, direction): <NEW_LINE> <INDENT> self.set_direction(direction) <NEW_LINE> self.pfrp.relays[index].turn_on() <NEW_LINE> time.sleep(delay) <NEW_LINE> self.pfrp.relays[index].turn_off() <NEW_LINE> <DEDENT> def move_base(self, delay, direction=0): <NEW_LINE> <INDENT> self.set_relay_for_period(BASE_INDEX, delay, direction) <NEW_LINE> <DEDENT> def move_shoulder(self, delay, direction=0): <NEW_LINE> <INDENT> self.set_relay_for_period(SHOULDER_INDEX, delay, direction) <NEW_LINE> <DEDENT> def move_elbow(self, delay, direction=0): <NEW_LINE> <INDENT> self.set_relay_for_period(ELBOW_INDEX, delay, direction) <NEW_LINE> <DEDENT> def move_wrist(self, delay, direction=0): <NEW_LINE> <INDENT> self.set_relay_for_period(WRIST_INDEX, delay, direction) <NEW_LINE> <DEDENT> def move_grip(self, delay, direction=0): <NEW_LINE> <INDENT> self.set_relay_for_period(GRIP_INDEX, delay, direction) <NEW_LINE> <DEDENT> def set_light(self, state): <NEW_LINE> <INDENT> self.set_direction(0) <NEW_LINE> self.pfrp.relays[LIGHT_INDEX].value = state
|
Robot Arm controlled by PiFace Relay Plus.
|
6259902b1f5feb6acb163bd2
|
class FunctionFieldMappedValuation_base(FunctionFieldValuation_base, MappedValuation_base): <NEW_LINE> <INDENT> def __init__(self, parent, base_valuation, to_base_valuation_domain, from_base_valuation_domain): <NEW_LINE> <INDENT> FunctionFieldValuation_base.__init__(self, parent) <NEW_LINE> MappedValuation_base.__init__(self, parent, base_valuation) <NEW_LINE> self._to_base = to_base_valuation_domain <NEW_LINE> self._from_base = from_base_valuation_domain <NEW_LINE> <DEDENT> def _to_base_domain(self, f): <NEW_LINE> <INDENT> return self._to_base(f) <NEW_LINE> <DEDENT> def _from_base_domain(self, f): <NEW_LINE> <INDENT> return self._from_base(f) <NEW_LINE> <DEDENT> def scale(self, scalar): <NEW_LINE> <INDENT> from sage.rings.rational_field import QQ <NEW_LINE> if scalar in QQ and scalar > 0 and scalar != 1: <NEW_LINE> <INDENT> return self.domain().valuation((self._base_valuation.scale(scalar), self._to_base, self._from_base)) <NEW_LINE> <DEDENT> return super(FunctionFieldMappedValuation_base, self).scale(scalar) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> to_base = repr(self._to_base) <NEW_LINE> if hasattr(self._to_base, '_repr_defn'): <NEW_LINE> <INDENT> to_base = self._to_base._repr_defn().replace('\n', ', ') <NEW_LINE> <DEDENT> return "%r (in %r after %s)" % (self._base_valuation, self._base_valuation.domain(), to_base) <NEW_LINE> <DEDENT> def is_discrete_valuation(self): <NEW_LINE> <INDENT> return self._base_valuation.is_discrete_valuation()
|
A valuation on a function field which relies on a ``base_valuation`` on an
isomorphic function field.
EXAMPLES::
sage: K.<x> = FunctionField(GF(2))
sage: v = K.valuation(1/x); v
Valuation at the infinite place
|
6259902b63f4b57ef0086563
|
class Source(Node, Publisher, threading.Thread, Stoppable): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> threading.Thread.__init__(self, name=name) <NEW_LINE> Node.__init__(self, name) <NEW_LINE> Publisher.__init__(self) <NEW_LINE> Stoppable.__init__(self) <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_next_item(self): <NEW_LINE> <INDENT> time.sleep(1.0) <NEW_LINE> return True <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.initialize() <NEW_LINE> while not self.stopped.is_set(): <NEW_LINE> <INDENT> if not self.get_next_item(): <NEW_LINE> <INDENT> break
|
Represents a node that is a source of data in the graph.
The node is only publishing data and has its own thread within which the
notification of subscribers should take place.
|
6259902bec188e330fdf9875
|
class GetConnection(): <NEW_LINE> <INDENT> def obtain_connection(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if os.environ.get('DATABASE_URL'): <NEW_LINE> <INDENT> conn = psycopg2.connect(os.environ.get('DATABASE_URL')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> conn = psycopg2.connect(os.environ.get('ECOM_DB')) <NEW_LINE> <DEDENT> cursor = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor) <NEW_LINE> return conn, cursor <NEW_LINE> <DEDENT> except (Exception, psycopg2.Error) as error: <NEW_LINE> <INDENT> print ("error while connecting to postgres", error) <NEW_LINE> <DEDENT> <DEDENT> def close_connection(self, conn, cursor): <NEW_LINE> <INDENT> conn.close() <NEW_LINE> cursor.close()
|
Connect to postgres DB
|
6259902b507cdc57c63a5d89
|
class OrderedResponseElasticSearch(ElasticSearch): <NEW_LINE> <INDENT> def _decode_response(self, response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> json_response = json.loads(response.text, object_pairs_hook=OrderedDict) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise InvalidJsonResponseError(response) <NEW_LINE> <DEDENT> return json_response <NEW_LINE> <DEDENT> def search(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(OrderedResponseElasticSearch, self) .search(*args, **kwargs) <NEW_LINE> <DEDENT> except TypeError as e: <NEW_LINE> <INDENT> if 'body' in kwargs: <NEW_LINE> <INDENT> kwargs['query'] = kwargs.pop('body') <NEW_LINE> return super(OrderedResponseElasticSearch, self) .search(*args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def count(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(OrderedResponseElasticSearch, self) .count(*args, **kwargs) <NEW_LINE> <DEDENT> except TypeError as e: <NEW_LINE> <INDENT> if 'body' in kwargs: <NEW_LINE> <INDENT> kwargs['query'] = kwargs.pop('body') <NEW_LINE> return super(OrderedResponseElasticSearch, self) .count(*args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise e
|
Extension of pyelasticsearch.ElasticSearch that decodes responses using an
OrderedDict instead of a plain dict.
|
6259902bc432627299fa3fd6
|
class TestApiKeyWorksFail(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> API.app.app.config['TESTING'] = True <NEW_LINE> self.app = API.app.app.test_client() <NEW_LINE> API.database_manager.conn = psycopg2.connect(db_credentials) <NEW_LINE> API.database_manager.create_tables() <NEW_LINE> API.database_manager.insert_user_details('12Jas97l59N603Kj3460a52', 'Jason', 'jason@jason.com') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> API.database_manager.drop_tables() <NEW_LINE> <DEDENT> def test(self): <NEW_LINE> <INDENT> rv = self.app.get('/post?api_key=12Jas97l5invalidkey9N603Kj3460a52') <NEW_LINE> assert b'You do not have a valid API key to write data. Enter key like -- api_key=YOUR_KEY' in rv.data
|
Tests the request to URL/post returns a message that the api_key was invalid. User cannot proceed.
|
6259902b6fece00bbaccc991
|
class GVG_104: <NEW_LINE> <INDENT> events = Play(CONTROLLER, MINION + (ATK == 1)).on(Buff(Play.CARD, "GVG_104a"))
|
Hobgoblin
|
6259902b711fe17d825e148b
|
class WeakQubitRef(BasicQubit): <NEW_LINE> <INDENT> pass
|
WeakQubitRef objects are used inside the Command object.
Qubits feature automatic deallocation when destroyed. WeakQubitRefs, on the
other hand, do not share this feature, allowing to copy them and pass them
along the compiler pipeline, while the actual qubit objects may be garbage-
collected (and, thus, cleaned up early). Otherwise there is no difference
between a WeakQubitRef and a Qubit object.
|
6259902b5166f23b2e2443b8
|
class NoneToEmptyString(Rule): <NEW_LINE> <INDENT> def apply(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> return value
|
Replace None values with an empty string. This is useful in cases
where legacy software uses None to create an empty cell, but your
other checks require a string.
|
6259902bd18da76e235b793f
|
class Track(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.context = DictStack() <NEW_LINE> self.registered_events = {} <NEW_LINE> <DEDENT> def clear_context(self): <NEW_LINE> <INDENT> self.context = DictStack() <NEW_LINE> <DEDENT> def push_context(self, more_context): <NEW_LINE> <INDENT> self.context.push(more_context) <NEW_LINE> <DEDENT> def pop_context(self): <NEW_LINE> <INDENT> self.context.pop() <NEW_LINE> <DEDENT> def event(self, event_name, event_data): <NEW_LINE> <INDENT> evt = Event(event_name, event_data, self.context.get_dict()) <NEW_LINE> if evt.name in self.registered_events: <NEW_LINE> <INDENT> schema = self.registered_events[evt.name] <NEW_LINE> if schema.validate(evt): <NEW_LINE> <INDENT> evt.validated = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("WARN: Invalid event.") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print("WARN: Unregistered event.") <NEW_LINE> <DEDENT> pprint(evt.to_json()) <NEW_LINE> <DEDENT> def register(self, event_name): <NEW_LINE> <INDENT> schema = EventSchema(event_name) <NEW_LINE> self.registered_events[event_name] = schema <NEW_LINE> return schema
|
Event tracking host.
|
6259902bd53ae8145f919446
|
class Bbdd: <NEW_LINE> <INDENT> def __init__(self, ruta): <NEW_LINE> <INDENT> self.con = None <NEW_LINE> self.conectar(ruta) <NEW_LINE> <DEDENT> def conectar(self, ruta): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.con = sqlite3.connect(ruta) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> notificar('Ha ocurrido un error al conectar a la base de datos.') <NEW_LINE> notificar(e, False) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return self.con <NEW_LINE> <DEDENT> <DEDENT> def desconectar(self): <NEW_LINE> <INDENT> self.con.close() <NEW_LINE> <DEDENT> def ex(self, sql, args = None, commit = False, many = False): <NEW_LINE> <INDENT> c = self.con.cursor() <NEW_LINE> try: <NEW_LINE> <INDENT> if args is not None: <NEW_LINE> <INDENT> if not isinstance(args, (list, tuple)): <NEW_LINE> <INDENT> args = (args,) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> args = () <NEW_LINE> <DEDENT> if commit and many: <NEW_LINE> <INDENT> c.executemany(sql, args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c.execute(sql, args) <NEW_LINE> <DEDENT> if not commit: <NEW_LINE> <INDENT> return c.fetchall() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.con.commit() <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> notificar('Ha ocurrido un error al interactuar con la base de datos') <NEW_LINE> print(e) <NEW_LINE> self.con.rollback() <NEW_LINE> return 1 <NEW_LINE> <DEDENT> c.close() <NEW_LINE> <DEDENT> def ex_m(self, sql, args = None, commit = False): <NEW_LINE> <INDENT> return self.ex(sql, args, commit, True) <NEW_LINE> <DEDENT> def w(self, sql, args = None): <NEW_LINE> <INDENT> return self.ex(sql, args, True) <NEW_LINE> <DEDENT> def w_m(self, sql, args = None): <NEW_LINE> <INDENT> return self.ex(sql, args, True, True) <NEW_LINE> <DEDENT> def r(self, sql, args = None): <NEW_LINE> <INDENT> return self.ex(sql, args, False) <NEW_LINE> <DEDENT> def r_range(self, sql, args = None, limit = 1, offset = 0): <NEW_LINE> <INDENT> sql += 'LIMIT %d OFFSET %d' % (limit, offset) <NEW_LINE> return self.r(sql, args) <NEW_LINE> <DEDENT> def r_one(self, sql, args = None): <NEW_LINE> <INDENT> return self.r_range(sql, args)
|
Abstrae la base de datos sqlite
|
6259902b5e10d32532ce40f5
|
class Seq: <NEW_LINE> <INDENT> def __init__(self, strbases): <NEW_LINE> <INDENT> print("New sequence is already created!") <NEW_LINE> self.strbases = strbases <NEW_LINE> <DEDENT> def len(self): <NEW_LINE> <INDENT> return len(self.strbases)
|
A class for representing sequences
|
6259902b8e05c05ec3f6f64d
|
class KeyServer(object): <NEW_LINE> <INDENT> def __init__(self, host, port=11371, proxies=None, headers=None, verify=True): <NEW_LINE> <INDENT> if host.startswith('hkp://') or host.startswith('hkps://'): <NEW_LINE> <INDENT> host = host.replace("hkp", "http", 1) <NEW_LINE> if host.startswith('https'): <NEW_LINE> <INDENT> if port == 11371: <NEW_LINE> <INDENT> port = 443 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Unsupported protocol, hkp|hkps are supported.") <NEW_LINE> <DEDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.session = requests.session() <NEW_LINE> self.session.headers = headers <NEW_LINE> self.session.proxies = proxies <NEW_LINE> if host.endswith("hkps.pool.sks-keyservers.net"): <NEW_LINE> <INDENT> verify = utils.ca().pem <NEW_LINE> <DEDENT> self.session.verify = verify <NEW_LINE> <DEDENT> def __parse_index(self, response): <NEW_LINE> <INDENT> lines = response.splitlines()[1:] <NEW_LINE> result, key = [], None <NEW_LINE> for line in iter(lines): <NEW_LINE> <INDENT> items = line.split(':') <NEW_LINE> if 'pub' in items[0]: <NEW_LINE> <INDENT> key = Key(self.host, self.port, * items[1:], session=self.session) <NEW_LINE> result.append(key) <NEW_LINE> <DEDENT> if 'uid' in items[0] and key: <NEW_LINE> <INDENT> key.identities.append(Identity(*items[1:])) <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def search(self, query, exact=False, nm=False): <NEW_LINE> <INDENT> opts = ( ('mr', True), ('nm', nm), ) <NEW_LINE> params = { 'op': 'index', 'options': ','.join(name for name, val in opts if val), 'search': query, 'exact': exact and 'on' or 'off', } <NEW_LINE> request_url = '{}:{}/pks/lookup'.format(self.host, self.port) <NEW_LINE> response = self.session.get( request_url, params=params) <NEW_LINE> if response.ok: <NEW_LINE> <INDENT> response = response.text <NEW_LINE> <DEDENT> elif response.status_code == requests.codes.not_found: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( '{}\nRequest URL: {}\nResponse:\n{}'.format(response.status_code, response.request.url, response.text)) <NEW_LINE> <DEDENT> return self.__parse_index(response) <NEW_LINE> <DEDENT> def add(self, key): <NEW_LINE> <INDENT> request_url = '{}:{}/pks/add'.format(self.host, self.port) <NEW_LINE> data = {'keytext': key} <NEW_LINE> response = self.session.post( request_url, data=data) <NEW_LINE> response.raise_for_status()
|
Keyserver object used for search queries.
|
6259902b8a349b6b4368721d
|
class UrlListParseAction(argparse.Action): <NEW_LINE> <INDENT> def __call__(self, parser, namespace, urls, option_string=None): <NEW_LINE> <INDENT> dest = getattr(namespace, self.dest) <NEW_LINE> if dest is urls: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for url in urls: <NEW_LINE> <INDENT> dest.append(url)
|
Custom action to avoid having the --file argument overwrite regular URLs, or vice versa.
Instead, this action will simply merge regular URLs with file URLs.
|
6259902b6fece00bbaccc992
|
class Formatter(metaclass=FormatterRegistry): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.can_preview = False <NEW_LINE> self.can_export = False <NEW_LINE> <DEDENT> def format(self, article, subscriber, codes=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def export(self, article, subscriber, codes=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def can_format(self, format_type, article): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def append_body_footer(self, article): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> article['body_html'].replace('<br>', '<br/>') <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> body = '' <NEW_LINE> if article[ITEM_TYPE] in [CONTENT_TYPE.TEXT, CONTENT_TYPE.PREFORMATTED] or is_takes_package(article): <NEW_LINE> <INDENT> body = article.get('body_html', '') <NEW_LINE> <DEDENT> elif article[ITEM_TYPE] in [CONTENT_TYPE.AUDIO, CONTENT_TYPE.PICTURE, CONTENT_TYPE.VIDEO]: <NEW_LINE> <INDENT> body = article.get('description', '') <NEW_LINE> <DEDENT> if body and article.get(FORMAT, '') == FORMATS.PRESERVED: <NEW_LINE> <INDENT> body = body.replace('\n', '\r\n').replace('\r\r', '\r') <NEW_LINE> parsed = parse_html(body, content='html') <NEW_LINE> for br in parsed.xpath('//br'): <NEW_LINE> <INDENT> br.tail = '\r\n' + br.tail if br.tail else '\r\n' <NEW_LINE> <DEDENT> etree.strip_elements(parsed, 'br', with_tail=False) <NEW_LINE> body = etree.tostring(parsed, encoding="unicode") <NEW_LINE> <DEDENT> if body and article.get('body_footer'): <NEW_LINE> <INDENT> footer = article.get('body_footer') <NEW_LINE> if article.get(FORMAT, '') == FORMATS.PRESERVED: <NEW_LINE> <INDENT> body = '{}\r\n{}'.format(body, get_text(footer)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> body = '{}{}'.format(body, footer) <NEW_LINE> <DEDENT> <DEDENT> return body <NEW_LINE> <DEDENT> def append_legal(self, article, truncate=False): <NEW_LINE> <INDENT> slugline = article.get('slugline', '') or '' <NEW_LINE> if article.get('flags', {}).get('marked_for_legal', False): <NEW_LINE> <INDENT> slugline = '{}: {}'.format('Legal', slugline) <NEW_LINE> if truncate: <NEW_LINE> <INDENT> slugline = slugline[:24] <NEW_LINE> <DEDENT> <DEDENT> return slugline <NEW_LINE> <DEDENT> def map_html_to_xml(self, element, html): <NEW_LINE> <INDENT> root = parse_html(html) <NEW_LINE> if not len(root.xpath('//p')) and len(root.xpath('//br')): <NEW_LINE> <INDENT> para = etree.SubElement(element, 'p') <NEW_LINE> for br in root.xpath('//br'): <NEW_LINE> <INDENT> etree.SubElement(para, 'br').text = br.text <NEW_LINE> <DEDENT> <DEDENT> for p in root.xpath('//p'): <NEW_LINE> <INDENT> para = etree.SubElement(element, 'p') <NEW_LINE> if len(p.xpath('//br')) > 0: <NEW_LINE> <INDENT> for br in p.xpath('//br'): <NEW_LINE> <INDENT> etree.SubElement(para, 'br').text = br.text <NEW_LINE> <DEDENT> <DEDENT> para.text = etree.tostring(p, encoding="unicode", method="text") <NEW_LINE> <DEDENT> if len(list(element)) == 0: <NEW_LINE> <INDENT> etree.SubElement(element, 'p').text = etree.tostring(root, encoding="unicode", method="text")
|
Base Formatter class for all types of Formatters like News ML 1.2, News ML G2, NITF, etc.
|
6259902bec188e330fdf9877
|
class Category(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'categories' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.Unicode(50), nullable=False) <NEW_LINE> @classmethod <NEW_LINE> def get_all(cls, ids: Set[int]): <NEW_LINE> <INDENT> categories = db.session.query(Category).filter( Category.id.in_(ids) ).all() <NEW_LINE> db_ids = {record.id for record in categories} <NEW_LINE> if len(categories) != len(ids): <NEW_LINE> <INDENT> raise NotFound([f"Category[{category_id}]" for category_id in ids.difference(db_ids)]) <NEW_LINE> <DEDENT> return categories <NEW_LINE> <DEDENT> @property <NEW_LINE> def serialized(self) -> CategoryPresentation: <NEW_LINE> <INDENT> return { 'id': self.id, 'name': self.name, }
|
Category db class.
|
6259902b5166f23b2e2443ba
|
class PromptHelp(CmdErr): <NEW_LINE> <INDENT> def __init__(self, error): <NEW_LINE> <INDENT> CmdErr.__init__(self, error) <NEW_LINE> self.prefix = "Prompt Help:"
|
PromptHelp covers prompt help conditions.
|
6259902b8e05c05ec3f6f64e
|
class LookupForm(gsoc_forms.GSoCModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = None <NEW_LINE> <DEDENT> def __init__(self, request_data=None, **kwargs): <NEW_LINE> <INDENT> super(LookupForm, self).__init__(**kwargs) <NEW_LINE> self.request_data = request_data <NEW_LINE> <DEDENT> user_id = djangoforms.CharField(label='Username') <NEW_LINE> def clean_user_id(self): <NEW_LINE> <INDENT> user_id_cleaner = cleaning.clean_link_id('user_id') <NEW_LINE> try: <NEW_LINE> <INDENT> user_id = user_id_cleaner(self) <NEW_LINE> <DEDENT> except djangoforms.ValidationError as e: <NEW_LINE> <INDENT> if e.code != 'invalid': <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> msg = ugettext(u'Enter a valid username.') <NEW_LINE> raise djangoforms.ValidationError(msg, code='invalid') <NEW_LINE> <DEDENT> user = user_model.User.get_by_id(user_id) <NEW_LINE> if not user: <NEW_LINE> <INDENT> raise djangoforms.ValidationError( 'There is no user with that email address') <NEW_LINE> <DEDENT> self.cleaned_data['user'] = user <NEW_LINE> query = profile_model.Profile.query( profile_model.Profile.program == ndb.Key.from_old_key( self.request_data.program.key()), ancestor=user.key) <NEW_LINE> self.cleaned_data['profile'] = query.get()
|
Django form for the lookup profile page.
|
6259902b6fece00bbaccc994
|
@Registry.register_sub_command <NEW_LINE> class ShowSubCommand(AbstractBaseSubCommand): <NEW_LINE> <INDENT> sub_command = "show" <NEW_LINE> sub_command_help = "show notes" <NEW_LINE> def invoke_on_note(self, args, note): <NEW_LINE> <INDENT> print_colored("%s%s" % (note.path, linesep), interactive_only=True) <NEW_LINE> with open(note.path, "r") as note_file: <NEW_LINE> <INDENT> copyfileobj(note_file, stdout)
|
A simple plugin that prints the contents of notes found to stdout.
|
6259902b6fece00bbaccc995
|
class Kepq3(Mast): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Kepq3, self).__init__() <NEW_LINE> self.dicttname = 'stars' <NEW_LINE> self.t = {'id' : 1, 'RA' : 2, 'DEC' : 3, 'KEPMAG' : 14} <NEW_LINE> self.dictcols = ['KIC', 'RA', 'DEC', 'PMRA', 'PMDEC', 'GMAG', 'RMAG', 'IMAG', 'ZMAG', 'D51MAG', 'JMAG', 'HMAG', 'KMAG', 'KEPMAG', 'VARCLS', 'TEFF', 'LOGG', 'FEH', 'AV', 'RADIUS', 'PERIOD', 'SNR', 'AOV', 'FC2_PER', 'FC2_CHM', 'AoV2_PER', 'AoV2_AOV', 'AoV2_SNR', 'AoV2_NEG'] <NEW_LINE> self.dicttypes = ['TEXT', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'TEXT', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL', 'REAL'] <NEW_LINE> self.dictnulls = [' NOT NULL UNIQUE ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] <NEW_LINE> self.npdicttype = [('KIC', 'a10'), ('RA', 'f4'), ('DEC', 'f4'), ('PMRA', 'f4'), ('PMDEC', 'f4'), ('GMAG', 'f4'), ('RMAG', 'f4'), ('IMAG', 'f4'), ('ZMAG', 'f4'), ('D51MAG', 'f4'), ('JMAG', 'f4'), ('HMAG', 'f4'), ('KMAG', 'f4'), ('KEPMAG', 'f4'), ('VARCLS', 'a12'), ('TEFF', 'f4'), ('LOGG', 'f4'), ('FEH', 'f4'), ('AV', 'f4'), ('RADIUS', 'f4'), ('PERIOD', 'f4'), ('SNR', 'f4'), ('AOV', 'f4'), ('FC2_PER', 'f4'), ('FC2_CHM', 'f4'), ('AoV2_PER', 'f4'), ('AoV2_AOV', 'f4'), ('AoV2_SNR', 'f4'), ('AoV2_NEG', 'f4')] <NEW_LINE> self.sdirindex = 29
|
class wrapper for Kepler Q3 data
|
6259902b796e427e5384f763
|
class MediaTranscodeItem(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.OutputStorage = None <NEW_LINE> self.Path = None <NEW_LINE> self.Definition = None <NEW_LINE> self.Bitrate = None <NEW_LINE> self.Height = None <NEW_LINE> self.Width = None <NEW_LINE> self.Size = None <NEW_LINE> self.Duration = None <NEW_LINE> self.Container = None <NEW_LINE> self.Md5 = None <NEW_LINE> self.AudioStreamSet = None <NEW_LINE> self.VideoStreamSet = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("OutputStorage") is not None: <NEW_LINE> <INDENT> self.OutputStorage = TaskOutputStorage() <NEW_LINE> self.OutputStorage._deserialize(params.get("OutputStorage")) <NEW_LINE> <DEDENT> self.Path = params.get("Path") <NEW_LINE> self.Definition = params.get("Definition") <NEW_LINE> self.Bitrate = params.get("Bitrate") <NEW_LINE> self.Height = params.get("Height") <NEW_LINE> self.Width = params.get("Width") <NEW_LINE> self.Size = params.get("Size") <NEW_LINE> self.Duration = params.get("Duration") <NEW_LINE> self.Container = params.get("Container") <NEW_LINE> self.Md5 = params.get("Md5") <NEW_LINE> if params.get("AudioStreamSet") is not None: <NEW_LINE> <INDENT> self.AudioStreamSet = [] <NEW_LINE> for item in params.get("AudioStreamSet"): <NEW_LINE> <INDENT> obj = MediaAudioStreamItem() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.AudioStreamSet.append(obj) <NEW_LINE> <DEDENT> <DEDENT> if params.get("VideoStreamSet") is not None: <NEW_LINE> <INDENT> self.VideoStreamSet = [] <NEW_LINE> for item in params.get("VideoStreamSet"): <NEW_LINE> <INDENT> obj = MediaVideoStreamItem() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.VideoStreamSet.append(obj)
|
转码信息
|
6259902b21a7993f00c66f64
|
class HashedCredentials(Credentials): <NEW_LINE> <INDENT> def password_match(self, password): <NEW_LINE> <INDENT> return match_token256(password, self.auth.password)
|
Credentials where the password is hashed.
|
6259902b8a349b6b43687221
|
class AcceptedListenChannel(RecvChannel): <NEW_LINE> <INDENT> def __init__(self, name=None, binding=None, parent_channel=None, **kwargs): <NEW_LINE> <INDENT> RecvChannel.__init__(self, name=name, binding=binding, **kwargs) <NEW_LINE> self._delivery_tags = set() <NEW_LINE> self._parent_channel = parent_channel <NEW_LINE> <DEDENT> def close_impl(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def recv(self, timeout=None): <NEW_LINE> <INDENT> msg = RecvChannel.recv(self, timeout=timeout) <NEW_LINE> self._delivery_tags.add(msg[2]) <NEW_LINE> return msg <NEW_LINE> <DEDENT> def _checkin(self, delivery_tag): <NEW_LINE> <INDENT> if not delivery_tag in self._delivery_tags: <NEW_LINE> <INDENT> log.warn("MISSING DTAG: %s", delivery_tag) <NEW_LINE> import traceback <NEW_LINE> traceback.print_stack() <NEW_LINE> return <NEW_LINE> <DEDENT> self._delivery_tags.remove(delivery_tag) <NEW_LINE> if len(self._delivery_tags) == 0: <NEW_LINE> <INDENT> self._parent_channel.exit_accept() <NEW_LINE> <DEDENT> <DEDENT> def ack(self, delivery_tag): <NEW_LINE> <INDENT> RecvChannel.ack(self, delivery_tag) <NEW_LINE> self._checkin(delivery_tag) <NEW_LINE> <DEDENT> def reject(self, delivery_tag, requeue=False): <NEW_LINE> <INDENT> RecvChannel.reject(self, delivery_tag, requeue=requeue) <NEW_LINE> self._checkin(delivery_tag)
|
The type of channel returned by accept.
|
6259902b3eb6a72ae038b64c
|
class Common(object): <NEW_LINE> <INDENT> BOT_FIRST_NAME = 'Wizzy Viktorovich' <NEW_LINE> BOT_NICKNAME = 'wizzy' <NEW_LINE> ADMINS = ['UM35HE6R5'] <NEW_LINE> TRIGGERS = ['cah', 'c!'] <NEW_LINE> _v = get_versions() <NEW_LINE> VERSION = _v['version'] <NEW_LINE> UPDATE_DATE = _v['date'] <NEW_LINE> DB_PATH = os.path.join(os.path.expanduser('~'), *['data', 'cahdb.db']) <NEW_LINE> if not os.path.exists(DB_PATH): <NEW_LINE> <INDENT> raise FileNotFoundError(f'DB_PATH at {DB_PATH} invalid...') <NEW_LINE> <DEDENT> DB_URI = f'sqlite:///{DB_PATH}' <NEW_LINE> engine = create_engine(DB_URI, isolation_level='SERIALIZABLE') <NEW_LINE> Base.metadata.bind = engine <NEW_LINE> SESSION = sessionmaker(bind=engine)
|
Configuration items common across all config types
|
6259902bd4950a0f3b111631
|
class ObjectNotFoundError(GitPathError, FileNotFoundError): <NEW_LINE> <INDENT> pass
|
Git object not found
|
6259902b8c3a8732951f7540
|
class GraphicsSocket(QGraphicsItem): <NEW_LINE> <INDENT> def __init__(self, socket: "Socket") -> None: <NEW_LINE> <INDENT> super(GraphicsSocket, self).__init__(socket.node.graphicsNode) <NEW_LINE> self.socket = socket <NEW_LINE> self.initUI() <NEW_LINE> self.hovered = False <NEW_LINE> <DEDENT> def initUI(self) -> None: <NEW_LINE> <INDENT> self.initSizes() <NEW_LINE> self.initStyle() <NEW_LINE> self.setAcceptHoverEvents(True) <NEW_LINE> <DEDENT> def initStyle(self) -> None: <NEW_LINE> <INDENT> self._colorBackground: QColor = getSocketColor(self.socketType.value) <NEW_LINE> self._colorOutline: QColor = QColor("#FF000000") <NEW_LINE> self._colorHovered: QColor = QColor("#FF37A6FF") <NEW_LINE> self._pen: QPen = QPen(self._colorOutline) <NEW_LINE> self._pen.setWidthF(self.outlineWidth) <NEW_LINE> self._brush: QBrush = QBrush(self._colorBackground) <NEW_LINE> self._penHovered: QPen = QPen(self._colorHovered) <NEW_LINE> self._penHovered.setWidthF(2.0) <NEW_LINE> <DEDENT> def initSizes(self) -> None: <NEW_LINE> <INDENT> self.radius: int = 6 <NEW_LINE> self.outlineWidth = 1.0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def socketType(self) -> SocketType: <NEW_LINE> <INDENT> return self.socket.socketType <NEW_LINE> <DEDENT> def updateSocketType(self) -> None: <NEW_LINE> <INDENT> self._colorBackground = getSocketColor(self.socketType.value) <NEW_LINE> self._brush = QBrush(self._colorBackground) <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def paint( self, painter: QPainter, options: QStyleOptionGraphicsItem, widget: Optional[QWidget] = None, ): <NEW_LINE> <INDENT> painter.setBrush(self._brush) <NEW_LINE> painter.setPen(self._pen if not self.hovered else self._penHovered) <NEW_LINE> painter.drawEllipse( -self.radius, -self.radius, 2 * self.radius, 2 * self.radius ) <NEW_LINE> painter.setBrush(QBrush(QColor(QApplication.palette().Button))) <NEW_LINE> if not self.socket.hasAnyEdge: <NEW_LINE> <INDENT> painter.drawEllipse( -int(self.radius * 0.5), -int(self.radius * 0.5), self.radius, self.radius, ) <NEW_LINE> <DEDENT> <DEDENT> def boundingRect(self) -> QRectF: <NEW_LINE> <INDENT> return QRectF( -self.radius - self.outlineWidth, -self.radius - self.outlineWidth, 2 * (self.radius + self.outlineWidth), 2 * (self.radius + self.outlineWidth), ) <NEW_LINE> <DEDENT> def hoverEnterEvent(self, event: QGraphicsSceneHoverEvent) -> None: <NEW_LINE> <INDENT> self.hovered = True <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def hoverLeaveEvent(self, event: QGraphicsSceneHoverEvent) -> None: <NEW_LINE> <INDENT> self.hovered = False <NEW_LINE> self.update()
|
:class:`~nodedge.graphics_socket.GraphicsSocket` class.
The graphics socket is the graphical representation of the
:class:`~nodedge.socket.Socket`.
|
6259902b925a0f43d25e902f
|
class CardAction(Model): <NEW_LINE> <INDENT> _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'title': {'key': 'title', 'type': 'str'}, 'image': {'key': 'image', 'type': 'str'}, 'text': {'key': 'text', 'type': 'str'}, 'display_text': {'key': 'displayText', 'type': 'str'}, 'value': {'key': 'value', 'type': 'object'}, } <NEW_LINE> def __init__(self, type=None, title=None, image=None, text=None, display_text=None, value=None): <NEW_LINE> <INDENT> super(CardAction, self).__init__() <NEW_LINE> self.type = type <NEW_LINE> self.title = title <NEW_LINE> self.image = image <NEW_LINE> self.text = text <NEW_LINE> self.display_text = display_text <NEW_LINE> self.value = value
|
A clickable action.
:param type: The type of action implemented by this button. Possible
values include: 'openUrl', 'imBack', 'postBack', 'playAudio', 'playVideo',
'showImage', 'downloadFile', 'signin', 'call', 'payment', 'messageBack'
:type type: str or ~botframework.connector.models.ActionTypes
:param title: Text description which appears on the button
:type title: str
:param image: Image URL which will appear on the button, next to text
label
:type image: str
:param text: Text for this action
:type text: str
:param display_text: (Optional) text to display in the chat feed if the
button is clicked
:type display_text: str
:param value: Supplementary parameter for action. Content of this property
depends on the ActionType
:type value: object
|
6259902b21bff66bcd723c4b
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.