code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class BaseJobRunner(object): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> _job_options = JOB_OPTIONS <NEW_LINE> def __init__(self, job, priority=NORMAL): <NEW_LINE> <INDENT> self._job = job <NEW_LINE> self._priority = priority <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def run_job(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def prepare_job_args(self): <NEW_LINE> <INDENT> pass
Abstract job runner class. Segregates job execution logic. Creates job arguments from the job instance and runs this job.
62598fb82c8b7c6e89bd390f
class GANModelTest(test.TestCase, parameterized.TestCase): <NEW_LINE> <INDENT> @parameterized.named_parameters( ('gan', get_gan_model, namedtuples.GANModel), ('callable_gan', get_callable_gan_model, namedtuples.GANModel), ('infogan', get_infogan_model, namedtuples.InfoGANModel), ('callable_infogan', get_callable_infogan_model, namedtuples.InfoGANModel), ('acgan', get_acgan_model, namedtuples.ACGANModel), ('callable_acgan', get_callable_acgan_model, namedtuples.ACGANModel), ('cyclegan', get_cyclegan_model, namedtuples.CycleGANModel), ('callable_cyclegan', get_callable_cyclegan_model, namedtuples.CycleGANModel), ('stargan', get_stargan_model, namedtuples.StarGANModel), ('callabel_stargan', get_callable_stargan_model, namedtuples.StarGANModel) ) <NEW_LINE> def test_output_type(self, create_fn, expected_tuple_type): <NEW_LINE> <INDENT> self.assertIsInstance(create_fn(), expected_tuple_type) <NEW_LINE> <DEDENT> def test_no_shape_check(self): <NEW_LINE> <INDENT> def dummy_generator_model(_): <NEW_LINE> <INDENT> return (None, None) <NEW_LINE> <DEDENT> def dummy_discriminator_model(data, conditioning): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> with self.assertRaisesRegexp(AttributeError, 'object has no attribute'): <NEW_LINE> <INDENT> train.gan_model( dummy_generator_model, dummy_discriminator_model, real_data=array_ops.zeros([1, 2]), generator_inputs=array_ops.zeros([1]), check_shapes=True) <NEW_LINE> <DEDENT> train.gan_model( dummy_generator_model, dummy_discriminator_model, real_data=array_ops.zeros([1, 2]), generator_inputs=array_ops.zeros([1]), check_shapes=False)
Tests for `gan_model`.
62598fb8e5267d203ee6ba49
class reply_nyc_weather (threading.Thread): <NEW_LINE> <INDENT> email_dict = None <NEW_LINE> sender = None <NEW_LINE> subject = None <NEW_LINE> text = None <NEW_LINE> html = None <NEW_LINE> def __init__ (self, email_dict, sender, subject, text, html=None): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.email_dict = email_dict <NEW_LINE> self.sender = sender <NEW_LINE> self.subject = subject <NEW_LINE> self.text = text <NEW_LINE> if html is not None: <NEW_LINE> <INDENT> self.html = html <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> weather_xml = get_url('http://forecast.weather.gov/MapClick.php?lat=40.71980&lon=-73.99300&FcstType=dwml') <NEW_LINE> if weather_xml is None: <NEW_LINE> <INDENT> send('NYC Weather', 'Sorry, this service is temporarily unavailable', recipient_list=[self.sender], sender=server_auto_email) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> doc = etree.fromstring(weather_xml) <NEW_LINE> report = [] <NEW_LINE> for elem in doc.xpath('//wordedForecast'): <NEW_LINE> <INDENT> for subelem in elem.getchildren(): <NEW_LINE> <INDENT> if subelem.tag == 'text': <NEW_LINE> <INDENT> report.append(subelem.text) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> send('NYC Weather', ' '.join(report), recipient_list=[self.sender], sender=server_auto_email)
In reply to email sent to nyc-weather@ -> lookup the current weather conditions for New York City and return it to the sender of this email
62598fb8a8370b77170f0528
class Struct: <NEW_LINE> <INDENT> def __init__(self, name, decls, bindingsgenerator): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.decls = decls <NEW_LINE> self.bindingsgenerator = bindingsgenerator
Representation of an Lvgl struct type for which to generate bindings To be overridden by language-specific classes
62598fb8dc8b845886d53702
class ZmqClientDirect(zmq_client_base.ZmqClientBase): <NEW_LINE> <INDENT> def __init__(self, conf, matchmaker=None, allowed_remote_exmods=None): <NEW_LINE> <INDENT> if conf.use_pub_sub or conf.use_router_proxy: <NEW_LINE> <INDENT> raise WrongClientException() <NEW_LINE> <DEDENT> publisher = zmq_dealer_publisher_direct.DealerPublisherDirect(conf, matchmaker) <NEW_LINE> super(ZmqClientDirect, self).__init__( conf, matchmaker, allowed_remote_exmods, publishers={"default": publisher} )
This kind of client (publishers combination) is to be used for direct connections only: use_pub_sub = false use_router_proxy = false
62598fb83d592f4c4edbb008
class Tile(LVMOpsBaseModel): <NEW_LINE> <INDENT> TileID = IntegerField(primary_key=True) <NEW_LINE> TargetIndex = IntegerField(null=True) <NEW_LINE> Target = CharField(null=False) <NEW_LINE> Telescope = CharField(null=False) <NEW_LINE> RA = FloatField(null=True, default=0) <NEW_LINE> DEC = FloatField(null=True, default=0) <NEW_LINE> PA = FloatField(null=True, default=0) <NEW_LINE> TargetPriority = IntegerField(null=True, default=0) <NEW_LINE> TilePriority = IntegerField(null=True, default=0) <NEW_LINE> AirmassLimit = FloatField(null=True, default=0) <NEW_LINE> LunationLimit = FloatField(null=True, default=0) <NEW_LINE> HzLimit = FloatField(null=True, default=0) <NEW_LINE> MoonDistanceLimit = FloatField(null=True, default=0) <NEW_LINE> TotalExptime = FloatField(null=True, default=0) <NEW_LINE> VisitExptime = FloatField(null=True, default=0) <NEW_LINE> Status = IntegerField(null=False)
Peewee ORM class for LVM Survey Tiles
62598fb8aad79263cf42e91e
@db_test_lib.DualDBTest <NEW_LINE> class ApiGetVfsFileContentUpdateStateHandlerTest( api_test_lib.ApiCallHandlerTest, VfsTestMixin): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(ApiGetVfsFileContentUpdateStateHandlerTest, self).setUp() <NEW_LINE> self.handler = vfs_plugin.ApiGetVfsFileContentUpdateStateHandler() <NEW_LINE> self.client_id = self.SetupClient(0) <NEW_LINE> <DEDENT> def testHandlerReturnsCorrectStateForFlow(self): <NEW_LINE> <INDENT> flow_id = self.CreateMultiGetFileFlow( self.client_id, file_path="fs/os/c/bin/bash", token=self.token) <NEW_LINE> args = vfs_plugin.ApiGetVfsFileContentUpdateStateArgs( client_id=self.client_id, operation_id=flow_id) <NEW_LINE> result = self.handler.Handle(args, token=self.token) <NEW_LINE> self.assertEqual(result.state, "RUNNING") <NEW_LINE> if data_store.RelationalDBEnabled(): <NEW_LINE> <INDENT> flow_base.TerminateFlow(self.client_id.Basename(), flow_id, "Fake error") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> flow_urn = self.client_id.Add("flows").Add(flow_id) <NEW_LINE> with aff4.FACTORY.Open( flow_urn, aff4_type=flow.GRRFlow, mode="rw", token=self.token) as flow_obj: <NEW_LINE> <INDENT> flow_obj.GetRunner().Error("Fake error") <NEW_LINE> <DEDENT> <DEDENT> result = self.handler.Handle(args, token=self.token) <NEW_LINE> self.assertEqual(result.state, "FINISHED") <NEW_LINE> <DEDENT> def testHandlerRaisesOnArbitraryFlowId(self): <NEW_LINE> <INDENT> if data_store.RelationalDBEnabled(): <NEW_LINE> <INDENT> flow_id = flow.StartFlow( client_id=self.client_id.Basename(), flow_cls=discovery.Interrogate) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> flow_id = flow.StartAFF4Flow( client_id=self.client_id, flow_name=discovery.Interrogate.__name__, token=self.token).Basename() <NEW_LINE> <DEDENT> args = vfs_plugin.ApiGetVfsFileContentUpdateStateArgs( client_id=self.client_id, operation_id=flow_id) <NEW_LINE> with self.assertRaises(vfs_plugin.VfsFileContentUpdateNotFoundError): <NEW_LINE> <INDENT> self.handler.Handle(args, token=self.token) <NEW_LINE> <DEDENT> <DEDENT> def testHandlerThrowsExceptionOnUnknownFlowId(self): <NEW_LINE> <INDENT> args = vfs_plugin.ApiGetVfsRefreshOperationStateArgs( client_id=self.client_id, operation_id="F:12345678") <NEW_LINE> with self.assertRaises(vfs_plugin.VfsFileContentUpdateNotFoundError): <NEW_LINE> <INDENT> self.handler.Handle(args, token=self.token)
Test for ApiGetVfsFileContentUpdateStateHandler.
62598fb85fdd1c0f98e5e0d9
class ResourceLimit(abc.ABC): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def check(self, usage: ResourceUsageTracker) -> None: <NEW_LINE> <INDENT> ...
Used to check if a particular resource limit is exceeded.
62598fb8f9cc0f698b1c5372
class Resize(object): <NEW_LINE> <INDENT> def __init__(self, output_size): <NEW_LINE> <INDENT> assert isinstance(output_size, (int, tuple)) <NEW_LINE> self.output_size = output_size <NEW_LINE> <DEDENT> def _resize(self, image): <NEW_LINE> <INDENT> h, w = image.size()[1:3] <NEW_LINE> if isinstance(self.output_size, int): <NEW_LINE> <INDENT> if h > w: <NEW_LINE> <INDENT> new_h, new_w = self.output_size * h / w, self.output_size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_h, new_w = self.output_size, self.output_size * w / h <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> new_h, new_w = self.output_size <NEW_LINE> <DEDENT> new_h, new_w = int(new_h), int(new_w) <NEW_LINE> img = F.interpolate(image.unsqueeze(0), (new_h, new_w)) <NEW_LINE> return img.squeeze(0) <NEW_LINE> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> raw_image, ref_image = sample['raw_image'], sample['ref_image'] <NEW_LINE> new_raw_image = self._resize(raw_image) <NEW_LINE> new_ref_image = self._resize(ref_image) <NEW_LINE> return {'raw_image': new_raw_image, 'ref_image': new_ref_image}
Rescale the image in a sample to a given size. Args: output_size (tuple or int): Desired output size. If tuple, output is matched to output_size. If int, smaller of image edges is matched to output_size keeping aspect ratio the same.
62598fb899fddb7c1ca62e90
class ColorTranslator(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def FromHtml(htmlColor): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def FromOle(oleColor): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def FromWin32(win32Color): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def ToHtml(c): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def ToOle(c): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def ToWin32(c): <NEW_LINE> <INDENT> pass
Translates colors to and from GDI+ System.Drawing.Color structures. This class cannot be inherited.
62598fb821bff66bcd722db3
class UserLoginSerializer(serializers.Serializer): <NEW_LINE> <INDENT> email= serializers.EmailField() <NEW_LINE> password = serializers.CharField(min_length=8) <NEW_LINE> def validate(self, data): <NEW_LINE> <INDENT> user = authenticate(username=data['email'], password=data['password']) <NEW_LINE> if not user: <NEW_LINE> <INDENT> raise serializers.ValidationError('Invalid credentials') <NEW_LINE> <DEDENT> if not user.is_verified: <NEW_LINE> <INDENT> raise serializers.ValidationError('Account is not activate yet D:') <NEW_LINE> <DEDENT> self.context['user'] = user <NEW_LINE> return data <NEW_LINE> <DEDENT> def create(self, data): <NEW_LINE> <INDENT> token, created = Token.objects.get_or_create(user=self.context['user']) <NEW_LINE> return self.context['user'], token.key
User Login serializer. Handle the login request data.
62598fb8adb09d7d5dc0a6c8
class GetJob(Resource): <NEW_LINE> <INDENT> def get(self,id): <NEW_LINE> <INDENT> response = db.get_one(id) <NEW_LINE> if response: <NEW_LINE> <INDENT> return make_response(jsonify({"status": 200, "data": [{'message': 'jobs available', 'jobs':response}]}), 200) <NEW_LINE> <DEDENT> return abort(make_response(jsonify({'message':'No jobs Found'}),400))
Class with method to get one job
62598fb856ac1b37e6302337
class Level(): <NEW_LINE> <INDENT> def __init__(self, player): <NEW_LINE> <INDENT> self.platform_list = None <NEW_LINE> self.background = None <NEW_LINE> self.world_shift = 0 <NEW_LINE> self.world_shift_y = 0 <NEW_LINE> self.level_limit = -1000 <NEW_LINE> self.platform_list = pygame.sprite.Group() <NEW_LINE> self.player = player <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.platform_list.update() <NEW_LINE> <DEDENT> def draw(self, screen): <NEW_LINE> <INDENT> screen.fill(constants.BLUE) <NEW_LINE> screen.blit(self.background,(self.world_shift, self.world_shift_y)) <NEW_LINE> self.platform_list.draw(screen) <NEW_LINE> <DEDENT> def shift_world(self, shift_x): <NEW_LINE> <INDENT> self.world_shift += shift_x <NEW_LINE> for platform in self.platform_list: <NEW_LINE> <INDENT> platform.rect.x += shift_x <NEW_LINE> <DEDENT> <DEDENT> def shift_world_y(self, shift_y): <NEW_LINE> <INDENT> self.world_shift_y += shift_y <NEW_LINE> for platform in self.platform_list: <NEW_LINE> <INDENT> platform.rect.y += shift_y
Cette super class definie tout le level et comporte deux classes filles définissant chaque level
62598fb84527f215b58ea021
class TestListar_mis_solicitudes(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = User.objects.create_user('super', 'lennon@thebeatles.com', 'super') <NEW_LINE> self.proyecto = Proyecto.objects.create(numero_fases=2, usuario=self.user, observaciones='ninguna', presupuesto=111, nombre='proyecto_test', estado='Pendiente') <NEW_LINE> self.fase = self.proyecto.fases.first() <NEW_LINE> <DEDENT> def test_listar_mis_solicitudes(self): <NEW_LINE> <INDENT> c = Client() <NEW_LINE> c.login(username='super', password='super') <NEW_LINE> url = reverse('solicitudCambio.views.listar_mis_solicitudes') <NEW_LINE> response = c.get(url, follow=True) <NEW_LINE> self.assertEqual(response.status_code, 200)
Clase de test para la vista solicitudCambio.views.listar_mis_solicitudes
62598fb8aad79263cf42e91f
class Category(models.Model): <NEW_LINE> <INDENT> nid = models.AutoField(primary_key=True) <NEW_LINE> title = models.CharField(max_length=32) <NEW_LINE> blog = models.ForeignKey(to="Blog", to_field="nid") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "文章分类"
个人博客文章分类
62598fb8167d2b6e312b70c0
class BasicType: <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "[" + self.__class__.__name__ + "]" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def has_member(cls, v): <NEW_LINE> <INDENT> return type(v) is cls
Basic Type declaration Z: [Name, Date] today : Date Python: Name = BasicType Date = BasicType today = BasicType()
62598fb830dc7b766599f999
class LeadTimeProjection(metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self, board_id, **kwargs): <NEW_LINE> <INDENT> self._board_id = board_id <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> self._work_item_start_times = {} <NEW_LINE> self._lead_times = {} <NEW_LINE> self._load_events() <NEW_LINE> subscribe(self._event_filter, self._handler) <NEW_LINE> <DEDENT> @property <NEW_LINE> def board_id(self): <NEW_LINE> <INDENT> return self._board_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def average_lead_time(self): <NEW_LINE> <INDENT> mean_lead_time = sum(self._lead_times.values()) / len(self._lead_times) <NEW_LINE> return datetime.timedelta(seconds=mean_lead_time) <NEW_LINE> <DEDENT> def lead_times(self): <NEW_LINE> <INDENT> return self._lead_times.values() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> unsubscribe(self._event_filter, self._handler) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def _load_events(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _event_filter(self, event): <NEW_LINE> <INDENT> return (event.originator_id == self.board_id and isinstance(event, (Board.WorkItemScheduled, Board.WorkItemAbandoned, Board.WorkItemRetired))) <NEW_LINE> <DEDENT> def _handler(self, event): <NEW_LINE> <INDENT> mutate(self, event)
A projection which tracks the lead time for work items with respect to a specified Board.
62598fb8e5267d203ee6ba4b
class LSTMacceptor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.model = dy.ParameterCollection() <NEW_LINE> self.trainer = dy.AdamTrainer(self.model) <NEW_LINE> self.embeddings = self.model.add_lookup_parameters((len(C2I), EMBEDDINGS_DIM)) <NEW_LINE> self.builder = dy.LSTMBuilder(LAYERS, EMBEDDINGS_DIM, HIDDEN_DIM, self.model) <NEW_LINE> self.W1 = self.model.add_parameters((HIDDEN_MLP_DIM, HIDDEN_DIM)) <NEW_LINE> self.b1 = self.model.add_parameters(HIDDEN_MLP_DIM) <NEW_LINE> self.W2 = self.model.add_parameters((len(T2I), HIDDEN_MLP_DIM)) <NEW_LINE> self.b2 = self.model.add_parameters(len(T2I)) <NEW_LINE> <DEDENT> def __call__(self, word): <NEW_LINE> <INDENT> dy.renew_cg() <NEW_LINE> embeddings = self.represent(word) <NEW_LINE> init_state = self.builder.initial_state() <NEW_LINE> output = init_state.transduce(embeddings)[-1] <NEW_LINE> result = self.W2 * (dy.tanh(self.W1 * output + self.b1)) + self.b2 <NEW_LINE> return dy.softmax(result) <NEW_LINE> <DEDENT> def represent(self, word): <NEW_LINE> <INDENT> characters_index = [C2I[character] for character in word] <NEW_LINE> embeddings = [self.embeddings[i] for i in characters_index] <NEW_LINE> return embeddings <NEW_LINE> <DEDENT> def compute_loss(self, word, tag): <NEW_LINE> <INDENT> word_t = self(word) <NEW_LINE> loss = -dy.log(dy.pick(word_t, T2I[tag])) <NEW_LINE> return loss <NEW_LINE> <DEDENT> def compute_prediction(self, word): <NEW_LINE> <INDENT> word_t = self(word) <NEW_LINE> return I2T[np.argmax(word_t.value())]
initialize LSTM acceptor model of 1 layer with MLP of one hidden layer
62598fb863b5f9789fe852b9
class Invocation(object): <NEW_LINE> <INDENT> def __init__(self, command, cwd): <NEW_LINE> <INDENT> self.command = command <NEW_LINE> self.cwd = cwd <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ' '.join(self.command) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_compile_command(cls, entry, extra_args): <NEW_LINE> <INDENT> if 'arguments' in entry: <NEW_LINE> <INDENT> command = entry['arguments'] <NEW_LINE> <DEDENT> elif 'command' in entry: <NEW_LINE> <INDENT> command = split_command(entry['command']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid compilation database entry: %s' % entry) <NEW_LINE> <DEDENT> compile_command, compile_args = command[0], command[1:] <NEW_LINE> if is_msvc_driver(compile_command): <NEW_LINE> <INDENT> extra_args = ['--driver-mode=cl'] + extra_args <NEW_LINE> <DEDENT> command = [IWYU_EXECUTABLE] + extra_args + compile_args <NEW_LINE> return cls(command, entry['directory']) <NEW_LINE> <DEDENT> def start(self, verbose): <NEW_LINE> <INDENT> if verbose: <NEW_LINE> <INDENT> print('# %s' % self) <NEW_LINE> <DEDENT> return Process.start(self)
Holds arguments of an IWYU invocation.
62598fb891f36d47f2230f4f
class ChangeSegmentation(base.TemplateView): <NEW_LINE> <INDENT> template_name = 'feats/segmentation/change_segments.html' <NEW_LINE> @property <NEW_LINE> def feature(self): <NEW_LINE> <INDENT> return self.feats_app.features[self.args[0]] <NEW_LINE> <DEDENT> def get_formset(self, feature, state): <NEW_LINE> <INDENT> return feature_segment_formset(feature, state=state) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> feature = self.feature <NEW_LINE> state = feature.state <NEW_LINE> if state is None: <NEW_LINE> <INDENT> state = FeatureState.initial( self.request.user.username ) <NEW_LINE> <DEDENT> segment_formset = self.get_formset(feature, state) <NEW_LINE> context['formset'] = segment_formset <NEW_LINE> context['feature'] = feature <NEW_LINE> return context
Changes how a Feature is Segmented and how selectors map to those segments. Updating segmentation resets any selector mappings, so this form is done in two steps The first form submits through a GET to mapping url with the segments. This does not save any data to the database. The next form submits through a POST to mapping url with the segments and mappings. This creates a new feature state and persists it. We update both segmentation and mapping in the same POST, as the alternative is to delete all mappings when segmentation is updated.
62598fb8fff4ab517ebcd934
class CrudAux(Crud): <NEW_LINE> <INDENT> permission_required = ('base.view_tabelas_auxiliares',) <NEW_LINE> class ListView(Crud.ListView): <NEW_LINE> <INDENT> template_name = "crud/list_tabaux.html" <NEW_LINE> <DEDENT> class BaseMixin(Crud.BaseMixin): <NEW_LINE> <INDENT> subnav_template_name = None <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> if 'subnav_template_name' not in context: <NEW_LINE> <INDENT> context['subnav_template_name'] = self.subnav_template_name <NEW_LINE> <DEDENT> return context <NEW_LINE> <DEDENT> <DEDENT> @classonlymethod <NEW_LINE> def build(cls, _model, _help_topic, _model_set=None, list_field_names=[]): <NEW_LINE> <INDENT> ModelCrud = Crud.build( _model, _help_topic, _model_set, list_field_names) <NEW_LINE> class ModelCrudAux(CrudAux, ModelCrud): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return ModelCrudAux
Checa permissão para ver qualquer dado de tabela auxiliar a permissão base.view_tabelas_auxiliares está definada class Meta do model sapl.base.models.AppConfig que, naturalmente é um arquivo de configuração geral e só pode ser acessado através das Tabelas Auxiliares... Com isso o script de geração de perfis acaba que por criar essa permissão apenas para o perfil Operador Geral.
62598fb8009cb60464d0166f
class ChiaJob(InspiralAnalysisJob): <NEW_LINE> <INDENT> def __init__(self,cp): <NEW_LINE> <INDENT> exec_name = 'chia' <NEW_LINE> sections = ['chia'] <NEW_LINE> extension = 'xml' <NEW_LINE> InspiralAnalysisJob.__init__(self,cp,sections,exec_name,extension)
A lalapps_coherent_inspiral job used by the inspiral pipeline. The static options are read from the section [chia] in the ini file. The stdout and stderr from the job are directed to the logs directory. The path to the executable is determined from the ini file.
62598fb8a05bb46b3848a9b7
class Status(object): <NEW_LINE> <INDENT> deserialized_types = { 'url': 'str', 'status': 'ask_sdk_model.services.list_management.list_item_state.ListItemState' } <NEW_LINE> attribute_map = { 'url': 'url', 'status': 'status' } <NEW_LINE> def __init__(self, url=None, status=None): <NEW_LINE> <INDENT> self.__discriminator_value = None <NEW_LINE> self.url = url <NEW_LINE> self.status = status <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.deserialized_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x.value if isinstance(x, Enum) else x, value )) <NEW_LINE> <DEDENT> elif isinstance(value, Enum): <NEW_LINE> <INDENT> result[attr] = value.value <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else (item[0], item[1].value) if isinstance(item[1], Enum) else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Status): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
:param url: :type url: (optional) str :param status: :type status: (optional) ask_sdk_model.services.list_management.list_item_state.ListItemState
62598fb8dc8b845886d53704
@implementer(ISequenceNumber) <NEW_LINE> class SequenceNumber(object): <NEW_LINE> <INDENT> def get_number(self, obj): <NEW_LINE> <INDENT> ann = unprotected_write(IAnnotations(obj)) <NEW_LINE> if SEQUENCE_NUMBER_ANNOTATION_KEY not in ann.keys(): <NEW_LINE> <INDENT> generator = getAdapter(obj, ISequenceNumberGenerator) <NEW_LINE> value = generator.generate() <NEW_LINE> ann[SEQUENCE_NUMBER_ANNOTATION_KEY] = value <NEW_LINE> <DEDENT> return ann.get(SEQUENCE_NUMBER_ANNOTATION_KEY) <NEW_LINE> <DEDENT> def remove_number(self, obj): <NEW_LINE> <INDENT> ann = unprotected_write(IAnnotations(obj)) <NEW_LINE> if SEQUENCE_NUMBER_ANNOTATION_KEY in ann.keys(): <NEW_LINE> <INDENT> del ann[SEQUENCE_NUMBER_ANNOTATION_KEY]
The sequence number utility provides a getNumber(obj) method which returns a unique number for each object.
62598fb871ff763f4b5e78c4
class VolumeGroup(FilesystemGroup, metaclass=VolumeGroupType): <NEW_LINE> <INDENT> uuid = ObjectField.Checked("uuid", check(str), check(str)) <NEW_LINE> size = ObjectField.Checked("size", check(int), check(int), readonly=True) <NEW_LINE> available_size = ObjectField.Checked("available_size", check(int), readonly=True) <NEW_LINE> used_size = ObjectField.Checked("used_size", check(int), readonly=True) <NEW_LINE> devices = DevicesField("devices") <NEW_LINE> logical_volumes = ObjectFieldRelatedSet( "logical_volumes", "LogicalVolumes", reverse=None ) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return super(VolumeGroup, self).__repr__(fields={"name", "size"}) <NEW_LINE> <DEDENT> async def delete(self): <NEW_LINE> <INDENT> await self._handler.delete(system_id=self.node.system_id, id=self.id)
A volume group on a machine.
62598fb823849d37ff8511ff
class EulerianBarycenter(Barycenter): <NEW_LINE> <INDENT> def __init__(self, loss, w=0.5): <NEW_LINE> <INDENT> super(EulerianBarycenter, self).__init__(loss, w) <NEW_LINE> self.a_i = (torch.ones(len(self.x_i)) / len(self.x_i)).type_as(self.x_i) <NEW_LINE> self.b_j = (torch.ones(len(self.y_j)) / len(self.y_j)).type_as(self.y_j) <NEW_LINE> self.l_k = Parameter(torch.zeros(len(self.z_k)).type_as(self.z_k)) <NEW_LINE> <DEDENT> def weights(self): <NEW_LINE> <INDENT> return torch.nn.functional.softmax(self.l_k, dim=0) <NEW_LINE> <DEDENT> def forward(self): <NEW_LINE> <INDENT> c_k = self.weights() <NEW_LINE> return self.w * self.loss(c_k, self.z_k, self.a_i, self.x_i) + ( 1 - self.w ) * self.loss(c_k, self.z_k, self.b_j, self.y_j)
Barycentric model with fixed locations z_k, as we optimize on the log-weights l_k.
62598fb826068e7796d4caa5
class UploadMode(object): <NEW_LINE> <INDENT> blocking = 0 <NEW_LINE> background = 1 <NEW_LINE> lazy = 2
How to add files on a :class:`Disk`.
62598fb866656f66f7d5a53e
class TransactionViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = TransactionSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> if self.request.user.has_perm("transaction.view"): <NEW_LINE> <INDENT> return Transaction.objects.all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Transaction.objects.filter(user=self.context['request'].user)
Views for Transaction objects. :methods: GET, POST, PATCH
62598fb98a349b6b43686388
class ExtensionError(SyntaxError): <NEW_LINE> <INDENT> def __init__(self, error, data): <NEW_LINE> <INDENT> super(ExtensionError, self).__init__(str(error), data) <NEW_LINE> self.inner = error
Defines an error when creating an extension object.
62598fb9f548e778e596b6f2
class Square: <NEW_LINE> <INDENT> def __init__(self, size): <NEW_LINE> <INDENT> __size = 0 <NEW_LINE> self.__size = size
define class square
62598fb997e22403b383b053
class MyRound(torch.autograd.Function): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def forward(ctx, input): <NEW_LINE> <INDENT> return torch.round(input) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def backward(ctx, grad_output): <NEW_LINE> <INDENT> return grad_output
default round function available to use in pytorch forward|backward module functions
62598fb910dbd63aa1c70d06
class Meta: <NEW_LINE> <INDENT> model = Author <NEW_LINE> fields = ('name',)
AuthorSerializer Meta.
62598fb9ad47b63b2c5a79a1
class AMQPAgent(): <NEW_LINE> <INDENT> def __init__(self, name, host, msg=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.host = host <NEW_LINE> self.msg = msg <NEW_LINE> <DEDENT> def send(self,msgQueue,msg): <NEW_LINE> <INDENT> cParams = pika.ConnectionParameters(host=self.host) <NEW_LINE> connection = pika.BlockingConnection(cParams) <NEW_LINE> channel = connection.channel() <NEW_LINE> channel.queue_declare(queue=msgQueue) <NEW_LINE> print(datetime.datetime.now().strftime('%H:%M:%S.%f') + ' ' + self.name +" Sending \t %r" % json.dumps(msg)) <NEW_LINE> channel.basic_publish(exchange='', routing_key=msgQueue, body=json.dumps(msg) ) <NEW_LINE> connection.close() <NEW_LINE> <DEDENT> def callback(self, ch, method, properties, body): <NEW_LINE> <INDENT> print(datetime.datetime.now().strftime('%H:%M:%S.%f') + ' ' + self.name +" Received \t%r" % body) <NEW_LINE> self.msg = json.loads(body) <NEW_LINE> ch.stop_consuming() <NEW_LINE> <DEDENT> def receive(self,msgQueue, callbackF): <NEW_LINE> <INDENT> cParams = pika.ConnectionParameters(host=self.host) <NEW_LINE> connection = pika.BlockingConnection(cParams) <NEW_LINE> channel = connection.channel() <NEW_LINE> channel.queue_declare(queue=msgQueue) <NEW_LINE> channel.basic_consume(callbackF, queue=msgQueue, no_ack=True) <NEW_LINE> channel.start_consuming() <NEW_LINE> connection.close()
Can send and receive msgs, init with host string and msg format uses json dumps and loads to send/receive native python objects
62598fb9ec188e330fdf89de
class Kitchen(Base): <NEW_LINE> <INDENT> __tablename__ = 'kitchen' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> user_id = Column(Integer, ForeignKey('users.id')) <NEW_LINE> ingredient_id = Column(Integer, ForeignKey('ingredients.id'))
What ingredients a user has
62598fb9a8370b77170f052c
class Synonyms(): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def is_synonym_throw(cls, name): <NEW_LINE> <INDENT> syn = False <NEW_LINE> if name in (Global.THROW, Global.OPEN, Global.ON, Global.ACTIVATE, "1"): <NEW_LINE> <INDENT> syn = True <NEW_LINE> <DEDENT> return syn <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def is_synonym_close(cls, name): <NEW_LINE> <INDENT> syn = False <NEW_LINE> if name in (Global.CLOSE, Global.OFF, Global.DEACTIVATE, "0"): <NEW_LINE> <INDENT> syn = True <NEW_LINE> <DEDENT> return syn <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def desired_to_reported(cls, desired): <NEW_LINE> <INDENT> reported = desired <NEW_LINE> if desired == Global.THROW: <NEW_LINE> <INDENT> reported = Global.THROWN <NEW_LINE> <DEDENT> if desired == Global.CLOSE: <NEW_LINE> <INDENT> reported = Global.CLOSED <NEW_LINE> <DEDENT> if desired == Global.OPEN: <NEW_LINE> <INDENT> reported = Global.OPENED <NEW_LINE> <DEDENT> if desired == Global.ACTIVATE: <NEW_LINE> <INDENT> reported = Global.ACTIVATED <NEW_LINE> <DEDENT> if desired == Global.DEACTIVATE: <NEW_LINE> <INDENT> reported = Global.DEACTIVATED <NEW_LINE> <DEDENT> return reported
help class for synonyms of global terms
62598fb9be383301e025394a
class CorrelationStats(DistanceMatrixStats): <NEW_LINE> <INDENT> @property <NEW_LINE> def DistanceMatrices(self): <NEW_LINE> <INDENT> return super(CorrelationStats, self).DistanceMatrices <NEW_LINE> <DEDENT> @DistanceMatrices.setter <NEW_LINE> def DistanceMatrices(self, dms): <NEW_LINE> <INDENT> DistanceMatrixStats.DistanceMatrices.fset(self, dms) <NEW_LINE> if len(dms) < 1: <NEW_LINE> <INDENT> raise ValueError("Must provide at least one distance matrix.") <NEW_LINE> <DEDENT> size = dms[0].num_samples <NEW_LINE> sample_ids = dms[0].sample_ids <NEW_LINE> for dm in dms: <NEW_LINE> <INDENT> if dm.num_samples != size: <NEW_LINE> <INDENT> raise ValueError("All distance matrices must have the same " "number of rows and columns.") <NEW_LINE> <DEDENT> if dm.sample_ids != sample_ids: <NEW_LINE> <INDENT> raise ValueError("All distance matrices must have matching " "sample IDs.")
Base class for distance matrix correlation statistical methods. It is subclassed by correlation methods such as partial Mantel and Mantel that compare two or more distance matrices. A valid instance of CorrelationStats must have at least one distance matrix, and all distance matrices must have matching dimensions and sample IDs (i.e. matching row/column labels). This check is in place to prevent the accidental comparison on two distance matrices that have sample IDs in different orders. Essentially, all of the distance matrices must be "compatible". Users of this class can optionally specify the number of allowable distance matrices and their minimum allowable size (the default is no restrictions on either of these).
62598fb95fc7496912d48322
class OperatorPDDiag(OperatorPDDiagBase): <NEW_LINE> <INDENT> def __init__(self, diag, verify_pd=True, name="OperatorPDDiag"): <NEW_LINE> <INDENT> super(OperatorPDDiag, self).__init__( diag, verify_pd=verify_pd, name=name) <NEW_LINE> <DEDENT> def _batch_log_det(self): <NEW_LINE> <INDENT> return math_ops.reduce_sum( math_ops.log(self._diag), reduction_indices=[-1]) <NEW_LINE> <DEDENT> def _inv_quadratic_form_on_vectors(self, x): <NEW_LINE> <INDENT> return self._iqfov_via_solve(x) <NEW_LINE> <DEDENT> def _batch_matmul(self, x, transpose_x=False): <NEW_LINE> <INDENT> if transpose_x: <NEW_LINE> <INDENT> x = array_ops.matrix_transpose(x) <NEW_LINE> <DEDENT> diag_mat = array_ops.expand_dims(self._diag, -1) <NEW_LINE> return diag_mat * x <NEW_LINE> <DEDENT> def _batch_sqrt_matmul(self, x, transpose_x=False): <NEW_LINE> <INDENT> if transpose_x: <NEW_LINE> <INDENT> x = array_ops.matrix_transpose(x) <NEW_LINE> <DEDENT> diag_mat = array_ops.expand_dims(self._diag, -1) <NEW_LINE> return math_ops.sqrt(diag_mat) * x <NEW_LINE> <DEDENT> def _batch_solve(self, rhs): <NEW_LINE> <INDENT> diag_mat = array_ops.expand_dims(self._diag, -1) <NEW_LINE> return rhs / diag_mat <NEW_LINE> <DEDENT> def _batch_sqrt_solve(self, rhs): <NEW_LINE> <INDENT> diag_mat = array_ops.expand_dims(self._diag, -1) <NEW_LINE> return rhs / math_ops.sqrt(diag_mat) <NEW_LINE> <DEDENT> def _to_dense(self): <NEW_LINE> <INDENT> return array_ops.matrix_diag(self._diag) <NEW_LINE> <DEDENT> def _sqrt_to_dense(self): <NEW_LINE> <INDENT> return array_ops.matrix_diag(math_ops.sqrt(self._diag)) <NEW_LINE> <DEDENT> def _add_to_tensor(self, mat): <NEW_LINE> <INDENT> mat_diag = array_ops.matrix_diag_part(mat) <NEW_LINE> new_diag = self._diag + mat_diag <NEW_LINE> return array_ops.matrix_set_diag(mat, new_diag)
Class representing a (batch) of positive definite matrices `A`. This class provides access to functions of a batch of symmetric positive definite (PD) matrices `A` in `R^{k x k}`. In this case, `A` is diagonal and is defined by a provided tensor `diag`, `A_{ii} = diag[i]`. Determinants, solves, and storage are `O(k)`. In practice, this operator represents a (batch) matrix `A` with shape `[N1,...,Nn, k, k]` for some `n >= 0`. The first `n` indices designate a batch member. For every batch member `(i1,...,ib)`, `A[i1,...,ib, : :]` is a `k x k` matrix. For example, ```python distributions = tf.contrib.distributions diag = [1.0, 2.0] operator = OperatorPDDiag(diag) operator.det() # ==> (1 * 2) # Compute the quadratic form x^T A^{-1} x for vector x. x = [1.0, 2.0] operator.inv_quadratic_form_on_vectors(x) # Matrix multiplication by the square root, S w, with A = S S^T. # Recall A is diagonal, and so then is S, with S_{ij} = sqrt(A_{ij}). # If w is iid normal, S w has covariance A. w = [[1.0], [2.0]] operator.sqrt_matmul(w) ``` The above three methods, `log_det`, `inv_quadratic_form_on_vectors`, and `sqrt_matmul` provide "all" that is necessary to use a covariance matrix in a multi-variate normal distribution. See the class `MultivariateNormalDiag`.
62598fb93d592f4c4edbb00c
class ItemAddBlocks(Item): <NEW_LINE> <INDENT> def __init__(self, x, y, level): <NEW_LINE> <INDENT> Item.__init__(self, x, y) <NEW_LINE> self.image = Assets.itemAddBlocks <NEW_LINE> self.level = level <NEW_LINE> <DEDENT> def affect(self, level): <NEW_LINE> <INDENT> level.place_random_blocks() <NEW_LINE> <DEDENT> def on_collect(self, paddle): <NEW_LINE> <INDENT> self.level.disturb_player(self.affect, self.level.player_color, True)
Add Blocks Item. Places additional blocks into enemy's game
62598fb955399d3f05626661
class UIInterfaceTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.module = UIModule() <NEW_LINE> self.interface = UIInterface(self.module) <NEW_LINE> <DEDENT> def _check_dbus_property(self, *args, **kwargs): <NEW_LINE> <INDENT> check_dbus_property( USER_INTERFACE, self.interface, *args, **kwargs ) <NEW_LINE> <DEDENT> def test_default_password_policies(self): <NEW_LINE> <INDENT> policies = PasswordPolicy.from_structure_dict( self.interface.PasswordPolicies) <NEW_LINE> expected_names = {"root", "user", "luks"} <NEW_LINE> assert policies.keys() == expected_names <NEW_LINE> for name in expected_names: <NEW_LINE> <INDENT> policy = policies[name] <NEW_LINE> expected_policy = PasswordPolicy.from_defaults(name) <NEW_LINE> assert compare_data(policy, expected_policy) <NEW_LINE> <DEDENT> <DEDENT> def test_password_policies_property(self): <NEW_LINE> <INDENT> policy = { "min-quality": get_variant(UInt16, 10), "min-length": get_variant(UInt16, 20), "allow-empty": get_variant(Bool, True), "is-strict": get_variant(Bool, False) } <NEW_LINE> self._check_dbus_property( "PasswordPolicies", {"luks": policy} )
Test DBus interface of the user interface module.
62598fb967a9b606de54611f
class BayesModel(Model): <NEW_LINE> <INDENT> def __init__(self, corpus): <NEW_LINE> <INDENT> self.__bigram_vectorizer = TfidfVectorizer(ngram_range=(2, 2), analyzer='word', stop_words='english') <NEW_LINE> self.__bigrams = self.__bigram_vectorizer.fit_transform(corpus) <NEW_LINE> print (self.__bigrams.shape) <NEW_LINE> <DEDENT> def train(self, inputs, targets, **options): <NEW_LINE> <INDENT> self.__label_encoder = LabelEncoder() <NEW_LINE> self.__train_labels = self.__label_encoder.fit_transform(targets) <NEW_LINE> X = self.__bigram_vectorizer.transform(inputs) <NEW_LINE> self.__model = MultinomialNB(alpha=0.20000000000000001).fit(X, self.__train_labels) <NEW_LINE> <DEDENT> def parameter_tuning(self, inputs, targets, **options): <NEW_LINE> <INDENT> self.__label_encoder = LabelEncoder() <NEW_LINE> self.__train_labels = self.__label_encoder.fit_transform(targets) <NEW_LINE> X = self.__bigram_vectorizer.transform(inputs) <NEW_LINE> kf = StratifiedKFold(n_splits=5, shuffle=False, random_state=None) <NEW_LINE> evaluation = cross_val_score(self.__model, X, self.__train_labels, cv=kf) <NEW_LINE> print(evaluation) <NEW_LINE> rmses = [np.sqrt(np.absolute(mse)) for mse in evaluation] <NEW_LINE> avg_rmse = np.mean(rmses) <NEW_LINE> std_rmse = np.std(rmses) <NEW_LINE> print(avg_rmse) <NEW_LINE> print(std_rmse) <NEW_LINE> param_grid = {"alpha": np.array([1, 0.1, 0.01, 0.2, 0.02, 0.3, 0.03, 0.4, 0.04, 0.5, 0.05, 0.6, 0.06, 0.7, 0.07, 0.8, 0.08, 0.9, 0.09, 0])} <NEW_LINE> gcv = GridSearchCV(self.__model, param_grid, cv=kf) <NEW_LINE> gcv.fit(X, self.__train_labels) <NEW_LINE> print("Best alpha parameter" + str(gcv.best_params_)) <NEW_LINE> print("Best alpha score" + str(gcv.best_score_)) <NEW_LINE> <DEDENT> def classify(self, inputs): <NEW_LINE> <INDENT> X = self.__bigram_vectorizer.transform(inputs) <NEW_LINE> prediction = self.__model.predict(X) <NEW_LINE> return self.__label_encoder.inverse_transform(prediction) <NEW_LINE> <DEDENT> def eval(self, inputs, targets): <NEW_LINE> <INDENT> predicted = self.classify(inputs) <NEW_LINE> return accuracy_score(targets, predicted)
Bayes Model
62598fb9851cf427c66b8404
class Kernel(BuildTask): <NEW_LINE> <INDENT> @property <NEW_LINE> def project(self): <NEW_LINE> <INDENT> return 'kernel' <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return 'https://www.kernel.org/pub/linux/kernel/v3.x/linux-3.11.1.tar.xz' <NEW_LINE> <DEDENT> def compile(self, j): <NEW_LINE> <INDENT> with cd(self.workdir_src): <NEW_LINE> <INDENT> if not self.mudlark: <NEW_LINE> <INDENT> sh.make('O=%s' % self.workdir_dst, 'clean', _out = self.log) <NEW_LINE> <DEDENT> sh.cp(resource('kernel.config'), mkpath(self.workdir_dst, '.config')) <NEW_LINE> sh.make('O=%s' % self.workdir_dst, 'vmlinux', 'modules', '-j4', _out = self.log) <NEW_LINE> <DEDENT> <DEDENT> def install(self, j): <NEW_LINE> <INDENT> with cd(self.workdir_src): <NEW_LINE> <INDENT> sh.make('O=%s' % self.workdir_dst, 'modules_install', _env = {'INSTALL_MOD_PATH': self.target}, _out = self.log) <NEW_LINE> <DEDENT> <DEDENT> def create(self, initramfs, target): <NEW_LINE> <INDENT> with cd(self.workdir_src): <NEW_LINE> <INDENT> sh.make('O=%s' % self.workdir_dst, 'bzImage', '-j4', _out = self.log) <NEW_LINE> <DEDENT> with cd(self.workdir_dst): <NEW_LINE> <INDENT> cp('arch/x86/boot/bzImage', 'arch/x86/boot/bzImage.bak') <NEW_LINE> <DEDENT> with cd(self.workdir_src): <NEW_LINE> <INDENT> sh.make('O=%s' % self.workdir_dst, 'CONFIG_INITRAMFS_SOURCE=%s' % initramfs, 'bzImage', '-j4', _out = self.log) <NEW_LINE> <DEDENT> with cd(self.workdir_dst): <NEW_LINE> <INDENT> cp('arch/x86_64/boot/bzImage', target)
Download and compile kernel
62598fb9a219f33f346c6954
class PostListView(LoginRequiredMixin, ListView): <NEW_LINE> <INDENT> model = models.Post <NEW_LINE> template_name = 'blog/index.html' <NEW_LINE> paginate_by = 10 <NEW_LINE> context_object_name = 'posts' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> queryset = super().get_queryset().filter(Q(is_public=True) | Q(user=self.request.user)) <NEW_LINE> form = forms.PostSearchForm(self.request.GET or None) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> queryset = form.filtered_queryset(queryset) <NEW_LINE> <DEDENT> queryset = queryset.order_by('-updated_at').prefetch_related('tags') <NEW_LINE> return queryset <NEW_LINE> <DEDENT> def get_context_data(self, *args, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(*args, **kwargs) <NEW_LINE> context['search_form'] = forms.PostSearchForm(self.request.GET or None) <NEW_LINE> return context
public blog list
62598fb960cbc95b0636448d
class OrderZip(OrderApiV1Mixin, OrderCsv): <NEW_LINE> <INDENT> def get(self, iuid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> order = self.get_order(iuid) <NEW_LINE> <DEDENT> except ValueError as msg: <NEW_LINE> <INDENT> raise tornado.web.HTTPError(404, reason=str(msg)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.check_readable(order) <NEW_LINE> <DEDENT> except ValueError as msg: <NEW_LINE> <INDENT> raise tornado.web.HTTPError(403, reason=str(msg)) <NEW_LINE> <DEDENT> zip_io = io.BytesIO() <NEW_LINE> with zipfile.ZipFile(zip_io, 'w') as writer: <NEW_LINE> <INDENT> name = order.get('identifier') or order['_id'] <NEW_LINE> csvwriter = self.write_order(order, writer=utils.CsvWriter('Order')) <NEW_LINE> writer.writestr(name + '.csv', csvwriter.getvalue()) <NEW_LINE> xlsxwriter = self.write_order(order, writer=utils.XlsxWriter('Order')) <NEW_LINE> writer.writestr(name + '.xlsx', xlsxwriter.getvalue()) <NEW_LINE> writer.writestr(name + '.json', json.dumps(self.get_order_json(order, full=True))) <NEW_LINE> for filename in sorted(order.get('_attachments', [])): <NEW_LINE> <INDENT> outfile = self.db.get_attachment(order, filename) <NEW_LINE> writer.writestr(filename, outfile.read()) <NEW_LINE> <DEDENT> <DEDENT> self.write(zip_io.getvalue()) <NEW_LINE> self.set_header('Content-Type', constants.ZIP_MIME) <NEW_LINE> filename = order.get('identifier') or order['_id'] <NEW_LINE> self.set_header('Content-Disposition', 'attachment; filename="%s.zip"' % filename)
Return a ZIP file containing CSV, XLSX, JSON and files for the order.
62598fb921bff66bcd722db7
class DetRootN_Exp(Expression): <NEW_LINE> <INDENT> def __init__(self, exp): <NEW_LINE> <INDENT> if exp.size[0] != exp.size[1]: <NEW_LINE> <INDENT> raise TypeError('Matrix must be square') <NEW_LINE> <DEDENT> Expression.__init__(self, "n-th Root of a Determinant", glyphs.power(glyphs.det(exp.string), glyphs.div(1, exp.size[0]))) <NEW_LINE> self.exp = exp <NEW_LINE> self.dim = exp.size[0] <NEW_LINE> <DEDENT> def eval(self, ind=None): <NEW_LINE> <INDENT> val = self.exp.eval(ind) <NEW_LINE> if not isinstance(val, cvx.base.matrix): <NEW_LINE> <INDENT> val = cvx.matrix(val) <NEW_LINE> <DEDENT> return (np.linalg.det(np.matrix(val)))**(1. / self.dim) <NEW_LINE> <DEDENT> @_scalar_argument <NEW_LINE> def __gt__(self, exp): <NEW_LINE> <INDENT> if isinstance(exp, AffinExp): <NEW_LINE> <INDENT> return DetRootNConstraint(self, exp) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented
A class storing the :math:`n`-th root of the determinant of a positive semidefinite matrix. Use the function :func:`picos.detrootn <picos.tools.detrootn>` to create an instance of this class. Note that the matrix :math:`X` is forced to be positive semidefinite when a constraint of the form ``t < pic.detrootn(X)`` is added. **Overloaded operator** :``>``: greater **or equal** than (a scalar affine expression)
62598fb9236d856c2adc94e7
class CategoryAdmin(object): <NEW_LINE> <INDENT> list_display = ['name', 'rank', 'create_time', 'update_time'] <NEW_LINE> search_fields = ['name', 'rank'] <NEW_LINE> list_filter = ['name', 'rank', 'create_time', 'update_time']
后台-文章类型
62598fb999cbb53fe6831027
class Driver_2: <NEW_LINE> <INDENT> def __init__(self, port1, port2): <NEW_LINE> <INDENT> self.L = SpeedCon(port1, True) <NEW_LINE> self.R = SpeedCon(port2, True) <NEW_LINE> self.vicList = [self.L, self.R] <NEW_LINE> print("Two-wheeled driver on ports " + str(port1) + " and " + str(port2)) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> print("stop called") <NEW_LINE> for motor in self.vicList: <NEW_LINE> <INDENT> motor.set_speed(0) <NEW_LINE> <DEDENT> <DEDENT> def tankDriveRaw(self, left, right): <NEW_LINE> <INDENT> self.L.set_speed(left) <NEW_LINE> self.R.set_speed(-right) <NEW_LINE> print ("tankDriveRaw at " + str(left) + " and " + str(right)) <NEW_LINE> <DEDENT> def arcadeDriveRaw(self, turn, power): <NEW_LINE> <INDENT> left = power + turn <NEW_LINE> right = power - turn <NEW_LINE> print("arcadeDriveRaw at " + str(power) + " and " + str(turn)) <NEW_LINE> self.tankDriveRaw(left, right) <NEW_LINE> <DEDENT> def tankDrive(self, ls, rs): <NEW_LINE> <INDENT> return self.tankDriveRaw(ls.getStickAxes()[1], rs.getStickAxes()[1]) <NEW_LINE> <DEDENT> def arcadeDrive(self, stick): <NEW_LINE> <INDENT> return self.arcadeDriveRaw(stick.getStickAxes()[0]/2, stick.getStickAxes()[1]/2)
Driver class for two motor robots
62598fb9283ffb24f3cf39d2
class GetViewMapGradientNormF0D: <NEW_LINE> <INDENT> def __init__(self, level: int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __call__(self, it: 'freestyle.types.Interface0DIterator') -> float: <NEW_LINE> <INDENT> pass
Class hierarchy: freestyle.types.UnaryFunction0D > freestyle.types.UnaryFunction0DFloat > GetViewMapGradientNormF0D
62598fb9ad47b63b2c5a79a3
class TemplateAdapter(object): <NEW_LINE> <INDENT> def __init__(self, target, logger): <NEW_LINE> <INDENT> self.target = target <NEW_LINE> self.logger = logger <NEW_LINE> <DEDENT> def get_auth_token(self, user, proxies): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = self.target.get_host() + BasicConstants.VERIFY_TARGET_URL <NEW_LINE> req = requests.post(url, json=user.get_params(), verify=self.target.verify_ssl, proxies=get_proxies(proxies, url)) <NEW_LINE> if req.status_code != requests.codes.ok: <NEW_LINE> <INDENT> req.raise_for_status() <NEW_LINE> <DEDENT> self.logger.debug('get_auth_token returned ' + req.text) <NEW_LINE> return TemplateToken(req.json()) <NEW_LINE> <DEDENT> except HTTPError as e: <NEW_LINE> <INDENT> raise TemplateError(req.status_code, str(e.message), req.text) <NEW_LINE> <DEDENT> except (ConnectTimeout, ReadTimeout, Timeout, ConnectionError) as e: <NEW_LINE> <INDENT> raise TemplateError(503, "Connection failed", e.message) <NEW_LINE> <DEDENT> <DEDENT> def get_template(self, token, template_id, proxies): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = self.target.get_host() + BasicConstants.ACTIVITY_1_URL + str(int(template_id)) <NEW_LINE> req = requests.get(url, headers=token.get_auth_header(), verify=self.target.verify_ssl, proxies=get_proxies(proxies, url)) <NEW_LINE> if req.status_code != requests.codes.ok: <NEW_LINE> <INDENT> req.raise_for_status() <NEW_LINE> <DEDENT> self.logger.debug('get_template returned ' + req.text) <NEW_LINE> return req.json() <NEW_LINE> <DEDENT> except HTTPError as e: <NEW_LINE> <INDENT> raise TemplateError(req.status_code, str(e.message), req.text) <NEW_LINE> <DEDENT> except (ConnectTimeout, ReadTimeout, Timeout, ConnectionError) as e: <NEW_LINE> <INDENT> raise TemplateError(503, "Connection failed", e.message) <NEW_LINE> <DEDENT> <DEDENT> def create_template(self, token, template_name, params, proxies): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = self.target.get_host() + BasicConstants.ACTIVITY_2_URL + template_name <NEW_LINE> req = requests.post(url, json=params.get_params(), headers=token.get_auth_header(), verify=self.target.verify_ssl, proxies=get_proxies(proxies, url)) <NEW_LINE> if req.status_code != requests.codes.ok: <NEW_LINE> <INDENT> req.raise_for_status() <NEW_LINE> <DEDENT> self.logger.debug('create_template returned ' + req.text) <NEW_LINE> return req.json() <NEW_LINE> <DEDENT> except HTTPError as e: <NEW_LINE> <INDENT> raise TemplateError(req.status_code, str(e.message), req.text) <NEW_LINE> <DEDENT> except (ConnectTimeout, ReadTimeout, Timeout, ConnectionError) as e: <NEW_LINE> <INDENT> raise TemplateError(503, "Connection failed", e.message)
The Template Adapter class.
62598fb97c178a314d78d5ed
class SDPD(Interaction): <NEW_LINE> <INDENT> def __init__(): <NEW_LINE> <INDENT> pass
Compute SDPD interaction with angular momentum conservation. Must be used together with :any:`Density` interaction with the same density kernel. The available density kernels are listed in :any:`Density`. The available equations of state (EOS) are: Linear equation of state: .. math:: p(\rho) = c^2 \rho where :math:`c` is the speed of sound, Quasi incompressible EOS: .. math:: p(\rho) = p_0 \left[ \left( \frac {\rho}{\rho_r} \right)^\gamma - 1 \right], where :math:`p_0`, :math:`\rho_r` and :math:`\gamma = 7` are parameters to be fitted to the desired fluid.
62598fb9460517430c432105
class post_get_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.STRUCT, 'success', (Post, Post.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = Post() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('post_get_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success
62598fb93617ad0b5ee06296
class FailView(utils.CSRFExempt, generic.TemplateView): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> payment_no = utils.get_request_data(request)['LMI_PAYMENT_NO'] <NEW_LINE> try: <NEW_LINE> <INDENT> invoice = Invoice.objects.get(number=payment_no) <NEW_LINE> logger.info( u'Invoice {0} fail page visited'.format(invoice.number)) <NEW_LINE> <DEDENT> except Invoice.DoesNotExist: <NEW_LINE> <INDENT> invoice = None <NEW_LINE> logger.error( u'Invoice {0} DoesNotExist'.format(payment_no)) <NEW_LINE> <DEDENT> signals.fail_visited.send( sender=self, data=utils.get_request_data(request), invoice=invoice) <NEW_LINE> return super(FailView, self).get(request) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> return self.get(request)
Страница неуспешного возврата. Предназначена исклчительно для уведомления пользователя об неудачном завершении операции.
62598fb92c8b7c6e89bd3914
class XTreeTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_find_tiebreaker(self): <NEW_LINE> <INDENT> final_actions = [((0, 0), (1, 1)), ((1, 1), (2, 2))] <NEW_LINE> self.assertEqual(((0, 0), (1, 1)), xtree.find_tiebreaker(final_actions)) <NEW_LINE> final_actions = [((0, 2), (1, 1)), ((0, 1), (2, 2))] <NEW_LINE> self.assertEqual(((0, 1), (2, 2)), xtree.find_tiebreaker(final_actions)) <NEW_LINE> <DEDENT> def test_find_if_valid_move(self): <NEW_LINE> <INDENT> state = { "players": [ { "color": "red", "score": 10, "places": [[0, 0]] }, { "color": "black", "score": 1, "places": [[0, 2], [0, 1]] } ], "board": [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4], [3, 3, 3, 3]] } <NEW_LINE> state = THHelper.create_state(state) <NEW_LINE> state.move_penguin(PlayerColor.RED, (0, 0), (3, 3)) <NEW_LINE> tree = FishGameTree(state) <NEW_LINE> neighbors = THHelper.find_coord_neighbors([3, 3]) <NEW_LINE> self.assertListEqual([((4, 0) ,(3, 1)), ((2, 0), (3, 1))], xtree.find_if_valid_move_from_state(tree, neighbors))
Test our test harness for Milestone 4
62598fb9ec188e330fdf89e0
class SourceData(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'source_data' <NEW_LINE> __mapper_args__ = { 'extension': BaseExtension(), } <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> method = db.Column(db.Text, index=True) <NEW_LINE> route = db.Column(db.Text, index=True) <NEW_LINE> payload = db.Column(postgresql.JSONB) <NEW_LINE> payload_hash = db.Column(db.Text, index=True) <NEW_LINE> response = db.Column(postgresql.JSONB) <NEW_LINE> status_code = db.Column(db.Integer) <NEW_LINE> created_at = db.Column(db.DateTime, default=datetime.utcnow()) <NEW_LINE> updated_at = db.Column(db.DateTime) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<SourceData {}:{}>'.format(self.id,self.route) <NEW_LINE> <DEDENT> def before_insert(self): <NEW_LINE> <INDENT> payload_hash = hashlib.sha1(self.payload.encode('utf-8')).hexdigest() <NEW_LINE> if self.query.filter(SourceData.payload_hash == payload_hash).first(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.payload_hash = payload_hash <NEW_LINE> <DEDENT> def before_update(self): <NEW_LINE> <INDENT> pass
Raw data, stored as JSONb. If data already exists, raises SQLAlchemy IntegrityError
62598fb97d43ff24874274ab
@dataclass <NEW_LINE> class Media: <NEW_LINE> <INDENT> title: str <NEW_LINE> url: str <NEW_LINE> format: Format <NEW_LINE> @property <NEW_LINE> def type(self) -> str: <NEW_LINE> <INDENT> if self.format in {Format.PDF, Format.PS}: <NEW_LINE> <INDENT> return f"application/{self.format}" <NEW_LINE> <DEDENT> return "text/html"
Represents a media item.
62598fb9dc8b845886d53708
class TopicTypesListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[TopicTypeInfo]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(TopicTypesListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None)
Result of the List Topic Types operation. :ivar value: A collection of topic types. :vartype value: list[~azure.mgmt.eventgrid.models.TopicTypeInfo]
62598fb9379a373c97d99166
class DocumentNotFound(ESException): <NEW_LINE> <INDENT> pass
Document not found exception. .. note:: When we are indexing files and a document is not found we can decide if we create it or fail.
62598fb944b2445a339b6a1c
class UserInfoView(LoginRequirdeMixin,View): <NEW_LINE> <INDENT> def get(self,request): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> address = Address.objects.get_default_address(user) <NEW_LINE> con = get_redis_connection('default') <NEW_LINE> history_key = 'history_%d'%user.id <NEW_LINE> sku_ids = con.lrange(history_key,0,4) <NEW_LINE> goods_li = [] <NEW_LINE> for id in sku_ids: <NEW_LINE> <INDENT> goods = GoodsSKU.objects.get(id=id) <NEW_LINE> goods_li.append(goods) <NEW_LINE> <DEDENT> context = { 'page': 'user', 'address': address, 'goods_li': goods_li, } <NEW_LINE> return render(request,'user_center_info.html',context)
用户中心-信息页
62598fb95fdd1c0f98e5e0df
class Break(object): <NEW_LINE> <INDENT> def __init__(self, break_type, name, time, image, plugins): <NEW_LINE> <INDENT> self.type = break_type <NEW_LINE> self.name = name <NEW_LINE> self.time = time <NEW_LINE> self.image = image <NEW_LINE> self.plugins = plugins <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Break: {{name: "{}", type: {}, time: {}}}\n'.format(self.name, self.type, self.time) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def is_long_break(self): <NEW_LINE> <INDENT> return self.type == BreakType.LONG_BREAK <NEW_LINE> <DEDENT> def is_short_break(self): <NEW_LINE> <INDENT> return self.type == BreakType.SHORT_BREAK <NEW_LINE> <DEDENT> def plugin_enabled(self, plugin_id, is_plugin_enabled): <NEW_LINE> <INDENT> if self.plugins: <NEW_LINE> <INDENT> return plugin_id in self.plugins <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return is_plugin_enabled
An entity class which represents a break.
62598fb9a219f33f346c6956
class ProductVariantCreateForm(ModelForm): <NEW_LINE> <INDENT> def __init__(self, options=None, product=None, *args, **kwargs): <NEW_LINE> <INDENT> super(ProductVariantCreateForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['slug'].required = False <NEW_LINE> self.options = options <NEW_LINE> self.product = product <NEW_LINE> <DEDENT> def prepare_slug(self, slug): <NEW_LINE> <INDENT> for option in self.options: <NEW_LINE> <INDENT> property_group_id, property_id, option_id = option.split("|") <NEW_LINE> o = PropertyOption.objects.get(pk=option_id) <NEW_LINE> if slug: <NEW_LINE> <INDENT> slug += "-" <NEW_LINE> <DEDENT> slug += slugify(o.name) <NEW_LINE> <DEDENT> product_slug = self.product.slug <NEW_LINE> if product_slug is None: <NEW_LINE> <INDENT> product_slug = '' <NEW_LINE> <DEDENT> if product_slug + slug.replace('-', '') == '': <NEW_LINE> <INDENT> slug = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> slug = "%s-%s" % (product_slug, slug) <NEW_LINE> slug = slug.rstrip('-') <NEW_LINE> <DEDENT> slug = slug[:80] <NEW_LINE> new_slug = slug <NEW_LINE> counter = 1 <NEW_LINE> while Product.objects.filter(slug=new_slug).exists(): <NEW_LINE> <INDENT> new_slug = '%s-%s' % (slug[:(79 - len(str(counter)))], counter) <NEW_LINE> counter += 1 <NEW_LINE> <DEDENT> slug = new_slug <NEW_LINE> return slug <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> cleaned_data = super(ProductVariantCreateForm, self).clean() <NEW_LINE> slug = self.prepare_slug(cleaned_data.get('slug', '')) <NEW_LINE> cleaned_data['slug'] = slug <NEW_LINE> return cleaned_data <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Product <NEW_LINE> fields = ("slug", "name", "price", )
Form used to create product variant for specific set of options
62598fb9ff9c53063f51a79e
@dataclass <NEW_LINE> class PrivacyIdCountParams: <NEW_LINE> <INDENT> noise_kind: NoiseKind <NEW_LINE> max_partitions_contributed: int <NEW_LINE> partition_extractor: Callable <NEW_LINE> budget_weight: float = 1 <NEW_LINE> public_partitions: Union[Iterable, 'PCollection', 'RDD'] = None
Specifies parameters for differentially-private privacy id count calculation. Args: noise_kind: The type of noise to use for the DP calculations. max_partitions_contributed: A bound on the number of partitions to which one unit of privacy (e.g., a user) can contribute. budget_weight: Relative weight of the privacy budget allocated for this operation. partition_extractor: A function which, given an input element, will return its partition id. public_partitions: A collection of partition keys that will be present in the result. Optional.
62598fb9851cf427c66b8406
class ComputePlanSpec(_BaseComputePlanSpec): <NEW_LINE> <INDENT> tag: Optional[str] <NEW_LINE> clean_models: Optional[bool] <NEW_LINE> metadata: Optional[Dict[str, str]] <NEW_LINE> type_: typing.ClassVar[Type] = Type.ComputePlan
Specification for creating a compute plan
62598fb95fdd1c0f98e5e0e0
class AssignmentStatement(BaseCQLStatement): <NEW_LINE> <INDENT> def __init__(self, table, assignments=None, consistency=None, where=None, ttl=None): <NEW_LINE> <INDENT> super(AssignmentStatement, self).__init__( table, consistency=consistency, where=where, ) <NEW_LINE> self.ttl = ttl <NEW_LINE> self.assignments = [] <NEW_LINE> for assignment in assignments or []: <NEW_LINE> <INDENT> self.add_assignment_clause(assignment) <NEW_LINE> <DEDENT> <DEDENT> def update_context_id(self, i): <NEW_LINE> <INDENT> super(AssignmentStatement, self).update_context_id(i) <NEW_LINE> for assignment in self.assignments: <NEW_LINE> <INDENT> assignment.set_context_id(self.context_counter) <NEW_LINE> self.context_counter += assignment.get_context_size() <NEW_LINE> <DEDENT> <DEDENT> def add_assignment_clause(self, clause): <NEW_LINE> <INDENT> if not isinstance(clause, AssignmentClause): <NEW_LINE> <INDENT> raise StatementException("only instances of AssignmentClause can be added to statements") <NEW_LINE> <DEDENT> clause.set_context_id(self.context_counter) <NEW_LINE> self.context_counter += clause.get_context_size() <NEW_LINE> self.assignments.append(clause) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_empty(self): <NEW_LINE> <INDENT> return len(self.assignments) == 0 <NEW_LINE> <DEDENT> def get_context(self): <NEW_LINE> <INDENT> ctx = super(AssignmentStatement, self).get_context() <NEW_LINE> for clause in self.assignments: <NEW_LINE> <INDENT> clause.update_context(ctx) <NEW_LINE> <DEDENT> return ctx
value assignment statements
62598fb9f548e778e596b6f6
class PanelSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Panel <NEW_LINE> fields = ('id', 'brand', 'serial', 'latitude', 'longitude')
Panel Serializer.
62598fb93317a56b869be5f6
class ContainerBrokerMigrationMixin(object): <NEW_LINE> <INDENT> class OverrideCreateShardRangesTable(object): <NEW_LINE> <INDENT> def __init__(self, func): <NEW_LINE> <INDENT> self.func = func <NEW_LINE> <DEDENT> def __get__(self, obj, obj_type): <NEW_LINE> <INDENT> if inspect.stack()[1][3] == '_initialize': <NEW_LINE> <INDENT> return lambda *a, **kw: None <NEW_LINE> <DEDENT> return self.func.__get__(obj, obj_type) <NEW_LINE> <DEDENT> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self._imported_create_object_table = ContainerBroker.create_object_table <NEW_LINE> ContainerBroker.create_object_table = prespi_create_object_table <NEW_LINE> self._imported_create_container_info_table = ContainerBroker.create_container_info_table <NEW_LINE> ContainerBroker.create_container_info_table = premetadata_create_container_info_table <NEW_LINE> self._imported_create_policy_stat_table = ContainerBroker.create_policy_stat_table <NEW_LINE> ContainerBroker.create_policy_stat_table = lambda *args: None <NEW_LINE> self._imported_create_shard_range_table = ContainerBroker.create_shard_range_table <NEW_LINE> if 'shard_range' not in self.expected_db_tables: <NEW_LINE> <INDENT> ContainerBroker.create_shard_range_table = self.OverrideCreateShardRangesTable( ContainerBroker.create_shard_range_table) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> @contextmanager <NEW_LINE> def old_broker(cls): <NEW_LINE> <INDENT> cls.runTest = lambda *a, **k: None <NEW_LINE> case = cls() <NEW_LINE> case.setUp() <NEW_LINE> try: <NEW_LINE> <INDENT> yield ContainerBroker <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> case.tearDown() <NEW_LINE> <DEDENT> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> ContainerBroker.create_container_info_table = self._imported_create_container_info_table <NEW_LINE> ContainerBroker.create_object_table = self._imported_create_object_table <NEW_LINE> ContainerBroker.create_shard_range_table = self._imported_create_shard_range_table <NEW_LINE> ContainerBroker.create_policy_stat_table = self._imported_create_policy_stat_table
Mixin for running ContainerBroker against databases created with older schemas.
62598fb956ac1b37e630233d
class ChangeBrowserContext: <NEW_LINE> <INDENT> def __init__(self, browser): <NEW_LINE> <INDENT> self.browser = world.browser <NEW_LINE> self.new_browser = browser <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> world.browser = self.new_browser <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> world.browser = self.browser
Switch between multiple browser context, will be used in with statement
62598fb91b99ca400228f5d9
class PhysicalASMixin(object): <NEW_LINE> <INDENT> PHYSICAL_AS_REQUIRED = True <NEW_LINE> @classmethod <NEW_LINE> def args(cls, metadata): <NEW_LINE> <INDENT> super(PhysicalASMixin, cls).args(metadata) <NEW_LINE> metadata.add_requirement("physical_address_space") <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(PhysicalASMixin, self).__init__(*args, **kwargs) <NEW_LINE> self.physical_address_space = self.session.physical_address_space <NEW_LINE> if not self.physical_address_space: <NEW_LINE> <INDENT> self.session.plugins.load_as().GetPhysicalAddressSpace() <NEW_LINE> self.physical_address_space = self.session.physical_address_space <NEW_LINE> <DEDENT> if self.PHYSICAL_AS_REQUIRED and not self.physical_address_space: <NEW_LINE> <INDENT> raise PluginError("Physical address space is not set. " "(Try plugins.load_as)")
A mixin for those plugins which require a valid physical address space. This class ensures a valid physical AS exists or an exception is raised.
62598fb9aad79263cf42e925
class GlobalKeyValueStore(MutableMapping): <NEW_LINE> <INDENT> def __init__(self, qe): <NEW_LINE> <INDENT> self.qe = qe <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for (k, v) in self.qe.global_items(): <NEW_LINE> <INDENT> yield k <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.qe.ctglobal() <NEW_LINE> <DEDENT> def __getitem__(self, k): <NEW_LINE> <INDENT> return self.qe.global_get(k) <NEW_LINE> <DEDENT> def __setitem__(self, k, v): <NEW_LINE> <INDENT> self.qe.global_set(k, v) <NEW_LINE> <DEDENT> def __delitem__(self, k): <NEW_LINE> <INDENT> self.qe.global_del(k)
A dict-like object that keeps its contents in a table. Mostly this is for holding the current branch and revision.
62598fb9498bea3a75a57c74
class GeometrySequence(object): <NEW_LINE> <INDENT> shape_factory = None <NEW_LINE> _geom = None <NEW_LINE> __p__ = None <NEW_LINE> _ndim = None <NEW_LINE> def __init__(self, parent, type): <NEW_LINE> <INDENT> self.shape_factory = type <NEW_LINE> self.__p__ = parent <NEW_LINE> <DEDENT> def _update(self): <NEW_LINE> <INDENT> self._geom = self.__p__._geom <NEW_LINE> self._ndim = self.__p__._ndim <NEW_LINE> <DEDENT> def _get_geom_item(self, i): <NEW_LINE> <INDENT> g = self.shape_factory() <NEW_LINE> g._owned = True <NEW_LINE> g._geom = lgeos.GEOSGetGeometryN(self._geom, i) <NEW_LINE> g._ndim = self._ndim <NEW_LINE> g.__p__ = self <NEW_LINE> return g <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> self._update() <NEW_LINE> for i in range(self.__len__()): <NEW_LINE> <INDENT> yield self._get_geom_item(i) <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> self._update() <NEW_LINE> return lgeos.GEOSGetNumGeometries(self._geom) <NEW_LINE> <DEDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> self._update() <NEW_LINE> M = self.__len__() <NEW_LINE> if i + M < 0 or i >= M: <NEW_LINE> <INDENT> raise IndexError("index out of range") <NEW_LINE> <DEDENT> if i < 0: <NEW_LINE> <INDENT> ii = M + i <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ii = i <NEW_LINE> <DEDENT> return self._get_geom_item(i) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _longest(self): <NEW_LINE> <INDENT> max = 0 <NEW_LINE> for g in iter(self): <NEW_LINE> <INDENT> l = len(g.coords) <NEW_LINE> if l > max: <NEW_LINE> <INDENT> max = l
Iterative access to members of a homogeneous multipart geometry.
62598fb98e7ae83300ee91f1
class GeoDegree(int): <NEW_LINE> <INDENT> __slots__ = [] <NEW_LINE> def __new__(cls, value=None): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return int.__new__(cls, 0) <NEW_LINE> <DEDENT> if isinstance(value, int): <NEW_LINE> <INDENT> if (value <= 90 and value >= -90) or (value <= 180 and value >= -180): <NEW_LINE> <INDENT> return int.__new__(cls, value) <NEW_LINE> <DEDENT> raise ValueError("Value must be in the range: -180,180 or -90,90") <NEW_LINE> <DEDENT> raise ValueError("Value must be an int or a GeoDegree") <NEW_LINE> <DEDENT> def __neg__(self): <NEW_LINE> <INDENT> return GeoDegree(-1*self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%i" % self <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return u"%i\xb0".encode('utf-8') % self
Data class representing a geographic coordinate degree componenent.
62598fb966673b3332c30521
class AristonAquaSwitch(SwitchEntity): <NEW_LINE> <INDENT> def __init__(self, name, device, switch_type): <NEW_LINE> <INDENT> self._api = device.api.ariston_api <NEW_LINE> self._icon = SWITCHES[switch_type][1] <NEW_LINE> self._name = "{} {}".format(name, SWITCHES[switch_type][0]) <NEW_LINE> self._switch_type = switch_type <NEW_LINE> self._state = None <NEW_LINE> self._device = device.device <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return f"{self._name}-{self._switch_type}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return self._icon <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return ( self._api.available and not self._api.sensor_values[self._switch_type][VALUE] is None ) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not self._api.available: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self._api.sensor_values[self._switch_type][VALUE] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> self._api.set_http_data(**{self._switch_type: "true"}) <NEW_LINE> <DEDENT> def turn_off(self, **kwargs): <NEW_LINE> <INDENT> self._api.set_http_data(**{self._switch_type: "false"}) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> return
Switch for Ariston Aqua.
62598fb99f28863672818916
class SocialLoginNoPermissionTests(SocialLoginWrongPermissionsMixin, SocialLoginTestCase): <NEW_LINE> <INDENT> fixtures = ['users_testdata']
User testing the views is not logged and therefore lacking the required permissions.
62598fb91f5feb6acb162d71
class GoodCategoryNestViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = GoodsCategory.objects.all() <NEW_LINE> serializer_class = GoodCategoryNestModelSerializer
list: 商品分类列表数据
62598fb9a05bb46b3848a9bd
class Token: <NEW_LINE> <INDENT> def __init__(self, term, token_value): <NEW_LINE> <INDENT> assert(isinstance(term, unicode)) <NEW_LINE> assert(isinstance(token_value, unicode)) <NEW_LINE> self._term = term <NEW_LINE> self._token_value = token_value <NEW_LINE> <DEDENT> def get_original_value(self): <NEW_LINE> <INDENT> return self._term <NEW_LINE> <DEDENT> def get_token_value(self): <NEW_LINE> <INDENT> return self._token_value
Token that stores original and resulted token values i.e.: term=',', token_value='<[COMMA]>'
62598fb9be383301e025394e
class TestBuildStaticLinks(BuildStaticTestCase, TestDefaults): <NEW_LINE> <INDENT> def run_collectstatic(self): <NEW_LINE> <INDENT> super(TestBuildStaticLinks, self).run_collectstatic(link=True) <NEW_LINE> <DEDENT> def test_links_created(self): <NEW_LINE> <INDENT> self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt')))
Test ``--link`` option for ``collectstatic`` management command. Note that by inheriting ``TestDefaults`` we repeat all the standard file resolving tests here, to make sure using ``--link`` does not change the file-selection semantics.
62598fb94f88993c371f05b6
class AmbilKurs(object): <NEW_LINE> <INDENT> def raw_kurs_bca(self): <NEW_LINE> <INDENT> html = urllib.urlopen('http://www.klikbca.com').read() <NEW_LINE> kurs_data1 = re.findall(re.compile(r"bgcolor=\"#dcdcdc\">\s?(\d+\.\d+)</td>"), html) <NEW_LINE> kurs_data2 = re.findall(re.compile(r"bgcolor=\"#f0f0f0\">\s?(\d+\.\d+)</td>"), html) <NEW_LINE> return kurs_data1, kurs_data2 <NEW_LINE> <DEDENT> def dollar_rupiah(self): <NEW_LINE> <INDENT> kurs_jual = self.raw_kurs_bca()[0][0] <NEW_LINE> kurs_beli = self.raw_kurs_bca()[0][1] <NEW_LINE> return kurs_jual + ' // ' + kurs_beli <NEW_LINE> <DEDENT> def sgd_rupiah(self): <NEW_LINE> <INDENT> kurs_jual = self.raw_kurs_bca()[1][0] <NEW_LINE> kurs_beli = self.raw_kurs_bca()[1][1] <NEW_LINE> return kurs_jual + ' // ' + kurs_beli <NEW_LINE> <DEDENT> def hkd_rupiah(self): <NEW_LINE> <INDENT> kurs_jual = self.raw_kurs_bca()[0][2] <NEW_LINE> kurs_beli = self.raw_kurs_bca()[0][3] <NEW_LINE> return kurs_jual + ' // ' + kurs_beli <NEW_LINE> <DEDENT> def chf_rupiah(self): <NEW_LINE> <INDENT> kurs_jual = self.raw_kurs_bca()[1][2] <NEW_LINE> kurs_beli = self.raw_kurs_bca()[1][3] <NEW_LINE> return kurs_jual + ' // ' + kurs_beli
Modul sederhana untuk menampilkan notifikasi kurs valas pada desktop Ubuntu. Penggunaan: $ python notifikasi_kurs.py
62598fb9f548e778e596b6f7
class ToolParser(argparse.ArgumentParser): <NEW_LINE> <INDENT> class StripTrailingSlash(argparse.Action): <NEW_LINE> <INDENT> def __call__(self, parser, namespace, values, option_string=None): <NEW_LINE> <INDENT> if values.endswith('/'): <NEW_LINE> <INDENT> values = values[:-1] <NEW_LINE> <DEDENT> setattr(namespace, self.dest, values) <NEW_LINE> <DEDENT> <DEDENT> def __init__( self, logger=None, include=None, *args, **kwargs): <NEW_LINE> <INDENT> super(ToolParser, self).__init__(*args, **kwargs) <NEW_LINE> self.include_set = set(include or []) <NEW_LINE> valid = set(['api', 'user', 'password', 'data', 'nocache', 'token']) <NEW_LINE> if self.include_set - valid: <NEW_LINE> <INDENT> raise ValueError( 'Unknown include items: {}'.format(self.include_set - valid)) <NEW_LINE> <DEDENT> if 'api' in self.include_set: <NEW_LINE> <INDENT> self.add_argument( '-a', '--api', help='Base URL of the API (default: http://localhost:8000)', default='http://localhost:8000', action=ToolParser.StripTrailingSlash) <NEW_LINE> <DEDENT> if 'user' in self.include_set: <NEW_LINE> <INDENT> self.add_argument( '-u', '--user', help='Username on API (default: prompt for username)') <NEW_LINE> <DEDENT> if 'password' in self.include_set: <NEW_LINE> <INDENT> self.add_argument( '-p', '--password', help='Password on API (default: prompt for password)') <NEW_LINE> <DEDENT> if logger: <NEW_LINE> <INDENT> self.logger = logger <NEW_LINE> self.add_argument( '-v', '--verbose', action='store_true', help='Print extra debug information') <NEW_LINE> self.add_argument( '-q', '--quiet', action='store_true', help='Only print warnings') <NEW_LINE> <DEDENT> if 'data' in self.include_set: <NEW_LINE> <INDENT> self.add_argument( '-d', '--data', default=_data_dir, action=ToolParser.StripTrailingSlash, help='Output data folder (default: %s)' % _data_dir) <NEW_LINE> <DEDENT> if 'nocache' in self.include_set: <NEW_LINE> <INDENT> self.add_argument( '--no-cache', action='store_false', default=True, dest='use_cache', help='Ignore cache and redownload files') <NEW_LINE> <DEDENT> if 'token' in self.include_set: <NEW_LINE> <INDENT> self.add_argument( '--token', help='Use this OAuth2 token for API access.') <NEW_LINE> <DEDENT> <DEDENT> def parse_args(self, *args, **kwargs): <NEW_LINE> <INDENT> args = super(ToolParser, self).parse_args(*args, **kwargs) <NEW_LINE> if self.logger: <NEW_LINE> <INDENT> verbose = args.verbose <NEW_LINE> quiet = args.quiet <NEW_LINE> console = logging.StreamHandler(sys.stderr) <NEW_LINE> formatter = logging.Formatter('%(levelname)s - %(message)s') <NEW_LINE> fmat = '%(levelname)s - %(message)s' <NEW_LINE> logger_name = 'tools' <NEW_LINE> if quiet: <NEW_LINE> <INDENT> level = logging.WARNING <NEW_LINE> <DEDENT> elif verbose: <NEW_LINE> <INDENT> level = logging.DEBUG <NEW_LINE> logger_name = '' <NEW_LINE> fmat = '%(name)s - %(levelname)s - %(message)s' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> level = logging.INFO <NEW_LINE> <DEDENT> formatter = logging.Formatter(fmat) <NEW_LINE> console.setLevel(level) <NEW_LINE> console.setFormatter(formatter) <NEW_LINE> logger = logging.getLogger(logger_name) <NEW_LINE> logger.setLevel(level) <NEW_LINE> logger.addHandler(console) <NEW_LINE> <DEDENT> return args
Parser with common options.
62598fb90fa83653e46f5034
class Host(): <NEW_LINE> <INDENT> def __init__(self, ip=None, mac=None, man=None, hostname=None, ports=[]): <NEW_LINE> <INDENT> self.ip = ip <NEW_LINE> self.mac = mac <NEW_LINE> self.man = man <NEW_LINE> self.hostname = hostname <NEW_LINE> self.ports = ports <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = self.__repr__() <NEW_LINE> if self.mac: <NEW_LINE> <INDENT> s += '\n {}'.format(self.mac) <NEW_LINE> if self.man: <NEW_LINE> <INDENT> s += ' ({})'.format(self.man) <NEW_LINE> <DEDENT> <DEDENT> if self.ports: <NEW_LINE> <INDENT> s += '\n PORTS\n {}'.format('\n '.join(self.ports)) <NEW_LINE> <DEDENT> return s + '\n' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> s = self.ip <NEW_LINE> if self.hostname: <NEW_LINE> <INDENT> s += ' ({})'.format(self.hostname) <NEW_LINE> <DEDENT> return s
basic class for storing nmap results
62598fb955399d3f05626665
class LiquidationApi(object): <NEW_LINE> <INDENT> def __init__(self, api_client=None): <NEW_LINE> <INDENT> if api_client is None: <NEW_LINE> <INDENT> api_client = ApiClient() <NEW_LINE> <DEDENT> self.api_client = api_client <NEW_LINE> <DEDENT> def liquidation_get(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.liquidation_get_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.liquidation_get_with_http_info(**kwargs) <NEW_LINE> return data <NEW_LINE> <DEDENT> <DEDENT> def liquidation_get_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = ['symbol', 'filter', 'columns', 'count', 'start', 'reverse', 'start_time', 'end_time'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = locals() <NEW_LINE> for key, val in six.iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise TypeError( "Got an unexpected keyword argument '%s'" " to method liquidation_get" % key ) <NEW_LINE> <DEDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> query_params = [] <NEW_LINE> if 'symbol' in params: <NEW_LINE> <INDENT> query_params.append(('symbol', params['symbol'])) <NEW_LINE> <DEDENT> if 'filter' in params: <NEW_LINE> <INDENT> query_params.append(('filter', params['filter'])) <NEW_LINE> <DEDENT> if 'columns' in params: <NEW_LINE> <INDENT> query_params.append(('columns', params['columns'])) <NEW_LINE> <DEDENT> if 'count' in params: <NEW_LINE> <INDENT> query_params.append(('count', params['count'])) <NEW_LINE> <DEDENT> if 'start' in params: <NEW_LINE> <INDENT> query_params.append(('start', params['start'])) <NEW_LINE> <DEDENT> if 'reverse' in params: <NEW_LINE> <INDENT> query_params.append(('reverse', params['reverse'])) <NEW_LINE> <DEDENT> if 'start_time' in params: <NEW_LINE> <INDENT> query_params.append(('startTime', params['start_time'])) <NEW_LINE> <DEDENT> if 'end_time' in params: <NEW_LINE> <INDENT> query_params.append(('endTime', params['end_time'])) <NEW_LINE> <DEDENT> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']) <NEW_LINE> header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json', 'application/x-www-form-urlencoded']) <NEW_LINE> auth_settings = [] <NEW_LINE> return self.api_client.call_api( '/liquidation', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[Liquidation]', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen
62598fb95166f23b2e24352f
class Expect(object): <NEW_LINE> <INDENT> def __init__(self, remote_command, args, incomparable_args=[]): <NEW_LINE> <INDENT> self.remote_command = remote_command <NEW_LINE> self.incomparable_args = incomparable_args <NEW_LINE> self.args = args <NEW_LINE> self.result = None <NEW_LINE> self.behaviors = [] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def behavior(cls, callable): <NEW_LINE> <INDENT> return ('callable', callable) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def log(self, name, **streams): <NEW_LINE> <INDENT> return ('log', name, streams) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def update(self, name, value): <NEW_LINE> <INDENT> return ('update', name, value) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> if isinstance(other, int): <NEW_LINE> <INDENT> self.behaviors.append(('rc', other)) <NEW_LINE> <DEDENT> elif isinstance(other, failure.Failure): <NEW_LINE> <INDENT> self.behaviors.append(('err', other)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.behaviors.append(other) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def runBehavior(self, behavior, args, command): <NEW_LINE> <INDENT> if behavior == 'rc': <NEW_LINE> <INDENT> command.rc = args[0] <NEW_LINE> <DEDENT> elif behavior == 'err': <NEW_LINE> <INDENT> return defer.fail(args[0]) <NEW_LINE> <DEDENT> elif behavior == 'update': <NEW_LINE> <INDENT> command.updates.setdefault(args[0], []).append(args[1]) <NEW_LINE> <DEDENT> elif behavior == 'log': <NEW_LINE> <INDENT> name, streams = args <NEW_LINE> if 'header' in streams: <NEW_LINE> <INDENT> command.logs[name].addHeader(streams['header']) <NEW_LINE> <DEDENT> if 'stdout' in streams: <NEW_LINE> <INDENT> command.logs[name].addStdout(streams['stdout']) <NEW_LINE> if command.collectStdout: <NEW_LINE> <INDENT> command.stdout += streams['stdout'] <NEW_LINE> <DEDENT> <DEDENT> if 'stderr' in streams: <NEW_LINE> <INDENT> command.logs[name].addStderr(streams['stderr']) <NEW_LINE> if command.collectStderr: <NEW_LINE> <INDENT> command.stderr += streams['stderr'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif behavior == 'callable': <NEW_LINE> <INDENT> return defer.maybeDeferred(lambda : args[0](command)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return defer.fail(failure.Failure( AssertionError('invalid behavior %s' % behavior))) <NEW_LINE> <DEDENT> return defer.succeed(None) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def runBehaviors(self, command): <NEW_LINE> <INDENT> for behavior in self.behaviors: <NEW_LINE> <INDENT> yield self.runBehavior(behavior[0], behavior[1:], command) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Expect("+repr(self.remote_command)+")"
Define an expected L{RemoteCommand}, with the same arguments Extra behaviors of the remote command can be added to the instance, using class methods. Use L{Expect.log} to add a logfile, L{Expect.update} to add an arbitrary update, or add an integer to specify the return code (rc), or add a Failure instance to raise an exception. Additionally, use L{Expect.behavior}, passing a callable that will be invoked with the real command and can do what it likes: def custom_behavior(command): ... Expect('somecommand', { args='foo' }) + Expect.behavior(custom_behavior), ... Expect('somecommand', { args='foo' }) + Expect.log('stdio', stdout='foo!') + Expect.log('config.log', stdout='some info') + Expect.update('status', 'running') + 0, # (specifies the rc) ...
62598fb93317a56b869be5f7
class QTraffic: <NEW_LINE> <INDENT> def __init__(self, iface): <NEW_LINE> <INDENT> self.iface = iface <NEW_LINE> self.plugin_dir = os.path.dirname(__file__) <NEW_LINE> self.pluginTag = 'QTraffic' <NEW_LINE> locale = QSettings().value('locale/userLocale')[0:2] <NEW_LINE> locale_path = os.path.join( self.plugin_dir, 'i18n', 'QTraffic_{}.qm'.format(locale)) <NEW_LINE> if os.path.exists(locale_path): <NEW_LINE> <INDENT> self.translator = QTranslator() <NEW_LINE> self.translator.load(locale_path) <NEW_LINE> if qVersion() > '4.3.3': <NEW_LINE> <INDENT> QCoreApplication.installTranslator(self.translator) <NEW_LINE> <DEDENT> <DEDENT> self.dlg = QTrafficDockWidget(self.iface.mainWindow(), self) <NEW_LINE> self.actions = [] <NEW_LINE> self.menu = self.tr(u'&QTraffic') <NEW_LINE> self.toolbar = self.iface.addToolBar(u'QTraffic') <NEW_LINE> self.toolbar.setObjectName(u'QTraffic') <NEW_LINE> <DEDENT> def tr(self, message): <NEW_LINE> <INDENT> return QCoreApplication.translate('QTraffic', message) <NEW_LINE> <DEDENT> def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): <NEW_LINE> <INDENT> icon = QIcon(icon_path) <NEW_LINE> action = QAction(icon, text, parent) <NEW_LINE> action.triggered.connect(callback) <NEW_LINE> action.setEnabled(enabled_flag) <NEW_LINE> if status_tip is not None: <NEW_LINE> <INDENT> action.setStatusTip(status_tip) <NEW_LINE> <DEDENT> if whats_this is not None: <NEW_LINE> <INDENT> action.setWhatsThis(whats_this) <NEW_LINE> <DEDENT> if add_to_toolbar: <NEW_LINE> <INDENT> self.toolbar.addAction(action) <NEW_LINE> <DEDENT> if add_to_menu: <NEW_LINE> <INDENT> self.iface.addPluginToMenu( self.menu, action) <NEW_LINE> <DEDENT> self.actions.append(action) <NEW_LINE> return action <NEW_LINE> <DEDENT> def initGui(self): <NEW_LINE> <INDENT> icon_path = ':/plugins/QTraffic/icon.png' <NEW_LINE> self.add_action( icon_path, text=self.tr(u'QTraffic - Traffic Emission Modelling'), callback=self.run, parent=self.iface.mainWindow()) <NEW_LINE> <DEDENT> def unload(self): <NEW_LINE> <INDENT> for action in self.actions: <NEW_LINE> <INDENT> self.iface.removePluginMenu( self.tr(u'&QTraffic'), action) <NEW_LINE> self.iface.removeToolBarIcon(action) <NEW_LINE> <DEDENT> del self.toolbar <NEW_LINE> try: <NEW_LINE> <INDENT> QgsMapLayerRegistry.instance().layerRemoved.disconnect(self.dlg.checkLayerDeletion) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> if not self.dlg.isVisible(): <NEW_LINE> <INDENT> self.iface.mainWindow().addDockWidget(Qt.BottomDockWidgetArea, self.dlg) <NEW_LINE> self.dlg.show()
QGIS Plugin Implementation.
62598fb99c8ee8231304021d
class TestInstallation(unittest.TestCase): <NEW_LINE> <INDENT> layer = INTEGRATION_TESTING <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.portal = self.layer['portal'] <NEW_LINE> <DEDENT> def testBrowserLayerRegistered(self): <NEW_LINE> <INDENT> layers = [o.__name__ for o in registered_layers()] <NEW_LINE> assert 'IYounglivesEthiopia' in layers <NEW_LINE> <DEDENT> def testCssInstalled(self): <NEW_LINE> <INDENT> assert '++resource++younglives.ethiopia.stylesheets/ethiopia.css' in self.portal.portal_css.getResourceIds()
Ensure product is properly installed
62598fb9bf627c535bcb15f6
class GenericContent(object): <NEW_LINE> <INDENT> PROPERTIES = [ ('dummy', 'shortstr'), ] <NEW_LINE> def __init__(self, **props): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for propname, _ in self.PROPERTIES: <NEW_LINE> <INDENT> if propname in props: <NEW_LINE> <INDENT> d[propname] = props[propname] <NEW_LINE> <DEDENT> <DEDENT> self.properties = d <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return hasattr(other, 'properties') and (self.properties == other.properties) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> if name == '__setstate__': <NEW_LINE> <INDENT> raise AttributeError('__setstate__') <NEW_LINE> <DEDENT> if name in self.properties: <NEW_LINE> <INDENT> return self.properties[name] <NEW_LINE> <DEDENT> if ('delivery_info' in self.__dict__) and (name in self.delivery_info): <NEW_LINE> <INDENT> return self.delivery_info[name] <NEW_LINE> <DEDENT> raise AttributeError(name) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> def _load_properties(self, raw_bytes): <NEW_LINE> <INDENT> r = AMQPReader(raw_bytes) <NEW_LINE> flags = [] <NEW_LINE> while True: <NEW_LINE> <INDENT> flag_bits = r.read_short() <NEW_LINE> flags.append(flag_bits) <NEW_LINE> if flag_bits & 1 == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> shift = 0 <NEW_LINE> d = {} <NEW_LINE> for key, proptype in self.PROPERTIES: <NEW_LINE> <INDENT> if shift == 0: <NEW_LINE> <INDENT> if not flags: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> flag_bits, flags = flags[0], flags[1:] <NEW_LINE> shift = 15 <NEW_LINE> <DEDENT> if flag_bits & (1 << shift): <NEW_LINE> <INDENT> d[key] = getattr(r, 'read_' + proptype)() <NEW_LINE> <DEDENT> shift -= 1 <NEW_LINE> <DEDENT> self.properties = d <NEW_LINE> <DEDENT> def _serialize_properties(self): <NEW_LINE> <INDENT> shift = 15 <NEW_LINE> flag_bits = 0 <NEW_LINE> flags = [] <NEW_LINE> raw_bytes = AMQPWriter() <NEW_LINE> for key, proptype in self.PROPERTIES: <NEW_LINE> <INDENT> val = self.properties.get(key, None) <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> if shift == 0: <NEW_LINE> <INDENT> flags.append(flag_bits) <NEW_LINE> flag_bits = 0 <NEW_LINE> shift = 15 <NEW_LINE> <DEDENT> flag_bits |= (1 << shift) <NEW_LINE> if proptype != 'bit': <NEW_LINE> <INDENT> getattr(raw_bytes, 'write_' + proptype)(val) <NEW_LINE> <DEDENT> <DEDENT> shift -= 1 <NEW_LINE> <DEDENT> flags.append(flag_bits) <NEW_LINE> result = AMQPWriter() <NEW_LINE> for flag_bits in flags: <NEW_LINE> <INDENT> result.write_short(flag_bits) <NEW_LINE> <DEDENT> result.write(raw_bytes.getvalue()) <NEW_LINE> return result.getvalue()
Abstract base class for AMQP content. Subclasses should override the PROPERTIES attribute.
62598fb956b00c62f0fb2a0d
class IconTree(Tree): <NEW_LINE> <INDENT> FIELDS = (gobject.TYPE_STRING, gobject.TYPE_PYOBJECT, gobject.TYPE_STRING, gtk.gdk.Pixbuf) <NEW_LINE> COLUMNS = [[gtk.CellRendererPixbuf, 'pixbuf', 3], [gtk.CellRendererText, 'markup', 2]] <NEW_LINE> def add_item(self, item, key=None, parent=None): <NEW_LINE> <INDENT> pixbuf = item.pixbuf <NEW_LINE> if key is None: <NEW_LINE> <INDENT> key = item.key <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> item.key = key <NEW_LINE> <DEDENT> titem = TreeItem(key, item) <NEW_LINE> row = [key, titem, self.get_markup(item), pixbuf] <NEW_LINE> niter = self.model.append(parent, row) <NEW_LINE> def reset(): <NEW_LINE> <INDENT> for model, ite in item._tree_models: <NEW_LINE> <INDENT> model.set_value(ite, 2, self.get_markup(item)) <NEW_LINE> model.set_value(ite, 3, item.pixbuf) <NEW_LINE> <DEDENT> <DEDENT> for obj in [item, titem]: <NEW_LINE> <INDENT> if not hasattr(obj, 'reset_markup'): <NEW_LINE> <INDENT> obj.reset_markup = reset <NEW_LINE> <DEDENT> if not hasattr(obj, '_tree_models'): <NEW_LINE> <INDENT> obj._tree_models = [] <NEW_LINE> <DEDENT> obj._tree_models.append([self.model, niter]) <NEW_LINE> <DEDENT> return niter
Tree with icons.
62598fb9ad47b63b2c5a79a7
class BaseItem(object): <NEW_LINE> <INDENT> def __init__(self, data, parent=None): <NEW_LINE> <INDENT> self.parentItem = parent <NEW_LINE> self.itemData = None <NEW_LINE> self.childItems = [] <NEW_LINE> self.updateData(data) <NEW_LINE> <DEDENT> def updateData(self, data): <NEW_LINE> <INDENT> if self.itemData != data: <NEW_LINE> <INDENT> self.itemData = data <NEW_LINE> self.updateChild() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.itemData = data <NEW_LINE> <DEDENT> <DEDENT> def updateChild(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def changeParent(self, parent): <NEW_LINE> <INDENT> self.parentItem = parent <NEW_LINE> <DEDENT> def appendChild(self, item): <NEW_LINE> <INDENT> item.changeParent(self) <NEW_LINE> self.childItems.append(item) <NEW_LINE> <DEDENT> def insertChild(self, index, item): <NEW_LINE> <INDENT> item.changeParent(self) <NEW_LINE> self.childItems.insert(index, item) <NEW_LINE> <DEDENT> def child(self, row): <NEW_LINE> <INDENT> return self.childItems[row] <NEW_LINE> <DEDENT> def childCount(self): <NEW_LINE> <INDENT> return len(self.childItems) <NEW_LINE> <DEDENT> def columnCount(self): <NEW_LINE> <INDENT> return 5 <NEW_LINE> <DEDENT> def data(self, column): <NEW_LINE> <INDENT> if column == 0: <NEW_LINE> <INDENT> return self.itemData['repr'] <NEW_LINE> <DEDENT> elif column == TreeCol.OJBTYPE: <NEW_LINE> <INDENT> return self.getType() <NEW_LINE> <DEDENT> elif column == TreeCol.PARAM: <NEW_LINE> <INDENT> return self.getParams() <NEW_LINE> <DEDENT> elif column == TreeCol.IS_DERIVED: <NEW_LINE> <INDENT> if '_is_derived' in self.itemData: <NEW_LINE> <INDENT> return str(self.itemData['_is_derived']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> elif column == TreeCol.LEN: <NEW_LINE> <INDENT> if '__len__' in self.itemData: <NEW_LINE> <INDENT> l = self.itemData['__len__'] <NEW_LINE> return str(l) if l else "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise IndexError <NEW_LINE> <DEDENT> <DEDENT> def parent(self): <NEW_LINE> <INDENT> return self.parentItem <NEW_LINE> <DEDENT> def row(self): <NEW_LINE> <INDENT> if self.parentItem: <NEW_LINE> <INDENT> return self.parentItem.childItems.index(self) <NEW_LINE> <DEDENT> return 0 <NEW_LINE> <DEDENT> def getType(self): <NEW_LINE> <INDENT> return self.itemData.get('type', '') <NEW_LINE> <DEDENT> def getParams(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __getattr__(self, item): <NEW_LINE> <INDENT> return self.itemData[item]
Base Item class for all tree item classes.
62598fb98e7ae83300ee91f3
class getActiveMemberMidsByBuddyMid_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None, e=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.e = e <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.success = [] <NEW_LINE> (_etype1332, _size1329) = iprot.readListBegin() <NEW_LINE> for _i1333 in range(_size1329): <NEW_LINE> <INDENT> _elem1334 = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> self.success.append(_elem1334) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e = TalkException() <NEW_LINE> self.e.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getActiveMemberMidsByBuddyMid_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.LIST, 0) <NEW_LINE> oprot.writeListBegin(TType.STRING, len(self.success)) <NEW_LINE> for iter1335 in self.success: <NEW_LINE> <INDENT> oprot.writeString(iter1335.encode('utf-8') if sys.version_info[0] == 2 else iter1335) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.e is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e', TType.STRUCT, 1) <NEW_LINE> self.e.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success - e
62598fb966673b3332c30523
class Video3x3ExampleMainWidget(Video2x2ExampleMainWidget): <NEW_LINE> <INDENT> plugin_uid = 'video_3x3' <NEW_LINE> cols = 3 <NEW_LINE> rows = 3
Video2x2 plugin widget for Example layout (placeholder `main`).
62598fb91f5feb6acb162d73
class ImagePlot(DocumentLayout): <NEW_LINE> <INDENT> def __init__(self, width=640, height=360): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.width = width <NEW_LINE> self.height = height <NEW_LINE> self.image_source = ColumnDataSource({'image': []}) <NEW_LINE> self._init_image_plot() <NEW_LINE> <DEDENT> def _init_image_plot(self): <NEW_LINE> <INDENT> self.fig = figure( title='Image Captured from Camera', x_axis_location='above', width=self.width, height=self.height, x_range=[0, self.width], y_range=[self.height, 0] ) <NEW_LINE> self.image = None <NEW_LINE> self.image = self.fig.image_rgba( image='image', x=0, y=self.height, dw=self.width, dh=self.height, source=self.image_source ) <NEW_LINE> <DEDENT> def _convert_image(self, image_rgb): <NEW_LINE> <INDENT> (height, width) = image_rgb.shape[:2] <NEW_LINE> image_rgba = np.dstack((image_rgb, np.ones((height, width)))) <NEW_LINE> image_rgba *= 255 <NEW_LINE> image_rgba = image_rgba.astype(np.uint8) <NEW_LINE> image_rgba = np.flipud(image_rgba) <NEW_LINE> return image_rgba <NEW_LINE> <DEDENT> def update_image(self, image_rgb): <NEW_LINE> <INDENT> image_rgba = self._convert_image(image_rgb) <NEW_LINE> (height, width) = image_rgba.shape[:2] <NEW_LINE> self.image_source.data = {'image': [image_rgba]} <NEW_LINE> <DEDENT> @property <NEW_LINE> def layout(self): <NEW_LINE> <INDENT> return self.fig
Plot of received images.
62598fb9a05bb46b3848a9bf
class RecipeList(generics.ListCreateAPIView): <NEW_LINE> <INDENT> queryset = Recipe.objects.all() <NEW_LINE> serializer_class = RecipeSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> queryset = Recipe.objects.all() <NEW_LINE> user_id = self.request.query_params.get('user_id') <NEW_LINE> if user_id: <NEW_LINE> <INDENT> queryset = queryset.filter(user_id=user_id) <NEW_LINE> <DEDENT> return queryset
Recipe List & Create View.
62598fb971ff763f4b5e78cc
class Biblioteca: <NEW_LINE> <INDENT> def __init__(self, name, root=vkconfig.BIBLIOTECHE_ROOT): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.root = root <NEW_LINE> self.textdao = XMLBiblioteche(root).getCorpusCollection(name) <NEW_LINE> self.sqldao = CorpusCollectionSQLite(root).getCorpusDAO(name) <NEW_LINE> self.corpuses = [] <NEW_LINE> <DEDENT> def create_corpus(self, corpus_name): <NEW_LINE> <INDENT> self.sqldao.create_corpus(corpus_name) <NEW_LINE> self.textdao.create_corpus(corpus_name) <NEW_LINE> <DEDENT> def get_corpuses(self): <NEW_LINE> <INDENT> with self.sqldao.ctx() as ctx: <NEW_LINE> <INDENT> self.corpuses = ctx.corpus.select() <NEW_LINE> for corpus in self.corpuses: <NEW_LINE> <INDENT> corpus.documents = self.sqldao.get_docs(corpus.ID, ctx=ctx) <NEW_LINE> for doc in corpus.documents: <NEW_LINE> <INDENT> doc.corpus = corpus <NEW_LINE> q = "SELECT COUNT(*) FROM sentence WHERE docID = ?" <NEW_LINE> p = (doc.ID,) <NEW_LINE> doc.sent_count = ctx.select_scalar(q, p) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self.corpuses <NEW_LINE> <DEDENT> def get_corpus_info(self, corpus, ctx=None): <NEW_LINE> <INDENT> if ctx is None: <NEW_LINE> <INDENT> with self.sqldao.ctx() as ctx: <NEW_LINE> <INDENT> return self.get_corpus_info(corpus, ctx=ctx) <NEW_LINE> <DEDENT> <DEDENT> corpus.documents = self.sqldao.get_docs(corpus.ID, ctx=ctx) <NEW_LINE> for doc in corpus.documents: <NEW_LINE> <INDENT> doc.corpus = corpus <NEW_LINE> q = "SELECT COUNT(*) FROM sentence WHERE docID = ?" <NEW_LINE> p = (doc.ID,) <NEW_LINE> doc.sent_count = ctx.select_scalar(q, p) <NEW_LINE> <DEDENT> return corpus
One biblioteca contains many corpora It's a collection of documents
62598fb9cc40096d6161a283
class Service(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.config = config.Config('email_service') <NEW_LINE> <DEDENT> def __callback(self, ch, method, properties, body): <NEW_LINE> <INDENT> print(' [x] Received {0}'.format(body)) <NEW_LINE> print(' [x] Sending email.') <NEW_LINE> try: <NEW_LINE> <INDENT> body = ast.literal_eval(body) <NEW_LINE> self.__send_email(body['to'], body['subject'], body['email_body'], body['attachment_path']) <NEW_LINE> print(' [x] Email sent.') <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> print(' [e] The message is missing the following key: {' '0}'.format(e.args)) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(' [e] An exception of type {0} occurred.'.format(type( e).__name__)) <NEW_LINE> print(' [e] Arguments: {0}'.format(e.args)) <NEW_LINE> print(' [e] Email not sent.') <NEW_LINE> <DEDENT> <DEDENT> def __send_email(self, recipient, subject, email_body, attachment_path): <NEW_LINE> <INDENT> email = MIMEMultipart() <NEW_LINE> email['From'] = self.config.sender <NEW_LINE> email['To'] = recipient <NEW_LINE> email['Subject'] = subject <NEW_LINE> if attachment_path: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> body = email_body <NEW_LINE> email.attach(MIMEText(body, 'plain')) <NEW_LINE> server = smtplib.SMTP("smtp.gmail.com", 587) <NEW_LINE> server.starttls() <NEW_LINE> server.login(self.config.username, self.config.password) <NEW_LINE> server.sendmail(self.config.sender, recipient, email.as_string()) <NEW_LINE> server.close() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> print('Starting service.') <NEW_LINE> connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) <NEW_LINE> channel = connection.channel() <NEW_LINE> channel.queue_declare(queue='email_service') <NEW_LINE> print(' [*] Waiting for messages. Press CTRL+C to exit.') <NEW_LINE> channel.basic_consume(self.__callback, queue='email_service', no_ack=True) <NEW_LINE> channel.start_consuming()
TODO Make this useful. This is the Service class.
62598fb9091ae35668704d75
class DBSubnetGroup(object): <NEW_LINE> <INDENT> def __init__(self, connection=None, name=None, description=None, subnet_ids=None): <NEW_LINE> <INDENT> self.connection = connection <NEW_LINE> self.name = name <NEW_LINE> self.description = description <NEW_LINE> if subnet_ids is not None: <NEW_LINE> <INDENT> self.subnet_ids = subnet_ids <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.subnet_ids = [] <NEW_LINE> <DEDENT> self.vpc_id = None <NEW_LINE> self.status = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'DBSubnetGroup:%s' % self.name <NEW_LINE> <DEDENT> def startElement(self, name, attrs, connection): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def endElement(self, name, value, connection): <NEW_LINE> <INDENT> if name == 'SubnetIdentifier': <NEW_LINE> <INDENT> self.subnet_ids.append(value) <NEW_LINE> <DEDENT> elif name == 'DBSubnetGroupName': <NEW_LINE> <INDENT> self.name = value <NEW_LINE> <DEDENT> elif name == 'DBSubnetGroupDescription': <NEW_LINE> <INDENT> self.description = value <NEW_LINE> <DEDENT> elif name == 'VpcId': <NEW_LINE> <INDENT> self.vpc_id = value <NEW_LINE> <DEDENT> elif name == 'SubnetGroupStatus': <NEW_LINE> <INDENT> self.status = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(self, name, value)
Represents an RDS database subnet group Properties reference available from the AWS documentation at http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DeleteDBSubnetGroup.html :ivar status: The current status of the subnet group. Possibile values are [ active, ? ]. Reference documentation lacks specifics of possibilities :ivar connection: boto.rds.RDSConnection associated with the current object :ivar description: The description of the subnet group :ivar subnet_ids: List of subnet identifiers in the group :ivar name: Name of the subnet group :ivar vpc_id: The ID of the VPC the subnets are inside
62598fb93d592f4c4edbb012
class SocialMediaObject(db.EmbeddedDocument): <NEW_LINE> <INDENT> facebook_id = db.StringField(max_length=100) <NEW_LINE> twitter_id = db.StringField(max_length=100) <NEW_LINE> def as_dict(self): <NEW_LINE> <INDENT> return swap_null_id(self._data)
ABOUT This helps us track if the post was coppied to a social platform such as Twitter or Facebook by storing the appropriate ID. The actual posting occurs in external modules
62598fb992d797404e388c0d
class AdminIndexView(admin.AdminIndexView): <NEW_LINE> <INDENT> @expose('/') <NEW_LINE> def index(self): <NEW_LINE> <INDENT> if not login.current_user.is_authenticated(): <NEW_LINE> <INDENT> return redirect(url_for('.login_view')) <NEW_LINE> <DEDENT> return super(AdminIndexView, self).index() <NEW_LINE> <DEDENT> @expose('/login/', methods=('GET', 'POST')) <NEW_LINE> def login_view(self): <NEW_LINE> <INDENT> form = LoginForm(request.form) <NEW_LINE> if helpers.validate_form_on_submit(form): <NEW_LINE> <INDENT> user = form.get_user() <NEW_LINE> login.login_user(user) <NEW_LINE> <DEDENT> if login.current_user.is_authenticated(): <NEW_LINE> <INDENT> return redirect(url_for('.index')) <NEW_LINE> <DEDENT> self._template_args['form'] = form <NEW_LINE> return super(AdminIndexView, self).index() <NEW_LINE> <DEDENT> @expose('/logout/') <NEW_LINE> def logout_view(self): <NEW_LINE> <INDENT> login.logout_user() <NEW_LINE> return redirect(url_for('.index'))
Customized index view class that handles login/logout"
62598fb957b8e32f525081c7
class ExactInference(InferenceModule): <NEW_LINE> <INDENT> def initializeUniformly(self, gameState): <NEW_LINE> <INDENT> self.beliefs = DiscreteDistribution() <NEW_LINE> for p in self.legalPositions: <NEW_LINE> <INDENT> self.beliefs[p] = 1.0 <NEW_LINE> <DEDENT> self.beliefs.normalize() <NEW_LINE> <DEDENT> def observeUpdate(self, observation, gameState): <NEW_LINE> <INDENT> jail_position = self.getJailPosition() <NEW_LINE> pacman_position = gameState.getPacmanPosition() <NEW_LINE> beliefs = self.beliefs <NEW_LINE> for potential_position in self.allPositions: <NEW_LINE> <INDENT> beliefs[potential_position] *= self.getObservationProb(observation, pacman_position, potential_position, jail_position) <NEW_LINE> <DEDENT> beliefs.normalize() <NEW_LINE> <DEDENT> def elapseTime(self, gameState): <NEW_LINE> <INDENT> old_beliefs = self.beliefs <NEW_LINE> new_beliefs = DiscreteDistribution() <NEW_LINE> for old_pos in self.allPositions: <NEW_LINE> <INDENT> for new_pos, p in self.getPositionDistribution(gameState, old_pos).items(): <NEW_LINE> <INDENT> new_beliefs[new_pos] += old_beliefs[old_pos]*p <NEW_LINE> <DEDENT> <DEDENT> self.beliefs = new_beliefs <NEW_LINE> <DEDENT> def getBeliefDistribution(self): <NEW_LINE> <INDENT> return self.beliefs
The exact dynamic inference module should use forward algorithm updates to compute the exact belief function at each time step.
62598fb95fcc89381b2661f6
class IterDB: <NEW_LINE> <INDENT> def __init__(self, db, report_type, stream_mode): <NEW_LINE> <INDENT> self.db = db <NEW_LINE> self.stream_mode = stream_mode <NEW_LINE> self.report_type = report_type <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def __next__(self) -> Report: <NEW_LINE> <INDENT> raise NotImplementedError()
IterDB class This class allows to browse a database as an iterable
62598fb9be7bc26dc9251f06
class Meta: <NEW_LINE> <INDENT> verbose_name = _("Concept Plan") <NEW_LINE> verbose_name_plural = _("Concept Plans") <NEW_LINE> display_order = 10
Class options.
62598fb9851cf427c66b840a
class TerminalAdapter(InputAdapter): <NEW_LINE> <INDENT> def process_input(self, *args): <NEW_LINE> <INDENT> user_input = input() <NEW_LINE> return Statement(text=user_input)
A simple adapter that allows ChatterBot to communicate through the terminal.
62598fb95fdd1c0f98e5e0e4
class Command: <NEW_LINE> <INDENT> (DATA, DISPLAY, ADDRESS) = (0x40, 0x80, 0xC0)
Enumeration of command registers addresses (bits 6 ~ 7).
62598fb95166f23b2e243531
@dataclass <NEW_LINE> class Const(Value): <NEW_LINE> <INDENT> value: object <NEW_LINE> _type: typ.Type <NEW_LINE> @AstNode.cache_type <NEW_LINE> def infer_type(self, checker: check.Checker) -> typ.Type: <NEW_LINE> <INDENT> return self.type <NEW_LINE> <DEDENT> def to_lir(self, ctx: gen_ctx.NasmGenCtx) -> lir.Value: <NEW_LINE> <INDENT> if self.type == typ.Int: <NEW_LINE> <INDENT> assert isinstance(self.value, int) <NEW_LINE> return lir.I64(self.value) <NEW_LINE> <DEDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def captures(self) -> Set[Ident]: <NEW_LINE> <INDENT> return set() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.value)
A literal. 1, true, -4.21983, point { x=1, y=2 }
62598fb9d7e4931a7ef3c1ea
class ImageIDField(forms.IntegerField): <NEW_LINE> <INDENT> widget = ImagePluginChoiceWidget(clearable=True) <NEW_LINE> def clean(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = super(ImageIDField, self).clean(value) <NEW_LINE> <DEDENT> except ValidationError: <NEW_LINE> <INDENT> raise ValidationError("Invalid image ID", code="invalid") <NEW_LINE> <DEDENT> return value
A custom field that stores the ID value of a Filer image and presents Shuup admin's image popup widget
62598fb9cc0a2c111447b161