code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class ConfigurationDialog(QtGui.QDialog, Ui_configurationDialog): <NEW_LINE> <INDENT> def __init__(self, name, settings, configuration_page, parent): <NEW_LINE> <INDENT> QtGui.QDialog.__init__(self, parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.uiTitleLabel.setText(name) <NEW_LINE> self.setWindowTitle(configuration_page.windowTitle()) <NEW_LINE> self.uiConfigStackedWidget.addWidget(configuration_page) <NEW_LINE> self.uiConfigStackedWidget.setCurrentWidget(configuration_page) <NEW_LINE> configuration_page.loadSettings(settings) <NEW_LINE> self._settings = settings <NEW_LINE> self._configuration_page = configuration_page <NEW_LINE> <DEDENT> def on_uiButtonBox_clicked(self, button): <NEW_LINE> <INDENT> if button == self.uiButtonBox.button(QtGui.QDialogButtonBox.Cancel): <NEW_LINE> <INDENT> QtGui.QDialog.reject(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._configuration_page.saveSettings(self._settings) <NEW_LINE> <DEDENT> except ConfigurationError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> QtGui.QDialog.accept(self) | Configuration dialog implementation.
:param name: node template name
:param settings: node template settings
:param configuration_page: QWidget page
:param parent: parent widget | 62598fada79ad1619776a031 |
@register_command <NEW_LINE> class XFilesCommand(GenericCommand): <NEW_LINE> <INDENT> _cmdline_ = "xfiles" <NEW_LINE> _syntax_ = f"{_cmdline_} [FILE [NAME]]" <NEW_LINE> _example_ = f"\n{_cmdline_} libc\n{_cmdline_} libc IO_vtables" <NEW_LINE> @only_if_gdb_running <NEW_LINE> def do_invoke(self, argv: List[str]) -> None: <NEW_LINE> <INDENT> color = gef.config["theme.table_heading"] <NEW_LINE> headers = ["Start", "End", "Name", "File"] <NEW_LINE> gef_print(Color.colorify("{:<{w}s}{:<{w}s}{:<21s} {:s}".format(*headers, w=gef.arch.ptrsize*2+3), color)) <NEW_LINE> filter_by_file = argv[0] if argv and argv[0] else None <NEW_LINE> filter_by_name = argv[1] if len(argv) > 1 and argv[1] else None <NEW_LINE> for xfile in get_info_files(): <NEW_LINE> <INDENT> if filter_by_file: <NEW_LINE> <INDENT> if filter_by_file not in xfile.filename: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if filter_by_name and filter_by_name not in xfile.name: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> l = [ format_address(xfile.zone_start), format_address(xfile.zone_end), f"{xfile.name:<21s}", xfile.filename, ] <NEW_LINE> gef_print(" ".join(l)) <NEW_LINE> <DEDENT> return | Shows all libraries (and sections) loaded by binary. This command extends the GDB command
`info files`, by retrieving more information from extra sources, and providing a better
display. If an argument FILE is given, the output will grep information related to only that file.
If an argument name is also given, the output will grep to the name within FILE. | 62598fad4e4d5625663723f1 |
class PosListApiView(ListAPIView): <NEW_LINE> <INDENT> queryset = Post.objects.all() <NEW_LINE> serializer_class = PostSerializer <NEW_LINE> permission_classes = [AllowAny] | API view for posts list | 62598fad5166f23b2e2433a4 |
class MySQLConnector(DBConnector): <NEW_LINE> <INDENT> INSTANCE = None <NEW_LINE> connection = None <NEW_LINE> cursor = None <NEW_LINE> def __new__(cls): <NEW_LINE> <INDENT> if not cls.INSTANCE: <NEW_LINE> <INDENT> cls.INSTANCE = super().__new__(cls) <NEW_LINE> <DEDENT> return cls.INSTANCE <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection = mysql.connector.connect(host=Context.get(Parameter.DB_HOST), database=Context.get(Parameter.DB_NAME), user=Context.get(Parameter.DB_USERMANE), password=Context.get(Parameter.DB_PASSWORD), auth_plugin='mysql_native_password') <NEW_LINE> self.connection.autocommit = True <NEW_LINE> if self.connection.is_connected(): <NEW_LINE> <INDENT> db_info = self.connection.get_server_info() <NEW_LINE> logging.getLogger(__name__).info("Connected to MySQL Server version on %s" %db_info) <NEW_LINE> <DEDENT> <DEDENT> except Error as er: <NEW_LINE> <INDENT> logging.getLogger(__name__).error("Error while connecting to MySQL %s" %er) <NEW_LINE> <DEDENT> <DEDENT> def get_cursor(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.cursor = self.connection.cursor() <NEW_LINE> logging.getLogger(__name__).info("Cursor was created.") <NEW_LINE> <DEDENT> except Error as er: <NEW_LINE> <INDENT> logging.getLogger(__name__).error("Something went wrong with cursor creating. %s" %er) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return self.cursor <NEW_LINE> <DEDENT> <DEDENT> def get_results(self): <NEW_LINE> <INDENT> return self.cursor.fetchall() <NEW_LINE> <DEDENT> def execute_query(self, query): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> query = self.cursor.execute(query) <NEW_LINE> logging.getLogger(__name__).info("Query was execute.") <NEW_LINE> <DEDENT> except Error as er: <NEW_LINE> <INDENT> logging.getLogger(__name__).error("Error while executing query %s" %er) <NEW_LINE> <DEDENT> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.connection.is_connected(): <NEW_LINE> <INDENT> self.cursor.close() <NEW_LINE> self.connection.close() <NEW_LINE> logging.getLogger(__name__).info("Connection was succesfully closed.") <NEW_LINE> <DEDENT> logging.getLogger(__name__).info("Connection already closed.") <NEW_LINE> <DEDENT> except Error as er: <NEW_LINE> <INDENT> logging.getLogger(__name__).error("Error while closing channel %s" %er) | Connector for exection common MySQL database methods | 62598fad7cff6e4e811b59f8 |
class UserGroupPagedResponse(ModelNormal): <NEW_LINE> <INDENT> allowed_values = { } <NEW_LINE> validations = { } <NEW_LINE> additional_properties_type = None <NEW_LINE> _nullable = False <NEW_LINE> @cached_property <NEW_LINE> def openapi_types(): <NEW_LINE> <INDENT> lazy_import() <NEW_LINE> return { 'total': (int,), 'offset': (int,), 'limit': (int,), 'results': ([UserGroupImpl],), } <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def discriminator(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attribute_map = { 'total': 'total', 'offset': 'offset', 'limit': 'limit', 'results': 'results', } <NEW_LINE> _composed_schemas = {} <NEW_LINE> required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) <NEW_LINE> @convert_js_args_to_python_args <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _check_type = kwargs.pop('_check_type', True) <NEW_LINE> _spec_property_naming = kwargs.pop('_spec_property_naming', False) <NEW_LINE> _path_to_item = kwargs.pop('_path_to_item', ()) <NEW_LINE> _configuration = kwargs.pop('_configuration', None) <NEW_LINE> _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) <NEW_LINE> if args: <NEW_LINE> <INDENT> raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) <NEW_LINE> <DEDENT> self._data_store = {} <NEW_LINE> self._check_type = _check_type <NEW_LINE> self._spec_property_naming = _spec_property_naming <NEW_LINE> self._path_to_item = _path_to_item <NEW_LINE> self._configuration = _configuration <NEW_LINE> self._visited_composed_classes = _visited_composed_classes + (self.__class__,) <NEW_LINE> for var_name, var_value in kwargs.items(): <NEW_LINE> <INDENT> if var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> setattr(self, var_name, var_value) | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values. | 62598fad796e427e5384e75f |
class DepthwiseXGBPipeline(BaseXGBPipeline): <NEW_LINE> <INDENT> def __init__(self, y_col: str, model_dir: str = None, error_function: Callable = ErrorFunctions.log_loss(), include_cols: OptStrList = None, n_calls: int = 100, random_state: int = 0) -> None: <NEW_LINE> <INDENT> super(DepthwiseXGBPipeline, self).__init__( y_col=y_col, model_dir=model_dir, error_function=error_function, include_cols=include_cols, n_calls=n_calls, random_state=random_state, ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def search_space(self): <NEW_LINE> <INDENT> space = [ Real(10**-5, 1.25, "log-uniform", name='learning_rate'), Real(10**-6, 4096, "log-uniform", name='alpha'), Real(10**-6, 2048, "log-uniform", name='lambda') ] <NEW_LINE> return space <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_params(self): <NEW_LINE> <INDENT> xparam = { 'objective': 'binary:logistic', 'booster': 'gbtree', 'num_boost_round': 1000, 'max_depth': 2, 'subsample': 0.5, 'grow_policy': 'depthwise', 'verbosity': 1, 'disable_default_eval_metric': 1 } <NEW_LINE> return xparam <NEW_LINE> <DEDENT> @property <NEW_LINE> def initial_params(self): <NEW_LINE> <INDENT> return [0.01, 1.0, 1.0] | Fit ensemble of gradient boosted regression trees.
Args:
y_col (str): Name of column denoting the prediction target.
model_dir (str): Path to directory to write fitted model and
hyper-parameters to.
included_cols (list of str, optional): Names of columns in the
local_data to consider during training or `None` to include all.
n_calls (int, optional): Number of iterations for hyper-parameter search.
random_state (int, optional): Random number seed. | 62598fad283ffb24f3cf3858 |
class ViewPlugin(AdhocView): <NEW_LINE> <INDENT> view_name=_("Generic view plugin") <NEW_LINE> view_id='viewplugin' <NEW_LINE> tooltip=_("You should not ever see this tooltip...") <NEW_LINE> def __init__(self, controller=None, parameters=None): <NEW_LINE> <INDENT> super(ViewPlugin, self).__init__(controller=controller) <NEW_LINE> self.controller=controller <NEW_LINE> self.options={} <NEW_LINE> opt, arg = self.load_parameters(parameters) <NEW_LINE> self.options.update(opt) <NEW_LINE> self.widget = self.build_widget() <NEW_LINE> <DEDENT> def get_save_arguments(self): <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> def register_callback (self, controller=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def unregister_callback (self, controller=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_widget (self): <NEW_LINE> <INDENT> return self.widget <NEW_LINE> <DEDENT> def popup(self, label=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_model (self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def activate_annotation (self, annotation): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def desactivate_annotation (self, annotation): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update_model (self, package): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update_annotation (self, annotation=None, event=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def activate_relation (self, relation): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def desactivate_relation (self, relation): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update_relation (self, relation=None, event=None): <NEW_LINE> <INDENT> pass | Abstract class defining the interface of ViewPlugins.
=====================================================
The generic way of dealing with a ViewPlugin is to create an
instance of it, then call the get_widget () method to get the
corresponding Gtk widget.
In the advene framework, the view should be registered via
calls to register_view () so that it gets notified of the
element's changes.
Do not inherit from this class, as it defines many optional
methods. Inherit from AdhocView, and define the relevant
additional methods.
self.load_parameters() takes a Content object as parameter, that
must be of application/x-advene-adhoc-view mimetype. It will read
the Content data, and return an options dictionary, and arguments
as a list of (name, value) tuples. If None is passed, the view
will try to load default options (cf load_parameters docstring).
@cvar view_name: the name of the view
@type view_name: string
@cvar view_id: the id of the view
@type view_id: string
@cvar tooltip: a description of the view
@type tooltip: string
@ivar options: view options
@type options: dict
@ivar controller: the controller
@type controller: AdveneController
@ivar widget: the gtk widget representing the view
@type widget: gkt.Widget | 62598fada219f33f346c67e2 |
class BotanicalPlantDeleteView(LoginRequiredMixin, PermissionRequiredMixin, View): <NEW_LINE> <INDENT> permission_required = ('botanical.add_botsystgenus') <NEW_LINE> def get(self, request, plant_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> plant = PlntLibraries.objects.get(id=plant_id) <NEW_LINE> <DEDENT> except PlntLibraries.DoesNotExist: <NEW_LINE> <INDENT> plant = None <NEW_LINE> <DEDENT> return render(request, 'botanical_delete.html', {'plant': plant}) <NEW_LINE> <DEDENT> def post(self, request, plant_id): <NEW_LINE> <INDENT> if request.POST.get('plant_delete'): <NEW_LINE> <INDENT> plant = PlntLibraries.objects.get(id=plant_id) <NEW_LINE> if plant.cultivar: <NEW_LINE> <INDENT> cultivar = BotSystCultivar.objects.get(id=plant.cultivar.id) <NEW_LINE> cultivar.delete() <NEW_LINE> <DEDENT> plant.delete() <NEW_LINE> return redirect('botanical') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> plant = PlntLibraries.objects.get(id=plant_id) <NEW_LINE> <DEDENT> except PlntLibraries.DoesNotExist: <NEW_LINE> <INDENT> plant = None <NEW_LINE> <DEDENT> return render(request, 'botanical_delete.html', {'plant': plant, 'plant_delete': 'tak'}) | USUWANIE ROŚLINY
Widok usuwa istniejące rośliny z katalogu
get -Wyświetla szablon z informacjami o roślinie
post - Wyświetla szablon z informacjami oraz formularz usunięcia rośliny | 62598fad091ae35668704bea |
class EventDayModelAdmin(ModelAdmin): <NEW_LINE> <INDENT> model = EventDay <NEW_LINE> menu_label = "Event days" <NEW_LINE> menu_icon = "fa-calendar" <NEW_LINE> menu_order = 102 <NEW_LINE> add_to_settings_menu = False <NEW_LINE> exclude_from_explorer = True <NEW_LINE> list_display = ( "event_date_with_day", "partial_day_discount", ) <NEW_LINE> ordering = ("date",) <NEW_LINE> def event_date_with_day(self, event_day): <NEW_LINE> <INDENT> return event_day | Registrant model admin. | 62598fad76e4537e8c3ef579 |
class CreateCommentAPIView(APIView): <NEW_LINE> <INDENT> serializer_class = CommentCreateUpdateSerializer <NEW_LINE> permission_classes = [IsAuthenticated] <NEW_LINE> def post(self, request, slug, *args, **kwargs): <NEW_LINE> <INDENT> post = get_object_or_404(Post, slug=slug) <NEW_LINE> serializer = CommentCreateUpdateSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(raise_exception=True): <NEW_LINE> <INDENT> serializer.save(author=request.user, parent=post) <NEW_LINE> return Response(serializer.data, status=200) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response({"errors": serializer.errors}, status=400) | post:
Create a comment instnace. Returns created comment data
parameters: [slug, body] | 62598fad090684286d5936c2 |
class _ImageVersionItem(object): <NEW_LINE> <INDENT> def __init__(self, image_ver=None, composer_ver=None, airflow_ver=None): <NEW_LINE> <INDENT> if image_ver is not None: <NEW_LINE> <INDENT> iv_parts = image_ver.split('-', 4) <NEW_LINE> self.composer_ver = iv_parts[1] <NEW_LINE> self.airflow_ver = iv_parts[3] <NEW_LINE> <DEDENT> if composer_ver is not None: <NEW_LINE> <INDENT> self.composer_ver = composer_ver <NEW_LINE> <DEDENT> if airflow_ver is not None: <NEW_LINE> <INDENT> self.airflow_ver = airflow_ver <NEW_LINE> <DEDENT> self.contains_aliases = False <NEW_LINE> if not ALIASES.isdisjoint({self.composer_ver, self.airflow_ver}): <NEW_LINE> <INDENT> self.contains_aliases = True <NEW_LINE> <DEDENT> <DEDENT> def GetImageVersionString(self): <NEW_LINE> <INDENT> return 'composer-{}-airflow-{}'.format(self.composer_ver, self.airflow_ver) | Class used to dissect and analyze image version components and strings. | 62598fadcc0a2c111447afdd |
class DynamicTypeField(models.Model): <NEW_LINE> <INDENT> TYPE_CHOICES = ( (u'varchar', u'Short Text (less than 255 characters)'), (u'text', u'Long Text'), (u'int', u'Integer'), (u'bool', u'Flag (Boolean)'), ) <NEW_LINE> TYPE_FIELDS = { 'varchar': models.CharField(max_length=255, blank=True, null=True, default=None), 'text': models.TextField(blank=True, null=True, default=None), 'int': models.IntegerField(blank=True, null=True, default=None), 'bool': models.BooleanField(default=False), } <NEW_LINE> dynamic_type = models.ForeignKey(DynamicType) <NEW_LINE> name = models.CharField(max_length=100, help_text="Should be all-lowercase with no spaces (use underscores instead of spaces)") <NEW_LINE> value_type = models.CharField(max_length=20, choices=TYPE_CHOICES) <NEW_LINE> column = models.CharField(max_length=20, editable=False) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def save(self, force_insert=False, force_update=False): <NEW_LINE> <INDENT> if not self.pk or self.value_type != DynamicTypeField.objects.get(pk=self.pk).value_type: <NEW_LINE> <INDENT> existing_names = DynamicTypeField.objects.filter(dynamic_type=self.dynamic_type, value_type=self.value_type, ).order_by("column").values_list("column", flat=True) <NEW_LINE> i = 1 <NEW_LINE> while ("%s%02d" % (self.value_type, i)) in existing_names: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> cname = "%s%02d" % (self.value_type, i) <NEW_LINE> if not hasattr(Attribute, cname): <NEW_LINE> <INDENT> field = self.get_field_for_type(self.name, cname, self.value_type) <NEW_LINE> try: <NEW_LINE> <INDENT> db.add_column(Attribute._meta.db_table, cname, field) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Attribute.add_to_class(cname, field) <NEW_LINE> <DEDENT> new_values = {cname: Attribute._meta.get_field(cname).default} <NEW_LINE> ids = self.dynamic_type.base.model_class().objects.filter(dynamic_type=self.dynamic_type).values_list('pk', flat=True) <NEW_LINE> Attribute.objects.filter(content_type=self.dynamic_type.base, object_id__in=ids).update(**new_values) <NEW_LINE> self.column = cname <NEW_LINE> <DEDENT> super(DynamicTypeField, self).save(force_insert, force_update) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_field_for_type(name, column, type): <NEW_LINE> <INDENT> field = copy.deepcopy(DynamicTypeField.TYPE_FIELDS[type]) <NEW_LINE> field.name = name <NEW_LINE> field.attname = name <NEW_LINE> field.column = column <NEW_LINE> field.db_column = column <NEW_LINE> return field | A single, dynamically-defined field for customizing a model. | 62598fadbaa26c4b54d4f27f |
class Meta: <NEW_LINE> <INDENT> model_class = ConnectionTarget | ConnectionTargetSchema metadata. | 62598fad2c8b7c6e89bd3792 |
class UserNameNotFoundError(Error): <NEW_LINE> <INDENT> def __init__(self, message_type = "showerror", message = "Incorrect username!"): <NEW_LINE> <INDENT> super().__init__(message_type, message) | UserNameNotFoundError Exeption raised for errors in get_post_by_name function
Args:
Error (error.Error): Base class for custom errors | 62598fad3d592f4c4edbae98 |
class UNet_Colorization(nn.Module): <NEW_LINE> <INDENT> output_downscaled = 1 <NEW_LINE> module = UNetModule <NEW_LINE> def __init__(self, input_channels=3, filters_base=32, down_filter_factors=(1, 2, 4, 8, 16), up_filter_factors=(1, 2, 4, 8, 16), bottom_s=4, num_classes=1): <NEW_LINE> <INDENT> super(UNet_Colorization, self).__init__() <NEW_LINE> self.num_classes = num_classes <NEW_LINE> assert len(down_filter_factors) == len(up_filter_factors) <NEW_LINE> assert down_filter_factors[-1] == up_filter_factors[-1] <NEW_LINE> down_filter_sizes = [filters_base * s for s in down_filter_factors] <NEW_LINE> up_filter_sizes = [filters_base * s for s in up_filter_factors] <NEW_LINE> self.down, self.up = nn.ModuleList(), nn.ModuleList() <NEW_LINE> self.down.append(self.module(input_channels, down_filter_sizes[0])) <NEW_LINE> for prev_i, nf in enumerate(down_filter_sizes[1:]): <NEW_LINE> <INDENT> self.down.append(self.module(down_filter_sizes[prev_i], nf)) <NEW_LINE> <DEDENT> for prev_i, nf in enumerate(up_filter_sizes[1:]): <NEW_LINE> <INDENT> self.up.append(self.module( down_filter_sizes[prev_i] + nf, up_filter_sizes[prev_i])) <NEW_LINE> <DEDENT> pool = nn.MaxPool2d(2, 2) <NEW_LINE> pool_bottom = nn.MaxPool2d(bottom_s, bottom_s) <NEW_LINE> upsample = nn.Upsample(scale_factor=2) <NEW_LINE> upsample_bottom = nn.Upsample(scale_factor=bottom_s) <NEW_LINE> self.downsamplers = [None] + [pool] * (len(self.down) - 1) <NEW_LINE> self.downsamplers[-1] = pool_bottom <NEW_LINE> self.upsamplers = [upsample] * len(self.up) <NEW_LINE> self.upsamplers[-1] = upsample_bottom <NEW_LINE> self.conv_final = nn.Conv2d(up_filter_sizes[0], num_classes, 1) <NEW_LINE> self.conv_colorization = nn.Conv2d(num_classes, 3, 1) <NEW_LINE> self.tanh = nn.Tanh() <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> xs = [] <NEW_LINE> for downsample, down in zip(self.downsamplers, self.down): <NEW_LINE> <INDENT> x_in = x if downsample is None else downsample(xs[-1]) <NEW_LINE> x_out = down(x_in) <NEW_LINE> xs.append(x_out) <NEW_LINE> <DEDENT> x_out = xs[-1] <NEW_LINE> for x_skip, upsample, up in reversed( list(zip(xs[:-1], self.upsamplers, self.up))): <NEW_LINE> <INDENT> x_out = upsample(x_out) <NEW_LINE> x_out = up(torch.cat([x_out, x_skip], 1)) <NEW_LINE> <DEDENT> x_out = self.conv_final(x_out) <NEW_LINE> x_out = self.tanh(self.conv_colorization(x_out)) <NEW_LINE> return x_out | Vanilla UNet.
Implementation from https://github.com/lopuhin/mapillary-vistas-2017/blob/master/unet_models.py | 62598fad009cb60464d014ed |
class Home(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> return render(request, "home.html") | Homepage view. | 62598fad4428ac0f6e6584f1 |
class BYTreeIsomorphism(SageObject): <NEW_LINE> <INDENT> def __init__(self, A, B, f, eps): <NEW_LINE> <INDENT> self._domain = A <NEW_LINE> self._codomain = B <NEW_LINE> self._f = f <NEW_LINE> self._epsilon = eps <NEW_LINE> <DEDENT> def domain(self): <NEW_LINE> <INDENT> return self._domain <NEW_LINE> <DEDENT> def codomain(self): <NEW_LINE> <INDENT> return self._codomain <NEW_LINE> <DEDENT> def epsilon(self, inp): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.domain().has_edge(inp): <NEW_LINE> <INDENT> inp = next(Y for Y in self.domain().yellow_components() if inp in Y) <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return self._epsilon(inp) <NEW_LINE> <DEDENT> def __call__(self, inp): <NEW_LINE> <INDENT> if isinstance(inp, tuple): <NEW_LINE> <INDENT> return (self._f(inp[0]), self._f(inp[1]), inp[2]) <NEW_LINE> <DEDENT> return self._f(inp) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "BY tree isomorphism from %s to %s" % (self.domain(), self.codomain()) <NEW_LINE> <DEDENT> def _test(self): <NEW_LINE> <INDENT> return True | Isomorphisms between BY trees, these are graph isomorphisms that preserve
the BY tree structure, and additionally assign an sign to each yellow
component of the tree.
EXAMPLES::
sage: from sage_cluster_pictures.cluster_pictures import BYTree, BYTreeIsomorphism
sage: T = BYTree()
sage: T.add_blue_vertex('v1', 1)
sage: T.add_blue_vertex('v2', 0)
sage: T.add_yellow_edge(('v1', 'v2', 2))
sage: f = lambda v: {'v1':'v2','v2':'v1'}[v]
sage: eps = lambda c: -1
sage: F = BYTreeIsomorphism(T, T, f, eps)
sage: F
BY tree isomorphism from BY tree with 0 yellow vertices, 2 blue vertices, 1 yellow edges, 0 blue edges to BY tree with 0 yellow vertices, 2 blue vertices, 1 yellow edges, 0 blue edges | 62598fad91f36d47f2230e8c |
class FacebookUsername(models.Model): <NEW_LINE> <INDENT> post = models.ForeignKey(FacebookGame, related_name='facebook_username') <NEW_LINE> username = models.CharField(_('username'), max_length=255, choices=FacebookUserName.choices, default='empty') <NEW_LINE> x = models.PositiveIntegerField(_('x')) <NEW_LINE> y = models.PositiveIntegerField(_('y')) <NEW_LINE> color = models.CharField(_('color'), max_length=255) <NEW_LINE> font_size = models.PositiveIntegerField(_('font_size')) <NEW_LINE> text_align = models.CharField(_('text align'), max_length=225, choices=UserNameAlign.choices, default='center') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('facebook username') <NEW_LINE> verbose_name_plural = _('facebook usernames') | The username options for a Facebook Game. | 62598fad7047854f4633f3a6 |
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH <NEW_LINE> async def async_step_user(self, user_input=None): <NEW_LINE> <INDENT> errors = {} <NEW_LINE> try: <NEW_LINE> <INDENT> if "ihc" not in self.hass.data: <NEW_LINE> <INDENT> errors["base"] = "no_ihc" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if "ihc0" in self.hass.data["ihc"]: <NEW_LINE> <INDENT> errors["base"] = "old_ihc" <NEW_LINE> <DEDENT> <DEDENT> await self.async_set_unique_id( "ihcviewer-699def04-a621-47f9-bd9b-4ed8b270ef28" ) <NEW_LINE> self._abort_if_unique_id_configured() <NEW_LINE> if user_input is not None: <NEW_LINE> <INDENT> return self.async_create_entry(title="IHC Viewer", data=user_input) <NEW_LINE> <DEDENT> <DEDENT> except AbortFlow: <NEW_LINE> <INDENT> errors["base"] = "already_setup" <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _LOGGER.exception("Unexpected exception") <NEW_LINE> errors["base"] = "unknown" <NEW_LINE> <DEDENT> return self.async_show_form( step_id="user", data_schema=vol.Schema({}), errors=errors ) | Handle a config flow for IHC Viewer. | 62598fad6e29344779b00628 |
class PrepareFailure(PrepareResult): <NEW_LINE> <INDENT> def __init__(self, logs, statuses, errors, environ, overrides): <NEW_LINE> <INDENT> super(PrepareFailure, self).__init__(logs, statuses, environ, overrides) <NEW_LINE> self._errors = errors <NEW_LINE> <DEDENT> @property <NEW_LINE> def failed(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def errors(self): <NEW_LINE> <INDENT> return self._errors <NEW_LINE> <DEDENT> def print_output(self): <NEW_LINE> <INDENT> super(PrepareFailure, self).print_output() <NEW_LINE> for error in self.errors: <NEW_LINE> <INDENT> print(error, file=sys.stderr) | Class describing the failed result of preparing the project to run. | 62598fadaad79263cf42e7a0 |
class Led: <NEW_LINE> <INDENT> def __init__(self, pin): <NEW_LINE> <INDENT> self.pin = pin <NEW_LINE> self.isOn = False <NEW_LINE> GPIO.setup(self.pin, GPIO.OUT) <NEW_LINE> <DEDENT> def on(self): <NEW_LINE> <INDENT> self.isOn = True <NEW_LINE> GPIO.output(self.pin, True) <NEW_LINE> <DEDENT> def off(self): <NEW_LINE> <INDENT> self.isOn = False <NEW_LINE> GPIO.output(self.pin, False) <NEW_LINE> <DEDENT> def toggle(self): <NEW_LINE> <INDENT> if (self.isOn == True) : <NEW_LINE> <INDENT> self.off() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.on() <NEW_LINE> <DEDENT> <DEDENT> def blink(self, cycles = 1, interval = .25): <NEW_LINE> <INDENT> counter = 0 <NEW_LINE> while counter < cycles: <NEW_LINE> <INDENT> self.on() <NEW_LINE> time.sleep(interval) <NEW_LINE> self.off() <NEW_LINE> time.sleep(interval) <NEW_LINE> counter +=1 | Class to represent a single, MONOCHROME LED. Recommended ports are 19, 17 | 62598fad8e7ae83300ee906f |
class Config: <NEW_LINE> <INDENT> SECRET_KEY = environ.get('SECRET_KEY') <NEW_LINE> SESSION_COOKIE_NAME = environ.get('SESSION_COOKIE_NAME') <NEW_LINE> STATIC_FOLDER = 'static' <NEW_LINE> TEMPLATES_FOLDER = 'templates' | Base config. | 62598fad1f037a2d8b9e40bb |
class CommitResponse(object): <NEW_LINE> <INDENT> def __init__(self, response, doc_service, sdf): <NEW_LINE> <INDENT> self.response = response <NEW_LINE> self.doc_service = doc_service <NEW_LINE> self.sdf = sdf <NEW_LINE> try: <NEW_LINE> <INDENT> if hasattr(response.content, 'decode') and not hasattr(response.content, 'encode'): <NEW_LINE> <INDENT> rc = response.content.decode('utf-8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rc = response.content <NEW_LINE> <DEDENT> self.content = json.loads(rc) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> boto.log.error('Error indexing documents.\nResponse Content:\n{0}\n\n' 'SDF:\n{1}'.format(response.content, self.sdf)) <NEW_LINE> raise boto.exception.BotoServerError(self.response.status_code, '', body=response.content) <NEW_LINE> <DEDENT> self.status = self.content['status'] <NEW_LINE> if self.status == 'error': <NEW_LINE> <INDENT> self.errors = [e.get('message') for e in self.content.get('errors', [])] <NEW_LINE> for e in self.errors: <NEW_LINE> <INDENT> if "Illegal Unicode character" in e: <NEW_LINE> <INDENT> raise EncodingError("Illegal Unicode character in document") <NEW_LINE> <DEDENT> elif e == "The Content-Length is too long": <NEW_LINE> <INDENT> raise ContentTooLongError("Content was too long") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.errors = [] <NEW_LINE> <DEDENT> self.adds = self.content['adds'] <NEW_LINE> self.deletes = self.content['deletes'] <NEW_LINE> self._check_num_ops('add', self.adds) <NEW_LINE> self._check_num_ops('delete', self.deletes) <NEW_LINE> <DEDENT> def _check_num_ops(self, type_, response_num): <NEW_LINE> <INDENT> commit_num = len([d for d in self.doc_service.documents_batch if d['type'] == type_]) <NEW_LINE> if response_num != commit_num: <NEW_LINE> <INDENT> raise CommitMismatchError( 'Incorrect number of {0}s returned. Commit: {1} Response: {2}' .format(type_, commit_num, response_num)) | Wrapper for response to Cloudsearch document batch commit.
:type response: :class:`requests.models.Response`
:param response: Response from Cloudsearch /documents/batch API
:type doc_service: :class:`boto.cloudsearch.document.DocumentServiceConnection`
:param doc_service: Object containing the documents posted and methods to
retry
:raises: :class:`boto.exception.BotoServerError`
:raises: :class:`boto.cloudsearch.document.SearchServiceException`
:raises: :class:`boto.cloudsearch.document.EncodingError`
:raises: :class:`boto.cloudsearch.document.ContentTooLongError` | 62598fad7047854f4633f3a7 |
class DuplicateVendorIdError(CvError): <NEW_LINE> <INDENT> def __init__(self, stanza): <NEW_LINE> <INDENT> CvError.__init__(self, stanza) <NEW_LINE> self.msg = '%s' % self.stanza['vendorId'] <NEW_LINE> self.strict = 0 | When there exists more than one connected component of stanzas (through derivedFrom) with the same vendorId | 62598fadaad79263cf42e7a1 |
class HomeRedirectView(RedirectView): <NEW_LINE> <INDENT> permanent = True <NEW_LINE> def get_redirect_url(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.request.user.is_authenticated: <NEW_LINE> <INDENT> return reverse('subscription_list') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return reverse('plan_list') | Choose the right home page for logged in and logged out users. | 62598fadadb09d7d5dc0a557 |
class LocationViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = Location.objects.filter(point__isnull=False) <NEW_LINE> serializer_class = LocationSerializer | API endpoint that allows Locations to be viewed | 62598fad97e22403b383aeda |
class PathString(str): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> super(PathString, self).__init__(value) <NEW_LINE> self.full_path = value | Helper class so that the file name strings
can pick up a full_path attribute. | 62598fadd7e4931a7ef3c063 |
class Question(Timestamps): <NEW_LINE> <INDENT> content = models.CharField(max_length=256, unique=True) <NEW_LINE> categories = models.ManyToManyField(Category) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f"{self.content}" <NEW_LINE> <DEDENT> def get_categories(self): <NEW_LINE> <INDENT> return ", ".join([ category.name for category in self.categories.all()]) <NEW_LINE> <DEDENT> get_categories.short_description = "Categories" | model for card question:
how do you feel about etc... | 62598fad67a9b606de545f9a |
class TraceGenerator(ElementGenerator): <NEW_LINE> <INDENT> def __init__(self, source, attributes=None): <NEW_LINE> <INDENT> if attributes is None: <NEW_LINE> <INDENT> attributes, classifiers, extensions = dict(), dict(), dict() <NEW_LINE> omni = {"trace": dict(), "event": dict()} <NEW_LINE> attributes = { 'attributes': attributes, 'classifiers': classifiers, 'extensions': extensions, 'omni': omni } <NEW_LINE> <DEDENT> super(TraceGenerator, self).__init__(source, attributes=attributes) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> if self._source is None: <NEW_LINE> <INDENT> raise ValueError( "No underlying generator has yet been initialized.") <NEW_LINE> <DEDENT> return iter(self._source) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_file(filepath, compression=None, infer_type=False): <NEW_LINE> <INDENT> gen = XESImporter(filepath, compression, infer_type) <NEW_LINE> attributes = gen._extract_meta() <NEW_LINE> return TraceGenerator(gen, attributes=attributes) | Generating trace class, representation for an event log.
Parameters
----------
source: iterable or list-like
Underlying generator.
attributes: dict, default `None`
Set of attributs, such as event log attributes, classifiers,
extensions and global trace and event definitions.
Examples
--------
First a simple example on how to construct (although very unlikely,
you'll ever do it this way) and iterate over a `TraceGenerator`.
>>> traces = [ Trace(Event(), Event()), Trace(Event())]
>>> L = TraceGenerator(traces)
>>> for t in L:
... print(t)
... Trace( attributes={}, number_of_events=2 )
... Trace( attributes={}, number_of_events=1 )
Now onto a more pragmatic example.
>>> filepath = "https://raw.githubusercontent.com/xcavation/feldspar/feature/base-setup/data/running-example.xes"
>>> L = TraceFeeder.from_file(filepath)
>>> L = L.map(lambda trace: tuple(event["concept:name"] for event in trace))
>>> L = L.filter(lambda trace: len(trace) < 5)
>>> L = L.shuffle() | 62598fada219f33f346c67e4 |
class ChatPhoto(TelegramObject): <NEW_LINE> <INDENT> def __init__( self, small_file_id: str, small_file_unique_id: str, big_file_id: str, big_file_unique_id: str, bot: 'Bot' = None, **_kwargs: Any, ): <NEW_LINE> <INDENT> self.small_file_id = small_file_id <NEW_LINE> self.small_file_unique_id = small_file_unique_id <NEW_LINE> self.big_file_id = big_file_id <NEW_LINE> self.big_file_unique_id = big_file_unique_id <NEW_LINE> self.bot = bot <NEW_LINE> self._id_attrs = ( self.small_file_unique_id, self.big_file_unique_id, ) <NEW_LINE> <DEDENT> def get_small_file(self, timeout: float = None, api_kwargs: JSONDict = None) -> 'File': <NEW_LINE> <INDENT> return self.bot.get_file( file_id=self.small_file_id, timeout=timeout, api_kwargs=api_kwargs ) <NEW_LINE> <DEDENT> def get_big_file(self, timeout: float = None, api_kwargs: JSONDict = None) -> 'File': <NEW_LINE> <INDENT> return self.bot.get_file(file_id=self.big_file_id, timeout=timeout, api_kwargs=api_kwargs) | This object represents a chat photo.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`small_file_unique_id` and :attr:`big_file_unique_id` are
equal.
Args:
small_file_id (:obj:`str`): Unique file identifier of small (160x160) chat photo. This
file_id can be used only for photo download and only for as long
as the photo is not changed.
small_file_unique_id (:obj:`str`): Unique file identifier of small (160x160) chat photo,
which is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
big_file_id (:obj:`str`): Unique file identifier of big (640x640) chat photo. This file_id
can be used only for photo download and only for as long as the photo is not changed.
big_file_unique_id (:obj:`str`): Unique file identifier of big (640x640) chat photo,
which is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
small_file_id (:obj:`str`): File identifier of small (160x160) chat photo.
This file_id can be used only for photo download and only for as long
as the photo is not changed.
small_file_unique_id (:obj:`str`): Unique file identifier of small (160x160) chat photo,
which is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
big_file_id (:obj:`str`): File identifier of big (640x640) chat photo.
This file_id can be used only for photo download and only for as long as
the photo is not changed.
big_file_unique_id (:obj:`str`): Unique file identifier of big (640x640) chat photo,
which is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file. | 62598fad091ae35668704bec |
class Project(models.Model): <NEW_LINE> <INDENT> WEB_CATEGORY = 1 <NEW_LINE> PROGRAMMING_CATEGORY = 2 <NEW_LINE> GAME_CATEGORY = 3 <NEW_LINE> CATEGORY_CHOICES = ((WEB_CATEGORY, 'Web Development'), (PROGRAMMING_CATEGORY, 'Programming'), (GAME_CATEGORY, 'Game Development'),) <NEW_LINE> PUBLISHED_CHOICES = ( (False, 'Save as Draft'), (True, 'Publish to Portfolio'), ) <NEW_LINE> title = models.CharField(max_length=64, default="") <NEW_LINE> subtitle = models.CharField(max_length=64, blank=True, default="") <NEW_LINE> date = models.DateField(blank=True, null=True) <NEW_LINE> published = models.BooleanField(default=False, choices=PUBLISHED_CHOICES) <NEW_LINE> slug = models.SlugField(max_length=64, unique=True, db_index=True, blank=True, default="") <NEW_LINE> external_url = models.URLField(blank=True, default="") <NEW_LINE> repository = models.URLField(blank=True, default="") <NEW_LINE> category = models.IntegerField(choices=CATEGORY_CHOICES, default=WEB_CATEGORY) <NEW_LINE> tags = TaggableManager(manager=ProjectTagManager, through=TaggedProject, blank=True) <NEW_LINE> snippet = models.CharField(max_length=1024, blank=True, default="") <NEW_LINE> description = models.CharField(max_length=160, blank=True, default="") <NEW_LINE> content = models.TextField(blank=True, default="") <NEW_LINE> thumbnail = models.ForeignKey(Image, blank=True, null=True, on_delete=models.SET_NULL) <NEW_LINE> images = GenericRelation(Image, related_query_name='project_images', content_type_field='content_type', object_id_field='object_id') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> get_latest_by = 'date' <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.slug is None: <NEW_LINE> <INDENT> self.slug = slugify(self.title) <NEW_LINE> <DEDENT> self.slug = slugify(self.slug) <NEW_LINE> super(Project, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def content_formatted(self): <NEW_LINE> <INDENT> md = markdown.Markdown(extensions=['markdown.extensions.tables', 'markdown.extensions.fenced_code', 'markdown.extensions.codehilite']) <NEW_LINE> content = insert_images(self, self.content) <NEW_LINE> return md.convert(self.content) <NEW_LINE> <DEDENT> def snippet_formatted(self): <NEW_LINE> <INDENT> md = markdown.Markdown(extensions=['markdown.extensions.fenced_code', 'markdown.extensions.codehilite']) <NEW_LINE> return md.convert(self.snippet) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.title | A project in the portfolio | 62598fad76e4537e8c3ef57b |
class ServiceHandlerBase(object): <NEW_LINE> <INDENT> url = None <NEW_LINE> service_type = None <NEW_LINE> name = "" <NEW_LINE> indexing_method = None <NEW_LINE> def __init__(self, url): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_cascaded(self): <NEW_LINE> <INDENT> return True if self.indexing_method == enumerations.CASCADED else False <NEW_LINE> <DEDENT> def create_geonode_service(self, owner, parent=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_keywords(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_resource(self, resource_id): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_resources(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def harvest_resource(self, resource_id, geonode_service): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def has_resources(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def has_unharvested_resources(self, geonode_service): <NEW_LINE> <INDENT> already_done = list(models.HarvestJob.objects.values_list( "resource_id", flat=True).filter(service=geonode_service)) <NEW_LINE> for resource in self.get_resources(): <NEW_LINE> <INDENT> if resource.id not in already_done: <NEW_LINE> <INDENT> result = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> return result | Base class for remote service handlers
This class is not to be instantiated directly, but rather subclassed by
concrete implementations. The method stubs defined here must be implemented
in derived classes. | 62598faddd821e528d6d8f03 |
class Sip_Acc(object): <NEW_LINE> <INDENT> def __init__(self, Name, Passw=0, Dep=0, Number=0, Mailbox=0): <NEW_LINE> <INDENT> self.Name = Name <NEW_LINE> self.Passw = Passw <NEW_LINE> self.Dep = Dep <NEW_LINE> self.Number = Number <NEW_LINE> self.Mailbox = Mailbox | This is a class of sip users | 62598fadcb5e8a47e493c160 |
class PageLanguageUrl(InclusionTag): <NEW_LINE> <INDENT> name = 'page_language_url' <NEW_LINE> template = 'cms/content.html' <NEW_LINE> options = Options( Argument('lang'), ) <NEW_LINE> def get_context(self, context, lang): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request = context['request'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return {'template': 'cms/content.html'} <NEW_LINE> <DEDENT> if hasattr(request, "_language_changer"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setattr(request._language_changer, 'request', request) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> url = "/%s" % lang + request._language_changer(lang) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> page = request.current_page <NEW_LINE> if page == "dummy": <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> url = page.get_absolute_url(language=lang, fallback=False) <NEW_LINE> url = "/" + lang + url <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> url = '' <NEW_LINE> <DEDENT> <DEDENT> return {'content':url} | Displays the url of the current page in the defined language.
You can set a language_changer function with the set_language_changer function in the utils.py if there is no page.
This is needed if you have slugs in more than one language. | 62598fadfff4ab517ebcd7b3 |
class AccessIPs(extensions.V3APIExtensionBase): <NEW_LINE> <INDENT> name = "AccessIPs" <NEW_LINE> alias = ALIAS <NEW_LINE> namespace = ("http://docs.openstack.org/compute/ext/" "os-access-ips/api/v3") <NEW_LINE> version = 1 <NEW_LINE> v4_key = '%s:access_ip_v4' % ALIAS <NEW_LINE> v6_key = '%s:access_ip_v6' % ALIAS <NEW_LINE> def get_controller_extensions(self): <NEW_LINE> <INDENT> controller = AccessIPsController() <NEW_LINE> extension = extensions.ControllerExtension(self, 'servers', controller) <NEW_LINE> return [extension] <NEW_LINE> <DEDENT> def get_resources(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def server_create(self, server_dict, create_kwargs): <NEW_LINE> <INDENT> if AccessIPs.v4_key in server_dict: <NEW_LINE> <INDENT> access_ip_v4 = server_dict.get(AccessIPs.v4_key) <NEW_LINE> if access_ip_v4: <NEW_LINE> <INDENT> self._validate_access_ipv4(access_ip_v4) <NEW_LINE> create_kwargs['access_ip_v4'] = access_ip_v4 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> create_kwargs['access_ip_v4'] = None <NEW_LINE> <DEDENT> <DEDENT> if AccessIPs.v6_key in server_dict: <NEW_LINE> <INDENT> access_ip_v6 = server_dict.get(AccessIPs.v6_key) <NEW_LINE> if access_ip_v6: <NEW_LINE> <INDENT> self._validate_access_ipv6(access_ip_v6) <NEW_LINE> create_kwargs['access_ip_v6'] = access_ip_v6 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> create_kwargs['access_ip_v6'] = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> server_update = server_create <NEW_LINE> server_rebuild = server_create <NEW_LINE> def _validate_access_ipv4(self, address): <NEW_LINE> <INDENT> if not utils.is_valid_ipv4(address): <NEW_LINE> <INDENT> expl = _('access_ip_v4 is not proper IPv4 format') <NEW_LINE> raise exc.HTTPBadRequest(explanation=expl) <NEW_LINE> <DEDENT> <DEDENT> def _validate_access_ipv6(self, address): <NEW_LINE> <INDENT> if not utils.is_valid_ipv6(address): <NEW_LINE> <INDENT> expl = _('access_ip_v6 is not proper IPv6 format') <NEW_LINE> raise exc.HTTPBadRequest(explanation=expl) | Access IPs support. | 62598fadd486a94d0ba2bf9d |
class FloatValidator(Validator): <NEW_LINE> <INDENT> minimum = Typed(float) <NEW_LINE> maximum = Typed(float) <NEW_LINE> allow_exponent = Bool(True) <NEW_LINE> def validate(self, text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = float(text) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> minimum = self.minimum <NEW_LINE> if minimum is not None and value < minimum: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> maximum = self.maximum <NEW_LINE> if maximum is not None and value > maximum: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self.allow_exponent and 'e' in text.lower(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | A concrete Validator which handles floating point input.
This validator ensures that the text represents a floating point
number within a specified range. | 62598fad5fdd1c0f98e5df5b |
class OrderList(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[Order]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(OrderList, self).__init__(**kwargs) <NEW_LINE> self.value = None <NEW_LINE> self.next_link = None | List of order entities.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: The list of orders.
:vartype value: list[~azure.mgmt.databoxedge.v2020_09_01_preview.models.Order]
:ivar next_link: Link to the next set of results.
:vartype next_link: str | 62598fad009cb60464d014ef |
@admin.register(EpicMember) <NEW_LINE> class UserAdmin(UserAdmin): <NEW_LINE> <INDENT> fieldsets = [ ( None, { "fields": [ "username", "password", "first_name", "last_name", "email", "team", ] }, ), ( "Status", { "classes": [ "collapse", ], "fields": ["is_active", "is_staff", "is_superuser"], }, ), ( "Dates", { "fields": ["date_joined", "last_login"], }, ), ] <NEW_LINE> readonly_fields = ["date_joined", "last_login"] <NEW_LINE> list_display = ( "username", "email", "team", ) <NEW_LINE> list_filter = ( "is_active", "team", ) <NEW_LINE> def get_readonly_fields(self, request, obj=None): <NEW_LINE> <INDENT> if request.user.team == EpicMember.Team.MANAGE: <NEW_LINE> <INDENT> return self.readonly_fields + ["is_superuser", "is_staff"] <NEW_LINE> <DEDENT> return self.readonly_fields <NEW_LINE> <DEDENT> def save_model(self, request, obj, form, change): <NEW_LINE> <INDENT> if request.user.is_superuser or request.user.team == EpicMember.Team.MANAGE: <NEW_LINE> <INDENT> obj.is_staff = True <NEW_LINE> obj.save() <NEW_LINE> <DEDENT> <DEDENT> def has_add_change_delete_permission(self, request, obj=None): <NEW_LINE> <INDENT> if not hasattr(request.user, "team"): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if request.user.is_superuser or request.user.team == EpicMember.Team.MANAGE: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def has_view_permission(self, request, obj=None): <NEW_LINE> <INDENT> return self.has_add_change_delete_permission(request, obj) <NEW_LINE> <DEDENT> def has_module_permission(self, request): <NEW_LINE> <INDENT> return self.has_add_change_delete_permission(request) <NEW_LINE> <DEDENT> def has_add_permission(self, request): <NEW_LINE> <INDENT> return self.has_add_change_delete_permission(request) <NEW_LINE> <DEDENT> def has_change_permission(self, request, obj=None): <NEW_LINE> <INDENT> return self.has_add_change_delete_permission(request, obj) <NEW_LINE> <DEDENT> def has_delete_permission(self, request, obj=None): <NEW_LINE> <INDENT> return self.has_add_change_delete_permission(request, obj) | Define the 'EpicMember' admin section behaviors & displays. | 62598fad6e29344779b0062a |
class Executor(object): <NEW_LINE> <INDENT> def execute(self, node): <NEW_LINE> <INDENT> if isinstance(node, DataAccess): <NEW_LINE> <INDENT> return self.execute_data_access(node) <NEW_LINE> <DEDENT> if isinstance(node, Aggregate): <NEW_LINE> <INDENT> return self.execute_aggregate(node) <NEW_LINE> <DEDENT> if isinstance(node, Filter): <NEW_LINE> <INDENT> return self.execute_filter(node) <NEW_LINE> <DEDENT> if isinstance(node, Join): <NEW_LINE> <INDENT> return self.execute_join(node) <NEW_LINE> <DEDENT> if isinstance(node, Limit): <NEW_LINE> <INDENT> return self.execute_limit(node) <NEW_LINE> <DEDENT> if isinstance(node, OrderBy): <NEW_LINE> <INDENT> return self.execute_order_by(node) <NEW_LINE> <DEDENT> if isinstance(node, Project): <NEW_LINE> <INDENT> return self.execute_project(node) <NEW_LINE> <DEDENT> raise NotImplemented <NEW_LINE> <DEDENT> def finalize(self, result): <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> def execute_data_access(self, node): <NEW_LINE> <INDENT> registry = DataSourceAdapterRegistry() <NEW_LINE> adapter = registry.get(type(self), type(node))() <NEW_LINE> return adapter.execute(node, self) <NEW_LINE> <DEDENT> def execute_aggregate(self, node): <NEW_LINE> <INDENT> raise NotImplemented <NEW_LINE> <DEDENT> def execute_filter(self, node): <NEW_LINE> <INDENT> raise NotImplemented <NEW_LINE> <DEDENT> def execute_join(self, node): <NEW_LINE> <INDENT> raise NotImplemented <NEW_LINE> <DEDENT> def execute_limit(self, node): <NEW_LINE> <INDENT> raise NotImplemented <NEW_LINE> <DEDENT> def execute_order_by(self, node): <NEW_LINE> <INDENT> raise NotImplemented <NEW_LINE> <DEDENT> def execute_project(self, node): <NEW_LINE> <INDENT> raise NotImplemented | The Executor interface. ALL methods must be copied over (and implemented)
to an Executor implementation, including the first method below which sets
up the dynamic dispatcher. | 62598fad627d3e7fe0e06e7c |
@reversion.register(follow=['owner_type']) <NEW_LINE> @encoding.python_2_unicode_compatible <NEW_LINE> class Owner(AbstractBase, SequenceMixin): <NEW_LINE> <INDENT> name = models.CharField( max_length=100, unique=True, help_text="The name of owner e.g Ministry of Health.") <NEW_LINE> description = models.TextField( null=True, blank=True, help_text="A brief summary of the owner.") <NEW_LINE> code = SequenceField( unique=True, help_text="A unique number to identify the owner." "Could be up to 7 characters long.", editable=False) <NEW_LINE> abbreviation = models.CharField( max_length=30, null=True, blank=True, help_text="Short form of the name of the owner e.g Ministry of health" " could be shortened as MOH") <NEW_LINE> owner_type = models.ForeignKey( OwnerType, help_text="The classification of the owner e.g INDIVIDUAL", on_delete=models.PROTECT) <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.code: <NEW_LINE> <INDENT> self.code = self.generate_next_code_sequence() <NEW_LINE> <DEDENT> super(Owner, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name | Entity that has exclusive legal rights to the facility.
For the master facility list, ownership especially for the faith-based
facilities is broadened to also include the body that coordinates
service delivery and health programs. Therefore, the Christian Health
Association of Kenya (CHAK), Kenya Episcopal Conference (KEC), or
Supreme Council of Kenya Muslim (SUPKEM) will be termed as owners though
in fact the facilities under them are owned by the individual churches,
mosques, or communities affiliated with the faith. | 62598fadfff4ab517ebcd7b4 |
class EpitheliumSegmentation: <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self._args = kwargs <NEW_LINE> <DEDENT> @lazy_property <NEW_LINE> def datasets(self): <NEW_LINE> <INDENT> logger.info('loading epithelium dataset...') <NEW_LINE> folds = create_cv(**self._args) <NEW_LINE> datasets = np.array([Dataset(f['pos'], f['neg']) for f in folds]) <NEW_LINE> return datasets <NEW_LINE> <DEDENT> def load(self, fold): <NEW_LINE> <INDENT> k = len(self.datasets) <NEW_LINE> assert 0 <= fold < k <NEW_LINE> test = self.datasets[fold] <NEW_LINE> validation = self.datasets[(fold + 1) % k] <NEW_LINE> train = [ds for ds in self.datasets if ds != test and ds != validation] <NEW_LINE> train = torch.utils.data.ConcatDataset(train) <NEW_LINE> return train, validation, test | A cross-validation loader for the epithelium segmentation dataset.
| 62598fad01c39578d7f12d4e |
class PlainTextCommandRenderer(renderers.BaseRenderer): <NEW_LINE> <INDENT> shebang = '#!/usr/bin/env sh' <NEW_LINE> media_type = 'text/plain' <NEW_LINE> format = 'txt' <NEW_LINE> def render(self, data, media_type=None, renderer_context=None): <NEW_LINE> <INDENT> if isinstance(data, dict) and data.has_key('execute'): <NEW_LINE> <INDENT> output = "%s\n%s\n" % (self.shebang, data['execute']) <NEW_LINE> return output <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return data | Renders a single command object to a shell script | 62598fad63d6d428bbee277a |
class TestMultipleNormals(unittest.TestCase): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> dir = N.array([[1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]).T / math.sqrt(3) <NEW_LINE> normal = N.array([[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]]).T / N.sqrt([1, 2, 3, 2]) <NEW_LINE> correct_reflection = N.tile([1, 1, 1], (4,1)).T / math.sqrt(3) <NEW_LINE> reflection = optics.reflections(dir, normal) <NEW_LINE> self.failUnless(N.allclose(reflection, correct_reflection), "Reflection is\n" + str(reflection) + "\nbut should be\n" + str(correct_reflection)) | When each ray has its own normal, each reflection uses the corresponding
normal | 62598fad10dbd63aa1c70b82 |
class FooterModule(PatchewModule): <NEW_LINE> <INDENT> name = "footer" <NEW_LINE> default_config = _default_config <NEW_LINE> def render_page_hook(self, request, context_data): <NEW_LINE> <INDENT> context_data.setdefault("footer", "") <NEW_LINE> context_data["footer"] += self.get_config_raw() | Documentation
-------------
This is a simple module to inject any HTML code into the page bottom. Can be
useful to add statistic code, etc..
The config is the raw HTML code to inject. | 62598fad60cbc95b0636431e |
class Main(BrowserView): <NEW_LINE> <INDENT> def _getRoot(self): <NEW_LINE> <INDENT> if not putils.base_hasattr(self, '_root'): <NEW_LINE> <INDENT> portal_url = getToolByName(self.context, 'portal_url') <NEW_LINE> portal = portal_url.getPortalObject() <NEW_LINE> obj = self.context <NEW_LINE> while aq_base(obj) is not aq_base(portal): <NEW_LINE> <INDENT> obj = aq_parent(aq_inner(obj)) <NEW_LINE> <DEDENT> self._root = [obj] <NEW_LINE> <DEDENT> return self._root[0] <NEW_LINE> <DEDENT> def inApplication(self): <NEW_LINE> <INDENT> root = self._getRoot() <NEW_LINE> portal_url = getToolByName(self.context, 'portal_url') <NEW_LINE> portal = portal_url.getPortalObject() <NEW_LINE> return root != aq_base(portal) | Main View
| 62598faddd821e528d6d8f04 |
class ArNMEAParser(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, name = "NMEA Parser"): <NEW_LINE> <INDENT> this = _AriaPy.new_ArNMEAParser(name) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> ParseFinished = _AriaPy.ArNMEAParser_ParseFinished <NEW_LINE> ParseError = _AriaPy.ArNMEAParser_ParseError <NEW_LINE> ParseData = _AriaPy.ArNMEAParser_ParseData <NEW_LINE> ParseUpdated = _AriaPy.ArNMEAParser_ParseUpdated <NEW_LINE> ParseFlags = _swig_property(_AriaPy.ArNMEAParser_ParseFlags_get, _AriaPy.ArNMEAParser_ParseFlags_set) <NEW_LINE> def setIgnoreChecksum(self, *args): <NEW_LINE> <INDENT> return _AriaPy.ArNMEAParser_setIgnoreChecksum(self, *args) <NEW_LINE> <DEDENT> def addHandler(self, *args): <NEW_LINE> <INDENT> return _AriaPy.ArNMEAParser_addHandler(self, *args) <NEW_LINE> <DEDENT> def removeHandler(self, *args): <NEW_LINE> <INDENT> return _AriaPy.ArNMEAParser_removeHandler(self, *args) <NEW_LINE> <DEDENT> def parse(self, *args): <NEW_LINE> <INDENT> return _AriaPy.ArNMEAParser_parse(self, *args) <NEW_LINE> <DEDENT> def getHandlersRef(self): <NEW_LINE> <INDENT> return _AriaPy.ArNMEAParser_getHandlersRef(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _AriaPy.delete_ArNMEAParser <NEW_LINE> __del__ = lambda self : None; | Proxy of C++ ArNMEAParser class | 62598fad56b00c62f0fb2884 |
class Uncrustify(Package): <NEW_LINE> <INDENT> homepage = "http://uncrustify.sourceforge.net/" <NEW_LINE> url = "http://downloads.sourceforge.net/project/uncrustify/uncrustify/uncrustify-0.61/uncrustify-0.61.tar.gz" <NEW_LINE> version('0.67', '0c9a08366e5c97cd02ae766064e957de41827611') <NEW_LINE> version('0.61', 'b6140106e74c64e831d0b1c4b6cf7727') <NEW_LINE> depends_on('cmake', type='build', when='@0.64:') <NEW_LINE> @when('@0.64:') <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> with working_dir('spack-build', create=True): <NEW_LINE> <INDENT> cmake('..', *std_cmake_args) <NEW_LINE> make() <NEW_LINE> make('install') <NEW_LINE> <DEDENT> <DEDENT> @when('@:0.62') <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> configure('--prefix={0}'.format(self.prefix)) <NEW_LINE> make() <NEW_LINE> make('install') | Source Code Beautifier for C, C++, C#, ObjectiveC, Java, and others. | 62598fadf7d966606f747fb5 |
class MissingError(Exception): <NEW_LINE> <INDENT> pass | Indicates something is missing | 62598fade76e3b2f99fd8a06 |
class Missing: <NEW_LINE> <INDENT> def __bool__(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) <NEW_LINE> <DEDENT> __nonzero__ = __bool__ <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<dynaconf.missing>" | Sentinel value object/singleton used to differentiate between ambiguous
situations where `None` is a valid value. | 62598fade5267d203ee6b8da |
class SetNode(ExprNode): <NEW_LINE> <INDENT> subexprs = ['args'] <NEW_LINE> type = set_type <NEW_LINE> is_set_literal = True <NEW_LINE> gil_message = "Constructing Python set" <NEW_LINE> def analyse_types(self, env): <NEW_LINE> <INDENT> for i in range(len(self.args)): <NEW_LINE> <INDENT> arg = self.args[i] <NEW_LINE> arg = arg.analyse_types(env) <NEW_LINE> self.args[i] = arg.coerce_to_pyobject(env) <NEW_LINE> <DEDENT> self.type = set_type <NEW_LINE> self.is_temp = 1 <NEW_LINE> return self <NEW_LINE> <DEDENT> def may_be_none(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def calculate_constant_result(self): <NEW_LINE> <INDENT> self.constant_result = {arg.constant_result for arg in self.args} <NEW_LINE> <DEDENT> def compile_time_value(self, denv): <NEW_LINE> <INDENT> values = [arg.compile_time_value(denv) for arg in self.args] <NEW_LINE> try: <NEW_LINE> <INDENT> return set(values) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.compile_time_value_error(e) <NEW_LINE> <DEDENT> <DEDENT> def generate_evaluation_code(self, code): <NEW_LINE> <INDENT> for arg in self.args: <NEW_LINE> <INDENT> arg.generate_evaluation_code(code) <NEW_LINE> <DEDENT> self.allocate_temp_result(code) <NEW_LINE> code.putln( "%s = PySet_New(0); %s" % ( self.result(), code.error_goto_if_null(self.result(), self.pos))) <NEW_LINE> self.generate_gotref(code) <NEW_LINE> for arg in self.args: <NEW_LINE> <INDENT> code.put_error_if_neg( self.pos, "PySet_Add(%s, %s)" % (self.result(), arg.py_result())) <NEW_LINE> arg.generate_disposal_code(code) <NEW_LINE> arg.free_temps(code) | Set constructor. | 62598fadac7a0e7691f724d9 |
class ModelData: <NEW_LINE> <INDENT> def __init__(self, dirname): <NEW_LINE> <INDENT> if not os.path.isdir(dirname): <NEW_LINE> <INDENT> raise ValueError("dirname needs to be a valid directory") <NEW_LINE> <DEDENT> files = os.listdir(dirname) <NEW_LINE> self.__meta_file = None <NEW_LINE> self.__data_files = {} <NEW_LINE> for f in files: <NEW_LINE> <INDENT> if ".meta" in f: <NEW_LINE> <INDENT> if self.__meta_file is None: <NEW_LINE> <INDENT> self.__meta_file = dirname + "/" + f <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> warn("Found at least two meta files in directory. Choosing first one.") <NEW_LINE> <DEDENT> <DEDENT> elif ".data" in f: <NEW_LINE> <INDENT> num_start = f.find(".ckpt") + 6 <NEW_LINE> num_end = f.find(".data") <NEW_LINE> try: <NEW_LINE> <INDENT> num = int(f[num_start:num_end]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.__data_files[num] = dirname + "/" + f[:num_end] <NEW_LINE> <DEDENT> <DEDENT> self.__input_dims = None <NEW_LINE> self._hidden_sizes = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def CheckpointIndices(self): <NEW_LINE> <INDENT> return sorted(self.__data_files.keys()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def FirstCheckpoint(self): <NEW_LINE> <INDENT> return self.__data_files[self.CheckpointIndices[0]] <NEW_LINE> <DEDENT> @property <NEW_LINE> def LastCheckpoint(self): <NEW_LINE> <INDENT> return self.__data_files[self.CheckpointIndices[-1]] <NEW_LINE> <DEDENT> @property <NEW_LINE> def ModelDefinition(self): <NEW_LINE> <INDENT> return self.__meta_file <NEW_LINE> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return item in self.__data_files <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> if type(item) != int: <NEW_LINE> <INDENT> raise TypeError("Key has to be integer") <NEW_LINE> <DEDENT> if item in self.__data_files: <NEW_LINE> <INDENT> return self.__data_files[item] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError("No checkpoint with index {0} found.".format(item)) | Provides access to model meta and checkpoint files by index from a given directory | 62598fad435de62698e9bdc0 |
class ActiveVWProcess(): <NEW_LINE> <INDENT> _buffer = b'' <NEW_LINE> def __init__(self, command, port=DEFAULT_PORT): <NEW_LINE> <INDENT> self.vw_process = pexpect.spawn(command) <NEW_LINE> time.sleep(5) <NEW_LINE> self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> connection_tries = 0 <NEW_LINE> while connection_tries < MAX_CONNECTION_ATTEMPTS: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.sock.connect(('127.0.0.1', port)) <NEW_LINE> break <NEW_LINE> <DEDENT> except socket.error: <NEW_LINE> <INDENT> connection_tries += 1 <NEW_LINE> time.sleep(CONNECTION_WAIT) <NEW_LINE> <DEDENT> <DEDENT> self.before = None <NEW_LINE> <DEDENT> def sendline(self, line): <NEW_LINE> <INDENT> line = line + '\n' <NEW_LINE> if not isinstance(line, bytes): <NEW_LINE> <INDENT> line = line.encode('UTF-8') <NEW_LINE> <DEDENT> self.sock.sendall(line) <NEW_LINE> <DEDENT> def _recvline(self): <NEW_LINE> <INDENT> if b'\n' in self._buffer: <NEW_LINE> <INDENT> line, _, self._buffer = self._buffer.partition(b'\n') <NEW_LINE> return line <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> more = self.sock.recv(4096) <NEW_LINE> self._buffer += more <NEW_LINE> if not more: <NEW_LINE> <INDENT> rv = self._buffer <NEW_LINE> self._buffer = b'' <NEW_LINE> return rv <NEW_LINE> <DEDENT> if b'\n' in more: <NEW_LINE> <INDENT> line, _, self._buffer = self._buffer.partition(b'\n') <NEW_LINE> return line <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def expect_exact(self, *args, **kwargs): <NEW_LINE> <INDENT> response = self._recvline() <NEW_LINE> self.before = response.strip() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.sock.close() <NEW_LINE> self.vw_process.close() | Class for spawning and interacting with a WV process
in active learning mode. This class implements a subset of the interface
of a pexpect.spawn() object so that it can be a drop-in replacement
for the VW.vw_process member. | 62598fadeab8aa0e5d30bd5c |
class AjaxSaveCusotmMarker(View): <NEW_LINE> <INDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> client_ip, is_routable = get_client_ip(request) <NEW_LINE> if BlockedIP.objects.filter(ip=client_ip).count() == 0: <NEW_LINE> <INDENT> form = CustomPlacemarkForm(request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> marker = form.save(commit=False) <NEW_LINE> marker.user_ip = client_ip <NEW_LINE> marker.user_image = request.FILES.get('user_image', None) <NEW_LINE> marker.save() <NEW_LINE> form.save_m2m() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response_data = {'detail': get_errors_form(form)['detail']} <NEW_LINE> return JsonResponse(response_data, status=400) <NEW_LINE> <DEDENT> <DEDENT> response_data = {'Success': True} <NEW_LINE> return JsonResponse(response_data) | Ajax - Save cusotm marker | 62598fadd268445f26639b6b |
class TimingRepeat(element.Element): <NEW_LINE> <INDENT> resource_type = "TimingRepeat" <NEW_LINE> def __init__(self, jsondict=None, strict=True, **kwargs): <NEW_LINE> <INDENT> self.boundsDuration = None <NEW_LINE> self.boundsPeriod = None <NEW_LINE> self.boundsRange = None <NEW_LINE> self.count = None <NEW_LINE> self.countMax = None <NEW_LINE> self.dayOfWeek = None <NEW_LINE> self.duration = None <NEW_LINE> self.durationMax = None <NEW_LINE> self.durationUnit = None <NEW_LINE> self.frequency = None <NEW_LINE> self.frequencyMax = None <NEW_LINE> self.offset = None <NEW_LINE> self.period = None <NEW_LINE> self.periodMax = None <NEW_LINE> self.periodUnit = None <NEW_LINE> self.timeOfDay = None <NEW_LINE> self.when = None <NEW_LINE> super(TimingRepeat, self).__init__(jsondict=jsondict, strict=strict, **kwargs) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(TimingRepeat, self).elementProperties() <NEW_LINE> js.extend([ ("boundsDuration", "boundsDuration", duration.Duration, False, "bounds", False), ("boundsPeriod", "boundsPeriod", period.Period, False, "bounds", False), ("boundsRange", "boundsRange", range.Range, False, "bounds", False), ("count", "count", int, False, None, False), ("countMax", "countMax", int, False, None, False), ("dayOfWeek", "dayOfWeek", str, True, None, False), ("duration", "duration", float, False, None, False), ("durationMax", "durationMax", float, False, None, False), ("durationUnit", "durationUnit", str, False, None, False), ("frequency", "frequency", int, False, None, False), ("frequencyMax", "frequencyMax", int, False, None, False), ("offset", "offset", int, False, None, False), ("period", "period", float, False, None, False), ("periodMax", "periodMax", float, False, None, False), ("periodUnit", "periodUnit", str, False, None, False), ("timeOfDay", "timeOfDay", fhirdate.FHIRDate, True, None, False), ("when", "when", str, True, None, False), ]) <NEW_LINE> return js | When the event is to occur.
A set of rules that describe when the event is scheduled. | 62598fad2c8b7c6e89bd3795 |
class LineTester(LineReceiver): <NEW_LINE> <INDENT> delimiter = b'\n' <NEW_LINE> MAX_LENGTH = 64 <NEW_LINE> def __init__(self, clock=None): <NEW_LINE> <INDENT> self.clock = clock <NEW_LINE> <DEDENT> def connectionMade(self): <NEW_LINE> <INDENT> self.received = [] <NEW_LINE> <DEDENT> def lineReceived(self, line): <NEW_LINE> <INDENT> self.received.append(line) <NEW_LINE> if line == b'': <NEW_LINE> <INDENT> self.setRawMode() <NEW_LINE> <DEDENT> elif line == b'pause': <NEW_LINE> <INDENT> self.pauseProducing() <NEW_LINE> self.clock.callLater(0, self.resumeProducing) <NEW_LINE> <DEDENT> elif line == b'rawpause': <NEW_LINE> <INDENT> self.pauseProducing() <NEW_LINE> self.setRawMode() <NEW_LINE> self.received.append(b'') <NEW_LINE> self.clock.callLater(0, self.resumeProducing) <NEW_LINE> <DEDENT> elif line == b'stop': <NEW_LINE> <INDENT> self.stopProducing() <NEW_LINE> <DEDENT> elif line[:4] == b'len ': <NEW_LINE> <INDENT> self.length = int(line[4:]) <NEW_LINE> <DEDENT> elif line.startswith(b'produce'): <NEW_LINE> <INDENT> self.transport.registerProducer(self, False) <NEW_LINE> <DEDENT> elif line.startswith(b'unproduce'): <NEW_LINE> <INDENT> self.transport.unregisterProducer() <NEW_LINE> <DEDENT> <DEDENT> def rawDataReceived(self, data): <NEW_LINE> <INDENT> data, rest = data[:self.length], data[self.length:] <NEW_LINE> self.length = self.length - len(data) <NEW_LINE> self.received[-1] = self.received[-1] + data <NEW_LINE> if self.length == 0: <NEW_LINE> <INDENT> self.setLineMode(rest) <NEW_LINE> <DEDENT> <DEDENT> def lineLengthExceeded(self, line): <NEW_LINE> <INDENT> if len(line) > self.MAX_LENGTH + 1: <NEW_LINE> <INDENT> self.setLineMode(line[self.MAX_LENGTH + 1:]) | A line receiver that parses data received and make actions on some tokens.
@type delimiter: C{bytes}
@ivar delimiter: character used between received lines.
@type MAX_LENGTH: C{int}
@ivar MAX_LENGTH: size of a line when C{lineLengthExceeded} will be called.
@type clock: L{twisted.internet.task.Clock}
@ivar clock: clock simulating reactor callLater. Pass it to constructor if
you want to use the pause/rawpause functionalities. | 62598fad45492302aabfc4a1 |
class IExternalizedObject(interface.Interface): <NEW_LINE> <INDENT> pass | A fully externalized object. | 62598fadfff4ab517ebcd7b5 |
class LoadingFailedNode: <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> self._parent = parent <NEW_LINE> self.children = [] <NEW_LINE> self.name = 'loading failed' <NEW_LINE> self.date_modified = '' <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def can_have_children(): <NEW_LINE> <INDENT> return False | A node to represent failed loading of children | 62598fad16aa5153ce4004d2 |
class Serializable(object): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> @classmethod <NEW_LINE> def deserialize(cls, state): <NEW_LINE> <INDENT> ver = state.pop('version') <NEW_LINE> assert ver == cls.VERSION <NEW_LINE> return cls(**state) <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> state = attr.asdict(self) <NEW_LINE> state['version'] = self.VERSION <NEW_LINE> return state | Base class supplying basic serialization methods and
used to mark things that are intended to be serialzable.
By serializable, we mean 'able to be rendered to dict of base types'
such that this state can be easily pickled. | 62598fad91f36d47f2230e8e |
class InformationSetting: <NEW_LINE> <INDENT> def __init__(self, spliting_factor=0.8,mode= Mode.ALL, strategy = Strategy.DISKDA): <NEW_LINE> <INDENT> self.mode = mode <NEW_LINE> self.strategy = strategy <NEW_LINE> loadService=StaticDataService() <NEW_LINE> df= loadService.df <NEW_LINE> if(mode!=Mode.ALL and spliting_factor<1 and spliting_factor>0 ): <NEW_LINE> <INDENT> train_df,test_df=loadService.splitTrainTest(spliting_factor) <NEW_LINE> if(mode==Mode.TRAIN):df=train_df <NEW_LINE> if(mode==Mode.TEST):df=test_df <NEW_LINE> <DEDENT> self.df=df <NEW_LINE> self.num_round=len(df.index) <NEW_LINE> pass <NEW_LINE> <DEDENT> def get_states(self, agent_ids, market): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_state(self, agent_id, market): <NEW_LINE> <INDENT> return self.get_states([agent_id], market)[agent_id] <NEW_LINE> <DEDENT> def getAgentQuantity(self,round,id): <NEW_LINE> <INDENT> hr_df=self.df.loc[round] <NEW_LINE> quantity=hr_df[str(id)] <NEW_LINE> return int(quantity) | Abstract information setting class.
Attributes
----------
observation_space: gym.spaces object
The specification of the observation space under this setting. | 62598fad7c178a314d78d46d |
class DecodeImg(Transform): <NEW_LINE> <INDENT> def __init__(self, mode_x='RGB', mode_y=None): <NEW_LINE> <INDENT> self.mode_x,self.mode_y = mode_x,mode_y <NEW_LINE> <DEDENT> def apply(self, x): return x.convert(self.mode_x) <NEW_LINE> def apply_image(self, y): return y.convert(self.mode_x if self.mode_y is None else self.mode_y) <NEW_LINE> def apply_mask(self, y): return y.convert('L' if self.mode_y is None else self.mode_y) | Convert regular image to RGB, masks to L mode. | 62598fad21bff66bcd722c37 |
class FiniteDimensionalAlgebraMorphism(RingHomomorphism_im_gens): <NEW_LINE> <INDENT> def __init__(self, parent, f, check=True, unitary=True): <NEW_LINE> <INDENT> A = parent.domain() <NEW_LINE> B = parent.codomain() <NEW_LINE> RingHomomorphism_im_gens.__init__(self, parent=parent, im_gens=f.rows(), check=check) <NEW_LINE> self._matrix = f <NEW_LINE> if unitary and check and (not A.is_unitary() or not B.is_unitary() or self(A.one()) != B.one()): <NEW_LINE> <INDENT> raise ValueError("homomorphism does not respect unit elements") <NEW_LINE> <DEDENT> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "Morphism from {} to {} given by matrix\n{}".format( self.domain(), self.codomain(), self._matrix) <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> x = self.domain()(x) <NEW_LINE> B = self.codomain() <NEW_LINE> return B.element_class(B, x.vector() * self._matrix) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (isinstance(other, FiniteDimensionalAlgebraMorphism) and self.parent() == other.parent() and self._matrix == other._matrix) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other <NEW_LINE> <DEDENT> def matrix(self): <NEW_LINE> <INDENT> return self._matrix <NEW_LINE> <DEDENT> def inverse_image(self, I): <NEW_LINE> <INDENT> coker_I = I.basis_matrix().transpose().kernel().basis_matrix().transpose() <NEW_LINE> return self.domain().ideal((self._matrix * coker_I).kernel().basis_matrix(), given_by_matrix=True) | Create a morphism between two :class:`finite-dimensional algebras <FiniteDimensionalAlgebra>`.
INPUT:
- ``parent`` -- the parent homset
- ``f`` -- matrix of the underlying `k`-linear map
- ``unitary`` -- boolean (default: ``True``); if ``True`` and ``check``
is also ``True``, raise a ``ValueError`` unless ``A`` and ``B`` are
unitary and ``f`` respects unit elements
- ``check`` -- boolean (default: ``True``); check whether the given
`k`-linear map really defines a (not necessarily unitary)
`k`-algebra homomorphism
The algebras ``A`` and ``B`` must be defined over the same base field.
EXAMPLES::
sage: from sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra_morphism import FiniteDimensionalAlgebraMorphism
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: H = Hom(A, B)
sage: f = H(Matrix([[1], [0]]))
sage: f.domain() is A
True
sage: f.codomain() is B
True
sage: f(A.basis()[0])
e
sage: f(A.basis()[1])
0
.. TODO:: An example illustrating unitary flag. | 62598fad1b99ca400228f518 |
class Font(ABC): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def render(self) -> Any: <NEW_LINE> <INDENT> pass | Abstract interface for an event. | 62598fadadb09d7d5dc0a55b |
class Evaluator(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def __init__(self, interpreter=None, *, initial_context: Mapping=None) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> @abc.abstractmethod <NEW_LINE> def context(self) -> Mapping: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def _evaluate_code(self, code: str, *, additional_context: Mapping=None) -> bool: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def _execute_code(self, code: str, *, additional_context: Mapping=None) -> None: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def execute_statechart(self, statechart: Statechart) -> None: <NEW_LINE> <INDENT> if statechart.preamble: <NEW_LINE> <INDENT> self._execute_code(statechart.preamble) <NEW_LINE> <DEDENT> <DEDENT> def evaluate_guard(self, transition: Transition, event: Event) -> bool: <NEW_LINE> <INDENT> if transition.guard: <NEW_LINE> <INDENT> return self._evaluate_code(transition.guard, additional_context={'event': event}) <NEW_LINE> <DEDENT> <DEDENT> def execute_action(self, transition: Transition, event: Event) -> None: <NEW_LINE> <INDENT> if transition.action: <NEW_LINE> <INDENT> self._execute_code(transition.action, additional_context={'event': event}) <NEW_LINE> <DEDENT> <DEDENT> def execute_onentry(self, state: StateMixin) -> None: <NEW_LINE> <INDENT> if getattr(state, 'on_entry', None): <NEW_LINE> <INDENT> self._execute_code(cast(ActionStateMixin, state).on_entry) <NEW_LINE> <DEDENT> <DEDENT> def execute_onexit(self, state: StateMixin) -> None: <NEW_LINE> <INDENT> if getattr(state, 'on_exit', None): <NEW_LINE> <INDENT> self._execute_code(cast(ActionStateMixin, state).on_exit) <NEW_LINE> <DEDENT> <DEDENT> def evaluate_preconditions(self, obj, event: Event=None) -> Iterator[str]: <NEW_LINE> <INDENT> event_d = {'event': event} if isinstance(obj, Transition) else None <NEW_LINE> return filter( lambda c: not self._evaluate_code(c, additional_context=event_d), getattr(obj, 'preconditions', []) ) <NEW_LINE> <DEDENT> def evaluate_invariants(self, obj, event: Event=None) -> Iterator[str]: <NEW_LINE> <INDENT> event_d = {'event': event} if isinstance(obj, Transition) else None <NEW_LINE> return filter( lambda c: not self._evaluate_code(c, additional_context=event_d), getattr(obj, 'invariants', []) ) <NEW_LINE> <DEDENT> def evaluate_postconditions(self, obj, event: Event=None) -> Iterator[str]: <NEW_LINE> <INDENT> event_d = {'event': event} if isinstance(obj, Transition) else None <NEW_LINE> return filter( lambda c: not self._evaluate_code(c, additional_context=event_d), getattr(obj, 'postconditions', []) ) | Abstract base class for any evaluator.
An instance of this class defines what can be done with piece of codes
contained in a statechart (condition, action, etc.).
Notice that the execute_* methods are called at each step, even if there is no
code to execute. This allows the evaluator to keep track of the states that are
entered or exited, and of the transitions that are processed.
:param interpreter: the interpreter that will use this evaluator,
is expected to be an *Interpreter* instance
:param initial_context: an optional dictionary to populate the context | 62598fad10dbd63aa1c70b84 |
class HuffmanTreeNode(object): <NEW_LINE> <INDENT> def __init__(self, value, possibility): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.possibility = possibility <NEW_LINE> self.left = None <NEW_LINE> self.right = None <NEW_LINE> self.Huffman = '' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'HuffmanTreeNode object, value: {v}, possibility: {p}, Huffman code: {h}' .format(v=self.value, p=self.possibility, h=self.Huffman) | 霍夫曼树结点 | 62598fadd7e4931a7ef3c067 |
class GetTaskInfoResponse(BaseFlowerClientResponse): <NEW_LINE> <INDENT> pass | A dict-like object as:
{
"root_id": "b4931472-3150-49a2-b33a-ea97d15190dd",
"result": null,
"children": [],
"uuid": "7d4d92db-39d0-4918-bd86-7ec243ba008d",
"clock": 7258101,
"exchange": null,
"routing_key": null,
"failed": null,
"state": "STARTED",
"client": null,
"parent_id": "b4931472-3150-49a2-b33a-ea97d15190dd",
"kwargs": "{'orcid': '0000-0002-2064-XXXX', 'oauth_token': 'mytoken', 'rec_id': 1261966}",
"sent": null,
"expires": null,
"parent": "b4931472-3150-49a2-b33a-ea97d15190dd",
"retries": 0,
"started": 1531321917.734636,
"timestamp": 1531321917.734636,
"args": "()",
"worker": "celery@inspire-prod-worker3-task5.cern.ch",
"rejected": null,
"name": "inspirehep.modules.orcid.tasks.orcid_push",
"received": 1531321484.761342,
"exception": null,
"revoked": null,
"succeeded": null,
"traceback": null,
"eta": null,
"retried": null,
"runtime": null,
"root": "b4931472-3150-49a2-b33a-ea97d15190dd"
} | 62598fad60cbc95b06364320 |
class Colors: <NEW_LINE> <INDENT> RED = '\x1B[38;5;196m' <NEW_LINE> GREEN = '\x1B[38;5;83m' <NEW_LINE> ORANGE = '\x1B[38;5;214m' <NEW_LINE> ENDC = '\x1B[0m' | Color enum | 62598fad55399d3f056264f5 |
class NodeServer(csi_pb2_grpc.NodeServicer): <NEW_LINE> <INDENT> def NodePublishVolume(self, request, context): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> hostvol = request.volume_context.get("hostvol", "") <NEW_LINE> pvpath = request.volume_context.get("path", "") <NEW_LINE> pvtype = request.volume_context.get("pvtype", "") <NEW_LINE> voltype = request.volume_context.get("type", "") <NEW_LINE> gserver = request.volume_context.get("gserver", None) <NEW_LINE> options = request.volume_context.get("options", None) <NEW_LINE> mntdir = os.path.join(HOSTVOL_MOUNTDIR, hostvol) <NEW_LINE> pvpath_full = os.path.join(mntdir, pvpath) <NEW_LINE> logging.debug(logf( "Received the mount request", volume=request.volume_id, voltype=voltype, hostvol=hostvol, pvpath=pvpath, pvtype=pvtype )) <NEW_LINE> if voltype == "External": <NEW_LINE> <INDENT> if pvpath == "": <NEW_LINE> <INDENT> mount_glusterfs_with_host(hostvol, request.target_path, gserver, options) <NEW_LINE> logging.debug(logf( "Mounted Volume for PV", volume=request.volume_id, mntdir=request.target_path, pvpath=gserver, options=options )) <NEW_LINE> return csi_pb2.NodePublishVolumeResponse() <NEW_LINE> <DEDENT> <DEDENT> volume = { 'name': hostvol, 'g_volname': hostvol, 'g_host': gserver, 'g_options': options, 'type': voltype, } <NEW_LINE> mount_glusterfs(volume, mntdir) <NEW_LINE> logging.debug(logf( "Mounted Hosting Volume", pv=request.volume_id, hostvol=hostvol, mntdir=mntdir, )) <NEW_LINE> mount_volume(pvpath_full, request.target_path, pvtype, fstype=None) <NEW_LINE> logging.info(logf( "Mounted PV", volume=request.volume_id, pvpath=pvpath, pvtype=pvtype, hostvol=hostvol, duration_seconds=time.time() - start_time )) <NEW_LINE> return csi_pb2.NodePublishVolumeResponse() <NEW_LINE> <DEDENT> def NodeUnpublishVolume(self, request, context): <NEW_LINE> <INDENT> logging.debug(logf( "Received the unmount request", volume=request.volume_id, )) <NEW_LINE> unmount_volume(request.target_path) <NEW_LINE> return csi_pb2.NodeUnpublishVolumeResponse() <NEW_LINE> <DEDENT> def NodeGetCapabilities(self, request, context): <NEW_LINE> <INDENT> return csi_pb2.NodeGetCapabilitiesResponse() <NEW_LINE> <DEDENT> def NodeGetInfo(self, request, context): <NEW_LINE> <INDENT> return csi_pb2.NodeGetInfoResponse( node_id=os.environ["NODE_ID"], ) | NodeServer object is responsible for handling host
volume mount and PV mounts.
Ref:https://github.com/container-storage-interface/spec/blob/master/spec.md | 62598fad99cbb53fe6830ea9 |
class InputOutput(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.reset() <NEW_LINE> <DEDENT> def get_dictionary(self): <NEW_LINE> <INDENT> return self.dictionary <NEW_LINE> <DEDENT> def set_dictionary(self, dictionary): <NEW_LINE> <INDENT> self.dictionary = dictionary <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.dictionary = {} <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.dictionary[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.dictionary[key] = value <NEW_LINE> <DEDENT> def to_string(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for i, value in self.dictionary.items(): <NEW_LINE> <INDENT> result[i] = contexts_to_standard(value) <NEW_LINE> <DEDENT> if is_empty_dictionary(result): return "{}" <NEW_LINE> return str(result) <NEW_LINE> <DEDENT> def get_senders(self): <NEW_LINE> <INDENT> return self.dictionary.keys() <NEW_LINE> <DEDENT> def get_number_of_contexts(self): <NEW_LINE> <INDENT> single_result = 0 <NEW_LINE> aggr_result = 0 <NEW_LINE> for key, values in self.dictionary.items(): <NEW_LINE> <INDENT> for value in values: <NEW_LINE> <INDENT> if value.is_single(): <NEW_LINE> <INDENT> single_result += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> aggr_result += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return single_result, aggr_result <NEW_LINE> <DEDENT> def get_in_standard_from(self): <NEW_LINE> <INDENT> results = {} <NEW_LINE> for key, value in self.dictionary.items(): <NEW_LINE> <INDENT> results[key] = contexts_to_standard(value) <NEW_LINE> <DEDENT> return results | database class | 62598fad4e4d5625663723f7 |
class UIEventSyntheticProvider(NSObject.NSObjectSyntheticProvider): <NEW_LINE> <INDENT> def __init__(self, value_obj, internal_dict): <NEW_LINE> <INDENT> super(UIEventSyntheticProvider, self).__init__(value_obj, internal_dict) <NEW_LINE> self.type_name = "UIEvent" <NEW_LINE> self.register_child_value("timestamp", ivar_name="_timestamp", primitive_value_function=SummaryBase.get_float_value, summary_function=self.get_timestamp_summary) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_timestamp_summary(value): <NEW_LINE> <INDENT> return "timeStamp={}".format(value) | Class representing UIEvent. | 62598fade76e3b2f99fd8a08 |
class IMemberSite(form.Schema): <NEW_LINE> <INDENT> pass | Schema interface for MemberSite | 62598fad8e7ae83300ee9074 |
class Song(object): <NEW_LINE> <INDENT> def __init__(self, json_dict, lyrics=''): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._body = json_dict['song'] <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self._body = json_dict <NEW_LINE> <DEDENT> self._body['lyrics'] = lyrics <NEW_LINE> self._url = self._body['url'] <NEW_LINE> self._api_path = self._body['api_path'] <NEW_LINE> self._id = self._body['id'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def title(self): <NEW_LINE> <INDENT> return str(self._body['title'].encode("utf-8", errors='ignore').decode("utf-8")) <NEW_LINE> <DEDENT> @property <NEW_LINE> def artist(self): <NEW_LINE> <INDENT> return str(self._body['primary_artist']['name'].encode("utf-8", errors='ignore').decode("utf-8")) <NEW_LINE> <DEDENT> @property <NEW_LINE> def lyrics(self): <NEW_LINE> <INDENT> return self._body['lyrics'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def album(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._body['album']['name'] <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def year(self): <NEW_LINE> <INDENT> return self._body['release_date'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self._body['url'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def album_url(self): <NEW_LINE> <INDENT> return self._body['album']['url'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def featured_artists(self): <NEW_LINE> <INDENT> return self._body['featured_artists'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def media(self): <NEW_LINE> <INDENT> m = {} <NEW_LINE> if 'media' in self._body: <NEW_LINE> <INDENT> [m.__setitem__(p['provider'], p['url']) for p in self._body['media']] <NEW_LINE> <DEDENT> return m <NEW_LINE> <DEDENT> @property <NEW_LINE> def writer_artists(self): <NEW_LINE> <INDENT> writers = [] <NEW_LINE> [writers.append((writer['name'], writer['id'], writer['url'])) for writer in self._body['writer_artists']] <NEW_LINE> return writers <NEW_LINE> <DEDENT> @property <NEW_LINE> def song_art_image_url(self): <NEW_LINE> <INDENT> return self._body['song_art_image_url'] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if len(self.lyrics) > 100: <NEW_LINE> <INDENT> lyr = self.lyrics[:100] + "..." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lyr = self.lyrics[:100] <NEW_LINE> <DEDENT> lyrics = lyr.replace('\n', '\n ') <NEW_LINE> return f'"{self.title}" by {self.artist}:\n {lyrics}' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr((self.title, self.artist)) <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> return cmp(self.title, other.title) and cmp(self.artist, other.artist) and cmp(self.lyrics, other.lyrics) | A song from the Genius.com database.
Attributes:
title: (str) Title of the song.
artist: (str) Primary artist on the song.
lyrcis: (str) Full set of song lyrics.
album: (str) Name of the album the song is on.
year: (int) Year the song was released. | 62598fad32920d7e50bc6026 |
class EditVideoSizeError(OAuthException): <NEW_LINE> <INDENT> error_code = 350 <NEW_LINE> error_id = "EDIT_VIDEO_SIZE" <NEW_LINE> error_description = 'Video file is too large' | Autogenerated exception class for API error code 350 | 62598faddd821e528d6d8f07 |
class TestObjectPropertyTypes(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 testObjectPropertyTypes(self): <NEW_LINE> <INDENT> pass | ObjectPropertyTypes unit test stubs | 62598fadeab8aa0e5d30bd5e |
class CalculateTeamScores(beam.PTransform): <NEW_LINE> <INDENT> def __init__(self, team_window_duration, allowed_lateness): <NEW_LINE> <INDENT> super(CalculateTeamScores, self).__init__() <NEW_LINE> self.team_window_duration = team_window_duration * 60 <NEW_LINE> self.allowed_lateness_sec = allowed_lateness * 60 <NEW_LINE> <DEDENT> def expand(self, pcoll): <NEW_LINE> <INDENT> return (pcoll | 'LeaderboardTeamFixedWindows' >> beam.WindowInto( beam.window.FixedWindows(self.team_window_duration), trigger=trigger.AfterWatermark( trigger.AfterCount(10), trigger.AfterCount(20)), accumulation_mode=trigger.AccumulationMode.ACCUMULATING) | 'ExtractAndSumScore' >> ExtractAndSumScore('team')) | Calculates scores for each team within the configured window duration.
Extract team/score pairs from the event stream, using hour-long windows by default. | 62598fadcc0a2c111447afe3 |
class StringPattern(Pattern): <NEW_LINE> <INDENT> def __init__(self, text, user=None): <NEW_LINE> <INDENT> Pattern.__init__(self, user) <NEW_LINE> self.text = text <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return makePrintable(self.text, 'ASCII') <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<StringPattern '%s'>" % self | Static string pattern | 62598fad2c8b7c6e89bd3797 |
class StaticFilesStorage(FileSystemStorage): <NEW_LINE> <INDENT> def __init__(self, location=None, base_url=None, *args, **kwargs): <NEW_LINE> <INDENT> if location is None: <NEW_LINE> <INDENT> location = settings.STATICFILES_ROOT <NEW_LINE> <DEDENT> if base_url is None: <NEW_LINE> <INDENT> base_url = settings.STATICFILES_URL <NEW_LINE> <DEDENT> if not location: <NEW_LINE> <INDENT> raise ImproperlyConfigured("You're using the staticfiles app " "without having set the STATICFILES_ROOT setting. Set it to " "the absolute path of the directory that holds static media.") <NEW_LINE> <DEDENT> if not base_url: <NEW_LINE> <INDENT> raise ImproperlyConfigured("You're using the staticfiles app " "without having set the STATICFILES_URL setting. Set it to " "URL that handles the files served from STATICFILES_ROOT.") <NEW_LINE> <DEDENT> if settings.DEBUG: <NEW_LINE> <INDENT> utils.check_settings() <NEW_LINE> <DEDENT> super(StaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) | Standard file system storage for site media files.
The defaults for ``location`` and ``base_url`` are
``STATICFILES_ROOT`` and ``STATICFILES_URL``. | 62598fadbaa26c4b54d4f285 |
class MainJavaLibraryComponent(JarFilesMixin, SubdirectoryComponent): <NEW_LINE> <INDENT> @property <NEW_LINE> def subdirectory(self): <NEW_LINE> <INDENT> return 'src/main/java' <NEW_LINE> <DEDENT> @property <NEW_LINE> def target_type(self): <NEW_LINE> <INDENT> return Target.java_library <NEW_LINE> <DEDENT> @property <NEW_LINE> def target_name(self): <NEW_LINE> <INDENT> return 'lib' <NEW_LINE> <DEDENT> @property <NEW_LINE> def pom_dependency_list(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def artifactId_suffix(self): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> @property <NEW_LINE> def _deps(self): <NEW_LINE> <INDENT> return self.pom.lib_deps <NEW_LINE> <DEDENT> def generate_target_arguments(self): <NEW_LINE> <INDENT> args = super(MainJavaLibraryComponent, self).generate_target_arguments() <NEW_LINE> library_deps = self._deps + [self.jar_target_spec] <NEW_LINE> module_path = os.path.dirname(self.pom.path) <NEW_LINE> if self.pom.mainclass: <NEW_LINE> <INDENT> spec_name = self.gen_context.infer_target_name(module_path, 'extra-files') <NEW_LINE> library_deps.append(self.gen_context.format_spec(path=module_path, name=spec_name)) <NEW_LINE> <DEDENT> artifactId = self.pom.deps_from_pom.artifact_id + self.artifactId_suffix <NEW_LINE> args.update({ 'sources': "rglobs('*.java')", 'dependencies': format_dependency_list(library_deps), 'resources': self.pom.resources, 'groupId': self.pom.deps_from_pom.group_id, 'artifactId': artifactId, 'platform': self.get_jvm_platform_name(), }) <NEW_LINE> return args | Generates targets for src/main/java. | 62598fadfff4ab517ebcd7b7 |
class Glimpse(CMSPlugin): <NEW_LINE> <INDENT> title = models.CharField(max_length=255, blank=True, null=True) <NEW_LINE> variant = models.CharField( _("Variant"), max_length=50, choices=GLIMPSE_VARIANTS, default=GLIMPSE_VARIANTS[0][0], blank=True, null=True, help_text=_("Form factor variant"), ) <NEW_LINE> image = FilerImageField( related_name="image", verbose_name=_("image"), on_delete=models.SET_NULL, null=True, blank=True, ) <NEW_LINE> content = models.TextField(_("Content"), null=True, blank=True, default="") <NEW_LINE> link_url = models.URLField( verbose_name=_("External URL"), blank=True, null=True, max_length=255, help_text=_("Make the glimpse as a link with an external URL."), ) <NEW_LINE> link_page = PageField( verbose_name=_("Internal URL"), blank=True, null=True, on_delete=models.SET_NULL, help_text=_("Make the glimpse as a link with an internal (page) URL."), ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return Truncator(self.title).words(6, truncate="...") <NEW_LINE> <DEDENT> def get_link(self): <NEW_LINE> <INDENT> link = None <NEW_LINE> if self.link_url: <NEW_LINE> <INDENT> link = self.link_url <NEW_LINE> <DEDENT> elif self.link_page_id: <NEW_LINE> <INDENT> link = self.link_page.get_absolute_url(language=self.language) <NEW_LINE> <DEDENT> return link <NEW_LINE> <DEDENT> def is_blank_target(self): <NEW_LINE> <INDENT> return bool(self.link_url) | Glimpse plugin model | 62598fad38b623060ffa906c |
@python_2_unicode_compatible <NEW_LINE> class GoalOption(OrderedModel): <NEW_LINE> <INDENT> goal_type = models.CharField( max_length=255, choices=GOAL_TYPES, default='services', db_index=True, ) <NEW_LINE> text = models.TextField( help_text='An option for the dropdowns in a specific ' + 'GoalSetting pageblock.') <NEW_LINE> created_at = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated_at = models.DateTimeField(auto_now=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return smart_text(self.text) | GoalSettingBlock dropdowns are populated by GoalOptions.
The contents of each GoalSettingBlock's dropdown depends on its
goal_type. | 62598fadd486a94d0ba2bfa1 |
class Questions(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'questions' <NEW_LINE> __table_args__ = {'extend_existing': True} <NEW_LINE> id = Column(BigInteger, primary_key=True) <NEW_LINE> question = Column(Text) <NEW_LINE> question_type = Column(BigInteger) <NEW_LINE> answer = Column(Text) <NEW_LINE> manually_grading = Column(Boolean, default=False) <NEW_LINE> points = Column(BigInteger) <NEW_LINE> test = relationship('QuestionsTests', cascade="all,delete", backref='questions', primaryjoin="Questions.id == QuestionsTests.question_id", uselist=False) | Keeps all questions according to all tests in the system | 62598fad4527f215b58e9eb3 |
class MemoryMeasureProcess(Process): <NEW_LINE> <INDENT> def __init__(self, process_id: int, child_connection: Connection, interval: float): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.process_id = process_id <NEW_LINE> self.interval = interval <NEW_LINE> self.connection = child_connection <NEW_LINE> self.num_measurements = 1 <NEW_LINE> self.mem_usage = get_cpu_memory(self.process_id) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.connection.send(0) <NEW_LINE> stop = False <NEW_LINE> while True: <NEW_LINE> <INDENT> self.mem_usage = max(self.mem_usage, get_cpu_memory(self.process_id)) <NEW_LINE> self.num_measurements += 1 <NEW_LINE> if stop: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> stop = self.connection.poll(self.interval) <NEW_LINE> <DEDENT> self.connection.send(self.mem_usage) <NEW_LINE> self.connection.send(self.num_measurements) | `MemoryMeasureProcess` inherits from `Process` and overwrites
its `run()` method. Used to measure the memory usage of a process | 62598fadf9cc0f698b1c52b2 |
class Room_WorldThree (Room): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> walls = [[0, 0, 20, 250, LIGHTPURPLE], [0, 350, 20, 250, LIGHTPURPLE], [780, 0, 20, 600, LIGHTPURPLE], [20, 0, 760, 20, LIGHTPURPLE], [20, 580, 760, 20, LIGHTPURPLE] ] <NEW_LINE> for item in walls: <NEW_LINE> <INDENT> wall = Wall(item[0], item[1], item[2], item[3], item[4]) <NEW_LINE> self.wall_list.add(wall) <NEW_LINE> <DEDENT> <DEDENT> def draw (self): <NEW_LINE> <INDENT> objects = [[200, 200, 40, 60, BLUE, "text here", "wow, this works!!"]] <NEW_LINE> for item in objects: <NEW_LINE> <INDENT> game_object = Object(item[0], item[1], item[2], item[3], item[4], item[5], item[6]) <NEW_LINE> self.object_list.add(game_object) <NEW_LINE> game_object.draw_hitbox(item[0], item[1], item[2], item[3]) <NEW_LINE> game_object.hit_hitbox(player.hitbox[0], player.hitbox[1], player.hitbox[2], player.hitbox[3]) <NEW_LINE> <DEDENT> sprites = [[200, 300, 20, 20, PEACH, "This is a character", "Hello!!"] ] <NEW_LINE> for item in sprites: <NEW_LINE> <INDENT> npc_Sprite = Sprite(item[0], item[1], item[2], item[3], item[4], item[5], item[6]) <NEW_LINE> self.chara_sprites.add(npc_Sprite) <NEW_LINE> npc_Sprite.draw_hitbox(item[0], item[1], item[2], item[3]) <NEW_LINE> npc_Sprite.hit_hitbox(player.hitbox[0], player.hitbox[1], player.hitbox[2], player.hitbox[3]) | This creates all the walls in room 3 | 62598fad3346ee7daa337632 |
class JalaliDatePersianNumbers(khayyam.JalaliDate): <NEW_LINE> <INDENT> def strftime(self, frmt): <NEW_LINE> <INDENT> result = _replace_if_match(frmt, '%Y', self.year) <NEW_LINE> result = _replace_if_match(result, '%y', lambda: str(self.year)[-2:]) <NEW_LINE> result = _replace_if_match(result, '%m', self.month) <NEW_LINE> result = _replace_if_match(result, '%d', self.day) <NEW_LINE> result = _replace_if_match(result, '%a', self.weekdayabbr) <NEW_LINE> result = _replace_if_match(result, '%A', self.weekdayname) <NEW_LINE> result = _replace_if_match(result, '%b', self.monthabbr) <NEW_LINE> result = _replace_if_match(result, '%B', self.monthname) <NEW_LINE> result = _replace_if_match(result, '%x', self.localformat) <NEW_LINE> result = _replace_if_match(result, '%j', self.dayofyear) <NEW_LINE> result = _replace_if_match(result, '%U', lambda: self.weekofyear(6)) <NEW_LINE> result = _replace_if_match(result, '%W', lambda: self.weekofyear(0)) <NEW_LINE> result = _replace_if_match(result, '%w', self.weekday) <NEW_LINE> result = _replace_if_match(result, '%%', '%') <NEW_LINE> return result <NEW_LINE> <DEDENT> def __add__(self, x): <NEW_LINE> <INDENT> d = super().__add__(x) <NEW_LINE> return JalaliDatePersianNumbers(d.year, d.month, d.day) | JalaliDate class with Persian numbers | 62598fad8a43f66fc4bf214f |
class Lunch(Meal): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Meal.__init__(self, 'sandwich', 'gin and tonic') <NEW_LINE> self.setName('midday meal') <NEW_LINE> <DEDENT> def setFood(self, food='sandwich'): <NEW_LINE> <INDENT> if food != 'sandwich' and food != 'omelet': <NEW_LINE> <INDENT> raise AngryChefException <NEW_LINE> Meal.setFood(self, food) | Holds the food and drink for lunch. | 62598fadaad79263cf42e7a7 |
class Solution: <NEW_LINE> <INDENT> def findNearestStore(self, stores, houses): <NEW_LINE> <INDENT> stores.sort() <NEW_LINE> print(stores) <NEW_LINE> closest = [] <NEW_LINE> for house in houses: <NEW_LINE> <INDENT> i = bisect(stores, house) <NEW_LINE> if i >= len(stores): <NEW_LINE> <INDENT> closest.append(stores[-1]) <NEW_LINE> <DEDENT> elif stores[i] == house: <NEW_LINE> <INDENT> closest.append(stores[i]) <NEW_LINE> <DEDENT> elif i > 0 and house - stores[i-1] <= stores[i] - house: <NEW_LINE> <INDENT> closest.append(stores[i-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> closest.append(stores[i]) <NEW_LINE> <DEDENT> <DEDENT> return closest | @param stores: The location of each store.
@param houses: The location of each house.
@return: The location of the nearest store to each house. | 62598fad8c0ade5d55dc367b |
class req(object): <NEW_LINE> <INDENT> def __init__(self, method, url, ver, rest, headers, fd): <NEW_LINE> <INDENT> self.method = method <NEW_LINE> self.url = url <NEW_LINE> self.ver = ver <NEW_LINE> self.rest = rest <NEW_LINE> self.headers = headers <NEW_LINE> self.bsk = socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM) <NEW_LINE> self.sk = self.bsk.makefile('rwb') <NEW_LINE> os.close(fd) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.sk.close() <NEW_LINE> self.bsk.close() <NEW_LINE> <DEDENT> def __getitem__(self, header): <NEW_LINE> <INDENT> if isinstance(header, str): <NEW_LINE> <INDENT> header = header.encode("ascii") <NEW_LINE> <DEDENT> header = header.lower() <NEW_LINE> for key, val in self.headers: <NEW_LINE> <INDENT> if key.lower() == header: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> <DEDENT> raise KeyError(header) <NEW_LINE> <DEDENT> def __contains__(self, header): <NEW_LINE> <INDENT> if isinstance(header, str): <NEW_LINE> <INDENT> header = header.encode("ascii") <NEW_LINE> <DEDENT> header = header.lower() <NEW_LINE> for key, val in self.headers: <NEW_LINE> <INDENT> if key.lower() == header: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def dup(self): <NEW_LINE> <INDENT> return req(self.method, self.url, self.ver, self.rest, self.headers, os.dup(self.bsk.fileno())) <NEW_LINE> <DEDENT> def match(self, match): <NEW_LINE> <INDENT> if isinstance(match, str): <NEW_LINE> <INDENT> match = match.encode("utf-8") <NEW_LINE> <DEDENT> if self.rest[:len(match)] == match: <NEW_LINE> <INDENT> self.rest = self.rest[len(match):] <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> def dec(b): <NEW_LINE> <INDENT> return b.decode("ascii", errors="replace") <NEW_LINE> <DEDENT> return "\"%s %s %s\"" % (dec(self.method), dec(self.url), dec(self.ver)) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, *excinfo): <NEW_LINE> <INDENT> self.sk.close() <NEW_LINE> return False | Represents a single ashd request. Normally, you would not
create instances of this class manually, but receive them from the
recvreq function.
For the abstract structure of ashd requests, please see the
ashd(7) manual page. This class provides access to the HTTP
method, raw URL, HTTP version and rest string via the `method',
`url', `ver' and `rest' variables respectively. It also implements
a dict-like interface for case-independent access to the HTTP
headers. The raw headers are available as a list of (name, value)
tuples in the `headers' variable.
For responding, the response socket is available as a standard
Python stream object in the `sk' variable. Again, see the ashd(7)
manpage for what to receive and transmit on the response socket.
Note that all request parts are stored in byte, rather than
string, form. The response socket is also opened in binary mode.
Note also that instances of this class contain a reference to the
live socket used for responding to requests, which should be
closed when you are done with the request. The socket can be
closed manually by calling the close() method on this
object. Alternatively, this class implements the resource-manager
interface, so that it can be used in `with' statements. | 62598fad55399d3f056264f7 |
class ContentConfig(BaseConfig): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> super().__init__(data) <NEW_LINE> self.modules = ModulesConfig(data.get('modules', {})) <NEW_LINE> self.python_versions = [version for version in SUPPORTED_PYTHON_VERSIONS if version in CONTROLLER_PYTHON_VERSIONS or version in self.modules.python_versions] <NEW_LINE> self.py2_support = any(version for version in self.python_versions if str_to_version(version)[0] == 2) | Configuration for all content. | 62598fad2ae34c7f260ab0b5 |
class Pylint(PylintWidget, SpyderPluginMixin): <NEW_LINE> <INDENT> CONF_SECTION = 'pylint' <NEW_LINE> CONFIGWIDGET_CLASS = PylintConfigPage <NEW_LINE> edit_goto = Signal(str, int, str) <NEW_LINE> def __init__(self, parent=None): <NEW_LINE> <INDENT> PylintWidget.__init__(self, parent=parent, max_entries=self.get_option('max_entries', 50)) <NEW_LINE> SpyderPluginMixin.__init__(self, parent) <NEW_LINE> self.initialize_plugin() <NEW_LINE> <DEDENT> def get_plugin_title(self): <NEW_LINE> <INDENT> return _("Static code analysis") <NEW_LINE> <DEDENT> def get_plugin_icon(self): <NEW_LINE> <INDENT> path = osp.join(self.PLUGIN_PATH, self.IMG_PATH) <NEW_LINE> return ima.icon('pylint', icon_path=path) <NEW_LINE> <DEDENT> def get_focus_widget(self): <NEW_LINE> <INDENT> return self.treewidget <NEW_LINE> <DEDENT> def get_plugin_actions(self): <NEW_LINE> <INDENT> history_action = create_action(self, _("History..."), None, ima.icon('history'), _("Set history maximum entries"), triggered=self.change_history_depth) <NEW_LINE> self.treewidget.common_actions += (None, history_action) <NEW_LINE> return [] <NEW_LINE> <DEDENT> def on_first_registration(self): <NEW_LINE> <INDENT> self.main.tabify_plugins(self.main.help, self) <NEW_LINE> self.dockwidget.hide() <NEW_LINE> <DEDENT> def register_plugin(self): <NEW_LINE> <INDENT> self.edit_goto.connect(self.main.editor.load) <NEW_LINE> self.redirect_stdio.connect(self.main.redirect_internalshell_stdio) <NEW_LINE> self.main.add_dockwidget(self) <NEW_LINE> pylint_act = create_action(self, _("Run static code analysis"), triggered=self.run_pylint) <NEW_LINE> pylint_act.setEnabled(PYLINT_PATH is not None) <NEW_LINE> self.register_shortcut(pylint_act, context="Pylint", name="Run analysis") <NEW_LINE> self.main.source_menu_actions += [None, pylint_act] <NEW_LINE> self.main.editor.pythonfile_dependent_actions += [pylint_act] <NEW_LINE> <DEDENT> def refresh_plugin(self): <NEW_LINE> <INDENT> self.remove_obsolete_items() <NEW_LINE> <DEDENT> def closing_plugin(self, cancelable=False): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def apply_plugin_settings(self, options): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @Slot() <NEW_LINE> def change_history_depth(self): <NEW_LINE> <INDENT> "" <NEW_LINE> depth, valid = QInputDialog.getInteger(self, _('History'), _('Maximum entries'), self.get_option('max_entries'), 10, 10000) <NEW_LINE> if valid: <NEW_LINE> <INDENT> self.set_option('max_entries', depth) <NEW_LINE> <DEDENT> <DEDENT> @Slot() <NEW_LINE> def run_pylint(self): <NEW_LINE> <INDENT> if self.get_option('save_before', True) and not self.main.editor.save(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.analyze( self.main.editor.get_current_filename() ) <NEW_LINE> <DEDENT> def analyze(self, filename): <NEW_LINE> <INDENT> if self.dockwidget and not self.ismaximized: <NEW_LINE> <INDENT> self.dockwidget.setVisible(True) <NEW_LINE> self.dockwidget.setFocus() <NEW_LINE> self.dockwidget.raise_() <NEW_LINE> <DEDENT> PylintWidget.analyze(self, filename) | Python source code analysis based on pylint | 62598fad4c3428357761a28d |
class NotifierListTestCase(test.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(NotifierListTestCase, self).setUp() <NEW_LINE> list_notifier._reset_drivers() <NEW_LINE> def mock_exception(cls, *args): <NEW_LINE> <INDENT> self.exception_count += 1 <NEW_LINE> <DEDENT> self.exception_count = 0 <NEW_LINE> list_notifier_log = logging.getLogger('nova.notifier.list_notifier') <NEW_LINE> self.stubs.Set(list_notifier_log, "exception", mock_exception) <NEW_LINE> def mock_notify(cls, *args): <NEW_LINE> <INDENT> self.notify_count += 1 <NEW_LINE> <DEDENT> self.notify_count = 0 <NEW_LINE> self.stubs.Set(nova.notifier.no_op_notifier, 'notify', mock_notify) <NEW_LINE> def mock_notify2(cls, *args): <NEW_LINE> <INDENT> raise RuntimeError("Bad notifier.") <NEW_LINE> <DEDENT> self.stubs.Set(nova.notifier.log_notifier, 'notify', mock_notify2) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> list_notifier._reset_drivers() <NEW_LINE> super(NotifierListTestCase, self).tearDown() <NEW_LINE> <DEDENT> def test_send_notifications_successfully(self): <NEW_LINE> <INDENT> self.flags(notification_driver='nova.notifier.list_notifier', list_notifier_drivers=['nova.notifier.no_op_notifier', 'nova.notifier.no_op_notifier']) <NEW_LINE> nova.notifier.api.notify('publisher_id', 'event_type', nova.notifier.api.WARN, dict(a=3)) <NEW_LINE> self.assertEqual(self.notify_count, 2) <NEW_LINE> self.assertEqual(self.exception_count, 0) <NEW_LINE> <DEDENT> def test_send_notifications_with_errors(self): <NEW_LINE> <INDENT> self.flags(notification_driver='nova.notifier.list_notifier', list_notifier_drivers=['nova.notifier.no_op_notifier', 'nova.notifier.log_notifier']) <NEW_LINE> nova.notifier.api.notify('publisher_id', 'event_type', nova.notifier.api.WARN, dict(a=3)) <NEW_LINE> self.assertEqual(self.notify_count, 1) <NEW_LINE> self.assertEqual(self.exception_count, 1) <NEW_LINE> <DEDENT> def test_when_driver_fails_to_import(self): <NEW_LINE> <INDENT> self.flags(notification_driver='nova.notifier.list_notifier', list_notifier_drivers=['nova.notifier.no_op_notifier', 'nova.notifier.logo_notifier', 'fdsjgsdfhjkhgsfkj']) <NEW_LINE> nova.notifier.api.notify('publisher_id', 'event_type', nova.notifier.api.WARN, dict(a=3)) <NEW_LINE> self.assertEqual(self.exception_count, 2) <NEW_LINE> self.assertEqual(self.notify_count, 1) | Test case for notifications | 62598fad63b5f9789fe8513a |
class NodeView(core.NodeViewBase, Node): <NEW_LINE> <INDENT> side_comment = core.DelegatedAttribute( 'side_comment', 'parent', descriptor = Node.side_comment, default_value_list = (None,) ) <NEW_LINE> comment = core.DelegatedAttribute( 'comment', 'parent', descriptor = Node.comment, default_value_list = (None,) ) | This class is the C implementation of :class:`~brownbat.core.NodeViewBase` class.
| 62598fad30dc7b766599f821 |
class Dumper(yaml.SafeDumper): <NEW_LINE> <INDENT> def represent_mapping( self, tag: str, mapping: OrderedDict, flow_style: None = None ) -> MappingNode: <NEW_LINE> <INDENT> value = [] <NEW_LINE> node = yaml.MappingNode(tag, value, flow_style=flow_style) <NEW_LINE> if self.alias_key is not None: <NEW_LINE> <INDENT> self.represented_objects[self.alias_key] = node <NEW_LINE> <DEDENT> best_style = False <NEW_LINE> if hasattr(mapping, "items"): <NEW_LINE> <INDENT> mapping = mapping.items() <NEW_LINE> <DEDENT> for item_key, item_value in mapping: <NEW_LINE> <INDENT> node_key = self.represent_data(item_key) <NEW_LINE> node_value = self.represent_data(item_value) <NEW_LINE> if not (isinstance(node_key, yaml.ScalarNode) and not node_key.style): <NEW_LINE> <INDENT> best_style = False <NEW_LINE> <DEDENT> if not (isinstance(node_value, yaml.ScalarNode) and not node_value.style): <NEW_LINE> <INDENT> best_style = False <NEW_LINE> <DEDENT> value.append((node_key, node_value)) <NEW_LINE> <DEDENT> if flow_style is None: <NEW_LINE> <INDENT> if self.default_flow_style is not None: <NEW_LINE> <INDENT> node.flow_style = self.default_flow_style <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node.flow_style = best_style <NEW_LINE> <DEDENT> <DEDENT> return node <NEW_LINE> <DEDENT> def represent_list(self, data): <NEW_LINE> <INDENT> node = super().represent_list(data) <NEW_LINE> length = len(data) <NEW_LINE> if self.default_flow_style is None and length < 4: <NEW_LINE> <INDENT> node.flow_style = True <NEW_LINE> <DEDENT> elif self.default_flow_style is None: <NEW_LINE> <INDENT> node.flow_style = False <NEW_LINE> <DEDENT> return node <NEW_LINE> <DEDENT> def represent_bool(self, data): <NEW_LINE> <INDENT> if data: <NEW_LINE> <INDENT> value = "yes" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = "no" <NEW_LINE> <DEDENT> return self.represent_scalar("tag:yaml.org,2002:bool", value) <NEW_LINE> <DEDENT> def represent_none(self, data): <NEW_LINE> <INDENT> return self.represent_scalar("tag:yaml.org,2002:null", "") | A PyYAML Dumper that represents OrderedDicts as ordinary mappings
(in order, of course). | 62598fad283ffb24f3cf3860 |
class AdmWebPage(QWebEnginePage): <NEW_LINE> <INDENT> def __init__(self, config, parent=None, profile=None, debug=None): <NEW_LINE> <INDENT> self.debug = debug or (lambda x: None) <NEW_LINE> self.config = config <NEW_LINE> if not profile: <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super().__init__(profile, parent) <NEW_LINE> <DEDENT> debug(f"Profile is: {self.profile()}") <NEW_LINE> <DEDENT> def javaScriptConsoleMessage(self, level, message, line, sourceid): <NEW_LINE> <INDENT> self.debug(f'Javascript Error in "{sourceid}" line {line}: {message}') <NEW_LINE> <DEDENT> def javaScriptConfirm(self, frame, msg): <NEW_LINE> <INDENT> if self.config.force_js_confirm == "accept": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.config.force_js_confirm == "deny": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super().javaScriptConfirm(self, frame, msg) <NEW_LINE> <DEDENT> <DEDENT> def javaScriptAlert(self, frame, msg): <NEW_LINE> <INDENT> if not self.config.suppress_alerts: <NEW_LINE> <INDENT> return super().javaScriptAlert(self, frame, msg) <NEW_LINE> <DEDENT> <DEDENT> def certificateError(self, error): <NEW_LINE> <INDENT> self.debug("certificate error") <NEW_LINE> if self.config.ssl_mode == 'ignore': <NEW_LINE> <INDENT> self.debug("Certificate error ignored") <NEW_LINE> self.debug(error.errorDescription()) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.setHtml( msg.CERTIFICATE_ERROR.format( url=error.url().toString(), start_url=self.config.start_url )) <NEW_LINE> <DEDENT> <DEDENT> def renderProcessTerminated(self, *args): <NEW_LINE> <INDENT> self.debug("RenderProcessTerminated: {}".format(args)) <NEW_LINE> super().renderProcessTerminated(args) | Subclassed QWebEnginePage,
representing the actual web page object in the browser.
This was subclassed so that some functions can be overridden. | 62598fade76e3b2f99fd8a0a |
class modelBase: <NEW_LINE> <INDENT> def __init__(self,dimensions,w0): <NEW_LINE> <INDENT> self.w=w0 <NEW_LINE> self.dim=len(w0) <NEW_LINE> self.dimensions=dimensions <NEW_LINE> self.signal=[0 for i in range(dimensions[1])] <NEW_LINE> self.dsdw=[0 for i in range(dimensions[1])] <NEW_LINE> self.input=[0 for i in range(dimensions[0])] <NEW_LINE> <DEDENT> def setInput(self,x): <NEW_LINE> <INDENT> self.input=x <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def derivative_w(self,i): <NEW_LINE> <INDENT> pass | This is the base class for the function. The key point is to have way to update the parameters w. | 62598faddd821e528d6d8f09 |
class MeasureGroup(backboneelement.BackboneElement): <NEW_LINE> <INDENT> resource_type = Field("MeasureGroup", const=True) <NEW_LINE> code: fhirtypes.CodeableConceptType = Field( None, alias="code", title="Meaning of the group", description=( "Indicates a meaning for the group. This can be as simple as a unique " "identifier, or it can establish meaning in a broader context by " "drawing from a terminology, allowing groups to be correlated across " "measures." ), element_property=True, ) <NEW_LINE> description: fhirtypes.String = Field( None, alias="description", title="Summary description", description="The human readable description of this population group.", element_property=True, ) <NEW_LINE> description__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_description", title="Extension field for ``description``." ) <NEW_LINE> population: typing.List[fhirtypes.MeasureGroupPopulationType] = Field( None, alias="population", title="Population criteria", description="A population criteria for the measure.", element_property=True, ) <NEW_LINE> stratifier: typing.List[fhirtypes.MeasureGroupStratifierType] = Field( None, alias="stratifier", title="Stratifier criteria for the measure", description=( "The stratifier criteria for the measure report, specified as either " "the name of a valid CQL expression defined within a referenced library" " or a valid FHIR Resource Path." ), element_property=True, ) <NEW_LINE> @classmethod <NEW_LINE> def elements_sequence(cls): <NEW_LINE> <INDENT> return [ "id", "extension", "modifierExtension", "code", "description", "population", "stratifier", ] | Disclaimer: Any field name ends with ``__ext`` doesn't part of
Resource StructureDefinition, instead used to enable Extensibility feature
for FHIR Primitive Data Types.
Population criteria group.
A group of population criteria for the measure. | 62598fad7b25080760ed7483 |
class CVSDiffParser(DiffParser): <NEW_LINE> <INDENT> regex_small = re.compile('^RCS file: (.+)$') <NEW_LINE> def __init__(self, data, repo): <NEW_LINE> <INDENT> DiffParser.__init__(self, data) <NEW_LINE> self.regex_full = re.compile('^RCS file: %s/(.*),v$' % re.escape(repo)) <NEW_LINE> <DEDENT> def parse_special_header(self, linenum, info): <NEW_LINE> <INDENT> linenum = super(CVSDiffParser, self).parse_special_header(linenum, info) <NEW_LINE> if 'index' not in info: <NEW_LINE> <INDENT> return linenum <NEW_LINE> <DEDENT> m = self.regex_full.match(self.lines[linenum]) <NEW_LINE> if not m: <NEW_LINE> <INDENT> m = self.regex_small.match(self.lines[linenum]) <NEW_LINE> <DEDENT> if m: <NEW_LINE> <INDENT> info['filename'] = m.group(1) <NEW_LINE> linenum += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise DiffParserError('Unable to find RCS line', linenum) <NEW_LINE> <DEDENT> while self.lines[linenum].startswith('retrieving '): <NEW_LINE> <INDENT> linenum += 1 <NEW_LINE> <DEDENT> if self.lines[linenum].startswith('diff '): <NEW_LINE> <INDENT> linenum += 1 <NEW_LINE> <DEDENT> return linenum <NEW_LINE> <DEDENT> def parse_diff_header(self, linenum, info): <NEW_LINE> <INDENT> linenum = super(CVSDiffParser, self).parse_diff_header(linenum, info) <NEW_LINE> if info.get('origFile') == '/dev/null': <NEW_LINE> <INDENT> info['origFile'] = info['newFile'] <NEW_LINE> info['origInfo'] = 'PRE-CREATION' <NEW_LINE> <DEDENT> elif 'filename' in info: <NEW_LINE> <INDENT> info['origFile'] = info['filename'] <NEW_LINE> <DEDENT> return linenum | This class is able to parse diffs created with CVS. | 62598fadcc0a2c111447afe5 |
class AuthFailedException(PickupGitException): <NEW_LINE> <INDENT> pass | Base class for Auth Failed exceptions | 62598fad7b180e01f3e4903a |
class InvalidPassword(Exception): <NEW_LINE> <INDENT> pass | Exception used for invalid password. | 62598fad498bea3a75a57af2 |
class RSAPublicKey(CompositeType): <NEW_LINE> <INDENT> def __init__(self, readLen): <NEW_LINE> <INDENT> CompositeType.__init__(self, readLen = readLen) <NEW_LINE> self.magic = UInt32Le(0x31415352, constant = True) <NEW_LINE> self.keylen = UInt32Le(lambda:(sizeof(self.modulus) + sizeof(self.padding))) <NEW_LINE> self.bitlen = UInt32Le(lambda:((self.keylen.value - 8) * 8)) <NEW_LINE> self.datalen = UInt32Le(lambda:((self.bitlen.value / 8) - 1)) <NEW_LINE> self.pubExp = UInt32Le() <NEW_LINE> self.modulus = String(readLen = UInt16Le(lambda:(self.keylen.value - 8))) <NEW_LINE> self.padding = String("\x00" * 8, readLen = UInt8(8)) | @see: http://msdn.microsoft.com/en-us/library/cc240520.aspx | 62598fad91f36d47f2230e90 |
class AdminPostForm(PostForm): <NEW_LINE> <INDENT> login = forms.CharField(widget=forms.HiddenInput()) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> kwargs.update(dict(zip(inspect.getargspec(forms.ModelForm.__init__)[0][1:], args))) <NEW_LINE> <DEDENT> if 'instance' in kwargs and kwargs['instance']: <NEW_LINE> <INDENT> kwargs.setdefault('initial', {}).update({'login': getattr(kwargs['instance'].user, username_field)}) <NEW_LINE> <DEDENT> super(AdminPostForm, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.user = User.objects.filter(**{username_field: self.cleaned_data['login']}).get() <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> if username_field != 'email': <NEW_LINE> <INDENT> create_data = {username_field: self.cleaned_data['login'], 'email': '%s@example.com' % self.cleaned_data['login']} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> create_data = {'email': '%s@example.com' % self.cleaned_data['login']} <NEW_LINE> <DEDENT> self.user = User.objects.create(**create_data) <NEW_LINE> <DEDENT> return super(AdminPostForm, self).save(*args, **kwargs) | Superusers can post messages from any user and from any time
If no user with specified name - new user will be created | 62598fad4428ac0f6e6584f9 |
class ListIdentifiers(OAI_PMH): <NEW_LINE> <INDENT> def __init__(self, base_url, from_date=None, until_date=None, oai_set=None, metadata_prefix=None): <NEW_LINE> <INDENT> super(ListIdentifiers, self).__init__(base_url) <NEW_LINE> self.verb = "ListIdentifiers" <NEW_LINE> self.from_date = from_date <NEW_LINE> self.until_date = until_date <NEW_LINE> self.oai_set = oai_set <NEW_LINE> self.metadata_prefix = metadata_prefix <NEW_LINE> self.records = [] <NEW_LINE> self.resumption = None <NEW_LINE> <DEDENT> def set_resumption(self, resumption_token, complete_list_size=None, cursor=None, expiry=-1): <NEW_LINE> <INDENT> self.resumption = {"resumption_token" : resumption_token, "expiry" : expiry} <NEW_LINE> if complete_list_size is not None: <NEW_LINE> <INDENT> self.resumption["complete_list_size"] = complete_list_size <NEW_LINE> <DEDENT> if cursor is not None: <NEW_LINE> <INDENT> self.resumption["cursor"] = cursor <NEW_LINE> <DEDENT> <DEDENT> def add_record(self, header): <NEW_LINE> <INDENT> self.records.append(header) <NEW_LINE> <DEDENT> def add_request_attributes(self, element): <NEW_LINE> <INDENT> if self.from_date is not None: <NEW_LINE> <INDENT> element.set("from", self.from_date) <NEW_LINE> <DEDENT> if self.until_date is not None: <NEW_LINE> <INDENT> element.set("until", self.until_date) <NEW_LINE> <DEDENT> if self.oai_set is not None: <NEW_LINE> <INDENT> element.set("set", self.oai_set) <NEW_LINE> <DEDENT> if self.metadata_prefix is not None: <NEW_LINE> <INDENT> element.set("metadataPrefix", self.metadata_prefix) <NEW_LINE> <DEDENT> <DEDENT> def get_element(self): <NEW_LINE> <INDENT> lr = etree.Element(self.PMH + "ListIdentifiers", nsmap=self.NSMAP) <NEW_LINE> for header in self.records: <NEW_LINE> <INDENT> lr.append(header) <NEW_LINE> <DEDENT> if self.resumption is not None: <NEW_LINE> <INDENT> rt = etree.SubElement(lr, self.PMH + "resumptionToken") <NEW_LINE> if "complete_list_size" in self.resumption: <NEW_LINE> <INDENT> rt.set("completeListSize", str(self.resumption.get("complete_list_size"))) <NEW_LINE> <DEDENT> if "cursor" in self.resumption: <NEW_LINE> <INDENT> rt.set("cursor", str(self.resumption.get("cursor"))) <NEW_LINE> <DEDENT> expiry = self.resumption.get("expiry", -1) <NEW_LINE> expire_date = None <NEW_LINE> if expiry >= 0: <NEW_LINE> <INDENT> expire_date = oaitools.DateFormat.format(datetime.now() + timedelta(0, expiry)) <NEW_LINE> rt.set("expirationDate", expire_date) <NEW_LINE> <DEDENT> rt.text = self.resumption.get("resumption_token") <NEW_LINE> <DEDENT> return lr | Serialisable object representing a ListIdentifiers response | 62598fad5fdd1c0f98e5df61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.