code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class WeightedEdge(): <NEW_LINE> <INDENT> def __init__(self, end_node, weight): <NEW_LINE> <INDENT> self.end_node = end_node <NEW_LINE> self.weight = weight | This represents the relationship between two nodes and the strength of
the relationship | 62598fbc4527f215b58ea08e |
class RunningAverage(): <NEW_LINE> <INDENT> def __init__(self, arrLength, averageNumber): <NEW_LINE> <INDENT> self.historyArray = numpy.zeros((averageNumber,arrLength)) <NEW_LINE> self.averageNumber = averageNumber <NEW_LINE> self.counter = 0 <NEW_LINE> self.filled = False <NEW_LINE> <DEDENT> def add(self, addition): <NEW_LINE> <INDENT> self.historyArray[self.counter] = addition <NEW_LINE> self.counter = (self.counter + 1) % self.averageNumber <NEW_LINE> if self.counter == 0: self.filled = True <NEW_LINE> <DEDENT> def getAverage(self): <NEW_LINE> <INDENT> if self.filled: <NEW_LINE> <INDENT> average = numpy.average(self.historyArray, 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> average = numpy.sum(self.historyArray, 0) / self.counter <NEW_LINE> <DEDENT> return average | Allows for smoothing of input data by taking a running average | 62598fbc3317a56b869be62b |
class TcpClient(LinkClient): <NEW_LINE> <INDENT> def _runLinkClient(self): <NEW_LINE> <INDENT> while not self.isfini: <NEW_LINE> <INDENT> sock = self._runConnLoop() <NEW_LINE> if sock == None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.fire('link:sock:init',sock=sock) <NEW_LINE> for mesg in sock: <NEW_LINE> <INDENT> self.fire('link:sock:mesg',sock=sock,mesg=mesg) <NEW_LINE> <DEDENT> self.fire('link:sock:fini',sock=sock) <NEW_LINE> <DEDENT> <DEDENT> def _runConnLoop(self): <NEW_LINE> <INDENT> sock = None <NEW_LINE> delay = self.relay.link[1].get('delay',0) <NEW_LINE> while not self.isfini and sock == None: <NEW_LINE> <INDENT> sock = self.relay.initClientSock() <NEW_LINE> if sock == None: <NEW_LINE> <INDENT> time.sleep(delay) <NEW_LINE> backoff = self.link[1].get('backoff', 0.2) <NEW_LINE> maxdelay = self.link[1].get('maxdelay', 2) <NEW_LINE> delay = min( maxdelay, delay + backoff ) <NEW_LINE> <DEDENT> <DEDENT> return sock | Implements a TCP client synapse LinkRelay. | 62598fbc3d592f4c4edbb078 |
class Orderable(with_metaclass(OrderableBase, models.Model)): <NEW_LINE> <INDENT> _order = models.IntegerField(_("Order"), null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> def with_respect_to(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name = self.order_with_respect_to <NEW_LINE> value = getattr(self, name) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> field = getattr(self.__class__, name) <NEW_LINE> if isinstance(field, GenericForeignKey): <NEW_LINE> <INDENT> names = (field.ct_field, field.fk_field) <NEW_LINE> return dict([(n, getattr(self, n)) for n in names]) <NEW_LINE> <DEDENT> return {name: value} <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self._order is None or self._order == "": <NEW_LINE> <INDENT> lookup = self.with_respect_to() <NEW_LINE> lookup["_order__isnull"] = False <NEW_LINE> concrete_model = base_concrete_model(Orderable, self) <NEW_LINE> self._order = concrete_model.objects.filter(**lookup).count() <NEW_LINE> <DEDENT> super(Orderable, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def delete(self, *args, **kwargs): <NEW_LINE> <INDENT> lookup = self.with_respect_to() <NEW_LINE> lookup["_order__gte"] = self._order <NEW_LINE> concrete_model = base_concrete_model(Orderable, self) <NEW_LINE> after = concrete_model.objects.filter(**lookup) <NEW_LINE> after.update(_order=models.F("_order") - 1) <NEW_LINE> super(Orderable, self).delete(*args, **kwargs) <NEW_LINE> <DEDENT> def _get_next_or_previous_by_order(self, is_next, **kwargs): <NEW_LINE> <INDENT> lookup = self.with_respect_to() <NEW_LINE> lookup["_order"] = self._order + (1 if is_next else -1) <NEW_LINE> concrete_model = base_concrete_model(Orderable, self) <NEW_LINE> try: <NEW_LINE> <INDENT> queryset = concrete_model.objects.published <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> queryset = concrete_model.objects.filter <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return queryset(**kwargs).get(**lookup) <NEW_LINE> <DEDENT> except concrete_model.DoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def get_next_by_order(self, **kwargs): <NEW_LINE> <INDENT> return self._get_next_or_previous_by_order(True, **kwargs) <NEW_LINE> <DEDENT> def get_previous_by_order(self, **kwargs): <NEW_LINE> <INDENT> return self._get_next_or_previous_by_order(False, **kwargs) | Abstract model that provides a custom ordering integer field
similar to using Meta's ``order_with_respect_to``, since to
date (Django 1.2) this doesn't work with ``ForeignKey("self")``,
or with Generic Relations. We may also want this feature for
models that aren't ordered with respect to a particular field. | 62598fbc26068e7796d4cb14 |
class Bootstrap4CardInnerPlugin(CMSPluginBase): <NEW_LINE> <INDENT> model = Bootstrap4CardInner <NEW_LINE> name = _('Card inner') <NEW_LINE> module = _('Bootstrap 4') <NEW_LINE> render_template = 'djangocms_bootstrap4/card.html' <NEW_LINE> change_form_template = 'djangocms_bootstrap4/admin/card.html' <NEW_LINE> allow_children = True <NEW_LINE> parent_classes = [ 'Bootstrap4CardPlugin', 'Bootstrap4CollapseTriggerPlugin', 'Bootstrap4CollapseContainerPlugin', ] <NEW_LINE> fieldsets = [ (None, { 'fields': ( 'inner_type', ) }), (_('Advanced settings'), { 'classes': ('collapse',), 'fields': ( 'tag_type', 'attributes', ) }), ] <NEW_LINE> def render(self, context, instance, placeholder): <NEW_LINE> <INDENT> classes = concat_classes([instance.inner_type] + [ instance.attributes.get('class'), ]) <NEW_LINE> instance.attributes['class'] = classes <NEW_LINE> return super().render( context, instance, placeholder ) | Components > "Card - Inner" Plugin (Header, Footer, Body)
https://getbootstrap.com/docs/4.0/components/card/ | 62598fbca219f33f346c69bf |
class UpdateBotInlineQuery(TLObject): <NEW_LINE> <INDENT> __slots__ = ["query_id", "user_id", "query", "offset", "geo"] <NEW_LINE> ID = 0x54826690 <NEW_LINE> QUALNAME = "types.UpdateBotInlineQuery" <NEW_LINE> def __init__(self, *, query_id: int, user_id: int, query: str, offset: str, geo=None): <NEW_LINE> <INDENT> self.query_id = query_id <NEW_LINE> self.user_id = user_id <NEW_LINE> self.query = query <NEW_LINE> self.geo = geo <NEW_LINE> self.offset = offset <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "UpdateBotInlineQuery": <NEW_LINE> <INDENT> flags = Int.read(b) <NEW_LINE> query_id = Long.read(b) <NEW_LINE> user_id = Int.read(b) <NEW_LINE> query = String.read(b) <NEW_LINE> geo = TLObject.read(b) if flags & (1 << 0) else None <NEW_LINE> offset = String.read(b) <NEW_LINE> return UpdateBotInlineQuery(query_id=query_id, user_id=user_id, query=query, offset=offset, geo=geo) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> flags = 0 <NEW_LINE> flags |= (1 << 0) if self.geo is not None else 0 <NEW_LINE> b.write(Int(flags)) <NEW_LINE> b.write(Long(self.query_id)) <NEW_LINE> b.write(Int(self.user_id)) <NEW_LINE> b.write(String(self.query)) <NEW_LINE> if self.geo is not None: <NEW_LINE> <INDENT> b.write(self.geo.write()) <NEW_LINE> <DEDENT> b.write(String(self.offset)) <NEW_LINE> return b.getvalue() | Attributes:
LAYER: ``112``
Attributes:
ID: ``0x54826690``
Parameters:
query_id: ``int`` ``64-bit``
user_id: ``int`` ``32-bit``
query: ``str``
offset: ``str``
geo (optional): Either :obj:`GeoPointEmpty <pyrogram.api.types.GeoPointEmpty>` or :obj:`GeoPoint <pyrogram.api.types.GeoPoint>` | 62598fbc796e427e5384e94f |
class UnderMapDialogTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.dialog = UnderMapDialog(None) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.dialog = None <NEW_LINE> <DEDENT> def test_dialog_ok(self): <NEW_LINE> <INDENT> button = self.dialog.button_box.button(QDialogButtonBox.Ok) <NEW_LINE> button.click() <NEW_LINE> result = self.dialog.result() <NEW_LINE> self.assertEqual(result, QDialog.Accepted) <NEW_LINE> <DEDENT> def test_dialog_cancel(self): <NEW_LINE> <INDENT> button = self.dialog.button_box.button(QDialogButtonBox.Cancel) <NEW_LINE> button.click() <NEW_LINE> result = self.dialog.result() <NEW_LINE> self.assertEqual(result, QDialog.Rejected) | Test dialog works. | 62598fbc7c178a314d78d659 |
class Pushover(object): <NEW_LINE> <INDENT> base_uri = 'https://api.pushover.net' <NEW_LINE> def __init__(self, module, user, token): <NEW_LINE> <INDENT> self.module = module <NEW_LINE> self.user = user <NEW_LINE> self.token = token <NEW_LINE> <DEDENT> def run(self, priority, msg): <NEW_LINE> <INDENT> url = '%s/1/messages.json' % (self.base_uri) <NEW_LINE> options = dict(user=self.user, token=self.token, priority=priority, message=msg) <NEW_LINE> data = urlencode(options) <NEW_LINE> headers = { "Content-type": "application/x-www-form-urlencoded"} <NEW_LINE> r, info = fetch_url(self.module, url, method='POST', data=data, headers=headers) <NEW_LINE> if info['status'] != 200: <NEW_LINE> <INDENT> raise Exception(info) <NEW_LINE> <DEDENT> return r.read() | Instantiates a pushover object, use it to send notifications | 62598fbc7b180e01f3e4912c |
class TriangleTyper: <NEW_LINE> <INDENT> epsilon = 1e-6 <NEW_LINE> @staticmethod <NEW_LINE> @list_unfolder <NEW_LINE> def compute_type(a, b, c): <NEW_LINE> <INDENT> assert(isinstance(a, numbers.Real)) <NEW_LINE> assert(isinstance(b, numbers.Real)) <NEW_LINE> assert(isinstance(c, numbers.Real)) <NEW_LINE> assert(a >= 0) <NEW_LINE> assert(b >= 0) <NEW_LINE> assert(c >= 0) <NEW_LINE> Dab = math.fabs(a-b) <NEW_LINE> Dac = math.fabs(a-c) <NEW_LINE> Dbc = math.fabs(b-c) <NEW_LINE> e = TriangleTyper.epsilon <NEW_LINE> typ = TriangleType.Scalene <NEW_LINE> if Dab < e and Dac < e: <NEW_LINE> <INDENT> assert(Dbc < e) <NEW_LINE> typ = TriangleType.Equilateral <NEW_LINE> <DEDENT> elif Dab < e or Dac < e or Dbc < e: <NEW_LINE> <INDENT> typ = TriangleType.Isocele <NEW_LINE> <DEDENT> return typ | Helper class to decide a triangle type: Equilateral, Isocele or Scalene | 62598fbc167d2b6e312b7130 |
class ForceDefaultLanguageMiddleware(object): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> request.META.pop('HTTP_ACCEPT_LANGUAGE', None) | Ignore Accept-Language HTTP headers
This will force the I18N machinery to always choose settings.LANGUAGE_CODE
as the default initial language, unless another one is set via sessions or cookies
Should be installed *before* any middleware that checks request.META['HTTP_ACCEPT_LANGUAGE'],
namely django.middleware.locale.LocaleMiddleware | 62598fbc7d43ff24874274e1 |
class _WalkerEvent(Event): <NEW_LINE> <INDENT> def __init__(self, walker, queue, row): <NEW_LINE> <INDENT> Event.__init__(self, queue, row) <NEW_LINE> self._walker = walker <NEW_LINE> <DEDENT> def tag_done(self): <NEW_LINE> <INDENT> self._walker.tag_event_done(self) <NEW_LINE> <DEDENT> def tag_retry(self, retry_time = 60): <NEW_LINE> <INDENT> self._walker.tag_event_retry(self, retry_time) <NEW_LINE> <DEDENT> def tag_failed(self, reason): <NEW_LINE> <INDENT> self._walker.tag_failed(self, reason) | Redirects status flags to BatchWalker.
That way event data can gc-d immidiately and
tag_done() events dont need to be remembered. | 62598fbcec188e330fdf8a4c |
class InformationObject(BaseModel): <NEW_LINE> <INDENT> def raise_for_json_error(self, json_response, request_url): <NEW_LINE> <INDENT> if 'message' in json_response: <NEW_LINE> <INDENT> if 'information object not found' in json_response['message'].lower(): <NEW_LINE> <INDENT> raise ConnectionError(f'No information object found at "{request_url}"') <NEW_LINE> <DEDENT> <DEDENT> super().raise_for_json_error(json_response, request_url) <NEW_LINE> <DEDENT> @property <NEW_LINE> def read_api_url(self): <NEW_LINE> <INDENT> return '/api/informationobjects/{identifier}' <NEW_LINE> <DEDENT> def read(self, id_: str, sf_culture: str = 'en'): <NEW_LINE> <INDENT> request_path = self.read_api_url.format(identifier=id_) <NEW_LINE> return self.get_json(request_path, params=None, sf_culture=sf_culture) <NEW_LINE> <DEDENT> @property <NEW_LINE> def browse_api_url(self): <NEW_LINE> <INDENT> return '/api/informationobjects' <NEW_LINE> <DEDENT> def browse(self, sq: dict, sf: dict, so: dict, filters: dict, sf_culture: str = 'en'): <NEW_LINE> <INDENT> self._validate_sq(sq) <NEW_LINE> self._validate_sf(sf) <NEW_LINE> self._validate_so(so) <NEW_LINE> self._validate_filters(filters) <NEW_LINE> params = { **sq, **sf, **so, **filters } <NEW_LINE> return self.get_json(self.browse_api_url, params=params, sf_culture=sf_culture) <NEW_LINE> <DEDENT> def _validate_sq(self, sq: dict): <NEW_LINE> <INDENT> self._validate_query_parameters(sq, two_letter_code='sq') <NEW_LINE> <DEDENT> def _validate_sf(self, sf: dict): <NEW_LINE> <INDENT> self._validate_query_parameters(sf, two_letter_code='sf') <NEW_LINE> <DEDENT> def _validate_so(self, so: dict): <NEW_LINE> <INDENT> self._validate_query_parameters(so, two_letter_code='so') <NEW_LINE> for value in so.values(): <NEW_LINE> <INDENT> if value not in ('and', 'or', 'not'): <NEW_LINE> <INDENT> name = QUERY_VALIDATORS['so']['verbose_name'] <NEW_LINE> raise ValueError(f'{name} "{value}" was not one of: and, or, not') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _validate_query_parameters(self, queries: dict, two_letter_code: str): <NEW_LINE> <INDENT> indices = set() <NEW_LINE> regex = QUERY_VALIDATORS[two_letter_code]['regex'] <NEW_LINE> name = QUERY_VALIDATORS[two_letter_code]['verbose_name'] <NEW_LINE> for key, value in queries.items(): <NEW_LINE> <INDENT> match_obj = regex.match(key) <NEW_LINE> if not match_obj: <NEW_LINE> <INDENT> raise ValueError(f'{name} "{key}" did not start with "{two_letter_code}", followed ' 'by one or more numbers') <NEW_LINE> <DEDENT> curr_index = int(match_obj.group('index')) <NEW_LINE> if curr_index in indices: <NEW_LINE> <INDENT> raise ValueError(f'{name} with index "{curr_index}" was specified more than once') <NEW_LINE> <DEDENT> indices.add(curr_index) <NEW_LINE> if not value: <NEW_LINE> <INDENT> raise ValueError(f'{name}s may not be empty') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _validate_filters(self, filters: dict): <NEW_LINE> <INDENT> for key, value in filters.items(): <NEW_LINE> <INDENT> if key not in VALID_FILTERS: <NEW_LINE> <INDENT> raise ValueError(f'Filter Type "{key}" was not recognized') <NEW_LINE> <DEDENT> if not value: <NEW_LINE> <INDENT> raise ValueError('Filter values may not be empty') | Browse for or read information objects. Browsing involves searching for information objects,
while reading involves fetching the metadata for a single object. | 62598fbc01c39578d7f12f35 |
@parser(Specs.keystone_log) <NEW_LINE> class KeystoneLog(LogFileOutput): <NEW_LINE> <INDENT> pass | Class for parsing ``/var/log/keystone/keystone.log`` file.
.. note::
Please refer to its super-class :class:`insights.core.LogFileOutput` | 62598fbc851cf427c66b8470 |
class RCNonSimplyLacedElement(RiggedConfigurationElement): <NEW_LINE> <INDENT> def to_virtual_configuration(self): <NEW_LINE> <INDENT> return self.parent().to_virtual(self) <NEW_LINE> <DEDENT> def e(self, a): <NEW_LINE> <INDENT> vct = self.parent()._folded_ct <NEW_LINE> L = [] <NEW_LINE> gamma = vct.scaling_factors() <NEW_LINE> for i in vct.folding_orbit()[a]: <NEW_LINE> <INDENT> L.extend([i]*gamma[a]) <NEW_LINE> <DEDENT> virtual_rc = self.parent().to_virtual(self).e_string(L) <NEW_LINE> if virtual_rc is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.parent().from_virtual(virtual_rc) <NEW_LINE> <DEDENT> def f(self, a): <NEW_LINE> <INDENT> vct = self.parent()._folded_ct <NEW_LINE> L = [] <NEW_LINE> gamma = vct.scaling_factors() <NEW_LINE> for i in vct.folding_orbit()[a]: <NEW_LINE> <INDENT> L.extend([i]*gamma[a]) <NEW_LINE> <DEDENT> virtual_rc = self.parent().to_virtual(self).f_string(L) <NEW_LINE> if virtual_rc is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.parent().from_virtual(virtual_rc) <NEW_LINE> <DEDENT> @cached_method <NEW_LINE> def cocharge(self): <NEW_LINE> <INDENT> vct = self.parent()._folded_ct <NEW_LINE> cc = 0 <NEW_LINE> rigging_sum = 0 <NEW_LINE> sigma = vct.folding_orbit() <NEW_LINE> gamma = vct.scaling_factors() <NEW_LINE> for a, p in enumerate(self): <NEW_LINE> <INDENT> t_check = len(sigma[a+1]) * gamma[a+1] / gamma[0] <NEW_LINE> for pos, i in enumerate(p._list): <NEW_LINE> <INDENT> rigging_sum += t_check * p.rigging[pos] <NEW_LINE> for dim in self.parent().dims: <NEW_LINE> <INDENT> if dim[0] == a + 1: <NEW_LINE> <INDENT> cc += t_check * min(dim[1], i) <NEW_LINE> <DEDENT> <DEDENT> cc -= t_check * p.vacancy_numbers[pos] <NEW_LINE> <DEDENT> <DEDENT> return cc / 2 + rigging_sum <NEW_LINE> <DEDENT> cc = cocharge | Rigged configuration elements for non-simply-laced types.
TESTS::
sage: RC = RiggedConfigurations(['C',2,1], [[1,2],[1,1],[2,1]])
sage: elt = RC(partition_list=[[3],[2]]); elt
<BLANKLINE>
0[ ][ ][ ]0
<BLANKLINE>
0[ ][ ]0
sage: TestSuite(elt).run() | 62598fbc377c676e912f6e4e |
class CategoricalColumn(FeatureColumn): <NEW_LINE> <INDENT> IdWeightPair = collections.namedtuple( 'IdWeightPair', ('id_tensor', 'weight_tensor')) <NEW_LINE> @abc.abstractproperty <NEW_LINE> def num_buckets(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def get_sparse_tensors(self, transformation_cache, state_manager): <NEW_LINE> <INDENT> pass | Represents a categorical feature.
A categorical feature typically handled with a `tf.sparse.SparseTensor` of
IDs. | 62598fbc4527f215b58ea08f |
class vtclinearEquation(myObject): <NEW_LINE> <INDENT> def __init__(self, c, ySpan): <NEW_LINE> <INDENT> typeTest([Num.constum, mSpan], c, ySpan) <NEW_LINE> self.args = (c, ySpan) <NEW_LINE> self.c = c <NEW_LINE> self.ySpan = ySpan | x = c for y in ySpan | 62598fbc67a9b606de546187 |
class RevocationCheckError(OperationalError): <NEW_LINE> <INDENT> def exception_telemetry(self, msg, cursor, connection): <NEW_LINE> <INDENT> pass | Exception for errors during certificate revocation check. | 62598fbc26068e7796d4cb16 |
class GetResourceTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_get_resource(self): <NEW_LINE> <INDENT> for res in ('credential', 'group', 'host', 'inventory', 'job_template', 'job', 'organization', 'project', 'team', 'user'): <NEW_LINE> <INDENT> tower_cli.get_resource(res) | Establish that the `tower_cli.get_resource` method works in the
way that it should. | 62598fbc7c178a314d78d65b |
class Splitters(pasoFunction): <NEW_LINE> <INDENT> @pasoDecorators.InitWrap() <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.inplace = False <NEW_LINE> return self <NEW_LINE> <DEDENT> @pasoDecorators.TTWrapXy(array=False) <NEW_LINE> def transform(self, X, y, **kwargs): <NEW_LINE> <INDENT> if "stratify" in self.kind_name_kwargs: <NEW_LINE> <INDENT> self.kind_name_kwargs["stratify"] = y <NEW_LINE> <DEDENT> X_train, X_test, y_train, y_test = train_test_split( X, y, **self.kind_name_kwargs ) <NEW_LINE> return X_train, X_test, y_train, y_test | Input returns dataset.
Tne metadata is the instance attibutesof Inputer prperties.
Note:
Warning: | 62598fbc7cff6e4e811b5bde |
class GetBoost: <NEW_LINE> <INDENT> MINIMUM_BOOST_LEVEL = 90 <NEW_LINE> BOOST_MAP = { 'blue': [3, 4], 'red': [29, 30], 'mid': [15, 18], 'any': [3, 4, 15, 18, 29, 30] } <NEW_LINE> def __init__(self, which_boost: str = 'any'): <NEW_LINE> <INDENT> self.which_boost = which_boost <NEW_LINE> self.agent: Optional[GoslingAgent] = None <NEW_LINE> <DEDENT> def run(self, agent: GoslingAgent): <NEW_LINE> <INDENT> self.agent = agent <NEW_LINE> boost_pad, brake_upon_destination = self._get_closest_boost_pad() <NEW_LINE> self._drive_to_boost_pad(boost_pad, brake_upon_destination) <NEW_LINE> self._boost_filled() <NEW_LINE> <DEDENT> def _get_boost_areas(self): <NEW_LINE> <INDENT> if self.which_boost == 'blue': <NEW_LINE> <INDENT> return ['blue', 'mid'] <NEW_LINE> <DEDENT> elif self.which_boost == 'red': <NEW_LINE> <INDENT> return ['red', 'mid'] <NEW_LINE> <DEDENT> elif self.which_boost == 'mid': <NEW_LINE> <INDENT> return ['mid', 'blue', 'red'] <NEW_LINE> <DEDENT> elif self.which_boost == 'any': <NEW_LINE> <INDENT> return ['any'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError(f"which_boost cannot be {self.which_boost}") <NEW_LINE> <DEDENT> <DEDENT> def _get_closest_boost_pad(self) -> Tuple[boost_object, bool]: <NEW_LINE> <INDENT> for area in self._get_boost_areas(): <NEW_LINE> <INDENT> distances = {((self.agent.me.location - self.agent.boosts[pad_index].location).magnitude()): pad_index for pad_index in self.BOOST_MAP[area] if self.agent.boosts[pad_index].active} <NEW_LINE> if len(distances) > 0: <NEW_LINE> <INDENT> boost_pad = distances[min(distances.keys())] <NEW_LINE> brake_upon_destination = False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> distances = {((self.agent.me.location - self.agent.boosts[pad_index].location).magnitude()): pad_index for pad_index in self.BOOST_MAP[self._get_boost_areas()[0]]} <NEW_LINE> boost_pad = distances[min(distances.keys())] <NEW_LINE> brake_upon_destination = True <NEW_LINE> <DEDENT> return boost_pad, brake_upon_destination <NEW_LINE> <DEDENT> def _drive_to_boost_pad(self, boost_pad: boost_object, brake_upon_destination: bool): <NEW_LINE> <INDENT> target = self.agent.boosts[boost_pad].location <NEW_LINE> local_target = self.agent.me.local(target - self.agent.me.location) <NEW_LINE> defaultPD(self.agent, local_target) <NEW_LINE> if brake_upon_destination: <NEW_LINE> <INDENT> speed = min(GameConstants.MAX_SPEED_BOOST, (self.agent.me.location - target).magnitude()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> speed = GameConstants.MAX_SPEED_BOOST <NEW_LINE> <DEDENT> defaultThrottle(self.agent, speed) <NEW_LINE> <DEDENT> def _boost_filled(self) -> bool: <NEW_LINE> <INDENT> minimum_boost_level = self.MINIMUM_BOOST_LEVEL <NEW_LINE> if self.agent.me.boost >= minimum_boost_level: <NEW_LINE> <INDENT> self.agent.pop() <NEW_LINE> defaultThrottle(self.agent, 0) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False | Drives towards the nearest active boost in the specified area. If no active boost is found, waits on the nearest
pad. Only considers large boost pads.
:param which_boost: Which region of the map to drive to. Either blue, red, mid, any
:type which_boost: str | 62598fbc091ae35668704ddf |
class OneOfEach(TBase): <NEW_LINE> <INDENT> def __init__(self, im_true=None, im_false=None, a_bite=127, integer16=32767, integer32=None, integer64=10000000000, double_precision=None, some_characters=None, zomg_unicode=None, what_who=None, base64=None, byte_list=[ 1, 2, 3, ], i16_list=[ 1, 2, 3, ], i64_list=[ 1, 2, 3, ],): <NEW_LINE> <INDENT> self.im_true = im_true <NEW_LINE> self.im_false = im_false <NEW_LINE> self.a_bite = a_bite <NEW_LINE> self.integer16 = integer16 <NEW_LINE> self.integer32 = integer32 <NEW_LINE> self.integer64 = integer64 <NEW_LINE> self.double_precision = double_precision <NEW_LINE> self.some_characters = some_characters <NEW_LINE> self.zomg_unicode = zomg_unicode <NEW_LINE> self.what_who = what_who <NEW_LINE> self.base64 = base64 <NEW_LINE> if byte_list is self.thrift_spec[12][4]: <NEW_LINE> <INDENT> byte_list = [ 1, 2, 3, ] <NEW_LINE> <DEDENT> self.byte_list = byte_list <NEW_LINE> if i16_list is self.thrift_spec[13][4]: <NEW_LINE> <INDENT> i16_list = [ 1, 2, 3, ] <NEW_LINE> <DEDENT> self.i16_list = i16_list <NEW_LINE> if i64_list is self.thrift_spec[14][4]: <NEW_LINE> <INDENT> i64_list = [ 1, 2, 3, ] <NEW_LINE> <DEDENT> self.i64_list = i64_list <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- im_true
- im_false
- a_bite
- integer16
- integer32
- integer64
- double_precision
- some_characters
- zomg_unicode
- what_who
- base64
- byte_list
- i16_list
- i64_list | 62598fbc97e22403b383b0c3 |
class SyntaxData(syndata.SyntaxDataBase): <NEW_LINE> <INDENT> def __init__(self, langid): <NEW_LINE> <INDENT> super(SyntaxData, self).__init__(langid) <NEW_LINE> self.SetLexer(stc.STC_LEX_PASCAL) <NEW_LINE> <DEDENT> def GetKeywords(self): <NEW_LINE> <INDENT> return [PAS_KEYWORDS, PAS_CLASSWORDS] <NEW_LINE> <DEDENT> def GetSyntaxSpec(self): <NEW_LINE> <INDENT> return SYNTAX_ITEMS <NEW_LINE> <DEDENT> def GetProperties(self): <NEW_LINE> <INDENT> return [FOLD, FLD_COMMENT] <NEW_LINE> <DEDENT> def GetCommentPattern(self): <NEW_LINE> <INDENT> return [u'{', u'}'] | SyntaxData object for Pascal | 62598fbca8370b77170f059c |
@python_2_unicode_compatible <NEW_LINE> class FilersCd(CalAccessBaseModel): <NEW_LINE> <INDENT> UNIQUE_KEY = "FILER_ID" <NEW_LINE> filer_id = fields.IntegerField( verbose_name='filer ID', db_column='FILER_ID', null=True, db_index=True, help_text="Filer's unique identification number", ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'calaccess_raw' <NEW_LINE> db_table = 'FILERS_CD' <NEW_LINE> verbose_name = 'FILERS_CD' <NEW_LINE> verbose_name_plural = 'FILERS_CD' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.filer_id) | This table is the parent table from which all links and associations
to a filer are derived. | 62598fbc167d2b6e312b7132 |
class authenticated(object): <NEW_LINE> <INDENT> error = _("Only valid users may access this function") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "authenticated" <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.instance = None <NEW_LINE> self.function = None <NEW_LINE> self.f_args = None <NEW_LINE> self.f_kwargs = None <NEW_LINE> <DEDENT> def check(self): <NEW_LINE> <INDENT> if not self.instance.current_user: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | A condition class to be used with the @require decorator that returns True
if the user is authenticated.
.. note::
Only meant to be used with WebSockets. `tornado.web.RequestHandler`
instances can use `@tornado.web.authenticated` | 62598fbc9f28863672818959 |
class Propagator(object): <NEW_LINE> <INDENT> def __init__(self, num_error=10**(-18), regime='SIL'): <NEW_LINE> <INDENT> self.num_error=num_error <NEW_LINE> self.regime=regime <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def propagate_wave_function(wf_init, hamilt, NK=10, dt=1., maxel=None, num_error=10**(-18), regime='SIL', file_out=None, **kwrds): <NEW_LINE> <INDENT> prop = envtb.time_propagator.lanczos.LanczosPropagator( wf=wf_init, ham=hamilt, NK=NK, dt=dt) <NEW_LINE> wf_final, dt_new, NK_new = prop.propagate( num_error=num_error, regime=regime) <NEW_LINE> if file_out is None: <NEW_LINE> <INDENT> return wf_final, dt_new, NK_new <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> wf_final.save_wave_function_pic(file_out, maxel, **kwrds) <NEW_LINE> return wf_final, dt_new, NK_new | docstring for Propagator | 62598fbc5fc7496912d48359 |
class LoanApplicationObject(Model): <NEW_LINE> <INDENT> def __init__(self, loan_application: LoanApplication=None): <NEW_LINE> <INDENT> self.swagger_types = { 'loan_application': LoanApplication } <NEW_LINE> self.attribute_map = { 'loan_application': 'loanApplication' } <NEW_LINE> self._loan_application = loan_application <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt) -> 'LoanApplicationObject': <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def loan_application(self) -> LoanApplication: <NEW_LINE> <INDENT> return self._loan_application <NEW_LINE> <DEDENT> @loan_application.setter <NEW_LINE> def loan_application(self, loan_application: LoanApplication): <NEW_LINE> <INDENT> if loan_application is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `loan_application`, must not be `None`") <NEW_LINE> <DEDENT> self._loan_application = loan_application | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fbc377c676e912f6e4f |
class NDEx: <NEW_LINE> <INDENT> def __init__(self, uri="http://public.ndexbio.org"): <NEW_LINE> <INDENT> ndex_creds = os.path.expanduser("~/.ndex") <NEW_LINE> if os.path.exists (ndex_creds): <NEW_LINE> <INDENT> with open(ndex_creds, "r") as stream: <NEW_LINE> <INDENT> ndex_creds_obj = json.loads (stream.read ()) <NEW_LINE> print (f"connecting to ndex as {ndex_creds_obj['username']}") <NEW_LINE> account = ndex_creds_obj['username'] <NEW_LINE> password = ndex_creds_obj['password'] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError ("No ndex credentials found.") <NEW_LINE> <DEDENT> self.uri = uri <NEW_LINE> self.session = None <NEW_LINE> self.account = account <NEW_LINE> self.password = password <NEW_LINE> try: <NEW_LINE> <INDENT> self.session = Ndex2 (uri, account, password) <NEW_LINE> self.session.update_status() <NEW_LINE> networks = self.session.status.get("networkCount") <NEW_LINE> users = self.session.status.get("userCount") <NEW_LINE> groups = self.session.status.get("groupCount") <NEW_LINE> print(f"session: networks: {networks} users: {users} groups: {groups}") <NEW_LINE> <DEDENT> except Exception as inst: <NEW_LINE> <INDENT> print(f"Could not access account {account}") <NEW_LINE> raise inst <NEW_LINE> <DEDENT> <DEDENT> def publish (self, name, graph): <NEW_LINE> <INDENT> assert name, "A name for the network is required." <NEW_LINE> """ Serialize node and edge python objects. """ <NEW_LINE> g = nx.MultiDiGraph() <NEW_LINE> print (f"{json.dumps (graph, indent=2)}") <NEW_LINE> jsonpath_query = parse ("$.[*].node_list.[*].[*]") <NEW_LINE> nodes = [ match.value for match in jsonpath_query.find (graph) ] <NEW_LINE> print (f"{json.dumps(nodes, indent=2)}") <NEW_LINE> jsonpath_query = parse ("$.[*].edge_list.[*].[*]") <NEW_LINE> edges = [ match.value for match in jsonpath_query.find (graph) ] <NEW_LINE> print (f"{json.dumps(edges, indent=2)}") <NEW_LINE> for n in nodes: <NEW_LINE> <INDENT> g.add_node(n['id'], attr_dict=n) <NEW_LINE> <DEDENT> for e in edges: <NEW_LINE> <INDENT> print (f" s: {json.dumps(e,indent=2)}") <NEW_LINE> g.add_edge (e['source_id'], e['target_id'], attr_dict=e) <NEW_LINE> <DEDENT> """ Convert to CX network. """ <NEW_LINE> nice_cx = create_nice_cx_from_networkx (g) <NEW_LINE> nice_cx.set_name (name) <NEW_LINE> print (f" connected: edges: {len(g.edges())} nodes: {len(g.nodes())}") <NEW_LINE> print (nice_cx) <NEW_LINE> """ Upload to NDEx. """ <NEW_LINE> upload_message = nice_cx.upload_to(self.uri, self.account, self.password) | An interface to the NDEx network catalog. | 62598fbce1aae11d1e7ce903 |
class MatchesScoreVote(models.Model): <NEW_LINE> <INDENT> tourney = models.ForeignKey('Tournament') <NEW_LINE> match = models.ForeignKey('Match') <NEW_LINE> user = models.ForeignKey(settings.AUTH_USER_MODEL) <NEW_LINE> entry_id = models.ForeignKey('MatchesTeam') <NEW_LINE> entry_val = models.IntegerField() | "tournament_matches_score_votes" => "id BIGINT NOT NULL auto_increment,
tourneyid BIGINT NOT NULL,
matchid BIGINT NOT NULL,
userid BIGINT NOT NULL,
entry_id BIGINT NOT NULL,
entry_val int(10) NOT NULL,
PRIMARY KEY (id)", | 62598fbc956e5f7376df575c |
class DataForm(object): <NEW_LINE> <INDENT> def __init__(self, name: str): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.fields = {} | a top-level variable holding persistent state
| 62598fbcbe7bc26dc9251f3a |
class FunctionBlock(Block): <NEW_LINE> <INDENT> def __init__(self, func_type, name, args, contents=None, sticky_front=None, sticky_end=None, before=None, after=None, variables=None): <NEW_LINE> <INDENT> super(FunctionBlock, self).__init__( contents=contents, sticky_front=sticky_front, sticky_end=sticky_end, before=before, after=after, variables=variables ) <NEW_LINE> self.func_type = func_type <NEW_LINE> self.args = args <NEW_LINE> self.name = name <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> self.append_variable(arg) <NEW_LINE> <DEDENT> <DEDENT> def block_strings(self): <NEW_LINE> <INDENT> indentation = " "*self.indent if self.should_indent else "" <NEW_LINE> child_contents = map(str, self.before) <NEW_LINE> child_contents += ["{type} {name}({args}){{".format( type=self.func_type, name=self.name, args=", ".join(map(str, self.args)) )] <NEW_LINE> for content in self.sticky_front + self.contents + self.sticky_end: <NEW_LINE> <INDENT> content = content.block_strings() <NEW_LINE> if isinstance(content, list): <NEW_LINE> <INDENT> for nested_content in content: <NEW_LINE> <INDENT> child_contents.append(indentation + str(nested_content)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> child_contents.append(indentation + str(content)) <NEW_LINE> <DEDENT> <DEDENT> child_contents += ["}"] <NEW_LINE> child_contents += map(str, self.after) <NEW_LINE> return child_contents | Block for functions.
func_type:
Data type to be returned by the func.
(int, float, etc.)
name:
Function name
args:
List of tuples containing CArguments.
contents:
List of blocks to fill this block with. | 62598fbc56ac1b37e63023aa |
class Student(Base): <NEW_LINE> <INDENT> __tablename__ = "students" <NEW_LINE> id = Column(Integer, primary_key=True, index=True) <NEW_LINE> name = Column(String) <NEW_LINE> address = Column(String) <NEW_LINE> neighbour = Column(String) <NEW_LINE> city = Column(String) <NEW_LINE> state = Column(String) <NEW_LINE> postal_code = Column(String) | Modelo de dados para persistir as informações dos estudantes. | 62598fbc99fddb7c1ca62eca |
class AdminOnlyAuthenticationMiddleware(AuthenticationMiddleware): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> if request.path.startswith(reverse('admin:index')): <NEW_LINE> <INDENT> super(AdminOnlyAuthenticationMiddleware, self).process_request(request) | Only do the session authentication stuff for admin urls.
The frontend relies on auth tokens so we clear the user. | 62598fbc283ffb24f3cf3a40 |
class login(): <NEW_LINE> <INDENT> def user_login(self,driver,username,password): <NEW_LINE> <INDENT> driver.find_element_by_xpath('//*[@id="app"]/div[3]/a[1]').click() <NEW_LINE> driver.find_element_by_xpath('//*[@id="app"]/div[3]/input[1]').clear() <NEW_LINE> driver.find_element_by_xpath('//*[@id="app"]/div[3]/input[1]').send_keys(username) <NEW_LINE> driver.find_element_by_xpath('//*[@id="app"]/div[3]/input[2]').clear() <NEW_LINE> driver.find_element_by_xpath('//*[@id="app"]/div[3]/input[2]').send_keys(password) <NEW_LINE> driver.find_element_by_xpath('//*[@id="dologin"]').click() <NEW_LINE> windows = driver.window_handles <NEW_LINE> driver.switch_to.window(windows[-1]) <NEW_LINE> driver.find_element_by_xpath('//*[@id="app"]/div[3]/select/option[1]').click() <NEW_LINE> driver.find_element_by_xpath('//*[@id="login"]').click() <NEW_LINE> <DEDENT> """退出""" <NEW_LINE> def user_logout(self,driver): <NEW_LINE> <INDENT> above = driver.find_element_by_xpath('//*[@id="page-wrapper"]/div[1]/nav/ul/li[4]/div/label') <NEW_LINE> ActionChains(driver).move_to_element(above).perform() <NEW_LINE> driver.find_element_by_xpath('//*[@id="page-wrapper"]/div[1]/nav/ul/li[4]/ul/li[1]/a/label').click() <NEW_LINE> driver.quit() | 登录 | 62598fbc1f5feb6acb162ddd |
class TimerDict(dict): <NEW_LINE> <INDENT> def stopTimer(self, k, v=None): <NEW_LINE> <INDENT> v = v or self.get(k) <NEW_LINE> if v and hasattr(v, "stop"): <NEW_LINE> <INDENT> v.stop() <NEW_LINE> <DEDENT> return bool(v) <NEW_LINE> <DEDENT> def setdefault(self, k, d=None): <NEW_LINE> <INDENT> self.stopTimer(k) <NEW_LINE> return super(TimerDict, self).setdefault(k, d) <NEW_LINE> <DEDENT> def __setitem__(self, k, v): <NEW_LINE> <INDENT> self.stopTimer(k) <NEW_LINE> return super(TimerDict, self).__setitem__(k, v) <NEW_LINE> <DEDENT> def __delitem__(self, k): <NEW_LINE> <INDENT> self.stopTimer(k) <NEW_LINE> return super(TimerDict, self).__delitem__(k) <NEW_LINE> <DEDENT> def pop(self, k, d=None): <NEW_LINE> <INDENT> self.stopTimer(k) <NEW_LINE> return super(TimerDict, self).pop(k, d) <NEW_LINE> <DEDENT> def popitem(self): <NEW_LINE> <INDENT> item = super(TimerDict, self).popitem() <NEW_LINE> self.stopTimer(*item) <NEW_LINE> return item <NEW_LINE> <DEDENT> def getById(self, timerId, default=None): <NEW_LINE> <INDENT> for timer in self.values(): <NEW_LINE> <INDENT> if timer.id == timerId: <NEW_LINE> <INDENT> return timer <NEW_LINE> <DEDENT> <DEDENT> return default | 全局定时器字典 {name: timer}
重载部分方法和操作符,防止timer内存泄漏 | 62598fbc3617ad0b5ee06303 |
class DiagonalConnection(Connection): <NEW_LINE> <INDENT> def __init__(self, connectionMetaData, columnLengthFactor, beamLengthFactor, gussetLengthFactor, beamsShearEfficiency, boltedPlateTemplate, intermediateJoint): <NEW_LINE> <INDENT> super(DiagonalConnection,self).__init__(connectionMetaData, columnLengthFactor, beamLengthFactor, gussetLengthFactor, beamsShearEfficiency, boltedPlateTemplate, intermediateJoint) <NEW_LINE> <DEDENT> def getHorizontalWeldLegSize(self): <NEW_LINE> <INDENT> className= type(self).__name__ <NEW_LINE> methodName= sys._getframe(0).f_code.co_name <NEW_LINE> lmsg.error(className+'.'+methodName+': not implemented yet.') <NEW_LINE> return 0.0 | Connection that has one or more diagonals. | 62598fbc4428ac0f6e6586e1 |
class CountingScheduler: <NEW_LINE> <INDENT> def __init__(self, max_computes=0): <NEW_LINE> <INDENT> self.total_computes = 0 <NEW_LINE> self.max_computes = max_computes <NEW_LINE> <DEDENT> def __call__(self, dsk, keys, **kwargs): <NEW_LINE> <INDENT> self.total_computes += 1 <NEW_LINE> if self.total_computes > self.max_computes: <NEW_LINE> <INDENT> raise RuntimeError( "Too many computes. Total: %d > max: %d." % (self.total_computes, self.max_computes) ) <NEW_LINE> <DEDENT> return dask.get(dsk, keys, **kwargs) | Simple dask scheduler counting the number of computes.
Reference: https://stackoverflow.com/questions/53289286/ | 62598fbc4c3428357761a479 |
class NoExtensionException(Exception): <NEW_LINE> <INDENT> pass | Raise if extension wasn't found. | 62598fbc4f88993c371f05e7 |
class Http11TestCase(HttpTestCase): <NEW_LINE> <INDENT> download_handler_cls = HTTP11DownloadHandler <NEW_LINE> def test_download_without_maxsize_limit(self): <NEW_LINE> <INDENT> request = Request(self.getURL('file')) <NEW_LINE> d = self.download_request(request, Spider('foo')) <NEW_LINE> d.addCallback(lambda r: r.body) <NEW_LINE> d.addCallback(self.assertEquals, b"0123456789") <NEW_LINE> return d <NEW_LINE> <DEDENT> def test_response_class_choosing_request(self): <NEW_LINE> <INDENT> body = b'Some plain text\ndata with tabs\t and null bytes\0' <NEW_LINE> def _test_type(response): <NEW_LINE> <INDENT> self.assertEquals(type(response), TextResponse) <NEW_LINE> <DEDENT> request = Request(self.getURL('nocontenttype'), body=body) <NEW_LINE> d = self.download_request(request, Spider('foo')) <NEW_LINE> d.addCallback(_test_type) <NEW_LINE> return d <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def test_download_with_maxsize(self): <NEW_LINE> <INDENT> request = Request(self.getURL('file')) <NEW_LINE> d = self.download_request(request, Spider('foo', download_maxsize=10)) <NEW_LINE> d.addCallback(lambda r: r.body) <NEW_LINE> d.addCallback(self.assertEquals, b"0123456789") <NEW_LINE> yield d <NEW_LINE> d = self.download_request(request, Spider('foo', download_maxsize=9)) <NEW_LINE> yield self.assertFailure(d, defer.CancelledError, error.ConnectionAborted) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def test_download_with_maxsize_per_req(self): <NEW_LINE> <INDENT> meta = {'download_maxsize': 2} <NEW_LINE> request = Request(self.getURL('file'), meta=meta) <NEW_LINE> d = self.download_request(request, Spider('foo')) <NEW_LINE> yield self.assertFailure(d, defer.CancelledError, error.ConnectionAborted) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def test_download_with_small_maxsize_per_spider(self): <NEW_LINE> <INDENT> request = Request(self.getURL('file')) <NEW_LINE> d = self.download_request(request, Spider('foo', download_maxsize=2)) <NEW_LINE> yield self.assertFailure(d, defer.CancelledError, error.ConnectionAborted) <NEW_LINE> <DEDENT> def test_download_with_large_maxsize_per_spider(self): <NEW_LINE> <INDENT> request = Request(self.getURL('file')) <NEW_LINE> d = self.download_request(request, Spider('foo', download_maxsize=100)) <NEW_LINE> d.addCallback(lambda r: r.body) <NEW_LINE> d.addCallback(self.assertEquals, b"0123456789") <NEW_LINE> return d | HTTP 1.1 test case | 62598fbc50812a4eaa620cca |
class nlpruError(Exception): <NEW_LINE> <INDENT> def __init__(self, reason): <NEW_LINE> <INDENT> Exception.__init__(self, reason) | The main exception handler for nlpru | 62598fbc442bda511e95c61a |
class MedicinalProductManufactured(domainresource.DomainResource): <NEW_LINE> <INDENT> resource_type = "MedicinalProductManufactured" <NEW_LINE> def __init__(self, jsondict=None, strict=True, **kwargs): <NEW_LINE> <INDENT> self.ingredient = None <NEW_LINE> self.manufacturedDoseForm = None <NEW_LINE> self.manufacturer = None <NEW_LINE> self.otherCharacteristics = None <NEW_LINE> self.physicalCharacteristics = None <NEW_LINE> self.quantity = None <NEW_LINE> self.unitOfPresentation = None <NEW_LINE> super(MedicinalProductManufactured, self).__init__(jsondict=jsondict, strict=strict, **kwargs) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(MedicinalProductManufactured, self).elementProperties() <NEW_LINE> js.extend([ ("ingredient", "ingredient", fhirreference.FHIRReference, True, None, False), ("manufacturedDoseForm", "manufacturedDoseForm", codeableconcept.CodeableConcept, False, None, True), ("manufacturer", "manufacturer", fhirreference.FHIRReference, True, None, False), ("otherCharacteristics", "otherCharacteristics", codeableconcept.CodeableConcept, True, None, False), ("physicalCharacteristics", "physicalCharacteristics", prodcharacteristic.ProdCharacteristic, False, None, False), ("quantity", "quantity", quantity.Quantity, False, None, True), ("unitOfPresentation", "unitOfPresentation", codeableconcept.CodeableConcept, False, None, False), ]) <NEW_LINE> return js | The manufactured item as contained in the packaged medicinal product.
| 62598fbc7b180e01f3e4912e |
class LoginAPI(generics.GenericAPIView): <NEW_LINE> <INDENT> serializer_class = LoginSerializer <NEW_LINE> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> serializer = self.get_serializer(data=request.data) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> user = serializer.validated_data <NEW_LINE> return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) | API for Login. Takes email and password | 62598fbc099cdd3c636754c1 |
class ActiveInstance(ExtendTable): <NEW_LINE> <INDENT> __tablename__ = 'active_instance' <NEW_LINE> __schema__ = [ Column('dummy_key', Integer, primary_key=True), Column('identity', pg.BYTEA(16)), Column('last_ping', DateTime), ] | Table to organize multiple orchestrator instances. | 62598fbcad47b63b2c5a7a13 |
class Inverter(SensorEntity): <NEW_LINE> <INDENT> def __init__( self, uid, serial, key, unit, state_class=None, device_class=None, ): <NEW_LINE> <INDENT> self.uid = uid <NEW_LINE> self.serial = serial <NEW_LINE> self.key = key <NEW_LINE> self.value = None <NEW_LINE> self.unit = unit <NEW_LINE> self._attr_state_class = state_class <NEW_LINE> self._attr_device_class = device_class <NEW_LINE> <DEDENT> @property <NEW_LINE> def native_value(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return self.uid <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return f"Solax {self.serial} {self.key}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def native_unit_of_measurement(self): <NEW_LINE> <INDENT> return self.unit <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return False | Class for a sensor. | 62598fbc956e5f7376df575d |
class SignupForm(AllAuthSignupForm): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(SignupForm, self).__init__(*args, **kwargs) <NEW_LINE> self.helper = FormHelper() <NEW_LINE> self.helper.form_id = 'signup-form' <NEW_LINE> self.helper.form_class = 'form-horizontal' <NEW_LINE> self.helper.label_class = 'col-lg-2' <NEW_LINE> self.helper.field_class = 'col-lg-8' <NEW_LINE> self.helper.layout = Layout( 'username', 'email', 'password1', 'password2', FormActions( Submit('save', 'Sign Up'), css_class="col-sm-offset-2 col-sm-10", ) ) | Shouldn't rewrite any functionality from allauth.accounts.forms.SignUpForm,
just plug crispy forms in | 62598fbc55399d3f056266d3 |
class Comment(models.Model): <NEW_LINE> <INDENT> author = models.ForeignKey(User, verbose_name='Автор комментария') <NEW_LINE> blank = models.ForeignKey(Blank, verbose_name='Название бланка') <NEW_LINE> date_added = models.DateTimeField('Дата добавления', auto_now_add=True) <NEW_LINE> body = models.TextField('Текст') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Комментарий' <NEW_LINE> verbose_name_plural = 'Комментарии' <NEW_LINE> ordering = ['-date_added'] <NEW_LINE> <DEDENT> def fullname(self): <NEW_LINE> <INDENT> return self.author.get_full_name() <NEW_LINE> <DEDENT> fullname.short_description = 'Имя и Фамилия' <NEW_LINE> fullname.allow_tags = True <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '{} {}: {}'.format(self.author.first_name, self.author.last_name, self.body) | Комментарии текущего бланка | 62598fbc56ac1b37e63023ac |
class Image(ImmutableObject): <NEW_LINE> <INDENT> uri = None <NEW_LINE> width = None <NEW_LINE> height = None | :param string uri: URI of the image
:param int width: Optional width of image or :class:`None`
:param int height: Optional height of image or :class:`None` | 62598fbc0fa83653e46f50a3 |
class FileCache(BaseCache): <NEW_LINE> <INDENT> def __init__(self, path, timeout=settings.FILE_CACHE_TIMEOUT): <NEW_LINE> <INDENT> self._dir = path <NEW_LINE> self._default_timeout = timeout <NEW_LINE> <DEDENT> def _key_to_filename(self, key): <NEW_LINE> <INDENT> digest = md5hex(key) <NEW_LINE> return os.path.join(self._dir, digest[-2:], digest[:-2]) <NEW_LINE> <DEDENT> def _get(self, key): <NEW_LINE> <INDENT> filename = self._key_to_filename(key) <NEW_LINE> try: <NEW_LINE> <INDENT> if time.time() >= os.stat(filename).st_mtime: <NEW_LINE> <INDENT> self.delete(filename) <NEW_LINE> raise CacheMiss <NEW_LINE> <DEDENT> with open(filename, 'rb') as f: <NEW_LINE> <INDENT> return settings.CACHEOPS_SERIALIZER.load(f) <NEW_LINE> <DEDENT> <DEDENT> except (IOError, OSError, EOFError): <NEW_LINE> <INDENT> raise CacheMiss <NEW_LINE> <DEDENT> <DEDENT> def _set(self, key, data, timeout=None): <NEW_LINE> <INDENT> filename = self._key_to_filename(key) <NEW_LINE> dirname = os.path.dirname(filename) <NEW_LINE> if timeout is None: <NEW_LINE> <INDENT> timeout = self._default_timeout <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if not os.path.exists(dirname): <NEW_LINE> <INDENT> os.makedirs(dirname) <NEW_LINE> <DEDENT> f = os.open(filename, os.O_EXCL | os.O_WRONLY | os.O_CREAT) <NEW_LINE> try: <NEW_LINE> <INDENT> os.write(f, settings.CACHEOPS_SERIALIZER.dumps(data)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.close(f) <NEW_LINE> <DEDENT> os.utime(filename, (0, time.time() + timeout)) <NEW_LINE> <DEDENT> except (IOError, OSError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def _delete(self, fname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove(fname) <NEW_LINE> dirname = os.path.dirname(fname) <NEW_LINE> os.rmdir(dirname) <NEW_LINE> <DEDENT> except (IOError, OSError): <NEW_LINE> <INDENT> pass | A file cache which fixes bugs and misdesign in django default one.
Uses mtimes in the future to designate expire time. This makes unnecessary
reading stale files. | 62598fbc283ffb24f3cf3a42 |
class LeadSentenceSelector(BaseContentSelector): <NEW_LINE> <INDENT> def select_content(self, documents, args): <NEW_LINE> <INDENT> selected_content = [] <NEW_LINE> for doc in documents: <NEW_LINE> <INDENT> lead_sentence = doc.get_sen_bypos(0) <NEW_LINE> lead_sentence.order_by = int(doc.date + doc.art_id) <NEW_LINE> selected_content.append(lead_sentence) <NEW_LINE> <DEDENT> self.selected_content = selected_content | Functions to summarize documents | 62598fbc4a966d76dd5ef092 |
class GetTimeEstimatesInputSet(InputSet): <NEW_LINE> <INDENT> def set_CustomerID(self, value): <NEW_LINE> <INDENT> super(GetTimeEstimatesInputSet, self)._set_input('CustomerID', value) <NEW_LINE> <DEDENT> def set_ProductID(self, value): <NEW_LINE> <INDENT> super(GetTimeEstimatesInputSet, self)._set_input('ProductID', value) <NEW_LINE> <DEDENT> def set_ServerToken(self, value): <NEW_LINE> <INDENT> super(GetTimeEstimatesInputSet, self)._set_input('ServerToken', value) <NEW_LINE> <DEDENT> def set_StartLatitude(self, value): <NEW_LINE> <INDENT> super(GetTimeEstimatesInputSet, self)._set_input('StartLatitude', value) <NEW_LINE> <DEDENT> def set_StartLongitude(self, value): <NEW_LINE> <INDENT> super(GetTimeEstimatesInputSet, self)._set_input('StartLongitude', value) | An InputSet with methods appropriate for specifying the inputs to the GetTimeEstimates
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 62598fbc44b2445a339b6a55 |
class CopyToTable(luigi.task.MixinNaiveBulkComplete, luigi.Task): <NEW_LINE> <INDENT> @abc.abstractproperty <NEW_LINE> def host(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @abc.abstractproperty <NEW_LINE> def database(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @abc.abstractproperty <NEW_LINE> def user(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @abc.abstractproperty <NEW_LINE> def password(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @abc.abstractproperty <NEW_LINE> def table(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> columns = [] <NEW_LINE> null_values = (None,) <NEW_LINE> column_separator = "\t" <NEW_LINE> def create_table(self, connection): <NEW_LINE> <INDENT> if len(self.columns[0]) == 1: <NEW_LINE> <INDENT> raise NotImplementedError("create_table() not implemented for %r and columns types not specified" % self.table) <NEW_LINE> <DEDENT> elif len(self.columns[0]) == 2: <NEW_LINE> <INDENT> coldefs = ','.join( '{name} {type}'.format(name=name, type=type) for name, type in self.columns ) <NEW_LINE> query = "CREATE TABLE {table} ({coldefs})".format(table=self.table, coldefs=coldefs) <NEW_LINE> connection.cursor().execute(query) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def update_id(self): <NEW_LINE> <INDENT> return self.task_id <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def output(self): <NEW_LINE> <INDENT> raise NotImplementedError("This method must be overridden") <NEW_LINE> <DEDENT> def init_copy(self, connection): <NEW_LINE> <INDENT> if hasattr(self, "clear_table"): <NEW_LINE> <INDENT> raise Exception("The clear_table attribute has been removed. Override init_copy instead!") <NEW_LINE> <DEDENT> <DEDENT> def post_copy(self, connection): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def copy(self, cursor, file): <NEW_LINE> <INDENT> raise NotImplementedError("This method must be overridden") | An abstract task for inserting a data set into RDBMS.
Usage:
Subclass and override the following attributes:
* `host`,
* `database`,
* `user`,
* `password`,
* `table`
* `columns` | 62598fbc3d592f4c4edbb07d |
class MirraApp(main.App): <NEW_LINE> <INDENT> def setUp(self) : <NEW_LINE> <INDENT> self.env = 'qt' <NEW_LINE> self.caption = "mirra QT example" <NEW_LINE> self.size = 800, 600 <NEW_LINE> self.pos = 100,100 <NEW_LINE> self.fullScreen = 0 <NEW_LINE> self.frameRate = 15 <NEW_LINE> <DEDENT> def start(self) : <NEW_LINE> <INDENT> import qtgui <NEW_LINE> qtgui.do(self.window) <NEW_LINE> self.bgColor = 1,0.5,0.7,0.5 <NEW_LINE> s = 'this is Mirra window opened using QT' <NEW_LINE> Text(s, 10, 100) <NEW_LINE> s = 'check QT website' <NEW_LINE> Text(s, 10, 120) <NEW_LINE> s = 'You just need to set self.env to qt on setUp() to activate QT ' <NEW_LINE> Text(s, 10, 140) <NEW_LINE> s = 'If no QT is found it defaults to pygame' <NEW_LINE> Text(s, 10, 200) <NEW_LINE> d = Rect(100, 400, 0, 25, 25) <NEW_LINE> d.interactiveState = 2 <NEW_LINE> self.r = Rect(100, 100, 1, 20, 20, color=(1,0,0,1), stroke=1) <NEW_LINE> Rect(self.size[0]/2, self.size[1]/2, 1, self.size[0], self.size[1], color=(1,1,0,1), stroke=1) <NEW_LINE> Line((0,0), self.size) <NEW_LINE> Line((0,self.size[1]),(self.size[0],0)) <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> self.r.loc = self.mouseLoc <NEW_LINE> <DEDENT> def mouseDown(self, x,y): pass <NEW_LINE> def mouseUp(self, x,y): pass <NEW_LINE> def mouseDragged(self, x,y): pass <NEW_LINE> def rightMouseDown(self, x,y): pass <NEW_LINE> def rightMouseUp(self, x,y): pass <NEW_LINE> def keyPressed(self, key,x,y): pass | main appplication class, handles window contains events and graphics manager.
Subclasses main.App and extends its public methods | 62598fbc3d592f4c4edbb07e |
class NewSparkJobForm(BaseSparkJobForm): <NEW_LINE> <INDENT> prefix = "new" <NEW_LINE> emr_release = EMRReleaseChoiceField() <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.fields["identifier"].widget.attrs.update( { "data-parsley-remote": ( reverse("jobs-identifier-available") + "?identifier={value}" ), "data-parsley-remote-reverse": "true", "data-parsley-remote-message": "Identifier unavailable", "data-parsley-debounce": "500", } ) <NEW_LINE> <DEDENT> class Meta(BaseSparkJobForm.Meta): <NEW_LINE> <INDENT> fields = BaseSparkJobForm.Meta.fields + ["emr_release"] | A :class:`~BaseSparkJobForm` subclass used for creating new jobs. | 62598fbc7047854f4633f595 |
class GenericScene: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.next_scene = self <NEW_LINE> <DEDENT> def handle_event(self, event): <NEW_LINE> <INDENT> print("Info - handle_events in GenericScene has not been overridden.") <NEW_LINE> <DEDENT> def update(self, dt): <NEW_LINE> <INDENT> print("Info - update in GenericScene has not been overridden.") <NEW_LINE> <DEDENT> def draw(self, screen): <NEW_LINE> <INDENT> print("Info - draw in GenericScene has not been overridden.") | A generic base class. All other scenes are children of this. | 62598fbc60cbc95b063644fe |
class DStruct(object): <NEW_LINE> <INDENT> _fields = [] <NEW_LINE> _defaults = {} <NEW_LINE> def __init__(self, *args_t, **args_d): <NEW_LINE> <INDENT> if len(args_t) > len(self._fields): <NEW_LINE> <INDENT> raise TypeError("Number of arguments is larger than of predefined fields") <NEW_LINE> <DEDENT> for (k,v) in self._defaults.iteritems(): <NEW_LINE> <INDENT> self.__dict__[k] = copy(v) <NEW_LINE> <DEDENT> self.__dict__.update(zip(self._fields, args_t)) <NEW_LINE> self.__dict__.update(args_d) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> rv = [] <NEW_LINE> for (k,v) in self.__dict__.iteritems(): <NEW_LINE> <INDENT> rv.append(k+"="+v.__repr__()) <NEW_LINE> <DEDENT> return self.__class__.__module__+"."+self.__class__.__name__+"("+(",".join(rv))+")" | Simple dynamic structure, like :const:`collections.namedtuple` but more flexible
(and less memory-efficient) | 62598fbc57b8e32f525081fc |
class CommandError(ClientException): <NEW_LINE> <INDENT> pass | Error in CLI tool. | 62598fbc4f88993c371f05e8 |
class Article(Content): <NEW_LINE> <INDENT> article_content = tinymce_models.HTMLField() <NEW_LINE> year = models.ManyToManyField('job_ready.Year', null=True, related_name='articles') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('title',) | Model for article content. | 62598fbca8370b77170f059f |
class TautulliSensor(CoordinatorEntity, SensorEntity): <NEW_LINE> <INDENT> coordinator: TautulliDataUpdateCoordinator <NEW_LINE> def __init__( self, coordinator: TautulliDataUpdateCoordinator, name: str, monitored_conditions: list[str], usernames: list[str], ) -> None: <NEW_LINE> <INDENT> super().__init__(coordinator) <NEW_LINE> self.monitored_conditions = monitored_conditions <NEW_LINE> self.usernames = usernames <NEW_LINE> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def native_value(self) -> StateType: <NEW_LINE> <INDENT> if not self.coordinator.activity: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return self.coordinator.activity.stream_count or 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self) -> str: <NEW_LINE> <INDENT> return "mdi:plex" <NEW_LINE> <DEDENT> @property <NEW_LINE> def native_unit_of_measurement(self) -> str: <NEW_LINE> <INDENT> return "Watching" <NEW_LINE> <DEDENT> @property <NEW_LINE> def extra_state_attributes(self) -> dict[str, Any] | None: <NEW_LINE> <INDENT> if ( not self.coordinator.activity or not self.coordinator.home_stats or not self.coordinator.users ): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> _attributes = { "stream_count": self.coordinator.activity.stream_count, "stream_count_direct_play": self.coordinator.activity.stream_count_direct_play, "stream_count_direct_stream": self.coordinator.activity.stream_count_direct_stream, "stream_count_transcode": self.coordinator.activity.stream_count_transcode, "total_bandwidth": self.coordinator.activity.total_bandwidth, "lan_bandwidth": self.coordinator.activity.lan_bandwidth, "wan_bandwidth": self.coordinator.activity.wan_bandwidth, } <NEW_LINE> for stat in self.coordinator.home_stats: <NEW_LINE> <INDENT> if stat.stat_id == "top_movies": <NEW_LINE> <INDENT> _attributes["Top Movie"] = stat.rows[0].title if stat.rows else None <NEW_LINE> <DEDENT> elif stat.stat_id == "top_tv": <NEW_LINE> <INDENT> _attributes["Top TV Show"] = stat.rows[0].title if stat.rows else None <NEW_LINE> <DEDENT> elif stat.stat_id == "top_users": <NEW_LINE> <INDENT> _attributes["Top User"] = stat.rows[0].user if stat.rows else None <NEW_LINE> <DEDENT> <DEDENT> for user in self.coordinator.users: <NEW_LINE> <INDENT> if ( self.usernames and user.username not in self.usernames or user.username == "Local" ): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> _attributes.setdefault(user.username, {})["Activity"] = None <NEW_LINE> <DEDENT> for session in self.coordinator.activity.sessions: <NEW_LINE> <INDENT> if not _attributes.get(session.username): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> _attributes[session.username]["Activity"] = session.state <NEW_LINE> for key in self.monitored_conditions: <NEW_LINE> <INDENT> _attributes[session.username][key] = getattr(session, key) <NEW_LINE> <DEDENT> <DEDENT> return _attributes | Representation of a Tautulli sensor. | 62598fbcf9cc0f698b1c53ae |
class ValidObjectsManager(ModelWithInvalidManager): <NEW_LINE> <INDENT> def get_query_set(self): <NEW_LINE> <INDENT> queryset = super(ValidObjectsManager, self).get_query_set() <NEW_LINE> return queryset.filter(invalid=False) | Manager returning only objects with invalid=False. | 62598fbc7d847024c075c57c |
class PlayerStatsPlayer(tk.Frame,PlayerStats): <NEW_LINE> <INDENT> def __init__(self, parent, controller): <NEW_LINE> <INDENT> tk.Frame.__init__(self, parent) <NEW_LINE> self.controller = controller <NEW_LINE> """ Widget Declearations """ <NEW_LINE> self.Title=tk.Label(self,text="Players Stats",font=controller.title_font) <NEW_LINE> self.lblTeamNumber = tk.Label(self,text="Team Number: ") <NEW_LINE> self.txtTeamNumber = tk.Entry(self) <NEW_LINE> self.GetPlayersButton =tk.Button(self,text="Get Player Stats",command=lambda:self.GetPlayersStats()) <NEW_LINE> self.BackButton= tk.Button(self, text="Back",command=lambda:SystemToolKit.BackButtonRun(controller)) <NEW_LINE> """ Widget Stylings """ <NEW_LINE> self.Title.config(background="#8ABFD9",fg = "#404040",pady="5") <NEW_LINE> self.lblTeamNumber.config(justify="right",fg = "black",background="#8ABFD9",font=("Arial", 10, 'bold')) <NEW_LINE> self.GetPlayersButton.config(compound="left",background="#307292",relief="flat",font=("Arial", 12, 'bold'),padx=5) <NEW_LINE> self.BackButton.config(compound="left",background="#307292",relief="flat",font=("Arial", 12, 'bold'),padx=5) <NEW_LINE> """ Widget Positions """ <NEW_LINE> self.Title.grid(row=0,column =0) <NEW_LINE> self.lblTeamNumber.grid(row=1,column=0) <NEW_LINE> self.txtTeamNumber.grid(row=1,column =1) <NEW_LINE> self.GetPlayersButton.grid(row=1,column =2) <NEW_LINE> self.BackButton.grid(row=1,column=3) | Methods:
__init__
Variables:
controller
Title - Title Label Widget
lblTeamNumber -Team Number Label widget
txtTeamNumber - Team Number Entry Widget
GetPlayersButton - Get Player Button Widget
BackButton - Back Button Label Widget | 62598fbc97e22403b383b0c7 |
class AddSubfieldCommand(BaseSubfieldCommand): <NEW_LINE> <INDENT> def _perform_on_all_matching_subfields_add_subfield(self, record, tag, field_number, callback): <NEW_LINE> <INDENT> if tag not in record.keys(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> subfield_exists = False <NEW_LINE> for field in record[tag]: <NEW_LINE> <INDENT> if field[4] == field_number: <NEW_LINE> <INDENT> for subfield in field[0]: <NEW_LINE> <INDENT> if subfield[0] == self._condition_subfield: <NEW_LINE> <INDENT> subfield_exists = True <NEW_LINE> <DEDENT> if self._condition_subfield == subfield[0] and self._condition_does_not_exist == False: <NEW_LINE> <INDENT> if self._subfield_condition_match(subfield[1]): <NEW_LINE> <INDENT> self._add_subfield_modification() <NEW_LINE> callback(record, tag, field_number, None) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self._condition_does_not_exist and subfield_exists == False: <NEW_LINE> <INDENT> self._add_subfield_modification() <NEW_LINE> callback(record, tag, field_number, None) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def process_field(self, record, tag, field_number): <NEW_LINE> <INDENT> action = lambda record, tag, field_number, subfield_index: bibrecord.record_add_subfield_into(record, tag, self._subfield, self._value, None, field_position_global=field_number) <NEW_LINE> if self._condition != 'condition' or self._condition_does_not_exist: <NEW_LINE> <INDENT> self._perform_on_all_matching_subfields_add_subfield(record, tag, field_number, action) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._add_subfield_modification() <NEW_LINE> action(record, tag, field_number, None) | Add subfield to a given field | 62598fbc5fc7496912d4835b |
class NengoObject(with_metaclass(NetworkMember)): <NEW_LINE> <INDENT> def _str(self, include_id): <NEW_LINE> <INDENT> return "<%s%s%s>" % ( self.__class__.__name__, "" if not hasattr(self, 'label') else " (unlabeled)" if self.label is None else ' "%s"' % self.label, " at 0x%x" % id(self) if include_id else "") <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._str( include_id=not hasattr(self, 'label') or self.label is None) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self._str(include_id=True) <NEW_LINE> <DEDENT> def __setattr__(self, name, val): <NEW_LINE> <INDENT> if hasattr(self, '_initialized') and not hasattr(self, name): <NEW_LINE> <INDENT> warnings.warn( "Creating new attribute '%s' on '%s'. " "Did you mean to change an existing attribute?" % (name, self), SyntaxWarning) <NEW_LINE> <DEDENT> if val is Default: <NEW_LINE> <INDENT> val = Config.default(type(self), name) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> super(NengoObject, self).__setattr__(name, val) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> arg0 = '' if len(e.args) == 0 else e.args[0] <NEW_LINE> arg0 = ("Validation error when setting '%s.%s': %s" % (self.__class__.__name__, name, arg0)) <NEW_LINE> e.args = (arg0,) + e.args[1:] <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> raise NotImplementedError("Nengo objects do not support pickling") <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> raise NotImplementedError("Nengo objects do not support pickling") <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def param_list(cls): <NEW_LINE> <INDENT> return (attr for attr in dir(cls) if is_param(getattr(cls, attr))) <NEW_LINE> <DEDENT> @property <NEW_LINE> def params(self): <NEW_LINE> <INDENT> return self.param_list() | A base class for Nengo objects.
This defines some functions that the Network requires
for correct operation. In particular, list membership
and object comparison require each object to have a unique ID. | 62598fbcaad79263cf42e995 |
class TB_CoOp_Mechazod2(TB_CoOp_Mechazod): <NEW_LINE> <INDENT> pass | Overloaded Mechazod | 62598fbc01c39578d7f12f3b |
class BlackjackException(UnbelievableException): <NEW_LINE> <INDENT> pass | Blackjack related exceptions inherit from this | 62598fbccc40096d6161a2b9 |
class UpdateNodePoolRequest(_messages.Message): <NEW_LINE> <INDENT> clusterId = _messages.StringField(1) <NEW_LINE> image = _messages.StringField(2) <NEW_LINE> imageProject = _messages.StringField(3) <NEW_LINE> imageType = _messages.StringField(4) <NEW_LINE> locations = _messages.StringField(5, repeated=True) <NEW_LINE> name = _messages.StringField(6) <NEW_LINE> nodePoolId = _messages.StringField(7) <NEW_LINE> nodeVersion = _messages.StringField(8) <NEW_LINE> projectId = _messages.StringField(9) <NEW_LINE> updatedNodePool = _messages.MessageField('NodePool', 10) <NEW_LINE> zone = _messages.StringField(11) | SetNodePoolVersionRequest updates the version of a node pool.
Fields:
clusterId: Deprecated. The name of the cluster to upgrade. This field has
been deprecated and replaced by the name field.
image: The desired name of the image name to use for this node. This is
used to create clusters using a custom image.
imageProject: The project containing the desired image to use for this
node pool. This is used to create clusters using a custom image.
imageType: The desired image type for the node pool.
locations: The desired list of Google Compute Engine
[zones](/compute/docs/zones#available) in which the node pool's nodes
should be located. Changing the locations for a node pool will result in
nodes being either created or removed from the node pool, depending on
whether locations are being added or removed.
name: The name (project, location, cluster, node pool) of the node pool to
update. Specified in the format
'projects/*/locations/*/clusters/*/nodePools/*'.
nodePoolId: Deprecated. The name of the node pool to upgrade. This field
has been deprecated and replaced by the name field.
nodeVersion: The Kubernetes version to change the nodes to (typically an
upgrade). Users may specify either explicit versions offered by
Kubernetes Engine or version aliases, which have the following behavior:
- "latest": picks the highest valid Kubernetes version - "1.X": picks
the highest valid patch+gke.N patch in the 1.X version - "1.X.Y": picks
the highest valid gke.N patch in the 1.X.Y version - "1.X.Y-gke.N":
picks an explicit Kubernetes version - "-": picks the Kubernetes master
version
projectId: Deprecated. The Google Developers Console [project ID or
project number](https://support.google.com/cloud/answer/6158840). This
field has been deprecated and replaced by the name field.
updatedNodePool: The updated node pool object. This field must be empty if
any other node pool field is set (e.g. 'node_version', 'image_type',
'locations', etc.)
zone: Deprecated. The name of the Google Compute Engine
[zone](/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field. | 62598fbc56ac1b37e63023ae |
class TestCompareXLSXFiles(ExcelComparisonTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.set_filename('print_area05.xlsx') <NEW_LINE> self.ignore_files = ['xl/printerSettings/printerSettings1.bin', 'xl/worksheets/_rels/sheet1.xml.rels'] <NEW_LINE> self.ignore_elements = {'[Content_Types].xml': ['<Default Extension="bin"'], 'xl/worksheets/sheet1.xml': ['<pageMargins', '<pageSetup']} <NEW_LINE> <DEDENT> def test_create_file(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.print_area('A1:A1048576') <NEW_LINE> worksheet.write('A1', 'Foo') <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual() | Test file created by XlsxWriter against a file created by Excel. | 62598fbc4527f215b58ea095 |
class SwapDownloader(IDownloader): <NEW_LINE> <INDENT> def __init__(self, kwargs): <NEW_LINE> <INDENT> IDownloader.__init__(self, kwargs) <NEW_LINE> self.kwargs['download_file_gz'] = os.path.join( kwargs['download_path'], kwargs['site'] + '.' + kwargs['country'] + '.gz') <NEW_LINE> <DEDENT> def download(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.kwargs['download_result'] = 1 <NEW_LINE> self.kwargs['downloaded'] = 0 <NEW_LINE> fil = self.kwargs['download_file'] <NEW_LINE> fgz = self.kwargs['download_file_gz'] <NEW_LINE> ftp = FTP('datatransfer.cj.com') <NEW_LINE> ftp.login('4616059', 'JZ$TYXPJ') <NEW_LINE> ftp.cwd('outgoing/productcatalog/187926') <NEW_LINE> ftp.retrbinary('RETR Swap_com-Swap_com_Product_Catalog.txt.gz', open(fgz, 'wb').write) <NEW_LINE> ftp.quit() <NEW_LINE> with gzip.open(fgz, 'rb') as ifile, open(fil, 'wb') as ofile: <NEW_LINE> <INDENT> ofile.write(ifile.read()) <NEW_LINE> self.kwargs['downloaded'] = 1 <NEW_LINE> <DEDENT> if not self.kwargs['downloaded']: <NEW_LINE> <INDENT> raise ZeroDownloadExcept <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.kwargs['download_error'] = sys.exc_info() <NEW_LINE> self.kwargs.update({'download_result': 0}) <NEW_LINE> <DEDENT> <DEDENT> def transform(self): <NEW_LINE> <INDENT> pass | Swap downloader | 62598fbc283ffb24f3cf3a44 |
class Chromosome: <NEW_LINE> <INDENT> def __init__(self, number, kind, bases, genes): <NEW_LINE> <INDENT> self.cid = number <NEW_LINE> self.ctype = kind <NEW_LINE> self.base_pairs = bases <NEW_LINE> self.genes = genes <NEW_LINE> <DEDENT> def get_gene_density(self): <NEW_LINE> <INDENT> return self.base_pairs / self.genes <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%2s (%s): %11i bp, %4i genes" % (self.cid, self.ctype, self.base_pairs, self.genes) | Stores basic data about a chromosome. | 62598fbc5fcc89381b26622d |
@dataclass <NEW_LINE> class _DataChunkIHDR(_DataChunkBase): <NEW_LINE> <INDENT> width: int = field(init=False) <NEW_LINE> height: int = field(init=False) <NEW_LINE> def __post_init__(self): <NEW_LINE> <INDENT> super().__post_init__() <NEW_LINE> self.width, self.height = struct.unpack(">II", self.pure_data[0:8]) <NEW_LINE> <DEDENT> def replace_resolution(self, new_width: int, new_height: int) -> '_DataChunkIHDR': <NEW_LINE> <INDENT> new_data = struct.pack(">II", new_width, new_height) + self.pure_data[8:] <NEW_LINE> return _DataChunkIHDR(_BaseChunk.make_chunk("IHDR", new_data)) | Data class of ``IHDR`` chunk. | 62598fbc44b2445a339b6a56 |
class EchoTask(BaseTask): <NEW_LINE> <INDENT> def __init__(self, base, min_length=1, max_length=5): <NEW_LINE> <INDENT> super(type(self), self).__init__() <NEW_LINE> self.base = base <NEW_LINE> self.eos = 0 <NEW_LINE> self.min_length = min_length <NEW_LINE> self.max_length = max_length <NEW_LINE> self._io_pairs = self._make_io_examples(50) <NEW_LINE> <DEDENT> def _make_io_examples(self, n): <NEW_LINE> <INDENT> np_random = np.random.RandomState(1234567890) <NEW_LINE> io_pairs = [] <NEW_LINE> for _ in xrange(n): <NEW_LINE> <INDENT> length = np_random.randint(self.min_length, self.max_length + 1) <NEW_LINE> input_seq = np_random.randint(1, self.base, length).tolist() + [self.eos] <NEW_LINE> output_seq = list(input_seq) <NEW_LINE> io_pairs.append((input_seq, output_seq)) <NEW_LINE> <DEDENT> return io_pairs <NEW_LINE> <DEDENT> def make_io_set(self): <NEW_LINE> <INDENT> return self._io_pairs | Echo string coding task.
Code needs to pipe input to putput (without any modifications). | 62598fbc4428ac0f6e6586e4 |
class General(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.name = "No Name" <NEW_LINE> <DEDENT> def Init(self, parent): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def NotifyTabChanged(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def NotifyDocumentOpened(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def NotifyNewTabOpened(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def NotifyDocumentSaved(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Stop(self): <NEW_LINE> <INDENT> pass | Gadget
Plugins of this class are notified at each event listed below.
The plugin then takes its action when notified. | 62598fbc3d592f4c4edbb080 |
class FillTableMonumentsValidation(unittest.TestCase, CustomAssertions): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> datasets = fill_table.get_all_dataset_sql() <NEW_LINE> self.text = fill_table.MonumentsAllSql(datasets).get_sql() <NEW_LINE> self.data = isolate_dataset_entries(self.text) <NEW_LINE> <DEDENT> def test_fill_table_monuments_all_replaced(self): <NEW_LINE> <INDENT> self.longMessage = True <NEW_LINE> for table, dataset in self.data.items(): <NEW_LINE> <INDENT> self.assertCountEqual( dataset['to_replace'], dataset['replaced'], msg=table) <NEW_LINE> <DEDENT> <DEDENT> def test_fill_table_monuments_all_required_replacements(self): <NEW_LINE> <INDENT> required = ['source', 'changed', 'country', 'lang', 'id', 'adm0'] <NEW_LINE> for table, dataset in self.data.items(): <NEW_LINE> <INDENT> msg = '%s in fill_table_monuments_all ' % table <NEW_LINE> msg += 'missing required variable(s): %s' <NEW_LINE> self.assert_all_in(required, dataset['replaced'], msg=msg) | Validate fill_table_monuments_all.sql. | 62598fbcd7e4931a7ef3c256 |
class Car: <NEW_LINE> <INDENT> wheels = 4 <NEW_LINE> def __init__(self, make, model): <NEW_LINE> <INDENT> self.make = make <NEW_LINE> self.model = model <NEW_LINE> <DEDENT> def info(self): <NEW_LINE> <INDENT> print('Make of the car is '+self.make) <NEW_LINE> print('Model of the car is '+self.model) | This is used to describe the class | 62598fbc8a349b6b436863fe |
class ChannelShuffle(HybridBlock): <NEW_LINE> <INDENT> def __init__(self, channels, groups, **kwargs): <NEW_LINE> <INDENT> super(ChannelShuffle, self).__init__(**kwargs) <NEW_LINE> assert (channels % groups == 0) <NEW_LINE> self.groups = groups <NEW_LINE> <DEDENT> def hybrid_forward(self, F, x): <NEW_LINE> <INDENT> return channel_shuffle(x, self.groups) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> s = "{name}(groups={groups})" <NEW_LINE> return s.format( name=self.__class__.__name__, groups=self.groups) | Channel shuffle layer. This is a wrapper over the same operation. It is designed to save the number of groups.
Parameters:
----------
channels : int
Number of channels.
groups : int
Number of groups. | 62598fbc656771135c489830 |
class ColumnDefinition: <NEW_LINE> <INDENT> column_types = ("text", "number") <NEW_LINE> def __init__(self, column_name, column_type="text", not_null=False): <NEW_LINE> <INDENT> if column_name is not None and column_type in ColumnDefinition.column_types: <NEW_LINE> <INDENT> self.column_name = column_name; <NEW_LINE> self.column_type = column_type; <NEW_LINE> self.not_null = not_null; <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Invalid column definition for %s, %s" % column_name % column_type); <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return json.dumps(self, default=lambda o: o.__dict__, indent=2); | Represents a column definition in the CSV Catalog. | 62598fbc167d2b6e312b7138 |
@attr.s(auto_attribs=True, frozen=True, slots=True) <NEW_LINE> class TraceRequestRedirectParams: <NEW_LINE> <INDENT> method: str <NEW_LINE> url: URL <NEW_LINE> headers: "CIMultiDict[str]" <NEW_LINE> response: ClientResponse | Parameters sent by the `on_request_redirect` signal | 62598fbc97e22403b383b0ca |
class Summary(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.description = '' <NEW_LINE> self.duration = 0.0 <NEW_LINE> self.run = 0 <NEW_LINE> self.passed = 0 <NEW_LINE> self.skipped = 0 <NEW_LINE> self.error = 0 <NEW_LINE> self.fail = 0 <NEW_LINE> self.rate = '' <NEW_LINE> self.category = '' <NEW_LINE> <DEDENT> def round_duration(self): <NEW_LINE> <INDENT> self.duration = round(self.duration, 3) <NEW_LINE> <DEDENT> def calc_rate(self): <NEW_LINE> <INDENT> if self.run: <NEW_LINE> <INDENT> self.rate = str(round((self.passed + self.skipped) * 100.0 / self.run, 2)) + '%' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rate = '0%' <NEW_LINE> <DEDENT> <DEDENT> def calc_category(self): <NEW_LINE> <INDENT> self.category = (self.fail or self.error) and 'danger' or self.skipped and 'warning' or 'success' | Base class of representation classes | 62598fbcaad79263cf42e997 |
class ContentBase(mixins.AuthorsMixin, mixins.PublicationMixin, models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=255) <NEW_LINE> summary = models.TextField() <NEW_LINE> slug = models.SlugField() <NEW_LINE> sections = models.ManyToManyField(Section, null=True, blank=True, related_name="%(app_label)s_%(class)s_alternates") <NEW_LINE> tags = TaggableManager(blank=True) <NEW_LINE> with_section = SectionSlugManager(section_field="sections") <NEW_LINE> objects = InheritanceManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.title | The base class providing the basic "armstrong" behavior for a model.
This is provided as a way to handle cross-model querying. For example, you
can use this to query across Article and Video models assuming they both
extend from a concrete implementation of this class.
This is *not* a concrete implementation. This is to avoid having any
tables created that are not needed. `armstrong.apps.content`_ provides a
concrete implementation of this if you want to use it without defining your
own base Content model.
.. _armstrong.apps.content: http://github.com/armstrongcms/armstrong.apps.content | 62598fbcad47b63b2c5a7a17 |
class UnsupportedMapperError(Exception): <NEW_LINE> <INDENT> def __init__(self, value="No message specified."): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.value) | Exception raised when the ROM has an unsupported mapper. | 62598fbc55399d3f056266d7 |
class StudentViewTransformer(BlockStructureTransformer): <NEW_LINE> <INDENT> WRITE_VERSION = 1 <NEW_LINE> READ_VERSION = 1 <NEW_LINE> STUDENT_VIEW_DATA = 'student_view_data' <NEW_LINE> STUDENT_VIEW_MULTI_DEVICE = 'student_view_multi_device' <NEW_LINE> def __init__(self, requested_student_view_data=None): <NEW_LINE> <INDENT> self.requested_student_view_data = requested_student_view_data or [] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def name(cls): <NEW_LINE> <INDENT> return "blocks_api:student_view" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def collect(cls, block_structure): <NEW_LINE> <INDENT> block_structure.request_xblock_fields('category') <NEW_LINE> for block_key in block_structure.topological_traversal(): <NEW_LINE> <INDENT> block = block_structure.get_xblock(block_key) <NEW_LINE> student_view = getattr(block.__class__, 'student_view', None) <NEW_LINE> supports_multi_device = block.has_support(student_view, 'multi_device') <NEW_LINE> block_structure.set_transformer_block_field( block_key, cls, cls.STUDENT_VIEW_MULTI_DEVICE, supports_multi_device, ) <NEW_LINE> if getattr(block, 'student_view_data', None): <NEW_LINE> <INDENT> student_view_data = block.student_view_data() <NEW_LINE> block_structure.set_transformer_block_field( block_key, cls, cls.STUDENT_VIEW_DATA, student_view_data, ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def transform(self, usage_info, block_structure): <NEW_LINE> <INDENT> for block_key in block_structure.post_order_traversal(): <NEW_LINE> <INDENT> if block_structure.get_xblock_field(block_key, 'category') not in self.requested_student_view_data: <NEW_LINE> <INDENT> block_structure.remove_transformer_block_field(block_key, self, self.STUDENT_VIEW_DATA) | Only show information that is appropriate for a learner | 62598fbc66656f66f7d5a5b5 |
class Monster(Combat): <NEW_LINE> <INDENT> min_hit_points = 1 <NEW_LINE> max_hit_points = 1 <NEW_LINE> min_experience = 1 <NEW_LINE> max_experience = 1 <NEW_LINE> attack_strength = 1 <NEW_LINE> attack_defense = 1 <NEW_LINE> weapon = 'sword' <NEW_LINE> sound = 'roar!' <NEW_LINE> location = (0, 0) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.hit_points = random.randint(self.min_hit_points, self.max_hit_points) <NEW_LINE> self.experience = random.randint(self.min_experience, self.max_experience) <NEW_LINE> for key, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{} {}'.format(self.color.title(), self.__class__.__name__, ) <NEW_LINE> <DEDENT> def battlecry(self): <NEW_LINE> <INDENT> return self.sound | Basic monster class attributes | 62598fbcbf627c535bcb1668 |
class Vehiculo: <NEW_LINE> <INDENT> def __init__(self,variable_id=None, latitud=None, longitud=None, gasolina=100, ruta=None): <NEW_LINE> <INDENT> self._ruta = list(Ruta.select().where(Ruta.ruta == ruta)) <NEW_LINE> self._indice_ruta = 0 <NEW_LINE> self._variable_id = variable_id <NEW_LINE> self._url = 'variables/'+ self._variable_id +'/values' <NEW_LINE> self._latitud = latitud <NEW_LINE> self._longitud = longitud <NEW_LINE> self._gasolina = gasolina <NEW_LINE> self._pasajeros = 0 <NEW_LINE> <DEDENT> def conducir(self): <NEW_LINE> <INDENT> self.set_ubicacion(self._ruta[self._indice_ruta].latitud, self._ruta[self._indice_ruta].longitud) <NEW_LINE> self.set_gasolina(self._gasolina-1) <NEW_LINE> if self._ruta[self._indice_ruta] == self._ruta[-1]: <NEW_LINE> <INDENT> self._indice_ruta = 0 <NEW_LINE> self._llenar_tanque() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._indice_ruta += 1 <NEW_LINE> <DEDENT> <DEDENT> def reportar(self): <NEW_LINE> <INDENT> headers = {'content-type': 'application/json', 'X-Auth-Token' : TOKEN} <NEW_LINE> data = {'value': str(self._gasolina),'context': '{"latitud":"'+str(self._latitud) +'","longitud":"'+str(self._longitud) +'","pasajeros":"'+str(self._pasajeros) +'"}'} <NEW_LINE> response = requests.post(URL_API + self._url, data=json.dumps(data), headers = headers) <NEW_LINE> return response <NEW_LINE> <DEDENT> def set_ubicacion(self, latitud, longitud): <NEW_LINE> <INDENT> self._latitud = latitud <NEW_LINE> self._longitud = longitud <NEW_LINE> <DEDENT> def set_gasolina(self, gasolina): <NEW_LINE> <INDENT> if gasolina < 20: <NEW_LINE> <INDENT> self._llenar_tanque() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._gasolina = gasolina <NEW_LINE> <DEDENT> <DEDENT> def get_gasolina(self): <NEW_LINE> <INDENT> return self._gasolina <NEW_LINE> <DEDENT> def _llenar_tanque(self): <NEW_LINE> <INDENT> self._gasolina= 100 <NEW_LINE> <DEDENT> def set_pasajeros(self, pasajeros): <NEW_LINE> <INDENT> if pasajeros <= 45 and pasajeros >= 0: <NEW_LINE> <INDENT> self._pasajeros = pasajeros <NEW_LINE> <DEDENT> <DEDENT> def actualizar_pasajeros(self): <NEW_LINE> <INDENT> value = random.randint(1,5) <NEW_LINE> if value % 2 == 0: <NEW_LINE> <INDENT> self.set_pasajeros(self._pasajeros - value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.set_pasajeros(self._pasajeros + value) | Clase de los objetos vehiculo. | 62598fbc4527f215b58ea096 |
class catalog_055(models.Model): <NEW_LINE> <INDENT> id = models.IntegerField(primary_key=True) <NEW_LINE> src_word = models.CharField(max_length=50) <NEW_LINE> tar_word = models.CharField(max_length=50) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.src_word + "-->" + self.tar_word | Create a table which contains catalog id
and word pair.
The number of this catalog table is 055
It contains three columns:
id int type catalog id
src_word char type the source word which needs to be subsitute
tar_word char type the word that is translated from the source word | 62598fbc283ffb24f3cf3a46 |
class Solution: <NEW_LINE> <INDENT> def lastPosition(self, nums, target): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> start, end = 0, len(nums) - 1 <NEW_LINE> while start + 1 < end: <NEW_LINE> <INDENT> mid = (start + end)//2 <NEW_LINE> if nums[mid] < target: <NEW_LINE> <INDENT> start = mid <NEW_LINE> <DEDENT> elif nums[mid] == target: <NEW_LINE> <INDENT> start = mid <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> end = mid <NEW_LINE> <DEDENT> <DEDENT> if nums[end] == target: <NEW_LINE> <INDENT> return end <NEW_LINE> <DEDENT> if nums[start] == target: <NEW_LINE> <INDENT> return start <NEW_LINE> <DEDENT> return -1 | @param nums: An integer array sorted in ascending order
@param target: An integer
@return: An integer | 62598fbc67a9b606de54618f |
class MDP(gym.Env): <NEW_LINE> <INDENT> action_map = {} <NEW_LINE> observation_map = {} <NEW_LINE> discount_factor = 0.95 <NEW_LINE> def transition(self, observation, action): <NEW_LINE> <INDENT> raise NotImplementedError | Extension of OpenAI gym to Markov Decision Process (MDP) | 62598fbc2c8b7c6e89bd3989 |
class _OneLike: <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "1" | object that looks similar to the int 1 | 62598fbca219f33f346c69ca |
class Processor(AwardProcessor): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> AwardProcessor.__init__(self, 'Dead Weight', 'Most Losses', [PLAYER_COL, Column('Losses', Column.NUMBER, Column.DESC)]) <NEW_LINE> <DEDENT> def on_loss(self, e): <NEW_LINE> <INDENT> for player in model_mgr.get_players(True): <NEW_LINE> <INDENT> if player.team_id == e.team.id: <NEW_LINE> <INDENT> player_stats = stat_mgr.get_player_stats(player) <NEW_LINE> self.results[player] = player_stats.losses | Overview
This processor is awarded to the player with the most losses.
Implementation
Use the losses value from core player stats when a loss event occurs.
Notes
None. | 62598fbca8370b77170f05a3 |
class Camellia(CMakePackage): <NEW_LINE> <INDENT> homepage = "https://bitbucket.org/nateroberts/Camellia" <NEW_LINE> url = "https://bitbucket.org/nateroberts/camellia.git" <NEW_LINE> maintainers = ['CamelliaDPG'] <NEW_LINE> version('master', git='https://bitbucket.org/nateroberts/camellia.git', branch='master') <NEW_LINE> variant('moab', default=True, description='Compile with MOAB to include support for reading standard mesh formats') <NEW_LINE> depends_on('trilinos+amesos+amesos2+belos+epetra+epetraext+exodus+ifpack+ifpack2+intrepid+intrepid2+kokkos+ml+muelu+sacado+shards+teuchos+tpetra+zoltan+mumps+superlu-dist+hdf5+zlib+pnetcdf@master,12.12.1:') <NEW_LINE> depends_on('moab@:4', when='+moab') <NEW_LINE> depends_on('hdf5@:1.8') <NEW_LINE> depends_on('mpi') <NEW_LINE> def cmake_args(self): <NEW_LINE> <INDENT> spec = self.spec <NEW_LINE> options = [ '-DTrilinos_PATH:PATH=%s' % spec['trilinos'].prefix, '-DMPI_DIR:PATH=%s' % spec['mpi'].prefix, '-DBUILD_FOR_INSTALL:BOOL=ON' ] <NEW_LINE> if '+moab' in spec: <NEW_LINE> <INDENT> options.extend([ '-DENABLE_MOAB:BOOL=ON', '-DMOAB_PATH:PATH=%s' % spec['moab'].prefix ]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> options.append('-DENABLE_MOAB:BOOL=OFF') <NEW_LINE> <DEDENT> return options | Camellia: user-friendly MPI-parallel adaptive finite element package,
with support for DPG and other hybrid methods, built atop Trilinos. | 62598fbc50812a4eaa620ccd |
class ConcatDataset(Dataset): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def cumsum(sequence): <NEW_LINE> <INDENT> r, s = [], 0 <NEW_LINE> for e in sequence: <NEW_LINE> <INDENT> l = len(e) <NEW_LINE> r.append(l + s) <NEW_LINE> s += l <NEW_LINE> <DEDENT> return r <NEW_LINE> <DEDENT> def __init__(self, datasets): <NEW_LINE> <INDENT> super(ConcatDataset, self).__init__() <NEW_LINE> assert len(datasets) > 0, 'datasets should not be an empty iterable' <NEW_LINE> self.datasets = list(datasets) <NEW_LINE> self.cumulative_sizes = self.cumsum(self.datasets) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.cumulative_sizes[-1] <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx) <NEW_LINE> if dataset_idx == 0: <NEW_LINE> <INDENT> sample_idx = idx <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sample_idx = idx - self.cumulative_sizes[dataset_idx - 1] <NEW_LINE> <DEDENT> return self.datasets[dataset_idx][sample_idx] <NEW_LINE> <DEDENT> @property <NEW_LINE> def cummulative_sizes(self): <NEW_LINE> <INDENT> warnings.warn("cummulative_sizes attribute is renamed to " "cumulative_sizes", DeprecationWarning, stacklevel=2) <NEW_LINE> return self.cumulative_sizes | Dataset to concatenate multiple datasets.
Purpose: useful to assemble different existing datasets, possibly
large-scale datasets as the concatenation operation is done in an
on-the-fly manner.
Arguments:
datasets (iterable): List of datasets to be concatenated | 62598fbce5267d203ee6bac3 |
class Agent: <NEW_LINE> <INDENT> def __init__(self, q_net, t_net, memory, batch_size=128, gamma=0.999, eps_start=1.0, eps_end=0.1, eps_decay=1000000, target_update=3, learning_rate=0.01): <NEW_LINE> <INDENT> self.q_net = q_net <NEW_LINE> self.t_net = t_net <NEW_LINE> self.memory = memory <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.gamma = gamma <NEW_LINE> self.eps_start = eps_start <NEW_LINE> self.eps_end = eps_end <NEW_LINE> self.eps_decay = eps_decay <NEW_LINE> self.target_update = target_update <NEW_LINE> self.lr = learning_rate <NEW_LINE> self.steps_done = 0 <NEW_LINE> self.t_net.load_state_dict(q_net.state_dict()) <NEW_LINE> self.t_net.eval() <NEW_LINE> self.optimizer = th.optim.RMSprop(self.q_net.parameters()) <NEW_LINE> <DEDENT> def select_action(self, state): <NEW_LINE> <INDENT> sample = random.random() <NEW_LINE> if self.steps_done <= self.eps_decay: <NEW_LINE> <INDENT> eps_threshold = (self.eps_start - ((self.eps_start - self.eps_end) * (self.steps_done / self.eps_decay))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> eps_threshold = self.eps_end <NEW_LINE> <DEDENT> self.steps_done += 1 <NEW_LINE> if sample > eps_threshold: <NEW_LINE> <INDENT> with th.no_grad(): <NEW_LINE> <INDENT> return self.q_net(state).max(1)[1].view(1, 1) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return th.tensor([[random.randrange(self.q_net.num_actions)]], device=device, dtype=th.long) <NEW_LINE> <DEDENT> <DEDENT> def optimize(self): <NEW_LINE> <INDENT> from torch.nn.functional import smooth_l1_loss <NEW_LINE> if len(self.memory) < self.batch_size: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> transitions = self.memory.sample(self.batch_size) <NEW_LINE> batch = Transition(*zip(*transitions)) <NEW_LINE> non_final_mask = th.tensor(tuple(map(lambda s: s is not None, batch.next_state)), device=device, dtype=th.uint8) <NEW_LINE> non_final_next_states = th.cat([s for s in batch.next_state if s is not None]) <NEW_LINE> state_batch = th.cat(batch.state) <NEW_LINE> action_batch = th.cat(batch.action) <NEW_LINE> reward_batch = th.cat(batch.reward) <NEW_LINE> state_action_values = self.q_net(state_batch).gather(1, action_batch) <NEW_LINE> next_state_values = th.zeros(self.batch_size, device=device) <NEW_LINE> next_state_values[non_final_mask] = self.t_net(non_final_next_states).max(1)[0].detach() <NEW_LINE> expected_state_action_values = (next_state_values * self.gamma) + reward_batch <NEW_LINE> loss = smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) <NEW_LINE> self.optimizer.zero_grad() <NEW_LINE> loss.backward() <NEW_LINE> self.optimizer.step() <NEW_LINE> return loss.item() | The agent for the RL environment | 62598fbc7b180e01f3e49131 |
class ValidateNoErrors(pyblish.api.InstancePlugin): <NEW_LINE> <INDENT> order = colorbleed.api.ValidateContentsOrder <NEW_LINE> hosts = ['houdini'] <NEW_LINE> label = 'Validate no errors' <NEW_LINE> def process(self, instance): <NEW_LINE> <INDENT> validate_nodes = [] <NEW_LINE> if len(instance) > 0: <NEW_LINE> <INDENT> validate_nodes.append(instance[0]) <NEW_LINE> <DEDENT> output_node = instance.data.get("output_node") <NEW_LINE> if output_node: <NEW_LINE> <INDENT> validate_nodes.append(output_node) <NEW_LINE> <DEDENT> for node in validate_nodes: <NEW_LINE> <INDENT> self.log.debug("Validating for errors: %s" % node.path()) <NEW_LINE> errors = get_errors(node) <NEW_LINE> if errors: <NEW_LINE> <INDENT> self.log.error(errors) <NEW_LINE> raise RuntimeError("Node has errors: %s" % node.path()) | Validate the Instance has no current cooking errors. | 62598fbc5fdd1c0f98e5e155 |
class TestGenericCsvParserBot(test.BotTestCase, unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def set_bot(cls): <NEW_LINE> <INDENT> cls.bot_reference = GenericCsvParserBot <NEW_LINE> cls.default_input_message = EXAMPLE_REPORT <NEW_LINE> cls.sysconfig = {"columns": [ "source.ip|source.network", "source.url" ], "delimiter": ",", "skip_header": True, "type": "botnet drone", "time_format": "timestamp", "default_url_protocol": "http://", "type_translation": None} <NEW_LINE> <DEDENT> def test_event(self): <NEW_LINE> <INDENT> self.run_bot() <NEW_LINE> self.assertMessageEqual(0, EXAMPLE_EVENT) <NEW_LINE> self.run_bot() <NEW_LINE> self.assertMessageEqual(1, EXAMPLE_EVENT2) | A TestCase for a GenericCsvParserBot with extra, column_regex_search and windows_nt time format. | 62598fbc091ae35668704de7 |
class S3MainMenu(default.S3MainMenu): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def menu_modules(cls): <NEW_LINE> <INDENT> logged_in = current.auth.is_logged_in() <NEW_LINE> return [ MM("Home", c="default", f="index"), MM("News", c="cms", f="newsfeed", args="datalist"), MM("Map", c="gis", f="index"), MM("Disease Tracking", c="disease", f="index"), MM("Hospitals", c="hms", f="hospital"), MM("Statistics", c="stats", f="demographic_data", m="summary"), MM("more", link=False, check=logged_in)( MM("Person Registry", c="pr", f="person",), MM("Organizations", c="org", f="organisation", m="summary"), MM("Burials", c="dvi", f="body"), MM("Content Management", c="cms", f="index"), MM("Documents", c="doc", f="document"), MM("Incidents", c="event", f="incident"), MM("Logistics", c="inv", f="warehouse"), MM("Projects", c="project", f="project"), MM("Requests", c="req", f="req"), MM("Staff", c="hrm", f="staff", m="summary", check=logged_in), MM("Transport", c="transport", f="index"), MM("Vehicles", c="vehicle", f="vehicle"), ), ] | Custom Application Main Menu | 62598fbcadb09d7d5dc0a741 |
class DeleteTemplateStatus(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.DeleteStatus = None <NEW_LINE> self.DeleteTime = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.DeleteStatus = params.get("DeleteStatus") <NEW_LINE> self.DeleteTime = params.get("DeleteTime") | 删除模板响应
| 62598fbc3346ee7daa33772a |
class Option(karesansui.db.model.Model): <NEW_LINE> <INDENT> def __init__(self, created_user, modified_user, key, value=None): <NEW_LINE> <INDENT> self.created_user = created_user <NEW_LINE> self.modified_user = modified_user <NEW_LINE> self.key = key <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def get_json(self, languages): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> ret["id"] = self.id <NEW_LINE> ret["key"] = self.key <NEW_LINE> ret["value"] = self.value <NEW_LINE> ret["created_user_id"] = self.created_user_id <NEW_LINE> ret["created_user"] = self.created_user.get_json(languages) <NEW_LINE> ret["modified_user_id"] = self.modified_user_id <NEW_LINE> ret["modified_user"] = self.modified_user.get_json(languages) <NEW_LINE> ret["created"] = self.created.strftime( DEFAULT_LANGS[languages]['DATE_FORMAT'][1]) <NEW_LINE> ret["modified"] = self.modified.strftime( DEFAULT_LANGS[languages]['DATE_FORMAT'][1]) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Option<'key=%s, value=%s>" % (self.key, self.value) | <comment-ja>
Optionテーブルモデルクラス
</comment-ja>
<comment-en>
TODO: English Comment
</comment-en> | 62598fbc851cf427c66b847a |
class b2ContactManager(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> _Box2D.b2ContactManager_swiginit(self,_Box2D.new_b2ContactManager()) <NEW_LINE> <DEDENT> def AddPair(self, *args, **kwargs): <NEW_LINE> <INDENT> return _Box2D.b2ContactManager_AddPair(self, *args, **kwargs) <NEW_LINE> <DEDENT> def FindNewContacts(self): <NEW_LINE> <INDENT> return _Box2D.b2ContactManager_FindNewContacts(self) <NEW_LINE> <DEDENT> def Destroy(self, *args, **kwargs): <NEW_LINE> <INDENT> return _Box2D.b2ContactManager_Destroy(self, *args, **kwargs) <NEW_LINE> <DEDENT> def Collide(self): <NEW_LINE> <INDENT> return _Box2D.b2ContactManager_Collide(self) <NEW_LINE> <DEDENT> broadPhase = _swig_property(_Box2D.b2ContactManager_broadPhase_get, _Box2D.b2ContactManager_broadPhase_set) <NEW_LINE> contactList = _swig_property(_Box2D.b2ContactManager_contactList_get, _Box2D.b2ContactManager_contactList_set) <NEW_LINE> contactCount = _swig_property(_Box2D.b2ContactManager_contactCount_get, _Box2D.b2ContactManager_contactCount_set) <NEW_LINE> contactFilter = _swig_property(_Box2D.b2ContactManager_contactFilter_get, _Box2D.b2ContactManager_contactFilter_set) <NEW_LINE> contactListener = _swig_property(_Box2D.b2ContactManager_contactListener_get, _Box2D.b2ContactManager_contactListener_set) <NEW_LINE> allocator = _swig_property(_Box2D.b2ContactManager_allocator_get, _Box2D.b2ContactManager_allocator_set) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return _format_repr(self, ['allocator','broadPhase','contactCount','contactFilter','contactList','contactListener']) <NEW_LINE> <DEDENT> __swig_destroy__ = _Box2D.delete_b2ContactManager | Proxy of C++ b2ContactManager class | 62598fbc92d797404e388c45 |
class Redis(GenericCommandsMixin, StringCommandsMixin, HyperLogLogCommandsMixin, SetCommandsMixin, HashCommandsMixin, TransactionsCommandsMixin, SortedSetCommandsMixin, ListCommandsMixin, ScriptingCommandsMixin, ServerCommandsMixin, PubSubCommandsMixin): <NEW_LINE> <INDENT> def __init__(self, connection): <NEW_LINE> <INDENT> self._conn = connection <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Redis {!r}>'.format(self._conn) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._conn.close() <NEW_LINE> <DEDENT> @asyncio.coroutine <NEW_LINE> def wait_closed(self): <NEW_LINE> <INDENT> yield from self._conn.wait_closed() <NEW_LINE> <DEDENT> @property <NEW_LINE> def db(self): <NEW_LINE> <INDENT> return self._conn.db <NEW_LINE> <DEDENT> @property <NEW_LINE> def encoding(self): <NEW_LINE> <INDENT> return self._conn.encoding <NEW_LINE> <DEDENT> @property <NEW_LINE> def connection(self): <NEW_LINE> <INDENT> return self._conn <NEW_LINE> <DEDENT> @property <NEW_LINE> def in_transaction(self): <NEW_LINE> <INDENT> return self._conn.in_transaction <NEW_LINE> <DEDENT> @property <NEW_LINE> def closed(self): <NEW_LINE> <INDENT> return self._conn.closed <NEW_LINE> <DEDENT> def auth(self, password): <NEW_LINE> <INDENT> return self._conn.auth(password) <NEW_LINE> <DEDENT> def echo(self, message, *, encoding=_NOTSET): <NEW_LINE> <INDENT> return self._conn.execute('ECHO', message, encoding=encoding) <NEW_LINE> <DEDENT> def ping(self, *, encoding=_NOTSET): <NEW_LINE> <INDENT> return self._conn.execute('PING', encoding=encoding) <NEW_LINE> <DEDENT> def quit(self): <NEW_LINE> <INDENT> return self._conn.execute('QUIT') <NEW_LINE> <DEDENT> def select(self, db): <NEW_LINE> <INDENT> return self._conn.select(db) | High-level Redis interface.
Gathers in one place Redis commands implemented in mixins.
For commands details see: http://redis.io/commands/#connection | 62598fbc56b00c62f0fb2a80 |
class CreateVNFFG(tackerV10.CreateCommand): <NEW_LINE> <INDENT> resource = _VNFFG <NEW_LINE> remove_output_fields = ["attributes"] <NEW_LINE> def add_known_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument( 'name', metavar='NAME', help=_('Set a name for the VNFFG')) <NEW_LINE> vnffgd_group = parser.add_mutually_exclusive_group(required=True) <NEW_LINE> vnffgd_group.add_argument( '--vnffgd-id', help=_('VNFFGD ID to use as template to create VNFFG')) <NEW_LINE> vnffgd_group.add_argument( '--vnffgd-name', help=_('VNFFGD Name to use as template to create VNFFG')) <NEW_LINE> vnffgd_group.add_argument( '--vnffgd-template', help=_('VNFFGD file to create VNFFG')) <NEW_LINE> parser.add_argument( '--vnf-mapping', help=_('List of logical VNFD name to VNF instance name mapping. ' 'Example: VNF1:my_vnf1,VNF2:my_vnf2')) <NEW_LINE> parser.add_argument( '--symmetrical', action='store_true', default=False, help=_('Should a reverse path be created for the NFP')) <NEW_LINE> parser.add_argument( '--param-file', help='Specify parameter yaml file' ) <NEW_LINE> <DEDENT> def args2body(self, parsed_args): <NEW_LINE> <INDENT> args = {'attributes': {}} <NEW_LINE> body = {self.resource: args} <NEW_LINE> tacker_client = self.get_client() <NEW_LINE> tacker_client.format = parsed_args.request_format <NEW_LINE> if parsed_args.vnf_mapping: <NEW_LINE> <INDENT> _vnf_mapping = dict() <NEW_LINE> _vnf_mappings = parsed_args.vnf_mapping.split(",") <NEW_LINE> for mapping in _vnf_mappings: <NEW_LINE> <INDENT> vnfd_name, vnf = mapping.split(":", 1) <NEW_LINE> _vnf_mapping[vnfd_name] = tackerV10.find_resourceid_by_name_or_id( tacker_client, 'vnf', vnf) <NEW_LINE> <DEDENT> parsed_args.vnf_mapping = _vnf_mapping <NEW_LINE> <DEDENT> if parsed_args.vnffgd_name: <NEW_LINE> <INDENT> _id = tackerV10.find_resourceid_by_name_or_id(tacker_client, 'vnffgd', parsed_args. vnffgd_name) <NEW_LINE> parsed_args.vnffgd_id = _id <NEW_LINE> <DEDENT> elif parsed_args.vnffgd_template: <NEW_LINE> <INDENT> with open(parsed_args.vnffgd_template) as f: <NEW_LINE> <INDENT> template = f.read() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> args['vnffgd_template'] = yaml.load( template, Loader=yaml.SafeLoader) <NEW_LINE> <DEDENT> except yaml.YAMLError as e: <NEW_LINE> <INDENT> raise exceptions.InvalidInput(reason=e) <NEW_LINE> <DEDENT> if not args['vnffgd_template']: <NEW_LINE> <INDENT> raise exceptions.InvalidInput( reason='The vnffgd file is empty') <NEW_LINE> <DEDENT> <DEDENT> if parsed_args.param_file: <NEW_LINE> <INDENT> with open(parsed_args.param_file) as f: <NEW_LINE> <INDENT> param_yaml = f.read() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> args['attributes']['param_values'] = yaml.load( param_yaml, Loader=yaml.SafeLoader) <NEW_LINE> <DEDENT> except yaml.YAMLError as e: <NEW_LINE> <INDENT> raise exceptions.InvalidInput(reason=e) <NEW_LINE> <DEDENT> <DEDENT> tackerV10.update_dict(parsed_args, body[self.resource], ['tenant_id', 'name', 'vnffgd_id', 'symmetrical', 'vnf_mapping']) <NEW_LINE> return body | Create a VNFFG. | 62598fbc283ffb24f3cf3a48 |
class FirstBPEliminationDrawGenerator(BaseBPEliminationDrawGenerator): <NEW_LINE> <INDENT> def make_pairings(self): <NEW_LINE> <INDENT> nteams = len(self.teams) <NEW_LINE> if nteams % 4 != 0 or not ispow2(nteams // 4): <NEW_LINE> <INDENT> raise DrawFatalError("Tried to do a first elimination draw with invalid break size: %d" % nteams) <NEW_LINE> <DEDENT> return self._four_way_fold(self.teams) | For the first elimination round where the break size is 4*2^n. | 62598fbc76e4537e8c3ef76b |
class ShortChannelIDType(IntegerType): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> super().__init__(name, 8, '>Q') <NEW_LINE> <DEDENT> def val_to_str(self, v: int, otherfields: Dict[str, Any]) -> str: <NEW_LINE> <INDENT> return "{}x{}x{}".format(v >> 40, (v >> 16) & 0xFFFFFF, v & 0xFFFF) <NEW_LINE> <DEDENT> def val_from_str(self, s: str) -> Tuple[int, str]: <NEW_LINE> <INDENT> a, b = split_field(s) <NEW_LINE> parts = a.split('x') <NEW_LINE> if len(parts) != 3: <NEW_LINE> <INDENT> raise ValueError("short_channel_id should be NxNxN") <NEW_LINE> <DEDENT> return ((int(parts[0]) << 40) | (int(parts[1]) << 16) | (int(parts[2]))), b <NEW_LINE> <DEDENT> def val_to_py(self, v: Any, otherfields: Dict[str, Any]) -> str: <NEW_LINE> <INDENT> return self.val_to_str(v, otherfields) | short_channel_id has a special string representation, but is
basically a u64.
| 62598fbc4527f215b58ea097 |
class Registration(ResourceBody): <NEW_LINE> <INDENT> key = jose.Field('key', omitempty=True, decoder=jose.JWK.from_json) <NEW_LINE> contact = jose.Field('contact', omitempty=True, default=()) <NEW_LINE> agreement = jose.Field('agreement', omitempty=True) <NEW_LINE> status = jose.Field('status', omitempty=True) <NEW_LINE> terms_of_service_agreed = jose.Field('termsOfServiceAgreed', omitempty=True) <NEW_LINE> only_return_existing = jose.Field('onlyReturnExisting', omitempty=True) <NEW_LINE> phone_prefix = 'tel:' <NEW_LINE> email_prefix = 'mailto:' <NEW_LINE> @classmethod <NEW_LINE> def from_data(cls, phone=None, email=None, **kwargs): <NEW_LINE> <INDENT> details = list(kwargs.pop('contact', ())) <NEW_LINE> if phone is not None: <NEW_LINE> <INDENT> details.append(cls.phone_prefix + phone) <NEW_LINE> <DEDENT> if email is not None: <NEW_LINE> <INDENT> details.extend([cls.email_prefix + mail for mail in email.split(',')]) <NEW_LINE> <DEDENT> kwargs['contact'] = tuple(details) <NEW_LINE> return cls(**kwargs) <NEW_LINE> <DEDENT> def _filter_contact(self, prefix): <NEW_LINE> <INDENT> return tuple( detail[len(prefix):] for detail in self.contact if detail.startswith(prefix)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def phones(self): <NEW_LINE> <INDENT> return self._filter_contact(self.phone_prefix) <NEW_LINE> <DEDENT> @property <NEW_LINE> def emails(self): <NEW_LINE> <INDENT> return self._filter_contact(self.email_prefix) | Registration Resource Body.
:ivar josepy.jwk.JWK key: Public key.
:ivar tuple contact: Contact information following ACME spec,
`tuple` of `unicode`.
:ivar unicode agreement: | 62598fbc8a349b6b43686402 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.