code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class RestInterface(): <NEW_LINE> <INDENT> def __init__(self, version, methods, schema=None, rules=None): <NEW_LINE> <INDENT> if not isinstance(methods, list): <NEW_LINE> <INDENT> methods = [methods] <NEW_LINE> <DEDENT> self.version = str(version) <NEW_LINE> self.methods = [m.upper() for m in methods] <NEW_LINE> self.schema = schema <NEW_LINE> self.rules = rules
Denotes the schema and rest rules associated with a rest API version and HTTP method.
62598fd05fdd1c0f98e5e3c8
class OrderAlreadyClosedError(ActiveParticipantError): <NEW_LINE> <INDENT> pass
Occurs when trying to cancel a already-closed Order
62598fd08a349b6b4368667d
class InactiveLoginError(ClientError): <NEW_LINE> <INDENT> def __init__(self, message, meta=None): <NEW_LINE> <INDENT> super().__init__(message) <NEW_LINE> self.meta = meta
Indicates some sort of configuration error
62598fd055399d3f05626956
class HttpConnection(object): <NEW_LINE> <INDENT> def __init__(self, username='', password=''): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.session = self._create_session() <NEW_LINE> <DEDENT> def _create_session(self): <NEW_LINE> <INDENT> s = requests.Session() <NEW_LINE> if self.username: <NEW_LINE> <INDENT> s.auth = (self.username, '') <NEW_LINE> <DEDENT> s.stream = True <NEW_LINE> return s <NEW_LINE> <DEDENT> def _send_request(self, request): <NEW_LINE> <INDENT> prepped = self.session.prepare_request(request) <NEW_LINE> response = self.session.send(prepped) <NEW_LINE> return response <NEW_LINE> <DEDENT> def _do_request(self, method, url, **kw): <NEW_LINE> <INDENT> request = requests.Request(method=method, url=url, **kw) <NEW_LINE> response = self._send_request(request) <NEW_LINE> if response.status_code != 200: <NEW_LINE> <INDENT> raise Exception('Server returned unhandled response code: %s' % response.code) <NEW_LINE> <DEDENT> return response.text <NEW_LINE> <DEDENT> def request(self, url, **kw): <NEW_LINE> <INDENT> return self._do_request(method='GET', url=url, **kw) <NEW_LINE> <DEDENT> def post(self, url, **kw): <NEW_LINE> <INDENT> return self._do_request(method='POST', url=url, **kw) <NEW_LINE> <DEDENT> def delete(self, url, **kw): <NEW_LINE> <INDENT> return self._do_request(method='DELETE', url=url, **kw)
Connects to the collection database by using Http protocol.
62598fd03d592f4c4edbb2f1
class Game(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.GameBoard = Board() <NEW_LINE> self.Score = 0 <NEW_LINE> self.GameWon = False <NEW_LINE> <DEDENT> def move_board(self, direction): <NEW_LINE> <INDENT> vector = direction.vector() <NEW_LINE> vector_x = vector[0] <NEW_LINE> vector_y = vector[1] <NEW_LINE> moveRow = vector_x != 0 <NEW_LINE> moveColumn = vector_y != 0 <NEW_LINE> if (moveRow and moveColumn): <NEW_LINE> <INDENT> raise Exception("Can't move both a row and a column at the same time!") <NEW_LINE> <DEDENT> before_move = self.GameBoard <NEW_LINE> if moveRow: <NEW_LINE> <INDENT> for row in self.GameBoard.square_board(): <NEW_LINE> <INDENT> row = self.execute_move(row, vector_x) <NEW_LINE> <DEDENT> <DEDENT> elif moveColumn: <NEW_LINE> <INDENT> for i, row in enumerate(self.GameBoard.square_board()): <NEW_LINE> <INDENT> column = self.GameBoard.get_column(i) <NEW_LINE> column = self.execute_move(column, vector_y) <NEW_LINE> <DEDENT> <DEDENT> if before_move != self.GameBoard: <NEW_LINE> <INDENT> self.GameBoard.get_random_unassigned_square().set_random_value() <NEW_LINE> <DEDENT> <DEDENT> def execute_move(self, line, direction): <NEW_LINE> <INDENT> line = self.move_line(line, direction) <NEW_LINE> line = self.handle_collisions(line, direction) <NEW_LINE> line = self.move_line(line, direction) <NEW_LINE> return line <NEW_LINE> <DEDENT> def move_line(self, line, direction): <NEW_LINE> <INDENT> new_line = [square for square in line if square.value != 0] <NEW_LINE> new_empty_squares = [Square()] * (self.GameBoard.board_size - len(new_line)) <NEW_LINE> if (direction > 0): <NEW_LINE> <INDENT> return new_empty_squares + new_line <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return new_line + new_empty_squares <NEW_LINE> <DEDENT> <DEDENT> def handle_collisions(self, line, direction): <NEW_LINE> <INDENT> if (direction > 0): <NEW_LINE> <INDENT> range_to_iterate_line = range(0, self.GameBoard.board_size - 1, direction) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> range_to_iterate_line = range(self.GameBoard.board_size - 1, 0, direction) <NEW_LINE> <DEDENT> for index in range_to_iterate_line: <NEW_LINE> <INDENT> if (line[index].value is 0): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if (self.collision_is_match(line[index], line[index + direction])): <NEW_LINE> <INDENT> new_value = line[index].value + line[index + direction].value <NEW_LINE> if (new_value == 2048): <NEW_LINE> <INDENT> self.GameWon = True <NEW_LINE> <DEDENT> line[index].value = new_value <NEW_LINE> line[index + direction].value = 0 <NEW_LINE> self.Score += new_value <NEW_LINE> <DEDENT> <DEDENT> return line <NEW_LINE> <DEDENT> def collision_is_match(self, first_square, second_square): <NEW_LINE> <INDENT> return first_square.value == second_square.value
A single game of 2048 - contains the board and functions which manipulate it
62598fd03346ee7daa337865
class Level_OpenDoorLoc(Level_OpenDoor): <NEW_LINE> <INDENT> def __init__(self, seed=None): <NEW_LINE> <INDENT> super().__init__( select_by="loc", seed=seed )
Go to the door The door is selected by location. (always unlocked, in the current room)
62598fd00fa83653e46f5324
class UDPLogClientFactory(protocol.ReconnectingClientFactory): <NEW_LINE> <INDENT> maxDelay = 30 <NEW_LINE> def __init__(self, protocolClass, *args, **kwargs): <NEW_LINE> <INDENT> self.protocol = protocolClass <NEW_LINE> self.args = args <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> def buildProtocol(self, addr): <NEW_LINE> <INDENT> self.resetDelay() <NEW_LINE> p = self.protocol(*self.args, **self.kwargs) <NEW_LINE> p.factory = self <NEW_LINE> return p
Reconnecting client factory that resets retry delay upon connecting.
62598fd060cbc95b0636477a
class ResourceTfWorkspace(object): <NEW_LINE> <INDENT> swagger_types = { 'links': 'HalRscLinks', 'name': 'str', 'modules': 'list[ResourceTfModule]' } <NEW_LINE> attribute_map = { 'links': '_links', 'name': 'name', 'modules': 'modules' } <NEW_LINE> def __init__(self, links=None, name=None, modules=None): <NEW_LINE> <INDENT> self._links = None <NEW_LINE> self._name = None <NEW_LINE> self._modules = None <NEW_LINE> self.discriminator = None <NEW_LINE> if links is not None: <NEW_LINE> <INDENT> self.links = links <NEW_LINE> <DEDENT> self.name = name <NEW_LINE> if modules is not None: <NEW_LINE> <INDENT> self.modules = modules <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def links(self): <NEW_LINE> <INDENT> return self._links <NEW_LINE> <DEDENT> @links.setter <NEW_LINE> def links(self, links): <NEW_LINE> <INDENT> self._links = links <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `name`, must not be `None`") <NEW_LINE> <DEDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def modules(self): <NEW_LINE> <INDENT> return self._modules <NEW_LINE> <DEDENT> @modules.setter <NEW_LINE> def modules(self, modules): <NEW_LINE> <INDENT> self._modules = modules <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ResourceTfWorkspace): <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
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fd05fdd1c0f98e5e3ca
class XmlExportPipeline(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.files = {} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_crawler(cls, crawler): <NEW_LINE> <INDENT> pipeline = cls() <NEW_LINE> crawler.signals.connect(pipeline.spider_opened, signals.spider_opened) <NEW_LINE> crawler.signals.connect(pipeline.spider_closed, signals.spider_closed) <NEW_LINE> return pipeline <NEW_LINE> <DEDENT> def spider_opened(self, spider): <NEW_LINE> <INDENT> file = open('%s_products.xml' % spider.name, 'w+b') <NEW_LINE> self.files[spider] = file <NEW_LINE> self.exporter = XmlItemExporter(file) <NEW_LINE> self.exporter.start_exporting() <NEW_LINE> <DEDENT> def spider_closed(self, spider): <NEW_LINE> <INDENT> self.exporter.finish_exporting() <NEW_LINE> file = self.files.pop(spider) <NEW_LINE> file.close() <NEW_LINE> <DEDENT> def process_item(self, item, spider): <NEW_LINE> <INDENT> self.exporter.export_item(item) <NEW_LINE> return item
XMLエクスポートクラス
62598fd050812a4eaa620e03
class RetryParameters(validation.Validated): <NEW_LINE> <INDENT> ATTRIBUTES = { TASK_RETRY_LIMIT: validation.Optional(validation.TYPE_INT), TASK_AGE_LIMIT: validation.Optional(_TASK_AGE_LIMIT_REGEX), MIN_BACKOFF_SECONDS: validation.Optional(validation.TYPE_FLOAT), MAX_BACKOFF_SECONDS: validation.Optional(validation.TYPE_FLOAT), MAX_DOUBLINGS: validation.Optional(validation.TYPE_INT), }
Retry parameters for a single task queue.
62598fd0ff9c53063f51aa8a
class component: <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> @abstractmethod <NEW_LINE> def createEvaluation(self): pass <NEW_LINE> @abstractmethod <NEW_LINE> def createTransition(self): pass <NEW_LINE> @abstractmethod <NEW_LINE> def createCovPrior(self): pass <NEW_LINE> @abstractmethod <NEW_LINE> def createMeanPrior(self): pass <NEW_LINE> @abstractmethod <NEW_LINE> def checkDimensions(self): pass
The abstract class provides the basic structure for all model components Methods: createEvaluation: create the initial evaluation matrix createTransition: create the initial transition matrix createCovPrior: create a simple prior covariance matrix createMeanPrior: create a simple prior latent state checkDimensions: if user supplies their own covPrior and meanPrior, this can be used to check if the dimension matches
62598fd0377c676e912f6f97
class GroupingDirective(Stmt): <NEW_LINE> <INDENT> body: List[Stmt] <NEW_LINE> def __init__(self, *body: Stmt) -> None: <NEW_LINE> <INDENT> self.body = list(body) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> inner_text = "".join(indent(str(stmt)) for stmt in self.body) <NEW_LINE> return f"<{type(self).__name__.lower().replace('stmt', '')}:\n{inner_text}>"
An un-scoped group of statements.
62598fd04a966d76dd5ef316
class Forbidden(modioException): <NEW_LINE> <INDENT> def __init__(self, msg): <NEW_LINE> <INDENT> super().__init__(msg)
You do not have permission to perform the requested action.
62598fd0656771135c489ab0
class PermissionsController(rest.RestController): <NEW_LINE> <INDENT> @decorators.db_exceptions <NEW_LINE> @secure(checks.guest) <NEW_LINE> @wsme_pecan.wsexpose([wtypes.text], int) <NEW_LINE> def get(self, worklist_id): <NEW_LINE> <INDENT> worklist = worklists_api.get(worklist_id) <NEW_LINE> if worklists_api.visible(worklist, request.current_user_id): <NEW_LINE> <INDENT> return worklists_api.get_permissions(worklist, request.current_user_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise exc.NotFound(_("Worklist %s not found") % worklist_id) <NEW_LINE> <DEDENT> <DEDENT> @decorators.db_exceptions <NEW_LINE> @secure(checks.authenticated) <NEW_LINE> @wsme_pecan.wsexpose(wtypes.text, int, body=wtypes.DictType(wtypes.text, wtypes.text)) <NEW_LINE> def post(self, worklist_id, permission): <NEW_LINE> <INDENT> if worklists_api.editable(worklists_api.get(worklist_id), request.current_user_id): <NEW_LINE> <INDENT> return worklists_api.create_permission(worklist_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise exc.NotFound(_("Worklist %s not found") % worklist_id) <NEW_LINE> <DEDENT> <DEDENT> @decorators.db_exceptions <NEW_LINE> @secure(checks.authenticated) <NEW_LINE> @wsme_pecan.wsexpose(wtypes.text, int, body=wtypes.DictType(wtypes.text, wtypes.text)) <NEW_LINE> def put(self, worklist_id, permission): <NEW_LINE> <INDENT> if worklists_api.editable(worklists_api.get(worklist_id), request.current_user_id): <NEW_LINE> <INDENT> return worklists_api.update_permission( worklist_id, permission).codename <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise exc.NotFound(_("Worklist %s not found") % worklist_id)
Manages operations on worklist permissions.
62598fd08a349b6b43686681
class HCNPreprocessAgent(Agent): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def add_cmdline_args(argparser): <NEW_LINE> <INDENT> WordDictionaryAgent.add_cmdline_args(argparser) <NEW_LINE> ActionDictionaryAgent.add_cmdline_args(argparser) <NEW_LINE> return argparser <NEW_LINE> <DEDENT> def __init__(self, opt, shared=None): <NEW_LINE> <INDENT> self.id = self.__class__.__name__ <NEW_LINE> self.actions = ActionDictionaryAgent(opt, shared) <NEW_LINE> self.words = WordDictionaryAgent(opt, shared) <NEW_LINE> self.slot_names = [] <NEW_LINE> if opt.get('dict_file') is not None and os.path.isfile(opt['dict_file'] + '.slots'): <NEW_LINE> <INDENT> self.slot_names = json.load(open(opt['dict_file'] + '.slots', 'r')) <NEW_LINE> <DEDENT> elif opt.get('pretrained_model') is not None and os.path.isfile(opt['pretrained_model'] + '.dict.slots'): <NEW_LINE> <INDENT> self.slot_names = json.load(open(opt['pretrained_model'] + '.dict.slots', 'r')) <NEW_LINE> <DEDENT> elif opt.get('model_file') is not None and os.path.isfile(opt['model_file'] + '.dict.slots'): <NEW_LINE> <INDENT> self.slot_names = json.load(open(opt['model_file'] + '.dict.slots', 'r')) <NEW_LINE> <DEDENT> <DEDENT> def act(self): <NEW_LINE> <INDENT> self.words.observe(self.observation) <NEW_LINE> self.words.act() <NEW_LINE> self.actions.observe(self.observation) <NEW_LINE> self.actions.act() <NEW_LINE> for intent in self.observation.get('intents', []): <NEW_LINE> <INDENT> for slot, value in intent.get('slots', []): <NEW_LINE> <INDENT> if slot not in self.slot_names: <NEW_LINE> <INDENT> self.slot_names.append(slot) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return {'id': self.getID()} <NEW_LINE> <DEDENT> def save(self, filename=None, append=False, sort=True): <NEW_LINE> <INDENT> if filename: <NEW_LINE> <INDENT> self.words.save(filename + '.words', sort=sort) <NEW_LINE> self.actions.save(filename + '.actions', sort=sort) <NEW_LINE> json.dump(self.slot_names, open(filename + '.slots', 'w')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.words.save(sort=sort) <NEW_LINE> self.actions.save(sort=sort) <NEW_LINE> <DEDENT> <DEDENT> def share(self): <NEW_LINE> <INDENT> shared = {} <NEW_LINE> shares['words'] = self.words <NEW_LINE> shares['actions'] = self.actions <NEW_LINE> shared['opt'] = self.opt <NEW_LINE> shared['class'] = type(self) <NEW_LINE> return shared <NEW_LINE> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> self.words.shutdown() <NEW_LINE> self.actions.shutdown() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.words) + '\n' + str(self.actions)
Contains WordDictionaryAgent and ActionDictionaryAgent.
62598fd0099cdd3c636755ff
class DisplayableSitemap(Sitemap): <NEW_LINE> <INDENT> def items(self): <NEW_LINE> <INDENT> return list(Displayable.objects.url_map(in_sitemap=True).values()) <NEW_LINE> <DEDENT> def lastmod(self, obj): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_urls(self, **kwargs): <NEW_LINE> <INDENT> kwargs["site"] = Site.objects.get(id=current_site_id()) <NEW_LINE> return super(DisplayableSitemap, self).get_urls(**kwargs)
Sitemap class for Django's sitemaps framework that returns all published items for models that subclass ``Displayable``.
62598fd050812a4eaa620e04
class RandomWalk: <NEW_LINE> <INDENT> def __init__(self,num_points = 5000): <NEW_LINE> <INDENT> self.num_points = num_points <NEW_LINE> self.x_values = [0] <NEW_LINE> self.y_values = [0] <NEW_LINE> <DEDENT> def fill_walk(self): <NEW_LINE> <INDENT> while len(self.x_values)< self.num_points: <NEW_LINE> <INDENT> x_direction = choice([20, -20]) <NEW_LINE> x_distance = choice([0,2,4]) <NEW_LINE> x_step = x_direction * x_distance <NEW_LINE> y_direction = choice([0.1, -0.1]) <NEW_LINE> y_distance = choice ([0,1,3]) <NEW_LINE> y_step = y_direction * y_distance <NEW_LINE> if x_step ==0 and y_step ==0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> x = self.x_values[-1] + x_step <NEW_LINE> y = self.y_values[-1] + y_step <NEW_LINE> self.x_values.append(x) <NEW_LINE> self.y_values.append(y)
a class to generate random walks
62598fd0bf627c535bcb18ed
class CommonLocators: <NEW_LINE> <INDENT> EBANKING_PAGE_TITLE = By.XPATH, '//h1[contains(text(),"E-Banking login")]' <NEW_LINE> DEMO_APP_LINK = By.XPATH, '//a[contains(text(),"demo")]' <NEW_LINE> WELCOME_MSG = By.XPATH, '//button[@class="Button__StyledButton-sc-13wwmgi-0 jjajkX"]' <NEW_LINE> PAGE_TITLE = By.XPATH, '//h2[contains(text(),"Account and custody account overview")]'
Rules for finding elements that appear on multiple pages
62598fd0377c676e912f6f98
class arch_sh2a(generic_sh): <NEW_LINE> <INDENT> def __init__(self, myspec): <NEW_LINE> <INDENT> generic_sh.__init__(self, myspec) <NEW_LINE> self.settings["CFLAGS"] = "-O2 -m2a -pipe" <NEW_LINE> self.settings["CHOST"] = "sh2a-unknown-linux-gnu"
Builder class for SH-2A [Little-endian]
62598fd04a966d76dd5ef318
class BoletoItau(BoletoData): <NEW_LINE> <INDENT> nosso_numero = custom_property('nosso_numero', 8) <NEW_LINE> conta_cedente = custom_property('conta_cedente', 5) <NEW_LINE> agencia_cedente = custom_property('agencia_cedente', 4) <NEW_LINE> carteira = custom_property('carteira', 3) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(BoletoItau, self).__init__() <NEW_LINE> self.codigo_banco = "341" <NEW_LINE> self.logo_image = "logo_itau.jpg" <NEW_LINE> self.especie_documento = 'DM' <NEW_LINE> <DEDENT> @property <NEW_LINE> def dv_nosso_numero(self): <NEW_LINE> <INDENT> composto = "%4s%5s%3s%8s" % (self.agencia_cedente, self.conta_cedente, self.carteira, self.nosso_numero) <NEW_LINE> return self.modulo10(composto) <NEW_LINE> <DEDENT> @property <NEW_LINE> def dv_agencia_conta_cedente(self): <NEW_LINE> <INDENT> agencia_conta = "%s%s" % (self.agencia_cedente, self.conta_cedente) <NEW_LINE> return self.modulo10(agencia_conta) <NEW_LINE> <DEDENT> @property <NEW_LINE> def agencia_conta_cedente(self): <NEW_LINE> <INDENT> return "%s/%s-%s" % (self.agencia_cedente, self.conta_cedente, self.dv_agencia_conta_cedente) <NEW_LINE> <DEDENT> def format_nosso_numero(self): <NEW_LINE> <INDENT> return "%3s/%8s-%1s" % (self.carteira, self.nosso_numero, self.dv_nosso_numero) <NEW_LINE> <DEDENT> @property <NEW_LINE> def campo_livre(self): <NEW_LINE> <INDENT> return str("%3s%8s%1s%4s%5s%1s%3s" % ( self.carteira, self.nosso_numero, self.dv_nosso_numero, self.agencia_cedente, self.conta_cedente, self.dv_agencia_conta_cedente, '000'))
Implementa Boleto Itaú Gera Dados necessários para criação de boleto para o banco Itau Todas as carteiras com excessão das que utilizam 15 dígitos: (106,107, 195,196,198)
62598fd0ec188e330fdf8cd7
class FilterWordsPipeline(object): <NEW_LINE> <INDENT> words_to_filter = ['Female', 'Male'] <NEW_LINE> def process_item(self, item): <NEW_LINE> <INDENT> for word in self.words_to_filter: <NEW_LINE> <INDENT> if word in unicode(item['description']).lower(): <NEW_LINE> <INDENT> raise DropItem("!!!!!!!!!!!!!!!!!!!!!!!!!Contains forbidden word: %s" % word) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return item
A pipeline for filtering out items which contain certain words in their description
62598fd055399d3f0562695c
class Event(Base): <NEW_LINE> <INDENT> __slots__ = [ 'author', 'id', 'name', 'type', 'url', 'view' ] <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Event, self).__init__(**kwargs) <NEW_LINE> _event = kwargs.pop('event').pop('data') <NEW_LINE> author = {} <NEW_LINE> author['user_id'] = kwargs['user'].pop('id') <NEW_LINE> author['nickname'] = kwargs.pop('user').pop('nickname') <NEW_LINE> author['autokicked'] = None <NEW_LINE> author['image_url'] = None <NEW_LINE> author['muted'] = None <NEW_LINE> author['id'] = None <NEW_LINE> self.author = Member(**author) <NEW_LINE> self.id = kwargs.pop('event_id') <NEW_LINE> self.name = _event.pop('event').pop('name') <NEW_LINE> self.url = _event.pop('url') <NEW_LINE> self.view = kwargs.pop('view')
Represents a Group Me image Supported Operations: +-----------+---------------------------------------+ | Operation | Description | +===========+=======================================+ | x == y | Checks if two images are equal. | +-----------+---------------------------------------+ | x != y | Checks if two images are not equal. | +-----------+---------------------------------------+ | hash(x) | Returns the image's hash | +-----------+---------------------------------------+ | str(x) | Returns the image's URL. | +-----------+---------------------------------------+ Attributes ---------- author : :class:`Member` The person who made the calander even id : str The unique ID of the event name : str The name of the event type : str The type of the attachment url : str The URL of the image view : str Not sure yet
62598fd0cc40096d6161a3f8
class SomeLines(object): <NEW_LINE> <INDENT> def __init__(self, listoflines, comments): <NEW_LINE> <INDENT> self.listoflines = listoflines <NEW_LINE> self.comments = comments <NEW_LINE> self.getourid() <NEW_LINE> <DEDENT> def getourid(self): <NEW_LINE> <INDENT> cmsgid = None <NEW_LINE> if not isinstance(self, Entry): <NEW_LINE> <INDENT> for i in self.comments: <NEW_LINE> <INDENT> if isinstance(i, TildedComment): <NEW_LINE> <INDENT> if cmsgid is None: <NEW_LINE> <INDENT> a = i.has_msgid() <NEW_LINE> if a is not None: <NEW_LINE> <INDENT> cmsgid = [a, ] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> a = i.has_quot() <NEW_LINE> if a is not None: <NEW_LINE> <INDENT> cmsgid.append(a) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> self.cmsgid = ''.join(cmsgid) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.listoflines) + "\ncomments:" + str(self.comments) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def rawwrite(self, opened): <NEW_LINE> <INDENT> for line in self.listoflines: <NEW_LINE> <INDENT> opened.write(line) <NEW_LINE> <DEDENT> opened.write("\n") <NEW_LINE> <DEDENT> def sortingname(self): <NEW_LINE> <INDENT> if self.cmsgid is not None: <NEW_LINE> <INDENT> return self.cmsgid <NEW_LINE> <DEDENT> return self.comments[0].line
SomeLines represents some lines from between two empty lines, not necessarily an Entry
62598fd03346ee7daa337868
class LoginForm(Form): <NEW_LINE> <INDENT> username = TextField(u'Name', validators=[validators.required()]) <NEW_LINE> password = PasswordField(u'Password', validators=[validators.Required()] )
Login form for Kremlin application
62598fd050812a4eaa620e05
class UpdateMirror9Test(BaseTest): <NEW_LINE> <INDENT> fixtureGpg = True <NEW_LINE> fixtureCmds = [ "aptly mirror create --keyring=aptlytest.gpg -with-sources flat-src https://cloud.r-project.org/bin/linux/debian jessie-cran35/", ] <NEW_LINE> runCmd = "aptly mirror update --keyring=aptlytest.gpg flat-src" <NEW_LINE> outputMatchPrepare = filterOutSignature <NEW_LINE> def output_processor(self, output): <NEW_LINE> <INDENT> return "\n".join(sorted(output.split("\n")))
update mirrors: flat repository + sources
62598fd0ff9c53063f51aa8e
class XZYJointDiscriminator(Initializable): <NEW_LINE> <INDENT> def __init__(self, x_discriminator, z_discriminator, joint_discriminator, **kwargs): <NEW_LINE> <INDENT> self.x_discriminator = x_discriminator <NEW_LINE> self.z_discriminator = z_discriminator <NEW_LINE> self.joint_discriminator = joint_discriminator <NEW_LINE> super(XZYJointDiscriminator, self).__init__(**kwargs) <NEW_LINE> self.children.extend([self.x_discriminator, self.z_discriminator, self.joint_discriminator]) <NEW_LINE> <DEDENT> @application(inputs=['x', 'z', 'y'], outputs=['output']) <NEW_LINE> def apply(self, x, z, y): <NEW_LINE> <INDENT> input_ = tensor.unbroadcast( tensor.concatenate( [self.x_discriminator.apply(x), self.z_discriminator.apply(z), y], axis=1), *range(x.ndim)) <NEW_LINE> return self.joint_discriminator.apply(input_)
Three-way discriminator. Parameters ---------- x_discriminator : :class:`blocks.bricks.Brick` Part of the discriminator taking :math:`x` as input. Its output will be concatenated with ``z_discriminator``'s output and fed to ``joint_discriminator``. z_discriminator : :class:`blocks.bricks.Brick` Part of the discriminator taking :math:`z` as input. Its output will be concatenated with ``x_discriminator``'s output and fed to ``joint_discriminator``. joint_discriminator : :class:`blocks.bricks.Brick` Part of the discriminator taking the concatenation of ``x_discriminator``'s and output ``z_discriminator``'s output as input and computing :math:`D(x, z)`.
62598fd0377c676e912f6f99
class Attachment(models.Model): <NEW_LINE> <INDENT> document = models.ForeignKey( 'document_library.Document', verbose_name=_('Document'), ) <NEW_LINE> position = models.PositiveIntegerField( verbose_name=_('Position'), null=True, blank=True, ) <NEW_LINE> content_type = models.ForeignKey(ContentType) <NEW_LINE> object_id = models.PositiveIntegerField() <NEW_LINE> content_object = generic.GenericForeignKey('content_type', 'object_id') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['position', ]
Mapping class to map any object to ``Document`` objects. This allows you to add inlines to your admins and attach documents to your objects.
62598fd04a966d76dd5ef31a
class BFList(list): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "<{0}: {1}>".format(self.__class__.__name__, list(self)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> def index(self, item): <NEW_LINE> <INDENT> if isinstance(item, str): <NEW_LINE> <INDENT> for i, value in enumerate(self): <NEW_LINE> <INDENT> if getattr(value, "idname", None) == item: return i <NEW_LINE> <DEDENT> <DEDENT> return list.index(self, item) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if isinstance(key, str): <NEW_LINE> <INDENT> for value in self: <NEW_LINE> <INDENT> if getattr(value, "idname", None) == key: return value <NEW_LINE> <DEDENT> raise KeyError(key) <NEW_LINE> <DEDENT> if isinstance(key, tuple) or isinstance(key, list): <NEW_LINE> <INDENT> return BFList([self[k] for k in key]) <NEW_LINE> <DEDENT> return list.__getitem__(self, key) <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> if isinstance(key, str): return self.get(key, False) and True <NEW_LINE> return list.__contains__(self, key) <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> for value in self: <NEW_LINE> <INDENT> if getattr(value, "idname", None) == key: return value <NEW_LINE> <DEDENT> if default is not None: return default
Enhanced list of objects with idname property. Get an item by its idname: bf_list["item idname"] Get a BFList of items by items idnames: bf_list[("item1 idname", "item2 idname")] Get the index of item: bf_list.index["item idname"] Check presence of item: "item idname" in bf_list Get item by idname with default: bf_list.get("item idname", default)
62598fd07b180e01f3e49271
class rfi: <NEW_LINE> <INDENT> location = "/data/attack-payloads/rfi/rfi.txt" <NEW_LINE> rfi = file_read(location)
This implements the rfi payloads from fuzzdb
62598fd03617ad0b5ee0658c
class PutInstanceTool(DataTool): <NEW_LINE> <INDENT> only2d = False <NEW_LINE> def mousePressEvent(self, event): <NEW_LINE> <INDENT> if event.button() == Qt.LeftButton: <NEW_LINE> <INDENT> self.editingStarted.emit() <NEW_LINE> pos = self.mapToPlot(event.pos()) <NEW_LINE> self.issueCommand.emit(Append([pos])) <NEW_LINE> event.accept() <NEW_LINE> self.editingFinished.emit() <NEW_LINE> return True <NEW_LINE> <DEDENT> return super().mousePressEvent(event)
Add a single data instance with a mouse click.
62598fd03d592f4c4edbb2f9
class Dictionary(Command): <NEW_LINE> <INDENT> name = 'survey:dictionary' <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(Dictionary, self).get_parser(prog_name) <NEW_LINE> parser.add_argument("--file", help="Survey file", action="store", required=False) <NEW_LINE> parser.add_argument("name", help="Survey name", action="store") <NEW_LINE> parser.add_argument("--output", help="path of file to output results", required=False) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, args): <NEW_LINE> <INDENT> file = args.file <NEW_LINE> name = args.name <NEW_LINE> out = Output(args.output) <NEW_LINE> if file is None: <NEW_LINE> <INDENT> file="surveys/%s/survey.json" % (name, ) <NEW_LINE> print("Using survey in '%s'" % file) <NEW_LINE> <DEDENT> json = read_json(file) <NEW_LINE> survey = json_parser_survey(json) <NEW_LINE> output = to_json(survey_to_dict(survey, survey_name=name), indent=2) <NEW_LINE> out.write(output) <NEW_LINE> out.close()
Validate survey description file agaisnt json schema
62598fd0cc40096d6161a3f9
class ModelBias(Metric): <NEW_LINE> <INDENT> def __init__(self, target, model_output=None, name=None, element_wise=False): <NEW_LINE> <INDENT> name = "Bias_" + target if name is None else name <NEW_LINE> super(ModelBias, self).__init__(name) <NEW_LINE> self.target = target <NEW_LINE> self.model_output = model_output <NEW_LINE> self.element_wise = element_wise <NEW_LINE> self.l2loss = 0.0 <NEW_LINE> self.n_entries = 0.0 <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.l2loss = 0.0 <NEW_LINE> self.n_entries = 0.0 <NEW_LINE> <DEDENT> def _get_diff(self, y, yp): <NEW_LINE> <INDENT> return y - yp <NEW_LINE> <DEDENT> def add_batch(self, batch, result): <NEW_LINE> <INDENT> y = batch[self.target] <NEW_LINE> if self.model_output is None: <NEW_LINE> <INDENT> yp = result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if type(self.model_output) is list: <NEW_LINE> <INDENT> for idx in self.model_output: <NEW_LINE> <INDENT> result = result[idx] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result = result[self.model_output] <NEW_LINE> <DEDENT> yp = result <NEW_LINE> <DEDENT> diff = self._get_diff(y, yp) <NEW_LINE> self.l2loss += torch.sum(diff.view(-1)).detach().cpu().data.numpy() <NEW_LINE> if self.element_wise: <NEW_LINE> <INDENT> self.n_entries += ( torch.sum(batch[Structure.atom_mask]).detach().cpu().data.numpy() * y.shape[-1] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.n_entries += np.prod(y.shape) <NEW_LINE> <DEDENT> <DEDENT> def aggregate(self): <NEW_LINE> <INDENT> return self.l2loss / self.n_entries
Calculates the bias of the model. For non-scalar quantities, the mean of all components is taken. Args: target (str): name of target property model_output (int, str): index or key, in case of multiple outputs (Default: None) name (str): name used in logging for this metric. If set to `None`, `MSE_[target]` will be used (Default: None) element_wise (bool): set to True if the model output is an element-wise property (forces, positions, ...)
62598fd0099cdd3c63675601
class PotentialOperator: <NEW_LINE> <INDENT> def __init__(self, op, component_count, space, evaluation_points): <NEW_LINE> <INDENT> self._op = op <NEW_LINE> self._component_count = component_count <NEW_LINE> self._space = space <NEW_LINE> self._evaluation_points = evaluation_points <NEW_LINE> <DEDENT> def evaluate(self, grid_fun): <NEW_LINE> <INDENT> res = self._op * grid_fun.coefficients <NEW_LINE> return res.reshape(self._component_count, -1, order='F') <NEW_LINE> <DEDENT> def __is_compatible(self, other): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> return (self.component_count == other.component_count and np.linalg.norm(self.evaluation_points - other.evaluation_points, ord=np.inf) == 0 and self.space.is_compatible(other.space)) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> if not self.__is_compatible(other): <NEW_LINE> <INDENT> raise ValueError("Potential operators not compatible.") <NEW_LINE> <DEDENT> return PotentialOperator( self.discrete_operator + other.discrete_operator, self.component_count, self.space, self.evaluation_points) <NEW_LINE> <DEDENT> def __mul__(self, obj): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> from bempp.api import GridFunction <NEW_LINE> if not isinstance(self, PotentialOperator): <NEW_LINE> <INDENT> return obj * self <NEW_LINE> <DEDENT> if np.isscalar(obj): <NEW_LINE> <INDENT> return PotentialOperator(obj * self.discrete_operator, self.component_count, self.space, self.evaluation_points, ) <NEW_LINE> <DEDENT> elif isinstance(obj, GridFunction): <NEW_LINE> <INDENT> return self.evaluate(obj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError("Cannot multiply with object of type {0}".format(str(type(obj)))) <NEW_LINE> <DEDENT> <DEDENT> def __neg__(self): <NEW_LINE> <INDENT> return self.__mul__(-1.0) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return self.__add__(-other) <NEW_LINE> <DEDENT> @property <NEW_LINE> def space(self): <NEW_LINE> <INDENT> return self._space <NEW_LINE> <DEDENT> @property <NEW_LINE> def component_count(self): <NEW_LINE> <INDENT> return self._component_count <NEW_LINE> <DEDENT> @property <NEW_LINE> def evaluation_points(self): <NEW_LINE> <INDENT> return self._evaluation_points <NEW_LINE> <DEDENT> @property <NEW_LINE> def discrete_operator(self): <NEW_LINE> <INDENT> return self._op <NEW_LINE> <DEDENT> @property <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> return self._op.dtype
Provides an interface to potential operators. This class is not supposed to be instantiated directly.
62598fd050812a4eaa620e06
class CrawlTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> if os.path.isdir(TEST_DIR): <NEW_LINE> <INDENT> shutil.rmtree(TEST_DIR) <NEW_LINE> <DEDENT> os.mkdir(TEST_DIR) <NEW_LINE> self.args = { 'output': os.path.join(TEST_DIR, '%s.out' % self.filename), 'log_file': os.path.join(TEST_DIR, '%s.log' % self.filename), 'working_dir': TEST_DIR } <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> shutil.rmtree(TEST_DIR) <NEW_LINE> <DEDENT> def assert_cache(self): <NEW_LINE> <INDENT> cache_dir = os.path.join(TEST_DIR, '.scrapy', 'httpcache', '%s.leveldb' % self.spider) <NEW_LINE> self.assertTrue(os.path.isdir(cache_dir)) <NEW_LINE> <DEDENT> def assert_log(self): <NEW_LINE> <INDENT> log_path = self.args['log_file'] <NEW_LINE> self.assertTrue(os.path.isfile(log_path)) <NEW_LINE> <DEDENT> def get_output_content(self): <NEW_LINE> <INDENT> output_path = self.args['output'] <NEW_LINE> self.assertTrue(os.path.isfile(output_path)) <NEW_LINE> with open(output_path) as f: <NEW_LINE> <INDENT> content = f.read() <NEW_LINE> <DEDENT> return content
Base class for crawl test cases.
62598fd0ff9c53063f51aa90
class VirtualMachineIdentity(Model): <NEW_LINE> <INDENT> _validation = { 'principal_id': {'readonly': True}, 'tenant_id': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'principal_id': {'key': 'principalId', 'type': 'str'}, 'tenant_id': {'key': 'tenantId', 'type': 'str'}, 'type': {'key': 'type', 'type': 'ResourceIdentityType'}, } <NEW_LINE> def __init__(self, type=None): <NEW_LINE> <INDENT> self.principal_id = None <NEW_LINE> self.tenant_id = None <NEW_LINE> self.type = type
Identity for the virtual machine. Variables are only populated by the server, and will be ignored when sending a request. :ivar principal_id: The principal id of virtual machine identity. :vartype principal_id: str :ivar tenant_id: The tenant id associated with the virtual machine. :vartype tenant_id: str :param type: The type of identity used for the virtual machine. Currently, the only supported type is 'SystemAssigned', which implicitly creates an identity. Possible values include: 'SystemAssigned' :type type: str or :class:`ResourceIdentityType <azure.mgmt.compute.v2016_03_30.models.ResourceIdentityType>`
62598fd097e22403b383b34d
class CleanImages(superdesk.Command): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print('Starting image cleaning.') <NEW_LINE> used_images = set() <NEW_LINE> types = ['picture', 'video', 'audio'] <NEW_LINE> query = {'$or': [{'type': {'$in': types}}, {ASSOCIATIONS: {'$ne': None}}]} <NEW_LINE> archive_items = superdesk.get_resource_service('archive').get_from_mongo(None, query) <NEW_LINE> self.__add_existing_files(used_images, archive_items) <NEW_LINE> archive_version_items = superdesk.get_resource_service('archive_versions').get_from_mongo(None, query) <NEW_LINE> self.__add_existing_files(used_images, archive_version_items) <NEW_LINE> ingest_items = superdesk.get_resource_service('ingest').get_from_mongo(None, {'type': {'$in': types}}) <NEW_LINE> self.__add_existing_files(used_images, ingest_items) <NEW_LINE> upload_items = superdesk.get_resource_service('upload').get_from_mongo(req=None, lookup={}) <NEW_LINE> self.__add_existing_files(used_images, upload_items) <NEW_LINE> legal_archive_items = superdesk.get_resource_service('legal_archive').get_from_mongo(None, query) <NEW_LINE> self.__add_existing_files(used_images, legal_archive_items) <NEW_LINE> legal_archive_version_items = superdesk.get_resource_service('legal_archive_versions'). get_from_mongo(None, query) <NEW_LINE> self.__add_existing_files(used_images, legal_archive_version_items) <NEW_LINE> print('Number of used files: ', len(used_images)) <NEW_LINE> superdesk.app.media.remove_unreferenced_files(used_images) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> print(ex) <NEW_LINE> <DEDENT> <DEDENT> def __add_existing_files(self, used_images, items): <NEW_LINE> <INDENT> for item in items: <NEW_LINE> <INDENT> if 'media' in item: <NEW_LINE> <INDENT> used_images.add(str(item['media'])) <NEW_LINE> <DEDENT> if item.get('renditions', {}): <NEW_LINE> <INDENT> used_images.add([str(rend.get('media')) for rend in item.get('renditions', {}).values() if rend.get('media')]) <NEW_LINE> <DEDENT> associations = [assoc.get('renditions') for assoc in (item.get(ASSOCIATIONS) or {}).values() if assoc and assoc.get('renditions')] <NEW_LINE> if associations: <NEW_LINE> <INDENT> for renditions in associations: <NEW_LINE> <INDENT> used_images.add([str(rend.get('media')) for rend in renditions.values() if rend.get('media')])
This command will remove all the images from the system which are not referenced by content. It checks the media type and calls the correspoinding function as s3 and mongo requires different approaches for handling multiple files. Probably running db.repairDatabase() is needed in Mongo to shring the DB size.
62598fd0ec188e330fdf8cdb
class ResizeImageTransformer(BaseTransformer): <NEW_LINE> <INDENT> def __init__(self, fraction_of_current_size): <NEW_LINE> <INDENT> self.fraction_of_current_size = fraction_of_current_size <NEW_LINE> <DEDENT> @overrides <NEW_LINE> def transform(self, observation): <NEW_LINE> <INDENT> return scipy.misc.imresize(observation, self.fraction_of_current_size) <NEW_LINE> <DEDENT> @overrides <NEW_LINE> def transformed_observation_space(self, wrapped_observation_space): <NEW_LINE> <INDENT> if type(wrapped_observation_space) is Box: <NEW_LINE> <INDENT> return Box(scipy.misc.imresize(wrapped_observation_space.low, self.fraction_of_current_size), scipy.misc.imresize(wrapped_observation_space.high, self.fraction_of_current_size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError("Currently only support Box observation spaces for ResizeImageTransformer")
Rescale a given image by a percentage
62598fd0656771135c489ab6
class HousePurchase(Purchase, House): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def prompt_init(): <NEW_LINE> <INDENT> init = House.prompt_init() <NEW_LINE> init.update(Purchase.prompt_init()) <NEW_LINE> return init
A class representin a house that is put for sale, having the details of both House and transaction to be made to purchase the house and the piece of land, that goes with the specified house
62598fd0956e5f7376df58a0
class EndPoint(TimePoint): <NEW_LINE> <INDENT> XML_tag = "end" <NEW_LINE> XML_tag_legacy = 'tEnd' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(self.__class__, self).__init__()
The end time of a :class:`~objects.TimeWindow.TimeWindow`. See documentation for :class:`~objects.timePoints.TimePoint`.
62598fd0091ae35668705071
class GuiFuncs(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def open_file(caption, lineedit: QtWidgets.QLineEdit, display_container: QtWidgets.QTextEdit or None = None, file: bool = True): <NEW_LINE> <INDENT> if file: <NEW_LINE> <INDENT> filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption=caption, directory=getcwd(), initialFilter="Text Files (*.txt)") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filename = QtWidgets.QFileDialog.getExistingDirectory(caption=caption, directory=getcwd()) <NEW_LINE> <DEDENT> lineedit.setText(filename) <NEW_LINE> if display_container: <NEW_LINE> <INDENT> GuiFuncs.display_load_data(load_file=filename, display_container=display_container) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def read_txt(path: str): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> with open(path, 'r') as file: <NEW_LINE> <INDENT> for line in file: <NEW_LINE> <INDENT> ans.append(line.strip()) <NEW_LINE> <DEDENT> <DEDENT> ans = [int(i) for i in ans] <NEW_LINE> x1, y1, x2, y2 = ans <NEW_LINE> ans = [(x1, y1), (x2, y2)] <NEW_LINE> return ans <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def display_load_data(load_file: str, display_container: QtWidgets.QTextEdit): <NEW_LINE> <INDENT> with open(load_file, 'r+') as file: <NEW_LINE> <INDENT> text = file.read() <NEW_LINE> display_container.setText(text) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def error(title, message): <NEW_LINE> <INDENT> msg = QtWidgets.QMessageBox() <NEW_LINE> msg.setWindowTitle(title) <NEW_LINE> msg.setText(message) <NEW_LINE> msg.exec_() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def string_to_list(var: str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ans = [int(num) for num in var.split(',')] <NEW_LINE> <DEDENT> except Exception as _: <NEW_LINE> <INDENT> ans = [] <NEW_LINE> <DEDENT> return ans <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def check_filter(text: str, length: int, edit_field: str): <NEW_LINE> <INDENT> ans = 1 <NEW_LINE> statement = f'Please edit the {edit_field} field' <NEW_LINE> text_length = len(text.split(',')) <NEW_LINE> if text_length < length: <NEW_LINE> <INDENT> ans = 0 <NEW_LINE> <DEDENT> text = [val.strip() for val in text.split(',')] <NEW_LINE> for val in text: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(val) <NEW_LINE> <DEDENT> except Exception as _: <NEW_LINE> <INDENT> print(_, val) <NEW_LINE> ans = 0 <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> if ans == 0: <NEW_LINE> <INDENT> GuiFuncs.error('Input Error', statement) <NEW_LINE> <DEDENT> return ans
Class linking functions to existing gui
62598fd0fbf16365ca794502
class Catcher(base.PyGameWrapper): <NEW_LINE> <INDENT> def __init__(self, width=256, height=256, init_lives=3): <NEW_LINE> <INDENT> actions = { "left": K_a, "right": K_d } <NEW_LINE> base.PyGameWrapper.__init__(self, width, height, actions=actions) <NEW_LINE> self.fruit_size = percent_round_int(height, 0.06) <NEW_LINE> self.fruit_fall_speed = 0.00095 * height <NEW_LINE> self.player_speed = 0.021 * width <NEW_LINE> self.paddle_width = percent_round_int(width, 0.2) <NEW_LINE> self.paddle_height = percent_round_int(height, 0.04) <NEW_LINE> self.dx = 0.0 <NEW_LINE> self.init_lives = init_lives <NEW_LINE> <DEDENT> def _handle_player_events(self): <NEW_LINE> <INDENT> self.dx = 0.0 <NEW_LINE> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> pygame.quit() <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> if event.type == pygame.KEYDOWN: <NEW_LINE> <INDENT> key = event.key <NEW_LINE> if key == self.actions['left']: <NEW_LINE> <INDENT> self.dx -= self.player_speed <NEW_LINE> <DEDENT> if key == self.actions['right']: <NEW_LINE> <INDENT> self.dx += self.player_speed <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def init(self): <NEW_LINE> <INDENT> self.score = 0 <NEW_LINE> self.lives = self.init_lives <NEW_LINE> self.player = Paddle(self.player_speed, self.paddle_width, self.paddle_height, self.width, self.height) <NEW_LINE> self.fruit = Fruit(self.fruit_fall_speed, self.fruit_size, self.width, self.height, self.rng) <NEW_LINE> self.fruit.reset() <NEW_LINE> <DEDENT> def getGameState(self): <NEW_LINE> <INDENT> state = { "player_x": self.player.rect.center[0], "player_vel": self.player.vel, "fruit_x": self.fruit.rect.center[0], "fruit_y": self.fruit.rect.center[1] } <NEW_LINE> return state <NEW_LINE> <DEDENT> def getScore(self): <NEW_LINE> <INDENT> return self.score <NEW_LINE> <DEDENT> def game_over(self): <NEW_LINE> <INDENT> return self.lives == 0 <NEW_LINE> <DEDENT> def step(self, dt): <NEW_LINE> <INDENT> self.screen.fill((0, 0, 0)) <NEW_LINE> self._handle_player_events() <NEW_LINE> self.score += self.rewards["tick"] <NEW_LINE> if self.fruit.rect.center[1] >= self.height: <NEW_LINE> <INDENT> self.score += self.rewards["negative"] <NEW_LINE> self.lives -= 1 <NEW_LINE> self.fruit.reset() <NEW_LINE> <DEDENT> if pygame.sprite.collide_rect(self.player, self.fruit): <NEW_LINE> <INDENT> self.score += self.rewards["positive"] <NEW_LINE> self.fruit.reset() <NEW_LINE> <DEDENT> self.player.update(self.dx, dt) <NEW_LINE> self.fruit.update(dt) <NEW_LINE> if self.lives == 0: <NEW_LINE> <INDENT> self.score += self.rewards["loss"] <NEW_LINE> <DEDENT> self.player.draw(self.screen) <NEW_LINE> self.fruit.draw(self.screen)
Based on `Eder Santana`_'s game idea. .. _`Eder Santana`: https://github.com/EderSantana Parameters ---------- width : int Screen width. height : int Screen height, recommended to be same dimension as width. init_lives : int (default: 3) The number lives the agent has.
62598fd03d592f4c4edbb2fb
class CacheController(BaseController): <NEW_LINE> <INDENT> @ckan_cache() <NEW_LINE> def defaults(self): <NEW_LINE> <INDENT> return "defaults" <NEW_LINE> <DEDENT> @ckan_cache(test=lambda *av, **kw: start + 3600) <NEW_LINE> def future(self): <NEW_LINE> <INDENT> return "future" <NEW_LINE> <DEDENT> @ckan_cache(test=lambda *av, **kw: now()) <NEW_LINE> def always(self): <NEW_LINE> <INDENT> return "always"
Dummy controller - we are testing the decorator not the controller
62598fd0099cdd3c63675602
class Topic(object): <NEW_LINE> <INDENT> def __init__(self, pub_or_sub, name_regex, *args, **kwargs): <NEW_LINE> <INDENT> self._pub_or_sub = pub_or_sub <NEW_LINE> self._name_regex = name_regex <NEW_LINE> self._args = args <NEW_LINE> self._kwargs = kwargs <NEW_LINE> self._topics = {} <NEW_LINE> topics = self._get_all_topics() <NEW_LINE> for topic in topics: <NEW_LINE> <INDENT> if re.match(name_regex, topic): <NEW_LINE> <INDENT> self._call_pub_or_sub(topic) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def reload_topics(self): <NEW_LINE> <INDENT> topics = self._get_all_topics() <NEW_LINE> for topic in topics: <NEW_LINE> <INDENT> if topic not in self._topics and re.match(self._name_regex, topic): <NEW_LINE> <INDENT> self._call_pub_or_sub(topic) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _get_all_topics(self): <NEW_LINE> <INDENT> master = rosgraph.Master('/rostopic') <NEW_LINE> try: <NEW_LINE> <INDENT> pubs, subs, _ = master.getSystemState() <NEW_LINE> <DEDENT> except socket.error: <NEW_LINE> <INDENT> raise ROSTopicIOException("Unable to communicate with master!") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> topics = list(set([t for t, _ in pubs] + [t for t, _ in subs])) <NEW_LINE> return sorted(topics) <NEW_LINE> <DEDENT> <DEDENT> def _call_pub_or_sub(self, topic): <NEW_LINE> <INDENT> data_class = rostopic.get_topic_class(topic)[0] <NEW_LINE> pub_or_sub = self._pub_or_sub(topic, data_class, *self._args, **self._kwargs) <NEW_LINE> self._topics[topic] = pub_or_sub <NEW_LINE> <DEDENT> def unregister(self, topic_name): <NEW_LINE> <INDENT> if topic_name in self._topics: <NEW_LINE> <INDENT> topic = self._topics.pop(topic_name) <NEW_LINE> topic.unregister() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rospy.logwarn("topic {} is not in subscribed topics".format(topic_name)) <NEW_LINE> <DEDENT> <DEDENT> def unregister_all(self): <NEW_LINE> <INDENT> for topic in self._topics.values(): <NEW_LINE> <INDENT> topic.unregister() <NEW_LINE> <DEDENT> self._topics.clear()
Super class for wildcard subscriber / publisher :type _topics: dict[str, (rospy.Subscriber|rospy.Publisher)]
62598fd09f28863672818aa0
class ObservedMac(Base): <NEW_LINE> <INDENT> __tablename__ = 'observed_mac' <NEW_LINE> switch_id = Column(Integer, ForeignKey('tor_switch.id', ondelete='CASCADE', name='obs_mac_hw_fk'), primary_key=True) <NEW_LINE> port_number = Column(Integer, primary_key=True) <NEW_LINE> mac_address = Column(AqMac(17), nullable=False, primary_key=True) <NEW_LINE> slot = Column(Integer, nullable=True, default=1, primary_key=True) <NEW_LINE> creation_date = deferred(Column('creation_date', DateTime, default=datetime.now, nullable=False)) <NEW_LINE> last_seen = deferred(Column('last_seen', DateTime, default=datetime.now, nullable=False)) <NEW_LINE> switch = relation(TorSwitch, backref=backref('observed_macs', cascade='delete', order_by=[asc('slot'), asc('port_number')]))
reports the observance of a mac address on a switch port.
62598fd0656771135c489ab8
class City(Base): <NEW_LINE> <INDENT> __tablename__ = 'cities' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String(128), nullable=False) <NEW_LINE> state_id = Column(Integer, ForeignKey("states.id"), nullable=False) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<Cities(name =' %s')>" % (self.name)
The city class for this table
62598fd060cbc95b06364785
@functools.total_ordering <NEW_LINE> class PhononMode(object): <NEW_LINE> <INDENT> __slots__ = [ "qpoint", "freq", "displ_cart", "structure" ] <NEW_LINE> def __init__(self, qpoint, freq, displ_cart, structure): <NEW_LINE> <INDENT> self.qpoint = Kpoint.as_kpoint(qpoint, structure.reciprocal_lattice) <NEW_LINE> self.freq = freq <NEW_LINE> self.displ_cart = displ_cart <NEW_LINE> self.structure = structure <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.freq == other.freq <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.freq < other.freq
A phonon mode has a q-point, a frequency, a cartesian displacement and a structure.
62598fd08a349b6b43686689
class TestGrainsReg(ModuleCase, LoaderModuleMockMixin): <NEW_LINE> <INDENT> def setup_loader_modules(self): <NEW_LINE> <INDENT> self.opts = opts = salt.config.DEFAULT_MINION_OPTS.copy() <NEW_LINE> utils = salt.loader.utils(opts, whitelist=['reg']) <NEW_LINE> return { salt.modules.reg: { '__opts__': opts, '__utils__': utils, } } <NEW_LINE> <DEDENT> @skipIf(not salt.utils.platform.is_windows(), 'Only run on Windows') <NEW_LINE> def test_win_cpu_model(self): <NEW_LINE> <INDENT> cpu_model_text = salt.modules.reg.read_value( 'HKEY_LOCAL_MACHINE', 'HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0', 'ProcessorNameString').get('vdata') <NEW_LINE> self.assertEqual( self.run_function('grains.items')['cpu_model'], cpu_model_text )
Test the core windows grains
62598fd0cc40096d6161a3fb
class InternalGetVariable(InternalThreadCommand): <NEW_LINE> <INDENT> def __init__(self, seq, thread_id, frame_id, scope, attrs): <NEW_LINE> <INDENT> self.sequence = seq <NEW_LINE> self.thread_id = thread_id <NEW_LINE> self.frame_id = frame_id <NEW_LINE> self.scope = scope <NEW_LINE> self.attributes = attrs <NEW_LINE> <DEDENT> def do_it(self, dbg): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> xml = StringIO.StringIO() <NEW_LINE> xml.write("<xml>") <NEW_LINE> _typeName, val_dict = pydevd_vars.resolve_compound_variable_fields(self.thread_id, self.frame_id, self.scope, self.attributes) <NEW_LINE> if val_dict is None: <NEW_LINE> <INDENT> val_dict = {} <NEW_LINE> <DEDENT> keys = dict_keys(val_dict) <NEW_LINE> if not (_typeName == "OrderedDict" or val_dict.__class__.__name__ == "OrderedDict" or IS_PY36_OR_GREATER): <NEW_LINE> <INDENT> keys.sort(key=compare_object_attrs_key) <NEW_LINE> <DEDENT> for k in keys: <NEW_LINE> <INDENT> val = val_dict[k] <NEW_LINE> evaluate_full_value = pydevd_xml.should_evaluate_full_value(val) <NEW_LINE> xml.write(pydevd_xml.var_to_xml(val, k, evaluate_full_value=evaluate_full_value)) <NEW_LINE> <DEDENT> xml.write("</xml>") <NEW_LINE> cmd = dbg.cmd_factory.make_get_variable_message(self.sequence, xml.getvalue()) <NEW_LINE> xml.close() <NEW_LINE> dbg.writer.add_command(cmd) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> cmd = dbg.cmd_factory.make_error_message( self.sequence, "Error resolving variables %s" % (get_exception_traceback_str(),)) <NEW_LINE> dbg.writer.add_command(cmd)
gets the value of a variable
62598fd097e22403b383b351
class HashServices (object): <NEW_LINE> <INDENT> def __init__(self, nodes): <NEW_LINE> <INDENT> self.nodes=[] <NEW_LINE> for n in nodes: <NEW_LINE> <INDENT> if n == 'self': <NEW_LINE> <INDENT> self.nodes.append(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.nodes.append(xmlrpclib.Server(n)) <NEW_LINE> <DEDENT> <DEDENT> self.storage={} <NEW_LINE> <DEDENT> def storeLocal(self, key, value): <NEW_LINE> <INDENT> self.storage[key]=value <NEW_LINE> return True <NEW_LINE> <DEDENT> def getLocal(self, key): <NEW_LINE> <INDENT> return self.storage[key] <NEW_LINE> <DEDENT> def keysLocal(self): <NEW_LINE> <INDENT> return self.storage.keys() <NEW_LINE> <DEDENT> def containsLocal(self, key): <NEW_LINE> <INDENT> return key in self.storage <NEW_LINE> <DEDENT> def deleteLocal(self, key): <NEW_LINE> <INDENT> del self.storage[key] <NEW_LINE> return True <NEW_LINE> <DEDENT> def __getNode(self, h): <NEW_LINE> <INDENT> return self.nodes[h % len(self.nodes)] <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> return self.__getNode(hash(key)).getLocal(key) <NEW_LINE> <DEDENT> def store(self, key, value): <NEW_LINE> <INDENT> return self.__getNode(hash(key)).storeLocal(key, value) <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> rv=[] <NEW_LINE> for n in self.nodes: <NEW_LINE> <INDENT> rv.extend(n.keysLocal()) <NEW_LINE> <DEDENT> return rv <NEW_LINE> <DEDENT> def contains(self, key): <NEW_LINE> <INDENT> return self.__getNode(hash(key)).containsLocal(key) <NEW_LINE> <DEDENT> def delete(self, key): <NEW_LINE> <INDENT> return self.__getNode(hash(key)).deleteLocal(key)
Basic hash services.
62598fd0ec188e330fdf8cdf
class LoadDialog(BoxLayout): <NEW_LINE> <INDENT> load = ObjectProperty(None) <NEW_LINE> cancel = ObjectProperty(None) <NEW_LINE> file_types = ListProperty(['*.*']) <NEW_LINE> text_input = ObjectProperty(None) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(LoadDialog, self).__init__(**kwargs) <NEW_LINE> self.filechooser.path = './' <NEW_LINE> self.create_drives() <NEW_LINE> <DEDENT> def create_drives(self): <NEW_LINE> <INDENT> for i in get_win_drives(): <NEW_LINE> <INDENT> btn = DarkButton() <NEW_LINE> btn.text = i <NEW_LINE> btn.bind(on_press=self.on_drive_selected) <NEW_LINE> self.ids.drives_list.add_widget(btn) <NEW_LINE> <DEDENT> self.ids.drives_list.add_widget(Label()) <NEW_LINE> <DEDENT> def on_drive_selected(self, *args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> selected_drive = args[0].text <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.filechooser.path = selected_drive
'Load File' popup dialog.
62598fd0091ae35668705075
class DirectoryMarketingDescription(object): <NEW_LINE> <INDENT> swagger_types = { 'de': 'list[str]', 'en': 'list[str]', 'fr': 'list[str]', 'it': 'list[str]' } <NEW_LINE> attribute_map = { 'de': 'de', 'en': 'en', 'fr': 'fr', 'it': 'it' } <NEW_LINE> def __init__(self, de=None, en=None, fr=None, it=None): <NEW_LINE> <INDENT> self._de = None <NEW_LINE> self._en = None <NEW_LINE> self._fr = None <NEW_LINE> self._it = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.de = de <NEW_LINE> self.en = en <NEW_LINE> self.fr = fr <NEW_LINE> self.it = it <NEW_LINE> <DEDENT> @property <NEW_LINE> def de(self): <NEW_LINE> <INDENT> return self._de <NEW_LINE> <DEDENT> @de.setter <NEW_LINE> def de(self, de): <NEW_LINE> <INDENT> if de is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `de`, must not be `None`") <NEW_LINE> <DEDENT> self._de = de <NEW_LINE> <DEDENT> @property <NEW_LINE> def en(self): <NEW_LINE> <INDENT> return self._en <NEW_LINE> <DEDENT> @en.setter <NEW_LINE> def en(self, en): <NEW_LINE> <INDENT> if en is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `en`, must not be `None`") <NEW_LINE> <DEDENT> self._en = en <NEW_LINE> <DEDENT> @property <NEW_LINE> def fr(self): <NEW_LINE> <INDENT> return self._fr <NEW_LINE> <DEDENT> @fr.setter <NEW_LINE> def fr(self, fr): <NEW_LINE> <INDENT> if fr is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `fr`, must not be `None`") <NEW_LINE> <DEDENT> self._fr = fr <NEW_LINE> <DEDENT> @property <NEW_LINE> def it(self): <NEW_LINE> <INDENT> return self._it <NEW_LINE> <DEDENT> @it.setter <NEW_LINE> def it(self, it): <NEW_LINE> <INDENT> if it is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `it`, must not be `None`") <NEW_LINE> <DEDENT> self._it = it <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(DirectoryMarketingDescription, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = 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, DirectoryMarketingDescription): <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
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fd03617ad0b5ee06591
class Resource(MethodView): <NEW_LINE> <INDENT> representations = None <NEW_LINE> method_decorators = [] <NEW_LINE> def dispatch_request(self, *args, **kwargs): <NEW_LINE> <INDENT> meth = getattr(self, request.method.lower(), None) <NEW_LINE> if meth is None and request.method == 'HEAD': <NEW_LINE> <INDENT> meth = getattr(self, 'get', None) <NEW_LINE> <DEDENT> assert meth is not None, 'Unimplemented method %r' % request.method <NEW_LINE> if isinstance(self.method_decorators, Mapping): <NEW_LINE> <INDENT> decorators = self.method_decorators.get(request.method.lower(), []) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> decorators = self.method_decorators <NEW_LINE> <DEDENT> for decorator in decorators: <NEW_LINE> <INDENT> meth = decorator(meth) <NEW_LINE> <DEDENT> resp = meth(*args, **kwargs) <NEW_LINE> if isinstance(resp, ResponseBase): <NEW_LINE> <INDENT> return resp <NEW_LINE> <DEDENT> representations = self.representations or OrderedDict() <NEW_LINE> mediatype = request.accept_mimetypes.best_match(representations, default=None) <NEW_LINE> if mediatype in representations: <NEW_LINE> <INDENT> data, code, headers = unpack(resp) <NEW_LINE> resp = representations[mediatype](data, code, headers) <NEW_LINE> resp.headers['Content-Type'] = mediatype <NEW_LINE> return resp <NEW_LINE> <DEDENT> return resp
Represents an abstract RESTful resource. Concrete resources should extend from this class and expose methods for each supported HTTP method. If a resource is invoked with an unsupported HTTP method, the API will return a response with status 405 Method Not Allowed. Otherwise the appropriate method is called and passed all arguments from the url rule used when adding the resource to an Api instance. See :meth:`~flask_restful.Api.add_resource` for details.
62598fd0bf627c535bcb18f7
class File(Base, bob.db.base.File): <NEW_LINE> <INDENT> __tablename__ = 'file' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> client_id = Column(Integer, ForeignKey('client.id')) <NEW_LINE> path = Column(String(100), unique=True) <NEW_LINE> session_id = Column(Integer) <NEW_LINE> camera_choices = ('ca0', 'caf', 'wc') <NEW_LINE> camera = Column(Enum(*camera_choices)) <NEW_LINE> shot_id = Column(Integer) <NEW_LINE> client = relationship("Client", backref=backref("files", order_by=id)) <NEW_LINE> annotation = relationship("Annotation", backref=backref("file"), uselist=False) <NEW_LINE> def __init__(self, client_id, path, session_id, camera, shot_id): <NEW_LINE> <INDENT> bob.db.base.File.__init__(self, path = path) <NEW_LINE> self.client_id = client_id <NEW_LINE> self.session_id = session_id <NEW_LINE> self.camera = camera <NEW_LINE> self.shot_id = shot_id
Generic file container
62598fd060cbc95b06364789
class FullpowerAnimator(Animator): <NEW_LINE> <INDENT> def __init__(self, calanfpga): <NEW_LINE> <INDENT> Animator.__init__(self, calanfpga) <NEW_LINE> self.figure = CalanFigure(n_plots=1, create_gui=True) <NEW_LINE> self.figure.create_axis(0, FullpowerAxis, self.settings.pow_info['reg_list']) <NEW_LINE> <DEDENT> def add_figure_widgets(self): <NEW_LINE> <INDENT> self.add_save_widgets("fullpower_data") <NEW_LINE> self.add_reset_button('pow_rst', 'Reset') <NEW_LINE> self.add_reg_entry(self.settings.pow_info['acc_len_reg']) <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> pow_data_arr = self.fpga.get_reg_list_data(self.settings.pow_info['reg_list']) <NEW_LINE> pow_data_arr = pow_data_arr / float(self.fpga.read_reg(self.settings.pow_info['acc_len_reg'])) <NEW_LINE> pow_data_arr = 10*np.log10(pow_data_arr) <NEW_LINE> pow_data_arr = pow_data_arr - (6.02*8 + 1.76) <NEW_LINE> return pow_data_arr
Class used to plot full bandwidth power of ADC signals as bar plot. Useful to test the power calibration of multiple ADC.
62598fd05fcc89381b266372
class PageNumberPagination(object): <NEW_LINE> <INDENT> page_size = settings.API_PAGE_SIZE <NEW_LINE> django_paginator_class = Paginator <NEW_LINE> page_query_param = "page" <NEW_LINE> page_size_query_param = 'page_size' <NEW_LINE> max_page_size = None <NEW_LINE> last_page_strings = ("last",) <NEW_LINE> request = None <NEW_LINE> paginator = None <NEW_LINE> invalid_page_message = 'Invalid page "{page_number}": {message}.' <NEW_LINE> def paginate_queryset(self, queryset, view=None): <NEW_LINE> <INDENT> page_size = self.get_page_size(view) <NEW_LINE> if not page_size: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.paginator = self.django_paginator_class(queryset, page_size) <NEW_LINE> page_number = self.request.GET.get(self.page_query_param, 1) <NEW_LINE> if page_number in self.last_page_strings: <NEW_LINE> <INDENT> page_number = self.paginator.num_pages <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.page = self.paginator.page(page_number) <NEW_LINE> <DEDENT> except InvalidPage as exc: <NEW_LINE> <INDENT> msg = self.invalid_page_message.format(page_number=page_number, message=six.text_type(exc)) <NEW_LINE> raise api_exceptions.NotFound(msg) <NEW_LINE> <DEDENT> return list(self.page) <NEW_LINE> <DEDENT> def get_paginated_response(self, data): <NEW_LINE> <INDENT> meta = dict( [ ("base", getattr(settings, "REQUEST_SCHEME") + "://" + self.request.get_host()), ("next", self.get_next_link()), ("count", self.paginator.count), ] ) <NEW_LINE> return OrderedDict([("data", data), ("meta", meta)]) <NEW_LINE> <DEDENT> def get_page_size(self, view): <NEW_LINE> <INDENT> if self.page_size_query_param: <NEW_LINE> <INDENT> if getattr(view, 'max_page_size', None): <NEW_LINE> <INDENT> self.max_page_size = view.max_page_size <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return _positive_int( self.request.GET[self.page_size_query_param], strict=True, cutoff=self.max_page_size ) <NEW_LINE> <DEDENT> except (KeyError, ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return self.page_size <NEW_LINE> <DEDENT> def get_next_link(self): <NEW_LINE> <INDENT> if not self.page.has_next(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> url = self.request.build_absolute_uri() <NEW_LINE> page_number = self.page.next_page_number() <NEW_LINE> return replace_query_param(url, self.page_query_param, page_number) <NEW_LINE> <DEDENT> def get_previous_link(self): <NEW_LINE> <INDENT> if not self.page.has_previous(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> url = self.request.build_absolute_uri() <NEW_LINE> page_number = self.page.previous_page_number() <NEW_LINE> return replace_query_param(url, self.page_query_param, page_number)
A simple page number based style that supports page numbers as query parameters. For example: http://api.example.org/accounts/?page=4 http://api.example.org/accounts/?page=4&page_size=100
62598fd0099cdd3c63675605
class AddressType(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'address_types' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> address_type = db.Column(db.String) <NEW_LINE> def __init__(self, address_type): <NEW_LINE> <INDENT> self.address_type = address_type
1|Electoral Postal 2|Electoral Physical 3|Parliamentary Postal 4|Parliamentary Physical 5|Alternative
62598fd0377c676e912f6f9e
class Potential (object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.explanation = ""
A potential class. Defined with the presence of two elements of the system.
62598fd04a966d76dd5ef324
class TemplateNodeRelationManager(models.Manager): <NEW_LINE> <INDENT> def related_map(self): <NEW_LINE> <INDENT> return self.select_related() <NEW_LINE> <DEDENT> def has_same_node(self, node, template): <NEW_LINE> <INDENT> return self.filter(node__code=node.code, node__name=node.name, node__parent=node.parent, template=template).count()
Exposes additional methods for model query operations. Open Budgets makes extensive use of related_map and related_map_min methods for efficient bulk select queries.
62598fd0283ffb24f3cf3cd2
class Shots: <NEW_LINE> <INDENT> def __init__(self, player_id, league_id="00", season="2014-15", season_type="Regular Season", team_id=0, game_id="", outcome="", location="", month=0, season_segment="", date_from="", date_to="", opp_team_id=0, vs_conference="", vs_division="", position="", rookie_year="", game_segment="", period=0, last_n_games=0, clutch_time="", ahead_behind="", point_diff="", range_type="", start_period="", end_period="", start_range="", end_range="", context_filter="", context_measure="FGA"): <NEW_LINE> <INDENT> self.player_id = player_id <NEW_LINE> self.base_url = "http://stats.nba.com/stats/shotchartdetail?" <NEW_LINE> self.url_paramaters = { "LeagueID": league_id, "Season": season, "SeasonType": season_type, "TeamID": team_id, "PlayerID": player_id, "GameID": game_id, "Outcome": outcome, "Location": location, "Month": month, "SeasonSegment": season_segment, "DateFrom": date_from, "DateTo": date_to, "OpponentTeamID": opp_team_id, "VsConference": vs_conference, "VsDivision": vs_division, "Position": position, "RookieYear": rookie_year, "GameSegment": game_segment, "Period": period, "LastNGames": last_n_games, "ClutchTime": clutch_time, "AheadBehind": ahead_behind, "PointDiff": point_diff, "RangeType": range_type, "StartPeriod": start_period, "EndPeriod": end_period, "StartRange": start_range, "EndRange": end_range, "ContextFilter": context_filter, "ContextMeasure": context_measure } <NEW_LINE> self.response = requests.get(self.base_url, params=self.url_paramaters) <NEW_LINE> <DEDENT> def change_params(self, parameters): <NEW_LINE> <INDENT> self.url_paramaters.update(parameters) <NEW_LINE> self.response = requests.get(self.base_url, params=self.url_paramaters) <NEW_LINE> <DEDENT> def get_shots(self): <NEW_LINE> <INDENT> shots = self.response.json()['resultSets'][0]['rowSet'] <NEW_LINE> headers = self.response.json()['resultSets'][0]['headers'] <NEW_LINE> return pd.DataFrame(shots, columns=headers) <NEW_LINE> <DEDENT> def get_img(self): <NEW_LINE> <INDENT> url = "http://stats.nba.com/media/players/230x185/" + str(self.player_id) + ".png" <NEW_LINE> img_file = str(self.player_id) + ".png" <NEW_LINE> return urllib.request.urlretrieve(url, img_file)[0] <NEW_LINE> <DEDENT> def get_league_avg(self): <NEW_LINE> <INDENT> shots = self.response.json()['resultSets'][1]['rowSet'] <NEW_LINE> headers = self.response.json()['resultSets'][1]['headers'] <NEW_LINE> return pd.DataFrame(shots, columns=headers)
Shots is a wrapper around the NBA stats API that can access the shot chart data and player image.
62598fd0ec188e330fdf8ce3
class put_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'table', None, None, ), (2, TType.STRUCT, 'tput', (TPut, TPut.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, table=None, tput=None,): <NEW_LINE> <INDENT> self.table = table <NEW_LINE> self.tput = tput <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 == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.table = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.tput = TPut() <NEW_LINE> self.tput.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('put_args') <NEW_LINE> if self.table is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('table', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.table) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.tput is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('tput', TType.STRUCT, 2) <NEW_LINE> self.tput.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if self.table is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field table is unset!') <NEW_LINE> <DEDENT> if self.tput is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field tput is unset!') <NEW_LINE> <DEDENT> 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: - table: the table to put data in - tput: the TPut to put
62598fd07b180e01f3e49276
class PresenceSensor(Actor): <NEW_LINE> <INDENT> def __init__(self, name, id, topics, inputobj, auto_init=False, normally_open=True ): <NEW_LINE> <INDENT> super(PresenceSensor, self).__init__(name=name) <NEW_LINE> self._name = name <NEW_LINE> self._id = id <NEW_LINE> self.allowed_topics = ('State', 'Value', 'StationErrorCode', 'StationErrorDescription', 'StationMessageCode', 'StationMessageDescription') <NEW_LINE> self.topics = topics <NEW_LINE> self._normally_open = normally_open <NEW_LINE> self._auto_init = auto_init <NEW_LINE> self.logger = logging.getLogger(name) <NEW_LINE> self.publisher = Publisher(self.topics, logger=self.logger, name=name) <NEW_LINE> self.inputobj = inputobj <NEW_LINE> if normally_open: <NEW_LINE> <INDENT> self.sensor_sm = NOSensorSM(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sensor_sm = NCSensorSM(self) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def normally_open(self): <NEW_LINE> <INDENT> return self._normally_open <NEW_LINE> <DEDENT> @property <NEW_LINE> def auto_init(self): <NEW_LINE> <INDENT> return self._auto_init <NEW_LINE> <DEDENT> @normally_open.setter <NEW_LINE> def normally_open(self, new_normally_open): <NEW_LINE> <INDENT> self._normally_open = new_normally_open <NEW_LINE> <DEDENT> @property <NEW_LINE> def topics(self): <NEW_LINE> <INDENT> return self._topics <NEW_LINE> <DEDENT> @topics.setter <NEW_LINE> def topics(self, new_topics): <NEW_LINE> <INDENT> for topic in new_topics: <NEW_LINE> <INDENT> if topic not in self.allowed_topics: <NEW_LINE> <INDENT> raise ValueError("Unknown topic: {0}".format(topic)) <NEW_LINE> <DEDENT> <DEDENT> self._topics = new_topics <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> def register_subscribers(self, topic, who, callback=None): <NEW_LINE> <INDENT> if topic not in self.allowed_topics: <NEW_LINE> <INDENT> raise ValueError("Unknown topic") <NEW_LINE> <DEDENT> self.publisher.register(topic, who, callback) <NEW_LINE> <DEDENT> def update_input(self): <NEW_LINE> <INDENT> current_value = self.inputobj.get_value() <NEW_LINE> if current_value: <NEW_LINE> <INDENT> self._inputpos_cb() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._inputneg_cb() <NEW_LINE> <DEDENT> <DEDENT> def _inputpos_cb(self): <NEW_LINE> <INDENT> posedge_event = events.SimpleSensorInputEvent(eventID=events.SimpleSensorInputEvents.PosEdge, sender=self.name) <NEW_LINE> self.handle_event(event=posedge_event) <NEW_LINE> <DEDENT> def _inputneg_cb(self): <NEW_LINE> <INDENT> negedge_event = events.SimpleSensorInputEvent(eventID=events.SimpleSensorInputEvents.NegEdge, sender=self.name) <NEW_LINE> self.handle_event(event=negedge_event) <NEW_LINE> <DEDENT> @event_decorator <NEW_LINE> def handle_event(self, *args, **kwargs): <NEW_LINE> <INDENT> self.sensor_sm.dispatch(*args, **kwargs)
Presence sensor class as an active object
62598fd0a219f33f346c6c53
class Browser(zope.testbrowser.browser.Browser): <NEW_LINE> <INDENT> def __init__(self, *args, **kw): <NEW_LINE> <INDENT> kw['mech_browser'] = InterceptBrowser() <NEW_LINE> super(Browser, self).__init__(*args, **kw)
Override the zope.testbrowser.browser.Browser interface so that it uses InterceptBrowser.
62598fd0656771135c489abe
class ModuleInterceptor(object): <NEW_LINE> <INDENT> def __init__(self, moduleName, callback): <NEW_LINE> <INDENT> self.module = __import__(moduleName, globals(), locals(), ['']) <NEW_LINE> self.callback = callback <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return getattr(self.module, attr) <NEW_LINE> <DEDENT> except AttributeError as msg: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.callback(self.module, attr) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise AttributeError(msg)
This class is used to intercept an unset attribute of a module to perfrom a callback. The callback will only be performed if the attribute does not exist on the module. Any error raised in the callback will cause the original AttributeError to be raised. def cb( module, attr): if attr == 'this': print "intercepted" else: raise ValueError import sys sys.modules[__name__] = ModuleInterceptor(__name__, cb) intercepted The class does not work when imported into the main namespace.
62598fd03346ee7daa33786e
class FocalMechanism(_ModelWithResourceID): <NEW_LINE> <INDENT> triggering_origin_id: Optional[ResourceIdentifier] = None <NEW_LINE> nodal_planes: Optional[NodalPlanes] = None <NEW_LINE> principal_axes: Optional[PrincipalAxes] = None <NEW_LINE> azimuthal_gap: Optional[float] = None <NEW_LINE> station_polarity_count: Optional[int] = None <NEW_LINE> misfit: Optional[float] = None <NEW_LINE> station_distribution_ratio: Optional[float] = None <NEW_LINE> method_id: Optional[ResourceIdentifier] = None <NEW_LINE> evaluation_mode: Optional[EvaluationMode] = None <NEW_LINE> evaluation_status: Optional[EvaluationStatus] = None <NEW_LINE> moment_tensor: Optional[MomentTensor] = None <NEW_LINE> creation_info: Optional[CreationInfo] = None <NEW_LINE> waveform_id: List[WaveformStreamID] = [] <NEW_LINE> comments: List[Comment] = []
Focal Mechanism
62598fd0099cdd3c63675606
class TimerCase(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def set_up_class(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tear_down_class(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def add_method(cls, method): <NEW_LINE> <INDENT> setattr(cls, method.__name__, method) <NEW_LINE> <DEDENT> def __init__(self, method_name): <NEW_LINE> <INDENT> self.method_name = method_name <NEW_LINE> self.method = inspect.getmembers(self, lambda object: inspect.ismethod(object) and object.__name__ == self.method_name)[0][1] <NEW_LINE> <DEDENT> def set_up(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tear_down(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def id(self): <NEW_LINE> <INDENT> return u"{}.{}".format(self.method.__self__.__class__.__name__, self.method_name) <NEW_LINE> <DEDENT> def run(self, result): <NEW_LINE> <INDENT> self.set_up() <NEW_LINE> timings = [] <NEW_LINE> process = psutil.Process(os.getpid()) <NEW_LINE> for i in range(getattr(self.method, "repeat", 1)): <NEW_LINE> <INDENT> user_cpu_time, system_cpu_time = process.cpu_times() <NEW_LINE> start_real_time = datetime.datetime.now() <NEW_LINE> start_cpu_time = user_cpu_time + system_cpu_time <NEW_LINE> self.method() <NEW_LINE> user_cpu_time, system_cpu_time = process.cpu_times() <NEW_LINE> end_real_time = datetime.datetime.now() <NEW_LINE> end_cpu_time = user_cpu_time + system_cpu_time <NEW_LINE> real_time_duration_in_seconds = time_delta_in_seconds( end_real_time - start_real_time) <NEW_LINE> cpu_time_duration_in_seconds = end_cpu_time - start_cpu_time <NEW_LINE> timings.append((real_time_duration_in_seconds, cpu_time_duration_in_seconds)) <NEW_LINE> <DEDENT> self.tear_down() <NEW_LINE> result[self.id()] = [datetime.datetime.now(), unicode(getattr(self.method, "description", self.id())), timings] <NEW_LINE> <DEDENT> def nr_timer_cases(self): <NEW_LINE> <INDENT> return 1
Timer case instances are the things that get timed by the framework. A :class:`timer runner <performance_analyst.timer_runner.TimerRunner>` can be used to time a collection of :class:`timer suites <performance_analyst.timer_suite.TimerSuite>` containing timer cases.
62598fd0ff9c53063f51aa9a
class DBTestTestFactory(factory.DjangoModelFactory): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = DBTestTest <NEW_LINE> <DEDENT> data_info = factory.SubFactory(DBTestDataBaseFactory)
Define temp data Factory
62598fd0283ffb24f3cf3cd4
class FakeClass(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def imitate(cls, *others): <NEW_LINE> <INDENT> for other in others: <NEW_LINE> <INDENT> for name in other.__dict__: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setattr(cls, name, mock.Mock()) <NEW_LINE> <DEDENT> except (TypeError, AttributeError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return cls <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def set_return(cls, class_name, fn_name, return_val): <NEW_LINE> <INDENT> getattr(cls, fn_name).return_value = return_val
Fake class.
62598fd0ec188e330fdf8ce5
class FileFolderItem(Widget): <NEW_LINE> <INDENT> @decorate_constructor_parameter_types([str, bool]) <NEW_LINE> def __init__(self, text, is_folder=False, **kwargs): <NEW_LINE> <INDENT> super(FileFolderItem, self).__init__(**kwargs) <NEW_LINE> super(FileFolderItem, self).set_layout_orientation(Widget.LAYOUT_HORIZONTAL) <NEW_LINE> self.style['margin'] = '3px' <NEW_LINE> self.isFolder = is_folder <NEW_LINE> self.EVENT_ONSELECTION = 'onselection' <NEW_LINE> self.attributes[self.EVENT_ONCLICK] = '' <NEW_LINE> self.icon = Widget() <NEW_LINE> self.icon.set_size(30, 30) <NEW_LINE> if is_folder: <NEW_LINE> <INDENT> self.icon.set_on_click_listener(self, self.EVENT_ONCLICK) <NEW_LINE> <DEDENT> self.icon.attributes['class'] = 'FileFolderItemIcon' <NEW_LINE> icon_file = 'res/folder.png' if is_folder else 'res/file.png' <NEW_LINE> self.icon.style['background-image'] = "url('%s')" % icon_file <NEW_LINE> self.label = Label(text) <NEW_LINE> self.label.set_size(400, 30) <NEW_LINE> self.label.set_on_click_listener(self, self.EVENT_ONSELECTION) <NEW_LINE> self.append(self.icon, key='icon') <NEW_LINE> self.append(self.label, key='text') <NEW_LINE> self.selected = False <NEW_LINE> <DEDENT> def onclick(self): <NEW_LINE> <INDENT> return self.eventManager.propagate(self.EVENT_ONCLICK, [self]) <NEW_LINE> <DEDENT> @decorate_set_on_listener("onclick", "(self,folderItemInstance)") <NEW_LINE> def set_on_click_listener(self, listener, funcname): <NEW_LINE> <INDENT> self.eventManager.register_listener(self.EVENT_ONCLICK, listener, funcname) <NEW_LINE> <DEDENT> def set_selected(self, selected): <NEW_LINE> <INDENT> self.selected = selected <NEW_LINE> self.style['color'] = 'red' if self.selected else 'black' <NEW_LINE> <DEDENT> def onselection(self): <NEW_LINE> <INDENT> self.set_selected(not self.selected) <NEW_LINE> return self.eventManager.propagate(self.EVENT_ONSELECTION, [self]) <NEW_LINE> <DEDENT> @decorate_set_on_listener("onselection", "(self,folderItemInstance)") <NEW_LINE> def set_on_selection_listener(self, listener, funcname): <NEW_LINE> <INDENT> self.eventManager.register_listener(self.EVENT_ONSELECTION, listener, funcname) <NEW_LINE> <DEDENT> def set_text(self, t): <NEW_LINE> <INDENT> self.children['text'].set_text(t) <NEW_LINE> <DEDENT> def get_text(self): <NEW_LINE> <INDENT> return self.children['text'].get_text()
FileFolderItem widget for the FileFolderNavigator
62598fd060cbc95b0636478d
class InMayaSettings(BaseSettingsWidget): <NEW_LINE> <INDENT> def __init__(self, cameras=None, filename=None, parent=None, *args, **kwargs): <NEW_LINE> <INDENT> super(InMayaSettings, self).__init__(parent=parent) <NEW_LINE> self.mayaFileInput = Widgets.CueLabelLineEdit('Maya File:', filename) <NEW_LINE> self.cameraSelector = Widgets.CueSelectPulldown('Render Cameras', options=cameras) <NEW_LINE> self.selectorLayout = QtWidgets.QHBoxLayout() <NEW_LINE> self.setupUi() <NEW_LINE> <DEDENT> def setupUi(self): <NEW_LINE> <INDENT> self.mainLayout.addWidget(self.mayaFileInput) <NEW_LINE> self.selectorLayout.addWidget(self.cameraSelector) <NEW_LINE> self.selectorLayout.addSpacerItem(Widgets.CueSpacerItem(Widgets.SpacerTypes.HORIZONTAL)) <NEW_LINE> self.mainLayout.addLayout(self.selectorLayout) <NEW_LINE> <DEDENT> def setCommandData(self, commandData): <NEW_LINE> <INDENT> self.mayaFileInput.setText(commandData.get('mayaFile', '')) <NEW_LINE> self.cameraSelector.setChecked(commandData.get('camera', '').split(',')) <NEW_LINE> <DEDENT> def getCommandData(self): <NEW_LINE> <INDENT> return { 'mayaFile': self.mayaFileInput.text(), 'camera': self.cameraSelector.text() }
Settings widget to be used when launching from within Maya.
62598fd0d8ef3951e32c8083
class NodeRef: <NEW_LINE> <INDENT> REF_PATTERN = re.compile( r"(?P<dir1>:[a-z\-]+:)?(?P<dir2>[a-z\-]+:)?`?(?P<refname>.*)`?$" ) <NEW_LINE> STD_ROLES = ("doc", "label", "term", "cmdoption", "envvar", "opcode", "token") <NEW_LINE> def __init__(self, refname: str, role: str, lang: Optional[str]): <NEW_LINE> <INDENT> self.refname: str = refname.strip() <NEW_LINE> self.role: str = role <NEW_LINE> self.lang: Optional[str] = lang <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def convert(cls, ctx: commands.Context, argument: str) -> "NodeRef": <NEW_LINE> <INDENT> argument = argument.strip("`") <NEW_LINE> match = cls.REF_PATTERN.match(argument) <NEW_LINE> refname = match["refname"] <NEW_LINE> if refname is None: <NEW_LINE> <INDENT> raise commands.BadArgument( f'Failed to parse reference "{argument}" - ' f"see `{ctx.prefix}help {ctx.invoked_with}` for details." ) <NEW_LINE> <DEDENT> if match["dir1"] and match["dir2"]: <NEW_LINE> <INDENT> lang = match["dir1"].strip(":") <NEW_LINE> role = match["dir2"].strip(":") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lang = None <NEW_LINE> if match["dir1"]: <NEW_LINE> <INDENT> role = match["dir1"].strip(":") <NEW_LINE> <DEDENT> elif match["dir2"]: <NEW_LINE> <INDENT> role = match["dir2"].strip(":") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> role = "any" <NEW_LINE> <DEDENT> <DEDENT> if role in cls.STD_ROLES: <NEW_LINE> <INDENT> lang = "std" <NEW_LINE> <DEDENT> return cls(refname, role, lang) <NEW_LINE> <DEDENT> @property <NEW_LINE> def reftype(self) -> str: <NEW_LINE> <INDENT> if self.lang is None: <NEW_LINE> <INDENT> return f"{self.role}" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f"{self.lang}:{self.role}" <NEW_LINE> <DEDENT> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return f":{self.reftype}:`{self.refname}`" <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return ( f"<NodeRef refname={self.refname!r} role={self.role!r} lang={self.lang!r}>" )
Class for a reference to a sphinx node. Attributes ---------- refname : str The reference name to search for. role : str The role for the reference. Can be ``"any"`` to be totally ambiguous. lang : Optional[str] The language to match the role. ``None`` if omitted - this is not often needed.
62598fd0091ae3566870507b
class Cell(Context): <NEW_LINE> <INDENT> __tablename__ = 'cell' <NEW_LINE> id = Column(Integer, ForeignKey('context.id', ondelete='CASCADE'), primary_key=True) <NEW_LINE> document_id = Column(Integer, ForeignKey('document.id')) <NEW_LINE> table_id = Column(Integer, ForeignKey('table.id')) <NEW_LINE> position = Column(Integer, nullable=False) <NEW_LINE> document = relationship('Document', backref=backref('cells', order_by=position, cascade='all, delete-orphan'), foreign_keys=document_id) <NEW_LINE> table = relationship('Table', backref=backref('cells', order_by=position, cascade='all, delete-orphan'), foreign_keys=table_id) <NEW_LINE> row_start = Column(Integer) <NEW_LINE> row_end = Column(Integer) <NEW_LINE> col_start = Column(Integer) <NEW_LINE> col_end = Column(Integer) <NEW_LINE> html_tag = Column(Text) <NEW_LINE> if snorkel_postgres: <NEW_LINE> <INDENT> html_attrs = Column(postgresql.ARRAY(String)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> html_attrs = Column(PickleType) <NEW_LINE> <DEDENT> __mapper_args__ = { 'polymorphic_identity': 'cell', } <NEW_LINE> __table_args__ = ( UniqueConstraint(document_id, table_id, position), ) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return ("Cell(Doc: %s, Table: %s, Row: %s, Col: %s, Pos: %s)" % (self.document.name.encode('utf-8'), self.table.position, tuple(set([self.row_start, self.row_end])), tuple(set([self.col_start, self.col_end])), self.position)) <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return self.__repr__() > other.__repr__()
A cell Context in a Document.
62598fd0fbf16365ca79450c
class BumpyboxExtractTranscodeH264(api.InstancePlugin): <NEW_LINE> <INDENT> order = inventory.get_order(__file__, "BumpyboxExtractTranscodeH264") <NEW_LINE> families = ["h264", "h264_half"] <NEW_LINE> label = "Transcode H264" <NEW_LINE> optional = True <NEW_LINE> def process(self, instance): <NEW_LINE> <INDENT> data = instance.data.get("transcodeTags", []) <NEW_LINE> data.extend(["h264", "h264_half"]) <NEW_LINE> instance.data["transcodeTags"] = data
Enable/Disable h264 transcoding.
62598fd05fdd1c0f98e5e3dc
class BrushGroupsToolItem (widgets.MenuButtonToolItem): <NEW_LINE> <INDENT> __gtype_name__ = "MyPaintBrushGroupsToolItem" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> widgets.MenuButtonToolItem.__init__(self) <NEW_LINE> self.menu = BrushGroupsMenu()
Toolbar item showing a dynamic dropdown BrushGroupsMenu This is instantiated by the app's UIManager using a FactoryAction which must be named "BrushGroups" (see factoryaction.py).
62598fd00fa83653e46f5338
class AppStaticStorage(FileSystemStorage): <NEW_LINE> <INDENT> source_dir = 'static' <NEW_LINE> def __init__(self, app, *args, **kwargs): <NEW_LINE> <INDENT> bits = app.__name__.split('.')[:-1] <NEW_LINE> self.app_name = bits[-1] <NEW_LINE> self.app_module = '.'.join(bits) <NEW_LINE> app = import_module(self.app_module) <NEW_LINE> location = self.get_location(os.path.dirname(app.__file__)) <NEW_LINE> super(AppStaticStorage, self).__init__(location, *args, **kwargs) <NEW_LINE> <DEDENT> def get_location(self, app_root): <NEW_LINE> <INDENT> if self.app_module == 'django.contrib.admin': <NEW_LINE> <INDENT> return os.path.join(app_root, 'media') <NEW_LINE> <DEDENT> return os.path.join(app_root, self.source_dir) <NEW_LINE> <DEDENT> def get_prefix(self): <NEW_LINE> <INDENT> if self.app_module == 'django.contrib.admin': <NEW_LINE> <INDENT> return self.app_name <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_files(self, ignore_patterns=[]): <NEW_LINE> <INDENT> files = [] <NEW_LINE> prefix = self.get_prefix() <NEW_LINE> for path in utils.get_files(self, ignore_patterns): <NEW_LINE> <INDENT> if prefix: <NEW_LINE> <INDENT> path = '/'.join([prefix, path]) <NEW_LINE> <DEDENT> files.append(path) <NEW_LINE> <DEDENT> return files
A file system storage backend that takes an app module and works for the ``static`` directory of it.
62598fd0283ffb24f3cf3cd6
class Executor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._test_filter = {} <NEW_LINE> <DEDENT> def test_filter(self): <NEW_LINE> <INDENT> return self._test_filter <NEW_LINE> <DEDENT> def clear_filter(self): <NEW_LINE> <INDENT> self._test_filter.clear() <NEW_LINE> <DEDENT> def test(self, testlist): <NEW_LINE> <INDENT> test_filter = self._test_filter <NEW_LINE> test_results = set() <NEW_LINE> for test in testlist: <NEW_LINE> <INDENT> if not test_filter or test.executable() in test_filter: <NEW_LINE> <INDENT> failures = test.execute( test_filter[test.executable()] if test_filter else [] ) <NEW_LINE> test_results.add(test) <NEW_LINE> if failures and test_filter: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._test_filter = { test.executable(): test.failures() for test in test_results if test.failures() } <NEW_LINE> runtime = 0.0 <NEW_LINE> fail_count = 0 <NEW_LINE> pass_count = 0 <NEW_LINE> failures = [] <NEW_LINE> for test in test_results: <NEW_LINE> <INDENT> runtime += test.run_time() <NEW_LINE> fail_count += test.fails() <NEW_LINE> pass_count += test.passes() <NEW_LINE> for failed_test in test.failures(): <NEW_LINE> <INDENT> outcome, out, err = test.test_results(failed_test) <NEW_LINE> failures.append([failed_test, out, err, outcome]) <NEW_LINE> <DEDENT> <DEDENT> runtime /= 1000 <NEW_LINE> return { "total_runtime": runtime, "total_passed": pass_count, "total_failed": fail_count, "failures": failures, }
Maintains the collection of tests detected by the :class:`Watcher` and provides an interface to execute all or some of those tests.
62598fd060cbc95b0636478f
class Lighting(object): <NEW_LINE> <INDENT> def __init__(self, alphastd): <NEW_LINE> <INDENT> self.alphastd = alphastd <NEW_LINE> self.eigval = torch.Tensor([0.2175, 0.0188, 0.0045]) <NEW_LINE> self.eigvec = torch.Tensor([ [-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.8140], [-0.5836, -0.6948, 0.4203], ]) <NEW_LINE> <DEDENT> def __call__(self, img): <NEW_LINE> <INDENT> if self.alphastd == 0: <NEW_LINE> <INDENT> return img <NEW_LINE> <DEDENT> alpha = img.new().resize_(3).normal_(0, self.alphastd) <NEW_LINE> rgb = self.eigvec.type_as(img).clone() .mul(alpha.view(1, 3).expand(3, 3)) .mul(self.eigval.view(1, 3).expand(3, 3)) .sum(1).squeeze() <NEW_LINE> return img.add(rgb.view(3, 1, 1).expand_as(img))
Lighting noise(AlexNet - style PCA - based noise)
62598fd0fbf16365ca79450e
class VerticalRange(BaseLayer): <NEW_LINE> <INDENT> time_lower = AstropyTime(help='The date/time at which the range starts.') <NEW_LINE> time_upper = AstropyTime(help='The date/time at which the range ends.') <NEW_LINE> color = Color(None, help='The fill color of the range.') <NEW_LINE> opacity = Opacity(0.2, help='The opacity of the fill color from 0 (transparent) to 1 (opaque).') <NEW_LINE> edge_color = Color(None, help='The edge color of the range.') <NEW_LINE> edge_opacity = Opacity(0.2, help='The opacity of the edge color from 0 (transparent) to 1 (opaque).') <NEW_LINE> edge_width = PositiveCFloat(0, help='The thickness of the edge, in pixels.') <NEW_LINE> def to_vega(self, yunit=None): <NEW_LINE> <INDENT> vega = {'type': 'rect', 'name': self.uuids[0], 'description': self.label, 'clip': True, 'encode': {'enter': {'x': {'scale': 'xscale', 'signal': time_to_vega(self.time_lower)}, 'x2': {'scale': 'xscale', 'signal': time_to_vega(self.time_upper)}, 'y': {'value': 0}, 'y2': {'field': {'group': 'height'}}, 'fill': {'value': self.color or DEFAULT_COLOR}, 'fillOpacity': {'value': self.opacity}, 'stroke': {'value': self.edge_color or DEFAULT_COLOR}, 'strokeOpacity': {'value': self.edge_opacity}, 'strokeWidth': {'value': self.edge_width}}}} <NEW_LINE> return [vega] <NEW_LINE> <DEDENT> def to_mpl(self, ax, yunit=None): <NEW_LINE> <INDENT> ax.fill_betweenx([-1e30, 1e30], self.time_lower, self.time_upper, color=self.color or DEFAULT_COLOR, alpha=self.opacity)
A continuous range specified by a lower and upper time.
62598fd04527f215b58ea321
class TestContentHistoryViewlet(ViewletsTestCase): <NEW_LINE> <INDENT> def afterSetUp(self): <NEW_LINE> <INDENT> self.folder.invokeFactory('Document', 'd1') <NEW_LINE> <DEDENT> def test_emptyHistory(self): <NEW_LINE> <INDENT> request = self.app.REQUEST <NEW_LINE> context = getattr(self.folder, 'd1') <NEW_LINE> viewlet = ContentHistoryViewlet(context, request, None, None) <NEW_LINE> viewlet.update() <NEW_LINE> self.assertEqual(viewlet.revisionHistory(), []) <NEW_LINE> <DEDENT> def test_revisionHistory(self): <NEW_LINE> <INDENT> repo_tool = self.portal.portal_repository <NEW_LINE> request = self.app.REQUEST <NEW_LINE> context = getattr(self.folder, 'd1') <NEW_LINE> self.loginAsPortalOwner() <NEW_LINE> repo_tool.save(context, comment='Initial Revision') <NEW_LINE> viewlet = ContentHistoryViewlet(context, request, None, None) <NEW_LINE> viewlet.update() <NEW_LINE> history = viewlet.revisionHistory() <NEW_LINE> self.assertEqual(len(history), 1) <NEW_LINE> self.assertEqual(history[0]['comments'], 'Initial Revision') <NEW_LINE> repo_tool.save(context, comment='Second Revision') <NEW_LINE> viewlet.update() <NEW_LINE> history = viewlet.revisionHistory() <NEW_LINE> self.assertEqual(history[0]['diff_previous_url'], 'http://nohost/plone/Members/test_user_1_/d1/@@history?one=1&two=0') <NEW_LINE> diff_tool = self.portal.portal_diff <NEW_LINE> diff_tool.setDiffForPortalType('Document', {}) <NEW_LINE> viewlet.update() <NEW_LINE> history = viewlet.revisionHistory() <NEW_LINE> self.assertFalse('diff_previous_url' in history[0])
Test the workflow history viewlet
62598fd0bf627c535bcb18ff
class VmData: <NEW_LINE> <INDENT> vmid = None <NEW_LINE> vmname = None <NEW_LINE> vmstatus = None <NEW_LINE> vmtype = None
A simple class whose objects will store (VMid, VMname, VMstatus, VMtype) tuples
62598fd03346ee7daa337870
@injected <NEW_LINE> @setup(IMessageService) <NEW_LINE> class MessageServiceAlchemy(EntityGetCRUDServiceAlchemy, IMessageService): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> EntityGetCRUDServiceAlchemy.__init__(self, Message, QMessage) <NEW_LINE> <DEDENT> def getMessages(self, sourceId=None, offset=None, limit=None, detailed=False, qm=None, qs=None): <NEW_LINE> <INDENT> sql = self.session().query(Message) <NEW_LINE> if sourceId: sql = sql.filter(Message.Source == sourceId) <NEW_LINE> if qm: sql = buildQuery(sql, qm, Message) <NEW_LINE> if qs: sql = buildQuery(sql.join(Source), qs, Source) <NEW_LINE> sqlLimit = buildLimits(sql, offset, limit) <NEW_LINE> if detailed: return IterPart(sqlLimit.all(), sql.count(), offset, limit) <NEW_LINE> return sqlLimit.all() <NEW_LINE> <DEDENT> def getComponentMessages(self, component, offset=None, limit=None, detailed=False, qm=None, qs=None): <NEW_LINE> <INDENT> sql = self.session().query(Message).join(Source).filter(Source.Component == component) <NEW_LINE> if qm: sql = buildQuery(sql, qm, Message) <NEW_LINE> if qs: sql = buildQuery(sql, qs, Source) <NEW_LINE> sqlLimit = buildLimits(sql, offset, limit) <NEW_LINE> if detailed: return IterPart(sqlLimit.all(), sql.count(), offset, limit) <NEW_LINE> return sqlLimit.all() <NEW_LINE> <DEDENT> def getPluginMessages(self, plugin, offset=None, limit=None, detailed=False, qm=None, qs=None): <NEW_LINE> <INDENT> sql = self.session().query(Message).join(Source).filter(Source.Plugin == plugin) <NEW_LINE> if qm: sql = buildQuery(sql, qm, Message) <NEW_LINE> if qs: sql = buildQuery(sql, qs, Source) <NEW_LINE> sqlLimit = buildLimits(sql, offset, limit) <NEW_LINE> if detailed: return IterPart(sqlLimit.all(), sql.count(), offset, limit) <NEW_LINE> return sqlLimit.all()
Alchemy implementation for @see: IMessageService
62598fd00fa83653e46f533a
class ShortestPath(MazeSolveAlgo): <NEW_LINE> <INDENT> def _solve(self): <NEW_LINE> <INDENT> self.start_edge = self._on_edge(self.start) <NEW_LINE> self.end_edge = self._on_edge(self.start) <NEW_LINE> start = self.start <NEW_LINE> if self.start_edge: <NEW_LINE> <INDENT> start = self._push_edge(self.start) <NEW_LINE> <DEDENT> start_posis = self._find_unblocked_neighbors(start) <NEW_LINE> if len(start_posis) == 0: <NEW_LINE> <INDENT> raise ValueError('Input maze is invalid.') <NEW_LINE> <DEDENT> solutions = [] <NEW_LINE> for s in start_posis: <NEW_LINE> <INDENT> if self.start_edge: <NEW_LINE> <INDENT> solutions.append([start, self._midpoint(start, s), s]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> solutions.append([self._midpoint(start, s), s]) <NEW_LINE> <DEDENT> <DEDENT> num_unfinished = len(solutions) <NEW_LINE> while num_unfinished > 0: <NEW_LINE> <INDENT> for s in range(len(solutions)): <NEW_LINE> <INDENT> if solutions[s][-1] in solutions[s][:-1]: <NEW_LINE> <INDENT> solutions[s].append(None) <NEW_LINE> <DEDENT> elif self._within_one(solutions[s][-1], self.end): <NEW_LINE> <INDENT> if not self._on_edge(self.end): <NEW_LINE> <INDENT> solutions[s] = solutions[s][:-1] <NEW_LINE> <DEDENT> return [solutions[s]] <NEW_LINE> <DEDENT> elif solutions[s][-1] != None: <NEW_LINE> <INDENT> if len(solutions[s]) > 1: <NEW_LINE> <INDENT> if self._midpoint(solutions[s][-1], solutions[s][-2]) == self.end: <NEW_LINE> <INDENT> return [solutions[s][:-1]] <NEW_LINE> <DEDENT> <DEDENT> ns = self._find_unblocked_neighbors(solutions[s][-1]) <NEW_LINE> ns = list(filter(lambda i: i not in solutions[s], ns)) <NEW_LINE> if len(ns) == 0: <NEW_LINE> <INDENT> solutions[s].append(None) <NEW_LINE> <DEDENT> elif len(ns) == 1: <NEW_LINE> <INDENT> solutions[s].append(self._midpoint(ns[0], solutions[s][-1])) <NEW_LINE> solutions[s].append(ns[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for j in range(1, len(ns)): <NEW_LINE> <INDENT> nxt = [self._midpoint(ns[j], solutions[s][-1]), ns[j]] <NEW_LINE> solutions.append(list(solutions[s]) + nxt) <NEW_LINE> <DEDENT> solutions[s].append(self._midpoint(ns[0], solutions[s][-1])) <NEW_LINE> solutions[s].append(ns[0]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> num_unfinished = sum(map(lambda sol: 0 if sol[-1] is None else 1 , solutions)) <NEW_LINE> <DEDENT> solutions = self._clean_up(solutions) <NEW_LINE> if len(solutions) == 0 or len(solutions[0]) == 0: <NEW_LINE> <INDENT> raise ValueError('No valid solutions found.') <NEW_LINE> <DEDENT> return solutions
The Algorithm: 1) create a solution for each starting position 2) loop through each solution, and find the neighbors of the last element 3) a solution reaches the end or a dead end when we mark it by appending a None. 4) clean-up solutions Results Find all unique solutions. Works against imperfect mazes.
62598fd0dc8b845886d53a10
class Session(object): <NEW_LINE> <INDENT> def query(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.session.query(*args, **kwargs) <NEW_LINE> <DEDENT> def files(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def models(self): <NEW_LINE> <INDENT> return [x[0] for x in self.query(Instance.model).distinct().all()] <NEW_LINE> <DEDENT> def experiments(self): <NEW_LINE> <INDENT> return [x[0] for x in self.query(Instance.experiment).distinct().all()] <NEW_LINE> <DEDENT> def variables(self): <NEW_LINE> <INDENT> return [x[0] for x in self.query(Instance.variable).distinct().all()] <NEW_LINE> <DEDENT> def mips(self): <NEW_LINE> <INDENT> return [x[0] for x in self.query(Instance.mip).distinct().all()] <NEW_LINE> <DEDENT> def outputs(self, **kwargs): <NEW_LINE> <INDENT> return self.query(Instance).filter_by(**kwargs)
Holds a connection to the catalog Create using :func:`ARCCSSive.CMIP5.connect()`
62598fd0adb09d7d5dc0a9cd
class AgentState(Enum): <NEW_LINE> <INDENT> NAVIGATING = 1 <NEW_LINE> BLOCKED_BY_VEHICLE = 2 <NEW_LINE> BLOCKED_RED_LIGHT = 3
AGENT_STATE represents the possible states of a roaming agent
62598fd09f28863672818aa6
class RequestError(Error): <NEW_LINE> <INDENT> pass
Raised when server failed to process a request. The client can continue normally with another request or repeat the failing request.
62598fd07b180e01f3e49279
class BadExpectation(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super(BadExpectation, self).__init__(message) <NEW_LINE> self.message = message <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return colored(self.message, 'red')
Raised when an assertion fails.
62598fd0bf627c535bcb1901
class AlreadyRegistered(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super(AlreadyRegistered, self).__init__('Endpoint {} is already registered'.format(message))
Exception raised attempting to register an endpoint already registered.
62598fd055399d3f0562696f
class Solution: <NEW_LINE> <INDENT> def longestConsecutive(self, root): <NEW_LINE> <INDENT> return self.helper(root, None, 0) <NEW_LINE> <DEDENT> def helper(self, node, parent, length): <NEW_LINE> <INDENT> if node == None: <NEW_LINE> <INDENT> return length <NEW_LINE> <DEDENT> if parent and node.val == parent.val+1: <NEW_LINE> <INDENT> length += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> length = 1 <NEW_LINE> <DEDENT> return max(length, self.helper(node.left, node, length), self.helper(node.right, node, length))
@param root: the root of binary tree @return: the length of the longest consecutive sequence path
62598fd05fdd1c0f98e5e3e2
class MaxPooling3D(object): <NEW_LINE> <INDENT> def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope="max_pool_3d"): <NEW_LINE> <INDENT> self.window_size = window_size <NEW_LINE> self.stride_size = stride_size <NEW_LINE> self.scope = scope <NEW_LINE> self.device_spec = get_device_spec(default_gpu_id, num_gpus) <NEW_LINE> with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE), tf.device(self.device_spec): <NEW_LINE> <INDENT> self.pooling_layer = tf.layers.MaxPooling3D(self.window_size, self.stride_size, "VALID") <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, input_data, input_mask): <NEW_LINE> <INDENT> with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE), tf.device(self.device_spec): <NEW_LINE> <INDENT> input_data_shape = tf.shape(input_data) <NEW_LINE> input_mask_shape = tf.shape(input_mask) <NEW_LINE> shape_size = len(input_data.get_shape().as_list()) <NEW_LINE> if shape_size > 5: <NEW_LINE> <INDENT> input_pooling = tf.reshape(input_data, shape=tf.concat([[-1], input_data_shape[-4:]], axis=0)) <NEW_LINE> input_pooling_mask = tf.reshape(input_mask, shape=tf.concat([[-1], input_mask_shape[-4:]], axis=0)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> input_pooling = input_data <NEW_LINE> input_pooling_mask = input_mask <NEW_LINE> <DEDENT> output_pooling = self.pooling_layer(input_pooling) <NEW_LINE> output_mask = self.pooling_layer(input_pooling_mask) <NEW_LINE> if shape_size > 5: <NEW_LINE> <INDENT> output_pooling_shape = tf.shape(output_pooling) <NEW_LINE> output_mask_shape = tf.shape(output_mask) <NEW_LINE> output_pooling = tf.reshape(output_pooling, shape=tf.concat([input_data_shape[:-4], output_pooling_shape[-4:]], axis=0)) <NEW_LINE> output_mask = tf.reshape(output_mask, shape=tf.concat([input_mask_shape[:-4], output_mask_shape[-4:]], axis=0)) <NEW_LINE> <DEDENT> <DEDENT> return output_pooling, output_mask
max pooling layer
62598fd0377c676e912f6fa3
class IofloMaster(object): <NEW_LINE> <INDENT> def __init__(self, opts): <NEW_LINE> <INDENT> self.opts = opts <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> behaviors = ['salt.transport.road.raet', 'salt.daemons.flo'] <NEW_LINE> metadata = explode_opts(self.opts) <NEW_LINE> ioflo.app.run.start( name='master', period=float(self.opts['ioflo_period']), stamp=0.0, real=self.opts['ioflo_realtime'], filepath=self.opts['master_floscript'], behaviors=behaviors, username="", password="", mode=None, houses=None, metadata=metadata, verbose=int(self.opts['ioflo_verbose']), )
IofloMaster Class
62598fd00fa83653e46f533e
class UploadJSON(FlaskForm): <NEW_LINE> <INDENT> selectarchivefile = FileField('CFFA Archive File', validators=[FileRequired(), FileAllowed('cffaDB', 'CFFA DB exports only!')]) <NEW_LINE> submitrecovery = SubmitField("Reset and Recover DB")
Form to upload JSON into the DB. Not implemented and likely validators will not work yet. Once implemented this will drop the current database collections for the tenancy to upload the JSON data. Will not append existing data. TO DO: Implement Attributes ---------- selectarchivefile : FileField FlaskForm class type. submitrecovery: SubmitField Confirm upload and reset of db.
62598fd0283ffb24f3cf3cdd
class StatIncrease: <NEW_LINE> <INDENT> def __init__(self, max_hp_up, max_hp_percentage_up, max_magic_points_up, max_magic_points_percentage_up, attack_up, attack_percentage_up, defense_up, defense_percentage_up, attack_speed_up, crit_rate_up, crit_damage_up, resistance_up, accuracy_up): <NEW_LINE> <INDENT> self.max_hp_up: mpf = max_hp_up <NEW_LINE> self.max_hp_percentage_up: mpf = max_hp_percentage_up <NEW_LINE> self.max_magic_points_up: mpf = max_magic_points_up <NEW_LINE> self.max_magic_points_percentage_up: mpf = max_magic_points_percentage_up <NEW_LINE> self.attack_up: mpf = attack_up <NEW_LINE> self.attack_percentage_up: mpf = attack_percentage_up <NEW_LINE> self.defense_up: mpf = defense_up <NEW_LINE> self.defense_percentage_up: mpf = defense_percentage_up <NEW_LINE> self.attack_speed_up: mpf = attack_speed_up <NEW_LINE> self.crit_rate_up: mpf = crit_rate_up <NEW_LINE> self.crit_damage_up: mpf = crit_damage_up <NEW_LINE> self.resistance_up: mpf = resistance_up <NEW_LINE> self.accuracy_up: mpf = accuracy_up <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> res: str = "" <NEW_LINE> res += "Max HP Up: " + str(self.max_hp_up) + "\n" <NEW_LINE> res += "Max HP Percentage Up: " + str(self.max_hp_percentage_up * 100) + "%\n" <NEW_LINE> res += "Max Magic Points Up: " + str(self.max_magic_points_up) + "\n" <NEW_LINE> res += "Max Magic Points Percentage Up: " + str(self.max_magic_points_percentage_up * 100) + "%\n" <NEW_LINE> res += "Attack Up: " + str(self.attack_up) + "\n" <NEW_LINE> res += "Attack Percentage Up: " + str(self.attack_percentage_up * 100) + "%\n" <NEW_LINE> res += "Defense Up: " + str(self.defense_up) + "\n" <NEW_LINE> res += "Defense Percentage Up: " + str(self.defense_percentage_up * 100) + "%\n" <NEW_LINE> res += "Attack Speed Up: " + str(self.attack_speed_up) + "\n" <NEW_LINE> res += "Crit Rate Up: " + str(self.crit_rate_up * 100) + "%\n" <NEW_LINE> res += "Crit Damage Up: " + str(self.crit_damage_up * 100) + "%\n" <NEW_LINE> res += "Resistance Up: " + str(self.resistance_up * 100) + "%\n" <NEW_LINE> res += "Accuracy Up: " + str(self.accuracy_up * 100) + "%\n" <NEW_LINE> return res <NEW_LINE> <DEDENT> def clone(self): <NEW_LINE> <INDENT> return copy.deepcopy(self)
This class contains attributes of increase in stats of a rune.
62598fd0be7bc26dc9252084
class Query(APIOperation): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.api = DataAPI() <NEW_LINE> self.cr = CReader('../APIInterface/sampledata') <NEW_LINE> <DEDENT> def probe(self): <NEW_LINE> <INDENT> self.api.connect() <NEW_LINE> self.api.dispReq(self.api.req) <NEW_LINE> self.api.dispRes(self.api.res)
classdocs
62598fd0a219f33f346c6c5e
class FaceApi(object): <NEW_LINE> <INDENT> def __init__(self, spath, attrs='gender,age'): <NEW_LINE> <INDENT> self.attrs = attrs <NEW_LINE> self.spath = spath <NEW_LINE> self.frist_write = True <NEW_LINE> self.faceurl = 'https://api-cn.faceplusplus.com/facepp/v3/detect' <NEW_LINE> self.payload = {'api_key': 'your_api_key', 'api_secret': 'your_api_secret', 'return_attributes': self.attrs} <NEW_LINE> self.headers = GetFakeAgent.get_agent() <NEW_LINE> self.info_dict = {'pic': '', "width": '', "top": '', "left": '', "height": ''} <NEW_LINE> <DEDENT> def get_result(self): <NEW_LINE> <INDENT> file_list = os.listdir(self.spath) <NEW_LINE> if len(file_list) > 0: <NEW_LINE> <INDENT> for file in file_list: <NEW_LINE> <INDENT> self.request_api(self.spath + file) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def request_api(self, file): <NEW_LINE> <INDENT> fname = file <NEW_LINE> bname = os.path.basename(fname) <NEW_LINE> ftype = mimetypes.guess_type(fname)[0] <NEW_LINE> files = {'image_file': (bname, open(fname, 'rb'), ftype)} <NEW_LINE> req = requests.post(self.faceurl, data=self.payload, headers=self.headers, files=files) <NEW_LINE> self.parse_json(req, bname) <NEW_LINE> <DEDENT> def parse_json(self, obj, bname): <NEW_LINE> <INDENT> json = obj.json() <NEW_LINE> info_dict = {'pic': '', "width": '', "top": '', "left": '', "height": ''} <NEW_LINE> for key in info_dict.keys(): <NEW_LINE> <INDENT> if key == 'pic': <NEW_LINE> <INDENT> info_dict[key] = bname <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> info_dict[key] = json['faces'][0]['face_rectangle'][key] <NEW_LINE> <DEDENT> <DEDENT> for attr in self.attrs.replace(' ', '').split(','): <NEW_LINE> <INDENT> info_dict.update( {attr: json['faces'][0]['attributes'][attr]['value']}) <NEW_LINE> <DEDENT> print(bname, '获取完毕,正在保存...') <NEW_LINE> self.save_info(info_dict) <NEW_LINE> <DEDENT> def save_info(self, obj): <NEW_LINE> <INDENT> with open(self.spath + 'result.csv', 'a+') as csvfile: <NEW_LINE> <INDENT> writer = csv.writer(csvfile) <NEW_LINE> if self.frist_write: <NEW_LINE> <INDENT> writer.writerow(['图片名', 'width', 'top', 'left', 'height'] + self.attrs.replace(' ', '').split(',')) <NEW_LINE> self.frist_write = False <NEW_LINE> <DEDENT> writer.writerow(list(obj.values()))
docstring for FaceApi
62598fd03617ad0b5ee0659f
class Heiltrank(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ID = 0 <NEW_LINE> self.typ = "Energie" <NEW_LINE> self.name = "Heiltrank" <NEW_LINE> zeile1 = [1] <NEW_LINE> self.spalte = [zeile1] <NEW_LINE> self.stapelbar = True <NEW_LINE> self.actor = Actor("models/box.x") <NEW_LINE> self.anzahl = 1 <NEW_LINE> self.maxanzahl = 20 <NEW_LINE> self.wert = 20
Erstellt ein Item vom Typ Heiltrank
62598fd0656771135c489ac8
class BaseFactory(factory.alchemy.SQLAlchemyModelFactory): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> sqlalchemy_session = db_session <NEW_LINE> sqlalchemy_session_persistence = 'flush'
Base model factory.
62598fd0bf627c535bcb1905
class CharacterClass(GenericEntry): <NEW_LINE> <INDENT> def __init__(self, e, file=None): <NEW_LINE> <INDENT> super().__init__(e, file=None) <NEW_LINE> <DEDENT> def display(self): <NEW_LINE> <INDENT> displayNext(self.element)
docstring for CharacterClass
62598fd00fa83653e46f5340
class ColourIndicator(wx.Window): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> wx.Window.__init__(self, parent, -1, style=wx.SUNKEN_BORDER) <NEW_LINE> self.SetBackgroundColour(wx.WHITE) <NEW_LINE> self.SetMinSize( (45, 45) ) <NEW_LINE> self.colour = self.thickness = None <NEW_LINE> self.Bind(wx.EVT_PAINT, self.OnPaint) <NEW_LINE> <DEDENT> def Update(self, colour, thickness): <NEW_LINE> <INDENT> self.colour = colour <NEW_LINE> self.thickness = thickness <NEW_LINE> self.Refresh() <NEW_LINE> <DEDENT> def OnPaint(self, event): <NEW_LINE> <INDENT> dc = wx.PaintDC(self) <NEW_LINE> if self.colour: <NEW_LINE> <INDENT> sz = self.GetClientSize() <NEW_LINE> pen = wx.Pen(self.colour, self.thickness) <NEW_LINE> dc.BeginDrawing() <NEW_LINE> dc.SetPen(pen) <NEW_LINE> dc.DrawLine(10, sz.height/2, sz.width-10, sz.height/2) <NEW_LINE> dc.EndDrawing()
An instance of this class is used on the ControlPanel to show a sample of what the current doodle line will look like.
62598fd0ff9c53063f51aaa4
class TestInlineObject8(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testInlineObject8(self): <NEW_LINE> <INDENT> pass
InlineObject8 unit test stubs
62598fd097e22403b383b361
class MyChevyStatus(Entity): <NEW_LINE> <INDENT> _name = "MyChevy Status" <NEW_LINE> _icon = "mdi:car-connected" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._state = None <NEW_LINE> <DEDENT> async def async_added_to_hass(self): <NEW_LINE> <INDENT> self.async_on_remove( self.hass.helpers.dispatcher.async_dispatcher_connect( UPDATE_TOPIC, self.success ) ) <NEW_LINE> self.async_on_remove( self.hass.helpers.dispatcher.async_dispatcher_connect( ERROR_TOPIC, self.error ) ) <NEW_LINE> <DEDENT> @callback <NEW_LINE> def success(self): <NEW_LINE> <INDENT> if self._state != MYCHEVY_SUCCESS: <NEW_LINE> <INDENT> _LOGGER.debug("Successfully connected to mychevy website") <NEW_LINE> self._state = MYCHEVY_SUCCESS <NEW_LINE> <DEDENT> self.async_write_ha_state() <NEW_LINE> <DEDENT> @callback <NEW_LINE> def error(self): <NEW_LINE> <INDENT> _LOGGER.error( "Connection to mychevy website failed. " "This probably means the mychevy to OnStar link is down" ) <NEW_LINE> self._state = MYCHEVY_ERROR <NEW_LINE> self.async_write_ha_state() <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return self._icon <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return False
A string representing the charge mode.
62598fd0ad47b63b2c5a7cb4
class DiskCreateOptionTypes(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> FROM_IMAGE = "FromImage" <NEW_LINE> EMPTY = "Empty" <NEW_LINE> ATTACH = "Attach"
Specifies how the virtual machine should be created.:code:`<br>`:code:`<br>` Possible values are::code:`<br>`:code:`<br>` **Attach** – This value is used when you are using a specialized disk to create the virtual machine.:code:`<br>`:code:`<br>` **FromImage** – This value is used when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference element described above. If you are using a marketplace image, you also use the plan element previously described.
62598fd07b180e01f3e4927c