code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Greeter: <NEW_LINE> <INDENT> greeting: Greeting <NEW_LINE> def __init__(self, greeting: Greeting): <NEW_LINE> <INDENT> self.greeting = greeting | A plain-old-class to engage a customer. | 62598f9d596a897236127a49 |
class Meta(object): <NEW_LINE> <INDENT> verbose_name_plural = "Server Type" | meta informations | 62598f9d0a50d4780f7051a3 |
class VotingButton: <NEW_LINE> <INDENT> def __init__(self, Booth, Buttontext, frame, row): <NEW_LINE> <INDENT> Button(frame, text = Buttontext, width = 40, command = self.Vote).grid( row = row, column = 0) <NEW_LINE> self.numberofvoteslabel = Label(frame, text = "0", width = 20) <NEW_LINE> self.numberofvoteslabel.grid( row = row, column = 1) <NEW_LINE> self.numberofvotes = 0 <NEW_LINE> self.Buttontext = Buttontext <NEW_LINE> self.Booth = Booth <NEW_LINE> <DEDENT> def Vote(self): <NEW_LINE> <INDENT> self.numberofvotes += 1 <NEW_LINE> self.numberofvoteslabel.config(text = self.numberofvotes) <NEW_LINE> for btn in self.Booth.Buttons: <NEW_LINE> <INDENT> if self.numberofvotes < self.Booth.maximum_votes: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.numberofvotes == btn.numberofvotes and self.Buttontext != btn.Buttontext: <NEW_LINE> <INDENT> self.Booth.currentwinnerlabel.config(text = "Tied") <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> self.Booth.maximum_votes = self.numberofvotes <NEW_LINE> self.Booth.currentwinnerlabel.config(text = self.Buttontext) | Blueprint for the creation of VotingButton objects including the
vote function | 62598f9d67a9b606de545d93 |
class SubprocessReader(AbstractSubprocessReader): <NEW_LINE> <INDENT> def __init__( self, identifer, stream, events_queue, expected, log=False, option='input' ): <NEW_LINE> <INDENT> self.id = identifer <NEW_LINE> self._s = stream <NEW_LINE> self._q = events_queue <NEW_LINE> self._e = expected <NEW_LINE> self.logging_on = log <NEW_LINE> self._l = self.print_console <NEW_LINE> if option == 'input': <NEW_LINE> <INDENT> self._r = self.input_reader <NEW_LINE> self._c = self.input_container <NEW_LINE> self._ex = self.input_exception <NEW_LINE> <DEDENT> elif option == 'stdout': <NEW_LINE> <INDENT> self._r = self.stdout_reader <NEW_LINE> self._c = self.stdout_container <NEW_LINE> self._ex = self.std_out_exception <NEW_LINE> <DEDENT> def _stream_to_queue( id, stream, reader, container, events_queue, expected, logger, exception ): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = reader(stream).strip().split(', ') <NEW_LINE> if len(result) == expected: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> event = container(result) <NEW_LINE> events_queue.put(event) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> if exception(result, id): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> except EOFError: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> logger("{} stopped".format(id)) <NEW_LINE> <DEDENT> self.t = Thread( target=_stream_to_queue, args=( self.id, self._s, self._r, self._c, self._q, self._e, self._l, self._ex, ) ) <NEW_LINE> self.t.daemon = True <NEW_LINE> self.t.start() | A class representing a SubprocessReader.
It contains an id for tracking with the ability
to handle different types of streamed events.
Parameters
----------
identifier : int
The human-readable identifier
stream: input | stdout
Stream to read
expected : int, length of stream
Length of message in stream
log: bool
Turns printing on/off
option : 'stdout' or 'input'
The SubprocessReader will read from the subprocess
sys.stdout or input() stream and feed these back
into the parent process events queue. | 62598f9d462c4b4f79dbb7d5 |
class Hasher(BaseModule): <NEW_LINE> <INDENT> def _process(self, item): <NEW_LINE> <INDENT> cov = [[[0.1], [0.05], [0.1]]] <NEW_LINE> img = signal.convolve(item, cov) <NEW_LINE> img = Image.fromarray(img.astype('uint8')).convert('RGB') <NEW_LINE> md5 = hashlib.md5(str(img).encode('utf-8')).hexdigest() <NEW_LINE> return md5 <NEW_LINE> <DEDENT> def _process_singlethread(self, list_): <NEW_LINE> <INDENT> md5_list = [] <NEW_LINE> for img in list_: <NEW_LINE> <INDENT> md5 = self._process(img) <NEW_LINE> md5_list.append(md5) <NEW_LINE> <DEDENT> return md5_list | 哈希模块
| 62598f9d009cb60464d012ef |
class Urls(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def login_url(): <NEW_LINE> <INDENT> return "https://www.facebook.com/v2.9/dialog/oauth?" "client_id=%s&redirect_uri=%s&scope=%s" % ( app_id, urllib.quote_plus(login_path), 'public_profile,email') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def access_token_url(code): <NEW_LINE> <INDENT> return "https://graph.facebook.com/v2.9/oauth/access_token?" "client_id=%(appid)s&redirect_uri=%(redirecturi)s" "&client_secret=%(appsecret)s&" "code=%(codeparameter)s" % {'appid': app_id, 'redirecturi': login_path, 'appsecret': secret, 'codeparameter': code} <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def user_info(access_token): <NEW_LINE> <INDENT> return "https://graph.facebook.com/v2.9/me?" "access_token=%s&fields=%s" % (access_token['access_token'], 'id,name,picture,email') | Wraps URLs creation, formatting and concatenating data when
needed. | 62598f9d3eb6a72ae038a40a |
class SocketTimeout(SocketError, socket.timeout): <NEW_LINE> <INDENT> pass | Socket timeout, server is probably down. | 62598f9d097d151d1a2c0df1 |
class ReturnsUnlockable(Matcher): <NEW_LINE> <INDENT> def __init__(self, lockable_thing): <NEW_LINE> <INDENT> Matcher.__init__(self) <NEW_LINE> self.lockable_thing = lockable_thing <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ('ReturnsUnlockable(lockable_thing=%s)' % self.lockable_thing) <NEW_LINE> <DEDENT> def match(self, lock_method): <NEW_LINE> <INDENT> lock_method().unlock() <NEW_LINE> if self.lockable_thing.is_locked(): <NEW_LINE> <INDENT> return _IsLocked(self.lockable_thing) <NEW_LINE> <DEDENT> return None | A matcher that checks for the pattern we want lock* methods to have:
They should return an object with an unlock() method.
Calling that method should unlock the original object.
:ivar lockable_thing: The object which can be locked that will be
inspected. | 62598f9d8da39b475be02fad |
class Ruestung(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ID = 0 <NEW_LINE> self.typ = "Kleidung" <NEW_LINE> self.name = "Ruestung" <NEW_LINE> zeile1 = [1,1] <NEW_LINE> zeile2 = [0,1] <NEW_LINE> self.spalte = [zeile1,zeile2] <NEW_LINE> self.stapelbar = False <NEW_LINE> self.wert = 5 | Erstellt ein Item vom Typ Ruestung | 62598f9d10dbd63aa1c70980 |
class FormDefender(PageBase): <NEW_LINE> <INDENT> def __new__(mcs, name, bases, attrs): <NEW_LINE> <INDENT> new_attrs = dict((k if k != 'base_form_class' else '_'+k, v) for k, v in attrs.items()) <NEW_LINE> cls = super().__new__(mcs, name, bases, new_attrs) <NEW_LINE> return cls <NEW_LINE> <DEDENT> @property <NEW_LINE> def base_form_class(cls): <NEW_LINE> <INDENT> return cls._base_form_class <NEW_LINE> <DEDENT> @base_form_class.setter <NEW_LINE> def base_form_class(cls, form_class): <NEW_LINE> <INDENT> my_form_class = cls._base_form_class <NEW_LINE> if my_form_class is None: <NEW_LINE> <INDENT> cls._base_form_class = form_class <NEW_LINE> return <NEW_LINE> <DEDENT> if (isinstance(form_class, type) and issubclass(form_class, my_form_class)): <NEW_LINE> <INDENT> cls._base_form_class = form_class <NEW_LINE> return <NEW_LINE> <DEDENT> if getattr(settings, "JOYOUS_DEFEND_FORMS", False): <NEW_LINE> <INDENT> if issubclass(my_form_class, BorgPageForm): <NEW_LINE> <INDENT> my_form_class.assimilate(form_class) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> warning = FormCannotAssimilateWarning( "{} cannot assimilate {}" .format(_getName(my_form_class), _getName(form_class))) <NEW_LINE> warnings.warn(warning, stacklevel=2) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> cls._base_form_class = form_class <NEW_LINE> warning = FormClassOverwriteWarning( "{} has been overwritten with {}, " "consider enabling JOYOUS_DEFEND_FORMS" .format(_getName(my_form_class), _getName(form_class))) <NEW_LINE> warnings.warn(warning, stacklevel=2) | Metaclass for pages who don't want their base_form_class changed | 62598f9d24f1403a92685797 |
class CustomNode(Node): <NEW_LINE> <INDENT> def __init__(self, children): <NEW_LINE> <INDENT> self.children = children <NEW_LINE> <DEDENT> @property <NEW_LINE> def args(self): <NEW_LINE> <INDENT> return self.children <NEW_LINE> <DEDENT> @property <NEW_LINE> def symbols_defined(self): <NEW_LINE> <INDENT> return set() <NEW_LINE> <DEDENT> @property <NEW_LINE> def undefined_symbols(self): <NEW_LINE> <INDENT> undefined = [] <NEW_LINE> for c in self.args: <NEW_LINE> <INDENT> if hasattr(c, 'undefined_symbols'): <NEW_LINE> <INDENT> undefined.extend(c.undefined_symbols) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> c = sp.sympify(c) <NEW_LINE> undefined.extend(c.free_symbols) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return set(undefined) - self.symbols_defined | Own custom base class for all AST nodes. | 62598f9d3539df3088ecc080 |
class LayeredSimple(sgc.Simple): <NEW_LINE> <INDENT> _layered = True | Layered Simple widget, to prevent click events from propagating
through to the background frame, and to enforce draw order. | 62598f9de64d504609df929d |
class FeatureExtractor(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_feature(self, obs): <NEW_LINE> <INDENT> pass | Base feature extractor. | 62598f9d498bea3a75a578eb |
class PosNegBatchSampler(BatchSampler): <NEW_LINE> <INDENT> def __init__(self, user_item_matrix, batch_size): <NEW_LINE> <INDENT> user_item_matrix = lil_matrix(user_item_matrix) <NEW_LINE> self.user_item_pos_pairs = np.asarray(user_item_matrix.nonzero()).T <NEW_LINE> self.user_item_neg_pairs = (1 - user_item_matrix.toarray()).nonzero().T <NEW_LINE> self.neg_rate = 3 <NEW_LINE> self.dataset = user_item_matrix <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.count = 0 <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> self.count = 0 <NEW_LINE> while self.count + self.batch_size < len(self.dataset): <NEW_LINE> <INDENT> indices = [] <NEW_LINE> indices.append(self.user_item_pos_pairs[self.count: self.count+self.batch_size]) <NEW_LINE> indices.append(self.user_item_neg_pairs[self.neg_rate*self.count: self.neg_rate*(self.count+self.batch_size)]) <NEW_LINE> yield indices <NEW_LINE> self.count += self.batch_size <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.dataset) // self.batch_size | BatchSampler - from a MNIST-like dataset, samples n_classes and within these classes samples n_samples.
Returns batches of size n_classes * n_samples | 62598f9d99cbb53fe6830c9d |
class ServiceConfigModel(BaseModel): <NEW_LINE> <INDENT> model_name = '服务配置' <NEW_LINE> model_sign = 'service_config' <NEW_LINE> DNS_TYP_NONE = 'none' <NEW_LINE> DNS_TYP_ECS = 'ecs' <NEW_LINE> DNS_TYP_SLB = 'slb' <NEW_LINE> DNS_TYP_CHOICES = ( (DNS_TYP_NONE, '无解析'), (DNS_TYP_ECS, '解析至ECS'), (DNS_TYP_SLB, '解析至SLB'), ) <NEW_LINE> ARTIFACT_TYP_GIT = 'git' <NEW_LINE> ARTIFACT_TYP_ARCHIVE = 'archive' <NEW_LINE> ARTIFACT_TYP_DOCKER = 'docker' <NEW_LINE> ARTIFACT_TYP_CHOICES = ( (ARTIFACT_TYP_GIT, 'git源码'), (ARTIFACT_TYP_ARCHIVE, '压缩包'), (ARTIFACT_TYP_DOCKER, 'Docker镜像'), ) <NEW_LINE> DEPLOY_TYP_ECS = 'ecs' <NEW_LINE> DEPLOY_TYP_K8S = 'k8s' <NEW_LINE> DEPLOY_TYP_CHOICES = ( (DEPLOY_TYP_ECS, 'ECS部署'), (DEPLOY_TYP_K8S, 'K8s部署'), ) <NEW_LINE> service = models.ForeignKey(ServiceModel, on_delete=models.CASCADE, verbose_name='服务') <NEW_LINE> environment = models.ForeignKey(EnvironmentModel, on_delete=models.CASCADE, verbose_name='环境') <NEW_LINE> port = models.IntegerField('端口号', null=True) <NEW_LINE> dns_typ = models.CharField('解析类型', max_length=128, choices=DNS_TYP_CHOICES) <NEW_LINE> artifact_typ = models.CharField('制品类型', max_length=128, choices=ARTIFACT_TYP_CHOICES) <NEW_LINE> deploy_typ = models.CharField('部署类型', max_length=128, choices=DEPLOY_TYP_CHOICES) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'service_config' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def none_to_dict(cls): <NEW_LINE> <INDENT> data = { 'port': None, 'dns_typ': '', 'dns_typ_desc': '', 'artifact_typ': '', 'artifact_typ_desc': '', 'deploy_typ': '', 'deploy_typ_desc': '', } <NEW_LINE> return data | 服务配置 | 62598f9d63b5f9789fe84f40 |
class MultiMessageDialog(Menu): <NEW_LINE> <INDENT> def __init__(self, text, block_movement=True): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self.block_movement = block_movement <NEW_LINE> self.current_panel = None <NEW_LINE> Menu.__init__(self, g_cfg.screen_width - 2 * cfg.border_width, g_cfg.screen_height / 2 - 2 * cfg.border_width, cfg.border_width, g_cfg.screen_height / 2 + cfg.border_width, bg=TRANSPARENT, blocking=block_movement) <NEW_LINE> font = self.theme.get_font(cfg.font_size) <NEW_LINE> box_width = g_cfg.screen_width - 4 * cfg.border_width <NEW_LINE> lines = build_lines(self.text, box_width, font) <NEW_LINE> box_height = g_cfg.screen_height / 2 - 4 * cfg.border_width <NEW_LINE> self.boxes = split_boxes(lines, box_height, cfg.line_spacing) <NEW_LINE> self.panels = [] <NEW_LINE> for box in self.boxes: <NEW_LINE> <INDENT> panel = Panel(self.width, self.height) <NEW_LINE> y_acc = 0 <NEW_LINE> for line in box: <NEW_LINE> <INDENT> label = Label(line[2]) <NEW_LINE> panel.add_widget(label, (cfg.border_width, cfg.border_width + y_acc)) <NEW_LINE> y_acc += line[1] + cfg.line_spacing <NEW_LINE> <DEDENT> self.panels.append(panel) <NEW_LINE> <DEDENT> self.advance_panel() <NEW_LINE> <DEDENT> def advance_panel(self): <NEW_LINE> <INDENT> if self.current_panel is not None: <NEW_LINE> <INDENT> self.remove_widget(self.current_panel) <NEW_LINE> self.current_panel = None <NEW_LINE> <DEDENT> if self.panels: <NEW_LINE> <INDENT> self.current_panel = self.panels.pop(0) <NEW_LINE> self.add_widget(self.current_panel, (0, 0)) <NEW_LINE> <DEDENT> <DEDENT> def activate(self): <NEW_LINE> <INDENT> self.advance_panel() <NEW_LINE> if self.current_panel is None: <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> <DEDENT> def update_input(self): <NEW_LINE> <INDENT> if Input.was_pressed(M_1): <NEW_LINE> <INDENT> self.activate() | Same as a MessageDialog but splits messages bigger than the default
box size into multiple dialogs. | 62598f9d55399d3f056262ec |
class State(object): <NEW_LINE> <INDENT> RUNNING = 0 <NEW_LINE> PENDING = 1 <NEW_LINE> UNKNOWN = 2 <NEW_LINE> ERROR = 3 <NEW_LINE> DELETED = 4 | Standard states for a loadbalancer
:cvar RUNNING: loadbalancer is running and ready to use
:cvar UNKNOWN: loabalancer state is unknown | 62598f9d21a7993f00c65d4d |
class Interface(object): <NEW_LINE> <INDENT> def __init__(self,actor): <NEW_LINE> <INDENT> self._actor = actor <NEW_LINE> <DEDENT> def refuse( self, *args ): <NEW_LINE> <INDENT> self._actor._gate.refuse( "object", *args ) <NEW_LINE> <DEDENT> def accept( self, *args ): <NEW_LINE> <INDENT> self._actor._gate.accept( "object", *args ) <NEW_LINE> <DEDENT> def default( self, *args ): <NEW_LINE> <INDENT> self._actor._gate.default( ( "object", ) + args ) <NEW_LINE> <DEDENT> def always( self, args, value ): <NEW_LINE> <INDENT> if not isinstance( args, tuple ): <NEW_LINE> <INDENT> args = ( args, ) <NEW_LINE> <DEDENT> self._actor._gate.always( ( ( "object", ) + args ), value ) <NEW_LINE> <DEDENT> def enable_call_threading( self ): <NEW_LINE> <INDENT> self._actor._set_call_threading_enabled(True) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name( self ): <NEW_LINE> <INDENT> return self._actor and self._actor.name <NEW_LINE> <DEDENT> def actor_yield(self, t = 0): <NEW_LINE> <INDENT> class Sleeper ( dramatis.Actor ): <NEW_LINE> <INDENT> def nap(self, t): <NEW_LINE> <INDENT> time.sleep( t ) <NEW_LINE> <DEDENT> <DEDENT> if t > 0: <NEW_LINE> <INDENT> sleeper = Sleeper() <NEW_LINE> ( dramatis.interface( sleeper ). continuation( { "continuation": "rpc", "nonblocking": True } ) ).nap( t ) <NEW_LINE> <DEDENT> self._actor.actor_send( [ "actor_yield" ], { "continuation": "rpc", "nonblocking": True } ) <NEW_LINE> return None <NEW_LINE> <DEDENT> def become(self, behavior): <NEW_LINE> <INDENT> self._actor.become( behavior ) <NEW_LINE> <DEDENT> def _gate( self ): <NEW_LINE> <INDENT> return self._actor._gate | provides actors with control over their runtime dynamics
A dramatis.Actor.Interface object provides actors that have mixed
in dramatis.Actor access to their actor name and other actor
operations. An instance of dramatis.Actor.Interface is typically
accessed through via self.actor.
Many of the interface method affect the <em>gate behavior</em> of
the actor, that is, whether tasks queued for the actor are allowed
to execute. With functions refuse, accept, default, and always, an
actor can control task scheduling.
Most of these methods accept an array of arguments that are matched
against each method by the runtime when determining whether a task
can be scheduled.
Each element in the array is tested, as "equal or subclass",
against the method and arguments of the task
underconsideration. If all the arguments match, the pattern
matches. Extra task parameters are ignored and the match
succeeds. If there are more arguments in the pattern than there
are associated with the task, the match fails.
Note that the interaction of multiple calls is a bit complex and currently
not documented. See the examples and tutorials.
This object should only be accessed from the actor it represents. | 62598f9d4428ac0f6e6582f5 |
class TestSingleActivityController(BaseTestCase): <NEW_LINE> <INDENT> def test_delete_activity(self): <NEW_LINE> <INDENT> response = self.client.open( '/activity-index/activities/{activityId}'.format(activityId='activityId_example'), method='DELETE', content_type='application/ld+json') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) <NEW_LINE> <DEDENT> def test_get_activity(self): <NEW_LINE> <INDENT> response = self.client.open( '/activity-index/activities/{activityId}'.format(activityId='activityId_example'), method='GET', content_type='application/ld+json') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) <NEW_LINE> <DEDENT> def test_post_activity(self): <NEW_LINE> <INDENT> activityObj = LearningActivity() <NEW_LINE> response = self.client.open( '/activity-index/activities', method='POST', data=json.dumps(activityObj), content_type='application/ld+json') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) <NEW_LINE> <DEDENT> def test_update_activity(self): <NEW_LINE> <INDENT> activityObj = None <NEW_LINE> response = self.client.open( '/activity-index/activities/{activityId}'.format(activityId='activityId_example'), method='PATCH', data=json.dumps(activityObj), content_type='application/ld+json') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) | SingleActivityController integration test stubs | 62598f9d91f36d47f2230d85 |
class MailTask(object): <NEW_LINE> <INDENT> @app.task(base=BaseTask, max_retries=3) <NEW_LINE> def send(mail_id, attach_file, to_email, title, auth): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mail = SendMail() <NEW_LINE> mail.send(attach_file, to_email, title, auth) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> MailTask.send.retry(countdown=30, exc=err) | 发送邮件,发送失败后间隔30秒重新发送
重试次数:5
mail_id: 邮件ID
attach_file: 附件文件路径
to_email: 收件方
title: 邮件标题
auth: 邮件作者 | 62598f9d10dbd63aa1c70981 |
class Remove(IteratorTask): <NEW_LINE> <INDENT> def dojob(self, name, context=None): <NEW_LINE> <INDENT> self.logger.info('remove(%s)', name) <NEW_LINE> name.remove() | Remove a file or directory tree.
constructor arguments:
Remove(*files) | 62598f9d7b25080760ed7271 |
@dataclass <NEW_LINE> class Recursive(JsonSchemaMixin): <NEW_LINE> <INDENT> a: str <NEW_LINE> b: Optional['Recursive'] = None | A recursive data-structure | 62598f9d63d6d428bbee257d |
class ZhaoEtAl2016SSlabSiteSigma(ZhaoEtAl2016SSlab): <NEW_LINE> <INDENT> def get_stddevs(self, C, n_sites, idx, stddev_types): <NEW_LINE> <INDENT> stddevs = [] <NEW_LINE> tau = C["tau"] + np.zeros(n_sites) <NEW_LINE> phi = np.zeros(n_sites) <NEW_LINE> for i in range(1, 5): <NEW_LINE> <INDENT> phi[idx[i]] += C["sc{:g}_sigma_S".format(i)] <NEW_LINE> <DEDENT> for stddev_type in stddev_types: <NEW_LINE> <INDENT> assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES <NEW_LINE> if stddev_type == const.StdDev.TOTAL: <NEW_LINE> <INDENT> stddevs.append(np.sqrt(phi ** 2. + tau ** 2.)) <NEW_LINE> <DEDENT> elif stddev_type == const.StdDev.INTRA_EVENT: <NEW_LINE> <INDENT> stddevs.append(phi) <NEW_LINE> <DEDENT> elif stddev_type == const.StdDev.INTER_EVENT: <NEW_LINE> <INDENT> stddevs.append(tau) <NEW_LINE> <DEDENT> <DEDENT> return stddevs | Subclass of the Zhao et al. (2016c) subduction in-slab GMPE for the
case of site-dependent within-event variability | 62598f9d30bbd7224646985c |
class SCSGateScenarioSwitch: <NEW_LINE> <INDENT> def __init__(self, scs_id, name, logger, hass): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._scs_id = scs_id <NEW_LINE> self._logger = logger <NEW_LINE> self._hass = hass <NEW_LINE> <DEDENT> @property <NEW_LINE> def scs_id(self): <NEW_LINE> <INDENT> return self._scs_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def process_event(self, message): <NEW_LINE> <INDENT> if isinstance(message, StateMessage): <NEW_LINE> <INDENT> scenario_id = message.bytes[4] <NEW_LINE> <DEDENT> elif isinstance(message, ScenarioTriggeredMessage): <NEW_LINE> <INDENT> scenario_id = message.scenario <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._logger.warn("Scenario switch: received unknown message %s", message) <NEW_LINE> return <NEW_LINE> <DEDENT> self._hass.bus.fire( "scenario_switch_triggered", {ATTR_ENTITY_ID: int(self._scs_id), ATTR_SCENARIO_ID: int(scenario_id, 16)}, ) | Provides a SCSGate scenario switch.
This switch is always in an 'off" state, when toggled it's used to trigger
events. | 62598f9dadb09d7d5dc0a355 |
class Prequestionnaire(ProxyModel): <NEW_LINE> <INDENT> user_id = IntegerField() <NEW_LINE> programming_years = TextField() <NEW_LINE> python_years = TextField() <NEW_LINE> professional_years = TextField() <NEW_LINE> coding_reason = TextField() <NEW_LINE> programming_proficiency = TextField(db_column='programming_profiency') <NEW_LINE> python_proficiency = TextField() <NEW_LINE> occupation = TextField() <NEW_LINE> occupation_other = TextField() <NEW_LINE> gender = TextField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'form_prequestionnaire' | A questionnaire with information about a participant's background. | 62598f9dc432627299fa2da4 |
class MultiCameraViewCtrlWidget(_BaseAnalysisCtrlWidgetS): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.output_channels = [] <NEW_LINE> self.properties = [] <NEW_LINE> for i in range(_N_CAMERAS): <NEW_LINE> <INDENT> if i < 2: <NEW_LINE> <INDENT> default_output = f"camera{i+1}:output" <NEW_LINE> default_ppt = _DEFAULT_PROPERTY <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> default_output = "" <NEW_LINE> default_ppt = "" <NEW_LINE> <DEDENT> self.output_channels.append(SmartLineEdit(default_output)) <NEW_LINE> self.properties.append(SmartLineEdit(default_ppt)) <NEW_LINE> <DEDENT> self._non_reconfigurable_widgets = [ *self.output_channels, *self.properties, ] <NEW_LINE> self.initUI() <NEW_LINE> self.initConnections() <NEW_LINE> <DEDENT> def initUI(self): <NEW_LINE> <INDENT> layout = self.layout() <NEW_LINE> for i, (ch, ppt) in enumerate(zip(self.output_channels, self.properties)): <NEW_LINE> <INDENT> layout.addRow(f"Output channel {i+1}: ", ch) <NEW_LINE> layout.addRow(f"Property {i+1}: ", ppt) <NEW_LINE> <DEDENT> <DEDENT> def initConnections(self): <NEW_LINE> <INDENT> pass | Multi-Camera view control widget. | 62598f9db7558d58954633fb |
class StoryFragment(object,IAddChild,IEnumerable[BlockElement],IEnumerable): <NEW_LINE> <INDENT> def Add(self,element): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __add__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __contains__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __iter__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __repr__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> FragmentName=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> FragmentType=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> StoryName=property(lambda self: object(),lambda self,v: None,lambda self: None) | Represents all or part of a story within an XPS document.
StoryFragment() | 62598f9d0a50d4780f7051a5 |
class OrderedTrees_all(DisjointUnionEnumeratedSets, OrderedTrees): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> DisjointUnionEnumeratedSets.__init__( self, Family(NonNegativeIntegers(), OrderedTrees_size), facade=True, keepkey=False) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "Ordered trees" <NEW_LINE> <DEDENT> def __contains__(self, x): <NEW_LINE> <INDENT> return isinstance(x, self.element_class) <NEW_LINE> <DEDENT> def unlabelled_trees(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def labelled_trees(self): <NEW_LINE> <INDENT> return LabelledOrderedTrees() <NEW_LINE> <DEDENT> def _element_constructor_(self, *args, **keywords): <NEW_LINE> <INDENT> return self.element_class(self, *args, **keywords) <NEW_LINE> <DEDENT> Element = OrderedTree | The set of all ordered trees.
EXAMPLES::
sage: OT = OrderedTrees(); OT
Ordered trees
sage: OT.cardinality()
+Infinity | 62598f9dbd1bec0571e14fa9 |
class UtilDjangoTests(TestCase): <NEW_LINE> <INDENT> shard = 1 <NEW_LINE> def test_get_current_request(self): <NEW_LINE> <INDENT> assert_is_none(get_current_request()) <NEW_LINE> <DEDENT> def test_get_current_request_hostname(self): <NEW_LINE> <INDENT> assert_is_none(get_current_request_hostname()) | Tests for methods exposed in util/django | 62598f9d2c8b7c6e89bd359d |
class GodsWorldHelpIntentHandler(AbstractRequestHandler): <NEW_LINE> <INDENT> def can_handle(self, handler_input): <NEW_LINE> <INDENT> session = handler_input.attributes_manager.session_attributes <NEW_LINE> scene = session.get('scene') <NEW_LINE> if not scene: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return scene == 'gods_world' and is_intent_name("AMAZON.HelpIntent")( handler_input) <NEW_LINE> <DEDENT> def handle(self, handler_input): <NEW_LINE> <INDENT> speech_text = 'ここは神様の国、神界。神界ではさまざまな神様の力を借りることができます。現在はオルぺの力で、物語3つを遊ぶことができます。「拒否部下と魔王軍」「魔女と猫と盲目の狩人」「夜道騒動フォリス」から選んでください。オルぺによるその他の物語追加や、「神、ガネーシャ」によるショップなどは、後日追加される予定です。楽しみにお待ちください。どの物語を遊びますか?' <NEW_LINE> handler_input.response_builder.speak(speech_text).ask(speech_text) <NEW_LINE> handler_input.response_builder.set_should_end_session(False) <NEW_LINE> handler_input.response_builder.set_card( ui.StandardCard( title='どの物語を遊びますか?', text='・拒否部下と魔王軍\r\n' '・魔女と猫と盲目の狩人\r\n' '・夜道騒動フォリス' ) ) <NEW_LINE> return handler_input.response_builder.response | Handler for Help Intent. | 62598f9d24f1403a92685798 |
class CChange(model.CEventsModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(CChange, self).__init__() <NEW_LINE> self.s_name = "Data Changed event" | data changed event class | 62598f9d63d6d428bbee257e |
@attr.s(slots=True) <NEW_LINE> class PackageCombinationsSieve(Sieve): <NEW_LINE> <INDENT> CONFIGURATION_DEFAULT: Dict[str, Union[None, List[str]]] = {"package_name": None, "package_combinations": []} <NEW_LINE> CONFIGURATION_SCHEMA = Schema( { Required("package_name"): None, Required("package_combinations"): [str], } ) <NEW_LINE> _package_tuples_seen = attr.ib( type=Dict[str, Tuple[str, str, str]], default=attr.Factory(dict), kw_only=True, init=False ) <NEW_LINE> _package_combinations = attr.ib(type=Set[str], default=attr.Factory(set), kw_only=True, init=False) <NEW_LINE> @classmethod <NEW_LINE> def should_include(cls, builder_context: "PipelineBuilderContext") -> Generator[Dict[str, Any], None, None]: <NEW_LINE> <INDENT> yield from () <NEW_LINE> return None <NEW_LINE> <DEDENT> def pre_run(self) -> None: <NEW_LINE> <INDENT> self._package_combinations = set(self.configuration["package_combinations"]) <NEW_LINE> if not self._package_combinations: <NEW_LINE> <INDENT> raise NotImplementedError("No package packages to compute combinations supplied") <NEW_LINE> <DEDENT> self._package_tuples_seen.clear() <NEW_LINE> super().pre_run() <NEW_LINE> <DEDENT> def run(self, package_versions: Generator[PackageVersion, None, None]) -> Generator[PackageVersion, None, None]: <NEW_LINE> <INDENT> for package_version in package_versions: <NEW_LINE> <INDENT> if package_version.name in self._package_combinations: <NEW_LINE> <INDENT> yield package_version <NEW_LINE> continue <NEW_LINE> <DEDENT> seen_package_tuple = self._package_tuples_seen.get(package_version.name) <NEW_LINE> if seen_package_tuple is None: <NEW_LINE> <INDENT> self._package_tuples_seen[package_version.name] = package_version.to_tuple() <NEW_LINE> yield package_version <NEW_LINE> continue <NEW_LINE> <DEDENT> if seen_package_tuple == package_version.to_tuple(): <NEW_LINE> <INDENT> yield package_version <NEW_LINE> continue | A sieve to filter out packages respecting desired combinations that should be computed. | 62598f9d004d5f362081eee3 |
class TestGetLogin(unittest.TestCase): <NEW_LINE> <INDENT> @patch("os.getuid", return_value=1001) <NEW_LINE> @patch("pwd.getpwuid") <NEW_LINE> def test_get_login(self, getpwuid, getuid): <NEW_LINE> <INDENT> getpwuid.return_value.pw_name = "user" <NEW_LINE> user = get_login() <NEW_LINE> getpwuid.assert_called_once_with(getuid.return_value) <NEW_LINE> self.assertEqual("user", user) | Test get_login | 62598f9d1f037a2d8b9e3eb3 |
class PersonalNoteSerializer(ModelSerializer): <NEW_LINE> <INDENT> notes = JSONField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = PersonalNote <NEW_LINE> fields = ("id", "user", "notes") <NEW_LINE> read_only_fields = ("user",) | Serializer for users.models.PersonalNote objects. | 62598f9d2ae34c7f260aaead |
class ClaimInvalid(ValidationFailure): <NEW_LINE> <INDENT> pass | The Validator object attempted validation of a given claim, but one of the
callbacks marked the claim as invalid. | 62598f9d2ae34c7f260aaeae |
class TestDestinyDefinitionsProgressionDestinyProgressionLevelRequirementDefinition(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testDestinyDefinitionsProgressionDestinyProgressionLevelRequirementDefinition(self): <NEW_LINE> <INDENT> pass | DestinyDefinitionsProgressionDestinyProgressionLevelRequirementDefinition unit test stubs | 62598f9da17c0f6771d5c007 |
class Page(object): <NEW_LINE> <INDENT> def __init__(self, stack=None, data=None): <NEW_LINE> <INDENT> self.stack = stack <NEW_LINE> self.data = odict(raeting.PAGE_DEFAULTS) <NEW_LINE> if data: <NEW_LINE> <INDENT> self.data.update(data) <NEW_LINE> <DEDENT> self.packed = b'' <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return len(self.packed) <NEW_LINE> <DEDENT> @property <NEW_LINE> def paginated(self): <NEW_LINE> <INDENT> return (True if self.data.get('pc', 0) > 1 else False) | RAET UXD protocol page object. Support sectioning of messages into Uxd pages | 62598f9de5267d203ee6b6da |
class KerasExperiment(ExperimentBase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.__enter_menu = False <NEW_LINE> self.__callback = DelegatingCallback(on_epoch_end=self.__on_epoch_end) <NEW_LINE> <DEDENT> def __on_epoch_end(self, epoch, logs=None): <NEW_LINE> <INDENT> self._update_after_epoch(epoch, logs=logs) <NEW_LINE> if not self.__enter_menu: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._show_main_menu() <NEW_LINE> self.__enter_menu = False <NEW_LINE> self._update_after_menu() <NEW_LINE> self._checkpoint() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def _update_after_menu(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def _update_after_epoch(self, epoch, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _handle_signal(self, signum, frame): <NEW_LINE> <INDENT> if self.__enter_menu: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> print("Signal caught, entering menu after current epoch.") <NEW_LINE> self.__enter_menu = True <NEW_LINE> <DEDENT> def _run_testing_step(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_callback(self): <NEW_LINE> <INDENT> return self.__callback <NEW_LINE> <DEDENT> def train(self): <NEW_LINE> <INDENT> self._run_training_step() | An experiment meant to better integrate with Keras. | 62598f9dd53ae8145f91825a |
class ResetMixin(object): <NEW_LINE> <INDENT> def reset(self): <NEW_LINE> <INDENT> instdict = self.__dict__ <NEW_LINE> classdict = self.__class__.__dict__ <NEW_LINE> for mname, mval in list(classdict.items()): <NEW_LINE> <INDENT> if mname in instdict and isinstance(mval, OneTimeProperty): <NEW_LINE> <INDENT> delattr(self, mname) | A Mixin class to add a .reset() method to users of OneTimeProperty.
By default, auto attributes once computed, become static. If they happen to
depend on other parts of an object and those parts change, their values may
now be invalid.
This class offers a .reset() method that users can call *explicitly* when
they know the state of their objects may have changed and they want to
ensure that *all* their special attributes should be invalidated. Once
reset() is called, all their auto attributes are reset to their
OneTimeProperty descriptors, and their accessor functions will be triggered
again.
Example
-------
>>> class A(ResetMixin):
... def __init__(self,x=1.0):
... self.x = x
...
... @auto_attr
... def y(self):
... print('*** y computation executed ***')
... return self.x / 2.0
...
>>> a = A(10)
About to access y twice, the second time no computation is done:
>>> a.y
*** y computation executed ***
5.0
>>> a.y
5.0
Changing x
>>> a.x = 20
a.y doesn't change to 10, since it is a static attribute:
>>> a.y
5.0
We now reset a, and this will then force all auto attributes to recompute
the next time we access them:
>>> a.reset()
About to access y twice again after reset():
>>> a.y
*** y computation executed ***
10.0
>>> a.y
10.0 | 62598f9d21bff66bcd722a31 |
class i2c_smbus_ioctl_data(Structure): <NEW_LINE> <INDENT> _fields_ = [ ('read_write', c_uint8), ('command', c_uint8), ('size', c_uint32), ('data', union_pointer_type)] <NEW_LINE> __slots__ = [name for name, type in _fields_] <NEW_LINE> @staticmethod <NEW_LINE> def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA): <NEW_LINE> <INDENT> u = union_i2c_smbus_data() <NEW_LINE> return i2c_smbus_ioctl_data( read_write=read_write, command=command, size=size, data=union_pointer_type(u)) | As defined in i2c-dev.h | 62598f9df7d966606f747db4 |
class AuthorizationGeekBrains: <NEW_LINE> <INDENT> def __init__(self, email: str, password: str): <NEW_LINE> <INDENT> self.email = email <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> def get_token(self): <NEW_LINE> <INDENT> self.url = f"{MAIN_LINK}/login" <NEW_LINE> self.connect = requests.Session() <NEW_LINE> self.html = self.connect.get(self.url,verify=True) <NEW_LINE> self.soup = BeautifulSoup(self.html.content, "html.parser") <NEW_LINE> print(self.soup) <NEW_LINE> self.hidden_auth_token = self.soup.find( 'input', {'name': 'authenticity_token'})['value'] <NEW_LINE> print(self.hidden_auth_token) <NEW_LINE> <DEDENT> def authorization(self): <NEW_LINE> <INDENT> self.connect.get(self.url, verify=True) <NEW_LINE> self.login_data = { "utf8": "✓", "authenticity_token": self.hidden_auth_token, "user[email]": self.email, "user[password]": self.password, "user[remember_me]": "0" } <NEW_LINE> self.connect.post( MAIN_LINK, data=self.login_data, headers={"Referer": f"{self.url}"} ) <NEW_LINE> <DEDENT> def login_gb(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.get_token() <NEW_LINE> self.authorization() <NEW_LINE> <DEDENT> except ConnectionError: <NEW_LINE> <INDENT> raise ConnectionError <NEW_LINE> <DEDENT> <DEDENT> def logout_gb(self): <NEW_LINE> <INDENT> self.connect.close() | Connect to GeekBrains with login and password. | 62598f9d97e22403b383acd9 |
class Pype: <NEW_LINE> <INDENT> def __init__(self, abspath: str, filename: str, plugin_name: str): <NEW_LINE> <INDENT> self.name = sub(r'\.py$', '', filename) <NEW_LINE> self.doc = self.__get_module_docstring(abspath) <NEW_LINE> self.abspath = abspath <NEW_LINE> self.plugin_name = plugin_name <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __get_module_docstring(filepath: str) -> str: <NEW_LINE> <INDENT> co = compile(open(filepath).read(), filepath, 'exec') <NEW_LINE> if co.co_consts and isinstance(co.co_consts[0], str): <NEW_LINE> <INDENT> return co.co_consts[0] <NEW_LINE> <DEDENT> return NOT_DOCUMENTED_YET | Data structure defining a pype. | 62598f9d3d592f4c4edbac9b |
class ComparableMixin(object): <NEW_LINE> <INDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return other >= self._cmpkey() <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return other > self._cmpkey() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return other == self._cmpkey() <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> return other < self._cmpkey() <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return other <= self._cmpkey() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return other != self._cmpkey() | Mixin class to allow comparing to other objects which are comparable. | 62598f9d8e7ae83300ee8e6c |
class LinearTransform: <NEW_LINE> <INDENT> def __init__(self, n_dims, n_hidden_dims, use_identity=False, normalize=False, A=None, theta_0=None, dummy=False): <NEW_LINE> <INDENT> self.n_dims = n_dims <NEW_LINE> self.n_hidden_dims = n_hidden_dims <NEW_LINE> self.use_identity = use_identity <NEW_LINE> self.normalize = normalize <NEW_LINE> if self.use_identity or dummy: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.A = A <NEW_LINE> self.theta_0 = theta_0 <NEW_LINE> if self.A is None: <NEW_LINE> <INDENT> self.A = torch.zeros([self.n_dims, self.n_hidden_dims], dtype=t_type, device=device) <NEW_LINE> self.A.uniform_(-1., 1.) <NEW_LINE> if self.normalize: <NEW_LINE> <INDENT> self.A = torch.tensor(orth(self.A.data.cpu().numpy()), dtype=t_type, device=device) <NEW_LINE> <DEDENT> <DEDENT> if self.theta_0 is None: <NEW_LINE> <INDENT> self.theta_0 = torch.zeros([self.n_dims, 1], dtype=t_type, device=device) <NEW_LINE> self.theta_0.uniform_(-1., 1.) <NEW_LINE> <DEDENT> self.AtA = torch.matmul(self.A.t(), self.A) <NEW_LINE> self.AtA_1 = torch.inverse(self.AtA) <NEW_LINE> self.inverse_base = torch.matmul(self.AtA_1, self.A.t()) <NEW_LINE> <DEDENT> def transform(self, theta, n_particles_second=True): <NEW_LINE> <INDENT> if self.use_identity: <NEW_LINE> <INDENT> return theta <NEW_LINE> <DEDENT> if n_particles_second: <NEW_LINE> <INDENT> return torch.matmul(self.A, theta) + self.theta_0 <NEW_LINE> <DEDENT> return (torch.matmul(self.A, theta.t()) + self.theta_0).t() <NEW_LINE> <DEDENT> def inverse_transform(self, theta, n_particles_second=True): <NEW_LINE> <INDENT> if self.use_identity: <NEW_LINE> <INDENT> return theta <NEW_LINE> <DEDENT> if n_particles_second: <NEW_LINE> <INDENT> return torch.matmul(self.inverse_base, theta - self.theta_0) <NEW_LINE> <DEDENT> return torch.matmul(self.inverse_base, theta.t() - self.theta_0).t() <NEW_LINE> <DEDENT> def project_inverse(self, theta, n_particles_second=True): <NEW_LINE> <INDENT> if self.use_identity: <NEW_LINE> <INDENT> return theta <NEW_LINE> <DEDENT> if n_particles_second: <NEW_LINE> <INDENT> return torch.matmul(self.inverse_base, theta) <NEW_LINE> <DEDENT> return torch.matmul(theta, self.inverse_base.t()) <NEW_LINE> <DEDENT> def state_dict(self, destination=None, prefix='', keep_vars=False): <NEW_LINE> <INDENT> if destination is None: <NEW_LINE> <INDENT> destination = OrderedDict() <NEW_LINE> destination._metadata = OrderedDict() <NEW_LINE> <DEDENT> destination._metadata[prefix[:-1]] = dict(version=1) <NEW_LINE> destination[prefix + 'A'] = self.A if keep_vars else self.A.data <NEW_LINE> destination[prefix + 'theta_0'] = self.theta_0 if keep_vars else self.theta_0.data <NEW_LINE> destination[prefix + 'n_dims'] = self.n_dims <NEW_LINE> destination[prefix + 'n_hidden_dims'] = self.n_hidden_dims <NEW_LINE> destination[prefix + 'use_identity'] = self.use_identity <NEW_LINE> destination[prefix + 'normalize'] = self.normalize <NEW_LINE> return destination <NEW_LINE> <DEDENT> def load_state_dict(self, state_dict, prefix=''): <NEW_LINE> <INDENT> self.__init__(state_dict[prefix + 'n_dims'], state_dict[prefix + 'n_hidden_dims'], state_dict[prefix + 'use_identity'], state_dict[prefix + 'normalize'], state_dict[prefix + 'A'], state_dict[prefix + 'theta_0'], dummy=False ) | Class for various linear transformations | 62598f9d91f36d47f2230d86 |
class RubyFixnum(RubyVALUE): <NEW_LINE> <INDENT> _type = RUBY_T_FIXNUM <NEW_LINE> def proxyval(self, visited): <NEW_LINE> <INDENT> return self.as_address() >> 1 | Class wrapping a gdb.Value that is a Fixnum | 62598f9d0a50d4780f7051a6 |
class AsyncTaskHandler: <NEW_LINE> <INDENT> sender = None <NEW_LINE> def get_host_from_task(self, sender): <NEW_LINE> <INDENT> self.sender = sender <NEW_LINE> value = base_settings.EOX_TENANT_ASYNC_TASKS_HANDLER_DICT.get(sender, 'tenant_from_sync_process') <NEW_LINE> action = getattr(self, value) <NEW_LINE> return action() <NEW_LINE> <DEDENT> def get_host_from_siteid(self): <NEW_LINE> <INDENT> def get_host(body): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> siteid = body.get('args')[0] <NEW_LINE> site = Site.objects.get(id=siteid) <NEW_LINE> domain = site.name <NEW_LINE> <DEDENT> except (Site.DoesNotExist, KeyError, TypeError): <NEW_LINE> <INDENT> return self.tenant_from_sync_process()(body) <NEW_LINE> <DEDENT> return domain <NEW_LINE> <DEDENT> return get_host <NEW_LINE> <DEDENT> def tenant_from_sync_process(self): <NEW_LINE> <INDENT> host = getattr(base_settings, 'EDNX_TENANT_DOMAIN', None) <NEW_LINE> if not host: <NEW_LINE> <INDENT> LOG.warning( "Could not find the host information for eox_tenant.signals " "for the task {sender}".format(sender=self.sender) ) <NEW_LINE> <DEDENT> def get_host(_body): <NEW_LINE> <INDENT> return host <NEW_LINE> <DEDENT> return get_host | Handler used to get the tenant of an async task. | 62598f9d6e29344779b00429 |
class PadAuthorTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.server = PadServer.objects.create( title=TS['title'], url=TS['url'], apikey=TS['apikey'] ) <NEW_LINE> self.user = User.objects.create(username='jdoe') <NEW_LINE> self.group = Group.objects.create(name='does') <NEW_LINE> self.padGroup = PadGroup.objects.create( group=self.group, server=self.server ) <NEW_LINE> self.author = PadAuthor.objects.create( user=self.user, server=self.server ) <NEW_LINE> <DEDENT> def testBasics(self): <NEW_LINE> <INDENT> self.assertTrue(isinstance(self.author, PadAuthor)) <NEW_LINE> self.assertEqual(self.author.__str__(), self.user.__str__()) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.padGroup.delete() | Test cases for the Author model
| 62598f9d435de62698e9bbc1 |
class APIHandler(BaseHandler, JSendMixin): <NEW_LINE> <INDENT> def initialize(self): <NEW_LINE> <INDENT> self.set_header("Content-Type", "application/json") <NEW_LINE> <DEDENT> def write_error(self, status_code, **kwargs): <NEW_LINE> <INDENT> def get_exc_message(exception): <NEW_LINE> <INDENT> return exception.log_message if hasattr(exception, "log_message") else str(exception) <NEW_LINE> <DEDENT> self.clear() <NEW_LINE> self.set_status(status_code) <NEW_LINE> exception = kwargs["exc_info"][1] <NEW_LINE> if any(isinstance(exception, c) for c in [APIError, ValidationError]): <NEW_LINE> <INDENT> if isinstance(exception, ValidationError): <NEW_LINE> <INDENT> self.set_status(400) <NEW_LINE> <DEDENT> self.fail(get_exc_message(exception)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.error( message=self._reason, data=get_exc_message(exception) if self.settings.get("debug") else None, code=status_code ) | RequestHandler for API calls
- Sets header as ``application/json``
- Provides custom write_error that writes error back as JSON rather than as the standard HTML template | 62598f9d01c39578d7f12b4b |
class GenericNoteClear(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "node.generic_note_clear" <NEW_LINE> bl_label = "Clear" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> node = context.node <NEW_LINE> node.clear() <NEW_LINE> return {'FINISHED'} | Clear Note Node | 62598f9d91af0d3eaad39bd8 |
class ListPostsInputSet(InputSet): <NEW_LINE> <INDENT> def set_Cursor(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Cursor', value) <NEW_LINE> <DEDENT> def set_Included(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Included', value) <NEW_LINE> <DEDENT> def set_Limit(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Limit', value) <NEW_LINE> <DEDENT> def set_Order(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Order', value) <NEW_LINE> <DEDENT> def set_PublicKey(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'PublicKey', value) <NEW_LINE> <DEDENT> def set_Related(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Related', value) <NEW_LINE> <DEDENT> def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ResponseFormat', value) <NEW_LINE> <DEDENT> def set_SinceID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'SinceID', value) <NEW_LINE> <DEDENT> def set_UserID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'UserID', value) <NEW_LINE> <DEDENT> def set_Username(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Username', value) | An InputSet with methods appropriate for specifying the inputs to the ListPosts
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 62598f9d596a897236127a4d |
class Ip(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.b_key = "ip" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.oper = {} <NEW_LINE> self.router = {} <NEW_LINE> self.ospf = {} <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value) | This class does not support CRUD Operations please use parent.
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` | 62598f9d8c0ade5d55dc3576 |
class Article: <NEW_LINE> <INDENT> def __init__(self, shop=None): <NEW_LINE> <INDENT> self.name = "" <NEW_LINE> self.brand = "" <NEW_LINE> self.articlenr = "" <NEW_LINE> self.ordernr = "" <NEW_LINE> self.price = None <NEW_LINE> self.url = "" <NEW_LINE> self.shop = shop <NEW_LINE> self.units = 1 <NEW_LINE> self.properties = {} <NEW_LINE> self.description = "" <NEW_LINE> self.image_url = "" <NEW_LINE> self.image = None <NEW_LINE> self.visible = True <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Article object " + "name=%s" % self.name + (", brand=%s" % self.brand if self.brand is not "" else "") + (", shop=%s" % self.shop.name if self.shop is not None else "") + (", price=%s" % "%.2f" % self.price if self.price is not None else "") + ">" | Contains imformation about an Article.
:ivar name: (basestring) name of the article
:ivar articlenr: (basestring) article number
:ivar shop: (AbstractShop) reference to the shop
:ivar brand: (basestring) name of the brand
:ivar image_url: (basestring) url to the article image
:ivar price: (float) price of the article
:ivar units: (int) number of units in one package
:ivar QPixmap image: image of the article | 62598f9d56ac1b37e6301fb8 |
class Plugin(object): <NEW_LINE> <INDENT> def data_available(self, device_sn, format, files): <NEW_LINE> <INDENT> pass | A plugin receives notifications when new data
is available, it can consume the data or transform it.
TCX file generation, and garmin connect upload are
both implementations of plugin. You can implement
your own to produce new file formats or upload somewhere. | 62598f9d009cb60464d012f3 |
class Font(object): <NEW_LINE> <INDENT> def __init__(self, existing_font=None, preset=None): <NEW_LINE> <INDENT> self._ff_messages = [] <NEW_LINE> if existing_font: <NEW_LINE> <INDENT> with self._captures_messages(): <NEW_LINE> <INDENT> self._ff = fontforge.open(existing_font) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._ff = fontforge.font() <NEW_LINE> self.name = DEFAULT_FONT_NAME <NEW_LINE> self.family = DEFAULT_FAMILY_NAME <NEW_LINE> self.postscript_name = DEFAULT_POSTSCRIPT_NAME <NEW_LINE> self.apply_preset(preset or DefaultPreset) <NEW_LINE> <DEDENT> self.closed = False <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len([i for i in self.glyphs]) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @contextmanager <NEW_LINE> def session(cls, *args, **kwargs): <NEW_LINE> <INDENT> font = cls(*args, **kwargs) <NEW_LINE> yield font <NEW_LINE> font.close() <NEW_LINE> font._ff = Null <NEW_LINE> <DEDENT> @contextmanager <NEW_LINE> def _captures_messages(self): <NEW_LINE> <INDENT> capture = py.io.StdCaptureFD() <NEW_LINE> yield <NEW_LINE> out, err = capture.reset() <NEW_LINE> if out or err: <NEW_LINE> <INDENT> self._ff_messages.append((out, err)) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def fontforge_instance(self): <NEW_LINE> <INDENT> return self._ff <NEW_LINE> <DEDENT> @property <NEW_LINE> def fontforge_messages(self): <NEW_LINE> <INDENT> return self._ff_messages <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.closed = True <NEW_LINE> self._ff.close() <NEW_LINE> <DEDENT> def apply_preset(self, preset): <NEW_LINE> <INDENT> for attr, val in preset.items(): <NEW_LINE> <INDENT> setattr(self._ff, attr, val) <NEW_LINE> <DEDENT> <DEDENT> def add_glyph(self, glyph_code, glyph_file, glyph_name=None): <NEW_LINE> <INDENT> if not isinstance(glyph_code, unicode): <NEW_LINE> <INDENT> raise GlyphCodeError('The glyph code must be unicode instance.') <NEW_LINE> <DEDENT> if not glyph_name: <NEW_LINE> <INDENT> glyph_name = hex(ord(glyph_code))[2:].upper() <NEW_LINE> <DEDENT> glyph = self._ff.createChar( ord(glyph_code), glyph_name ) <NEW_LINE> glyph.importOutlines(glyph_file) <NEW_LINE> glyph.left_side_bearing = 15 <NEW_LINE> glyph.right_side_bearing = 15 <NEW_LINE> return Glyph(glyph) <NEW_LINE> <DEDENT> def save(self, location): <NEW_LINE> <INDENT> with self._captures_messages(): <NEW_LINE> <INDENT> self._ff.generate(location) <NEW_LINE> <DEDENT> if not local(location).check(): <NEW_LINE> <INDENT> raise SaveFailed(location) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def postscript_name(self): <NEW_LINE> <INDENT> return self._ff.fontname <NEW_LINE> <DEDENT> @postscript_name.setter <NEW_LINE> def postscript_name(self, value): <NEW_LINE> <INDENT> self._ff.fontname = value.replace(' ', '') <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._ff.fullname <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, value): <NEW_LINE> <INDENT> self._ff.fullname = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def family(self): <NEW_LINE> <INDENT> return self._ff.familyname <NEW_LINE> <DEDENT> @family.setter <NEW_LINE> def family(self, value): <NEW_LINE> <INDENT> self._ff.familyname = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def style(self): <NEW_LINE> <INDENT> style = self.name.replace(self.family, '').strip() <NEW_LINE> return style or DEFAULT_STYLE <NEW_LINE> <DEDENT> @property <NEW_LINE> def glyphs(self): <NEW_LINE> <INDENT> for glyph in self._ff.glyphs(): <NEW_LINE> <INDENT> yield Glyph(glyph) | Main interface for working with the FontHammer API. | 62598f9d3eb6a72ae038a40e |
class DALStorage(dict): <NEW_LINE> <INDENT> def __getattr__(self, key): <NEW_LINE> <INDENT> return self[key] <NEW_LINE> <DEDENT> def __setattr__(self, key, value): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> raise SyntaxError( 'Object \'%s\'exists and cannot be redefined' % key) <NEW_LINE> <DEDENT> self[key] = value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<DALStorage ' + dict.__repr__(self) + '>' | a dictionary that let you do d['a'] as well as d.a | 62598f9d3c8af77a43b67e25 |
class SimpleFILO(list): <NEW_LINE> <INDENT> push = list.append <NEW_LINE> def is_empty(self): <NEW_LINE> <INDENT> return not bool(self) | Simple *first in, last out* stack implementation. | 62598f9d925a0f43d25e7e0b |
class IsOwner(BasePermission): <NEW_LINE> <INDENT> message = "You can not delete another user" <NEW_LINE> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> print(obj, request.user) <NEW_LINE> return obj == request.user | Custom permission to check if the user is owner of the object. | 62598f9d30dc7b766599f61b |
class Content(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "S3Bucket": (str, True), "S3Key": (str, True), "S3ObjectVersion": (str, False), } | `Content <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-layerversion-content.html>`__ | 62598f9da05bb46b3848a64d |
class NotificationList(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> notifications = Notification.objects.filter(receiver=Token.objects.get(key=self.request.META['HTTP_AUTHORIZATION'].split(' ', 1)[1]).user.id, unread=True).order_by('created_at') <NEW_LINE> for notification in notifications: <NEW_LINE> <INDENT> notification.unread = False <NEW_LINE> notification.save() <NEW_LINE> <DEDENT> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> return Response("Your API key is wrong or your records are corrupted.", status=status.HTTP_401_UNAUTHORIZED) <NEW_LINE> <DEDENT> serializer = NotificationSerializer(notifications, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.request.POST.set('sender', Token.objects.get(key=self.request.META['HTTP_AUTHORIZATION'].split(' ', 1)[1]).user.id) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> return Response("Your API key is wrong or your records are corrupted.", status=status.HTTP_401_UNAUTHORIZED) <NEW_LINE> <DEDENT> serializer = NotificationSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | Retrieve or insert notifications | 62598f9d10dbd63aa1c70984 |
class Selectable(ClauseElement): <NEW_LINE> <INDENT> __visit_name__ = 'selectable' | mark a class as being selectable | 62598f9d090684286d5935c1 |
class ConfigurationConformity(ModelSQL, CompanyValueMixin): <NEW_LINE> <INDENT> __name__ = 'account.configuration.default_account' <NEW_LINE> conformity_required = fields.Boolean('Conformity Required') <NEW_LINE> ensure_conformity = fields.Boolean('Ensure Conformity') | Account Configuration Default Account | 62598f9d596a897236127a4e |
class GameSetState(BaseState): <NEW_LINE> <INDENT> def __init__(self, *, machine): <NEW_LINE> <INDENT> super().__init__(machine=machine) <NEW_LINE> self._gameset_label = self.create_label('Game set!', font_size=100) <NEW_LINE> self._gameset_label.set_style('color', colors.GRAY1 + (255,)) <NEW_LINE> self._snd_gameset = self.sorcerer.create_sound( 'snd_gameset', file_name='Jingle_Win_00.wav' ) <NEW_LINE> self._player = pyglet.media.Player() <NEW_LINE> <DEDENT> def _go_back(self, dt): <NEW_LINE> <INDENT> if self._server is not None: <NEW_LINE> <INDENT> self._server._state = Scene.ST_BEGIN <NEW_LINE> <DEDENT> self.pop_until('game_begin') <NEW_LINE> <DEDENT> def on_begin(self): <NEW_LINE> <INDENT> if not self._player.playing: <NEW_LINE> <INDENT> self._player.queue(self._snd_gameset) <NEW_LINE> self._player.play() <NEW_LINE> <DEDENT> self.set_background_color(*colors.TURQUOISE) <NEW_LINE> pyglet.clock.schedule_once( self._go_back, self._snd_gameset.duration + 2 ) <NEW_LINE> <DEDENT> def on_update(self): <NEW_LINE> <INDENT> self._gameset_label.draw() | Game begin state | 62598f9dbe383301e02535c3 |
class AddLiveAppRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v1"): <NEW_LINE> <INDENT> super(AddLiveAppRequest, self).__init__( '/apps', 'POST', header, version) <NEW_LINE> self.parameters = parameters | 添加直播应用名
- 需要提前在应用(app)级别绑定功能模板时才需要提前新建应用名
- 新的应用名可以推流时自动创建
| 62598f9d1f5feb6acb1629f0 |
class Partitions_constraints(IntegerListsLex): <NEW_LINE> <INDENT> def __setstate__(self, data): <NEW_LINE> <INDENT> n = data['n'] <NEW_LINE> self.__class__ = Partitions_with_constraints <NEW_LINE> constraints = {'max_slope' : 0, 'min_part' : 1} <NEW_LINE> constraints.update(data['constraints']) <NEW_LINE> self.__init__(n, **constraints) | For unpickling old constrained ``Partitions_constraints`` objects created
with sage <= 3.4.1. See :class:`Partitions`. | 62598f9d498bea3a75a578ef |
class EntryLevel(IntEnum): <NEW_LINE> <INDENT> CREATED = auto() <NEW_LINE> INITIALIZED = auto() <NEW_LINE> PRIMED = auto() <NEW_LINE> CACHED = auto() | Represents the level of progress we've made on a TaskRunnerEntry's TaskState.
There are four levels of progress (in order):
1. CREATED: The TaskState exists but not much work has been done on it.
2. INITIALIZED: The TaskState's initialize() method has been called. At this point
all of the task's dependencies are guaranteed to have provenance digests
available, which means we can attempt to load its value from the persistent
cache.
3. PRIMED: If the TaskState's value is persistable, this is equivalent to CACHED;
otherwise it's equivalent to INITIALIZED. This abstract definition is useful
because it guarantees two things:
a. The task's provenance digest is available, which means any downstream tasks
can have their values loaded from the persisted cache. For a task with
non-persistable output, its provenance digest depends only on its
provenance; it doesn't actually require the task to be computed. However,
for a task with persistable output, the provenance digest depends on its
actual value, so the task must be computed and its output cached.
b. There is no additional *persistable* work to do on this task. In other words,
if we have any dependent tasks that we plan to run in a separate process,
we can go ahead and start them; there may be more work to do on this
task, but it will have to be done in that separate process, because its
results can't be serialized and transmitted. (On the other hand, if we
have a dependent task to run *in this same process*, we'll want to bring
this task to the CACHED level instead.) As with (a), for a task with
non-persistable output, this milestone is reached as soon as we compute
its provenance; for a task with persistable output, it's reached only
when the task is computed and its output is cached.
4. CACHED: The task has been computed and its output value is stored somewhere --
in the persistent cache, in memory on the TaskState, and/or in memory on this
entry (depending on the cache settings). This is the final level: after this,
there is no more work to do on this task.
Normally an entry will only make forward progress through these levels; however,
we do sometimes evict temporarily-memoized values, which can cause an entry to
regress from CACHED to PRIMED. | 62598f9dd53ae8145f91825c |
class Combo(models.Model): <NEW_LINE> <INDENT> combo = models.ForeignKey(Products, related_name="combo_combo_id", on_delete=models.CASCADE) <NEW_LINE> product = models.ForeignKey(Products, related_name="quantity", on_delete=models.CASCADE) <NEW_LINE> quantity = models.IntegerField() | This model is to add extra field - quantity to the many to many relationship
of combos with products. | 62598f9d55399d3f056262f0 |
class OAuth2Reddit(BaseReddit): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(OAuth2Reddit, self).__init__(*args, **kwargs) <NEW_LINE> self.client_id = self.config.client_id <NEW_LINE> self.client_secret = self.config.client_secret <NEW_LINE> self.redirect_uri = self.config.redirect_uri <NEW_LINE> <DEDENT> def _handle_oauth_request(self, data): <NEW_LINE> <INDENT> auth = (self.client_id, self.client_secret) <NEW_LINE> url = self.config['access_token_url'] <NEW_LINE> response = self._request(url, auth=auth, data=data, raw_response=True) <NEW_LINE> if not response.ok: <NEW_LINE> <INDENT> msg = 'Unexpected OAuthReturn: {0}'.format(response.status_code) <NEW_LINE> raise errors.OAuthException(msg, url) <NEW_LINE> <DEDENT> retval = response.json() <NEW_LINE> if 'error' in retval: <NEW_LINE> <INDENT> error = retval['error'] <NEW_LINE> if error == 'invalid_grant': <NEW_LINE> <INDENT> raise errors.OAuthInvalidGrant(error, url) <NEW_LINE> <DEDENT> raise errors.OAuthException(retval['error'], url) <NEW_LINE> <DEDENT> return retval <NEW_LINE> <DEDENT> @decorators.require_oauth <NEW_LINE> def get_access_information(self, code): <NEW_LINE> <INDENT> data = {'code': code, 'grant_type': 'authorization_code', 'redirect_uri': self.redirect_uri} <NEW_LINE> retval = self._handle_oauth_request(data) <NEW_LINE> return {'access_token': retval['access_token'], 'refresh_token': retval.get('refresh_token'), 'scope': set(retval['scope'].split(' '))} <NEW_LINE> <DEDENT> @decorators.require_oauth <NEW_LINE> def get_authorize_url(self, state, scope='identity', refreshable=False): <NEW_LINE> <INDENT> params = {'client_id': self.client_id, 'response_type': 'code', 'redirect_uri': self.redirect_uri, 'state': state, 'scope': _to_reddit_list(scope)} <NEW_LINE> params['duration'] = 'permanent' if refreshable else 'temporary' <NEW_LINE> request = Request('GET', self.config['authorize'], params=params) <NEW_LINE> return request.prepare().url <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_oauth_app_info(self): <NEW_LINE> <INDENT> return all((self.client_id is not None, self.client_secret is not None, self.redirect_uri is not None)) <NEW_LINE> <DEDENT> @decorators.require_oauth <NEW_LINE> def refresh_access_information(self, refresh_token): <NEW_LINE> <INDENT> data = {'grant_type': 'refresh_token', 'redirect_uri': self.redirect_uri, 'refresh_token': refresh_token} <NEW_LINE> retval = self._handle_oauth_request(data) <NEW_LINE> return {'access_token': retval['access_token'], 'refresh_token': refresh_token, 'scope': set(retval['scope'].split(' '))} <NEW_LINE> <DEDENT> def set_oauth_app_info(self, client_id, client_secret, redirect_uri): <NEW_LINE> <INDENT> self.client_id = client_id <NEW_LINE> self.client_secret = client_secret <NEW_LINE> self.redirect_uri = redirect_uri | Provides functionality for obtaining reddit OAuth2 access tokens.
You should **not** directly instantiate instances of this class. Use
:class:`.Reddit` instead. | 62598f9dac7a0e7691f722da |
class RequestLoggingMiddleware(object): <NEW_LINE> <INDENT> def process_response(self, request, response): <NEW_LINE> <INDENT> content_type = response['Content-Type'] <NEW_LINE> if not any(x in content_type for x in TYPES.values()): <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> def get_meta(prop): <NEW_LINE> <INDENT> return request.META.get(prop, '') <NEW_LINE> <DEDENT> def try_loads(string, default): <NEW_LINE> <INDENT> if TYPES['JSON'] not in content_type: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return json.loads(string) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> <DEDENT> request_data = { 'status': response.status_code, 'content_length': get_meta('CONTENT_LENGTH'), 'user_agent': get_meta('HTTP_USER_AGENT').decode('utf-8', 'replace'), 'body': try_loads(request.body, ''), 'response': try_loads(response.content, response.content), 'request_headers': dict([(key, val) for key, val in request.META.items() if key.isupper()]), 'response_headers': dict([(key.upper().replace('-', '_'), val) for key, val in response.items()]), 'hostname': get_meta('HTTP_X_FORWARDED_HOST'), 'name': 'Request Log', 'time': IMLDateTime.utcnow().isoformat(), 'v': 0, 'pid': os.getpid(), 'msg': 'Request made to {0} {1}'.format(request.method, request.get_full_path()), 'level': settings.LOG_LEVEL + 10, } <NEW_LINE> logger.debug(json.dumps(request_data)) <NEW_LINE> return response | When the log level is in debug mode it should log all request / response pairs.
If the log level is > DEBUG it does not log the request, response body or their headers. | 62598f9df8510a7c17d7e05f |
class NodeAdmin(object): <NEW_LINE> <INDENT> def __init__(self, name=None, css=None, host=None, port=None, wmgrSecretFile=None): <NEW_LINE> <INDENT> if name: <NEW_LINE> <INDENT> if not css: <NEW_LINE> <INDENT> raise ValueError('css has to be specified if name is used') <NEW_LINE> <DEDENT> params = css.getNodeParams(name) <NEW_LINE> self.host = params.host <NEW_LINE> if not self.host: <NEW_LINE> <INDENT> raise _Exception(_Exception.CSS_HOST_NAME_MISS, "node=" + name) <NEW_LINE> <DEDENT> self.port = params.port <NEW_LINE> self._name = name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not (host and port): <NEW_LINE> <INDENT> raise _Exception(_Exception.ARG_ERR, 'either name or host/port has to be provided') <NEW_LINE> <DEDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self._name = host + ':' + str(port) <NEW_LINE> <DEDENT> self.wmgrSecretFile = wmgrSecretFile <NEW_LINE> self.client = None <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def wmgrClient(self): <NEW_LINE> <INDENT> if self.client is None: <NEW_LINE> <INDENT> self.client = WmgrClient(self.host, self.port, secretFile=self.wmgrSecretFile) <NEW_LINE> <DEDENT> return self.client | Class representing administration/communication endpoint for qserv worker. | 62598f9d7cff6e4e811b57f1 |
class Solution(object): <NEW_LINE> <INDENT> def longestCommonPrefix(self, strs): <NEW_LINE> <INDENT> if len(strs) == 0: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> commonStr = strs[0] <NEW_LINE> for s in strs[1:]: <NEW_LINE> <INDENT> for i in range(len(commonStr),-1, -1): <NEW_LINE> <INDENT> if s.startswith(commonStr[0:i]): <NEW_LINE> <INDENT> commonStr = commonStr[0:i] <NEW_LINE> break <NEW_LINE> <DEDENT> commonStr = commonStr[0:i] <NEW_LINE> <DEDENT> if commonStr == "": <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return commonStr | Intro | 62598f9d45492302aabfc2a7 |
class FailoverInstanceRequest(_messages.Message): <NEW_LINE> <INDENT> class DataProtectionModeValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> DATA_PROTECTION_MODE_UNSPECIFIED = 0 <NEW_LINE> LIMITED_DATA_LOSS = 1 <NEW_LINE> FORCE_DATA_LOSS = 2 <NEW_LINE> <DEDENT> dataProtectionMode = _messages.EnumField('DataProtectionModeValueValuesEnum', 1) | Request for Failover.
Enums:
DataProtectionModeValueValuesEnum: Optional. Available data protection
modes that the user can choose. If it's unspecified, data protection
mode will be LIMITED_DATA_LOSS by default.
Fields:
dataProtectionMode: Optional. Available data protection modes that the
user can choose. If it's unspecified, data protection mode will be
LIMITED_DATA_LOSS by default. | 62598f9d4a966d76dd5eecb0 |
class CinemaModel(models.Model): <NEW_LINE> <INDENT> created = models.DateTimeField( 'created at', auto_now_add=True, help_text='Date time on which the objetc was created' ) <NEW_LINE> modified = models.DateTimeField( 'modified at', auto_now=True, help_text='Date time on which the objetc was last modified' ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> get_latest_by = 'created' <NEW_LINE> ordering = ['-created', '-modified'] | All our models inherit it of this class
The CinemaModel use a abstract method, that mean that is a base
model and not a table in data base.
the following class have functions of Created at and updated at. | 62598f9d44b2445a339b6854 |
class Bunch(HasDynamicProperties): <NEW_LINE> <INDENT> def __init__(self, **kwds): <NEW_LINE> <INDENT> self.__dict__.update(kwds) <NEW_LINE> <DEDENT> def dict(self): <NEW_LINE> <INDENT> return self.__dict__ <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> return self.__dict__.get(key, default) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.__dict__) <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return self.__dict__.items() <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return self.__dict__.keys() <NEW_LINE> <DEDENT> def values(self): <NEW_LINE> <INDENT> return self.__dict__.values() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"{self.__dict__}" <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return bool(self.__dict__) <NEW_LINE> <DEDENT> __nonzero__ = __bool__ <NEW_LINE> def __setitem__(self, k, v): <NEW_LINE> <INDENT> self.__dict__.__setitem__(k, v) <NEW_LINE> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return item in self.__dict__ | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308
Often we want to just collect a bunch of stuff together, naming each item of
the bunch; a dictionary's OK for that, but a small do-nothing class is even handier, and prettier to use. | 62598f9d6e29344779b0042b |
class TmuxScripter: <NEW_LINE> <INDENT> def __init__( self, session: str, defaultSessionPath: str, detach: bool = True ) -> "TmuxScripter": <NEW_LINE> <INDENT> self.session_name = session <NEW_LINE> self.start_dir = defaultSessionPath <NEW_LINE> self.detach = detach <NEW_LINE> self.windows = [] <NEW_LINE> self.layout_id = "" <NEW_LINE> self.layout = "" <NEW_LINE> self.window_width = 0 <NEW_LINE> self.window_height = 0 <NEW_LINE> self.builder = None <NEW_LINE> self.commands = "" <NEW_LINE> self.injected_width = None <NEW_LINE> self.injected_height = None <NEW_LINE> <DEDENT> def set_terminal_size(self, width: int, height: int) -> "TmuxScripter": <NEW_LINE> <INDENT> self.injected_width = width <NEW_LINE> self.injected_height = height <NEW_LINE> return self <NEW_LINE> <DEDENT> def analyze(self, window_list: str) -> None: <NEW_LINE> <INDENT> self.parse_windows(window_list) <NEW_LINE> ObjectTracker().reset() <NEW_LINE> self.create_builder() <NEW_LINE> self.commands = self.build_commands() <NEW_LINE> <DEDENT> def parse_windows(self, layout_string: str) -> None: <NEW_LINE> <INDENT> windows_data = layout_string.split("\n") <NEW_LINE> if "" in windows_data: <NEW_LINE> <INDENT> windows_data.remove("") <NEW_LINE> <DEDENT> num = 0 <NEW_LINE> for data in windows_data: <NEW_LINE> <INDENT> window = Window("win" + str(num), "TBD", num == 0) <NEW_LINE> window.set_session_name(self.session_name) <NEW_LINE> window.set_start_dir(self.start_dir) <NEW_LINE> window.set_number(num) <NEW_LINE> window.load_from_layout(data) <NEW_LINE> self.windows.append(window) <NEW_LINE> num += 1 <NEW_LINE> <DEDENT> <DEDENT> def create_builder(self): <NEW_LINE> <INDENT> self.builder = TmuxBuilder(self.session_name, self.start_dir, self.detach) <NEW_LINE> if self.injected_width and self.injected_height: <NEW_LINE> <INDENT> self.builder.set_terminal_size(self.injected_width, self.injected_height) <NEW_LINE> <DEDENT> for window in self.windows: <NEW_LINE> <INDENT> first_pane = True <NEW_LINE> for pane in window.panes: <NEW_LINE> <INDENT> if first_pane: <NEW_LINE> <INDENT> self.builder.add_window( window.identity, pane.identity, window.name, window.panes[0].start_dir, ) <NEW_LINE> first_pane = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.builder.add_pane( pane.identity, pane.direction, window.identity, pane.split_from, pane.start_dir, ) <NEW_LINE> if hasattr(pane, "parent_number"): <NEW_LINE> <INDENT> self.builder.set_pane_parent(pane.parent_number) <NEW_LINE> <DEDENT> <DEDENT> self.builder.set_pane_height(pane.height).set_pane_width( pane.width ).run_command(pane.command) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_builder(self) -> TmuxBuilder: <NEW_LINE> <INDENT> return self.builder <NEW_LINE> <DEDENT> def build_commands(self) -> str: <NEW_LINE> <INDENT> if not self.builder: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> return self.builder.build() | Responsible for creating commands to recreate an existing tmux session | 62598f9d9c8ee82313040055 |
class RGBTest(Lightshow): <NEW_LINE> <INDENT> def init_parameters(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def check_runnable(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> blend_whole_strip_to_color(self.strip, (255, 0, 0), fadetime_sec=0) <NEW_LINE> self.sleep(10) <NEW_LINE> blend_whole_strip_to_color(self.strip, (0, 255, 0), fadetime_sec=0) <NEW_LINE> self.sleep(10) <NEW_LINE> blend_whole_strip_to_color(self.strip, (0, 0, 255), fadetime_sec=0) <NEW_LINE> self.sleep(10) <NEW_LINE> blend_whole_strip_to_color(self.strip, (255, 255, 255), fadetime_sec=0) <NEW_LINE> self.sleep(10) <NEW_LINE> self.strip.clear_strip() <NEW_LINE> self.sleep(5) | turns on all red, then all green, then all blue leds and then all together
No parameters necessary | 62598f9d07f4c71912baf21a |
class EnumerationField(Field): <NEW_LINE> <INDENT> def __init__(self, field, mapping, required=False, default=None): <NEW_LINE> <INDENT> if not isinstance(mapping, dict): <NEW_LINE> <INDENT> raise exceptions.InvalidInputError( error="%s initializer must be a " "dict" % self.__class__.__name__) <NEW_LINE> <DEDENT> super(EnumerationField, self).__init__( field, required=required, default=default, converter=mapping.get) | Enumerated field of a JSON object.
:param field: JSON field to fetch the value from.
:param mapping: a `dict` to look up mapped values at.
:param required: whether this field is required. Missing required
fields result in MissingAttributeError.
:param default: the default value to use when the field is missing. | 62598f9dbaa26c4b54d4f07c |
class AmiiboMasterKey: <NEW_LINE> <INDENT> KEY_FMT = '=16s14sBB16s32s' <NEW_LINE> DATA_BIN_SHA256_HEXDIGEST = '868106135941cbcab3552bd14880a7a34304ef340958a6998b61a38ba3ce13d3' <NEW_LINE> TAG_BIN_SHA256_HEXDIGEST = 'b48727797cd2548200b99c665b20a78190470163ccb8e5682149f1b2f7a006cf' <NEW_LINE> def __init__(self, data, sha256_digest): <NEW_LINE> <INDENT> count = len(data) <NEW_LINE> if count != 80: <NEW_LINE> <INDENT> raise ValueError('Data is {} bytes (should be 80).'.format(count)) <NEW_LINE> <DEDENT> digest = sha256(data).hexdigest() <NEW_LINE> if digest != sha256_digest: <NEW_LINE> <INDENT> raise ValueError( ( 'Data failed check, may be corrupt\n' '{} != {}' ).format(digest, sha256_digest)) <NEW_LINE> <DEDENT> ( self.hmac_key, self.type_string, self.rfu, self.magic_size, self.magic_bytes, self.xor_pad ) = unpack(self.KEY_FMT, data) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_separate_bin(cls, data_bin, tag_bin): <NEW_LINE> <INDENT> data = cls(data_bin, cls.DATA_BIN_SHA256_HEXDIGEST) <NEW_LINE> tag = cls(tag_bin, cls.TAG_BIN_SHA256_HEXDIGEST) <NEW_LINE> return data, tag <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_separate_hex(cls, data_str, tag_str): <NEW_LINE> <INDENT> return cls.from_separate_bin( bytes.fromhex(data_str), bytes.fromhex(tag_str)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_combined_bin(cls, combined_bin): <NEW_LINE> <INDENT> count = len(combined_bin) <NEW_LINE> if count != 160: <NEW_LINE> <INDENT> raise ValueError('Data is {} bytes (should be 160).'.format(count)) <NEW_LINE> <DEDENT> return cls.from_separate_bin(combined_bin[:80], combined_bin[80:]) | Helper class to validate and unpack crypto master keys.
The keys are commonly called ``unfixed-info.bin`` (data key) and
``locked-secret.bin`` (tag key). | 62598f9d56b00c62f0fb2680 |
class NopMapper(BinMapper): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(NopMapper,self).__init__() <NEW_LINE> self.nbins = 1 <NEW_LINE> self.labels = ['nop'] <NEW_LINE> <DEDENT> def assign(self, coords, mask=None, output=None): <NEW_LINE> <INDENT> if output is None: <NEW_LINE> <INDENT> output = numpy.zeros((len(coords),), dtype=index_dtype) <NEW_LINE> <DEDENT> if mask is None: <NEW_LINE> <INDENT> mask = numpy.ones((len(coords),), dtype=numpy.bool_) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mask = numpy.require(mask, dtype=numpy.bool_) <NEW_LINE> <DEDENT> output[mask] = 0 | Put everything into one bin. | 62598f9d91af0d3eaad39bda |
class Ta1ThroughputSection(section.Ta1Section): <NEW_LINE> <INDENT> def _store_query_throughput_table(self): <NEW_LINE> <INDENT> constraint_list = self._config.get_constraint_list(throughput=True) <NEW_LINE> categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT), (t1s.DBP_TABLENAME, t1s.DBP_TESTCASEID)], constraint_list=constraint_list) <NEW_LINE> throughput_table = latex_classes.LatexTable( "Query Throughputs", "thru_main", ["DBNR", "DBRS", "Select", "Query Type", "testcase", "count", "throughput"]) <NEW_LINE> for (dbnr, dbrs, selection_cols, query_cat, tcid) in categories: <NEW_LINE> <INDENT> inp = t1ai.Input() <NEW_LINE> inp[t1s.DBF_CAT] = query_cat <NEW_LINE> inp[t1s.DBF_NUMRECORDS] = dbnr <NEW_LINE> inp[t1s.DBF_RECORDSIZE] = dbrs <NEW_LINE> inp[t1s.DBP_SELECTIONCOLS] = selection_cols <NEW_LINE> this_constraint_list = constraint_list + inp.get_constraint_list() + [ (t1s.DBP_TABLENAME, t1s.DBP_TESTCASEID, tcid)] <NEW_LINE> [starttimes, endtimes] = self._config.results_db.get_query_values( simple_fields=[(t1s.DBP_TABLENAME, t1s.DBP_SENDTIME), (t1s.DBP_TABLENAME, t1s.DBP_RESULTSTIME)], constraint_list=this_constraint_list) <NEW_LINE> numqueries = len(starttimes) <NEW_LINE> assert len(endtimes) == numqueries <NEW_LINE> starttime = min(starttimes) <NEW_LINE> endtime = max(endtimes) <NEW_LINE> duration = endtime - starttime <NEW_LINE> if numqueries > 0: <NEW_LINE> <INDENT> throughput = numqueries / duration <NEW_LINE> throughput_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, tcid, str(numqueries), str(round(throughput, 3))]) <NEW_LINE> <DEDENT> <DEDENT> self._outp["query_throughput_table"] = throughput_table.get_string() <NEW_LINE> <DEDENT> def _populate_output(self): <NEW_LINE> <INDENT> self._store_query_throughput_table() | The throughput section of the TA1 report | 62598f9d596a897236127a4f |
class StatusHistory(): <NEW_LINE> <INDENT> EPOCH_TIME = 1452556800 <NEW_LINE> START_TIME = int(time.time()) <NEW_LINE> def __init__(self, uid): <NEW_LINE> <INDENT> with open("log/{uid}.txt".format(uid=uid)) as f: <NEW_LINE> <INDENT> self.activity = self.parse_status(map(str.strip, f.readlines())) <NEW_LINE> <DEDENT> <DEDENT> def create_time_map(self, status_list): <NEW_LINE> <INDENT> status_map = {} <NEW_LINE> for item in status_list: <NEW_LINE> <INDENT> status_map[int(float(item["time"]))] = item["status"] <NEW_LINE> <DEDENT> return status_map <NEW_LINE> <DEDENT> def parse_status(self, lines): <NEW_LINE> <INDENT> activity = [] <NEW_LINE> seen_times = set() <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> time, fields = line.split("|") <NEW_LINE> if time not in seen_times: <NEW_LINE> <INDENT> seen_times.add(time) <NEW_LINE> status_obj = status.Status(int(float(time)), fields) <NEW_LINE> activity.append(status_obj) <NEW_LINE> <DEDENT> <DEDENT> return activity <NEW_LINE> <DEDENT> def get_status(self, time): <NEW_LINE> <INDENT> idx = bisect.bisect(self.activity, time) <NEW_LINE> current_status = self.activity[max(0, idx - 1)] <NEW_LINE> return current_status <NEW_LINE> <DEDENT> def normalised(self, max_time_back_seconds=None, resolution=60, status_type=None): <NEW_LINE> <INDENT> if max_time_back_seconds is None: <NEW_LINE> <INDENT> start_time = self.EPOCH_TIME <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start_time = self.START_TIME - max_time_back_seconds <NEW_LINE> <DEDENT> for tick in range(start_time, self.START_TIME, resolution): <NEW_LINE> <INDENT> status_obj = self.get_status(tick) <NEW_LINE> if status_type is None: <NEW_LINE> <INDENT> yield status_obj.highest_active_status_type() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield status_obj._status[status_type] | Object representing the history for a particular user. History stored sparse. | 62598f9d63d6d428bbee2582 |
class PcsSharedPath(NamedTuple): <NEW_LINE> <INDENT> fs_id: int <NEW_LINE> path: str <NEW_LINE> size: int <NEW_LINE> is_dir: bool <NEW_LINE> is_file: bool <NEW_LINE> md5: Optional[str] = None <NEW_LINE> local_ctime: Optional[int] = None <NEW_LINE> local_mtime: Optional[int] = None <NEW_LINE> server_ctime: Optional[int] = None <NEW_LINE> server_mtime: Optional[int] = None <NEW_LINE> uk: Optional[int] = None <NEW_LINE> share_id: Optional[int] = None <NEW_LINE> bdstoken: Optional[str] = None <NEW_LINE> @staticmethod <NEW_LINE> def from_(info) -> "PcsSharedPath": <NEW_LINE> <INDENT> if "parent_path" in info: <NEW_LINE> <INDENT> path = unquote(info["parent_path"] or "") + "/" + info["server_filename"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = info["path"] <NEW_LINE> <DEDENT> return PcsSharedPath( fs_id=info.get("fs_id"), path=path, size=info.get("size"), is_dir=info.get("isdir") == 1, is_file=info.get("isdir") == 0, md5=info.get("md5"), local_ctime=info.get("local_ctime"), local_mtime=info.get("local_mtime"), server_ctime=info.get("server_ctime"), server_mtime=info.get("server_mtime"), uk=info.get("uk"), share_id=info.get("share_id") or info.get("shareid"), bdstoken=info.get("bdstoken"), ) | User shared path
`sharedpath`: original shared path
`remotepath`: the directory where the `sharedpath` will save | 62598f9dbe383301e02535c5 |
class Ichengjianjiaoyudifangfujia(Iyuedu): <NEW_LINE> <INDENT> pass | chengjian jiaoyu difangjiaoyufujia shenbao biao | 62598f9d3cc13d1c6d46553c |
class SearchFilter(db.Model): <NEW_LINE> <INDENT> __table_args__ = {'mysql_collate': 'utf8_bin'} <NEW_LINE> __tablename__ = 'search_filter' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey(User.id)) <NEW_LINE> user = relationship(User) <NEW_LINE> from zeeguu_core.model.search import Search <NEW_LINE> search_id = db.Column(db.Integer, db.ForeignKey(Search.id)) <NEW_LINE> search = relationship(Search) <NEW_LINE> UniqueConstraint(user_id, search_id) <NEW_LINE> def __init__(self, user, search): <NEW_LINE> <INDENT> self.user = user <NEW_LINE> self.search = search <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'Search filter ({self.user.name}, {self.search})' <NEW_LINE> <DEDENT> __repr__ = __str__ <NEW_LINE> @classmethod <NEW_LINE> def find_or_create(cls, session, user, search): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return (cls.query.filter(cls.user == user) .filter(cls.search == search) .one()) <NEW_LINE> <DEDENT> except sqlalchemy.orm.exc.NoResultFound: <NEW_LINE> <INDENT> new = cls(user, search) <NEW_LINE> session.add(new) <NEW_LINE> session.commit() <NEW_LINE> return new <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def all_for_user(cls, user): <NEW_LINE> <INDENT> return cls.query.filter(cls.user == user).all() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def with_search_id(cls, i, user): <NEW_LINE> <INDENT> return (cls.query.filter(cls.search_id == i) .filter(cls.user == user)).one() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def with_search(cls, search_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return (cls.query.filter(cls.search_id == search_id)).one() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> from sentry_sdk import capture_exception <NEW_LINE> capture_exception(e) <NEW_LINE> return None | A search filter is created when the user
wants to filter out a particular search.
This is then taken into account in the
mixed recomemnder, when retrieving articles. | 62598f9d1f037a2d8b9e3eb7 |
class UniFiBandwidthSensor(UniFiClient, SensorEntity): <NEW_LINE> <INDENT> DOMAIN = DOMAIN <NEW_LINE> _attr_native_unit_of_measurement = DATA_MEGABYTES <NEW_LINE> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return f"{super().name} {self.TYPE.upper()}" <NEW_LINE> <DEDENT> async def options_updated(self) -> None: <NEW_LINE> <INDENT> if not self.controller.option_allow_bandwidth_sensors: <NEW_LINE> <INDENT> await self.remove_item({self.client.mac}) | UniFi bandwidth sensor base class. | 62598f9d8e71fb1e983bb886 |
class adc_sar_templates__sarbias_8slices(Module): <NEW_LINE> <INDENT> def __init__(self, bag_config, parent=None, prj=None, **kwargs): <NEW_LINE> <INDENT> Module.__init__(self, bag_config, yaml_file, parent=parent, prj=prj, **kwargs) <NEW_LINE> <DEDENT> def design(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_layout_params(self, **kwargs): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def get_layout_pin_mapping(self): <NEW_LINE> <INDENT> return {} | Module for library adc_sar_templates cell sarbias_8slices.
Fill in high level description here. | 62598f9d8a43f66fc4bf1f4c |
class BackupDirectory(Directory): <NEW_LINE> <INDENT> def __init__(self, directory_path): <NEW_LINE> <INDENT> Directory.__init__(self, directory_path) <NEW_LINE> self.name = os.path.basename(self.path) <NEW_LINE> self.archive_name = '_'.join([ self.name.lower().replace(' ', '-'), date.today().isoformat()]) <NEW_LINE> logging.debug(f'Initialized {self.path} as backup directory') | This class extends the Directory class and adds the name and
archive_name properties, needed when creating an archive and
uploading. | 62598f9d656771135c489453 |
class Prompt(BaseEnum): <NEW_LINE> <INDENT> pass | Device i/o prompts.. | 62598f9d32920d7e50bc5e27 |
class Solitaire(QMainWindow): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.initUI() <NEW_LINE> <DEDENT> def initUI(self): <NEW_LINE> <INDENT> self.sboard = Board(self) <NEW_LINE> self.statusbar = self.statusBar() <NEW_LINE> self.sboard.msg2Statusbar[str].connect(self.statusbar.showMessage) <NEW_LINE> self.resize(315, 250) <NEW_LINE> self.setMinimumSize(QSize(350, 265)) <NEW_LINE> self.setMaximumSize(QSize(350, 265)) <NEW_LINE> self.sboard.setMinimumSize(QSize(240, 240)) <NEW_LINE> self.sboard.setMaximumSize(QSize(240, 240)) <NEW_LINE> self.center() <NEW_LINE> self.setWindowTitle('Peg Solitaire') <NEW_LINE> self.sboard.start() <NEW_LINE> self.undoButton = QPushButton(self) <NEW_LINE> self.undoButton.setGeometry(QRect(250, 10, 80, 40)) <NEW_LINE> self.undoButton.setObjectName("undoButton") <NEW_LINE> self.undoButton.setText("Undo") <NEW_LINE> self.undoButton.clicked.connect(self.buttonClicked) <NEW_LINE> self.redoButton = QPushButton(self) <NEW_LINE> self.redoButton.setGeometry(QRect(250, 60, 80, 40)) <NEW_LINE> self.redoButton.setObjectName("redoButton") <NEW_LINE> self.redoButton.setText("Redo") <NEW_LINE> self.redoButton.clicked.connect(self.buttonClicked) <NEW_LINE> self.solverButton = QPushButton(self) <NEW_LINE> self.solverButton.setGeometry(QRect(250, 110, 80, 40)) <NEW_LINE> self.solverButton.setObjectName("solveButton") <NEW_LINE> self.solverButton.setText("Solve") <NEW_LINE> self.solverButton.clicked.connect(self.buttonClicked) <NEW_LINE> self.showSolutionButton = QPushButton(self) <NEW_LINE> self.showSolutionButton.setGeometry(QRect(250, 160, 100, 40)) <NEW_LINE> self.showSolutionButton.setObjectName("showSolutionButton") <NEW_LINE> self.showSolutionButton.setText("Show Sol") <NEW_LINE> self.showSolutionButton.clicked.connect(self.buttonClicked) <NEW_LINE> self.show() <NEW_LINE> <DEDENT> def center(self): <NEW_LINE> <INDENT> screen = QDesktopWidget().screenGeometry() <NEW_LINE> size = self.geometry() <NEW_LINE> self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) <NEW_LINE> <DEDENT> def buttonClicked(self): <NEW_LINE> <INDENT> sender = self.sender() <NEW_LINE> if sender == self.undoButton: <NEW_LINE> <INDENT> self.sboard.table.moves.undo(self.sboard) <NEW_LINE> <DEDENT> elif sender == self.redoButton: <NEW_LINE> <INDENT> self.sboard.table.moves.redo(self.sboard) <NEW_LINE> <DEDENT> elif sender == self.solverButton: <NEW_LINE> <INDENT> self.solver = Solver1(self.sboard.table) <NEW_LINE> self.solver.solve() <NEW_LINE> <DEDENT> elif sender == self.showSolutionButton: <NEW_LINE> <INDENT> self.solver.show_next(self.sboard) <NEW_LINE> <DEDENT> return | docstring for Solitaire | 62598f9d38b623060ffa8e62 |
class HmacSha1Signature(SignatureMethod): <NEW_LINE> <INDENT> NAME = 'HMAC-SHA1' <NEW_LINE> def sign(self, consumer_secret, access_token_secret, method, url, oauth_params, req_kwargs): <NEW_LINE> <INDENT> url = self._remove_qs(url) <NEW_LINE> oauth_params = self._normalize_request_parameters(oauth_params, req_kwargs) <NEW_LINE> parameters = map(self._escape, [method, url, oauth_params]) <NEW_LINE> key = self._escape(consumer_secret) + '&' <NEW_LINE> if access_token_secret is not None: <NEW_LINE> <INDENT> key += self._escape(access_token_secret) <NEW_LINE> <DEDENT> signature_base_string = '&'.join(parameters) <NEW_LINE> hashed = hmac.new(key, signature_base_string, sha1) <NEW_LINE> return base64.b64encode(hashed.digest()) | HMAC-SHA1 Signature Method.
This is a signature method, as per the OAuth 1.0/a specs. As the name
might suggest, this method signs parameters with HMAC using SHA1. | 62598f9df7d966606f747db8 |
class BaseIRC(object): <NEW_LINE> <INDENT> def __init__(self, server, names, nick, channel, sock=None, printing=True): <NEW_LINE> <INDENT> self.sock = sock or socket.socket() <NEW_LINE> self.server = server <NEW_LINE> self.names = names <NEW_LINE> self.nick = nick <NEW_LINE> self.channel = channel <NEW_LINE> self.printing = printing <NEW_LINE> <DEDENT> def _send(self, message): <NEW_LINE> <INDENT> if self.printing: <NEW_LINE> <INDENT> print("<< " + message) <NEW_LINE> <DEDENT> self.sock.sendall((message + "\r\n").encode()) <NEW_LINE> <DEDENT> def connect(self, server=None): <NEW_LINE> <INDENT> server = server or self.server <NEW_LINE> self.sock.connect(server) <NEW_LINE> <DEDENT> def ident(self, names=None): <NEW_LINE> <INDENT> names = names or self.names <NEW_LINE> if isinstance(names, dict): <NEW_LINE> <INDENT> send = "USER {user} 0 * :{real}".format(**names) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> send = "USER {} 0 * :{}".format(*names) <NEW_LINE> <DEDENT> self._send(send) <NEW_LINE> <DEDENT> def set_nick(self, nick=None): <NEW_LINE> <INDENT> nick = nick or self.nick <NEW_LINE> send = "NICK {}".format(nick) <NEW_LINE> self._send(send) <NEW_LINE> <DEDENT> def join(self, channel=None): <NEW_LINE> <INDENT> channel = channel or self.channel <NEW_LINE> send = "JOIN {}".format(channel) <NEW_LINE> self._send(send) <NEW_LINE> <DEDENT> def privmsg(self, message, target=None): <NEW_LINE> <INDENT> target = target or self.channel <NEW_LINE> send = "PRIVMSG {} :{}".format(target, message) <NEW_LINE> self._send(send) <NEW_LINE> <DEDENT> def _handle_register(self, line): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> getattr(self, "handle_" + line.command.upper())(line) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def _handle_mc_registered(self, line): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> getattr(self, "mc_handle_" + line.mcevent.upper())(line) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> sockf = self.sock.makefile() <NEW_LINE> for line in sockf: <NEW_LINE> <INDENT> if self.printing: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print((">> " + line).rstrip('\r\n')) <NEW_LINE> <DEDENT> except UnicodeEncodeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> p_line = parser.Line(line, self.mcserverlist) <NEW_LINE> if not p_line.frommc: <NEW_LINE> <INDENT> self._handle_register(p_line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._handle_mc_registered(p_line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def mcprivmsg(self, line, message, mctarget = None, irctarget = None): <NEW_LINE> <INDENT> irctarget = irctarget or line._nick <NEW_LINE> mctarget = mctarget or line._mcparams[0] <NEW_LINE> send = 'PRIVMSG {} :.msg {} {}'.format(irctarget, mctarget, message) <NEW_LINE> self._send(send) | Client object makes connection to IRC server and handles data
example usage: | 62598f9dac7a0e7691f722dc |
class AppleMusicShare(ShareClass): <NEW_LINE> <INDENT> def canonical_uri(self, uri): <NEW_LINE> <INDENT> match = re.search( r"https://music\.apple\.com/\w+/album/[^/]+/\d+\?i=(\d+)", uri ) <NEW_LINE> if match: <NEW_LINE> <INDENT> return "song:" + match.group(1) <NEW_LINE> <DEDENT> match = re.search(r"https://music\.apple\.com/\w+/album/[^/]+/(\d+)", uri) <NEW_LINE> if match: <NEW_LINE> <INDENT> return "album:" + match.group(1) <NEW_LINE> <DEDENT> match = re.search( r"https://music\.apple\.com/\w+/playlist/[^/]+/(pl\.[-a-zA-Z0-9]+)", uri ) <NEW_LINE> if match: <NEW_LINE> <INDENT> return "playlist:" + match.group(1) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def service_number(self): <NEW_LINE> <INDENT> return 52231 <NEW_LINE> <DEDENT> def extract(self, uri): <NEW_LINE> <INDENT> uri = self.canonical_uri(uri) <NEW_LINE> share_type = uri.split(":")[0] <NEW_LINE> encoded_uri = uri.replace(":", "%3a") <NEW_LINE> return (share_type, encoded_uri) | Apple Music share class. | 62598f9d45492302aabfc2a9 |
class UnionEnumerable(Enumerable): <NEW_LINE> <INDENT> def __init__(self, enumerable1, enumerable2, key): <NEW_LINE> <INDENT> super(UnionEnumerable, self).__init__(enumerable1) <NEW_LINE> self.enumerable = enumerable2 <NEW_LINE> self.key = key <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> union = dict() <NEW_LINE> for e in itertools.chain(iter(self._iterable), self.enumerable): <NEW_LINE> <INDENT> key = self.key(e) <NEW_LINE> key_hash = hash(json.dumps(key, default=str)) <NEW_LINE> if key_hash not in union: <NEW_LINE> <INDENT> yield e <NEW_LINE> union[key_hash] = e | Class to hold state for determining the set union of a collection with another collection | 62598f9d60cbc95b0636411e |
class Fantray(BaseACIPhysModule): <NEW_LINE> <INDENT> def __init__(self, pod, node, slot, parent=None): <NEW_LINE> <INDENT> self.type = 'fantray' <NEW_LINE> self.status = None <NEW_LINE> if parent: <NEW_LINE> <INDENT> if not isinstance(parent, Node): <NEW_LINE> <INDENT> raise TypeError('An instance of Node class or node id string is requried') <NEW_LINE> <DEDENT> <DEDENT> super(Fantray, self).__init__(pod, node, slot, parent) <NEW_LINE> self.name = 'FT-' + '/'.join([pod, node, slot]) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get(cls, session, parent=None): <NEW_LINE> <INDENT> if not isinstance(session, Session): <NEW_LINE> <INDENT> raise TypeError('An instance of Session class is required') <NEW_LINE> <DEDENT> if parent: <NEW_LINE> <INDENT> if not isinstance(parent, Node): <NEW_LINE> <INDENT> raise TypeError('An instance of Node class is requried') <NEW_LINE> <DEDENT> <DEDENT> fans = cls.get_obj(session, 'eqptFt', parent) <NEW_LINE> return fans <NEW_LINE> <DEDENT> def _populate_from_attributes(self, attributes): <NEW_LINE> <INDENT> self.serial = str(attributes['ser']) <NEW_LINE> self.model = str(attributes['model']) <NEW_LINE> self.dn = str(attributes['dn']) <NEW_LINE> self.descr = str(attributes['descr']) <NEW_LINE> self.oper_st = str(attributes['operSt']) <NEW_LINE> self.type = 'fantray' <NEW_LINE> self.name = str(attributes.get('fanName', 'None')) <NEW_LINE> self.status = str(attributes['status']) <NEW_LINE> self.modify_time = str(attributes['modTs']) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_firmware(dist_name): <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> def populate_children(self, deep=False, include_concrete=False): <NEW_LINE> <INDENT> Fan.get(self._session, self) <NEW_LINE> if deep: <NEW_LINE> <INDENT> for child in self._children: <NEW_LINE> <INDENT> child.populate_children(deep, include_concrete) <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_table(modules, title=''): <NEW_LINE> <INDENT> result = [] <NEW_LINE> headers = ['Slot', 'Model', 'Name', 'Tray Serial', 'Fan ID', 'Oper St', 'Direction', 'Speed', 'Fan Serial'] <NEW_LINE> table = [] <NEW_LINE> for fantray in sorted(modules, key=lambda x: x.slot): <NEW_LINE> <INDENT> fans = fantray.get_children(Fan) <NEW_LINE> first_fan = sorted(fans, key=lambda x: x.id)[0] <NEW_LINE> table.append([fantray.slot, fantray.model, fantray.name, fantray.serial, 'fan-' + first_fan.id, first_fan.oper_st, first_fan.direction, first_fan.speed, first_fan.serial]) <NEW_LINE> for fan in sorted(fans, key=lambda x: x.id): <NEW_LINE> <INDENT> if fan != first_fan: <NEW_LINE> <INDENT> table.append([fantray.slot, fantray.model, fantray.name, fantray.serial, 'fan-' + fan.id, fan.oper_st, fan.direction, fan.speed, fan.serial]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> result.append(Table(table, headers, title=title + 'Fan Trays')) <NEW_LINE> return result | Class for the fan tray of a node | 62598f9d460517430c431f43 |
class TransportClearNodeGroupId(message.Cmd): <NEW_LINE> <INDENT> def __init__(self, group): <NEW_LINE> <INDENT> super(TransportClearNodeGroupId, self).__init__() <NEW_LINE> self.command = _CMD_GROUP_TRANSPORT + CMDID_TRANSPORT_NODE_GROUP_ID_CLEAR <NEW_LINE> self.add_args(group) <NEW_LINE> <DEDENT> def process_resp(self, resp): <NEW_LINE> <INDENT> pass | Command to clear a Node Group ID to the node so that it can ignore
broadcast commands that are received from that node group. | 62598f9d435de62698e9bbc5 |
class MTree: <NEW_LINE> <INDENT> nSteps = 0 <NEW_LINE> mainID = '123123123123123123123' <NEW_LINE> t = np.zeros((0)) <NEW_LINE> a = np.zeros((0)) <NEW_LINE> z = np.zeros((0)) <NEW_LINE> mainBranchID = [] <NEW_LINE> mainBranchNPart = np.full((0), 0) <NEW_LINE> mainBranchNProg = np.full((0), 0) <NEW_LINE> isToken = np.full((0), False) <NEW_LINE> def __init__(self, n, ID): <NEW_LINE> <INDENT> self.mainID = ID <NEW_LINE> self.nSteps = n <NEW_LINE> self.z = np.zeros((n)) <NEW_LINE> self.a = np.zeros((n)) <NEW_LINE> self.t = np.zeros((n)) <NEW_LINE> self.mainBranchID = [''] * n <NEW_LINE> self.mainBranchNPart = np.full((n), 0) <NEW_LINE> self.mainBranchNProg = np.full((n), 0) <NEW_LINE> self.isToken = np.full((n), False) <NEW_LINE> <DEDENT> def fill_mass_id(self, nps, ids): <NEW_LINE> <INDENT> for iM in range(0 , self.nSteps): <NEW_LINE> <INDENT> self.mainBranchNPart[iM] = nps[iM] <NEW_LINE> self.mainBranchID[iM] = ids[iM] <NEW_LINE> <DEDENT> <DEDENT> def get_mass_id(self): <NEW_LINE> <INDENT> return [self.mainBranchNPart, self.mainBranchID] <NEW_LINE> <DEDENT> def print_mass_id(self): <NEW_LINE> <INDENT> for iM in range(0, self.nSteps): <NEW_LINE> <INDENT> print("%s %d" % (self.mainBranchID[iM], self.mainBranchNPart[iM])) <NEW_LINE> <DEDENT> <DEDENT> def norm_mass(self): <NEW_LINE> <INDENT> norm_mass = [] <NEW_LINE> m_zero = self.mainBranchNPart[0] <NEW_LINE> return self.mainBranchNPart[:]/m_zero <NEW_LINE> <DEDENT> def update_desc_prog(self, iStep, dP): <NEW_LINE> <INDENT> self.mainBranchID[iStep] = dP.descID <NEW_LINE> self.mainBranchNPart[iStep] = dP.descNPart <NEW_LINE> self.mainBranchNProg[iStep] = dP.descNProg <NEW_LINE> <DEDENT> def init_a(self, file_name): <NEW_LINE> <INDENT> self.a = read_a(file_name) <NEW_LINE> <DEDENT> def init_z(self, file_name): <NEW_LINE> <INDENT> self.z = read_z(file_name) <NEW_LINE> <DEDENT> def dump_to_mass_id(self): <NEW_LINE> <INDENT> f_name = 'halo_' + self.mainID + '.full_tree' <NEW_LINE> f_out = open(f_name, 'w') <NEW_LINE> line = "%s %d" % (self.mainBranchID[iM], self.mainBranchNPart[iM]) + '\n' <NEW_LINE> if self.mainBranchNPart[iM] > 0: <NEW_LINE> <INDENT> f_out.write(line) <NEW_LINE> <DEDENT> <DEDENT> def dump_to_file_id(self, f_name): <NEW_LINE> <INDENT> f_out = open(f_name, 'w') <NEW_LINE> for iM in range(0, self.nSteps): <NEW_LINE> <INDENT> line = "%s" % (self.mainBranchID[iM]) + '\n' <NEW_LINE> f_out.write(line) | Basic Merger tree class for the database | 62598f9d01c39578d7f12b4f |
class ApiTeamDetails(webapp.RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> team_key = self.request.get('team') <NEW_LINE> year = self.request.get('year') <NEW_LINE> team_dict = ApiHelper.getTeamInfo(team_key) <NEW_LINE> if self.request.get('events'): <NEW_LINE> <INDENT> team_dict = ApiHelper.addTeamEvents(team_dict, year) <NEW_LINE> <DEDENT> self.response.out.write(simplejson.dumps(team_dict)) | Information about a Team in a particular year, including full Event and Match objects | 62598f9d596a897236127a51 |
class EachSegmentizer(object): <NEW_LINE> <INDENT> def __init__(self, fieldname, from_python=noop_conv): <NEW_LINE> <INDENT> self.fieldname = fieldname <NEW_LINE> self.from_python = from_python <NEW_LINE> <DEDENT> def _iter_objects(self, queryset): <NEW_LINE> <INDENT> return ((getattr(o,self.fieldname), o.pk) for o in queryset) <NEW_LINE> <DEDENT> def __call__(self, queryset): <NEW_LINE> <INDENT> it = self._iter_objects(queryset) <NEW_LINE> conv = self.from_python <NEW_LINE> return ( (conv(lbl), queryset.filter(pk=k)) for (lbl,k) in it ) | Segmentizer that places each record in the database in its own
segment. | 62598f9de5267d203ee6b6df |
class IotCentralClientConfiguration(Configuration): <NEW_LINE> <INDENT> def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> if credential is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'credential' must not be None.") <NEW_LINE> <DEDENT> if subscription_id is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'subscription_id' must not be None.") <NEW_LINE> <DEDENT> super(IotCentralClientConfiguration, self).__init__(**kwargs) <NEW_LINE> self.credential = credential <NEW_LINE> self.subscription_id = subscription_id <NEW_LINE> self.api_version = "2021-06-01" <NEW_LINE> self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) <NEW_LINE> kwargs.setdefault('sdk_moniker', 'mgmt-iotcentral/{}'.format(VERSION)) <NEW_LINE> self._configure(**kwargs) <NEW_LINE> <DEDENT> def _configure( self, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) <NEW_LINE> self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) <NEW_LINE> self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) <NEW_LINE> self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) <NEW_LINE> self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) <NEW_LINE> self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) <NEW_LINE> self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) <NEW_LINE> self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) <NEW_LINE> self.authentication_policy = kwargs.get('authentication_policy') <NEW_LINE> if self.credential and not self.authentication_policy: <NEW_LINE> <INDENT> self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) | Configuration for IotCentralClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: The subscription identifier.
:type subscription_id: str | 62598f9d8da39b475be02fb1 |
class TestClans(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.ntf = ds.clans(5, 32, 5, .95, 1) <NEW_LINE> self.poles = np.array((0.41835234+0.0j, 0.48922229+0.1709716j, 0.48922229-0.1709716j, 0.65244885+0.3817224j, 0.65244885-0.3817224j)) <NEW_LINE> <DEDENT> def test_clans(self): <NEW_LINE> <INDENT> self.assertTrue( np.allclose(self.poles, self.ntf[1], atol=1e-8, rtol=1e-5)) | Class doc string | 62598f9d596a897236127a52 |
class ContainerForBiggestAbs: <NEW_LINE> <INDENT> negativeList = [] <NEW_LINE> positiveList = [] <NEW_LINE> negativeAmount = 2 <NEW_LINE> positiveAmount = 3 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> print("Lexer::__init__") <NEW_LINE> <DEDENT> def check(self, value): <NEW_LINE> <INDENT> if value == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> self.negativeList.append(-value) <NEW_LINE> self.negativeList.sort() <NEW_LINE> self.negativeList.reverse() <NEW_LINE> while self.negativeList.__len__() > self.negativeAmount: <NEW_LINE> <INDENT> self.negativeList.pop() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.positiveList.append(value) <NEW_LINE> self.positiveList.sort() <NEW_LINE> self.positiveList.reverse() <NEW_LINE> while self.positiveList.__len__() > self.positiveAmount: <NEW_LINE> <INDENT> self.positiveList.pop() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def getNegativeList(self): <NEW_LINE> <INDENT> amount = len(self.negativeList) <NEW_LINE> if amount == 0 or amount == 2: <NEW_LINE> <INDENT> return self.negativeList <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> def getPositiveList(self): <NEW_LINE> <INDENT> return self.positiveList | idea is to push all incoming data to the corresponding list (neg or pos). Then do a cutoff after sorting. | 62598f9d090684286d5935c3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.