code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
@attr('functional') <NEW_LINE> class TestExplorerJob(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> arkane = Arkane() <NEW_LINE> cls.job_list = arkane.load_input_file( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'methoxy_explore.py')) <NEW_LINE> for job in cls.job_list: <NEW_LINE> <INDENT> if not isinstance(job, ExplorerJob): <NEW_LINE> <INDENT> job.execute(output_file=None, plot=None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> thermo_library, kinetics_library, species_list = arkane.get_libraries() <NEW_LINE> job.execute(output_file=None, plot=None, thermo_library=thermo_library, kinetics_library=kinetics_library) <NEW_LINE> cls.thermo_library = thermo_library <NEW_LINE> cls.kinetics_library = kinetics_library <NEW_LINE> cls.explorer_job = cls.job_list[-1] <NEW_LINE> cls.pdep_job = cls.job_list[-2] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> import rmgpy.data.rmg <NEW_LINE> rmgpy.data.rmg.database.kinetics = None <NEW_LINE> <DEDENT> def test_reactions(self): <NEW_LINE> <INDENT> self.assertEqual(len(self.explorer_job.networks[0].path_reactions), 7) <NEW_LINE> <DEDENT> def test_isomers(self): <NEW_LINE> <INDENT> self.assertEqual(len(self.explorer_job.networks[0].isomers), 2) <NEW_LINE> <DEDENT> def test_job_rxns(self): <NEW_LINE> <INDENT> for rxn in self.explorer_job.job_rxns: <NEW_LINE> <INDENT> self.assertIn(rxn, self.explorer_job.networks[0].path_reactions) | Contains tests for ExplorerJob class execute method | 62599040be383301e0254a9d |
class Update(APIResource): <NEW_LINE> <INDENT> SCHEMAS = { "POST": Schema({ Required("version"): STRINGS})} <NEW_LINE> isLeaf = False <NEW_LINE> def post(self, **kwargs): <NEW_LINE> <INDENT> request = kwargs["request"] <NEW_LINE> data = kwargs["data"] <NEW_LINE> agent = config["agent"] <NEW_LINE> url = "%s/agents/updates/%s" % (config["master_api"], data["version"]) <NEW_LINE> url = url.encode() <NEW_LINE> def download_update(version): <NEW_LINE> <INDENT> config["downloading_update"] = True <NEW_LINE> deferred = get(url) <NEW_LINE> deferred.addCallback(update_downloaded) <NEW_LINE> deferred.addErrback(update_failed) <NEW_LINE> <DEDENT> def update_failed(arg): <NEW_LINE> <INDENT> logger.error("Downloading update failed: %r", arg) <NEW_LINE> if isinstance(arg, twisted.python.failure.Failure): <NEW_LINE> <INDENT> logger.error("Traceback: %s", arg.getTraceback()) <NEW_LINE> <DEDENT> reactor.callLater(http_retry_delay(), download_update, data["version"]) <NEW_LINE> <DEDENT> def update_downloaded(response): <NEW_LINE> <INDENT> if response.code == OK: <NEW_LINE> <INDENT> update_filename = join(config["agent_updates_dir"], "pyfarm-agent.zip") <NEW_LINE> logger.debug("Writing update to %s", update_filename) <NEW_LINE> if not isdir(config["agent_updates_dir"]): <NEW_LINE> <INDENT> makedirs(config["agent_updates_dir"]) <NEW_LINE> <DEDENT> with open(update_filename, "wb+") as update_file: <NEW_LINE> <INDENT> collect(response, update_file.write) <NEW_LINE> <DEDENT> logger.info("Update file for version %s has been downloaded " "and stored under %s", data["version"], update_filename) <NEW_LINE> config["restart_requested"] = True <NEW_LINE> if len(config["current_assignments"]) == 0: <NEW_LINE> <INDENT> stopping = agent.stop() <NEW_LINE> stopping.addCallback(lambda _: reactor.stop()) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.error("Unexpected return code %s on downloading update " "from master", response.code) <NEW_LINE> <DEDENT> config["downloading_update"] = False <NEW_LINE> <DEDENT> if ("downloading_update" not in config or not config["downloading_update"]): <NEW_LINE> <INDENT> download_update(data["version"]) <NEW_LINE> <DEDENT> request.setResponseCode(ACCEPTED) <NEW_LINE> request.finish() <NEW_LINE> return NOT_DONE_YET | Requests the agent to download and apply the specified version of itself.
Will make the agent restart at the next opportunity.
.. http:post:: /api/v1/update HTTP/1.1
**Request**
.. sourcecode:: http
POST /api/v1/update HTTP/1.1
Accept: application/json
{
"version": 1.2.3
}
**Response**
.. sourcecode:: http
HTTP/1.1 200 ACCEPTED
Content-Type: application/json | 62599040b830903b9686edbc |
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class _ExprOperator(_Expr): <NEW_LINE> <INDENT> def __init__(self, backend, key, operand, transform): <NEW_LINE> <INDENT> super(_ExprOperator, self).__init__(backend) <NEW_LINE> self._key = key <NEW_LINE> self._operand = operand <NEW_LINE> self._transform = transform <NEW_LINE> if transform: <NEW_LINE> <INDENT> self._normalize = lambda x: x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._normalize = self.InitializeNormalization <NEW_LINE> <DEDENT> <DEDENT> def InitializeNormalization(self, value): <NEW_LINE> <INDENT> self._normalize = lambda x: x <NEW_LINE> if re.match(r'\d\d\d\d-\d\d-\d\d[ T]\d\d:\d\d:\d\d', value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = times.ParseDateTime(value) <NEW_LINE> tzinfo = times.LOCAL if value.tzinfo else None <NEW_LINE> self._operand.Initialize( self._operand.list_value or self._operand.string_value, normalize=lambda x: times.ParseDateTime(x, tzinfo=tzinfo)) <NEW_LINE> self._normalize = times.ParseDateTime <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> def Evaluate(self, obj): <NEW_LINE> <INDENT> value = resource_property.Get(obj, self._key) <NEW_LINE> if self._transform: <NEW_LINE> <INDENT> value = self._transform.Evaluate(value) <NEW_LINE> <DEDENT> if value and isinstance(value, (list, tuple)): <NEW_LINE> <INDENT> resource_values = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resource_values = [value] <NEW_LINE> <DEDENT> values = [] <NEW_LINE> for value in resource_values: <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = self._normalize(value) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> values.append(value) <NEW_LINE> <DEDENT> if self._operand.list_value: <NEW_LINE> <INDENT> operands = self._operand.list_value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> operands = [self._operand] <NEW_LINE> <DEDENT> for value in values: <NEW_LINE> <INDENT> for operand in operands: <NEW_LINE> <INDENT> if operand.numeric_value is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.Apply(float(value), operand.numeric_value): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if not operand.numeric_constant: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> if self.Apply(value, operand.string_value): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> except (AttributeError, ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> if (value is not None and not isinstance(value, (six.string_types, dict, list)) and self.Apply(_Stringize(value), operand.string_value)): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if six.PY3 and value is None and self.Apply('', operand.string_value): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def Apply(self, value, operand): <NEW_LINE> <INDENT> pass | Base term (<key operator operand>) node.
ExprOperator subclasses must define the function Apply(self, value, operand)
that returns the result of <value> <op> <operand>.
Attributes:
_key: Resource object key (list of str, int and/or None values).
_normalize: The resource value normalization function.
_operand: The term ExprOperand operand.
_transform: Optional key value transform calls. | 625990408a43f66fc4bf3416 |
class Expr(expr.Expr): <NEW_LINE> <INDENT> def __init__(self, where, queryables=None, encoding=None, scope_level=0): <NEW_LINE> <INDENT> where = _validate_where(where) <NEW_LINE> self.encoding = encoding <NEW_LINE> self.condition = None <NEW_LINE> self.filter = None <NEW_LINE> self.terms = None <NEW_LINE> self._visitor = None <NEW_LINE> local_dict = DeepChainMap() <NEW_LINE> if isinstance(where, Expr): <NEW_LINE> <INDENT> local_dict = where.env.scope <NEW_LINE> where = where.expr <NEW_LINE> <DEDENT> elif isinstance(where, (list, tuple)): <NEW_LINE> <INDENT> for idx, w in enumerate(where): <NEW_LINE> <INDENT> if isinstance(w, Expr): <NEW_LINE> <INDENT> local_dict = w.env.scope <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> w = _validate_where(w) <NEW_LINE> where[idx] = w <NEW_LINE> <DEDENT> <DEDENT> where = " & ".join(map("({})".format, com.flatten(where))) <NEW_LINE> <DEDENT> self.expr = where <NEW_LINE> self.env = Scope(scope_level + 1, local_dict=local_dict) <NEW_LINE> if queryables is not None and isinstance(self.expr, str): <NEW_LINE> <INDENT> self.env.queryables.update(queryables) <NEW_LINE> self._visitor = ExprVisitor( self.env, queryables=queryables, parser="pytables", engine="pytables", encoding=encoding, ) <NEW_LINE> self.terms = self.parse() <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.terms is not None: <NEW_LINE> <INDENT> return pprint_thing(self.terms) <NEW_LINE> <DEDENT> return pprint_thing(self.expr) <NEW_LINE> <DEDENT> def evaluate(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.condition = self.terms.prune(ConditionBinOp) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError( "cannot process expression [{expr}], [{slf}] " "is not a valid condition".format(expr=self.expr, slf=self) ) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.filter = self.terms.prune(FilterBinOp) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError( "cannot process expression [{expr}], [{slf}] " "is not a valid filter".format(expr=self.expr, slf=self) ) <NEW_LINE> <DEDENT> return self.condition, self.filter | hold a pytables like expression, comprised of possibly multiple 'terms'
Parameters
----------
where : string term expression, Expr, or list-like of Exprs
queryables : a "kinds" map (dict of column name -> kind), or None if column
is non-indexable
encoding : an encoding that will encode the query terms
Returns
-------
an Expr object
Examples
--------
'index>=date'
"columns=['A', 'D']"
'columns=A'
'columns==A'
"~(columns=['A','B'])"
'index>df.index[3] & string="bar"'
'(index>df.index[3] & index<=df.index[6]) | string="bar"'
"ts>=Timestamp('2012-02-01')"
"major_axis>=20130101" | 62599040d99f1b3c44d06922 |
class TProcessor(object): <NEW_LINE> <INDENT> def __init__(self, service, handler): <NEW_LINE> <INDENT> self._service = service <NEW_LINE> self._handler = handler <NEW_LINE> <DEDENT> def process_in(self, iprot): <NEW_LINE> <INDENT> api, type, seqid = iprot.read_message_begin() <NEW_LINE> if api not in self._service.thrift_services: <NEW_LINE> <INDENT> iprot.skip(TType.STRUCT) <NEW_LINE> iprot.read_message_end() <NEW_LINE> return api, seqid, TApplicationException(TApplicationException.UNKNOWN_METHOD), None <NEW_LINE> <DEDENT> args = getattr(self._service, api + "_args")() <NEW_LINE> args.read(iprot) <NEW_LINE> iprot.read_message_end() <NEW_LINE> result = getattr(self._service, api + "_result")() <NEW_LINE> api_args = [args.thrift_spec[k][1] for k in sorted(args.thrift_spec)] <NEW_LINE> def call(): <NEW_LINE> <INDENT> f = getattr(self._handler, api) <NEW_LINE> return f(*(args.__dict__[k] for k in api_args)) <NEW_LINE> <DEDENT> return api, seqid, result, call <NEW_LINE> <DEDENT> def send_exception(self, oprot, api, exc, seqid): <NEW_LINE> <INDENT> oprot.write_message_begin(api, TMessageType.EXCEPTION, seqid) <NEW_LINE> exc.write(oprot) <NEW_LINE> oprot.write_message_end() <NEW_LINE> oprot.trans.flush() <NEW_LINE> <DEDENT> def send_result(self, oprot, api, result, seqid): <NEW_LINE> <INDENT> oprot.write_message_begin(api, TMessageType.REPLY, seqid) <NEW_LINE> result.write(oprot) <NEW_LINE> oprot.write_message_end() <NEW_LINE> oprot.trans.flush() <NEW_LINE> <DEDENT> def handle_exception(self, e, result): <NEW_LINE> <INDENT> for k in sorted(result.thrift_spec): <NEW_LINE> <INDENT> if result.thrift_spec[k][1] == "success": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> _, exc_name, exc_cls, _ = result.thrift_spec[k] <NEW_LINE> if isinstance(e, exc_cls): <NEW_LINE> <INDENT> setattr(result, exc_name, e) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> def process(self, iprot, oprot): <NEW_LINE> <INDENT> api, seqid, result, call = self.process_in(iprot) <NEW_LINE> if isinstance(result, TApplicationException): <NEW_LINE> <INDENT> return self.send_exception(oprot, api, result, seqid) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result.success = call() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.handle_exception(e, result) <NEW_LINE> <DEDENT> if not result.oneway: <NEW_LINE> <INDENT> self.send_result(oprot, api, result, seqid) | Base class for procsessor, which works on two streams. | 6259904007d97122c4217f25 |
class StudentProfileForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = StudentProfile <NEW_LINE> exclude = ('user_profile', ) | Student Profile Form | 6259904015baa72349463217 |
class EditPost(webapp2.RequestHandler): <NEW_LINE> <INDENT> def get(self, postkey): <NEW_LINE> <INDENT> user = users.get_current_user() <NEW_LINE> singlepost = Post.get(postkey) <NEW_LINE> parentblog = Blog.get_by_id(int(singlepost.parent_key().id())) <NEW_LINE> if user: <NEW_LINE> <INDENT> if parentblog.ownerid == user.user_id(): <NEW_LINE> <INDENT> template = JINJA_ENVIRONMENT.get_template('/templates/editpost.html') <NEW_LINE> self.response.write(template.render({'postkey':postkey, 'pretitle':singlepost.title, 'precontent':singlepost.content, 'pretags': singlepost.tagStr(), 'images': singlepost.images})) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> template = JINJA_ENVIRONMENT.get_template('/templates/error.html') <NEW_LINE> self.response.write(template.render({'dir': 'singlepost','key': postkey})) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.redirect(users.create_login_url('/editpost/%s' % postkey)) <NEW_LINE> <DEDENT> <DEDENT> def post(self, postkey): <NEW_LINE> <INDENT> singlepost = Post.get(postkey) <NEW_LINE> singlepost.title = self.request.get('title') <NEW_LINE> singlepost.content = self.request.get('content') <NEW_LINE> tags = self.request.get('tags') <NEW_LINE> taglist = re.split('[,; ]+', tags) <NEW_LINE> singlepost.tags = [] <NEW_LINE> for tagstr in taglist: <NEW_LINE> <INDENT> tag = Tag.all().filter('tag =', tagstr).get() <NEW_LINE> if tag == None: <NEW_LINE> <INDENT> tag = Tag(tag=tagstr) <NEW_LINE> tag.put() <NEW_LINE> <DEDENT> singlepost.tags.append(tag.key()) <NEW_LINE> <DEDENT> if self.request.get('file'): <NEW_LINE> <INDENT> image = Image() <NEW_LINE> image.image = self.request.POST.get('file').file.read() <NEW_LINE> image.contentType = self.request.body_file.vars['file'].headers['content-type'] <NEW_LINE> image.post = singlepost <NEW_LINE> image.put() <NEW_LINE> singlepost.content = singlepost.content + '\n' + '[img:%s]' % image.key() + '\n' <NEW_LINE> <DEDENT> singlepost.put() <NEW_LINE> self.redirect('/singlepost/%s' % postkey) | Edit Post, content will be prefilled by previous one | 62599040c432627299fa4244 |
class OrdemDeServico(models.Model): <NEW_LINE> <INDENT> numero = models.CharField(_(u'Número'), max_length=20) <NEW_LINE> tipo = models.ForeignKey('outorga.TipoContrato') <NEW_LINE> acordo = models.ForeignKey('outorga.Acordo') <NEW_LINE> contrato = models.ForeignKey('outorga.Contrato') <NEW_LINE> data_inicio = NARADateField(_(u'Início')) <NEW_LINE> data_rescisao = NARADateField(_(u'Término'), null=True, blank=True) <NEW_LINE> antes_rescisao = models.IntegerField(_(u'Prazo p/ solicitar rescisão (dias)'), null=True, blank=True) <NEW_LINE> descricao = models.TextField(_(u'Descrição')) <NEW_LINE> estado = models.ForeignKey('outorga.EstadoOS') <NEW_LINE> pergunta = models.ManyToManyField('memorando.Pergunta', null=True, blank=True) <NEW_LINE> substituicoes = models.TextField(null=True, blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s %s" % (self.tipo, self.numero) <NEW_LINE> <DEDENT> def mostra_prazo(self): <NEW_LINE> <INDENT> if self.antes_rescisao < 1: <NEW_LINE> <INDENT> return '-' <NEW_LINE> <DEDENT> if self.antes_rescisao > 1: <NEW_LINE> <INDENT> return u'%s dias' % self.antes_rescisao <NEW_LINE> <DEDENT> return u'%s dias' % self.antes_rescisao <NEW_LINE> <DEDENT> mostra_prazo.short_description = _(u'Prazo p/ rescisão') <NEW_LINE> def entidade(self): <NEW_LINE> <INDENT> return self.contrato.entidade <NEW_LINE> <DEDENT> def primeiro_arquivo(self): <NEW_LINE> <INDENT> if self.arquivos.all().exists(): <NEW_LINE> <INDENT> osf = self.arquivos.all()[:1].get() <NEW_LINE> return osf.arquivo <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _(u'Alteração de contrato (OS)') <NEW_LINE> verbose_name_plural = _(u'Alteração de contratos (OS)') <NEW_LINE> ordering = ('tipo', 'numero') | Uma instância dessa classe representa uma ordem de serviço de um Contrato.
arquivos: related_name para ArquivoOS | 62599040e64d504609df9d14 |
class GroupExpirationMiddleware(MiddlewareMixin): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> if hasattr(user, 'active_range') and user.groups.exists(): <NEW_LINE> <INDENT> today = now().date() <NEW_LINE> end_date = user.active_range.end_date <NEW_LINE> if end_date and end_date < today: <NEW_LINE> <INDENT> user.is_staff = False <NEW_LINE> user.save() <NEW_LINE> user.groups.clear() <NEW_LINE> message = _('This account no longer has staff access.') <NEW_LINE> messages.error(request, message) | Middleware which removes users from all groups after a specified expiration
date.
Needs to come after auth middleware because it needs request.user.
Needs to come after message middleware because it needs request._messages. | 625990401d351010ab8f4da4 |
class Player(Model): <NEW_LINE> <INDENT> def __init__(self, name, number=None, team=None, color=None, **kwargs): <NEW_LINE> <INDENT> super(Player, self).__init__(**kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.number = number <NEW_LINE> if isinstance(team, Team): <NEW_LINE> <INDENT> self.team = team <NEW_LINE> <DEDENT> elif isinstance(team, str): <NEW_LINE> <INDENT> self.team = Team(team, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.team = None <NEW_LINE> <DEDENT> self.color = color | Um jogador de futebol | 625990408e05c05ec3f6f79e |
@dataclass <NEW_LINE> class CaptureTextEvent: <NEW_LINE> <INDENT> capture_id: str <NEW_LINE> text: str <NEW_LINE> complete: bool | Keyboard event denoting the current capture state of text
Capturing text is triggered by calling `capture_text` on the keyboard handler. | 6259904016aa5153ce401774 |
class ConditionException(Exception): <NEW_LINE> <INDENT> def __init__(self, var = "Condition Fail"): <NEW_LINE> <INDENT> self.var = var | If there is a failure in building a condition this is raised | 6259904050485f2cf55dc20b |
class UnlockServer(command.Command): <NEW_LINE> <INDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(UnlockServer, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'server', metavar='<server>', nargs='+', help=_('Server(s) to unlock (name or ID)'), ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> compute_client = self.app.client_manager.compute <NEW_LINE> for server in parsed_args.server: <NEW_LINE> <INDENT> utils.find_resource( compute_client.servers, server, ).unlock() | Unlock server(s) | 62599040b830903b9686edbd |
class Cell: <NEW_LINE> <INDENT> def __init__(self, value, row, column, block_size): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.row = row <NEW_LINE> self.column = column <NEW_LINE> self.block = self.calc_block_index(block_size) <NEW_LINE> self.candidate_set = set() <NEW_LINE> self.index = column + row*(block_size**2) <NEW_LINE> <DEDENT> def calc_block_index(self, block_size): <NEW_LINE> <INDENT> return self.column//block_size+((self.row//block_size)*block_size) <NEW_LINE> <DEDENT> def showinfo(self): <NEW_LINE> <INDENT> print('index' + str(self.index), end='') <NEW_LINE> print(' value' + self.value) <NEW_LINE> print('row' + str(self.row), end='') <NEW_LINE> print(' column' + str(self.column), end='') <NEW_LINE> print(' block' + str(self.block), end='') <NEW_LINE> print(' candidate' + str(self.candidate_set)) <NEW_LINE> print('\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\') | 数独表のセルの管理クラス | 625990401f5feb6acb163e7b |
class rbm_qmc: <NEW_LINE> <INDENT> def __init__(self, nvisible, nhidden, hbias=None, vbias=None, W_real=None, W_imag=None, input=None, np_rng=None, theano_rng=None, ): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def prop_up(self,vsample): <NEW_LINE> <INDENT> pass | This is a variational monte carlo implementation on the Neural Network
representing ground state.
It is the Python implementation with Theano on the Science paper
Science 355 ,602-606 (2017).
For the details, please refer to the original paper. | 625990404e696a045264e765 |
class ClientViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = serializers.ClientSerializer <NEW_LINE> queryset = models.Client.objects.all() | A viewset for viewing and editing user instances. | 62599040d6c5a102081e33ad |
class C4View: <NEW_LINE> <INDENT> def prompt_turn(self, name): <NEW_LINE> <INDENT> choice = input("{}, where would you like to go? ".format(name)) <NEW_LINE> return choice <NEW_LINE> <DEDENT> def show_instructions(self): <NEW_LINE> <INDENT> print_statement = ("1. On your turn, drop one of your discs into any slot in the top of " "the grid.\n" "2. Take turns until one player get four\nof their color discs in a" "row -\n" "horizontally, vertically, or diagonally\n" "3. The first player to 4-in-a-row wins!") <NEW_LINE> print(print_statement, sep="", end="") <NEW_LINE> <DEDENT> def win_statement(self, name): <NEW_LINE> <INDENT> winning_statement = ("Congrats {} you've won!!!!").format(name) <NEW_LINE> print(winning_statement) <NEW_LINE> <DEDENT> def tie_statement(self): <NEW_LINE> <INDENT> tie_statement = ("The board is full, no one wins X_x," "basically you're both losers.") <NEW_LINE> print(tie_statement) <NEW_LINE> <DEDENT> def print_board(self,board): <NEW_LINE> <INDENT> final_board = " 1 2 3 4 5 6 7\n" <NEW_LINE> for row in range(5, -1, -1): <NEW_LINE> <INDENT> new_row = "" <NEW_LINE> for col in range(7): <NEW_LINE> <INDENT> new_row += "| {} ".format(board[col][row]) <NEW_LINE> <DEDENT> new_row += "|\n" <NEW_LINE> final_board += new_row <NEW_LINE> <DEDENT> print(final_board[:-1]) <NEW_LINE> <DEDENT> def prompt_name(self, player_num): <NEW_LINE> <INDENT> return input("\nYo yo player {}, what's your name? ".format(player_num)) | Connect 4 view | 62599040711fe17d825e15e0 |
class TestNodeCLI(): <NEW_LINE> <INDENT> def __init__(self, binary, datadir): <NEW_LINE> <INDENT> self.options = [] <NEW_LINE> self.binary = binary <NEW_LINE> self.datadir = datadir <NEW_LINE> self.input = None <NEW_LINE> self.log = logging.getLogger('TestFramework.bitcoincli') <NEW_LINE> <DEDENT> def __call__(self, *options, input=None): <NEW_LINE> <INDENT> cli = TestNodeCLI(self.binary, self.datadir) <NEW_LINE> cli.options = [str(o) for o in options] <NEW_LINE> cli.input = input <NEW_LINE> return cli <NEW_LINE> <DEDENT> def __getattr__(self, command): <NEW_LINE> <INDENT> return TestNodeCLIAttr(self, command) <NEW_LINE> <DEDENT> def batch(self, requests): <NEW_LINE> <INDENT> results = [] <NEW_LINE> for request in requests: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> results.append(dict(result=request())) <NEW_LINE> <DEDENT> except JSONRPCException as e: <NEW_LINE> <INDENT> results.append(dict(error=e)) <NEW_LINE> <DEDENT> <DEDENT> return results <NEW_LINE> <DEDENT> def send_cli(self, command=None, *args, **kwargs): <NEW_LINE> <INDENT> pos_args = [str(arg) for arg in args] <NEW_LINE> named_args = [str(key) + "=" + str(value) for (key, value) in kwargs.items()] <NEW_LINE> assert not (pos_args and named_args), "Cannot use positional arguments and named arguments in the same eros-cli call" <NEW_LINE> p_args = [self.binary, "-datadir=" + self.datadir] + self.options <NEW_LINE> if named_args: <NEW_LINE> <INDENT> p_args += ["-named"] <NEW_LINE> <DEDENT> if command is not None: <NEW_LINE> <INDENT> p_args += [command] <NEW_LINE> <DEDENT> p_args += pos_args + named_args <NEW_LINE> self.log.debug("Running bitcoin-cli command: %s" % command) <NEW_LINE> process = subprocess.Popen(p_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) <NEW_LINE> cli_stdout, cli_stderr = process.communicate(input=self.input) <NEW_LINE> returncode = process.poll() <NEW_LINE> if returncode: <NEW_LINE> <INDENT> match = re.match(r'error code: ([-0-9]+)\nerror message:\n(.*)', cli_stderr) <NEW_LINE> if match: <NEW_LINE> <INDENT> code, message = match.groups() <NEW_LINE> raise JSONRPCException(dict(code=int(code), message=message)) <NEW_LINE> <DEDENT> raise subprocess.CalledProcessError(returncode, self.binary, output=cli_stderr) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return json.loads(cli_stdout, parse_float=decimal.Decimal) <NEW_LINE> <DEDENT> except JSONDecodeError: <NEW_LINE> <INDENT> return cli_stdout.rstrip("\n") | Interface to eros-cli for an individual node | 6259904023849d37ff852341 |
class PelicanMathJaxCorrectDisplayMath(markdown.treeprocessors.Treeprocessor): <NEW_LINE> <INDENT> def __init__(self, pelican_mathjax_extension): <NEW_LINE> <INDENT> self.pelican_mathjax_extension = pelican_mathjax_extension <NEW_LINE> <DEDENT> def correct_html(self, root, children, div_math, insert_idx, text): <NEW_LINE> <INDENT> current_idx = 0 <NEW_LINE> for idx in div_math: <NEW_LINE> <INDENT> el = markdown.util.etree.Element('p') <NEW_LINE> el.text = text <NEW_LINE> el.extend(children[current_idx:idx]) <NEW_LINE> if len(el) != 0 or (el.text and not el.text.isspace()): <NEW_LINE> <INDENT> root.insert(insert_idx, el) <NEW_LINE> insert_idx += 1 <NEW_LINE> <DEDENT> text = children[idx].tail <NEW_LINE> children[idx].tail = None <NEW_LINE> root.insert(insert_idx, children[idx]) <NEW_LINE> insert_idx += 1 <NEW_LINE> current_idx = idx+1 <NEW_LINE> <DEDENT> el = markdown.util.etree.Element('p') <NEW_LINE> el.text = text <NEW_LINE> el.extend(children[current_idx:]) <NEW_LINE> if len(el) != 0 or (el.text and not el.text.isspace()): <NEW_LINE> <INDENT> root.insert(insert_idx, el) <NEW_LINE> <DEDENT> <DEDENT> def run(self, root): <NEW_LINE> <INDENT> math_tag_class = self.pelican_mathjax_extension.getConfig('math_tag_class') <NEW_LINE> for parent in root: <NEW_LINE> <INDENT> div_math = [] <NEW_LINE> children = list(parent) <NEW_LINE> for div in parent.findall('div'): <NEW_LINE> <INDENT> if div.get('class') == math_tag_class: <NEW_LINE> <INDENT> div_math.append(children.index(div)) <NEW_LINE> <DEDENT> <DEDENT> if not div_math: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> insert_idx = list(root).index(parent) <NEW_LINE> self.correct_html(root, children, div_math, insert_idx, parent.text) <NEW_LINE> root.remove(parent) <NEW_LINE> <DEDENT> return root | Corrects invalid html that results from a <div> being put inside
a <p> for displayed math | 62599040e76e3b2f99fd9c94 |
class PerformanceResource(api.ApiResource): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> LOG.debug('=== Creating PerformanceResource ===') <NEW_LINE> <DEDENT> def on_get(self, req, resp): <NEW_LINE> <INDENT> resp.status = falcon.HTTP_200 <NEW_LINE> resp.body = '42' | Supports a static response to support performance testing. | 625990403c8af77a43b68880 |
class PartsmanagementException(Exception): <NEW_LINE> <INDENT> def __init__(self, error): <NEW_LINE> <INDENT> super(PartsmanagementException, self).__init__(error) <NEW_LINE> logger.error(_("An fatal error has been occurred: %s" % error)) | Base exceptions for this packages | 62599040b57a9660fecd2d03 |
class ModuleComponentFilter(MultiValueFilter): <NEW_LINE> <INDENT> @value_is_not_empty <NEW_LINE> def _filter(self, qs, name, values): <NEW_LINE> <INDENT> query = Q() <NEW_LINE> for value in values: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name, branch = value.split('/', 2) <NEW_LINE> filters = {'name': name, 'srpm_commit_branch': branch} <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> filters = {'name': value} <NEW_LINE> <DEDENT> query |= Q(**filters) <NEW_LINE> <DEDENT> rpms = RPM.objects.filter(query) <NEW_LINE> qs = qs.filter(rpms__in=rpms).distinct() <NEW_LINE> return qs | Multi-value filter for modules with an RPM with given name and branch. | 62599040507cdc57c63a6024 |
class NoSignupAccountAdapter(DefaultAccountAdapter): <NEW_LINE> <INDENT> def is_open_for_signup(self, request): <NEW_LINE> <INDENT> return False | Disable open signup. | 6259904024f1403a92686211 |
class TradesLine(object): <NEW_LINE> <INDENT> def __init__(self, src, dest, rate, amount, date, sell_or_buy, fee): <NEW_LINE> <INDENT> self.src = src <NEW_LINE> self.dest = dest <NEW_LINE> self.rate = rate <NEW_LINE> self.amount = amount <NEW_LINE> self.date = date <NEW_LINE> self.type = sell_or_buy <NEW_LINE> self.fee = fee | A representation of a line inside the trades CSV file | 6259904007f4c71912bb06bb |
class _LayerList(list): <NEW_LINE> <INDENT> def __new__(cls, data=None): <NEW_LINE> <INDENT> obj = super(_LayerList, cls).__new__(cls, data) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if len(self) == 0: <NEW_LINE> <INDENT> return '[]' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> layer_index_added = [('layer[%d]: ' % i) + self[i].__repr__() for i in range(len(self))] <NEW_LINE> return '\n'.join(layer_index_added) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return _LayerList(list(self) + list(other)) | Like regular list, but has a different str and repr function | 6259904023e79379d538d789 |
class Command(WeblateTranslationCommand): <NEW_LINE> <INDENT> help = 'performs automatic translation based on other components' <NEW_LINE> def add_arguments(self, parser): <NEW_LINE> <INDENT> super(Command, self).add_arguments(parser) <NEW_LINE> parser.add_argument( '--user', default='anonymous', help=( 'User performing the change' ) ) <NEW_LINE> parser.add_argument( '--source', default='', help=( 'Source component <project/component>' ) ) <NEW_LINE> parser.add_argument( '--add', default=False, action='store_true', help=( 'Add translations if they do not exist' ) ) <NEW_LINE> parser.add_argument( '--overwrite', default=False, action='store_true', help=( 'Overwrite existing translations in target component' ) ) <NEW_LINE> parser.add_argument( '--inconsistent', default=False, action='store_true', help=( 'Process only inconsistent translations' ) ) <NEW_LINE> parser.add_argument( '--mt', action='append', default=[], help=( 'Add machine translation source' ) ) <NEW_LINE> parser.add_argument( '--threshold', default=80, type=int, help=( 'Set machine translation threshold' ) ) <NEW_LINE> <DEDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> translation = self.get_translation(**options) <NEW_LINE> try: <NEW_LINE> <INDENT> user = User.objects.get(username=options['user']) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> raise CommandError('User does not exist!') <NEW_LINE> <DEDENT> if options['source']: <NEW_LINE> <INDENT> parts = options['source'].split('/') <NEW_LINE> if len(parts) != 2: <NEW_LINE> <INDENT> raise CommandError('Invalid source component specified!') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> component = Component.objects.get( project__slug=parts[0], slug=parts[1], ) <NEW_LINE> <DEDENT> except Component.DoesNotExist: <NEW_LINE> <INDENT> raise CommandError('No matching source component found!') <NEW_LINE> <DEDENT> source = component.id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> source = '' <NEW_LINE> <DEDENT> if options['mt']: <NEW_LINE> <INDENT> for translator in options['mt']: <NEW_LINE> <INDENT> if translator not in MACHINE_TRANSLATION_SERVICES.keys(): <NEW_LINE> <INDENT> raise CommandError( 'Machine translation {} is not available'.format( translator ) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if options['inconsistent']: <NEW_LINE> <INDENT> filter_type = 'check:inconsistent' <NEW_LINE> <DEDENT> elif options['overwrite']: <NEW_LINE> <INDENT> filter_type = 'all' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filter_type = 'todo' <NEW_LINE> <DEDENT> request = HttpRequest() <NEW_LINE> request.user = user <NEW_LINE> auto = AutoTranslate(user, translation, filter_type, request) <NEW_LINE> if options['mt']: <NEW_LINE> <INDENT> auto.process_mt(options['mt'], options['threshold']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> auto.process_others(source, check_acl=False) <NEW_LINE> <DEDENT> self.stdout.write('Updated {0} units'.format(auto.updated)) | Command for mass automatic translation. | 625990403eb6a72ae038b8f4 |
class Frame(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.frame = [] <NEW_LINE> <DEDENT> def __contains__(self, searched_item): <NEW_LINE> <INDENT> if len(self.frame) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for item_dict in self.frame: <NEW_LINE> <INDENT> for item_name in item_dict.keys(): <NEW_LINE> <INDENT> if searched_item == item_name: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.frame) <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> if self.frame is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> content = [] <NEW_LINE> for item in self.frame: <NEW_LINE> <INDENT> for var, var_t in item.items(): <NEW_LINE> <INDENT> for value in var_t.values(): <NEW_LINE> <INDENT> for val, val_t in value.items(): <NEW_LINE> <INDENT> content.append("{} -> value: {} type: {}".format(var, val, val_t).encode('unicode_escape').decode('utf-8')) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return str.join('\n', content) <NEW_LINE> <DEDENT> def print_dict(self): <NEW_LINE> <INDENT> for item in self.frame: <NEW_LINE> <INDENT> print(item) <NEW_LINE> <DEDENT> <DEDENT> def append(self, item): <NEW_LINE> <INDENT> self.frame.append(item) <NEW_LINE> <DEDENT> def redef(self, searched_var): <NEW_LINE> <INDENT> for item in self.frame: <NEW_LINE> <INDENT> for var in item.keys(): <NEW_LINE> <INDENT> if var == searched_var: <NEW_LINE> <INDENT> item[var] = {'value':{None:None}} <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def update(self, searched_var, value, value_t): <NEW_LINE> <INDENT> for item in self.frame: <NEW_LINE> <INDENT> for var in item.keys(): <NEW_LINE> <INDENT> if var == searched_var: <NEW_LINE> <INDENT> item[var] = {'value':{value:value_t}} <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def get_val(self, searched_var): <NEW_LINE> <INDENT> for item in self.frame: <NEW_LINE> <INDENT> for var in item.keys(): <NEW_LINE> <INDENT> if var == searched_var: <NEW_LINE> <INDENT> for v in item[var].values(): <NEW_LINE> <INDENT> for val, val_t in v.items(): <NEW_LINE> <INDENT> return (val, val_t) | Base class for every frame | 6259904015baa7234946321b |
class _SparseFeatureHandler(object): <NEW_LINE> <INDENT> def __init__(self, name, feature_spec, value_index, index_index, reader=None, encoder=None): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._cast_fn = _make_cast_fn(feature_spec.dtype) <NEW_LINE> self._np_dtype = feature_spec.dtype.as_numpy_dtype <NEW_LINE> self._value_index = value_index <NEW_LINE> self._value_name = feature_spec.value_key <NEW_LINE> self._index_index = index_index <NEW_LINE> self._index_name = feature_spec.index_key <NEW_LINE> self._size = feature_spec.size <NEW_LINE> self._reader = reader <NEW_LINE> self._encoder = encoder <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def parse_value(self, string_list): <NEW_LINE> <INDENT> value_str = string_list[self._value_index] <NEW_LINE> index_str = string_list[self._index_index] <NEW_LINE> if value_str and self._reader: <NEW_LINE> <INDENT> values = map(self._cast_fn, _decode_with_reader(value_str, self._reader)) <NEW_LINE> <DEDENT> elif value_str: <NEW_LINE> <INDENT> values = [self._cast_fn(value_str)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> values = [] <NEW_LINE> <DEDENT> if index_str and self._reader: <NEW_LINE> <INDENT> indices = map(int, _decode_with_reader(index_str, self._reader)) <NEW_LINE> <DEDENT> elif index_str: <NEW_LINE> <INDENT> indices = [int(index_str)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> indices = [] <NEW_LINE> <DEDENT> if indices: <NEW_LINE> <INDENT> i_min, i_max = min(indices), max(indices) <NEW_LINE> if i_min < 0 or i_max >= self._size: <NEW_LINE> <INDENT> i_bad = i_min if i_min < 0 else i_max <NEW_LINE> raise ValueError('SparseFeature %r has index %d out of range [0, %d)' % (self._name, i_bad, self._size)) <NEW_LINE> <DEDENT> <DEDENT> if len(values) != len(indices): <NEW_LINE> <INDENT> raise ValueError( 'SparseFeature %r has indices and values of different lengths: ' 'values: %r, indices: %r' % (self._name, values, indices)) <NEW_LINE> <DEDENT> return (np.asarray(indices, dtype=np.int64), np.asarray(values, dtype=self._np_dtype)) <NEW_LINE> <DEDENT> def encode_value(self, string_list, sparse_value): <NEW_LINE> <INDENT> index, value = sparse_value <NEW_LINE> if len(value) == len(index): <NEW_LINE> <INDENT> if self._encoder: <NEW_LINE> <INDENT> string_list[self._value_index] = self._encoder.encode_record( map(str, value)) <NEW_LINE> string_list[self._index_index] = self._encoder.encode_record( map(str, index)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> string_list[self._value_index] = str(value[0]) if value else '' <NEW_LINE> string_list[self._index_index] = str(index[0]) if index else '' <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( 'SparseFeature %r has value and index unaligned %r vs %r.' % (self._name, value, index)) | Handler for `SparseFeature` values.
`SparseFeature` values will be parsed as a tuple of 1-D arrays where the first
array corresponds to their indices and the second to the values. | 62599040b5575c28eb71360e |
class PreferencesProxy(PreferencesDialog): <NEW_LINE> <INDENT> def __init__(self, parent, session): <NEW_LINE> <INDENT> PreferencesDialog.__init__(self, "Proxy") <NEW_LINE> proxies = [ ["Proxy for torrent peer connections", session.peer_proxy, session.set_peer_proxy], ["Proxy for torrent web seed connections", session.web_seed_proxy, session.set_web_seed_proxy], ["Proxy for tracker connections", session.tracker_proxy, session.set_tracker_proxy], ["Proxy for DHT connections", session.dht_proxy, session.set_dht_proxy], ] <NEW_LINE> for title, rfunc, wfunc in proxies: <NEW_LINE> <INDENT> pg = ProxyGroup(self, title, rfunc, wfunc) <NEW_LINE> pg.show() <NEW_LINE> self.box.pack_end(pg) | Proxy preference dialog | 6259904063b5f9789fe863f6 |
class StatsLogNotFound(StepNotFound): <NEW_LINE> <INDENT> pass | Step of statslog not found in pipeline | 62599040e76e3b2f99fd9c96 |
class PLATFORM(_Enum): <NEW_LINE> <INDENT> AMD = _Enum_Type(0) <NEW_LINE> APPLE = _Enum_Type(1) <NEW_LINE> INTEL = _Enum_Type(2) <NEW_LINE> NVIDIA = _Enum_Type(3) <NEW_LINE> BEIGNET = _Enum_Type(4) <NEW_LINE> POCL = _Enum_Type(5) <NEW_LINE> UNKNOWN = _Enum_Type(-1) | ArrayFire enum for common platforms | 625990406e29344779b018dc |
class InventoryRoles(CumulocityResource): <NEW_LINE> <INDENT> def __init__(self, c8y): <NEW_LINE> <INDENT> super().__init__(c8y, '/user/inventoryroles') <NEW_LINE> self.object_name = "roles" <NEW_LINE> <DEDENT> def get(self, id: str | int) -> InventoryRole: <NEW_LINE> <INDENT> role = InventoryRole.from_json(self._get_object(id)) <NEW_LINE> role.c8y = self.c8y <NEW_LINE> return role <NEW_LINE> <DEDENT> def select(self, limit: int = None, page_size: int = 1000) -> Generator[InventoryRole]: <NEW_LINE> <INDENT> base_query = self._build_base_query(page_size=page_size) <NEW_LINE> return super()._iterate(base_query, limit, InventoryRole.from_json) <NEW_LINE> <DEDENT> def get_all(self, limit: int = None, page_size: int = 1000) -> List[InventoryRole]: <NEW_LINE> <INDENT> return list(self.select(limit=limit, page_size=page_size)) <NEW_LINE> <DEDENT> def select_assignments(self, username: str) -> Generator[InventoryRoleAssignment]: <NEW_LINE> <INDENT> query = f'/user/{self.c8y.tenant_id}/users/{username}/roles/inventory' <NEW_LINE> assignments_json = self.c8y.get(query) <NEW_LINE> for j in assignments_json['inventoryAssignments']: <NEW_LINE> <INDENT> result = InventoryRoleAssignment.from_json(j) <NEW_LINE> result.c8y = self.c8y <NEW_LINE> yield result <NEW_LINE> <DEDENT> <DEDENT> def get_all_assignments(self, username: str) -> List[InventoryRoleAssignment]: <NEW_LINE> <INDENT> return list(self.select_assignments(username)) <NEW_LINE> <DEDENT> def create(self, *roles: InventoryRole): <NEW_LINE> <INDENT> super()._create(InventoryRole.to_full_json, *roles) <NEW_LINE> <DEDENT> def update(self, *roles: InventoryRole): <NEW_LINE> <INDENT> super()._update(InventoryRole.to_diff_json, *roles) | Provides access to the InventoryRole API.
This class can be used for get, search for, create, update and
delete inventory roles within the Cumulocity database.
See also: https://cumulocity.com/api/#tag/Inventory-Roles | 6259904045492302aabfd765 |
class ObjKey2(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.required = [ "k1","k2"] <NEW_LINE> self.b_key = "obj-key-2" <NEW_LINE> self.a10_url="/axapi/v3/cm-ut/obj-key-2/{k1}+{k2}" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.k2 = "" <NEW_LINE> self.k1 = "" <NEW_LINE> self.d1 = "" <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value) | Class Description::
Unit test of optional key.
Class obj-key-2 supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param k2: {"minLength": 1, "maxLength": 32, "type": "string", "optional": false, "format": "string"}
:param k1: {"optional": false, "minimum": 1, "type": "number", "maximum": 32, "format": "number"}
:param d1: {"optional": true, "type": "string", "description": "some data", "format": "ipv4-address"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/cm-ut/obj-key-2/{k1}+{k2}`. | 625990408e05c05ec3f6f7a0 |
class ImportBlockbotList(BaseModel): <NEW_LINE> <INDENT> blockbot_id: str <NEW_LINE> name: str <NEW_LINE> class Config: <NEW_LINE> <INDENT> orm_mode = True | Details needed to import a Twitter list. | 6259904030c21e258be99a97 |
class Whoami(Plugin): <NEW_LINE> <INDENT> def tell(self, msg): <NEW_LINE> <INDENT> return msg['from'] <NEW_LINE> <DEDENT> def _init(self, event): <NEW_LINE> <INDENT> self.dispatcher.notify_until(Event(self, 'console.command.add', {'plugin': self.__class__.__name__, 'actions': {'tell': (self.tell, lambda p, a, u: True)}})) | Plugin that tells caller about itself profile | 62599040507cdc57c63a6026 |
class UserProfile(models.Model): <NEW_LINE> <INDENT> user = models.OneToOneField(User, related_name='profile') <NEW_LINE> picture = models.ImageField(upload_to='profile_images', blank=True, help_text='Your pretty face') <NEW_LINE> pushover_key = models.CharField(max_length=256, help_text='account key from pushover') <NEW_LINE> friends = models.ManyToManyField(User, blank=True, null=True, help_text='A trusted friend') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return str(self.user) | Extra information to track for each user | 625990408e71fb1e983bcd58 |
class IncomeTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> income = pd.read_excel("indicator gapminder gdp_per_capita_ppp.xlsx", index_col = "gdp pc test") <NEW_LINE> self.income = income.transpose() | Base class for TestCases that require income DF | 62599040287bf620b6272e71 |
class SmtpSinkServer(smtpd.SMTPServer): <NEW_LINE> <INDENT> __version__ = 'SMTP Test Sink version 1.00' <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> smtpd.SMTPServer.__init__(self, *args, **kwargs) <NEW_LINE> self.mailboxFile = None <NEW_LINE> <DEDENT> def setMailboxFile(self, mailboxFile): <NEW_LINE> <INDENT> self.mailboxFile = mailboxFile <NEW_LINE> <DEDENT> def process_message(self, peer, mailfrom, rcpttos, data): <NEW_LINE> <INDENT> if self.mailboxFile is not None: <NEW_LINE> <INDENT> self.mailboxFile.write('From {0}\n'.format(mailfrom)) <NEW_LINE> self.mailboxFile.write(data) <NEW_LINE> self.mailboxFile.write('\n\n') <NEW_LINE> self.mailboxFile.flush() | Unix Mailbox File SMTP Server Class | 6259904007d97122c4217f2a |
class Documento: <NEW_LINE> <INDENT> file_path = "" <NEW_LINE> arquivo = None <NEW_LINE> texto = "" <NEW_LINE> palavras = None <NEW_LINE> indice = None <NEW_LINE> classe = "" <NEW_LINE> def __init__(self, f): <NEW_LINE> <INDENT> self.file_path = f <NEW_LINE> self.palavras = array <NEW_LINE> self.indice = dict() <NEW_LINE> self.manager() <NEW_LINE> <DEDENT> def abrir(self, mode): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.arquivo = open(self.file_path, mode) <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print ("Ocorreu um erro ao tentar abrir o arquivo!") <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def fechar(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.arquivo.close() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print ( "Nao foi possivel fechar o arquivo! Verifique se o seu sistema esta impossibilitando este procedimento.") <NEW_LINE> <DEDENT> <DEDENT> def ler(self): <NEW_LINE> <INDENT> self.arquivo = open(self.file_path, "r") <NEW_LINE> if self.arquivo: <NEW_LINE> <INDENT> self.texto = self.arquivo.read() <NEW_LINE> self.fechar() <NEW_LINE> return True <NEW_LINE> <DEDENT> self.fechar() <NEW_LINE> return False <NEW_LINE> <DEDENT> def setClasse(self, classe): <NEW_LINE> <INDENT> self.classe = classe <NEW_LINE> <DEDENT> def separaPalavras(self): <NEW_LINE> <INDENT> self.palavras = self.texto.split(" ") <NEW_LINE> <DEDENT> def calculaFrequencia(self): <NEW_LINE> <INDENT> for palavra in self.palavras: <NEW_LINE> <INDENT> if palavra: <NEW_LINE> <INDENT> if palavra in self.indice: <NEW_LINE> <INDENT> value = self.indice.get(palavra) <NEW_LINE> self.indice[palavra] = value + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.indice[palavra] = 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def getPalavras(self): <NEW_LINE> <INDENT> return self.palavras <NEW_LINE> <DEDENT> def getChaves(self): <NEW_LINE> <INDENT> return self.indice.keys() <NEW_LINE> <DEDENT> def getValores(self): <NEW_LINE> <INDENT> return self.indice.values() <NEW_LINE> <DEDENT> def getItens(self): <NEW_LINE> <INDENT> return self.indice.items() <NEW_LINE> <DEDENT> def manager(self): <NEW_LINE> <INDENT> self.ler() <NEW_LINE> self.separaPalavras() <NEW_LINE> self.calculaFrequencia() | Classe modelo para o documento | 625990408da39b475be0447a |
class IdenticaResponder(utils.RouteResponder): <NEW_LINE> <INDENT> map = Mapper() <NEW_LINE> map.connect('login', '/auth', action='login', requirements=dict(method='POST')) <NEW_LINE> map.connect('process', '/process', action='process') <NEW_LINE> def __init__(self, storage, consumer_key, consumer_secret): <NEW_LINE> <INDENT> self.consumer_key = consumer_key <NEW_LINE> self.consumer_secret = consumer_secret <NEW_LINE> self.storage = storage <NEW_LINE> self._consumer = oauth.Consumer(consumer_key, consumer_secret) <NEW_LINE> self._sigmethod = oauth.SignatureMethod_HMAC_SHA1() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parse_config(cls, config): <NEW_LINE> <INDENT> key_map = {'Consumer Key': 'consumer_key', 'Consumer Secret': 'consumer_secret'} <NEW_LINE> identica_vals = config['Identica'] <NEW_LINE> params = {} <NEW_LINE> for k, v in key_map.items(): <NEW_LINE> <INDENT> params[v] = identica_vals[k] <NEW_LINE> <DEDENT> params['storage'] = config['UserStore'] <NEW_LINE> return params <NEW_LINE> <DEDENT> def login(self, req): <NEW_LINE> <INDENT> end_point = req.POST['end_point'] <NEW_LINE> client = oauth.Client(self._consumer) <NEW_LINE> params = {'oauth_callback': req.link('process', qualified=True)} <NEW_LINE> request = oauth.Request.from_consumer_and_token(self._consumer, http_url=REQUEST_URL, parameters=params) <NEW_LINE> request.sign_request(self._sigmethod, self._consumer, None) <NEW_LINE> resp, content = httplib2.Http.request(client, REQUEST_URL, method='GET', headers=request.to_header()) <NEW_LINE> if resp['status'] != '200': <NEW_LINE> <INDENT> log.debug("Identi.ca oauth failed: %r %r", resp, content) <NEW_LINE> return self._error_redirect(3, end_point) <NEW_LINE> <DEDENT> request_token = oauth.Token.from_string(content) <NEW_LINE> req.session['token'] = content <NEW_LINE> req.session['end_point'] = end_point <NEW_LINE> req.session.save() <NEW_LINE> request = oauth.Request.from_token_and_callback(token=request_token, http_url=AUTHORIZE_URL) <NEW_LINE> return exc.HTTPFound(location=request.to_url()) <NEW_LINE> <DEDENT> def process(self, req): <NEW_LINE> <INDENT> end_point = req.session['end_point'] <NEW_LINE> request_token = oauth.Token.from_string(req.session['token']) <NEW_LINE> verifier = req.GET.get('oauth_verifier') <NEW_LINE> if not verifier: <NEW_LINE> <INDENT> return self._error_redirect(1, end_point) <NEW_LINE> <DEDENT> request_token.set_verifier(verifier) <NEW_LINE> client = oauth.Client(self._consumer, request_token) <NEW_LINE> resp, content = client.request(ACCESS_URL, "POST") <NEW_LINE> if resp['status'] != '200': <NEW_LINE> <INDENT> return self._error_redirect(2, end_point) <NEW_LINE> <DEDENT> access_token = dict(urlparse.parse_qsl(content)) <NEW_LINE> profile = {} <NEW_LINE> profile['providerName'] = 'Identica' <NEW_LINE> profile['displayName'] = access_token['screen_name'] <NEW_LINE> profile['identifier'] = 'http://identi.ca/%s' % access_token['user_id'] <NEW_LINE> result_data = {'status': 'ok', 'profile': profile} <NEW_LINE> cred = {'oauthAccessToken': access_token['oauth_token'], 'oauthAccessTokenSecret': access_token['oauth_token_secret']} <NEW_LINE> result_data['credentials'] = cred <NEW_LINE> return self._success_redirect(result_data, end_point) | Handle Identi.ca OAuth login/authentication | 62599040711fe17d825e15e2 |
class OWLObjectProperty(OWLObjectPropertyExpression, OWLProperty): <NEW_LINE> <INDENT> def __init__(self, iri_or_str): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> if isinstance(iri_or_str, str): <NEW_LINE> <INDENT> self.iri = URIRef(iri_or_str) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.iri = iri_or_str <NEW_LINE> <DEDENT> self.built_in = self.iri in { OWLRDFVocabulary.OWL_TOP_OBJECT_PROPERTY.iri, OWLRDFVocabulary.OWL_BOTTOM_OBJECT_PROPERTY.iri} <NEW_LINE> <DEDENT> def type_index(self): <NEW_LINE> <INDENT> return 1002 <NEW_LINE> <DEDENT> def hash_index(self): <NEW_LINE> <INDENT> return 293 <NEW_LINE> <DEDENT> def get_entity_type(self): <NEW_LINE> <INDENT> return EntityType.OBJECT_PROPERTY <NEW_LINE> <DEDENT> def get_named_property(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_owl_object_property(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def is_top_entity(self): <NEW_LINE> <INDENT> return self.is_owl_top_object_property() <NEW_LINE> <DEDENT> def is_bottom_entity(self): <NEW_LINE> <INDENT> return self.is_owl_bottom_object_property() <NEW_LINE> <DEDENT> def is_owl_top_object_property(self): <NEW_LINE> <INDENT> return self.iri == OWLRDFVocabulary.OWL_TOP_OBJECT_PROPERTY.iri <NEW_LINE> <DEDENT> def is_owl_bottom_object_property(self): <NEW_LINE> <INDENT> return self.iri == OWLRDFVocabulary.OWL_BOTTOM_OBJECT_PROPERTY.iri <NEW_LINE> <DEDENT> def accept(self, visior): <NEW_LINE> <INDENT> if isinstance(visior, OWLObjectVisitor) or isinstance(visior, OWLPropertyExpressionVisitor) or isinstance(visior, OWLEntityVisitor) or isinstance(visior, OWLNamedObjectVisitor): <NEW_LINE> <INDENT> visior.visit(self) <NEW_LINE> <DEDENT> elif isinstance(visior, OWLObjectVisitorEx) or isinstance(visior, OWLPropertyExpressionVisitorEx) or isinstance(visior, OWLEntityVisitorEx) or isinstance(visior, OWLNamedObjectVisitorEx): <NEW_LINE> <INDENT> return visior.visit(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super().accept(visior) <NEW_LINE> <DEDENT> <DEDENT> def to_string_id(self): <NEW_LINE> <INDENT> return str(self.iri) <NEW_LINE> <DEDENT> def is_built_in(self): <NEW_LINE> <INDENT> return self.built_in <NEW_LINE> <DEDENT> def get_inverse_property(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def components(self): <NEW_LINE> <INDENT> return (c for c in [self.iri]) <NEW_LINE> <DEDENT> def get_iri(self): <NEW_LINE> <INDENT> return self.iri | Represents an
<a href="http://www.w3.org/TR/owl2-syntax/#Object_Properties">Object Property</a>
in the OWL 2 Specification. | 62599040d164cc6175822202 |
class Interpreter(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.handleArguments(sys.argv) <NEW_LINE> <DEDENT> def handleArguments(self, argv): <NEW_LINE> <INDENT> if (argv[1] != "--ip" or argv[3] != "--port" or argv[5] != "--protocol") : <NEW_LINE> <INDENT> print("Call with: --ip <ip> --port <port> --protocol <protocol>") <NEW_LINE> print("<ip>: host ip address") <NEW_LINE> print("<port>: host port number") <NEW_LINE> print("<protocol>: tcp, udp, http") <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> self.host = "".join(sys.argv[2]) <NEW_LINE> self.port = int(sys.argv[4]) <NEW_LINE> self.protocol = "".join(sys.argv[6]) <NEW_LINE> <DEDENT> def getHost(self): <NEW_LINE> <INDENT> return self.host <NEW_LINE> <DEDENT> def getPort(self): <NEW_LINE> <INDENT> return self.port <NEW_LINE> <DEDENT> def getProtocol(self): <NEW_LINE> <INDENT> return self.protocol <NEW_LINE> <DEDENT> def isUdp(self): <NEW_LINE> <INDENT> if self.protocol == "udp": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def isTcp(self): <NEW_LINE> <INDENT> if self.protocol == "tcp": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def isHttp(self): <NEW_LINE> <INDENT> if self.protocol == "http": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Class Config | 62599040d99f1b3c44d06928 |
class CTD_ANON_80 (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = None <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('/Users/ethanwaldie/thesis/malmo/Schemas/MissionHandlers.xsd', 2154, 4) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __Block = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'Block'), 'Block', '__httpProjectMalmo_microsoft_com_CTD_ANON_80_httpProjectMalmo_microsoft_comBlock', True, pyxb.utils.utility.Location('/Users/ethanwaldie/thesis/malmo/Schemas/MissionHandlers.xsd', 2156, 8), ) <NEW_LINE> Block = property(__Block.value, __Block.set, None, None) <NEW_LINE> __dimension = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'dimension'), 'dimension', '__httpProjectMalmo_microsoft_com_CTD_ANON_80_dimension', _module_typeBindings.Dimension, unicode_default='0') <NEW_LINE> __dimension._DeclarationLocation = pyxb.utils.utility.Location('/Users/ethanwaldie/thesis/malmo/Schemas/MissionHandlers.xsd', 2059, 4) <NEW_LINE> __dimension._UseLocation = pyxb.utils.utility.Location('/Users/ethanwaldie/thesis/malmo/Schemas/MissionHandlers.xsd', 2059, 4) <NEW_LINE> dimension = property(__dimension.value, __dimension.set, None, None) <NEW_LINE> _ElementMap.update({ __Block.name() : __Block }) <NEW_LINE> _AttributeMap.update({ __dimension.name() : __dimension }) | Sends a rewards when an agent comes in contact with a specific block type. | 62599040d53ae8145f9196e8 |
class CreateCharacterResponseSchema(schema.ResponseSchema): <NEW_LINE> <INDENT> fields = { "CharacterId": fields.Str(required=True, load_from="CharacterId"), } | CreateCharacter - 创建角色 | 625990400a366e3fb87ddc71 |
class TaggedRelation: <NEW_LINE> <INDENT> def __init__(self, tag, head = -1, dep = -1): <NEW_LINE> <INDENT> self.tag = tag <NEW_LINE> self.head = head <NEW_LINE> self.dep = dep | Relation between two annotations that are identified by ordinal number. | 62599040c432627299fa4247 |
class SecurityVERIFYUnapprovedExecutableWithSetUIDCompareRPMs(TestCompareRPMs): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.after_rpm.add_installed_file( "/usr/bin/verify", rpmfluff.SourceFile("file", "a" * 5), mode="4755" ) <NEW_LINE> self.inspection = "permissions" <NEW_LINE> self.result = "VERIFY" <NEW_LINE> self.waiver_auth = "Security" | Assert when a setuid file is in a package and it's on the fileinfo list,
INFO result occurs when testing the RPMs. | 625990401d351010ab8f4da9 |
class Image(models.Model): <NEW_LINE> <INDENT> property = models.ForeignKey(Property) <NEW_LINE> imagetype = models.ForeignKey(ImageType, null=True, blank=True) <NEW_LINE> capture_date = models.DateField(null=True, blank=True) <NEW_LINE> webserver_layer = models.CharField(max_length=200, null=True, blank=True) <NEW_LINE> croptype = models.ForeignKey(CropType, null=True, blank=True) <NEW_LINE> flight_time = models.TimeField(null=True, blank=True) <NEW_LINE> resolution = models.IntegerField(max_length=10, null=True, blank=True) <NEW_LINE> aircraft = models.ForeignKey(AirCraft, null=True, blank=True) <NEW_LINE> camera = models.ForeignKey(Camera, null=True, blank=True) <NEW_LINE> image_processing_version = models.CharField(max_length=50, null=True, blank=True) <NEW_LINE> published_date = models.DateField(null=True, blank=True) <NEW_LINE> server = models.ForeignKey(Server, null=True, blank=True) <NEW_LINE> description = models.TextField(null=True, blank=True) <NEW_LINE> locked = models.NullBooleanField(default=False, null=True, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '%s' % (self.webserver_layer) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "Images" <NEW_LINE> db_table = "images" | Image object | 6259904023849d37ff852346 |
class ExpressionInitializationError(Exception): <NEW_LINE> <INDENT> pass | An exception used to indicate an error during initialization
of an expression. | 62599040d4950a0f3b111786 |
class Cell: <NEW_LINE> <INDENT> def __init__(self, store_type, obj_count=0): <NEW_LINE> <INDENT> self.store_type = store_type <NEW_LINE> self.count = obj_count <NEW_LINE> self.ids = set() <NEW_LINE> if self.store_type == StoreType.matrix: <NEW_LINE> <INDENT> size = range(self.count) <NEW_LINE> self.pairs = [[False for _ in size] for _ in size] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.pairs = set() <NEW_LINE> <DEDENT> <DEDENT> def add_pairs(self, bid): <NEW_LINE> <INDENT> if self.store_type == StoreType.matrix: <NEW_LINE> <INDENT> for bid2 in self.ids: <NEW_LINE> <INDENT> self.pairs[bid][bid2] = True <NEW_LINE> self.pairs[bid2][bid] = True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for bid2 in self.ids: <NEW_LINE> <INDENT> self.pairs.add((bid, bid2)) <NEW_LINE> self.pairs.add((bid2, bid)) <NEW_LINE> <DEDENT> <DEDENT> self.ids.add(bid) <NEW_LINE> <DEDENT> def remove_pairs(self, bid): <NEW_LINE> <INDENT> self.ids.discard(bid) <NEW_LINE> if self.store_type == StoreType.matrix: <NEW_LINE> <INDENT> for bid2 in self.ids: <NEW_LINE> <INDENT> self.pairs[bid][bid2] = False <NEW_LINE> self.pairs[bid2][bid] = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for bid2 in self.ids: <NEW_LINE> <INDENT> self.pairs.discard((bid, bid2)) <NEW_LINE> self.pairs.discard((bid2, bid)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.pairs) | This class represents single cell in grid (dense matrix).
It implements methods for adding and removing pairs. | 6259904063b5f9789fe863f8 |
class Hinge(Joint): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> for _s in [Joint]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{})) <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, Hinge, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> for _s in [Joint]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{})) <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, Hinge, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> if self.__class__ == Hinge: <NEW_LINE> <INDENT> _self = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _self = self <NEW_LINE> <DEDENT> this = _pynewton.new_Hinge(_self, *args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> def GetJointAngle(self): <NEW_LINE> <INDENT> return _pynewton.Hinge_GetJointAngle(self) <NEW_LINE> <DEDENT> def GetJointOmega(self): <NEW_LINE> <INDENT> return _pynewton.Hinge_GetJointOmega(self) <NEW_LINE> <DEDENT> def GetJointForce(self): <NEW_LINE> <INDENT> return _pynewton.Hinge_GetJointForce(self) <NEW_LINE> <DEDENT> def CalculateStopAlpha(self, *args): <NEW_LINE> <INDENT> return _pynewton.Hinge_CalculateStopAlpha(self, *args) <NEW_LINE> <DEDENT> def OnCallback(self, *args): <NEW_LINE> <INDENT> return _pynewton.Hinge_OnCallback(self, *args) <NEW_LINE> <DEDENT> __swig_destroy__ = _pynewton.delete_Hinge <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def __disown__(self): <NEW_LINE> <INDENT> self.this.disown() <NEW_LINE> _pynewton.disown_Hinge(self) <NEW_LINE> return weakref_proxy(self) | 1 | 62599040e76e3b2f99fd9c98 |
class TestIbzkpt(mytest.MyTestCase): <NEW_LINE> <INDENT> def test_example(self): <NEW_LINE> <INDENT> ibz_file = 'IBZKPT.example' <NEW_LINE> kpoints = Kpoints() <NEW_LINE> kpoints.from_file(vasp_dir=_rpath, ibz_filename=ibz_file) <NEW_LINE> testout = _rpath + 'IBZKPT.example.out.test' <NEW_LINE> with open(testout, 'w') as f: <NEW_LINE> <INDENT> writeline = lambda s: f.write(s + '\n') <NEW_LINE> writeline("nktot = %s"%(kpoints.nktot)) <NEW_LINE> writeline("ntet = %s"%(kpoints.ntet)) <NEW_LINE> writeline("volt = %s"%(kpoints.volt)) <NEW_LINE> writeline("kpts:\n%s"%(kpoints.kpts)) <NEW_LINE> writeline("tets:\n%s"%(kpoints.itet)) <NEW_LINE> <DEDENT> expected = _rpath + 'IBZKPT.example.out' <NEW_LINE> self.assertFileEqual(testout, expected) <NEW_LINE> <DEDENT> def test_notet(self): <NEW_LINE> <INDENT> ibz_file = 'IBZKPT.notet' <NEW_LINE> kpoints = Kpoints() <NEW_LINE> kpoints.from_file(vasp_dir=_rpath, ibz_filename=ibz_file) <NEW_LINE> testout = _rpath + 'IBZKPT.notet.out.test' <NEW_LINE> with open(testout, 'w') as f: <NEW_LINE> <INDENT> writeline = lambda s: f.write(s + '\n') <NEW_LINE> writeline("nktot = %s"%(kpoints.nktot)) <NEW_LINE> writeline("kpts:\n%s"%(kpoints.kpts)) <NEW_LINE> <DEDENT> expected = _rpath + 'IBZKPT.notet.out' <NEW_LINE> self.assertFileEqual(testout, expected) | Function:
def read_plocar(filename)
Scenarios:
- full IBZKPT file with tetrahedra
- partial IBZKPT file with k-points only | 6259904071ff763f4b5e8a2b |
class ShowSubnet(ShowCommand): <NEW_LINE> <INDENT> resource = 'subnet' <NEW_LINE> log = logging.getLogger(__name__ + '.ShowSubnet') <NEW_LINE> def add_known_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument( '--network_id', help='Neutron Netwotk Id') | Show information of a given OF Subnet. | 62599040e64d504609df9d17 |
class GaussianAndEpsilonStrategy(RawExplorationStrategy): <NEW_LINE> <INDENT> def __init__(self, action_space, epsilon, max_sigma=1.0, min_sigma=None, decay_period=1000000): <NEW_LINE> <INDENT> assert len(action_space.shape) == 1 <NEW_LINE> if min_sigma is None: <NEW_LINE> <INDENT> min_sigma = max_sigma <NEW_LINE> <DEDENT> self._max_sigma = max_sigma <NEW_LINE> self._epsilon = epsilon <NEW_LINE> self._min_sigma = min_sigma <NEW_LINE> self._decay_period = decay_period <NEW_LINE> self._action_space = action_space <NEW_LINE> <DEDENT> def get_action_from_raw_action(self, action, t=None, **kwargs): <NEW_LINE> <INDENT> if random.random() < self._epsilon: <NEW_LINE> <INDENT> return self._action_space.sample() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sigma = self._max_sigma - (self._max_sigma - self._min_sigma) * min(1.0, t * 1.0 / self._decay_period) <NEW_LINE> return np.clip( action + np.random.normal(size=len(action)) * sigma, self._action_space.low, self._action_space.high, ) | With probability epsilon, take a completely random action.
with probability 1-epsilon, add Gaussian noise to the action taken by a
deterministic policy. | 625990408c3a8732951f77e5 |
class GetRecentMeUrls(TLObject): <NEW_LINE> <INDENT> __slots__ = ["referer"] <NEW_LINE> ID = 0x3dc0f114 <NEW_LINE> QUALNAME = "functions.help.GetRecentMeUrls" <NEW_LINE> def __init__(self, *, referer: str): <NEW_LINE> <INDENT> self.referer = referer <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "GetRecentMeUrls": <NEW_LINE> <INDENT> referer = String.read(b) <NEW_LINE> return GetRecentMeUrls(referer=referer) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> b.write(String(self.referer)) <NEW_LINE> return b.getvalue() | Attributes:
LAYER: ``112``
Attributes:
ID: ``0x3dc0f114``
Parameters:
referer: ``str``
Returns:
:obj:`help.RecentMeUrls <pyrogram.api.types.help.RecentMeUrls>` | 62599040b57a9660fecd2d07 |
class Resource(base.Resource): <NEW_LINE> <INDENT> def update(self, new_domain=UNDEF, project=UNDEF, scope=UNDEF, availability_zone=UNDEF): <NEW_LINE> <INDENT> self._http.put(self._url_resource_path, self._id, data=utils.get_json_body( 'domain_entry', domain=new_domain, project=project, scope=scope, availability_zone=availability_zone)) <NEW_LINE> <DEDENT> def add_entry(self, name=None, ip=None, dns_type="A"): <NEW_LINE> <INDENT> self._http.put(self._url_resource_path, self._id, data=utils.get_json_body( 'domain_entry', domain=new_domain, project=project, scope=scope, availability_zone=availability_zone)) <NEW_LINE> <DEDENT> def remove_entry(self, name=None): <NEW_LINE> <INDENT> self._http.delete(self._url_resource_path, self._id, 'entries', name) <NEW_LINE> <DEDENT> def get_entry(self, ip=None): <NEW_LINE> <INDENT> ret = self._http.get(self._url_resource_path, self._id, 'entries', name) <NEW_LINE> return ret.get('dns_entries') | Resource class for floating IP DNS entries in Compute API v2 | 62599040507cdc57c63a6028 |
class MongoDB: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print('Connecting to the DB - {} {}.{}'.format(Config.host_DB, Config.DB_name, Config.DB_collection)) <NEW_LINE> self.client = pymongo.MongoClient(Config.host_DB) <NEW_LINE> self.db_name = self.client[Config.DB_name] <NEW_LINE> self.db_collection = self.db_name[Config.DB_collection] <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise Exception("Something went wrong during DB connection:{}".format(e)) <NEW_LINE> <DEDENT> <DEDENT> def fill_collections_to_db(self, collection_list): <NEW_LINE> <INDENT> container = Container() <NEW_LINE> try: <NEW_LINE> <INDENT> collection = self.db_collection <NEW_LINE> collection_list = [x for x in collection_list if (not self._is_collection_exist(x)) or container.is_valid_collection(x)] <NEW_LINE> if len(collection_list) > 0: <NEW_LINE> <INDENT> collection.insert_many(collection_list) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise Exception("Something went wrong during DB insertion:{}".format(e)) <NEW_LINE> <DEDENT> <DEDENT> def read_collections_from_db(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> temp = [] <NEW_LINE> collection = self.db_collection <NEW_LINE> temp.extend(collection.find()) <NEW_LINE> return temp <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise Exception("Something went wrong during DB reading:{}".format(e)) <NEW_LINE> <DEDENT> <DEDENT> def find_invalid_collections_from_db(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> collection = self.db_collection <NEW_LINE> temp = [x for x in collection.find({'is_valid': False})] <NEW_LINE> return temp <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise Exception("Something went wrong during DB reading:{}".format(e)) <NEW_LINE> <DEDENT> <DEDENT> def set_validity_for_collections(self, collection_list, bool_val): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> collection = self.db_collection <NEW_LINE> for i in collection_list: <NEW_LINE> <INDENT> if self._is_collection_exist(i): <NEW_LINE> <INDENT> collection.update_many({"sha": i['sha']}, {"$set": {"is_valid": bool_val}}) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise Exception("Something went wrong during value updating collections:{}".format(e)) <NEW_LINE> <DEDENT> <DEDENT> def _is_collection_exist(self, single_collection): <NEW_LINE> <INDENT> collection = self.db_collection <NEW_LINE> if collection.find({"sha": single_collection['sha']}).count() > 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Object initiator function | 6259904030c21e258be99a99 |
class ConfigurationStorage(storage.GenericAnnotationStorage): <NEW_LINE> <INDENT> grok.context(IStructuredItem) <NEW_LINE> grok.provides(storage.IStorage) <NEW_LINE> storage = AdapterAnnotationProperty( storage.IDictStorage['storage'], ns="sd.rendering.configuration" ) | Stores a configuration sheet onto the object in an annotation.
| 6259904076d4e153a661dbba |
class ModuleStoreEnum(object): <NEW_LINE> <INDENT> class Type(object): <NEW_LINE> <INDENT> split = 'split' <NEW_LINE> mongo = 'mongo' <NEW_LINE> xml = 'xml' <NEW_LINE> <DEDENT> class RevisionOption(object): <NEW_LINE> <INDENT> draft_preferred = 'rev-opt-draft-preferred' <NEW_LINE> draft_only = 'rev-opt-draft-only' <NEW_LINE> published_only = 'rev-opt-published-only' <NEW_LINE> all = 'rev-opt-all' <NEW_LINE> <DEDENT> class Branch(object): <NEW_LINE> <INDENT> draft_preferred = 'draft-preferred' <NEW_LINE> published_only = 'published-only' <NEW_LINE> <DEDENT> class BranchName(object): <NEW_LINE> <INDENT> draft = 'draft-branch' <NEW_LINE> published = 'published-branch' <NEW_LINE> <DEDENT> class UserID(object): <NEW_LINE> <INDENT> mgmt_command = -1 <NEW_LINE> primitive_command = -2 <NEW_LINE> test = -3 <NEW_LINE> <DEDENT> class SortOrder(object): <NEW_LINE> <INDENT> ascending = 1 <NEW_LINE> descending = 2 | A class to encapsulate common constants that are used with the various modulestores. | 62599040a79ad1619776b30c |
class Electronic(models.Model): <NEW_LINE> <INDENT> author = models.ForeignKey('auth.User', null=True, on_delete=models.DO_NOTHING) <NEW_LINE> edited_by = models.CharField(max_length=200, null=True) <NEW_LINE> type_component = models.ForeignKey('Type_Component', help_text="Type of the electronic component.", on_delete=models.DO_NOTHING) <NEW_LINE> name_component = models.CharField(max_length=200, blank=True) <NEW_LINE> location = models.ForeignKey('Location', help_text="Where it is the electronic component.", on_delete=models.DO_NOTHING) <NEW_LINE> unit = models.ForeignKey('Unit', help_text="Unit of the value of the electronic componente.", on_delete=models.DO_NOTHING) <NEW_LINE> value = models.CharField(max_length=200, blank=True, help_text="Value of the electronic component.") <NEW_LINE> created_date = models.DateTimeField(default=timezone.now, help_text="Date when was created.") <NEW_LINE> def create(self): <NEW_LINE> <INDENT> self.created_date = timezone.now() <NEW_LINE> self.save() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name_component | Electronic model docstring.
This model stores the electronic components. | 6259904007f4c71912bb06be |
class DummyEnv(gym.Env): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.episode_over = False <NEW_LINE> self.action_space = gym.spaces.Discrete(2) <NEW_LINE> self.state = np.zeros(3) <NEW_LINE> self.observation_space = self.state <NEW_LINE> self.reward_range = (-1, 1000) <NEW_LINE> self.start_state = 0 <NEW_LINE> self.goal_state = 10 <NEW_LINE> <DEDENT> def step(self, action): <NEW_LINE> <INDENT> if action == 0: <NEW_LINE> <INDENT> self.state[0] = max(self.start_state, self.state[0] - 1) <NEW_LINE> <DEDENT> elif action == 1: <NEW_LINE> <INDENT> self.state[0] = min(self.goal_state, self.state[0] + 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise("action not defined") <NEW_LINE> <DEDENT> episode_over = self.state[0] == self.goal_state <NEW_LINE> reward = self.reward_range[1] * int(self.state[0] == self.goal_state) <NEW_LINE> reward += self.reward_range[0] * np.random.random() <NEW_LINE> ob = self.state + 2 * np.random.random() - 1.0 <NEW_LINE> return ob, reward, episode_over, {} <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.state = np.zeros(3) <NEW_LINE> self.state[0] = self.start_state <NEW_LINE> return self.state <NEW_LINE> <DEDENT> def render(self, mode='human', close=False): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def seed(self, seed=None): <NEW_LINE> <INDENT> pass | DummyEnv - The simplest possible implementation of an OpenAI gym environment | 6259904015baa7234946321e |
class EnergyGoalSetting(ResourceGoalSetting): <NEW_LINE> <INDENT> pass | Energy goal settings. | 625990408da39b475be0447c |
class BillingTier(models.Model): <NEW_LINE> <INDENT> cost_to_operator_per_min = models.IntegerField(default=0) <NEW_LINE> cost_to_operator_per_sms = models.IntegerField(default=0) <NEW_LINE> cost_to_subscriber_per_min = models.IntegerField(default=0) <NEW_LINE> cost_to_subscriber_per_sms = models.IntegerField(default=0) <NEW_LINE> destination_group = models.ForeignKey('DestinationGroup', null=True, blank=True, on_delete=models.CASCADE) <NEW_LINE> choices = [(v, v) for v in ('on_network_receive', 'on_network_send', 'off_network_receive', 'off_network_send')] <NEW_LINE> directionality = models.TextField(choices=choices) <NEW_LINE> name = models.TextField(default='Billing Tier') <NEW_LINE> network = models.ForeignKey('Network', null=True, on_delete=models.CASCADE) <NEW_LINE> traffic_enabled = models.BooleanField(default=True) <NEW_LINE> billable_unit = models.IntegerField(default=1) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return ('BillingTier "%s" connected to Network "%s"' % (self.name, self.network)) | A network billing tier.
This is how we charge operators and allow operators to set prices for their
subscribers. All costs to operators are in millicents; all costs to
subscribers are in currency-agnostic "credits". Credits are always integer
values that, when combined with a currency code, can yield a useful value.
Each network will have seven associated billing tiers: four
off_network_send tiers, and one each of an off_network_receive,
on_network_send and on_network_receive tier. These four 'classes' of tiers
are captured in the 'directionality' attribute of the BillingTier.
Tiers map directly to DestinationGroups and operators can completely
disable connectivity to a DG via the traffic_enabled flag. | 6259904023e79379d538d78c |
class KeyError(Exception): <NEW_LINE> <INDENT> pass | Exception raise while input an error key.
| 62599040004d5f362081f92b |
class UserLoginViews(generics.GenericAPIView): <NEW_LINE> <INDENT> serializer_class = LoginSerializer <NEW_LINE> JWT_serializer_class = JWTSerializer <NEW_LINE> permission_classes = (AllowAny,) <NEW_LINE> @sensitive_post_parameters_m <NEW_LINE> def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(UserLoginViews, self).dispatch(*args, **kwargs) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> serializer = self.serializer_class(data=request.data, context={'request': request}) <NEW_LINE> if serializer.is_valid(raise_exception=True): <NEW_LINE> <INDENT> user = serializer.validated_data['user'] <NEW_LINE> token = jwt_encode(user) <NEW_LINE> login(request, user) <NEW_LINE> return Response( get_data_response(self.JWT_serializer_class, token, status.HTTP_200_OK), status=status.HTTP_201_CREATED ) | Endpoint For User Login. | 62599040711fe17d825e15e3 |
class GwyGraphModel_init(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.test_meta = {'ncurves': 2, 'title': 'Plot', 'top_label': 'Top label', 'left_label': 'Left label', 'right_label': 'Right label', 'bottom_label': 'Bottom label', 'x_unit': 'm', 'y_unit': 'm', 'x_min': 0., 'x_min_set': True, 'x_max': 1., 'x_max_set': True, 'y_min': None, 'y_min_set': False, 'y_max': None, 'y_max_set': False, 'x_is_logarithmic': False, 'y_is_logarithmic': False, 'label.visible': True, 'label.has_frame': True, 'label.reverse': False, 'label.frame_thickness': 1, 'label.position': 0, 'grid-type': 1} <NEW_LINE> self.test_curves = [Mock(spec=GwyGraphCurve), Mock(spec=GwyGraphCurve)] <NEW_LINE> <DEDENT> def test_init_with_curves_and_meta(self): <NEW_LINE> <INDENT> graph = GwyGraphModel(curves=self.test_curves, meta=self.test_meta) <NEW_LINE> self.assertEqual(graph.curves, self.test_curves) <NEW_LINE> self.assertDictEqual(graph.meta, self.test_meta) <NEW_LINE> <DEDENT> def test_init_with_curves_without_meta(self): <NEW_LINE> <INDENT> graph = GwyGraphModel(curves=self.test_curves) <NEW_LINE> self.assertEqual(graph.curves, self.test_curves) <NEW_LINE> self.assertDictEqual(graph.meta, {'ncurves': 2, 'title': '', 'top_label': '', 'left_label': '', 'right_label': '', 'bottom_label': '', 'x_unit': '', 'y_unit': '', 'x_min': None, 'x_min_set': False, 'x_max': None, 'x_max_set': False, 'y_min': None, 'y_min_set': False, 'y_max': None, 'y_max_set': False, 'x_is_logarithmic': False, 'y_is_logarithmic': False, 'label.visible': True, 'label.has_frame': True, 'label.reverse': False, 'label.frame_thickness': 1, 'label.position': 0, 'grid-type': 1}) <NEW_LINE> <DEDENT> def test_raise_TypeError_if_curve_is_not_GwyGraphCurve(self): <NEW_LINE> <INDENT> self.assertRaises(TypeError, GwyGraphModel, curves=np.random.rand(10)) <NEW_LINE> <DEDENT> def test_raise_ValueError_if_curves_number_and_ncurves_different(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, GwyGraphModel, curves=[Mock(GwyGraphCurve)], meta=self.test_meta) | Test constructor of GwyGraphModel class
| 62599040596a897236128ef5 |
class ResourceInformation(object): <NEW_LINE> <INDENT> def __init__(self, name: str, addresses: List[str]): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._addresses = addresses <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def addresses(self) -> List[str]: <NEW_LINE> <INDENT> return self._addresses | Class to hold information about a type of Resource. A resource could be a GPU, FPGA, etc.
The array of addresses are resource specific and its up to the user to interpret the address.
One example is GPUs, where the addresses would be the indices of the GPUs
.. versionadded:: 3.0.0
Parameters
----------
name : str
the name of the resource
addresses : list
an array of strings describing the addresses of the resource
Notes
-----
This API is evolving. | 625990408a43f66fc4bf341e |
class Item(Resource): <NEW_LINE> <INDENT> resource = "data/item" <NEW_LINE> def build_url(self, item, resource=resource): <NEW_LINE> <INDENT> url = super(Item, self).build_url(resource=self.resource) <NEW_LINE> return "%s/%s" % (url, item) | A Resource for a Diablo Item. See http://blizzard.github.io/d3-api-docs/#item-information/item-information-example | 62599040d53ae8145f9196ea |
class SetRadioText(Action): <NEW_LINE> <INDENT> def execute(self, instance): <NEW_LINE> <INDENT> index = self.evaluate_index(0) <NEW_LINE> value = self.evaluate_index(0) <NEW_LINE> instance.objectPlayer.set_text(index, value) | Set Radio button->Change text
Parameters:
0: Change text (EXPRESSION, ExpressionParameter)
1: Change text (EXPSTRING, ExpressionParameter) | 6259904076d4e153a661dbbb |
class FastGrrMessageList(rdf_structs.RDFProtoStruct): <NEW_LINE> <INDENT> type_description = type_info.TypeDescriptorSet( type_info.ProtoList(type_info.ProtoEmbedded( name="job", field_number=1, nested=StructGrrMessage)) ) | A Faster implementation of GrrMessageList. | 6259904024f1403a92686214 |
class MethodInstanceHop(object): <NEW_LINE> <INDENT> def __init__(self, part_name): <NEW_LINE> <INDENT> self._part_name = part_name <NEW_LINE> self._next_parts = [] <NEW_LINE> <DEDENT> def _append_next(self, next): <NEW_LINE> <INDENT> self._next_parts.append(next) <NEW_LINE> <DEDENT> def _get_next(self, name): <NEW_LINE> <INDENT> for it in self._next_parts: <NEW_LINE> <INDENT> if it._accept(name): <NEW_LINE> <INDENT> return it <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _get_all_next(self): <NEW_LINE> <INDENT> return self._next_parts <NEW_LINE> <DEDENT> def _accept(self, name): <NEW_LINE> <INDENT> return self._part_name.lower() == name.lower() <NEW_LINE> <DEDENT> def __getattribute__(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(MethodInstanceHop, self).__getattribute__(name) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> for next_part in self._next_parts: <NEW_LINE> <INDENT> if next_part._accept(name): <NEW_LINE> <INDENT> return next_part <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Method Instance Hop "%s" at 0x%08X>' % (self._part_name, id(self)) | 方法实例跳板
| 6259904023e79379d538d78e |
class UnstructuredGrid(PointSet): <NEW_LINE> <INDENT> def GetCellTypes(self): <NEW_LINE> <INDENT> if not self.VTKObject.GetCellTypesArray(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return vtkDataArrayToVTKArray( self.VTKObject.GetCellTypesArray(), self) <NEW_LINE> <DEDENT> def GetCellLocations(self): <NEW_LINE> <INDENT> if not self.VTKObject.GetCellLocationsArray(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return vtkDataArrayToVTKArray( self.VTKObject.GetCellLocationsArray(), self) <NEW_LINE> <DEDENT> def GetCells(self): <NEW_LINE> <INDENT> if not self.VTKObject.GetCells(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return vtkDataArrayToVTKArray( self.VTKObject.GetCells().GetData(), self) <NEW_LINE> <DEDENT> def SetCells(self, cellTypes, cellLocations, cells): <NEW_LINE> <INDENT> from ..util.vtkConstants import VTK_ID_TYPE <NEW_LINE> from ..vtkCommonDataModel import vtkCellArray <NEW_LINE> cellTypes = numpyTovtkDataArray(cellTypes) <NEW_LINE> cellLocations = numpyTovtkDataArray(cellLocations, array_type=VTK_ID_TYPE) <NEW_LINE> cells = numpyTovtkDataArray(cells, array_type=VTK_ID_TYPE) <NEW_LINE> ca = vtkCellArray() <NEW_LINE> ca.SetCells(cellTypes.GetNumberOfTuples(), cells) <NEW_LINE> self.VTKObject.SetCells(cellTypes, cellLocations, ca) <NEW_LINE> <DEDENT> CellTypes = property(GetCellTypes, None, None, "This property returns the types of cells.") <NEW_LINE> CellLocations = property(GetCellLocations, None, None, "This property returns the locations of cells.") <NEW_LINE> Cells = property(GetCells, None, None, "This property returns the connectivity of cells.") | This is a python friendly wrapper of a vtkUnstructuredGrid that defines
a few useful properties. | 6259904007f4c71912bb06c1 |
class PosixPipeInput(Vt100Input, PipeInput): <NEW_LINE> <INDENT> _id = 0 <NEW_LINE> def __init__(self, text: str = "") -> None: <NEW_LINE> <INDENT> self._r, self._w = os.pipe() <NEW_LINE> class Stdin: <NEW_LINE> <INDENT> encoding = "utf-8" <NEW_LINE> def isatty(stdin) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def fileno(stdin) -> int: <NEW_LINE> <INDENT> return self._r <NEW_LINE> <DEDENT> <DEDENT> super().__init__(cast(TextIO, Stdin())) <NEW_LINE> self.send_text(text) <NEW_LINE> self.__class__._id += 1 <NEW_LINE> self._id = self.__class__._id <NEW_LINE> <DEDENT> def send_bytes(self, data: bytes) -> None: <NEW_LINE> <INDENT> os.write(self._w, data) <NEW_LINE> <DEDENT> def send_text(self, data: str) -> None: <NEW_LINE> <INDENT> os.write(self._w, data.encode("utf-8")) <NEW_LINE> <DEDENT> def raw_mode(self) -> ContextManager[None]: <NEW_LINE> <INDENT> return DummyContext() <NEW_LINE> <DEDENT> def cooked_mode(self) -> ContextManager[None]: <NEW_LINE> <INDENT> return DummyContext() <NEW_LINE> <DEDENT> def close(self) -> None: <NEW_LINE> <INDENT> os.close(self._r) <NEW_LINE> os.close(self._w) <NEW_LINE> <DEDENT> def typeahead_hash(self) -> str: <NEW_LINE> <INDENT> return "pipe-input-%s" % (self._id,) | Input that is send through a pipe.
This is useful if we want to send the input programmatically into the
application. Mostly useful for unit testing.
Usage::
input = PosixPipeInput()
input.send_text('inputdata') | 62599040ec188e330fdf9b29 |
class Album(LogOwlModel): <NEW_LINE> <INDENT> title = models.CharField(max_length=255) <NEW_LINE> prefix = models.CharField(max_length=20, blank=True) <NEW_LINE> subtitle = models.CharField(blank=True, max_length=255) <NEW_LINE> slug = models.SlugField() <NEW_LINE> band = models.ForeignKey(Band, blank=True) <NEW_LINE> label = models.ForeignKey(Label, blank=True) <NEW_LINE> asin = models.CharField(max_length=14, blank=True) <NEW_LINE> release_date = models.DateField(blank=True, null=True) <NEW_LINE> cover = models.FileField(upload_to='albums', blank=True) <NEW_LINE> review = models.TextField(blank=True) <NEW_LINE> genre = models.ManyToManyField(Genre, blank=True) <NEW_LINE> is_ep = models.BooleanField(default=False) <NEW_LINE> is_compilation = models.BooleanField(default=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'music_albums' <NEW_LINE> ordering = ('title',) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return '%s' % self.full_title <NEW_LINE> <DEDENT> @permalink <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return ('music_album_detail', None, { 'slug': self.slug }) <NEW_LINE> <DEDENT> @property <NEW_LINE> def full_title(self): <NEW_LINE> <INDENT> return '%s %s' % (self.prefix, self.title) <NEW_LINE> <DEDENT> @property <NEW_LINE> def cover_url(self): <NEW_LINE> <INDENT> return '%s%s' % (settings.MEDIA_URL, self.cover) <NEW_LINE> <DEDENT> @property <NEW_LINE> def amazon_url(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return 'http://www.amazon.com/dp/%s/?%s' % (self.asin, settings.AMAZON_AFFILIATE_EXTENTION) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return 'http://www.amazon.com/dp/%s/' % self.asin | Album model | 6259904007d97122c4217f2f |
class SubprocessTimeoutTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self._path = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> <DEDENT> def test_normal_exec_no_timeout(self): <NEW_LINE> <INDENT> cmdline = "sleep 1; echo Done" <NEW_LINE> (return_code, output, err) = sub.run(cmdline, cwd=self._path, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, timeout=10) <NEW_LINE> self.assertEqual(0, return_code) <NEW_LINE> self.assertEqual("Done\n", output) <NEW_LINE> self.assertEqual(None, err) <NEW_LINE> <DEDENT> def test_exec_with_timeout(self): <NEW_LINE> <INDENT> cmdline = "sleep 100; echo Done" <NEW_LINE> (return_code, output, err) = sub.run(cmdline, cwd=self._path, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, timeout=1) <NEW_LINE> self.assertEqual(sub.E_TIMEOUT, return_code) <NEW_LINE> self.assertEqual("", output) <NEW_LINE> self.assertEqual(None, err) <NEW_LINE> <DEDENT> def test_exec_with_timeout_python_interpreter(self): <NEW_LINE> <INDENT> cmdline = "python -c \"while True: pass\"" <NEW_LINE> (return_code, output, err) = sub.run(cmdline, cwd=self._path, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, timeout=5) <NEW_LINE> self.assertEqual(sub.E_TIMEOUT, return_code) <NEW_LINE> self.assertEqual("", output) <NEW_LINE> self.assertEqual(None, err) | Test the support for execution of programs with timeouts | 625990401d351010ab8f4dad |
class VesperRpgSystem(Thread): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> while rpg_const.SYSTEM_ACTIVE: <NEW_LINE> <INDENT> RpgTick.all_tock() <NEW_LINE> time.sleep(1 / rpg_const.FPS_MAX) | Class to manage the continuous processing of VesperRpg System in a separate
thread. | 6259904073bcbd0ca4bcb51b |
class Encryption(base.LibvirtXMLBase): <NEW_LINE> <INDENT> __slots__ = ('format', 'secret') <NEW_LINE> def __init__(self, virsh_instance=base.virsh): <NEW_LINE> <INDENT> accessors.XMLAttribute('format', self, parent_xpath='/', tag_name='encryption', attribute='format') <NEW_LINE> accessors.XMLElementDict('secret', self, parent_xpath='/', tag_name='secret') <NEW_LINE> super(VolXML.Encryption, self).__init__(virsh_instance=virsh_instance) <NEW_LINE> self.xml = '<encryption/>' | Encryption volume XML class
Properties:
format:
string.
secret:
dict, keys: type, uuid | 625990401d351010ab8f4dae |
class AddFields(logging.Filter): <NEW_LINE> <INDENT> def __init__(self, attribute_name, thread_local_field_names, constant_field_values): <NEW_LINE> <INDENT> self.attribute_name = attribute_name <NEW_LINE> self.thread_local_field_names = thread_local_field_names <NEW_LINE> self.constant_field_values = constant_field_values <NEW_LINE> <DEDENT> def filter(self, record): <NEW_LINE> <INDENT> values = threading.local() <NEW_LINE> if self.attribute_name: <NEW_LINE> <INDENT> values = getattr(values, self.attribute_name) <NEW_LINE> <DEDENT> for local_field_name, logging_field_name in self.thread_local_field_names.iteritems(): <NEW_LINE> <INDENT> if hasattr(values, local_field_name): <NEW_LINE> <INDENT> record.setattr(record, logging_field_name, getattr(values,local_field_name)) <NEW_LINE> <DEDENT> elif isinstance(values, dict) and local_field_name in values: <NEW_LINE> <INDENT> record.setattr(record, logging_field_name, values[local_field_name]) <NEW_LINE> <DEDENT> <DEDENT> for key,value in self.constant_field_values.iteritems(): <NEW_LINE> <INDENT> setattr(record,key,value) | add custom fields to messages for graypy to forward to graylog
if the values are constant, can may be added as a dictionary when the filter is created.
if they change, the values can be copied form thread-local fields with the given names.
NOTE: graypy will automatically also add: function, pid, process_name, thread_name | 6259904029b78933be26aa0b |
class SetReference(Reference): <NEW_LINE> <INDENT> def __init__(self, element, location=None): <NEW_LINE> <INDENT> super(SetReference, self).__init__(None, location=location) <NEW_LINE> self.element = reference(element) <NEW_LINE> self._init_type() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<SetReference %s>' % self.element <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'set<%s>' % self.element <NEW_LINE> <DEDENT> def _init_type(self): <NEW_LINE> <INDENT> if not self.element: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._type = pdefc.lang.collects.Set(self.element.dereference(), location=self.location) <NEW_LINE> <DEDENT> def link(self, lookup): <NEW_LINE> <INDENT> logging.debug('Linking %s', self) <NEW_LINE> errors = self.element.link(lookup) <NEW_LINE> if errors: <NEW_LINE> <INDENT> return errors <NEW_LINE> <DEDENT> self._init_type() <NEW_LINE> return [] <NEW_LINE> <DEDENT> def _validate(self): <NEW_LINE> <INDENT> logging.debug('Validating %s', self) <NEW_LINE> if not self._type: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return self._type.validate() <NEW_LINE> <DEDENT> @property <NEW_LINE> def referenced_types(self): <NEW_LINE> <INDENT> result = super(SetReference, self).referenced_types <NEW_LINE> result += self.element.referenced_types <NEW_LINE> return result | SetReference has a child for an element, creates a set on linking. | 62599040d53ae8145f9196ed |
class Model(Shape): <NEW_LINE> <INDENT> def __init__(self, camera=None, light=None, file_string=None, name="", x=0.0, y=0.0, z=0.0, rx=0.0, ry=0.0, rz=0.0, sx=1.0, sy=1.0, sz=1.0, cx=0.0, cy=0.0, cz=0.0): <NEW_LINE> <INDENT> super(Model, self).__init__(camera, light, name, x, y, z, rx, ry, rz, sx, sy, sz, cx, cy, cz) <NEW_LINE> if '__clone__' in file_string: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.exf = file_string[-3:].lower() <NEW_LINE> if VERBOSE: <NEW_LINE> <INDENT> print("Loading ",file_string) <NEW_LINE> <DEDENT> if self.exf == 'egg': <NEW_LINE> <INDENT> self.model = loaderEgg.loadFileEGG(self, file_string) <NEW_LINE> <DEDENT> elif self.exf == 'obj': <NEW_LINE> <INDENT> self.model = loaderObj.loadFileOBJ(self, file_string) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(self.exf, "file not supported") <NEW_LINE> <DEDENT> <DEDENT> def clone(self, camera = None, light = None): <NEW_LINE> <INDENT> newModel = Model(file_string = "__clone__", x=self.unif[0], y=self.unif[1], z=self.unif[2], rx=self.unif[3], ry=self.unif[4], rz=self.unif[5], sx=self.unif[6], sy=self.unif[7], sz=self.unif[8], cx=self.unif[9], cy=self.unif[10], cz=self.unif[11]) <NEW_LINE> newModel.buf = self.buf <NEW_LINE> newModel.vGroup = self.vGroup <NEW_LINE> newModel.shader = self.shader <NEW_LINE> newModel.textures = self.textures <NEW_LINE> return newModel <NEW_LINE> <DEDENT> def reparentTo(self, parent): <NEW_LINE> <INDENT> pass | 3d model inherits from Shape
loads vertex, normal, uv, index, texture and material data from obj or egg files
at the moment it doesn't fully implement the features such as animation,
reflectivity etc | 6259904045492302aabfd76b |
class Alarm(AWSObject): <NEW_LINE> <INDENT> resource_type = "AWS::CloudWatch::Alarm" <NEW_LINE> props: PropsDictType = { "ActionsEnabled": (boolean, False), "AlarmActions": ([str], False), "AlarmDescription": (str, False), "AlarmName": (str, False), "ComparisonOperator": (str, True), "DatapointsToAlarm": (integer, False), "Dimensions": ([MetricDimension], False), "EvaluateLowSampleCountPercentile": (str, False), "EvaluationPeriods": (integer, True), "ExtendedStatistic": (str, False), "InsufficientDataActions": ([str], False), "MetricName": (str, False), "Metrics": ([MetricDataQuery], False), "Namespace": (str, False), "OKActions": ([str], False), "Period": (integer, False), "Statistic": (str, False), "Threshold": (double, False), "ThresholdMetricId": (str, False), "TreatMissingData": (validate_treat_missing_data, False), "Unit": (str, False), } <NEW_LINE> def validate(self): <NEW_LINE> <INDENT> validate_alarm(self) | `Alarm <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html>`__ | 625990408e05c05ec3f6f7a3 |
class LEDDownBlock(nn.Layer): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels, correct_size_mismatch, bn_eps, data_format="channels_last", **kwargs): <NEW_LINE> <INDENT> super(LEDDownBlock, self).__init__(**kwargs) <NEW_LINE> self.correct_size_mismatch = correct_size_mismatch <NEW_LINE> self.data_format = data_format <NEW_LINE> self.axis = get_channel_axis(data_format) <NEW_LINE> self.pool = MaxPool2d( pool_size=2, strides=2, data_format=data_format, name="pool") <NEW_LINE> self.conv = conv3x3( in_channels=in_channels, out_channels=(out_channels - in_channels), strides=2, use_bias=True, data_format=data_format, name="conv") <NEW_LINE> self.norm_activ = NormActivation( in_channels=out_channels, bn_eps=bn_eps, data_format=data_format, name="norm_activ") <NEW_LINE> <DEDENT> def call(self, x, training=None): <NEW_LINE> <INDENT> y1 = self.pool(x) <NEW_LINE> y2 = self.conv(x) <NEW_LINE> if self.correct_size_mismatch: <NEW_LINE> <INDENT> if self.data_format == "channels_last": <NEW_LINE> <INDENT> diff_h = y2.size()[1] - y1.size()[1] <NEW_LINE> diff_w = y2.size()[2] - y1.size()[2] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> diff_h = y2.size()[2] - y1.size()[2] <NEW_LINE> diff_w = y2.size()[3] - y1.size()[3] <NEW_LINE> <DEDENT> y1 = nn.ZeroPadding2D( padding=((diff_w // 2, diff_w - diff_w // 2), (diff_h // 2, diff_h - diff_h // 2)), data_format=self.data_format)(y1) <NEW_LINE> <DEDENT> x = tf.concat([y2, y1], axis=self.axis) <NEW_LINE> x = self.norm_activ(x, training=training) <NEW_LINE> return x | LEDNet specific downscale block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
correct_size_mistmatch : bool
Whether to correct downscaled sizes of images.
bn_eps : float
Small float added to variance in Batch norm.
data_format : str, default 'channels_last'
The ordering of the dimensions in tensors. | 62599040507cdc57c63a602c |
class RealChange(NamedTuple): <NEW_LINE> <INDENT> id_code: str <NEW_LINE> value: float | Real value (floating point) change descriptor. | 625990408e71fb1e983bcd5e |
class SelectionFrame(tk.Frame): <NEW_LINE> <INDENT> def __init__(self,master,data,plot): <NEW_LINE> <INDENT> super().__init__(master) <NEW_LINE> self._master = master <NEW_LINE> self._stationselect = tk.Label(master,text="Station Selection: ") <NEW_LINE> self._stationselect.pack(side=tk.LEFT,anchor=tk.SW, pady = 20) <NEW_LINE> self._data = data <NEW_LINE> self._plotter = plot <NEW_LINE> self._chk = "" <NEW_LINE> <DEDENT> def checkbutton(self,station,colour,i): <NEW_LINE> <INDENT> self._chk = tk.Checkbutton(self._master, text=station,fg=colour, command = lambda: self.toggle(i)) <NEW_LINE> self._chk.select() <NEW_LINE> self._chk.pack(side=tk.LEFT,anchor=tk.SW, pady = 20) <NEW_LINE> <DEDENT> def toggle(self,i): <NEW_LINE> <INDENT> self._data.toggle_selected(i) <NEW_LINE> self._plotter.redraw() | This class inherits from tkinter Frame class
It holds the checkbuttons responsible for toggling
each station's Boolean value | 6259904007d97122c4217f30 |
class Weather : <NEW_LINE> <INDENT> def __init__(self,id,url) : <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.id = id <NEW_LINE> self.refresh() <NEW_LINE> <DEDENT> def refresh(self) : <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> page = urllib.urlopen(self.url) <NEW_LINE> report = page.readline() <NEW_LINE> data = report.split(" ") <NEW_LINE> self.baro = float(data[6]) <NEW_LINE> self.ts = time.time() <NEW_LINE> self.updated = True <NEW_LINE> <DEDENT> except Exception : <NEW_LINE> <INDENT> self.updated = False | cut down version just for the barometer mock | 6259904050485f2cf55dc215 |
class SBS_COMMAND_BQ_TURBO(DecoratedEnum): <NEW_LINE> <INDENT> TURBO_POWER = 0x59 <NEW_LINE> TURBO_FINAL = 0x5a <NEW_LINE> TURBO_PACK_R = 0x5b <NEW_LINE> TURBO_SYS_R = 0x5c <NEW_LINE> TURBO_EDV = 0x5d <NEW_LINE> TURBO_CURRENT = 0x5e | Commands used in BQ family SBS chips which support TURBO mode
| 62599040a4f1c619b294f7d0 |
class MySensorsBinarySensor(mysensors.device.MySensorsEntity, BinarySensorEntity): <NEW_LINE> <INDENT> @property <NEW_LINE> def is_on(self) -> bool: <NEW_LINE> <INDENT> return self._values.get(self.value_type) == STATE_ON <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_class(self) -> str | None: <NEW_LINE> <INDENT> pres = self.gateway.const.Presentation <NEW_LINE> device_class = SENSORS.get(pres(self.child_type).name) <NEW_LINE> if device_class in DEVICE_CLASSES: <NEW_LINE> <INDENT> return device_class <NEW_LINE> <DEDENT> return None | Representation of a MySensors Binary Sensor child node. | 625990401f5feb6acb163e85 |
class NullRegister(Register): <NEW_LINE> <INDENT> def write(self, val): <NEW_LINE> <INDENT> pass | Supports read and write, but always returns 0. | 625990408a349b6b436874d9 |
class Get_revit_elements: <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_elems_by_category(cls, category_class, active_view=None, name=None): <NEW_LINE> <INDENT> if not active_view: <NEW_LINE> <INDENT> els = FilteredElementCollector(doc).OfClass(category_class). ToElements() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> els = FilteredElementCollector(doc, active_view). OfClass(category_class).ToElements() <NEW_LINE> <DEDENT> if name: <NEW_LINE> <INDENT> els = [i for i in els if name in i.Name] <NEW_LINE> <DEDENT> return els <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_elems_by_builtinCategory(cls, built_in_cat=None, include=[], active_view=None): <NEW_LINE> <INDENT> if not include: <NEW_LINE> <INDENT> if not active_view: <NEW_LINE> <INDENT> els = FilteredElementCollector(doc).OfCategory(built_in_cat) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> els = FilteredElementCollector(doc, active_view). OfCategory(built_in_cat) <NEW_LINE> <DEDENT> return els.ToElements() <NEW_LINE> <DEDENT> if include: <NEW_LINE> <INDENT> new_list = [] <NEW_LINE> for i in include: <NEW_LINE> <INDENT> if not active_view: <NEW_LINE> <INDENT> els = FilteredElementCollector(doc).OfCategory(built_in_cat) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> els = FilteredElementCollector(doc, active_view). OfCategory(built_in_cat) <NEW_LINE> <DEDENT> new_list += els.ToElements() <NEW_LINE> <DEDENT> return new_list | Класс для поиска элементов в Revit. | 6259904015baa72349463223 |
class EventObjectQueueProducer(QueueProducer): <NEW_LINE> <INDENT> def ProduceEventObject(self, event_object): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._queue.PushItem(event_object) <NEW_LINE> <DEDENT> except ValueError as exception: <NEW_LINE> <INDENT> logging.error(( u'Unable to produce a serialized event object with ' u'error: {0:s}').format(exception)) <NEW_LINE> <DEDENT> <DEDENT> def ProduceEventObjects(self, event_objects): <NEW_LINE> <INDENT> for event_object in event_objects: <NEW_LINE> <INDENT> self.ProduceEventObject(event_object) | Class that implements the event object queue producer.
The producer generates updates on the queue. | 6259904050485f2cf55dc216 |
class NtdtestFoldingGetIterMixedKeyTd(NetAppObject): <NEW_LINE> <INDENT> _key_2 = None <NEW_LINE> @property <NEW_LINE> def key_2(self): <NEW_LINE> <INDENT> return self._key_2 <NEW_LINE> <DEDENT> @key_2.setter <NEW_LINE> def key_2(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('key_2', val) <NEW_LINE> <DEDENT> self._key_2 = val <NEW_LINE> <DEDENT> _key_1 = None <NEW_LINE> @property <NEW_LINE> def key_1(self): <NEW_LINE> <INDENT> return self._key_1 <NEW_LINE> <DEDENT> @key_1.setter <NEW_LINE> def key_1(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('key_1', val) <NEW_LINE> <DEDENT> self._key_1 = val <NEW_LINE> <DEDENT> _key_0 = None <NEW_LINE> @property <NEW_LINE> def key_0(self): <NEW_LINE> <INDENT> return self._key_0 <NEW_LINE> <DEDENT> @key_0.setter <NEW_LINE> def key_0(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('key_0', val) <NEW_LINE> <DEDENT> self._key_0 = val <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_api_name(): <NEW_LINE> <INDENT> return "ntdtest-folding-get-iter-mixed-key-td" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_desired_attrs(): <NEW_LINE> <INDENT> return [ 'key-2', 'key-1', 'key-0', ] <NEW_LINE> <DEDENT> def describe_properties(self): <NEW_LINE> <INDENT> return { 'key_2': { 'class': basestring, 'is_list': False, 'required': 'optional' }, 'key_1': { 'class': basestring, 'is_list': False, 'required': 'optional' }, 'key_0': { 'class': basestring, 'is_list': False, 'required': 'optional' }, } | Key typedef for table ntdtest_folding | 6259904073bcbd0ca4bcb51d |
class ModificationDateTimeField(CreationDateTimeField): <NEW_LINE> <INDENT> def pre_save(self, model, add): <NEW_LINE> <INDENT> value = datetime.datetime.now() <NEW_LINE> setattr(model, self.attname, value) <NEW_LINE> return value <NEW_LINE> <DEDENT> def get_internal_type(self): <NEW_LINE> <INDENT> return "DateTimeField" | ModificationDateTimeField
By default, sets editable=False, blank=True, default=datetime.now
Sets value to datetime.now() on each save of the model. | 6259904071ff763f4b5e8a31 |
@dns.immutable.immutable <NEW_LINE> class ZONEMD(dns.rdata.Rdata): <NEW_LINE> <INDENT> __slots__ = ['serial', 'scheme', 'hash_algorithm', 'digest'] <NEW_LINE> def __init__(self, rdclass, rdtype, serial, scheme, hash_algorithm, digest): <NEW_LINE> <INDENT> super().__init__(rdclass, rdtype) <NEW_LINE> self.serial = self._as_uint32(serial) <NEW_LINE> self.scheme = dns.zone.DigestScheme.make(scheme) <NEW_LINE> self.hash_algorithm = dns.zone.DigestHashAlgorithm.make(hash_algorithm) <NEW_LINE> self.digest = self._as_bytes(digest) <NEW_LINE> if self.scheme == 0: <NEW_LINE> <INDENT> raise ValueError('scheme 0 is reserved') <NEW_LINE> <DEDENT> if self.hash_algorithm == 0: <NEW_LINE> <INDENT> raise ValueError('hash_algorithm 0 is reserved') <NEW_LINE> <DEDENT> hasher = dns.zone._digest_hashers.get(self.hash_algorithm) <NEW_LINE> if hasher and hasher().digest_size != len(self.digest): <NEW_LINE> <INDENT> raise ValueError('digest length inconsistent with hash algorithm') <NEW_LINE> <DEDENT> <DEDENT> def to_text(self, origin=None, relativize=True, **kw): <NEW_LINE> <INDENT> kw = kw.copy() <NEW_LINE> chunksize = kw.pop('chunksize', 128) <NEW_LINE> return '%d %d %d %s' % (self.serial, self.scheme, self.hash_algorithm, dns.rdata._hexify(self.digest, chunksize=chunksize, **kw)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None): <NEW_LINE> <INDENT> serial = tok.get_uint32() <NEW_LINE> scheme = tok.get_uint8() <NEW_LINE> hash_algorithm = tok.get_uint8() <NEW_LINE> digest = tok.concatenate_remaining_identifiers().encode() <NEW_LINE> digest = binascii.unhexlify(digest) <NEW_LINE> return cls(rdclass, rdtype, serial, scheme, hash_algorithm, digest) <NEW_LINE> <DEDENT> def _to_wire(self, file, compress=None, origin=None, canonicalize=False): <NEW_LINE> <INDENT> header = struct.pack("!IBB", self.serial, self.scheme, self.hash_algorithm) <NEW_LINE> file.write(header) <NEW_LINE> file.write(self.digest) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): <NEW_LINE> <INDENT> header = parser.get_struct("!IBB") <NEW_LINE> digest = parser.get_remaining() <NEW_LINE> return cls(rdclass, rdtype, header[0], header[1], header[2], digest) | ZONEMD record | 625990406e29344779b018e4 |
class AnalogPotentiometer(LiveWindowSendable): <NEW_LINE> <INDENT> def __init__(self, channel, fullRange=1.0, offset=0.0): <NEW_LINE> <INDENT> if not hasattr(channel, "getVoltage"): <NEW_LINE> <INDENT> channel = AnalogInput(channel) <NEW_LINE> <DEDENT> self.analog_input = channel <NEW_LINE> self.fullRange = fullRange <NEW_LINE> self.offset = offset <NEW_LINE> self.init_analog_input = True <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> return (self.analog_input.getVoltage() / hal.getUserVoltage5V()) * self.fullRange + self.offset <NEW_LINE> <DEDENT> def pidGet(self): <NEW_LINE> <INDENT> return self.get() <NEW_LINE> <DEDENT> def getSmartDashboardType(self): <NEW_LINE> <INDENT> return "Analog Input" <NEW_LINE> <DEDENT> def updateTable(self): <NEW_LINE> <INDENT> table = self.getTable() <NEW_LINE> if table is not None: <NEW_LINE> <INDENT> table.putNumber("Value", self.get()) <NEW_LINE> <DEDENT> <DEDENT> def startLiveWindowMode(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def stopLiveWindowMode(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def free(self): <NEW_LINE> <INDENT> if self.init_analog_input: <NEW_LINE> <INDENT> self.analog_input.free() <NEW_LINE> del self.analog_input <NEW_LINE> self.init_analog_input = False | Reads a potentiometer via an :class:`.AnalogInput`
Analog potentiometers read
in an analog voltage that corresponds to a position. The position is in
whichever units you choose, by way of the scaling and offset constants
passed to the constructor.
.. not_implemented: initPot | 6259904029b78933be26aa0c |
class Spider(object): <NEW_LINE> <INDENT> page_loader = loader.Loader() <NEW_LINE> links_parser = parser.LinksParser() <NEW_LINE> use_existing = True <NEW_LINE> def __init__(self, ldr=None, links_parser=None): <NEW_LINE> <INDENT> if not ldr is None: <NEW_LINE> <INDENT> self.page_loader = ldr <NEW_LINE> <DEDENT> if not links_parser is None: <NEW_LINE> <INDENT> self.links_parser = links_parser <NEW_LINE> <DEDENT> <DEDENT> def crawl_on_page(self, page): <NEW_LINE> <INDENT> if self.use_existing and page.isloaded(): <NEW_LINE> <INDENT> loading = page.get_last_successful_loading() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start_time = datetime.datetime.utcnow() <NEW_LINE> load_result = self.page_loader.load(page.url) <NEW_LINE> loading = models.Loading() <NEW_LINE> loading.page = page <NEW_LINE> loading.success = not load_result is None <NEW_LINE> loading.headers = dict(getattr(load_result, "headers", {})) <NEW_LINE> loading.content = getattr(load_result, "body", "") <NEW_LINE> loading.time = start_time <NEW_LINE> loading.loading_time = (datetime.datetime.utcnow() - start_time).total_seconds() <NEW_LINE> <DEDENT> if len(loading.content): <NEW_LINE> <INDENT> links = self.links_parser.parse(loading) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> links = None <NEW_LINE> <DEDENT> return loading, links | Gets page content, parses it for new links.
If use_existing is True then if content is already loaded
it will be parsed, not loaded again. | 6259904045492302aabfd76d |
class Solution: <NEW_LINE> <INDENT> def kClosest(self, points, origin, k): <NEW_LINE> <INDENT> return sorted(points, key=lambda p: ((p.x - origin.x)**2 + (p.y - origin.y)**2, p.x, p.y))[:k] | @param points: a list of points
@param origin: a point
@param k: An integer
@return: the k closest points | 6259904030c21e258be99aa0 |
class BufferCopyRequest(Request): <NEW_LINE> <INDENT> request_id = RequestId.BUFFER_GENERATE <NEW_LINE> def __init__( self, frame_count=None, source_buffer_id=None, source_starting_frame=None, target_buffer_id=None, target_starting_frame=None, ): <NEW_LINE> <INDENT> Request.__init__(self) <NEW_LINE> self._source_buffer_id = int(source_buffer_id) <NEW_LINE> self._target_buffer_id = int(target_buffer_id) <NEW_LINE> if frame_count is not None: <NEW_LINE> <INDENT> frame_count = int(frame_count) <NEW_LINE> assert -1 <= frame_count <NEW_LINE> <DEDENT> self._frame_count = frame_count <NEW_LINE> if source_starting_frame is not None: <NEW_LINE> <INDENT> source_starting_frame = int(source_starting_frame) <NEW_LINE> assert 0 <= source_starting_frame <NEW_LINE> <DEDENT> self._source_starting_frame = source_starting_frame <NEW_LINE> if target_starting_frame is not None: <NEW_LINE> <INDENT> target_starting_frame = int(target_starting_frame) <NEW_LINE> assert 0 <= target_starting_frame <NEW_LINE> <DEDENT> self._target_starting_frame = target_starting_frame <NEW_LINE> <DEDENT> def to_osc(self, *, with_placeholders=False): <NEW_LINE> <INDENT> request_id = self.request_name <NEW_LINE> frame_count = self.frame_count <NEW_LINE> if frame_count is None: <NEW_LINE> <INDENT> frame_count = -1 <NEW_LINE> <DEDENT> source_starting_frame = self.source_starting_frame <NEW_LINE> if source_starting_frame is None: <NEW_LINE> <INDENT> source_starting_frame = 0 <NEW_LINE> <DEDENT> target_starting_frame = self.target_starting_frame <NEW_LINE> if target_starting_frame is None: <NEW_LINE> <INDENT> target_starting_frame = 0 <NEW_LINE> <DEDENT> contents = [ request_id, self.target_buffer_id, "copy", target_starting_frame, self.source_buffer_id, source_starting_frame, frame_count, ] <NEW_LINE> message = supriya.osc.OscMessage(*contents) <NEW_LINE> return message <NEW_LINE> <DEDENT> @property <NEW_LINE> def frame_count(self): <NEW_LINE> <INDENT> return self._frame_count <NEW_LINE> <DEDENT> @property <NEW_LINE> def response_patterns(self): <NEW_LINE> <INDENT> return ["/done", "/b_gen", self.target_buffer_id], None <NEW_LINE> <DEDENT> @property <NEW_LINE> def source_buffer_id(self): <NEW_LINE> <INDENT> return self._source_buffer_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def source_starting_frame(self): <NEW_LINE> <INDENT> return self._source_starting_frame <NEW_LINE> <DEDENT> @property <NEW_LINE> def target_buffer_id(self): <NEW_LINE> <INDENT> return self._target_buffer_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def target_starting_frame(self): <NEW_LINE> <INDENT> return self._target_starting_frame | A `/b_gen copy` request.
::
>>> import supriya.commands
>>> request = supriya.commands.BufferCopyRequest(
... source_buffer_id=23,
... target_buffer_id=666,
... )
>>> print(request)
BufferCopyRequest(
source_buffer_id=23,
target_buffer_id=666,
)
::
>>> request.to_osc()
OscMessage('/b_gen', 666, 'copy', 0, 23, 0, -1) | 62599040287bf620b6272e79 |
@dataclasses.dataclass <NEW_LINE> class TestSuites: <NEW_LINE> <INDENT> name: t.Optional[str] = None <NEW_LINE> suites: t.List[TestSuite] = dataclasses.field(default_factory=list) <NEW_LINE> @property <NEW_LINE> def disabled(self) -> int: <NEW_LINE> <INDENT> return sum(suite.disabled for suite in self.suites) <NEW_LINE> <DEDENT> @property <NEW_LINE> def errors(self) -> int: <NEW_LINE> <INDENT> return sum(suite.errors for suite in self.suites) <NEW_LINE> <DEDENT> @property <NEW_LINE> def failures(self) -> int: <NEW_LINE> <INDENT> return sum(suite.failures for suite in self.suites) <NEW_LINE> <DEDENT> @property <NEW_LINE> def tests(self) -> int: <NEW_LINE> <INDENT> return sum(suite.tests for suite in self.suites) <NEW_LINE> <DEDENT> @property <NEW_LINE> def time(self) -> decimal.Decimal: <NEW_LINE> <INDENT> return t.cast(decimal.Decimal, sum(suite.time for suite in self.suites)) <NEW_LINE> <DEDENT> def get_attributes(self) -> t.Dict[str, str]: <NEW_LINE> <INDENT> return _attributes( disabled=self.disabled, errors=self.errors, failures=self.failures, name=self.name, tests=self.tests, time=self.time, ) <NEW_LINE> <DEDENT> def get_xml_element(self) -> ET.Element: <NEW_LINE> <INDENT> element = ET.Element('testsuites', self.get_attributes()) <NEW_LINE> element.extend([suite.get_xml_element() for suite in self.suites]) <NEW_LINE> return element <NEW_LINE> <DEDENT> def to_pretty_xml(self) -> str: <NEW_LINE> <INDENT> return _pretty_xml(self.get_xml_element()) | A collection of test suites. | 6259904024f1403a92686216 |
class StatusDisplay: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.preText = '' <NEW_LINE> self.percentage = 0.0 <NEW_LINE> self.overwriteLine = False <NEW_LINE> self.silent = False <NEW_LINE> self.percentFormat = '% 5.1f' <NEW_LINE> self.textLength = 0 <NEW_LINE> <DEDENT> def display_percentage(self, text, percent=0.0, format='% 5.1f'): <NEW_LINE> <INDENT> import sys <NEW_LINE> self.overwriteLine = True <NEW_LINE> self.preText = text <NEW_LINE> self.percentage = percent <NEW_LINE> self.percentFormat = format <NEW_LINE> text = self.preText + self.percentFormat % percent + '%' <NEW_LINE> self.textLength = len(text) <NEW_LINE> if not self.silent: <NEW_LINE> <INDENT> sys.stdout.write(text) <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> <DEDENT> def update_percentage(self, percent): <NEW_LINE> <INDENT> import sys <NEW_LINE> text = self.preText + self.percentFormat % percent + '%' <NEW_LINE> sys.stdout.write('\b' * self.textLength) <NEW_LINE> self.textLength = len(text) <NEW_LINE> if not self.silent: <NEW_LINE> <INDENT> sys.stdout.write(text) <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> <DEDENT> def end_percentage(self, text='done'): <NEW_LINE> <INDENT> import sys <NEW_LINE> text = self.preText + text <NEW_LINE> sys.stdout.write('\b' * self.textLength) <NEW_LINE> fmt = '%%-%ds\n' % self.textLength <NEW_LINE> self.textLength = len(text) <NEW_LINE> if not self.silent: <NEW_LINE> <INDENT> sys.stdout.write(fmt % text) <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> self.overwriteLine = False <NEW_LINE> <DEDENT> def write(self, text): <NEW_LINE> <INDENT> import sys <NEW_LINE> if self.overwriteLine and text != '\n': <NEW_LINE> <INDENT> sys.stdout.write('\n') <NEW_LINE> <DEDENT> sys.stdout.write(text) <NEW_LINE> sys.stdout.flush() | A class to sequentially display percentage completion of an iterative
process on a single line. | 6259904007f4c71912bb06c5 |
class TranslationExtension(Extension): <NEW_LINE> <INDENT> tags = {"translation"} <NEW_LINE> def parse(self, parser): <NEW_LINE> <INDENT> lineno = next(parser.stream).lineno <NEW_LINE> block_language = parser.parse_expression() <NEW_LINE> body = parser.parse_statements(["name:endtranslation"], drop_needle=True) <NEW_LINE> return nodes.CallBlock( self.call_method("_override", [block_language]), [], [], body ).set_lineno(lineno) <NEW_LINE> <DEDENT> def _override(self, block_language, caller): <NEW_LINE> <INDENT> with translation.override(block_language): <NEW_LINE> <INDENT> value = caller() <NEW_LINE> <DEDENT> return value | Provide a Jinja2 tag like Django's {% translation %} block
Usage:
{% translation 'en-US' %}
<p>_('This string is translatable, but displayed in English.')</p>
{% endtranslation %}
See Django documentation for details:
https://docs.djangoproject.com/en/1.11/topics/i18n/translation/#switching-language-in-templates
Jinja2 has a parsing phase and then a rendering phase. This parses the {%
translation %} block as a CallBlock node that will override the translation
at render time. It is very similar to the example in the docs:
http://jinja.pocoo.org/docs/2.10/extensions/#module-jinja2.ext | 6259904023e79379d538d792 |
class ListTagView(LGRHandlingBaseMixin, TemplateView): <NEW_LINE> <INDENT> template_name = 'lgr_editor/tags.html' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> ctx = super().get_context_data(**kwargs) <NEW_LINE> tag_classes = self.lgr_info.lgr.get_tag_classes() <NEW_LINE> tags = [{ 'name': tag, 'nb_cp': len(clz.codepoints), 'view_more': len(clz.codepoints) > TRUNCATE_AFTER_N_CP_TAGS, 'codepoints': [{ 'cp_disp': render_cp_or_sequence(c), 'cp_id': cp_to_slug((c,)), } for c in islice(clz.codepoints, TRUNCATE_AFTER_N_CP_TAGS)] } for tag, clz in tag_classes.items()] <NEW_LINE> ctx.update({ 'tags': tags, 'lgr': self.lgr_info.lgr, 'lgr_id': self.lgr_id, 'is_set': self.lgr_info.is_set or self.lgr_set_id is not None }) <NEW_LINE> if self.lgr_set_id: <NEW_LINE> <INDENT> lgr_set_info = self.session.select_lgr(self.lgr_set_id) <NEW_LINE> ctx['lgr_set'] = lgr_set_info.lgr <NEW_LINE> ctx['lgr_set_id'] = self.lgr_set_id <NEW_LINE> <DEDENT> return ctx | List/edit tags of an LGR. | 62599040d99f1b3c44d06930 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.