code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class BW2RegionalizationError(Exception): <NEW_LINE> <INDENT> pass | Base class for BW2 regionalization errors | 625990577b25080760ed879f |
class EmailWrapper(TimestampModel, UUIDModel, OrganizationMixin): <NEW_LINE> <INDENT> name = models.CharField('Name', max_length=50) <NEW_LINE> header = models.TextField('Header', validators=[validate_template]) <NEW_LINE> footer = models.TextField('Footer', validators=[validate_template]) <NEW_LINE> default = models.BooleanField('Default', default=False) <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> verbose_name = "Email Wrapper" <NEW_LINE> verbose_name_plural = "Email Wrappers" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> Template(self.header + u' ' + self.footer) <NEW_LINE> if self.default: <NEW_LINE> <INDENT> queryset = EmailWrapper.objects.filter( organization=self.organization, default=True) <NEW_LINE> if self.pk: <NEW_LINE> <INDENT> queryset = queryset.exclude(pk=self.pk) <NEW_LINE> <DEDENT> queryset.update(default=False) <NEW_LINE> <DEDENT> return super(EmailWrapper, self).save(*args, **kwargs) | Template for email | 625990572ae34c7f260ac668 |
class DasResourceOptions(ResourceOptions): <NEW_LINE> <INDENT> serializer = DASSerializer() <NEW_LINE> capability = "feature" <NEW_LINE> chr_type = "Chromosome" <NEW_LINE> authority = "GRCh" <NEW_LINE> version = 37 <NEW_LINE> method = 'Default' <NEW_LINE> ftype = 'Default' <NEW_LINE> filename = 'placeholder.bed' <NEW_LINE> queryfunc = '' <NEW_LINE> ref_prefix = '' <NEW_LINE> filetype = None | Provides Human defaults for the metadata. User really needs to set
these however. | 6259905710dbd63aa1c7213a |
class RequestContextSerializer(om_serializer.Serializer): <NEW_LINE> <INDENT> def __init__(self, base=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._base = base <NEW_LINE> <DEDENT> def serialize_entity(self, ctxt, entity): <NEW_LINE> <INDENT> if not self._base: <NEW_LINE> <INDENT> return entity <NEW_LINE> <DEDENT> return self._base.serialize_entity(ctxt, entity) <NEW_LINE> <DEDENT> def deserialize_entity(self, ctxt, entity): <NEW_LINE> <INDENT> if not self._base: <NEW_LINE> <INDENT> return entity <NEW_LINE> <DEDENT> return self._base.deserialize_entity(ctxt, entity) <NEW_LINE> <DEDENT> def serialize_context(self, ctxt): <NEW_LINE> <INDENT> _context = ctxt.to_dict() <NEW_LINE> prof = profiler.get() <NEW_LINE> if prof: <NEW_LINE> <INDENT> trace_info = { "hmac_key": prof.hmac_key, "base_id": prof.get_base_id(), "parent_id": prof.get_id() } <NEW_LINE> _context['trace_info'] = trace_info <NEW_LINE> <DEDENT> return _context <NEW_LINE> <DEDENT> def deserialize_context(self, ctxt): <NEW_LINE> <INDENT> rpc_ctxt_dict = ctxt.copy() <NEW_LINE> trace_info = rpc_ctxt_dict.pop("trace_info", None) <NEW_LINE> if trace_info: <NEW_LINE> <INDENT> profiler.init(**trace_info) <NEW_LINE> <DEDENT> return context.Context.from_dict(rpc_ctxt_dict) | Convert RPC common context into Neutron Context. | 625990578a43f66fc4bf370f |
class BatchApi(object): <NEW_LINE> <INDENT> def __init__(self, api_client=None): <NEW_LINE> <INDENT> if api_client is None: <NEW_LINE> <INDENT> api_client = ApiClient() <NEW_LINE> <DEDENT> self.api_client = api_client <NEW_LINE> <DEDENT> def get_api_group(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.get_api_group_with_http_info(**kwargs) <NEW_LINE> <DEDENT> def get_api_group_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) <NEW_LINE> for key, val in six.iteritems(local_var_params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_api_group" % key ) <NEW_LINE> <DEDENT> local_var_params[key] = val <NEW_LINE> <DEDENT> del local_var_params['kwargs'] <NEW_LINE> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> query_params = [] <NEW_LINE> header_params = dict(local_var_params.get('_headers', {})) <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) <NEW_LINE> auth_settings = ['BearerToken'] <NEW_LINE> response_types_map = { 200: "V1APIGroup", 401: None, } <NEW_LINE> return self.api_client.call_api( '/apis/batch/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) | NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually. | 62599057462c4b4f79dbcf86 |
class TermValidator(object): <NEW_LINE> <INDENT> def set_context(self, serializer): <NEW_LINE> <INDENT> self.serializer = serializer <NEW_LINE> <DEDENT> def __call__(self, attrs): <NEW_LINE> <INDENT> model = self.serializer.Meta.model <NEW_LINE> instance = getattr(self.serializer, 'instance', None) <NEW_LINE> validated_data = dict(attrs) <NEW_LINE> request_method = self.serializer.request_method <NEW_LINE> attr_errors = {} <NEW_LINE> if request_method == 'POST': <NEW_LINE> <INDENT> for id_attr in self.serializer.Meta.lookup_fields: <NEW_LINE> <INDENT> id_value = validated_data.get(id_attr, empty) <NEW_LINE> if id_value != empty: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> instance = model.objects.get(**{id_attr: id_value}) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except MultipleObjectsReturned as e: <NEW_LINE> <INDENT> attr_errors[id_attr] = _("{} `{}`='{}'").format(str(e), id_attr, id_value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.serializer.check_object_permissions(instance) <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> parent__slug = validated_data.pop('parent__slug', None) <NEW_LINE> if parent__slug is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> TermModel.objects.get(slug=parent__slug) <NEW_LINE> <DEDENT> except (ObjectDoesNotExist, MultipleObjectsReturned) as e: <NEW_LINE> <INDENT> attr_errors['parent__slug'] = str(e) <NEW_LINE> <DEDENT> <DEDENT> if attr_errors: <NEW_LINE> <INDENT> raise serializers.ValidationError(attr_errors) <NEW_LINE> <DEDENT> validate_unique = instance is None <NEW_LINE> try: <NEW_LINE> <INDENT> model(**validated_data).full_clean(validate_unique=validate_unique) <NEW_LINE> <DEDENT> except (ObjectDoesNotExist, ValidationError) as e: <NEW_LINE> <INDENT> raise serializers.ValidationError(str(e)) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return unicode_to_repr('<%s>' % ( self.__class__.__name__ )) | Term Validator | 62599057d6c5a102081e36a1 |
class SelectField(Field): <NEW_LINE> <INDENT> type = 'select' <NEW_LINE> def __init__(self, label=None, validators=None, value=None, choices=None, **options): <NEW_LINE> <INDENT> self.choices = choices or tuple() <NEW_LINE> super(SelectField, self).__init__(label, validators=validators, value=value, **options) <NEW_LINE> <DEDENT> def parse(self, value): <NEW_LINE> <INDENT> chosen = unicode(value) <NEW_LINE> for (candidate, label) in self.choices: <NEW_LINE> <INDENT> if unicode(candidate) == chosen: <NEW_LINE> <INDENT> return chosen if value is not None else value <NEW_LINE> <DEDENT> <DEDENT> raise ValueError(_("This is not a valid choice.")) | Field for dealing with select lists.
The ``choices`` argument is used to specify the list of value-label pairs
that are used to present the valid choices in the interface. The field
value is then checked against the list of value and the parser validates
whether the supplied value is among the valid ones.
:Python type: str (unicode in Python 2.x)
:type: select | 6259905763d6d428bbee3d48 |
@python_2_unicode_compatible <NEW_LINE> class Cart(cart.Cart): <NEW_LINE> <INDENT> timestamp = None <NEW_LINE> billing_address = None <NEW_LINE> def __init__(self, session_cart, discounts=None): <NEW_LINE> <INDENT> super(Cart, self).__init__() <NEW_LINE> self.session_cart = session_cart <NEW_LINE> self.discounts = discounts <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def for_session_cart(cls, session_cart, discounts=None): <NEW_LINE> <INDENT> cart = Cart(session_cart, discounts=discounts) <NEW_LINE> product_ids = [item.data['product_id'] for item in session_cart] <NEW_LINE> products = Product.objects.filter(id__in=product_ids) <NEW_LINE> products = products.select_subclasses() <NEW_LINE> product_map = dict((p.id, p) for p in products) <NEW_LINE> for item in session_cart: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> product = product_map[item.data['product_id']] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> variant = product.variants.get(pk=item.data['variant_id']) <NEW_LINE> <DEDENT> quantity = item.quantity <NEW_LINE> cart.add(variant, quantity=quantity, check_quantity=False, skip_session_cart=True) <NEW_LINE> <DEDENT> return cart <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return pgettext( 'Shopping cart', 'Your cart (%(cart_count)s)') % {'cart_count': self.count()} <NEW_LINE> <DEDENT> def get_data_for_product(self, variant): <NEW_LINE> <INDENT> variant_price = variant.get_price_per_item(discounts=self.discounts) <NEW_LINE> variant_data = { 'product_slug': variant.product.get_slug(), 'product_id': variant.product.pk, 'variant_id': variant.pk, 'unit_price_gross': str(variant_price.gross), 'unit_price_net': str(variant_price.net)} <NEW_LINE> return variant_data <NEW_LINE> <DEDENT> def add(self, product, quantity=1, data=None, replace=False, check_quantity=True, skip_session_cart=False): <NEW_LINE> <INDENT> super(Cart, self).add(product, quantity, data, replace, check_quantity) <NEW_LINE> data = self.get_data_for_product(product) <NEW_LINE> if not skip_session_cart: <NEW_LINE> <INDENT> self.session_cart.add(smart_text(product), quantity, data, replace=replace) <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> super(Cart, self).clear() <NEW_LINE> self.session_cart.clear() <NEW_LINE> <DEDENT> def create_line(self, product, quantity, data): <NEW_LINE> <INDENT> return CartLine(product, quantity, data=data, discounts=self.discounts) | Contains cart items. Serialized instance of cart is saved into django
session. | 62599057d99f1b3c44d06c22 |
class SpinBox(InputType): <NEW_LINE> <INDENT> InputClass = QSpinBox <NEW_LINE> def __init__(self, minimum=0, maximum=100000000, step=1, lockable=False, locked=False, reversed_lock=False, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.minimum = minimum <NEW_LINE> self.maximum = maximum <NEW_LINE> self.input = self.InputClass() <NEW_LINE> self.input.setMinimum(minimum) <NEW_LINE> self.input.setMaximum(maximum) <NEW_LINE> self.input.setSingleStep(step) <NEW_LINE> self.input.valueChanged.connect(self.changed.emit) <NEW_LINE> self.registerFocusEvent(self.input) <NEW_LINE> self.lockable = lockable <NEW_LINE> if lockable: <NEW_LINE> <INDENT> self.lock_button = QPushButton() <NEW_LINE> self.lock_button.setCheckable(True) <NEW_LINE> self.lock_button.setChecked(locked) <NEW_LINE> self.lock_button.setSizePolicy( QSizePolicy.Fixed, QSizePolicy.Fixed) <NEW_LINE> def toggle_icon(emit=True): <NEW_LINE> <INDENT> is_locked = self.lock_button.isChecked() <NEW_LINE> fn = '20190619_iconset_mob_lock_locked_02.png' if is_locked else '20190619_iconset_mob_lock_unlocked_03.png' <NEW_LINE> self.input.setEnabled(is_locked if reversed_lock else not is_locked) <NEW_LINE> icon_path = os.path.join(settings.IMAGE_PATH, 'iconset_mob', fn) <NEW_LINE> icon = QIcon(icon_path) <NEW_LINE> self.lock_button.setIcon(icon) <NEW_LINE> self.locked.emit(is_locked) <NEW_LINE> <DEDENT> toggle_icon(emit=False) <NEW_LINE> self.lock_button.clicked.connect(lambda: toggle_icon(emit=True)) <NEW_LINE> <DEDENT> <DEDENT> def set_value(self, value: int): <NEW_LINE> <INDENT> self.input.setValue(value or 0) <NEW_LINE> <DEDENT> def get_value(self) -> int: <NEW_LINE> <INDENT> return self.input.value() <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_locked(self) -> bool: <NEW_LINE> <INDENT> if not self.lockable: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.lock_button.isChecked() <NEW_LINE> <DEDENT> def draw(self, layout: QLayout, unit: str = ''): <NEW_LINE> <INDENT> l = QHBoxLayout() <NEW_LINE> l.addWidget(self.input) <NEW_LINE> if unit: <NEW_LINE> <INDENT> l.addWidget(QLabel(unit)) <NEW_LINE> <DEDENT> if self.lockable: <NEW_LINE> <INDENT> l.addWidget(self.lock_button) <NEW_LINE> <DEDENT> layout.addLayout(l) | spinbox integer number input | 62599057009cb60464d02ab6 |
class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet,mixins.RetrieveModelMixin): <NEW_LINE> <INDENT> queryset = Goods.objects.all() <NEW_LINE> serializer_class = GoodsSerializer <NEW_LINE> paignation_class = GoodsPagination <NEW_LINE> filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) <NEW_LINE> filter_class = GoodsFilter <NEW_LINE> search_fields = ('name', 'goods_brief', 'goods_desc') <NEW_LINE> ordering_fields = ('sold_num', 'add_time') | 商品列表页 | 6259905730dc7b76659a0d40 |
class EasyTestStream(CondStream): <NEW_LINE> <INDENT> def __init__(self, inputs, conditions, effects, test, **kwargs): <NEW_LINE> <INDENT> super(EasyTestStream, self).__init__(inputs, [], conditions, effects, cost=TEST_COST, **kwargs) <NEW_LINE> if not callable(test): <NEW_LINE> <INDENT> raise ValueError( 'EasyTestStream expects test to be a function: %s' % test) <NEW_LINE> <DEDENT> self.test = test <NEW_LINE> <DEDENT> class StreamFn(TestStream): <NEW_LINE> <INDENT> def test(self, inputs): <NEW_LINE> <INDENT> values = tuple(inp.type.get_value(inp) for inp in inputs) <NEW_LINE> truth = self.cond_stream.test(*values) <NEW_LINE> if truth not in (True, False): <NEW_LINE> <INDENT> raise ValueError( 'Expected boolean test output but received %s' % truth) <NEW_LINE> <DEDENT> return truth | Conditional stream given by a test.
Example for collision checking:
.. code:: python
POSE = EasyType()
CollisionFree = EasyPredicate(POSE, POSE)
P1, P1 = EasyParameter(POSE), EasyParameter(POSE)
cs = EasyTestStream(inputs=[P1, P2], conditions=[], effects=[CollisionFree(P1, P2)],
test=lambda p1, p2: p1 != p2) | 625990578e71fb1e983bd04b |
class MapTreeHead(object): <NEW_LINE> <INDENT> def __init__(self, mutation_log_tree_head, root_hash): <NEW_LINE> <INDENT> self._mutation_log_tree_head = mutation_log_tree_head <NEW_LINE> self._root_hash = root_hash <NEW_LINE> <DEDENT> def mutation_log_tree_head(self): <NEW_LINE> <INDENT> return self._mutation_log_tree_head <NEW_LINE> <DEDENT> def root_hash(self): <NEW_LINE> <INDENT> return self._root_hash <NEW_LINE> <DEDENT> def tree_size(self): <NEW_LINE> <INDENT> return self.mutation_log_tree_head().tree_size() <NEW_LINE> <DEDENT> def leaf_hash(self): <NEW_LINE> <INDENT> return leaf_merkle_tree_hash(object_hash({ "mutation_log": { "tree_size": self.tree_size(), "tree_hash": base64.b64encode(self.mutation_log_tree_head().root_hash()), }, "map_hash": base64.b64encode(self.root_hash()), })) | Class for Tree Hash as returned for a map with a given size. | 62599057f7d966606f749379 |
class TargetEncoder(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def __init__(self, cols=None, dtype='float64', nocol=None): <NEW_LINE> <INDENT> if cols is not None and not isinstance(cols, (list, str)): <NEW_LINE> <INDENT> raise TypeError('cols must be None, or a list or a string') <NEW_LINE> <DEDENT> if isinstance(cols, list): <NEW_LINE> <INDENT> if not all(isinstance(c, str) for c in cols): <NEW_LINE> <INDENT> raise TypeError('each element of cols must be a string') <NEW_LINE> <DEDENT> <DEDENT> if not isinstance(dtype, str): <NEW_LINE> <INDENT> raise TypeError('dtype must be a string (e.g. \'uint8\'') <NEW_LINE> <DEDENT> if nocol is not None and nocol not in ('warn', 'err'): <NEW_LINE> <INDENT> raise ValueError('nocol must be None, \'warn\', or \'err\'') <NEW_LINE> <DEDENT> if isinstance(cols, str): <NEW_LINE> <INDENT> self.cols = [cols] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cols = cols <NEW_LINE> <DEDENT> self.dtype = dtype <NEW_LINE> self.nocol = nocol <NEW_LINE> <DEDENT> def fit(self, X, y): <NEW_LINE> <INDENT> if self.cols is None: <NEW_LINE> <INDENT> self.cols = [col for col in X if str(X[col].dtype)=='object'] <NEW_LINE> <DEDENT> if self.nocol == 'err': <NEW_LINE> <INDENT> for col in self.cols: <NEW_LINE> <INDENT> if col not in X: <NEW_LINE> <INDENT> raise ValueError('Column \''+col+'\' not in X') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif self.nocol == 'warn': <NEW_LINE> <INDENT> for col in self.cols: <NEW_LINE> <INDENT> if col not in X: <NEW_LINE> <INDENT> print('Column \''+col+'\' not in X') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.maps = dict() <NEW_LINE> for col in self.cols: <NEW_LINE> <INDENT> if col in X: <NEW_LINE> <INDENT> tmap = dict() <NEW_LINE> uniques = X[col].unique() <NEW_LINE> for unique in uniques: <NEW_LINE> <INDENT> tmap[unique] = y[X[col]==unique].mean() <NEW_LINE> <DEDENT> self.maps[col] = tmap <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def transform(self, X, y=None): <NEW_LINE> <INDENT> Xo = X.copy() <NEW_LINE> for col, tmap in self.maps.items(): <NEW_LINE> <INDENT> vals = np.full(X.shape[0], np.nan, dtype=self.dtype) <NEW_LINE> for val, mean_target in tmap.items(): <NEW_LINE> <INDENT> vals[X[col]==val] = mean_target <NEW_LINE> <DEDENT> Xo[col] = vals <NEW_LINE> <DEDENT> return Xo <NEW_LINE> <DEDENT> def fit_transform(self, X, y=None): <NEW_LINE> <INDENT> return self.fit(X, y).transform(X, y) | Target encoder.
Replaces category values in categorical column(s) with the mean target
(dependent variable) value for each category. | 62599057d7e4931a7ef3d601 |
class ThemeTaggable(object): <NEW_LINE> <INDENT> implements(IThemeTagging) <NEW_LINE> adapts(IThemeTaggable) <NEW_LINE> def __init__(self, context): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> annotations = IAnnotations(context) <NEW_LINE> mapping = annotations.get(KEY) <NEW_LINE> if mapping is None: <NEW_LINE> <INDENT> themes = {'themes': PersistentList()} <NEW_LINE> mapping = annotations[KEY] = PersistentDict(themes) <NEW_LINE> <DEDENT> self.mapping = mapping <NEW_LINE> <DEDENT> @property <NEW_LINE> def tags(self): <NEW_LINE> <INDENT> anno = IAnnotations(self.context) <NEW_LINE> mapping = anno.get(KEY) <NEW_LINE> tags = list(mapping['themes']) <NEW_LINE> return getMergedThemes(self.context, tags) <NEW_LINE> <DEDENT> @tags.setter <NEW_LINE> def tags(self, value): <NEW_LINE> <INDENT> if value == self.tags: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> anno = IAnnotations(self.context) <NEW_LINE> mapping = anno.get(KEY) <NEW_LINE> themes = list(value) <NEW_LINE> checkTheme(self.context, themes) <NEW_LINE> mapping['themes'] = PersistentList(themes) <NEW_LINE> info = Attributes(IThemeTagging, 'tags') <NEW_LINE> notify(ObjectModifiedEvent(self, info)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def nondeprecated_tags(self): <NEW_LINE> <INDENT> tags = self.tags <NEW_LINE> vocab = getUtility(IVocabularyFactory, 'Allowed themes for edit') <NEW_LINE> current_themes = [term.value for term in vocab(self)] <NEW_LINE> return [tag for tag in tags if tag in current_themes] | Theme Taggable
| 6259905745492302aabfda59 |
class TestBaseHandler(TestBase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUp(cls): <NEW_LINE> <INDENT> cls.test = cls.testbed.Testbed() <NEW_LINE> cls.test.activate() <NEW_LINE> cls.policy = cls.datastore.PseudoRandomHRConsistencyPolicy( probability=1) <NEW_LINE> cls.test.init_datastore_v3_stub(consistency_policy=cls.policy) <NEW_LINE> cls.test.init_memcache_stub() <NEW_LINE> cls.ndb.get_context().set_cache_policy(False) <NEW_LINE> cls.test.init_search_stub() <NEW_LINE> <DEDENT> def get_message_exception(self, exception): <NEW_LINE> <INDENT> self.list_args = exception.split("\n") <NEW_LINE> self.dict = eval(self.list_args[1]) <NEW_LINE> return self.dict["msg"] | SuperClass of the handler's tests. | 6259905763b5f9789fe866f5 |
class GatekeeperSerialMixin(SingleObjectMixin, GatekeeperAuthenticationMixin): <NEW_LINE> <INDENT> def get_object(self, queryset=None): <NEW_LINE> <INDENT> if self.kwargs.get('pk') and self.request.user.is_staff: <NEW_LINE> <INDENT> result = get_object_or_404(self.model, id=self.kwargs.get('pk')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> winner = get_appropriate_object_from_model(self.model) <NEW_LINE> if winner: <NEW_LINE> <INDENT> id = winner.id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> id = None <NEW_LINE> <DEDENT> result = get_object_or_404(self.model, id=id) <NEW_LINE> <DEDENT> return result | This handles serial filtering. What I mean by this:
Models using this mixin are assumed to only have one instance of the object "live" at any given time.
Therefore the gatekeeper is used against all of the instances of the model to find the "right"
instance to return.
A good example of this is a Homepage app where the content producer can stage multiple instances of the
homepage to go live at different times. | 6259905721bff66bcd7241e7 |
class Message(object): <NEW_LINE> <INDENT> def __init__(self, message, sender, message_id =1000000, sequencer=None): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> self.sender = sender <NEW_LINE> self.message_id = message_id <NEW_LINE> self.sequencer = sequencer <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> return self.__lt__(other) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if self.message_id < other.message_id: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Message class, need to maintain order in priority queue | 62599057097d151d1a2c25ed |
class CssefServer(object): <NEW_LINE> <INDENT> def __init__(self, config=None): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> if not self.config: <NEW_LINE> <INDENT> self.config = Configuration() <NEW_LINE> <DEDENT> self.database_connection = None <NEW_LINE> self.rpc_methods = Methods() <NEW_LINE> self.endpoint_sources = [] <NEW_LINE> self.plugin_manager = PluginManager(module_list=self.config.installed_plugins) <NEW_LINE> <DEDENT> def load_endpoint_sources(self): <NEW_LINE> <INDENT> from cssefserver import tasks as base_tasks <NEW_LINE> temp_list = [] <NEW_LINE> temp_list.append(base_tasks.endpoint_source()) <NEW_LINE> for plugin in self.plugin_manager.available_plugins: <NEW_LINE> <INDENT> temp_list.append(plugin.endpoint_info()) <NEW_LINE> <DEDENT> self.endpoint_sources = temp_list <NEW_LINE> <DEDENT> def load_endpoints(self): <NEW_LINE> <INDENT> logging.info("Loading endpoints from {} sources.".format(len(self.endpoint_sources))) <NEW_LINE> for source in self.endpoint_sources: <NEW_LINE> <INDENT> logging.info("Loading endpoints from source '{}'.".format(source['name'])) <NEW_LINE> for endpoint in source['endpoints']: <NEW_LINE> <INDENT> instance = endpoint['reference'](self) <NEW_LINE> self.rpc_methods.add_method(instance, endpoint['rpc_name']) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.load_endpoint_sources() <NEW_LINE> self.load_endpoints() <NEW_LINE> logging.info('Starting httpserver') <NEW_LINE> self.rpc_methods.serve_forever() | The CSSEF Server object
The server coordinates the tracking of configurations, plugins,
endpoints, database connection and socket connection (via jsonrpcserver) for
incoming requests. | 625990574e4d562566373989 |
class ResourcesHandler(webapp2.RequestHandler): <NEW_LINE> <INDENT> def rebase_path(self, path): <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> def transform_resource(self, resource_str): <NEW_LINE> <INDENT> return resource_str <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> path = self.rebase_path(self.request.path) <NEW_LINE> if path.startswith('/'): <NEW_LINE> <INDENT> path = path[1:] <NEW_LINE> <DEDENT> path = os.path.normpath(path) <NEW_LINE> resource_file = os.path.join(appengine_config.BUNDLE_ROOT, path) <NEW_LINE> mimetype = mimetypes.guess_type(resource_file)[0] <NEW_LINE> if mimetype is None: <NEW_LINE> <INDENT> mimetype = 'application/octet-stream' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.response.status = 200 <NEW_LINE> self.response.headers['Content-Type'] = mimetype <NEW_LINE> self.response.cache_control.no_cache = None <NEW_LINE> self.response.cache_control.public = 'public' <NEW_LINE> self.response.cache_control.max_age = 600 <NEW_LINE> stream = open(resource_file) <NEW_LINE> self.response.write(self.transform_resource(stream.read())) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> self.error(404) | Content handler for resources associated with custom tags. | 625990573c8af77a43b68a01 |
class About(View): <NEW_LINE> <INDENT> def dispatch_request(self): <NEW_LINE> <INDENT> return render_template("base/about.html") | Define class About with attribute(s) and method(s).
Define view for about page.
It defines:
:attributes:
| None
:methods:
| dispatch_request - Method view for about page | 625990574e4d56256637398a |
class TD_COAP_CORE_02 (CoAPTestcase): <NEW_LINE> <INDENT> pass | Identifier:
TD_COAP_CORE_02
Objective:
Perform DELETE transaction (CON mode)
Configuration:
CoAP_CFG_BASIC
References:
[COAP] 5.8.4,1.2,2.1,2.2,3.1
Pre-test
conditions:
• Server offers a /test resource that handles DELETE
Test Sequence:
Step
Type
Description
1
Stimulus
Client is requested to send a DELETE request with:
• Type = 0(CON)
• Code = 4(DELETE)
2
Check
The request sent by the client contains:
• Type=0 and Code=4
• Client-generated Message ID (➔ CMID)
• Client-generated Token (➔ CTOK)
• Uri-Path option "test"
3
Check
Server sends response containing:
• Code = 66(2.02 Deleted)
• Message ID = CMID, Token = CTOK
• Content-format option if payload non-empty
• Empty or non-empty Payload
4
Verify
Client displays the received information | 62599057dd821e528d6da441 |
class ListStaffByStatusView(ListAPIView): <NEW_LINE> <INDENT> pagination_class = CustomPagination <NEW_LINE> permission_classes = (IsCrowdfitAuthenticated, IsCrowdfitCEOUser,) <NEW_LINE> parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) <NEW_LINE> renderer_classes = (renderers.JSONRenderer,) <NEW_LINE> serializer_class = ListStaffByStatusSerializer <NEW_LINE> def is_valid_user_role_status(self, user_role_status): <NEW_LINE> <INDENT> return user_role_status.department_role.department.department_index_id != settings.CROWDFIT_API_DEPARTMENT_INDEX_COMMUNITY_ID <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> status_id = self.kwargs['status_id'] <NEW_LINE> list_user_role_status = UserRoleStatus.objects.filter(status=status_id).order_by('-user_id') <NEW_LINE> list_staff = [] <NEW_LINE> current_user_id = 0 <NEW_LINE> staff_data = None <NEW_LINE> for item in list_user_role_status: <NEW_LINE> <INDENT> if self.is_valid_user_role_status(item): <NEW_LINE> <INDENT> apt_id = item.department_role.department.apartment_id <NEW_LINE> dep_id = item.department_role.department_id <NEW_LINE> role_id = item.department_role.role_id <NEW_LINE> role_name = item.department_role.role.role <NEW_LINE> last_update = item.department_role.last_update <NEW_LINE> status_id = item.status_id <NEW_LINE> is_active = item.is_active <NEW_LINE> staff_id = None <NEW_LINE> if item.staff: <NEW_LINE> <INDENT> staff_id = item.staff_id <NEW_LINE> <DEDENT> document_url = None <NEW_LINE> if item.document_file: <NEW_LINE> <INDENT> document_url = item.document_file.file_url.url <NEW_LINE> <DEDENT> if current_user_id == item.user_id: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if staff_data: <NEW_LINE> <INDENT> list_staff.append(staff_data) <NEW_LINE> <DEDENT> staff_data = {'user_id': item.user.id, 'fullname': item.user.fullname, 'phone': item.user.phone, 'last_update': item.user.last_update, 'create_date': item.user.create_date, 'list_dep_role_status': []} <NEW_LINE> current_user_id = item.user_id <NEW_LINE> <DEDENT> staff_data['list_dep_role_status'].append({'apartment_id': apt_id, 'department_id': dep_id, 'role_id': role_id, 'role_name': role_name, 'last_update': last_update, 'staff_id': staff_id, 'document_url': document_url, 'status_id': status_id, 'is_active': is_active}) <NEW_LINE> <DEDENT> <DEDENT> if staff_data: <NEW_LINE> <INDENT> list_staff.append(staff_data) <NEW_LINE> <DEDENT> queryset = list_staff <NEW_LINE> return queryset | list all staff by status. department: All, except community | 625990572ae34c7f260ac669 |
class PreviewFamilyVisibilityMode(Enum,IComparable,IFormattable,IConvertible): <NEW_LINE> <INDENT> def __eq__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __format__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ge__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __gt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __le__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __lt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ne__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Off=None <NEW_LINE> On=None <NEW_LINE> Uncut=None <NEW_LINE> value__=None | Modes that control visibility of family elements depending on
the currently applied Element Visibility Settings of a view.
enum PreviewFamilyVisibilityMode,values: Off (0),On (1),Uncut (2) | 6259905723849d37ff852647 |
class ApproximateQAgent(PacmanQAgent): <NEW_LINE> <INDENT> def __init__(self, extractor='IdentityExtractor', **args): <NEW_LINE> <INDENT> self.featExtractor = util.lookup(extractor, globals())() <NEW_LINE> PacmanQAgent.__init__(self, **args) <NEW_LINE> self.weights = util.Counter() <NEW_LINE> <DEDENT> def getWeights(self): <NEW_LINE> <INDENT> return self.weights <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> QVal = 0 <NEW_LINE> features = self.featExtractor.getFeatures(state, action) <NEW_LINE> for feature in features: <NEW_LINE> <INDENT> QVal += self.weights[feature] * features[feature] <NEW_LINE> <DEDENT> return QVal <NEW_LINE> <DEDENT> def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> newQVal = self.discount * self.computeValueFromQValues(nextState) + reward <NEW_LINE> QVal = self.getQValue(state, action) <NEW_LINE> transition = newQVal - QVal <NEW_LINE> features = self.featExtractor.getFeatures(state, action) <NEW_LINE> for feature, value in features.iteritems(): <NEW_LINE> <INDENT> self.weights[feature] += self.alpha * transition * features[feature] <NEW_LINE> <DEDENT> <DEDENT> def final(self, state): <NEW_LINE> <INDENT> PacmanQAgent.final(self, state) <NEW_LINE> if self.episodesSoFar == self.numTraining: <NEW_LINE> <INDENT> pass | ApproximateQLearningAgent
You should only have to overwrite getQValue
and update. All other QLearningAgent functions
should work as is. | 62599057435de62698e9d386 |
class inviteIntoChat_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None, e=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.e = e <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = InviteIntoChatResponse() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e = TalkException() <NEW_LINE> self.e.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('inviteIntoChat_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.e is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e', TType.STRUCT, 1) <NEW_LINE> self.e.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- e | 625990572ae34c7f260ac66a |
class BaseTestQueue(unittest.TestCase): <NEW_LINE> <INDENT> nonexistant_keys = ('nonexistant key', ('nonexistant', 'key')) <NEW_LINE> priority_cb = None <NEW_LINE> chars = string.digits + string.ascii_letters <NEW_LINE> files = (lambda c: ['file%s' % c[x] for x in range(0, 6)])(chars) <NEW_LINE> uids = [('network%d' % i, 'user%d' % j) for i in range(0, 2) for j in range(0, 5)] <NEW_LINE> uids += [False, 0, tuple()] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(BaseTestQueue, self).setUp() <NEW_LINE> self.users = OrderedDict() <NEW_LINE> for uid in self.uids: <NEW_LINE> <INDENT> user = MockUser(uid, self.files) <NEW_LINE> self.users[user.bucket_id] = user <NEW_LINE> <DEDENT> self.assertIn(0, self.users, "Mock user setup failed: 0") <NEW_LINE> self.assertIn(False, self.users, "Mock user setup failed: False") <NEW_LINE> self.assertIn(tuple(), self.users, "Mock user setup failed: ()") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self._check_invariants() <NEW_LINE> <DEDENT> def _check_invariants(self, target_count=None, queue=None): <NEW_LINE> <INDENT> queue = queue or self.queue <NEW_LINE> self.assertEqual(len(queue._buckets), len(queue._subqueues), "There should be exactly one subqueue per entry in the heap") <NEW_LINE> self.assertTrue(all(queue._subqueues.values()), "Empty subqueues should expire immediately for maximum fairness") <NEW_LINE> if target_count is not None: <NEW_LINE> <INDENT> self.assertEqual(len(queue._buckets), target_count, "Bucket heap should gain exactly one entry per bucket") <NEW_LINE> self.assertEqual(len(queue._subqueues), target_count, "Subqueues dict should gain exactly one entry per bucket") <NEW_LINE> <DEDENT> test_heap = self.queue._buckets[:] <NEW_LINE> heapq.heapify(test_heap) <NEW_LINE> self.assertEqual(self.queue._buckets, test_heap, "Previous operation may have broken the heap invariant!") <NEW_LINE> <DEDENT> def _check_equivalence(self, other): <NEW_LINE> <INDENT> users_in_heap = [x[1] for x in sorted(self.queue._buckets)] <NEW_LINE> if isinstance(other, FairQueue): <NEW_LINE> <INDENT> self.assertEqual(len(self.queue), len(other)) <NEW_LINE> self.assertEqual(bool(self.queue), bool(other)) <NEW_LINE> users_in_other_heap = [x[1] for x in sorted(other._buckets)] <NEW_LINE> self.assertEqual(users_in_heap, users_in_other_heap, "Heap ordering not equivalent") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> other = OrderedDict((x, other[x].goal) for x in other) <NEW_LINE> <DEDENT> for user in other: <NEW_LINE> <INDENT> self.assertIn(user, users_in_heap, "One or more buckets missing from the heap") <NEW_LINE> self.assertIn(user, self.queue, "One or more buckets missing from the subqueue dict") <NEW_LINE> self.assertEqual(other[user], self.queue[user], "Must not drop or reorder requests within the same bucket") <NEW_LINE> <DEDENT> for user in users_in_heap: <NEW_LINE> <INDENT> self.assertIn(user, other, "Queue has heap entries not in other") <NEW_LINE> <DEDENT> for user in self.queue._subqueues: <NEW_LINE> <INDENT> self.assertIn(user, other, "Queue has subqueues not in other") | Code common to all `FairQueue` tests. | 625990570c0af96317c57821 |
class Evaluator(BaseEvaluator): <NEW_LINE> <INDENT> _writer_names = { 'summary': SummaryWriter, } <NEW_LINE> def evaluate(self, data): <NEW_LINE> <INDENT> for mention, ref, occs, pred in data.zip(scores=True): <NEW_LINE> <INDENT> i = np.argmax(pred) <NEW_LINE> id_ = data.labels[i] <NEW_LINE> score = pred[i] <NEW_LINE> outcome = id_ in ref <NEW_LINE> self.total += len(occs) <NEW_LINE> self.correct += outcome*len(occs) <NEW_LINE> for writer in self.writers: <NEW_LINE> <INDENT> writer.update(mention, occs, ref, id_, score, outcome) | Count a selection of outcomes and compute accuracy. | 625990572c8b7c6e89bd4d71 |
class Node: <NEW_LINE> <INDENT> def __init__(self, nodename, ip, description='', lastupd='19880000000000'): <NEW_LINE> <INDENT> self._name = nodename <NEW_LINE> self._ip = ip <NEW_LINE> self._description = description <NEW_LINE> self._lastupd = lastupd <NEW_LINE> self._execlist = [] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ('Node ' + self._nodename + '\n' + ' IP ' + self._ip) <NEW_LINE> <DEDENT> def set_node_description(self, description): <NEW_LINE> <INDENT> self._description = description <NEW_LINE> <DEDENT> def set_last_upd_time(self,lastupd): <NEW_LINE> <INDENT> self._lastupd = lastupd <NEW_LINE> <DEDENT> def insert_node_exec(self, exeobj): <NEW_LINE> <INDENT> self._execlist.append(exeobj) <NEW_LINE> <DEDENT> def remove_node_exec(self, exename): <NEW_LINE> <INDENT> for exe in self._execlist: <NEW_LINE> <INDENT> if str(exe.get_exec_name()) == exename: <NEW_LINE> <INDENT> self._execlist.remove(exe) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_node_name(self): <NEW_LINE> <INDENT> return str(self._name) <NEW_LINE> <DEDENT> def get_node_ip(self): <NEW_LINE> <INDENT> return self._ip <NEW_LINE> <DEDENT> def get_node_description(self): <NEW_LINE> <INDENT> return str(self._description) <NEW_LINE> <DEDENT> def get_node_last_upd(self): <NEW_LINE> <INDENT> return self._lastupd <NEW_LINE> <DEDENT> def get_node_exec_version_list(self): <NEW_LINE> <INDENT> verslist = [] <NEW_LINE> for exe in self._execlist: <NEW_LINE> <INDENT> verslist.append(exe.get_exec_version()) <NEW_LINE> <DEDENT> return verslist <NEW_LINE> <DEDENT> def get_node_exec_list(self): <NEW_LINE> <INDENT> return self._execlist <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> pass | A node representation.
Attributes:
name -- hostname, default = NOD | 62599057004d5f362081faae |
class ReducedUrlList(APIView): <NEW_LINE> <INDENT> permission_classes = (permissions.AllowAny,) <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> logger.error("test") <NEW_LINE> serializer.save(owner=self.request.user) <NEW_LINE> <DEDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> reducedUrl = ReducedUrl.objects.all() <NEW_LINE> serializer = ReducedUrlSerializer(reducedUrl, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> serializer = ReducedUrlSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> logger.error(request.user) <NEW_LINE> logger.error(type(request.user)) <NEW_LINE> if request.auth: <NEW_LINE> <INDENT> serializer.save(owner=request.user) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error("test if") <NEW_LINE> serializer.save() <NEW_LINE> <DEDENT> return Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | List all ReducedUrls, or create a new ReducedUrl. | 625990574a966d76dd5f0474 |
class partition_name_to_spec_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'part_name', None, None, ), ) <NEW_LINE> def __init__(self, part_name=None,): <NEW_LINE> <INDENT> self.part_name = part_name <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.part_name = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('partition_name_to_spec_args') <NEW_LINE> if self.part_name is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('part_name', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.part_name) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- part_name | 625990573cc13d1c6d466cc2 |
class MultiHeadAttention(nn.Module): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> super(MultiHeadAttention, self).__init__() <NEW_LINE> self.hidden_size = config.hidden_size <NEW_LINE> self.num_heads = config.num_heads <NEW_LINE> if self.hidden_size % self.num_heads != 0: <NEW_LINE> <INDENT> raise ValueError("hidden_size: %d is not divisible to num_heads: %d" % (self.hidden_size, self.num_heads)) <NEW_LINE> <DEDENT> self.d_k = int(self.hidden_size / self.num_heads) <NEW_LINE> self.linear_layers = cloneModule(nn.Linear(self.hidden_size, self.hidden_size), 4) <NEW_LINE> self.dropout_layer = nn.Dropout(p=config.dropout) <NEW_LINE> <DEDENT> def forward(self, query, key, value, mask=None): <NEW_LINE> <INDENT> batch_size = query.size(0) <NEW_LINE> query = self.linear_layers[0](query) .view(batch_size, -1, self.num_heads, self.d_k) .transpose(1, 2) <NEW_LINE> key = self.linear_layers[1](key) .view(batch_size, -1, self.num_heads, self.d_k) .transpose(1, 2) <NEW_LINE> value = self.linear_layers[2](value) .view(batch_size, -1, self.num_heads, self.d_k) .transpose(1, 2) <NEW_LINE> attn_output, _ = attention(query, key, value, mask, None) <NEW_LINE> attn_output = attn_output.transpose(1, 2).contiguous() .view(batch_size, -1, self.hidden_size) <NEW_LINE> output = self.linear_layers[3](attn_output) <NEW_LINE> return output | Multi-Head Attention
args:
config: TransformerConfig | 6259905716aa5153ce401a67 |
class Document(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'Links': 'list[Link]', 'FileName': 'str', 'SourceFormat': 'DocumentFormat', 'IsEncrypted': 'bool', 'IsSigned': 'bool', 'DocumentProperties': 'DocumentProperties' } <NEW_LINE> self.attributeMap = { 'Links': 'Links','FileName': 'FileName','SourceFormat': 'SourceFormat','IsEncrypted': 'IsEncrypted','IsSigned': 'IsSigned','DocumentProperties': 'DocumentProperties'} <NEW_LINE> self.Links = None <NEW_LINE> self.FileName = None <NEW_LINE> self.SourceFormat = None <NEW_LINE> self.IsEncrypted = None <NEW_LINE> self.IsSigned = None <NEW_LINE> self.DocumentProperties = None | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 625990577047854f46340942 |
class WikipediaEn(Platform): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.platformName = "Wikipedia (en)" <NEW_LINE> self.parameterName = "wikipedia" <NEW_LINE> self.tags = ["social", "news"] <NEW_LINE> self.isValidMode = {} <NEW_LINE> self.isValidMode["phonefy"] = False <NEW_LINE> self.isValidMode["usufy"] = True <NEW_LINE> self.isValidMode["searchfy"] = False <NEW_LINE> self.url = {} <NEW_LINE> self.url["usufy"] = "http://en.wikipedia.org/wiki/user:" + "<usufy>" <NEW_LINE> self.needsCredentials = {} <NEW_LINE> self.needsCredentials["usufy"] = False <NEW_LINE> self.validQuery = {} <NEW_LINE> self.validQuery["usufy"] = ".+" <NEW_LINE> self.notFoundText = {} <NEW_LINE> self.notFoundText["usufy"] = ["is not registered.", "user page</a> with this exact name.</b> In general, this page should be created and edited by"] <NEW_LINE> self.fieldsRegExp = {} <NEW_LINE> self.fieldsRegExp["usufy"] = {} <NEW_LINE> self.foundFields = {} | A <Platform> object for WikipediaEn. | 62599057be8e80087fbc0606 |
class Priority(models.Model): <NEW_LINE> <INDENT> _name = 'anytracker.priority' <NEW_LINE> _description = 'Priority of Ticket by method' <NEW_LINE> _order = 'method_id, seq' <NEW_LINE> name = fields.Char( 'Priority name', required=True, size=64, translate=True) <NEW_LINE> description = fields.Text( 'Priority description', translate=True) <NEW_LINE> seq = fields.Integer( 'Priority', help='a low value is higher priority') <NEW_LINE> active = fields.Boolean( 'Active', default=True, help='if check, this object is always available') <NEW_LINE> method_id = fields.Many2one( 'anytracker.method', string='Method', required=True, ondelete='cascade') <NEW_LINE> deadline = fields.Boolean( 'Force to choose a deadline on the ticket?') <NEW_LINE> date = fields.Date( 'Milestone') | Priorities represent the timeframe to do tasks.
It can represent timeboxes, deadlines, milestones
TODO : add milestone | 625990577cff6e4e811b6fc6 |
class MAC(Pattern): <NEW_LINE> <INDENT> pattern = compile(r'^(?:(?:[0-9a-fA-F]{1,2})([:.-])(?:[0-9a-fA-F]{1,2})\1(?:[0-9a-fA-F]{1,2})\1(?:[0-9a-fA-F]{1,2})\1(?:[0-9a-fA-F]{1,2})\1(?:[0-9a-fA-F]{1,2}))$') | A Media Access Control (MAC) address. Also referred to as a "Wi-Fi Address" or "Hardware ID". | 625990573eb6a72ae038bbe3 |
class AdvancedSearchTSVView(FormView): <NEW_LINE> <INDENT> form_class = AdvSearchDownloadForm <NEW_LINE> header_template = "DataRepo/search/downloads/download_header.tsv" <NEW_LINE> row_template = "DataRepo/search/downloads/download_row.tsv" <NEW_LINE> content_type = "application/text" <NEW_LINE> success_url = "" <NEW_LINE> basv_metadata = BaseAdvancedSearchView() <NEW_LINE> def form_invalid(self, form): <NEW_LINE> <INDENT> saved_form = form.saved_data <NEW_LINE> qry = {} <NEW_LINE> if "qryjson" in saved_form: <NEW_LINE> <INDENT> qry = json.loads(saved_form["qryjson"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("ERROR: qryjson hidden input not in saved form.") <NEW_LINE> <DEDENT> now = datetime.now() <NEW_LINE> dt_string = now.strftime("%d/%m/%Y %H:%M:%S") <NEW_LINE> res = {} <NEW_LINE> return self.render_to_response( self.get_context_data(res=res, qry=qry, dt=dt_string, debug=settings.DEBUG) ) <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> cform = form.cleaned_data <NEW_LINE> try: <NEW_LINE> <INDENT> qry = json.loads(cform["qryjson"]) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> qry = cform["qryjson"] <NEW_LINE> <DEDENT> if not isQryObjValid(qry, self.basv_metadata.getFormatNames().keys()): <NEW_LINE> <INDENT> print("ERROR: Invalid qry object: ", qry) <NEW_LINE> raise Http404("Invalid json") <NEW_LINE> <DEDENT> now = datetime.now() <NEW_LINE> dt_string = now.strftime("%d/%m/%Y %H:%M:%S") <NEW_LINE> filename = ( qry["searches"][qry["selectedtemplate"]]["name"] + "_" + now.strftime("%d.%m.%Y.%H.%M.%S") + ".tsv" ) <NEW_LINE> if isValidQryObjPopulated(qry): <NEW_LINE> <INDENT> res, tot = performQuery(qry, qry["selectedtemplate"], self.basv_metadata) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res, tot = getAllBrowseData(qry["selectedtemplate"], self.basv_metadata) <NEW_LINE> <DEDENT> headtmplt = loader.get_template(self.header_template) <NEW_LINE> rowtmplt = loader.get_template(self.row_template) <NEW_LINE> return StreamingHttpResponse( self.tsv_template_iterator(rowtmplt, headtmplt, res, qry, dt_string), content_type=self.content_type, headers={"Content-Disposition": f"attachment; filename={filename}"}, ) <NEW_LINE> <DEDENT> def tsv_template_iterator(self, rowtmplt, headtmplt, res, qry, dt): <NEW_LINE> <INDENT> yield headtmplt.render({"qry": qry, "dt": dt}) <NEW_LINE> for row in res: <NEW_LINE> <INDENT> yield rowtmplt.render({"qry": qry, "row": row}) | This is the download view for the advanced search page. | 625990573617ad0b5ee076cd |
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class ModuleDriver(object): <NEW_LINE> <INDENT> def get_type(self): <NEW_LINE> <INDENT> return self.get_name() <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.__class__.__name__.lower().replace( 'driver', '').replace(' ', '_') <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def get_description(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def get_updated(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def apply(self, name, datastore, ds_version, data_file): <NEW_LINE> <INDENT> return False, "Not a concrete driver" <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def remove(self, name, datastore, ds_version, data_file): <NEW_LINE> <INDENT> return False, "Not a concrete driver" | Base class that defines the contract for module drivers.
Note that you don't have to derive from this class to have a valid
driver; it is purely a convenience. | 62599057d99f1b3c44d06c24 |
class TransformedSeriesTest(test.TestCase): <NEW_LINE> <INDENT> def test_repr(self): <NEW_LINE> <INDENT> col = learn.TransformedSeries( [mocks.MockSeries("foobar", [])], mocks.MockTwoOutputTransform("thb", "nth", "snt"), "qux") <NEW_LINE> expected = ("MockTransform({'param_one': 'thb', 'param_three': 'snt', " "'param_two': 'nth'})" "(foobar)[qux]") <NEW_LINE> self.assertEqual(expected, repr(col)) <NEW_LINE> <DEDENT> def test_build_no_output(self): <NEW_LINE> <INDENT> def create_no_output_series(): <NEW_LINE> <INDENT> return learn.TransformedSeries( [mocks.MockSeries("foobar", [])], mocks.MockZeroOutputTransform("thb", "nth"), None) <NEW_LINE> <DEDENT> self.assertRaises(ValueError, create_no_output_series) <NEW_LINE> <DEDENT> def test_build_single_output(self): <NEW_LINE> <INDENT> col = learn.TransformedSeries([mocks.MockSeries("foobar", [])], mocks.MockOneOutputTransform("thb", "nth"), "out1") <NEW_LINE> result = col.build() <NEW_LINE> expected = mocks.MockTensor("Mock Tensor 1", dtypes.int32) <NEW_LINE> self.assertEqual(expected, result) <NEW_LINE> <DEDENT> def test_build_multiple_output(self): <NEW_LINE> <INDENT> col = learn.TransformedSeries( [mocks.MockSeries("foobar", [])], mocks.MockTwoOutputTransform("thb", "nth", "snt"), "out2") <NEW_LINE> result = col.build() <NEW_LINE> expected = mocks.MockTensor("Mock Tensor 2", dtypes.int32) <NEW_LINE> self.assertEqual(expected, result) | Test of `TransformedSeries`. | 625990578e71fb1e983bd04d |
class NuagePoints: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def fit(self, X, y=None): <NEW_LINE> <INDENT> self.nuage = X <NEW_LINE> self.labels = y <NEW_LINE> <DEDENT> def kneighbors(self, X, n_neighbors=1, return_distance=True): <NEW_LINE> <INDENT> if n_neighbors != 1: <NEW_LINE> <INDENT> raise NotImplementedError( "Not implemented when n_neighbors != 1.") <NEW_LINE> <DEDENT> if not return_distance: <NEW_LINE> <INDENT> raise NotImplementedError( "Not implemented when return_distance is False.") <NEW_LINE> <DEDENT> dist = numpy.zeros(X.shape[0]) <NEW_LINE> ind = numpy.zeros(X.shape[0], dtype=numpy.int64) <NEW_LINE> for i in range(X.shape[0]): <NEW_LINE> <INDENT> row = X[i, :] <NEW_LINE> row.resize((1, X.shape[1])) <NEW_LINE> r = self.ppv(row) <NEW_LINE> dist[i], ind[i] = r <NEW_LINE> <DEDENT> return dist, ind <NEW_LINE> <DEDENT> @property <NEW_LINE> def shape(self): <NEW_LINE> <INDENT> return self.nuage.shape <NEW_LINE> <DEDENT> def distance(self, obj1, obj2): <NEW_LINE> <INDENT> return euclidean(obj1, obj2) <NEW_LINE> <DEDENT> def label(self, i): <NEW_LINE> <INDENT> return self.label[i] if self.label is not None else None <NEW_LINE> <DEDENT> def ppv(self, obj): <NEW_LINE> <INDENT> ones = numpy.ones((self.nuage.shape[0], 1)) <NEW_LINE> mat = ones @ obj <NEW_LINE> if len(mat.shape) == 1: <NEW_LINE> <INDENT> mat.resize((mat.shape[0], 1)) <NEW_LINE> <DEDENT> delta = self.nuage - mat <NEW_LINE> norm = numpy.linalg.norm(delta, axis=1) <NEW_LINE> i = numpy.argmin(norm) <NEW_LINE> return norm[i], i | Définit une classe de nuage de points.
On suppose qu'ils sont définis par une matrice,
chaque ligne est un élément. | 62599057dd821e528d6da442 |
class LinfProjectedGradientDescentAttack(LinfBaseGradientDescent): <NEW_LINE> <INDENT> def __init__( self, *, rel_stepsize: float = 0.01 / 0.3, abs_stepsize: Optional[float] = None, steps: int = 40, random_start: bool = True, ) -> None: <NEW_LINE> <INDENT> super().__init__( rel_stepsize=rel_stepsize, abs_stepsize=abs_stepsize, steps=steps, random_start=random_start, ) | Linf Projected Gradient Descent
Args:
rel_stepsize: Stepsize relative to epsilon (defaults to 0.01 / 0.3).
abs_stepsize: If given, it takes precedence over rel_stepsize.
steps : Number of update steps to perform.
random_start : Whether the perturbation is initialized randomly or starts at zero. | 6259905701c39578d7f141f9 |
class Node( object ): <NEW_LINE> <INDENT> __metaclass__ = DynamicProps <NEW_LINE> def __init__( self, name, rwAttrs=None, roAttrs=None ): <NEW_LINE> <INDENT> self.makeProperty( "name", name, True ) <NEW_LINE> self.makeProperty( "visited", False ) <NEW_LINE> self.__edges = list() <NEW_LINE> rwAttrs = rwAttrs if type(rwAttrs) == dict else {} <NEW_LINE> for attr, value in rwAttrs.items(): <NEW_LINE> <INDENT> self.makeProperty( attr, value, False ) <NEW_LINE> <DEDENT> roAttrs = roAttrs if type(roAttrs) == dict else {} <NEW_LINE> for attr, value in roAttrs.items(): <NEW_LINE> <INDENT> self.makeProperty( attr, value, True ) <NEW_LINE> <DEDENT> <DEDENT> def __contains__( self, edge ): <NEW_LINE> <INDENT> if not isinstance( edge, Edge ): <NEW_LINE> <INDENT> raise TypeError( "edge should be an instance or subclass of Edge" ) <NEW_LINE> <DEDENT> return edge in self.__edges <NEW_LINE> <DEDENT> def __iter__( self ): <NEW_LINE> <INDENT> return self.__edges.__iter__() <NEW_LINE> <DEDENT> def edges( self ): <NEW_LINE> <INDENT> return self.__edges <NEW_LINE> <DEDENT> def addEdge( self, edge ): <NEW_LINE> <INDENT> if not isinstance( edge, Edge ): <NEW_LINE> <INDENT> raise TypeError( "supplied edge argument should be an Edge instance or subclass" ) <NEW_LINE> <DEDENT> if edge not in self: <NEW_LINE> <INDENT> self.__edges.append( edge ) <NEW_LINE> <DEDENT> <DEDENT> def connect( self, other, rwAttrs=None, roAttrs=None ): <NEW_LINE> <INDENT> if not isinstance( other, Node ): <NEW_LINE> <INDENT> raise TypeError( "argument other should be a Node instance!" ) <NEW_LINE> <DEDENT> edge = Edge( self, other, rwAttrs, roAttrs ) <NEW_LINE> if edge not in self: <NEW_LINE> <INDENT> self.__edges.append( edge ) <NEW_LINE> <DEDENT> return edge | .. class:: Node
graph node | 625990578e7ae83300eea611 |
class Slurm(Scheduler): <NEW_LINE> <INDENT> _vardict = {"cores":"core", "nodes":"nodes", "cpus_per_task":"cpus_per_task"} <NEW_LINE> def initialize(self): <NEW_LINE> <INDENT> self.get_vardict() <NEW_LINE> <DEDENT> def get_script(self): <NEW_LINE> <INDENT> lines = []; app = lines.append <NEW_LINE> app('#!/bin/bash -l\n') <NEW_LINE> partition = self.get_arg("partition",None) <NEW_LINE> if self.name: app("#SBATCH -J %s"%self.name) <NEW_LINE> if partition: app('#SBATCH --partition %s'%partition) <NEW_LINE> qos = self.get_arg("qos",None) <NEW_LINE> if qos: app('#SBATCH --qos=%s'%qos) <NEW_LINE> dependency = self.get_arg("dependency",None) <NEW_LINE> if dependency: app("#SBATCH --dependency=%s"%dependency) <NEW_LINE> if self.nodes: app("#SBATCH -N %d" % self.nodes) <NEW_LINE> if self.cores: app("#SBATCH --ntasks-per-node=%d" % self.cores) <NEW_LINE> if self.cpus_per_task: app("#SBATCH --cpus-per-task=%d" % self.cpus_per_task ) <NEW_LINE> mem_per_cpu = self.get_arg("mem_per_cpu",None) <NEW_LINE> if mem_per_cpu: app("#SBATCH --mem-per-cpu=%s" % mem_per_cpu) <NEW_LINE> app("#SBATCH --time=0-%s" % self.walltime) <NEW_LINE> app(self.get_commands()) <NEW_LINE> return "\n".join(lines) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.get_script() <NEW_LINE> <DEDENT> def run(self,filename='run.sh',dry=False,command="sbatch",verbose=0): <NEW_LINE> <INDENT> if dry: <NEW_LINE> <INDENT> print(self) <NEW_LINE> return <NEW_LINE> <DEDENT> self.write(filename) <NEW_LINE> workdir = os.path.dirname(filename) <NEW_LINE> basename = os.path.basename(filename) <NEW_LINE> p = subprocess.Popen([command,basename],stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd=workdir) <NEW_LINE> self.stdout,self.stderr = p.communicate() <NEW_LINE> self.jobid = self.stdout.decode().split(' ')[-1].strip() <NEW_LINE> if self.stderr: raise Exception(self.stderr) <NEW_LINE> if verbose: print(self.stdout) <NEW_LINE> <DEDENT> def check_job_status(self,workdir): <NEW_LINE> <INDENT> p = subprocess.Popen(['squeue','-j %s'%self.jobid],stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd=workdir) <NEW_LINE> stdout,stderr = p.communicate() <NEW_LINE> if stdout: <NEW_LINE> <INDENT> if stdout.decode()[-9:-1]=='(REASON)': job_status = 'NULL' <NEW_LINE> else: job_status = stdout.decode().split('\n')[1].split()[4] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> job_status = 'NULL' <NEW_LINE> <DEDENT> return job_status | Class to submit jobs through the Slurm scheduler
``_vardict`` states the default assignement of the nodes and cores variables
from the schduler class to the variables needed in this class | 6259905723849d37ff852649 |
class URLTest(TestCase): <NEW_LINE> <INDENT> def test_unescape(self): <NEW_LINE> <INDENT> self.assertEqual(unescape(u'foo&bar'), u'foo&bar') <NEW_LINE> self.assertEqual(unescape(u'foo bar'), u'foo\xa0bar') <NEW_LINE> self.assertEqual(unescape(u'"foo"'), u'"foo"') <NEW_LINE> <DEDENT> def test_normalisation(self): <NEW_LINE> <INDENT> self.assertEqual(normaliseURL('http://example.com//bar/baz&baz'), u'http://example.com/bar/baz&baz') | Tests for URL utility functions. | 62599057379a373c97d9a5a9 |
class TaskWindowLayout(LayoutContainer): <NEW_LINE> <INDENT> active_task = Str <NEW_LINE> items = List(Either(Str, TaskLayout), pretty_skip=True) <NEW_LINE> position = Tuple(-1, -1) <NEW_LINE> size = Tuple(800, 600) <NEW_LINE> def get_active_task(self): <NEW_LINE> <INDENT> if self.active_task: <NEW_LINE> <INDENT> return self.active_task <NEW_LINE> <DEDENT> elif self.items: <NEW_LINE> <INDENT> first = self.items[0] <NEW_LINE> return first if isinstance(first, basestring) else first.id <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_tasks(self): <NEW_LINE> <INDENT> return [ (item if isinstance(item, basestring) else item.id) for item in self.items ] <NEW_LINE> <DEDENT> def is_equivalent_to(self, layout): <NEW_LINE> <INDENT> return isinstance(layout, TaskWindowLayout) and set(self.get_tasks()) == set(layout.get_tasks()) | The layout of a TaskWindow.
| 625990578e7ae83300eea612 |
class UserQuestSetAction(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "User Quest Set Action" <NEW_LINE> verbose_name_plural = "User Quest Set Actions" <NEW_LINE> unique_together = ("user", "questset") <NEW_LINE> <DEDENT> user = models.ForeignKey(User, db_index=True) <NEW_LINE> questset = models.ForeignKey('QuestSet', db_index=True) <NEW_LINE> complete = models.BooleanField(default=False) <NEW_LINE> beginTime = models.DateField() <NEW_LINE> completionTime = models.DateField(null=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return str(self.user) + " - " + str(self.questset) | Tracks the progress of a given User for a given Quest Set | 6259905729b78933be26ab87 |
class ReversibleSequence(Module): <NEW_LINE> <INDENT> def __init__(self, blocks, rev_thres = 0, send_signal = False): <NEW_LINE> <INDENT> self.rev_thres = rev_thres <NEW_LINE> self.blocks = nn.ModuleList([ReversibleBlock(f, g, depth, send_signal) for depth, (f, g) in enumerate(blocks)]) <NEW_LINE> self.irrev_blocks = nn.ModuleList([IrreversibleBlock(f=f, g=g) for f, g in blocks]) <NEW_LINE> <DEDENT> def forward(self, x, arg_route = (True, True), **kwargs): <NEW_LINE> <INDENT> reverse = x.shape[1] > self.rev_thres <NEW_LINE> blocks = self.blocks if reverse else self.irrev_blocks <NEW_LINE> f_args, g_args = map(lambda route: kwargs if route else {}, arg_route) <NEW_LINE> block_kwargs = {'f_args': f_args, 'g_args': g_args} <NEW_LINE> if not reverse: <NEW_LINE> <INDENT> for block in blocks: <NEW_LINE> <INDENT> x = block(x, **block_kwargs) <NEW_LINE> <DEDENT> return x <NEW_LINE> <DEDENT> return _ReversibleFunction.apply(x, blocks, block_kwargs) | Stack of ReversibleBlocks constructed from blocks.Applies ReversibleBlocks if
sequence length is > rev_thres or else IrreversibleBlocks. | 625990571f037a2d8b9e532e |
class User(AbstractUser): <NEW_LINE> <INDENT> name = CharField(_("Name of User"), blank=True, max_length=255) <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse("users:detail", kwargs={"username": self.username}) | Default user for url-tweets. | 6259905791af0d3eaad3b3ad |
@final <NEW_LINE> class PytestUnhandledCoroutineWarning(PytestWarning): <NEW_LINE> <INDENT> __module__ = "pytest" | Warning emitted for an unhandled coroutine.
A coroutine was encountered when collecting test functions, but was not
handled by any async-aware plugin.
Coroutine test functions are not natively supported. | 625990577047854f46340944 |
class ModifiedAccessConditions(Model): <NEW_LINE> <INDENT> _attribute_map = { 'if_modified_since': {'key': '', 'type': 'rfc-1123'}, 'if_unmodified_since': {'key': '', 'type': 'rfc-1123'}, 'if_match': {'key': '', 'type': 'str'}, 'if_none_match': {'key': '', 'type': 'str'}, } <NEW_LINE> def __init__(self, *, if_modified_since=None, if_unmodified_since=None, if_match: str=None, if_none_match: str=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(ModifiedAccessConditions, self).__init__(**kwargs) <NEW_LINE> self.if_modified_since = if_modified_since <NEW_LINE> self.if_unmodified_since = if_unmodified_since <NEW_LINE> self.if_match = if_match <NEW_LINE> self.if_none_match = if_none_match | Additional parameters for a set of operations.
:param if_modified_since: Specify this header value to operate only on a
blob if it has been modified since the specified date/time.
:type if_modified_since: datetime
:param if_unmodified_since: Specify this header value to operate only on a
blob if it has not been modified since the specified date/time.
:type if_unmodified_since: datetime
:param if_match: Specify an ETag value to operate only on blobs with a
matching value.
:type if_match: str
:param if_none_match: Specify an ETag value to operate only on blobs
without a matching value.
:type if_none_match: str | 6259905716aa5153ce401a69 |
class QQPDOffsetDisplay(QOffsetDisplay): <NEW_LINE> <INDENT> def __init__(self, q_label = None, **kwds): <NEW_LINE> <INDENT> super().__init__(**kwds) <NEW_LINE> self.q_label = q_label <NEW_LINE> self.update_timer = QtCore.QTimer(self) <NEW_LINE> self.update_timer.setInterval(100) <NEW_LINE> self.update_timer.timeout.connect(self.handleUpdateTimer) <NEW_LINE> self.update_timer.start() <NEW_LINE> <DEDENT> def handleGoodLock(self, good_lock): <NEW_LINE> <INDENT> if good_lock: <NEW_LINE> <INDENT> self.bar_color = QtGui.QColor(0, 255, 0, 150) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.bar_color = QtGui.QColor(0, 0, 0, 150) <NEW_LINE> <DEDENT> <DEDENT> def handleUpdateTimer(self): <NEW_LINE> <INDENT> self.q_label.setText("{0:.1f}".format(self.value)) <NEW_LINE> <DEDENT> def setFunctionality(self, functionality): <NEW_LINE> <INDENT> super().setFunctionality(functionality) <NEW_LINE> self.has_center_bar = self.functionality.getParameter("offset_has_center_bar") <NEW_LINE> self.scale_max = 1000.0 * self.functionality.getParameter("offset_maximum") <NEW_LINE> self.scale_min = 1000.0 * self.functionality.getParameter("offset_minimum") <NEW_LINE> self.warning_high = 1000.0 * self.functionality.getParameter("offset_warning_high") <NEW_LINE> self.warning_low = 1000.0 * self.functionality.getParameter("offset_warning_low") <NEW_LINE> self.scale_range = 1.0/(self.scale_max - self.scale_min) <NEW_LINE> self.functionality.qpdUpdate.connect(self.updateValue) <NEW_LINE> <DEDENT> def updateValue(self, qpd_dict): <NEW_LINE> <INDENT> if self.isEnabled() and qpd_dict["is_good"]: <NEW_LINE> <INDENT> value = 1000.0 * qpd_dict["offset"] <NEW_LINE> super().updateValue(value) | Focus lock offset display. Converts to nanometers. | 62599057be8e80087fbc0608 |
class MatchingContainers(object): <NEW_LINE> <INDENT> def __init__(self, label_value): <NEW_LINE> <INDENT> self.label_value = label_value <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> filters = {'status': 'running', 'label': 'org.eff.certbot.cert_cns'} <NEW_LINE> try: <NEW_LINE> <INDENT> client = docker.client.DockerClient() <NEW_LINE> containers = client.containers.list(filters=filters) <NEW_LINE> for container in containers: <NEW_LINE> <INDENT> label_value = container.labels.get('org.eff.certbot.cert_cns') <NEW_LINE> if csv_contains_value(label_value, self.label_value): <NEW_LINE> <INDENT> yield container <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except docker.errors.APIError as error: <NEW_LINE> <INDENT> raise ContainerError(str(error)) | Iterable for live Docker containers matching filter label value. | 625990574428ac0f6e659ac1 |
class ShowChildren(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.show_children" <NEW_LINE> bl_label = "Show all children of active object" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> active_ob = bpy.context.object <NEW_LINE> if bpy.context.scene.select_recursive: <NEW_LINE> <INDENT> children = selChildrenRecur([active_ob]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> children = [ob for ob in bpy.context.scene.objects if ob.parent == active_ob] <NEW_LINE> <DEDENT> for ob in children: <NEW_LINE> <INDENT> ob.hide = False <NEW_LINE> <DEDENT> return {'FINISHED'} | Show all children of active object | 62599057507cdc57c63a632b |
@dataclass(frozen=True) <NEW_LINE> class SbdWithDevicesNotUsedCannotSetDevice(ReportItemMessage): <NEW_LINE> <INDENT> node: str <NEW_LINE> _code = codes.SBD_WITH_DEVICES_NOT_USED_CANNOT_SET_DEVICE <NEW_LINE> @property <NEW_LINE> def message(self) -> str: <NEW_LINE> <INDENT> return ( "Cluster is not configured to use SBD with shared storage, cannot " f"specify SBD devices for node '{self.node}'" ) | The cluster is not using SBD with devices, cannot specify a device.
node -- node name | 6259905721bff66bcd7241ea |
class FactorizedMSTPostProcessor(PostProcessor): <NEW_LINE> <INDENT> def __init__(self, annotation_ids, vocabs): <NEW_LINE> <INDENT> super(FactorizedMSTPostProcessor, self).__init__(annotation_ids, vocabs) <NEW_LINE> assert len(self.annotation_ids) == 2 <NEW_LINE> self.heads_id, self.labels_id = self.annotation_ids <NEW_LINE> <DEDENT> def post_process(self, sentence, logits): <NEW_LINE> <INDENT> head_logits = logits[self.heads_id] <NEW_LINE> assert len(head_logits.shape) == 2 <NEW_LINE> assert head_logits.shape[0] == head_logits.shape[1] <NEW_LINE> head_logprobs = log_softmax(head_logits, dim=1).detach().cpu().numpy() <NEW_LINE> head_indices = chuliu_edmonds_one_root(head_logprobs) <NEW_LINE> self.retrieve_labeled_dependency_tree(sentence, head_indices) <NEW_LINE> <DEDENT> def retrieve_labeled_dependency_tree(self, sentence, head_indices): <NEW_LINE> <INDENT> heads = sentence[self.heads_id] <NEW_LINE> labels = sentence[self.labels_id] <NEW_LINE> heads.data[:] = [self.vocabs[self.heads_id].ix2token(int(head_ix)) for head_ix in head_indices] <NEW_LINE> for i in range(len(labels)): <NEW_LINE> <INDENT> labels[i][0] = "[null]" <NEW_LINE> <DEDENT> for dependent_ix in range(1, len(labels)): <NEW_LINE> <INDENT> true_head_ix = head_indices[dependent_ix] <NEW_LINE> for head_ix in range(len(labels)): <NEW_LINE> <INDENT> if head_ix != true_head_ix: <NEW_LINE> <INDENT> labels[head_ix][dependent_ix] = "[null]" <NEW_LINE> <DEDENT> elif head_ix == true_head_ix == 0: <NEW_LINE> <INDENT> labels[head_ix][dependent_ix] = "root" | Post-processor to assemble a basic dependency tree from a logits tensor of arc scores (output of ArcScorer) by
using the Chu-Liu/Edmonds MST algorithm and only keeping those entries in the sentence's DependencyMatrix which
correspond to tree edges.
(This is the "usual" method for graph-based parsing of syntactic dependency trees.) | 6259905799cbb53fe6832465 |
class User(UserMixin, SurrogatePK, Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> username = Column(db.Unicode(128), unique=True, nullable=False) <NEW_LINE> email = Column(db.String(255), unique=False, nullable=False, index=True) <NEW_LINE> email_verified = Column(db.Boolean, nullable=False, default=False) <NEW_LINE> created_at = Column(db.DateTime, nullable=False, default=now) <NEW_LINE> modified_at = Column(db.DateTime, nullable=False, default=now, onupdate=now) <NEW_LINE> password = Column(db.Binary(128), nullable=True) <NEW_LINE> password_set_at = Column(db.DateTime, nullable=True) <NEW_LINE> password_reset_at = Column(db.DateTime, nullable=True) <NEW_LINE> password_reset_token = Column(db.Binary(128), nullable=True) <NEW_LINE> first_name = Column(db.Unicode(50), nullable=True) <NEW_LINE> last_name = Column(db.Unicode(50), nullable=True) <NEW_LINE> is_active = Column(db.Boolean, nullable=False, default=False) <NEW_LINE> is_admin = Column(db.Boolean, nullable=False, default=False) <NEW_LINE> def __init__(self, username, email, password=None, **kwargs): <NEW_LINE> <INDENT> db.Model.__init__(self, username=username, email=email, **kwargs) <NEW_LINE> if password: <NEW_LINE> <INDENT> self.set_password(password) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.password = None <NEW_LINE> <DEDENT> <DEDENT> def set_password(self, password): <NEW_LINE> <INDENT> self.password = bcrypt.generate_password_hash(password) <NEW_LINE> self.password_set_at = now() <NEW_LINE> <DEDENT> def check_password(self, value): <NEW_LINE> <INDENT> return bcrypt.check_password_hash(self.password, value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def full_name(self): <NEW_LINE> <INDENT> return '{0} {1}'.format(self.first_name, self.last_name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<User({username!r})>'.format(username=self.username) | A user of the app. | 6259905745492302aabfda5e |
class stop_after_delay(stop_base): <NEW_LINE> <INDENT> def __init__(self, max_delay): <NEW_LINE> <INDENT> self.max_delay = max_delay <NEW_LINE> <DEDENT> def __call__(self, previous_attempt_number, delay_since_first_attempt): <NEW_LINE> <INDENT> return delay_since_first_attempt >= self.max_delay | Stop when the time from the first attempt >= limit. | 62599057b57a9660fecd3001 |
class TestSequence(unittest.TestCase): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> rptable = RPTable() <NEW_LINE> oh_init_rpt(rptable) <NEW_LINE> for rpte in rptentries: <NEW_LINE> <INDENT> self.assertEqual(oh_add_resource(rptable, rpte, None, 0), 0) <NEW_LINE> <DEDENT> self.assertEqual(oh_add_rdr(rptable, SAHPI_FIRST_ENTRY, sensors[0], None,0), 0) <NEW_LINE> record_id = oh_get_rdr_uid(sensors[0].RdrType, sensors[0].RdrTypeUnion.SensorRec.Num) <NEW_LINE> sensors[0].RecordId = record_id <NEW_LINE> tmprdr = oh_get_rdr_by_id(rptable, SAHPI_FIRST_ENTRY, record_id) <NEW_LINE> self.assertEqual(not (tmprdr), False) <NEW_LINE> self.assertEqual(memcmp(sensors[0], tmprdr, sizeof_SaHpiRdrT), 0) | runTest : Starts with an RPTable of 10 resources, adds 1 rdr
to first resource. Fetches rdr by record id and compares
with original. A failed comparison means the test failed,
otherwise the test passed.
Return value: 0 on success, 1 on failure | 62599057dd821e528d6da443 |
class FileslistAndLasteditInfoFunctions(): <NEW_LINE> <INDENT> def addtolist(self, path, list, textlist): <NEW_LINE> <INDENT> if os.path.isdir(path): <NEW_LINE> <INDENT> for root, dirs, files in os.walk(path): <NEW_LINE> <INDENT> for filename in files: <NEW_LINE> <INDENT> pathandname = root + filename <NEW_LINE> try: <NEW_LINE> <INDENT> width, height = get_image_size(pathandname) <NEW_LINE> wh = str(width / height) + '_' <NEW_LINE> <DEDENT> except UnknownImageFormat: <NEW_LINE> <INDENT> wh = 'noimage_' <NEW_LINE> <DEDENT> if textlist is not None: <NEW_LINE> <INDENT> tx = '' <NEW_LINE> if wh == 'noimage_': <NEW_LINE> <INDENT> print('path: ', pathandname) <NEW_LINE> try: <NEW_LINE> <INDENT> if '.pdf' in filename: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif '.txt' in filename: <NEW_LINE> <INDENT> txf = open(pathandname, encoding='utf-8') <NEW_LINE> tx = txf.read() <NEW_LINE> txf.close() <NEW_LINE> <DEDENT> elif '.docx' in filename: <NEW_LINE> <INDENT> tx = docx2txt.process(pathandname) <NEW_LINE> <DEDENT> elif '.odt' in filename: <NEW_LINE> <INDENT> textdoc = load(pathandname) <NEW_LINE> tx = teletype.extractText(textdoc.body) <NEW_LINE> <DEDENT> elif '.xlsx' in filename: <NEW_LINE> <INDENT> wb = xlrd.open_workbook(pathandname) <NEW_LINE> sh1 = wb.sheet_by_index(0) <NEW_LINE> for rownum in range(sh1.nrows): <NEW_LINE> <INDENT> onerow = ' '.join(sh1.row_values(rownum)) <NEW_LINE> tx = tx + onerow + '\n' <NEW_LINE> <DEDENT> <DEDENT> elif '.ods' in filename: <NEW_LINE> <INDENT> doc = ODSReader(pathandname, clonespannedcolumns=True) <NEW_LINE> table = doc.getSheet(u'Sheet1') <NEW_LINE> for i in range(len(table)): <NEW_LINE> <INDENT> for j in range(len(table[i])): <NEW_LINE> <INDENT> tx = tx + ' ' + table[i][j] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> textlist.append(tx) <NEW_LINE> <DEDENT> list.append(wh + pathandname) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if textlist is not None: <NEW_LINE> <INDENT> return list, textlist <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return list <NEW_LINE> <DEDENT> <DEDENT> last_edited = 0 <NEW_LINE> def speaklastedited(self): <NEW_LINE> <INDENT> return FileslistAndLasteditInfoFunctions.last_edited <NEW_LINE> <DEDENT> def setlastedited(self, pk): <NEW_LINE> <INDENT> FileslistAndLasteditInfoFunctions.last_edited = pk | liefert die dateien eines ordners als liste
und setzt oder liest last_edited (variabel des zuletzt geänderten datensatzes) um (wenn superuser) nach dem bearbeiten dorthin zu scrollen | 625990572ae34c7f260ac66d |
@attrs(**ATTRSCONFIG) <NEW_LINE> class PrivateDnsNamespace(Resource): <NEW_LINE> <INDENT> RESOURCE_TYPE = "AWS::ServiceDiscovery::PrivateDnsNamespace" <NEW_LINE> Properties: PrivateDnsNamespaceProperties = attrib( factory=PrivateDnsNamespaceProperties, converter=create_object_converter(PrivateDnsNamespaceProperties), ) | A Private Dns Namespace for ServiceDiscovery.
See Also:
`AWS Cloud Formation documentation for PrivateDnsNamespace
<http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-privatednsnamespace.html>`_ | 6259905707f4c71912bb09c1 |
class Program(AST): <NEW_LINE> <INDENT> def __init__(self, declarations=None, main=None): <NEW_LINE> <INDENT> self.declarations = declarations or [] <NEW_LINE> self.main = main <NEW_LINE> <DEDENT> def evaluate(self): <NEW_LINE> <INDENT> self.declarations.evaluate() <NEW_LINE> self.main.evaluate() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Program(decl={}, main={})'.format(self.declarations, self.main) | The AST node that represents the PROGRAM block
The PROGRAM block in Caspal consists of:
- variable declarations
- the main block | 625990577b25080760ed87a2 |
class MiniModel(keras.Model): <NEW_LINE> <INDENT> def __init__(self, generate_infinity=False): <NEW_LINE> <INDENT> super(MiniModel, self).__init__(name="") <NEW_LINE> self._generate_infinity = generate_infinity <NEW_LINE> self.fc = keras.layers.Dense( 1, kernel_initializer="ones", bias_initializer="ones", activation="linear") <NEW_LINE> <DEDENT> @def_function.function <NEW_LINE> def call(self, inputs, training=True): <NEW_LINE> <INDENT> y = self.fc(inputs) <NEW_LINE> if self._generate_infinity: <NEW_LINE> <INDENT> y = math_ops.divide(y, array_ops.zeros_like(y)) <NEW_LINE> <DEDENT> return y | Minimal subclassed Keras model. | 6259905776e4537e8c3f0b13 |
class AsyncDropWhile: <NEW_LINE> <INDENT> def __init__(self, predicate, iterable): <NEW_LINE> <INDENT> self._predicate = _async_callable(predicate) <NEW_LINE> self._iterable = iterable <NEW_LINE> self._initialized = False <NEW_LINE> self._found = False <NEW_LINE> <DEDENT> async def __aiter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> async def __anext__(self): <NEW_LINE> <INDENT> if not self._initialized: <NEW_LINE> <INDENT> self._iterable = await aiter(self._iterable) <NEW_LINE> self._initialized = True <NEW_LINE> <DEDENT> while not self._found: <NEW_LINE> <INDENT> value = await anext(self._iterable) <NEW_LINE> self._found = not (await self._predicate(value)) <NEW_LINE> if self._found: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> return await anext(self._iterable) | Async version of the dropwhile iterable. | 62599057435de62698e9d38a |
class User(UserMixin): <NEW_LINE> <INDENT> def check_user(self, username, password): <NEW_LINE> <INDENT> ht = HtpasswdFile(HTPASSWD_FILE) <NEW_LINE> if username in ht.users(): <NEW_LINE> <INDENT> if ht.check_password(username, password): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def get_id(self): <NEW_LINE> <INDENT> return uuid.uuid4() | Contains all neede information to validate and authenticate a user in the
system using the htpasswd file. | 62599057fff4ab517ebcedab |
class FiniteDifferenceDynamics(Dynamics): <NEW_LINE> <INDENT> def __init__(self, f, state_dimension, control_dimension, x_eps=None, u_eps=None): <NEW_LINE> <INDENT> self.f_ = f <NEW_LINE> self.state_dimension_ = state_dimension <NEW_LINE> self.control_dimension_ = control_dimension <NEW_LINE> self.x_eps_ = x_eps if x_eps else onp.sqrt(onp.finfo(float).eps) <NEW_LINE> self.u_eps_ = u_eps if x_eps else onp.sqrt(onp.finfo(float).eps) <NEW_LINE> self.x_eps_hess_ = onp.sqrt(self.x_eps_) <NEW_LINE> self.u_eps_hess_ = onp.sqrt(self.u_eps_) <NEW_LINE> super(FiniteDifferenceDynamics, self).__init__() <NEW_LINE> <DEDENT> @property <NEW_LINE> def state_dimension(self): <NEW_LINE> <INDENT> return self.state_dimension_ <NEW_LINE> <DEDENT> @property <NEW_LINE> def control_dimension(self): <NEW_LINE> <INDENT> return self.control_dimension_ <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_hessians(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def f(self, x, u, i): <NEW_LINE> <INDENT> return self.f_(x, u, i) <NEW_LINE> <DEDENT> def f_x(self, x, u, i): <NEW_LINE> <INDENT> J = np.vstack([optimize.approx_fprime(x, lambda x : self.f_(x, u, i)[m], self.x_eps_) for m in range(0, self.state_dimension_)]) <NEW_LINE> return J <NEW_LINE> <DEDENT> def f_u(self, x, u, i): <NEW_LINE> <INDENT> J = np.vstack([optimize.approx_fprime(u, lambda u: self.f_(x, u, i)[m], self.u_eps_) for m in range(0, self.state_dimension_)]) <NEW_LINE> return J <NEW_LINE> <DEDENT> def f_xx(self, x, u, i): <NEW_LINE> <INDENT> Q = np.array([ [optimize.approx_fprime(x, lambda x: self.f_x(x, u, i)[m, n], self.u_eps_hess_) for n in range(0, self.state_dimension_)] ] for m in range (0, self.state_dimension_)) <NEW_LINE> return Q <NEW_LINE> <DEDENT> def f_ux(self, x, u, i): <NEW_LINE> <INDENT> Q = np.array([ [optimize.approx_fprime(x, lambda x: self.f_u(x, u, i)[m, n], self.u_eps_hess_) for n in range(0, self.control_dimension_)] ] for m in range(0, self.state_dimension_)) <NEW_LINE> return Q <NEW_LINE> <DEDENT> def f_uu(self, x, u, i): <NEW_LINE> <INDENT> Q = np.array([ [optimize.approx_fprime(u, lambda u: self.f_u(x, u, i)[m, n], self.u_eps_hess_) for n in range(0, self.control_dimension_)] ] for m in range(0, self.control_dimension_)) <NEW_LINE> return Q | Finite difference approximated dynamics model | 625990571f037a2d8b9e532f |
class MyInt(int): <NEW_LINE> <INDENT> def __eq__(self, value): <NEW_LINE> <INDENT> return super().__ne__(value) <NEW_LINE> <DEDENT> def __ne__(self, value): <NEW_LINE> <INDENT> return super().__eq__(value) | MyInt is a rebel. MyInt has == and != operators inverted.
| 62599057e64d504609df9e93 |
@override_settings(KEGBOT_BACKEND="pykeg.core.testutils.TestBackend") <NEW_LINE> class BackendsFixtureTestCase(TransactionTestCase): <NEW_LINE> <INDENT> fixtures = ["testdata/full_demo_site.json"] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.backend = get_kegbot_backend() <NEW_LINE> <DEDENT> def test_delete_keg(self): <NEW_LINE> <INDENT> site = models.KegbotSite.get() <NEW_LINE> original_stats = site.get_stats() <NEW_LINE> self.assertEqual(755, original_stats["total_pours"]) <NEW_LINE> keg = models.Keg.objects.get(pk=2) <NEW_LINE> keg_stats = keg.get_stats() <NEW_LINE> keg_drinks = keg.drinks.all() <NEW_LINE> self.assertEqual(185, len(keg_drinks)) <NEW_LINE> self.backend.cancel_keg(keg) <NEW_LINE> stats = site.get_stats() <NEW_LINE> self.assertEqual(755 - 185, stats["total_pours"]) <NEW_LINE> self.assertEqual( original_stats["total_volume_ml"] - keg_stats["total_volume_ml"], stats["total_volume_ml"], ) | Test backened using fixture (demo) data. | 62599057498bea3a75a590ae |
class VirtualAdversarialAttack(BatchAttack): <NEW_LINE> <INDENT> def _clip_perturbation(self, a, perturbation, epsilon): <NEW_LINE> <INDENT> norm = np.sqrt(np.mean(np.square(perturbation))) <NEW_LINE> norm = max(1e-12, norm) <NEW_LINE> min_, max_ = a.bounds() <NEW_LINE> s = max_ - min_ <NEW_LINE> factor = min(1, epsilon * s / norm) <NEW_LINE> return perturbation * factor <NEW_LINE> <DEDENT> @generator_decorator <NEW_LINE> def as_generator(self, a, xi=1e-5, iterations=1, epsilons=1000, max_epsilon=0.3): <NEW_LINE> <INDENT> assert a.target_class is None, ( "Virtual Adversarial is an " "untargeted adversarial attack." ) <NEW_LINE> yield from self._run( a, xi=xi, iterations=iterations, epsilons=epsilons, max_epsilon=max_epsilon ) <NEW_LINE> <DEDENT> def _run(self, a, xi, iterations, epsilons, max_epsilon): <NEW_LINE> <INDENT> if not a.has_gradient(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> x = a.unperturbed <NEW_LINE> min_, max_ = a.bounds() <NEW_LINE> logits, _ = yield from a.forward_one(x) <NEW_LINE> if not isinstance(epsilons, Iterable): <NEW_LINE> <INDENT> epsilons = np.linspace(0, max_epsilon, num=epsilons + 1)[1:] <NEW_LINE> decrease_if_first = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> decrease_if_first = False <NEW_LINE> <DEDENT> for _ in range(2): <NEW_LINE> <INDENT> for i, epsilon in enumerate(epsilons): <NEW_LINE> <INDENT> d = np.random.normal(0.0, 1.0, size=x.shape) <NEW_LINE> for it in range(iterations): <NEW_LINE> <INDENT> d = xi * d / np.sqrt((d ** 2).sum()) <NEW_LINE> logits_d, _ = yield from a.forward_one(x + d) <NEW_LINE> dl_dp = softmax(logits) - softmax(logits_d) <NEW_LINE> d = yield from a.backward_one(gradient=dl_dp, x=x + d, strict=False) <NEW_LINE> d = (max_ - min_) * d <NEW_LINE> if np.allclose(np.sqrt((d ** 2).sum()), 0, atol=1e-16): <NEW_LINE> <INDENT> raise RuntimeError( "Gradient vanished; this can happen " "if xi is too small." ) <NEW_LINE> <DEDENT> <DEDENT> delta = d / np.sqrt((d ** 2).mean()) <NEW_LINE> perturbed = x + self._clip_perturbation(a, delta, epsilon) <NEW_LINE> perturbed = np.clip(perturbed, 0, 1) <NEW_LINE> _, is_adversarial = yield from a.forward_one(perturbed) <NEW_LINE> if is_adversarial: <NEW_LINE> <INDENT> if decrease_if_first and i < 20: <NEW_LINE> <INDENT> logging.info("repeating attack with smaller epsilons") <NEW_LINE> break <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> <DEDENT> max_epsilon = epsilons[i] <NEW_LINE> epsilons = np.linspace(0, max_epsilon, num=20 + 1)[1:] | Calculate an untargeted adversarial perturbation by performing a
approximated second order optimization step on the KL divergence between
the unperturbed predictions and the predictions for the adversarial
perturbation. This attack was introduced in [1]_.
References
----------
.. [1] Takeru Miyato, Shin-ichi Maeda, Masanori Koyama, Ken Nakae,
Shin Ishii,
"Distributional Smoothing with Virtual Adversarial Training",
https://arxiv.org/abs/1507.00677 | 625990578a43f66fc4bf3715 |
class AddressSchema(Schema): <NEW_LINE> <INDENT> identifierList = fields.List(fields.Str(), many=True, allow_none=True) <NEW_LINE> addressId = fields.UUID() <NEW_LINE> addressTypeList = fields.List(fields.Str(), many=True, allow_none=True) <NEW_LINE> addressName = fields.Str() <NEW_LINE> label = fields.Str() <NEW_LINE> @post_load <NEW_LINE> def save_object(self, data): <NEW_LINE> <INDENT> return Address(**data) | The equivalent Schema of Address Class | 625990573617ad0b5ee076d1 |
class TokenResponse(object): <NEW_LINE> <INDENT> def __init__(self, response): <NEW_LINE> <INDENT> self.response = response <NEW_LINE> try: <NEW_LINE> <INDENT> self.access_token = response.json.get("access_token") <NEW_LINE> self.refresh_token = response.json.get("refresh_token") <NEW_LINE> self.id_token = response.json.get("id_token") <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.access_token = None <NEW_LINE> self.refresh_token = None <NEW_LINE> self.id_token = None <NEW_LINE> <DEDENT> <DEDENT> def do_asserts(self): <NEW_LINE> <INDENT> assert self.response.status_code == 200, self.response.json <NEW_LINE> assert "access_token" in self.response.json <NEW_LINE> assert "refresh_token" in self.response.json <NEW_LINE> assert "id_token" in self.response.json | Note that the ID token is not part of the OAuth2 spec, but is part of the
OIDC core spec and therefore this implementation.
Attributes:
access_token (dict)
refresh_token (dict)
id_token (dict) | 62599057009cb60464d02abc |
class PermissionDeniedError(Exception): <NEW_LINE> <INDENT> def __init__(self, username, pathsAndOperations): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.pathsAndOperations = pathsAndOperations <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> pathsAndOperations = ['%s on %r' % (operation, path) for path, operation in self.pathsAndOperations] <NEW_LINE> pathsAndOperations = ', '.join(pathsAndOperations) <NEW_LINE> return ("User '%s' cannot perform the following operations: %s" % (self.username, pathsAndOperations)) | Raised when an attempt to perform an unauthorized operation is made. | 625990578da39b475be04774 |
class PTBAxesInputException(Exception): <NEW_LINE> <INDENT> pass | Exception for PTBAxes input | 6259905745492302aabfda5f |
class DiscNumberTagFormatter(NumberTagFormatter): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> TagFormatter.__init__(self, 'discnumber') | A formatter for the discnumber of a track | 62599057097d151d1a2c25f3 |
class AutomationActions(BaseApi): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(AutomationActions, self).__init__(*args, **kwargs) <NEW_LINE> self.endpoint = 'automations' <NEW_LINE> self.workflow_id = None <NEW_LINE> <DEDENT> def pause(self, workflow_id): <NEW_LINE> <INDENT> self.workflow_id = workflow_id <NEW_LINE> return self._mc_client._post(url=self._build_path(workflow_id, 'actions/pause-all-emails')) <NEW_LINE> <DEDENT> def start(self, workflow_id): <NEW_LINE> <INDENT> self.workflow_id = workflow_id <NEW_LINE> return self._mc_client._post(url=self._build_path(workflow_id, 'actions/start-all-emails')) | Actions for the Automations endpoint. | 62599057507cdc57c63a632d |
class ILoginForm(Interface): <NEW_LINE> <INDENT> login = schema.BytesLine(title=u'Username', required=True) <NEW_LINE> password = schema.Password(title=u'Password', required=True) | Our login form implements login and password schema fields.
| 6259905745492302aabfda60 |
class ChartLine(chart.Chart): <NEW_LINE> <INDENT> def __init__(self, options=None): <NEW_LINE> <INDENT> super(ChartLine, self).__init__() <NEW_LINE> if options is None: <NEW_LINE> <INDENT> options = {} <NEW_LINE> <DEDENT> self.default_marker = {'type': 'none'} <NEW_LINE> self.smooth_allowed = True <NEW_LINE> self.label_position_default = 'right' <NEW_LINE> self.label_positions = { 'center': 'ctr', 'right': 'r', 'left': 'l', 'above': 't', 'below': 'b', 'top': 't', 'bottom': 'b'} <NEW_LINE> <DEDENT> def _write_chart_type(self, args): <NEW_LINE> <INDENT> self._write_line_chart(args) <NEW_LINE> <DEDENT> def _write_line_chart(self, args): <NEW_LINE> <INDENT> if args['primary_axes']: <NEW_LINE> <INDENT> series = self._get_primary_axes_series() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> series = self._get_secondary_axes_series() <NEW_LINE> <DEDENT> if not len(series): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._xml_start_tag('c:lineChart') <NEW_LINE> self._write_grouping('standard') <NEW_LINE> for data in series: <NEW_LINE> <INDENT> self._write_ser(data) <NEW_LINE> <DEDENT> self._write_drop_lines() <NEW_LINE> self._write_hi_low_lines() <NEW_LINE> self._write_up_down_bars() <NEW_LINE> self._write_marker_value() <NEW_LINE> self._write_axis_ids(args) <NEW_LINE> self._xml_end_tag('c:lineChart') <NEW_LINE> <DEDENT> def _write_d_pt_point(self, index, point): <NEW_LINE> <INDENT> self._xml_start_tag('c:dPt') <NEW_LINE> self._write_idx(index) <NEW_LINE> self._xml_start_tag('c:marker') <NEW_LINE> self._write_sp_pr(point) <NEW_LINE> self._xml_end_tag('c:marker') <NEW_LINE> self._xml_end_tag('c:dPt') | A class for writing the Excel XLSX Line charts. | 62599057e76e3b2f99fd9f87 |
class GeometryMap: <NEW_LINE> <INDENT> def __init__(self, syms, exprs): <NEW_LINE> <INDENT> from sympy import Array, oo <NEW_LINE> if not isinstance(exprs, list) and not isinstance(exprs, Array): <NEW_LINE> <INDENT> raise ValueError("The ctor arg of GeometryMap -- exprs -- should be a list of sympy expressions.") <NEW_LINE> <DEDENT> self._exprs = Array(exprs) <NEW_LINE> self._syms = [] <NEW_LINE> for sym in syms: <NEW_LINE> <INDENT> if isinstance(sym, tuple): <NEW_LINE> <INDENT> assert(len(sym)==3) <NEW_LINE> self._syms.append(sym) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._syms.append( (sym, -oo, +oo) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def exprs(self): <NEW_LINE> <INDENT> return self._exprs <NEW_LINE> <DEDENT> def expr(self, i:int): <NEW_LINE> <INDENT> return self._exprs[i] <NEW_LINE> <DEDENT> def subs(self, *arg): <NEW_LINE> <INDENT> return GeometryMap(self, self._exprs.subs(*arg), self._syms) <NEW_LINE> <DEDENT> @property <NEW_LINE> def syms(self): <NEW_LINE> <INDENT> return [sym[0] for sym in self._syms] <NEW_LINE> <DEDENT> def sym(self, i:int): <NEW_LINE> <INDENT> return self._syms[i][0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def sym_limits(self): <NEW_LINE> <INDENT> return [sym[1:] for sym in self._syms] <NEW_LINE> <DEDENT> def sym_limit(self, i:int): <NEW_LINE> <INDENT> return self._syms[i][1:] <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def jacobian(self): <NEW_LINE> <INDENT> from sympy import Array <NEW_LINE> return self.exprs.diff( Array(self.syms)) <NEW_LINE> <DEDENT> def lambdified(self, *arg, **kwarg): <NEW_LINE> <INDENT> from sympy import lambdify <NEW_LINE> return lambdify( self.syms, self.exprs.tolist(), *arg, **kwarg) | Base class for geometry map.
| 625990574e4d56256637398f |
class registarPage(BasePage): <NEW_LINE> <INDENT> url = "http://39.98.138.157/shopxo/index.php?s=/index/user/reginfo.html" <NEW_LINE> user =(By.NAME,"accounts") <NEW_LINE> pwd = (By.NAME,"pwd") <NEW_LINE> xuyi =(By.XPATH,'/html/body/div[4]/div/div/div/div[2]/div/div/div[1]/form/div[3]/label/span/i[2]') <NEW_LINE> registar = (By.XPATH,"/html/body/div[4]/div/div/div/div[2]/div/div/div[1]/form/div[4]/button") <NEW_LINE> def input_user(self,txt): <NEW_LINE> <INDENT> self.locator(self.user).send_keys(txt) <NEW_LINE> <DEDENT> def input_pwd(self,txt): <NEW_LINE> <INDENT> self.locator(self.pwd).send_keys(txt) <NEW_LINE> <DEDENT> def click_xuyi(self): <NEW_LINE> <INDENT> self.locator(self.xuyi).click() <NEW_LINE> <DEDENT> def click_registar(self): <NEW_LINE> <INDENT> self.locator(self.registar).click() | registarPage的核心业务是注册流程的实现
1.登陆关联的元素(element)获取
2.基于元素实现的方式 | 625990572ae34c7f260ac66f |
class GoogleWebSearchPage(Top25Page): <NEW_LINE> <INDENT> def __init__(self, page_set): <NEW_LINE> <INDENT> super(GoogleWebSearchPage, self).__init__( url='https://www.google.com/#hl=en&q=barack+obama', page_set=page_set) <NEW_LINE> <DEDENT> def RunNavigateSteps(self, action_runner): <NEW_LINE> <INDENT> action_runner.NavigateToPage(self) <NEW_LINE> action_runner.WaitForElement(text='Next') <NEW_LINE> <DEDENT> def RunStressMemory(self, action_runner): <NEW_LINE> <INDENT> action_runner.RunAction(ScrollAction()) <NEW_LINE> old_href = _GetCurrentLocation(action_runner) <NEW_LINE> action_runner.ClickElement(text='Next') <NEW_LINE> _WaitForLocationChange(action_runner, old_href) <NEW_LINE> action_runner.WaitForElement(text='Next') <NEW_LINE> action_runner.RunAction(ScrollAction()) <NEW_LINE> old_href = _GetCurrentLocation(action_runner) <NEW_LINE> action_runner.ClickElement(text='Next') <NEW_LINE> _WaitForLocationChange(action_runner, old_href) <NEW_LINE> action_runner.WaitForElement(text='Next') <NEW_LINE> action_runner.RunAction(ScrollAction()) <NEW_LINE> old_href = _GetCurrentLocation(action_runner) <NEW_LINE> action_runner.ClickElement(text='Next') <NEW_LINE> _WaitForLocationChange(action_runner, old_href) <NEW_LINE> action_runner.WaitForElement(text='Previous') <NEW_LINE> action_runner.RunAction(ScrollAction()) <NEW_LINE> old_href = _GetCurrentLocation(action_runner) <NEW_LINE> action_runner.ClickElement(text='Previous') <NEW_LINE> _WaitForLocationChange(action_runner, old_href) <NEW_LINE> action_runner.WaitForElement(text='Previous') <NEW_LINE> action_runner.RunAction(ScrollAction()) <NEW_LINE> old_href = _GetCurrentLocation(action_runner) <NEW_LINE> action_runner.ClickElement(text='Previous') <NEW_LINE> _WaitForLocationChange(action_runner, old_href) <NEW_LINE> action_runner.WaitForElement(text='Previous') <NEW_LINE> action_runner.RunAction(ScrollAction()) <NEW_LINE> old_href = _GetCurrentLocation(action_runner) <NEW_LINE> action_runner.ClickElement(text='Previous') <NEW_LINE> _WaitForLocationChange(action_runner, old_href) <NEW_LINE> action_runner.WaitForElement(text='Images') <NEW_LINE> action_runner.RunAction(ScrollAction()) <NEW_LINE> old_href = _GetCurrentLocation(action_runner) <NEW_LINE> action_runner.ClickElement(text='Images') <NEW_LINE> _WaitForLocationChange(action_runner, old_href) <NEW_LINE> action_runner.WaitForElement(text='Images') | Why: top google property; a google tab is often open | 625990574e4d562566373990 |
class TestGuestPlayable(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testGuestPlayable(self): <NEW_LINE> <INDENT> pass | GuestPlayable unit test stubs | 6259905723e79379d538da85 |
class CorrectAnswer(object): <NEW_LINE> <INDENT> def __init__(self, answer): <NEW_LINE> <INDENT> self.answer = answer <NEW_LINE> <DEDENT> def __call__(self, form, field): <NEW_LINE> <INDENT> error_messages = ['Sorry, that\'s not the correct answer.', 'Try that again...', 'Incorrect answer.', 'Please check this answer...', 'Oops! Try again...', 'Nope! Sorry... try again!', 'No, not quite... try again!', 'Hmmm, not exactly right...'] <NEW_LINE> num = randrange(0, len(error_messages)) <NEW_LINE> message = error_messages[num] <NEW_LINE> if field.data != self.answer: <NEW_LINE> <INDENT> raise ValidationError(message) | Custom validator for WTForms to check
if the correct answer was submitted | 625990578e71fb1e983bd052 |
@pytest.mark.django_db <NEW_LINE> class TestPaymentMethod: <NEW_LINE> <INDENT> @pytest.mark.django_db <NEW_LINE> def test_payment_method_fees(self): <NEW_LINE> <INDENT> b = BasePaymentMethod({ 'name': 'testpaymentmethod', 'fee_per_transaction': Decimal('0.30'), 'fee_percent': Decimal('2.9'), 'display_name': 'test_display_name', 'currencies': ['EUR'] }) <NEW_LINE> assert b.calculate_fee(Decimal('100')) == Decimal('3.2') <NEW_LINE> <DEDENT> @pytest.mark.django_db <NEW_LINE> def test_payment_method_without_name(self): <NEW_LINE> <INDENT> with pytest.raises(PaymentMethodDoesNotHaveName): <NEW_LINE> <INDENT> b = BasePaymentMethod({ 'display_name': 'test_display_name', 'currencies': ['EUR'] }) <NEW_LINE> <DEDENT> <DEDENT> @pytest.mark.django_db <NEW_LINE> def test_payment_method_without_currencies(self): <NEW_LINE> <INDENT> with pytest.raises(PaymentMethodDoesNotHaveCurrencies): <NEW_LINE> <INDENT> b = BasePaymentMethod({ 'name': 'test_name', 'display_name': 'test_display_name' }) <NEW_LINE> <DEDENT> <DEDENT> @pytest.mark.django_db <NEW_LINE> def test_concrete_payment_method_creation(self): <NEW_LINE> <INDENT> class SuperPay(BasePaymentMethod): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> options = { 'name': 'superpay', 'display_name': 'test_display_name', 'currencies': ['EUR'] } <NEW_LINE> instance = SuperPay(options) <NEW_LINE> assert isinstance(instance, SuperPay) <NEW_LINE> assert method_registry['superpay'] == instance <NEW_LINE> <DEDENT> @pytest.mark.django_db <NEW_LINE> def test_verify(self, method_options): <NEW_LINE> <INDENT> b = BasePaymentMethod({ 'name': 'testpaymentmethod', 'fee_per_transaction': Decimal('0.30'), 'fee_percent': Decimal('2.9'), 'display_name': 'test_display_name', 'currencies': ['EUR'] }) <NEW_LINE> assert b.calculate_fee(Decimal('100')) == Decimal('3.2') | Base class for all the payment method. | 62599057b7558d58954649ef |
class HyphenSeparatedParticleAnalyzer(AnalogyAnalizerUnit): <NEW_LINE> <INDENT> ESTIMATE_DECAY = 0.9 <NEW_LINE> PARTICLES_AFTER_HYPHEN = [ "-то", "-ка", "-таки", "-де", "-тко", "-тка", "-с", "-ста", ] <NEW_LINE> def parse(self, word, word_lower, seen_parses): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for unsuffixed_word, particle in self.possible_splits(word_lower): <NEW_LINE> <INDENT> method = (self, particle) <NEW_LINE> for fixed_word, tag, normal_form, score, methods_stack in self.morph.parse(unsuffixed_word): <NEW_LINE> <INDENT> parse = ( fixed_word+particle, tag, normal_form+particle, score*self.ESTIMATE_DECAY, methods_stack+(method,) ) <NEW_LINE> add_parse_if_not_seen(parse, result, seen_parses) <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def tag(self, word, word_lower, seen_tags): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for unsuffixed_word, particle in self.possible_splits(word_lower): <NEW_LINE> <INDENT> result.extend(self.morph.tag(unsuffixed_word)) <NEW_LINE> break <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def possible_splits(self, word): <NEW_LINE> <INDENT> if '-' not in word: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for particle in self.PARTICLES_AFTER_HYPHEN: <NEW_LINE> <INDENT> if not word.endswith(particle): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> unsuffixed_word = word[:-len(particle)] <NEW_LINE> if not unsuffixed_word: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> yield unsuffixed_word, particle <NEW_LINE> <DEDENT> <DEDENT> def normalizer(self, form, this_method): <NEW_LINE> <INDENT> particle = this_method[1] <NEW_LINE> normal_form = yield without_fixed_suffix(form, len(particle)) <NEW_LINE> yield with_suffix(normal_form, particle) <NEW_LINE> <DEDENT> def lexemizer(self, form, this_method): <NEW_LINE> <INDENT> particle = this_method[1] <NEW_LINE> lexeme = yield without_fixed_suffix(form, len(particle)) <NEW_LINE> yield [with_suffix(f, particle) for f in lexeme] | Parse the word by analyzing it without
a particle after a hyphen.
Example: смотри-ка -> смотри + "-ка".
.. note::
This analyzer doesn't remove particles from the result
so for normalization you may need to handle
particles at tokenization level. | 62599057dc8b845886d54b4f |
class OrderInfo(BaseModel): <NEW_LINE> <INDENT> status_choices = ( (0, '未支付'), (1, '已支付'), (2, '待发货'), (3, '已发货'), (4, '已完成'), (5, '待退款'), (6, '已关闭'), (7, '退款成功') ) <NEW_LINE> wx_user = models.ForeignKey(WxUser,on_delete=models.CASCADE, verbose_name='微信用户') <NEW_LINE> address = models.CharField(max_length=255,null=True, verbose_name='收件地址') <NEW_LINE> name = models.CharField(max_length=30, null=True,verbose_name='收件人姓名') <NEW_LINE> phone = models.CharField(max_length=11, null=True,verbose_name='收件人手机') <NEW_LINE> order_id = models.CharField(max_length=255, verbose_name='订单号') <NEW_LINE> commodity_total_price = models.FloatField(verbose_name='商品总价') <NEW_LINE> total_price = models.FloatField(verbose_name='订单总价') <NEW_LINE> total_count = models.IntegerField(verbose_name='订单总件数') <NEW_LINE> transit_price = models.FloatField(default=0, verbose_name='运费') <NEW_LINE> discount_price = models.FloatField(default=0, verbose_name='优惠金额') <NEW_LINE> state = models.SmallIntegerField(default=0, choices=status_choices, verbose_name='订单状态') <NEW_LINE> courier_number = models.CharField(max_length=255,default='', verbose_name='快递单号',null=True,blank=True) <NEW_LINE> returns_number = models.CharField(max_length=255,default='', verbose_name='退货单号',null=True,blank=True) <NEW_LINE> note = models.CharField(max_length=255,default='', verbose_name='备注' ,null=True,blank=True) <NEW_LINE> cancel_time = models.CharField(max_length=30,null=True, verbose_name='取消时间',blank=True) <NEW_LINE> complete_time = models.CharField(max_length=30,null=True, verbose_name='完成时间',blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'gd_order_info' <NEW_LINE> verbose_name = '订单表' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.id) | 订单表 | 62599057435de62698e9d38d |
class Trip(object): <NEW_LINE> <INDENT> def __init__(self, trip): <NEW_LINE> <INDENT> items = trip.split('-') <NEW_LINE> self.startFloor = int(items[0]) <NEW_LINE> self.endFloor = int(items[1]) <NEW_LINE> if self.startFloor < self.endFloor: <NEW_LINE> <INDENT> self.direction = 'up' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.direction = 'down' | represents one elevator trip
code from https://raw.githubusercontent.com/mxvanzant/pyelevator/master/elevator.py | 62599057f7d966606f74937d |
class MountPointTest(shared_test_lib.BaseTestCase): <NEW_LINE> <INDENT> def testGetAttributeNames(self): <NEW_LINE> <INDENT> attribute_container = storage_media.MountPoint() <NEW_LINE> expected_attribute_names = ['mount_path', 'path_specification'] <NEW_LINE> attribute_names = sorted(attribute_container.GetAttributeNames()) <NEW_LINE> self.assertEqual(attribute_names, expected_attribute_names) | Tests for the mount point attribute container. | 625990574428ac0f6e659ac5 |
class OffPolicyBuffer: <NEW_LINE> <INDENT> def __init__(self, buffer_size=int(1e6), epoch_size=5000, batch_size=100): <NEW_LINE> <INDENT> self.buffer_size, self.path_start_idx = buffer_size, 0 <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.epoch_size = epoch_size or buffer_size <NEW_LINE> if buffer_size % self.epoch_size != 0: <NEW_LINE> <INDENT> raise NotImplementedError("Buffer size which is not integer " "multiple of epoch size not supported") <NEW_LINE> <DEDENT> self.store_ctr, self.buf = 0, None <NEW_LINE> <DEDENT> def store(self, to_buffer): <NEW_LINE> <INDENT> if not self.buf: <NEW_LINE> <INDENT> self.buf = self.initialize_buf(to_buffer) <NEW_LINE> <DEDENT> for key, val in to_buffer.items(): <NEW_LINE> <INDENT> self.buf[key][self.ptr] = val <NEW_LINE> <DEDENT> self.store_ctr += 1 <NEW_LINE> <DEDENT> def finish_path(self, last_obs=None): <NEW_LINE> <INDENT> self.update_path_next_obs(self.path_slice, last_obs) <NEW_LINE> self.path_start_idx = self.ptr <NEW_LINE> <DEDENT> def batches(self, n_batches): <NEW_LINE> <INDENT> for _ in range(n_batches): <NEW_LINE> <INDENT> yield self.sample_batch(self.batch_size) <NEW_LINE> <DEDENT> <DEDENT> def sample_batch(self, batch_size): <NEW_LINE> <INDENT> self.assert_path_finished() <NEW_LINE> batch_inds = np.random.randint(0, self.n_stored, batch_size) <NEW_LINE> return {key: val[batch_inds] for key, val in self.buf.items()} <NEW_LINE> <DEDENT> def assert_path_finished(self): <NEW_LINE> <INDENT> if self.ptr != self.path_start_idx: <NEW_LINE> <INDENT> raise RuntimeError('Most recent path has not been finished. ' + 'Please call "finish_path"') <NEW_LINE> <DEDENT> <DEDENT> def update_path_next_obs(self, path_slice, last_obs): <NEW_LINE> <INDENT> path_obs = self.buf['obs'][path_slice] <NEW_LINE> path_next_obs = np.vstack([ path_obs[1:, :], last_obs[np.newaxis, :] ]) <NEW_LINE> self.buf['next_obs'][path_slice] = path_next_obs <NEW_LINE> <DEDENT> def initialize_buf(self, to_buffer): <NEW_LINE> <INDENT> buf = {'next_obs': self.zeros(to_buffer['obs'])} <NEW_LINE> return {**buf, **{key: self.zeros(val) for key, val in to_buffer.items()}} <NEW_LINE> <DEDENT> def zeros(self, val): <NEW_LINE> <INDENT> return np.zeros(combined_shape(self.buffer_size, val), dtype=np.float32) <NEW_LINE> <DEDENT> @property <NEW_LINE> def ptr(self): <NEW_LINE> <INDENT> return self.store_ctr % self.buffer_size <NEW_LINE> <DEDENT> @property <NEW_LINE> def n_stored(self): <NEW_LINE> <INDENT> return min(self.store_ctr, self.buffer_size) <NEW_LINE> <DEDENT> @property <NEW_LINE> def path_slice(self): <NEW_LINE> <INDENT> return slice(self.path_start_idx, self.ptr or self.buffer_size) | Stores episode experience (rewards, observations,
actions, etc), calculates the advantage and rewards-to-go at the end of
trajectories. These stored values can then be used for training by the
agent. | 6259905721bff66bcd7241ee |
class ConsistencyCheck : <NEW_LINE> <INDENT> def __init__(self, checks = list()): <NEW_LINE> <INDENT> self.checks = checks; <NEW_LINE> <DEDENT> def __call__(self, paver) : <NEW_LINE> <INDENT> count = 0; <NEW_LINE> for sr in paver.solvedata : <NEW_LINE> <INDENT> for i in paver.instancedata.index : <NEW_LINE> <INDENT> paver.addSolveAttribute(i, sr.split('@')[0], sr.split('@')[1], 'Fail', False); <NEW_LINE> paver.addSolveAttribute(i, sr.split('@')[0], sr.split('@')[1], 'FailReason', ""); <NEW_LINE> <DEDENT> <DEDENT> paver.instancedata['Fail'] = False; <NEW_LINE> paver.instancedata['FailReason'] = ""; <NEW_LINE> for c in self.checks : <NEW_LINE> <INDENT> count += c(paver); <NEW_LINE> <DEDENT> return count; | Methods to check consistency of solver outcomes.
Stores a list of checks that can be executed to check a particular solver run
or that crosscheck all solver outcomes for a particular instance. | 62599057d7e4931a7ef3d609 |
class Repeat(ComplexNode): <NEW_LINE> <INDENT> def __init__(self, count, children=[]): <NEW_LINE> <INDENT> ComplexNode.__init__(self, children) <NEW_LINE> self.count = Expr(count) <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> return bool(self.count) and len(self) > 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def args(self): <NEW_LINE> <INDENT> return (self.count, list(self)) <NEW_LINE> <DEDENT> def movepointer(self, offset): <NEW_LINE> <INDENT> ComplexNode.movepointer(self, offset) <NEW_LINE> self.count = self.count.movepointer(offset) <NEW_LINE> <DEDENT> def withmemory(self, map): <NEW_LINE> <INDENT> self.count = self.count.withmemory(map) <NEW_LINE> <DEDENT> def offsets(self): <NEW_LINE> <INDENT> if self.stride() == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def prereferences(self): <NEW_LINE> <INDENT> bodyrefs = cellset(sure=self.count.references(), unsure=self.bodyprereferences().unsure) <NEW_LINE> stride = self.stride() <NEW_LINE> if stride != 0: <NEW_LINE> <INDENT> bodyrefs.addunsure(None) <NEW_LINE> <DEDENT> return bodyrefs <NEW_LINE> <DEDENT> def postreferences(self): <NEW_LINE> <INDENT> bodyrefs = cellset(unsure=self.bodypostreferences().unsure) <NEW_LINE> stride = self.stride() <NEW_LINE> if stride is not None: <NEW_LINE> <INDENT> bodyrefs.updatesure(_setmovepointer(self.count.references(), -stride)) <NEW_LINE> <DEDENT> if stride != 0: <NEW_LINE> <INDENT> bodyrefs.addunsure(None) <NEW_LINE> <DEDENT> return bodyrefs <NEW_LINE> <DEDENT> def preupdates(self): <NEW_LINE> <INDENT> bodyupdates = cellset(unsure=self.bodypreupdates().unsure) <NEW_LINE> stride = self.stride() <NEW_LINE> if stride != 0: <NEW_LINE> <INDENT> bodyupdates.addunsure(None) <NEW_LINE> <DEDENT> return bodyupdates <NEW_LINE> <DEDENT> def postupdates(self): <NEW_LINE> <INDENT> bodyupdates = cellset(unsure=self.bodypostupdates().unsure) <NEW_LINE> stride = self.stride() <NEW_LINE> if stride != 0: <NEW_LINE> <INDENT> bodyupdates.addunsure(None) <NEW_LINE> <DEDENT> return bodyupdates <NEW_LINE> <DEDENT> def compactrepr(self): <NEW_LINE> <INDENT> return 'Repeat[%s; %s]' % (self.count.compactrepr(), self._innerrepr()) | Repeat node.
Repeat[count; ...] executes its body count times. Count can be an
expression, but only evaluated once before the loop. | 6259905707f4c71912bb09c5 |
class NNCfg(object): <NEW_LINE> <INDENT> def __init__(self, optimizer=None, metrics=None): <NEW_LINE> <INDENT> self.loss_fn = 'mean_squared_error' <NEW_LINE> self.optimizer = 'adadelta' if optimizer is None else optimizer <NEW_LINE> self.pdb_batch_size = 1 <NEW_LINE> self.pdb_shuffle = True <NEW_LINE> self.steps_per_epoch = 5 <NEW_LINE> self.validation_steps = 3 <NEW_LINE> self.numepochs = 2 <NEW_LINE> self.callbacks = None <NEW_LINE> self.metrics = metrics <NEW_LINE> self.preloaded_db = None <NEW_LINE> self.feature_layers = -1 <NEW_LINE> self.load_models_dir = None <NEW_LINE> self.load_weights_dir = None <NEW_LINE> self.save_models_dir = None <NEW_LINE> self.save_weights_dir = None | NNCfg describes base model configuration for neural network. | 6259905701c39578d7f141fc |
class ServiceStateTransitionsEnum(EnumDefinitionImpl): <NEW_LINE> <INDENT> correct_service = PermissibleValue(text="correct_service", description="A correct service is delivered when the observed behavior matches those of the corresponding function described in the specification.") <NEW_LINE> service_failure = PermissibleValue(text="service_failure", description="The transition from correct service to incorrect service.") <NEW_LINE> incorrect_service = PermissibleValue(text="incorrect_service", description="An incorrect service is delivered when the observed behavior does not match those of the corresponding function described in the specification. A service failure is implicated.") <NEW_LINE> restoration = PermissibleValue(text="restoration", description="The transition from incorrect service to correct service.") <NEW_LINE> _defn = EnumDefinition( name="ServiceStateTransitionsEnum", description="System behavior represented by a sequence of internal/external states.", ) | System behavior represented by a sequence of internal/external states. | 6259905724f1403a92686394 |
class PyMutTestGeom: <NEW_LINE> <INDENT> def __init__(self, geom_type, coords_fcn=random_list, subtype=tuple, **kwargs): <NEW_LINE> <INDENT> self.geom_type = geom_type <NEW_LINE> self.subtype = subtype <NEW_LINE> self.coords_fcn = coords_fcn <NEW_LINE> self.fcn_args = kwargs <NEW_LINE> self.coords = self.coords_fcn(**kwargs) <NEW_LINE> self.geom = self.make_geom() <NEW_LINE> <DEDENT> def newitem(self, **kwargs): <NEW_LINE> <INDENT> a = self.coords_fcn.single(**kwargs) <NEW_LINE> return self.subtype(a), tuple(a) <NEW_LINE> <DEDENT> @property <NEW_LINE> def tuple_coords(self): <NEW_LINE> <INDENT> return tuple(self.coords) <NEW_LINE> <DEDENT> def make_geom(self): <NEW_LINE> <INDENT> return self.geom_type(map(self.subtype,self.coords)) | The Test Geometry class container. | 6259905773bcbd0ca4bcb81d |
class SuitabilityCircumstancesDetailsForm(NannyForm): <NEW_LINE> <INDENT> field_label_classes = "form-label-bold" <NEW_LINE> error_summary_title = "There was a problem" <NEW_LINE> error_summary_template_name = "standard-error-summary.html" <NEW_LINE> auto_replace_widgets = True <NEW_LINE> suitability_circumstances_details = forms.CharField( widget=forms.Textarea(), label="Details of your suitability", error_messages={ "required": "Details of circumstances that might affect your suitability to work with, or be in contact with children must be entered" }, ) <NEW_LINE> def clean_suitability_circumstances_details(self): <NEW_LINE> <INDENT> suitability_circumstances_details = self.cleaned_data['suitability_circumstances_details'] <NEW_LINE> if len(suitability_circumstances_details) > 1000: <NEW_LINE> <INDENT> raise forms.ValidationError( 'Details must be under 1000 characters long') <NEW_LINE> <DEDENT> return suitability_circumstances_details | GOV.UK form for the suitability details page | 62599057adb09d7d5dc0baf5 |
class executionManager: <NEW_LINE> <INDENT> def __init__(self, server_manager, system_manager, test_manager , executor_type, variables, matrix_manager, xtrabackup_manager): <NEW_LINE> <INDENT> self.server_manager = server_manager <NEW_LINE> self.system_manager = system_manager <NEW_LINE> self.matrix_manager = matrix_manager <NEW_LINE> self.xtrabackup_manager = xtrabackup_manager <NEW_LINE> self.logging = system_manager.logging <NEW_LINE> self.test_manager = test_manager <NEW_LINE> if variables['verbose']: <NEW_LINE> <INDENT> self.logging.info("Initializing test execution manager...") <NEW_LINE> <DEDENT> self.skip_keys = [ 'server_manager' , 'system_manager' , 'test_manager' , 'executors' , 'executor_start_count' , 'executor_current_count' , 'record_flag' , 'start_and_exit' ] <NEW_LINE> self.debug = variables['debug'] <NEW_LINE> self.verbose = variables['verbose'] <NEW_LINE> self.force = variables['force'] <NEW_LINE> self.record_flag = variables['record'] <NEW_LINE> self.gendata_file = variables['gendatafile'] <NEW_LINE> self.testcase_repeat_count = variables['repeat'] <NEW_LINE> self.start_and_exit = variables['startandexit'] <NEW_LINE> self.executors = {} <NEW_LINE> self.executor_name_base = 'bot' <NEW_LINE> self.executor_start_count = 0 <NEW_LINE> self.executor_current_count = 0 <NEW_LINE> self.executor_count = 1 <NEW_LINE> self.executor_type = executor_type <NEW_LINE> self.logging.debug_class(self) <NEW_LINE> <DEDENT> def execute_tests(self): <NEW_LINE> <INDENT> self.create_test_executors() <NEW_LINE> for executor_name, executor in self.executors.items(): <NEW_LINE> <INDENT> self.logging.verbose("Starting executor: %s" %(executor_name)) <NEW_LINE> executor.execute(self.start_and_exit) <NEW_LINE> <DEDENT> while self.has_running_executors(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.test_manager.statistical_report() <NEW_LINE> self.logging.info("Test execution complete") <NEW_LINE> <DEDENT> def has_running_executors(self): <NEW_LINE> <INDENT> for executor in self.executors.values(): <NEW_LINE> <INDENT> if executor.status == 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> <DEDENT> return 0 <NEW_LINE> <DEDENT> def create_test_executors(self): <NEW_LINE> <INDENT> self.logging.info("Creating %d %s(s)" %(self.executor_count , self.executor_name_base)) <NEW_LINE> for i in range(self.executor_start_count,self.executor_count,1): <NEW_LINE> <INDENT> executor_name = "%s%d" %(self.executor_name_base,i) <NEW_LINE> new_executor = self.create_test_executor(executor_name) <NEW_LINE> <DEDENT> <DEDENT> def create_test_executor(self, executor_name): <NEW_LINE> <INDENT> self.logging.verbose("Creating %s" %(executor_name)) <NEW_LINE> new_executor = self.executor_type( self, executor_name , self.verbose, self.debug) <NEW_LINE> self.log_executor(executor_name, new_executor) <NEW_LINE> <DEDENT> def log_executor(self, executor_name, new_executor): <NEW_LINE> <INDENT> self.executors[executor_name] = new_executor <NEW_LINE> self.executor_current_count += 1 | Manages the mode-specific test-executors
and serves as an intermediary between the executors
and the other management code (system, server, test) | 62599057be383301e0254d52 |
@implements('FIFOReliableBroadcast') <NEW_LINE> @uses('ReliableBroadcast', 'rb') <NEW_LINE> class BroadcastWithSequenceNumber(ABC): <NEW_LINE> <INDENT> def upon_Init(self): <NEW_LINE> <INDENT> self.lsn = itertools.count(0) <NEW_LINE> self.pending = defaultdict(dict) <NEW_LINE> self.next = defaultdict(int) <NEW_LINE> <DEDENT> def upon_Broadcast(self, m): <NEW_LINE> <INDENT> trigger(self.rb, 'Broadcast', { 'sn': next(self.lsn), 'origin': self.addr, 'data': m, }) <NEW_LINE> <DEDENT> def upon_Deliver(self, q, m): <NEW_LINE> <INDENT> origin = m['origin'] <NEW_LINE> p = self.pending[origin] <NEW_LINE> p[m['sn']] = m['data'] <NEW_LINE> while self.next[origin] in p: <NEW_LINE> <INDENT> data = p.pop(self.next[origin]) <NEW_LINE> trigger(self.upper, 'Deliver', origin, data) <NEW_LINE> self.next[origin] += 1 | Algorithm 3.12
FIFO delivery: if some process broadcasts message m1 before it broadcasts
message m2, then no correct process delivers m2 unless it has already
delivered m1. | 6259905732920d7e50bc75d2 |
class Sink(Component): <NEW_LINE> <INDENT> bogus_path = Str('', iotype='in') <NEW_LINE> text_data = Str(iotype='out') <NEW_LINE> binary_data = Array(dtype='d', iotype='out') <NEW_LINE> text_file = File(iotype='in') <NEW_LINE> binary_file = File(iotype='in') <NEW_LINE> def execute(self): <NEW_LINE> <INDENT> if self.bogus_path: <NEW_LINE> <INDENT> self.text_file.path = self.bogus_path <NEW_LINE> <DEDENT> inp = self.text_file.open() <NEW_LINE> self.text_data = inp.read() <NEW_LINE> inp.close() <NEW_LINE> inp = self.binary_file.open() <NEW_LINE> self.binary_data = cPickle.load(inp) <NEW_LINE> inp.close() | Consumes files. | 62599057a79ad1619776b583 |
class GobjectIntrospection(Package): <NEW_LINE> <INDENT> homepage = "https://wiki.gnome.org/Projects/GObjectIntrospection" <NEW_LINE> url = "http://ftp.gnome.org/pub/gnome/sources/gobject-introspection/1.49/gobject-introspection-1.49.2.tar.xz" <NEW_LINE> version('1.49.2', 'c47a76b05b2d8438089f519922180747') <NEW_LINE> version('1.48.0', '01301fa9019667d48e927353e08bc218') <NEW_LINE> depends_on("[email protected]:", when="@1.49.2:") <NEW_LINE> depends_on("[email protected]", when="@1.48.0") <NEW_LINE> depends_on("python") <NEW_LINE> depends_on("cairo") <NEW_LINE> depends_on("bison", type="build") <NEW_LINE> depends_on("flex", type="build") <NEW_LINE> depends_on("pkgconfig", type="build") <NEW_LINE> depends_on('sed', when='platform=darwin', type='build') <NEW_LINE> patch("sbang.patch") <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> configure("--prefix=%s" % prefix) <NEW_LINE> filter_file('#!/usr/bin/env @PYTHON@', '#!@PYTHON@', 'tools/g-ir-tool-template.in') <NEW_LINE> make() <NEW_LINE> make("install") <NEW_LINE> <DEDENT> def setup_environment(self, spack_env, run_env): <NEW_LINE> <INDENT> spack_env.set('SPACK_SBANG', "%s/bin/sbang" % spack_root) | The GObject Introspection is used to describe the program APIs and
collect them in a uniform, machine readable format.Cairo is a 2D graphics
library with support for multiple output | 62599057435de62698e9d38f |
class CreativeWork(Thing): <NEW_LINE> <INDENT> _validation = { '_type': {'required': True}, 'id': {'readonly': True}, 'web_search_url': {'readonly': True}, 'name': {'readonly': True}, 'url': {'readonly': True}, 'image': {'readonly': True}, 'description': {'readonly': True}, 'alternate_name': {'readonly': True}, 'bing_id': {'readonly': True}, 'thumbnail_url': {'readonly': True}, 'provider': {'readonly': True}, 'text': {'readonly': True}, } <NEW_LINE> _attribute_map = { '_type': {'key': '_type', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'web_search_url': {'key': 'webSearchUrl', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}, 'image': {'key': 'image', 'type': 'ImageObject'}, 'description': {'key': 'description', 'type': 'str'}, 'alternate_name': {'key': 'alternateName', 'type': 'str'}, 'bing_id': {'key': 'bingId', 'type': 'str'}, 'thumbnail_url': {'key': 'thumbnailUrl', 'type': 'str'}, 'provider': {'key': 'provider', 'type': '[Thing]'}, 'text': {'key': 'text', 'type': 'str'}, } <NEW_LINE> _subtype_map = { '_type': {'MediaObject': 'MediaObject'} } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(CreativeWork, self).__init__() <NEW_LINE> self.thumbnail_url = None <NEW_LINE> self.provider = None <NEW_LINE> self.text = None <NEW_LINE> self._type = 'CreativeWork' | CreativeWork.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: MediaObject
Variables are only populated by the server, and will be ignored when
sending a request.
:param _type: Constant filled by server.
:type _type: str
:ivar id: A String identifier.
:vartype id: str
:ivar web_search_url: The URL To Bing's search result for this item.
:vartype web_search_url: str
:ivar name: The name of the thing represented by this object.
:vartype name: str
:ivar url: The URL to get more information about the thing represented by
this object.
:vartype url: str
:ivar image:
:vartype image:
~azure.cognitiveservices.search.videosearch.models.ImageObject
:ivar description: A short description of the item.
:vartype description: str
:ivar alternate_name:
:vartype alternate_name: str
:ivar bing_id: An ID that uniquely identifies this item.
:vartype bing_id: str
:ivar thumbnail_url: The URL to a thumbnail of the item.
:vartype thumbnail_url: str
:ivar provider: The source of the creative work.
:vartype provider:
list[~azure.cognitiveservices.search.videosearch.models.Thing]
:ivar text:
:vartype text: str | 6259905707d97122c4218236 |
class Human(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.player = None <NEW_LINE> <DEDENT> def set_player_ind(self, p): <NEW_LINE> <INDENT> self.player = p <NEW_LINE> <DEDENT> def get_action(self, board): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> location = input("Your move: ") <NEW_LINE> if isinstance(location, str): <NEW_LINE> <INDENT> location = [int(n, 10) for n in location.split(",")] <NEW_LINE> <DEDENT> move = board.location_to_move(location) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> move = -1 <NEW_LINE> <DEDENT> if move == -1 or move not in board.availables[self.player]: <NEW_LINE> <INDENT> print("invalid move") <NEW_LINE> move = self.get_action(board) <NEW_LINE> <DEDENT> return move <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Human {}".format(self.player) | human player | 6259905799cbb53fe683246a |
class PDFDisplay(BoxLayout): <NEW_LINE> <INDENT> def __init__(self, controller, template, display_type, **kwargs): <NEW_LINE> <INDENT> super(PDFDisplay, self).__init__(**kwargs) <NEW_LINE> self.controller = controller <NEW_LINE> self.template = template <NEW_LINE> self.pdf_canvas = PDFCanvas(controller, display_type) <NEW_LINE> self.ids.pdf_canvas_area.add_widget(self.pdf_canvas) <NEW_LINE> <DEDENT> def load_pdf(self, directory): <NEW_LINE> <INDENT> self.pdf_canvas.load_pdf(directory) <NEW_LINE> <DEDENT> def next_page(self): <NEW_LINE> <INDENT> self.pdf_canvas.next_page() <NEW_LINE> <DEDENT> def prev_page(self): <NEW_LINE> <INDENT> self.pdf_canvas.prev_page() <NEW_LINE> <DEDENT> def get_canvas(self): <NEW_LINE> <INDENT> return self.pdf_canvas <NEW_LINE> <DEDENT> def update_canvas(self, transformation, boxes): <NEW_LINE> <INDENT> return self.pdf_canvas.update_canvas(transformation, boxes) <NEW_LINE> <DEDENT> def clear_page(self): <NEW_LINE> <INDENT> self.pdf_canvas.clear_page() <NEW_LINE> <DEDENT> def get_boxes(self): <NEW_LINE> <INDENT> return self.pdf_canvas.get_boxes() <NEW_LINE> <DEDENT> def get_image_boundaries(self): <NEW_LINE> <INDENT> return self.pdf_canvas.get_image_boundaries() <NEW_LINE> <DEDENT> def add_to_box_list(self, boxes): <NEW_LINE> <INDENT> self.pdf_canvas.add_to_box_list(boxes) | PDFDisplay class handles displaying PDF as images functionalities on GUI
Attributes:
boxes: a list of rectangles objects drawn
controller: the overall layout
fig, ax: matplotlib object
pdf_canvas: kivy backend Figure Canvas object
templates_text_input: see main.kv; a boxlayout that has all text boxes
pages: read all images in a folder and store them to a list of numpy array
pageNum: current page number | 6259905745492302aabfda63 |
class Absolute(Container): <NEW_LINE> <INDENT> _command = "\\absolute" | Absolute block. | 62599057507cdc57c63a6331 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.