code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
class Thing(JsonObject): <NEW_LINE> <INDENT> def __init__(self, _dict: Dict[str, Any]): <NEW_LINE> <INDENT> self.id = None <NEW_LINE> self.thumbnail = None <NEW_LINE> self.name = None <NEW_LINE> self.url = None <NEW_LINE> self.description = None <NEW_LINE> super().__init__(_dict)
|
Class representing a thing.
|
62599012d18da76e235b77ac
|
class tag_embedded(EmbeddedDocument): <NEW_LINE> <INDENT> tagsDoc = ListField(StringField(min_length=0,max_length=30, regex='^[A-ZÁÉÍÓÚÑÜ][a-z A-Z À-ÿ / & ,]*[a-záéíóúñü]$'), required=False, max_length=10) <NEW_LINE> def to_json(self): <NEW_LINE> <INDENT> return self.tagsDoc
|
EmbeddedDocument Class for Tags.
This embedded document makes sure that the values of each tag follow the regex pattern in the database.
List of attributes:
- tagsDoc: <List> All the tags belonging to a document.
Methods
-------
to_json()
Returns the json equivalent of the object.
|
62599012bf627c535bcb216e
|
class ColorInputField(InputField): <NEW_LINE> <INDENT> def __init__(self, id, value): <NEW_LINE> <INDENT> super(ColorInputField, self).__init__(id, value) <NEW_LINE> self.html_script = '%s=%s' % (IsSafari() and not IsMobile() and 'onclick' or 'onchange', '"ralStep(\'%s\', this.value, 0);"' % id) <NEW_LINE> self.default_tag = 'ral-color' <NEW_LINE> <DEDENT> def is_implemented(self): <NEW_LINE> <INDENT> if IsIE() and float(BrowserVersion()) < 9: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def set_value(self, value, **kw): <NEW_LINE> <INDENT> super(ColorInputField, self).set_value(value, **kw) <NEW_LINE> if not value: <NEW_LINE> <INDENT> self.current_value = None <NEW_LINE> <DEDENT> self.html_min = 0 <NEW_LINE> self.html_max = 9999 <NEW_LINE> self.html_step = 1 <NEW_LINE> <DEDENT> def html(self, tag=None): <NEW_LINE> <INDENT> tag_mapping = { 'title' : 'title-div', 'content' : IsFirefox() and ('ral-color-calc',) or ('ral-color',), } <NEW_LINE> return super(ColorInputField, self).html(tag in tag_mapping and tag_mapping[tag] or tag)
|
Поле ввода кода RAL (цвет)
|
625990125166f23b2e24408f
|
class Bounds(SlaveAllocatorTestMixin, unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> return super(Bounds, self).setUp(slaves=10, maxRequestsPerSec=1) <NEW_LINE> <DEDENT> def test_LowerBounds(self): <NEW_LINE> <INDENT> deferredList = [] <NEW_LINE> for i in range(1, 11): <NEW_LINE> <INDENT> jobSpec = self.createJobSpec() <NEW_LINE> jobSpec.clientFunction = "%d" % i <NEW_LINE> deferred = self.sa.allocate(jobSpec) <NEW_LINE> deferred.addCallback(self.checkAllocationLength, i) <NEW_LINE> deferredList.append(deferred) <NEW_LINE> <DEDENT> return DeferredList(deferredList)
|
Allocation boundary checks.
|
6259901221a7993f00c66c3a
|
class DynamicsInterfaceInferer(ComponentClassInterfaceInferer, BaseDynamicsVisitor): <NEW_LINE> <INDENT> def __init__(self, dynamics): <NEW_LINE> <INDENT> self.state_variable_names = set() <NEW_LINE> super(DynamicsInterfaceInferer, self).__init__(dynamics) <NEW_LINE> <DEDENT> def action_statevariable(self, state_variable, **kwargs): <NEW_LINE> <INDENT> self.declared_symbols.add(state_variable.name) <NEW_LINE> <DEDENT> def action_outputevent(self, event_out, **kwargs): <NEW_LINE> <INDENT> self.event_out_port_names.add(event_out.port_name) <NEW_LINE> <DEDENT> def action_onevent(self, on_event, **kwargs): <NEW_LINE> <INDENT> self.input_event_port_names.add(on_event.src_port_name) <NEW_LINE> <DEDENT> def action_analogreceiveport(self, analog_receive_port, **kwargs): <NEW_LINE> <INDENT> self.declared_symbols.add(analog_receive_port.name) <NEW_LINE> <DEDENT> def action_analogreduceport(self, analog_reduce_port, **kwargs): <NEW_LINE> <INDENT> self.declared_symbols.add(analog_reduce_port.name) <NEW_LINE> <DEDENT> def action_stateassignment(self, assignment, **kwargs): <NEW_LINE> <INDENT> inferred_sv = assignment.lhs <NEW_LINE> self.declared_symbols.add(inferred_sv) <NEW_LINE> self.state_variable_names.add(inferred_sv) <NEW_LINE> self.atoms.update(assignment.rhs_atoms) <NEW_LINE> <DEDENT> def action_timederivative(self, time_derivative, **kwargs): <NEW_LINE> <INDENT> inferred_sv = time_derivative.variable <NEW_LINE> self.state_variable_names.add(inferred_sv) <NEW_LINE> self.declared_symbols.add(inferred_sv) <NEW_LINE> self.atoms.update(time_derivative.rhs_atoms) <NEW_LINE> <DEDENT> def action_trigger(self, trigger, **kwargs): <NEW_LINE> <INDENT> self.atoms.update(trigger.rhs_atoms)
|
Used to infer output |EventPorts|, |StateVariables| & |Parameters|.
|
6259901215fb5d323ce7f9fd
|
class ProcessHandle(object): <NEW_LINE> <INDENT> def __init__(self, handle, kind): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_output(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def finished(self): <NEW_LINE> <INDENT> raise NotImplementedError
|
ProcessHandle is a superclass for what a handle to a process
should include. Examples of processes are SLURM scripts or
running straight on the command line.
Each subclass of ProcessHandle should be able to provide a single
handle, and describe what kind of handle it is. The subclass
must also be able to get the output, which will always be a blocking
call, and tell if the process has finished, which will never be blocking
|
625990128c3a8732951f7224
|
class CmdlineParser(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.port = DEFAULT_PORT <NEW_LINE> self.autosave_directory = DEFAULT_AUTOSAVE_DIRECTORY <NEW_LINE> self.autosave_interval = DEFAULT_AUTOSAVE_INTERVAL <NEW_LINE> self.save_hook = None <NEW_LINE> <DEDENT> def parse(self): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description=_("Server for Cournal."), epilog=_("e.g.: %(prog)s -p port")) <NEW_LINE> parser.add_argument("-p", "--port", nargs=1, type=int, default=[self.port], help=_("Port to listen on")) <NEW_LINE> parser.add_argument("-s", "--autosave-directory", nargs=1, default=[self.autosave_directory], help=_("The directory within which to store the documents on the server.")) <NEW_LINE> parser.add_argument("-i", "--autosave-interval", nargs=1, type=int, default=[self.autosave_interval], help=_("Interval in seconds within which to save modified documents to permanent storage. Set to 0 to disable autosave.")) <NEW_LINE> parser.add_argument("-k", "--save-hook", nargs=1, help=_("Script or application to execute after all documents were saved. The first argument is the autosave directory, followed by all filenames of files that were changed.")) <NEW_LINE> parser.add_argument("-v", "--version", action="version", version="%(prog)s " + cournal_version) <NEW_LINE> args = parser.parse_args() <NEW_LINE> self.port = args.port[0] <NEW_LINE> self.autosave_directory = args.autosave_directory[0] <NEW_LINE> self.autosave_interval = args.autosave_interval[0] <NEW_LINE> if args.save_hook: <NEW_LINE> <INDENT> self.save_hook = args.save_hook[0] <NEW_LINE> <DEDENT> return self
|
Parse commandline options. Results are available as attributes of this class
|
6259901215fb5d323ce7f9ff
|
class Service(): <NEW_LINE> <INDENT> def get_configuration(self, node_fqdn): <NEW_LINE> <INDENT> node = utils.get_or_create_node(node_fqdn) <NEW_LINE> all_role_assignments = node.get_role_assignments() <NEW_LINE> config_classes = get_config_classes(all_role_assignments) <NEW_LINE> settings = get_default_settings(config_classes) <NEW_LINE> if node.get_group(): <NEW_LINE> <INDENT> override_defaults(settings, node.get_group_overrides()) <NEW_LINE> <DEDENT> override_defaults(settings, node.get_overrides()) <NEW_LINE> running_services = filter_enabled_services(all_role_assignments) <NEW_LINE> settings['VPX_TAGS'] = str(running_services)[1:-1] <NEW_LINE> stopped_services = managed_services - set(running_services) <NEW_LINE> running_services.sort() <NEW_LINE> stopped_services = list(stopped_services) <NEW_LINE> stopped_services.sort() <NEW_LINE> c = Context({'classes': frozenset(config_classes), 'running_services': running_services, 'stopped_services': stopped_services, 'settings': settings}) <NEW_LINE> return "%s" % loader.get_template("core/recipes.yaml").render(c)
|
Service used by the Puppet External Node Classifier
|
62599012d164cc6175821c40
|
class OptimizedCachedRequireJsStorage(OptimizedFilesMixin, PipelineForgivingStorage): <NEW_LINE> <INDENT> pass
|
Custom storage backend that is used by Django-require.
|
62599012bf627c535bcb2174
|
class HitAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> form = HitAdminForm <NEW_LINE> list_display = ('src_path', 'event_type', 'yara_tags', 'vTotal', 'filesize', 'short_fileType', 'watcher', 'wasSeenBefore', 'is_malicious', 'created') <NEW_LINE> list_filter = ('is_malicious', 'watcher__server_name', 'event_type', 'fileExtension', 'wasSeenBefore', 'created') <NEW_LINE> readonly_fields = ( 'matched_files', 'is_malicious', 'wasSeenBefore', 'emailWasSent') <NEW_LINE> search_fields = ('src_path', 'md5sum', 'sha256sum', 'fileType', 'fileContent') <NEW_LINE> ordering = ['-created']
|
Admin View for Hit
|
625990126fece00bbaccc67a
|
class RdioOAuth1(BaseRdio, BaseOAuth1): <NEW_LINE> <INDENT> name = 'rdio-oauth1' <NEW_LINE> REQUEST_TOKEN_URL = 'http://api.rdio.com/oauth/request_token' <NEW_LINE> AUTHORIZATION_URL = 'https://www.rdio.com/oauth/authorize' <NEW_LINE> ACCESS_TOKEN_URL = 'http://api.rdio.com/oauth/access_token' <NEW_LINE> EXTRA_DATA = [ ('key', 'rdio_id'), ('icon', 'rdio_icon_url'), ('url', 'rdio_profile_url'), ('username', 'rdio_username'), ('streamRegion', 'rdio_stream_region'), ] <NEW_LINE> def user_data(self, access_token, *args, **kwargs): <NEW_LINE> <INDENT> params = {'method': 'currentUser', 'extras': 'username,displayName,streamRegion'} <NEW_LINE> request = self.oauth_request(access_token, RDIO_API, params, method='POST') <NEW_LINE> return self.get_json(request.url, method='POST', data=request.to_postdata())['result']
|
Rdio OAuth authentication backend
|
62599012be8e80087fbbfd38
|
class LayoutCell(object): <NEW_LINE> <INDENT> @property <NEW_LINE> def pos(self): <NEW_LINE> <INDENT> raise NotImplementedError("pos property has to be overridden") <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> raise NotImplementedError("size property has to be overridden")
|
Base Layout Cell.
Not to be used directly. Usually subclasses of this class are returned by layouts.
Instances can be passed to Widgets as the ``pos`` argument. The ``size`` argument will
be automatically overridden.
Note that manually setting ``size`` will override the size set by the layout cell,
though the position will be kept.
|
62599012bf627c535bcb2178
|
class OriginDeleteView(PermissionRequiredMixin, DeleteView): <NEW_LINE> <INDENT> model = Origin <NEW_LINE> permission_required = ('origins.delete_origin', ) <NEW_LINE> success_url = reverse_lazy('origins:origin_list')
|
Removes an origin permanantly.
Removing an origin may have strange effects on characters with that origin.
|
6259901256b00c62f0fb3586
|
class TemplatedPAComponentUpdateParameters(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 { 'parent_template_id': (str,), 'description': (str,), 'component_data': (PAComponentData,), } <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def discriminator(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attribute_map = { 'parent_template_id': 'parentTemplateId', 'description': 'description', 'component_data': 'componentData', } <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.
|
62599012925a0f43d25e8d08
|
class OctagonTarget(PolygonTarget): <NEW_LINE> <INDENT> def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> super(OctagonTarget, self).__init__(n=8, *args, **kwds)
|
A target in the form of a 8-sided polygon.
|
625990126fece00bbaccc67e
|
class UnaryOp(Node): <NEW_LINE> <INDENT> __slots__ = 'op', 'right_node'
|
A unary operation (e.g. ``-x``, ``not x``).
Attributes:
op: the operator (an enum from ``Node.OPS``).
right_node: the operand at the right of the operator.
|
62599012462c4b4f79dbc6d1
|
class Target(object): <NEW_LINE> <INDENT> def __init__(self,host,port): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port
|
Contains hostname, portnumber and a dict
of protocols that should be enabled/disabled.
|
62599012be8e80087fbbfd3a
|
class BiosVfNUMAOptimized(ManagedObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> ManagedObject.__init__(self, "BiosVfNUMAOptimized") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def class_id(): <NEW_LINE> <INDENT> return "biosVfNUMAOptimized" <NEW_LINE> <DEDENT> DN = "Dn" <NEW_LINE> RN = "Rn" <NEW_LINE> STATUS = "Status" <NEW_LINE> VP_NUMAOPTIMIZED = "VpNUMAOptimized" <NEW_LINE> CONST_VP_NUMAOPTIMIZED_DISABLED = "Disabled" <NEW_LINE> CONST_VP_NUMAOPTIMIZED_ENABLED = "Enabled" <NEW_LINE> CONST__VP_NUMAOPTIMIZED_DISABLED = "disabled" <NEW_LINE> CONST__VP_NUMAOPTIMIZED_ENABLED = "enabled" <NEW_LINE> CONST_VP_NUMAOPTIMIZED_PLATFORM_DEFAULT = "platform-default"
|
This class contains the relevant properties and constant supported by this MO.
|
62599012925a0f43d25e8d0a
|
class PelotonWorkoutAchievement(PelotonObject): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.slug = kwargs.get('slug') <NEW_LINE> self.description = kwargs.get('description') <NEW_LINE> self.image_url = kwargs.get('image_url') <NEW_LINE> self.id = kwargs.get('id') <NEW_LINE> self.name = kwargs.get('name')
|
Class that represents a single achievement that a user
earned during the workout
|
625990120a366e3fb87dd6bd
|
class GenericParser(object): <NEW_LINE> <INDENT> def __init__(self, filename, parser, mime, backup, is_writable, **kwargs): <NEW_LINE> <INDENT> self.filename = '' <NEW_LINE> self.parser = parser <NEW_LINE> self.mime = mime <NEW_LINE> self.backup = backup <NEW_LINE> self.is_writable = is_writable <NEW_LINE> self.editor = hachoir_editor.createEditor(parser) <NEW_LINE> try: <NEW_LINE> <INDENT> self.filename = hachoir_core.cmd_line.unicodeFilename(filename) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> <DEDENT> self.basename = os.path.basename(filename) <NEW_LINE> self.output = hachoir_core.cmd_line.unicodeFilename(tempfile.mkstemp()[1]) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if os.path.exists(self.output): <NEW_LINE> <INDENT> mat.secure_remove(self.output) <NEW_LINE> <DEDENT> <DEDENT> def is_clean(self): <NEW_LINE> <INDENT> for field in self.editor: <NEW_LINE> <INDENT> if self._should_remove(field): <NEW_LINE> <INDENT> return self._is_clean(self.editor) <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def _is_clean(self, fieldset): <NEW_LINE> <INDENT> for field in fieldset: <NEW_LINE> <INDENT> remove = self._should_remove(field) <NEW_LINE> if remove is True: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if remove is FIELD: <NEW_LINE> <INDENT> if not self._is_clean(field): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def remove_all(self): <NEW_LINE> <INDENT> state = self._remove_all(self.editor) <NEW_LINE> hachoir_core.field.writeIntoFile(self.editor, self.output) <NEW_LINE> self.do_backup() <NEW_LINE> return state <NEW_LINE> <DEDENT> def _remove_all(self, fieldset): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for field in fieldset: <NEW_LINE> <INDENT> remove = self._should_remove(field) <NEW_LINE> if remove is True: <NEW_LINE> <INDENT> self._remove(fieldset, field.name) <NEW_LINE> <DEDENT> if remove is FIELD: <NEW_LINE> <INDENT> self._remove_all(field) <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def _remove(self, fieldset, field): <NEW_LINE> <INDENT> del fieldset[field] <NEW_LINE> <DEDENT> def get_meta(self): <NEW_LINE> <INDENT> metadata = {} <NEW_LINE> self._get_meta(self.editor, metadata) <NEW_LINE> return metadata <NEW_LINE> <DEDENT> def _get_meta(self, fieldset, metadata): <NEW_LINE> <INDENT> for field in fieldset: <NEW_LINE> <INDENT> remove = self._should_remove(field) <NEW_LINE> if remove: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> metadata[field.name] = field.value <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> metadata[field.name] = 'harmful content' <NEW_LINE> <DEDENT> <DEDENT> if remove is FIELD: <NEW_LINE> <INDENT> self._get_meta(field, None) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _should_remove(self, key): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def create_backup_copy(self): <NEW_LINE> <INDENT> shutil.copy2(self.filename, self.filename + '.bak') <NEW_LINE> <DEDENT> def do_backup(self): <NEW_LINE> <INDENT> if self.backup: <NEW_LINE> <INDENT> shutil.move(self.filename, self.filename + '.bak') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mat.secure_remove(self.filename) <NEW_LINE> <DEDENT> shutil.move(self.output, self.filename)
|
Parent class of all parsers
|
62599012462c4b4f79dbc6d3
|
class TitleRule(HeadingRule): <NEW_LINE> <INDENT> type = 'title' <NEW_LINE> first = True <NEW_LINE> def condition(self, block): <NEW_LINE> <INDENT> if not self.first: return False <NEW_LINE> self.first = False <NEW_LINE> return HeadingRule.condition(self, block)
|
题目时文档的第一个块,但前提时它是大标题。
|
6259901221a7993f00c66c47
|
class IntervalReloadFileContents(FileContents): <NEW_LINE> <INDENT> def __init__(self, path, interval = 1): <NEW_LINE> <INDENT> self._last_check = 0 <NEW_LINE> self._last_mtime = 0 <NEW_LINE> self._interval = interval <NEW_LINE> super(IntervalReloadFileContents, self).__init__(path) <NEW_LINE> <DEDENT> @property <NEW_LINE> def contents(self): <NEW_LINE> <INDENT> self._check_reload() <NEW_LINE> return super(IntervalReloadFileContents, self).contents <NEW_LINE> <DEDENT> @property <NEW_LINE> def hash_string(self): <NEW_LINE> <INDENT> self._check_reload() <NEW_LINE> return super(IntervalReloadFileContents, self).hash_string <NEW_LINE> <DEDENT> def _check_reload(self): <NEW_LINE> <INDENT> ctime = time.time() <NEW_LINE> if ctime >= self._last_check + self._interval: <NEW_LINE> <INDENT> stat = os.stat(self._path) <NEW_LINE> if stat.st_mtime != self._last_mtime: <NEW_LINE> <INDENT> self.load() <NEW_LINE> self._last_mtime = stat.st_mtime <NEW_LINE> <DEDENT> self._last_check = ctime
|
Loads the contents of a file and holds it in memory. Each time the
file contents are requested, checks to see if the file has been modified
since last checked.
:param path: Path to the file to load.
:keyword interval: The interval (in seconds) between modification checks.
|
62599012bf627c535bcb217c
|
class Algorithm(object): <NEW_LINE> <INDENT> def __init__(self, dpid_to_switch, mintravcap, topochangeupdate): <NEW_LINE> <INDENT> self.dpid_to_switch = dpid_to_switch <NEW_LINE> self.topology_last_update = time.time() <NEW_LINE> self.min_trasverse_capacity = mintravcap <NEW_LINE> self.update_forwarding_only_on_topology_change = topochangeupdate <NEW_LINE> <DEDENT> def find_route(self, src, dst): <NEW_LINE> <INDENT> logger.error('Algorithm not implemented') <NEW_LINE> return None
|
Algorithm base class
|
6259901215fb5d323ce7fa0a
|
class PrestagePackagesState(PrestageState): <NEW_LINE> <INDENT> def __init__(self, region_name): <NEW_LINE> <INDENT> super(PrestagePackagesState, self).__init__( next_state=consts.STRATEGY_STATE_PRESTAGE_IMAGES, region_name=region_name) <NEW_LINE> <DEDENT> def _do_state_action(self, strategy_step): <NEW_LINE> <INDENT> extra_args = utils.get_sw_update_strategy_extra_args(self.context) <NEW_LINE> payload = { 'sysadmin_password': extra_args['sysadmin_password'], 'oam_floating_ip': extra_args['oam_floating_ip_dict'][strategy_step.subcloud.name], 'force': extra_args['force'] } <NEW_LINE> prestage.prestage_packages(self.context, strategy_step.subcloud, payload) <NEW_LINE> self.info_log(strategy_step, "Packages finished")
|
Perform prestage packages operation
|
62599012d164cc6175821c4a
|
class TokenRefresh(Resource): <NEW_LINE> <INDENT> @jwt_refresh_token_required <NEW_LINE> def post(self): <NEW_LINE> <INDENT> current_user_id = get_jwt_identity() <NEW_LINE> new_token = create_access_token(identity=current_user_id) <NEW_LINE> response, status = { 'message': 'Access token was successfully refreshed', 'access_token': new_token }, 200 <NEW_LINE> return Response(dumps(response), status=status, mimetype='application/json')
|
Refresh token handler
|
625990126fece00bbaccc683
|
class Controller(object): <NEW_LINE> <INDENT> def __init__(self, model): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> <DEDENT> def add_malt_view(self,malt): <NEW_LINE> <INDENT> self.model.add_malt_view(malt) <NEW_LINE> self.model.announce_model_updated() <NEW_LINE> <DEDENT> def remove_malt(self,malt): <NEW_LINE> <INDENT> self.model.remove_malt(malt) <NEW_LINE> self.model.announce_model_updated()
|
classdocs
|
625990128c3a8732951f7230
|
class UrrySelector(Selector): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Urry Selector" <NEW_LINE> <DEDENT> def select( self, index: int = None, items: numpy.ndarray = None, administered_items: List[int] = None, est_theta: float = None, **kwargs ) -> Union[int, None]: <NEW_LINE> <INDENT> items, administered_items, est_theta = self._prepare_args( return_items=True, return_est_theta=True, index=index, items=items, administered_items=administered_items, est_theta=est_theta, **kwargs ) <NEW_LINE> assert est_theta is not None <NEW_LINE> assert administered_items is not None <NEW_LINE> assert items is not None <NEW_LINE> ordered_items = self._sort_by_b(items, est_theta) <NEW_LINE> valid_indexes = self._get_non_administered(ordered_items, administered_items) <NEW_LINE> if len(valid_indexes) == 0: <NEW_LINE> <INDENT> warn("There are no more items to be applied.") <NEW_LINE> return None <NEW_LINE> <DEDENT> return valid_indexes[0]
|
Selector that returns the item whose difficulty parameter is closest to the examinee's ability
|
62599012d164cc6175821c4c
|
class GroupAccessDict(Dict): <NEW_LINE> <INDENT> def from_json(self, value): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> return {int(k): value[k] for k in value} <NEW_LINE> <DEDENT> <DEDENT> def to_json(self, value): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> return {unicode(k): value[k] for k in value}
|
Special Dict class for serializing the group_access field.
|
625990136fece00bbaccc685
|
class findAdGroupById_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.I32, 'group_id', None, None, ), ) <NEW_LINE> def __init__(self, group_id=None,): <NEW_LINE> <INDENT> self.group_id = group_id <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.group_id = iprot.readI32(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('findAdGroupById_args') <NEW_LINE> if self.group_id is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('group_id', TType.I32, 1) <NEW_LINE> oprot.writeI32(self.group_id) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
|
Attributes:
- group_id
|
6259901321a7993f00c66c4b
|
class BoundedTestGenerator(TestGenerationEngine): <NEW_LINE> <INDENT> def __init__(self, features, possible_args, num_tests): <NEW_LINE> <INDENT> super().__init__(features, possible_args) <NEW_LINE> self.num_tests = num_tests <NEW_LINE> <DEDENT> def generate(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def next_test(self): <NEW_LINE> <INDENT> if self.index < self.num_tests: <NEW_LINE> <INDENT> row_features = {(router, f, arg): random.choices([-1, random.randrange(0, len(self.possible_args[f]))], weights=[10, 1])[0] for (router, f, arg) in self.features} <NEW_LINE> args = translate_args(row_features) <NEW_LINE> self.index = self.index + 1 <NEW_LINE> return args <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
|
Test generator which randomly assigns parameter values from the boundary value space.
Corresponds to bounded Metha in the Metha paper.
|
6259901315fb5d323ce7fa0e
|
class res_partner_server(orm.Model): <NEW_LINE> <INDENT> _name = 'res.partner.server' <NEW_LINE> _description = 'Server' <NEW_LINE> _columns={ 'name': fields.char('Nome', size=30, required=True), 'domain': fields.char('Dominio', size=60), 'ip': fields.char('IP', size=15, required=True), 'note': fields.text('Note'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'os_id': fields.many2one('res.partner.server.os', 'Operating System'), 'password_ids': fields.one2many('res.partner.server.password', 'server_id', 'Password'), 'service_ids': fields.one2many('res.partner.server.service', 'server_id', 'Services'), 'bit': fields.selection([ ('32', '32 bit'), ('64', '64 bit') ], 'Bit', select=True), }
|
Server per partner
|
6259901321a7993f00c66c4d
|
class BadSignatureError(ValueError): <NEW_LINE> <INDENT> pass
|
Raised when the signature was forged or otherwise corrupt.
|
6259901356b00c62f0fb3590
|
class IsOfferJoinedFilter(filters.BaseFilterBackend): <NEW_LINE> <INDENT> def filter_queryset(self, request, queryset, view): <NEW_LINE> <INDENT> if request.query_params.get('joined') == 'true': <NEW_LINE> <INDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> return queryset.filter(volunteers__in=[request.user]) <NEW_LINE> <DEDENT> return queryset.none() <NEW_LINE> <DEDENT> elif request.query_params.get('joined') == 'false': <NEW_LINE> <INDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> return queryset.exclude(volunteers__in=[request.user]) <NEW_LINE> <DEDENT> <DEDENT> return queryset
|
Filter offers based on if user joined an offer.
|
6259901321a7993f00c66c4f
|
class BaseSwap(object): <NEW_LINE> <INDENT> def test_simple(self): <NEW_LINE> <INDENT> x = arange(3.,dtype=self.dtype) <NEW_LINE> y = zeros(shape(x),x.dtype) <NEW_LINE> desired_x = y.copy() <NEW_LINE> desired_y = x.copy() <NEW_LINE> x, y = self.blas_func(x,y) <NEW_LINE> assert_array_equal(desired_x,x) <NEW_LINE> assert_array_equal(desired_y,y) <NEW_LINE> <DEDENT> def test_x_stride(self): <NEW_LINE> <INDENT> x = arange(6.,dtype=self.dtype) <NEW_LINE> y = zeros(3,x.dtype) <NEW_LINE> desired_x = y.copy() <NEW_LINE> desired_y = x.copy()[::2] <NEW_LINE> x, y = self.blas_func(x,y,n=3,incx=2) <NEW_LINE> assert_array_equal(desired_x,x[::2]) <NEW_LINE> assert_array_equal(desired_y,y) <NEW_LINE> <DEDENT> def test_y_stride(self): <NEW_LINE> <INDENT> x = arange(3.,dtype=self.dtype) <NEW_LINE> y = zeros(6,x.dtype) <NEW_LINE> desired_x = y.copy()[::2] <NEW_LINE> desired_y = x.copy() <NEW_LINE> x, y = self.blas_func(x,y,n=3,incy=2) <NEW_LINE> assert_array_equal(desired_x,x) <NEW_LINE> assert_array_equal(desired_y,y[::2]) <NEW_LINE> <DEDENT> def test_x_and_y_stride(self): <NEW_LINE> <INDENT> x = arange(12.,dtype=self.dtype) <NEW_LINE> y = zeros(6,x.dtype) <NEW_LINE> desired_x = y.copy()[::2] <NEW_LINE> desired_y = x.copy()[::4] <NEW_LINE> x, y = self.blas_func(x,y,n=3,incx=4,incy=2) <NEW_LINE> assert_array_equal(desired_x,x[::4]) <NEW_LINE> assert_array_equal(desired_y,y[::2]) <NEW_LINE> <DEDENT> def test_x_bad_size(self): <NEW_LINE> <INDENT> x = arange(12.,dtype=self.dtype) <NEW_LINE> y = zeros(6,x.dtype) <NEW_LINE> try: <NEW_LINE> <INDENT> self.blas_func(x,y,n=4,incx=5) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> assert_(0) <NEW_LINE> <DEDENT> def test_y_bad_size(self): <NEW_LINE> <INDENT> x = arange(12.,dtype=self.dtype) <NEW_LINE> y = zeros(6,x.dtype) <NEW_LINE> try: <NEW_LINE> <INDENT> self.blas_func(x,y,n=3,incy=5) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> assert_(0)
|
Mixin class for swap tests
|
6259901356b00c62f0fb3592
|
class HelloApiView(APIView): <NEW_LINE> <INDENT> serializer_class = serializers.HelloSerializer <NEW_LINE> def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Uses HTTP methods as functions (get, post, patch, push, delete)', 'Is similar to a traditional Django View', 'Gives you the most control over you application logic', 'Is mapped manually to URLs', ] <NEW_LINE> return Response({'message': 'Hello!', 'an_apiview': an_apiview}) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> serializer = self.serializer_class(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> name = serializer.validated_data.get('name') <NEW_LINE> message = f'Hello {name}' <NEW_LINE> return Response({'message': message}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) <NEW_LINE> <DEDENT> <DEDENT> def put(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method': 'PUT'}) <NEW_LINE> <DEDENT> def patch(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method': 'PATCH'}) <NEW_LINE> <DEDENT> def delete(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method': 'DELETE'})
|
Test API View
|
62599013507cdc57c63a5a76
|
class ReadResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'page': {'required': True, 'minimum': 1}, 'angle': {'required': True, 'maximum': 180, 'minimum_ex': -180}, 'width': {'required': True, 'minimum': 0}, 'height': {'required': True, 'minimum': 0}, 'unit': {'required': True}, } <NEW_LINE> _attribute_map = { 'page': {'key': 'page', 'type': 'int'}, 'angle': {'key': 'angle', 'type': 'float'}, 'width': {'key': 'width', 'type': 'float'}, 'height': {'key': 'height', 'type': 'float'}, 'unit': {'key': 'unit', 'type': 'str'}, 'lines': {'key': 'lines', 'type': '[TextLine]'}, 'selection_marks': {'key': 'selectionMarks', 'type': '[SelectionMark]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ReadResult, self).__init__(**kwargs) <NEW_LINE> self.page = kwargs['page'] <NEW_LINE> self.angle = kwargs['angle'] <NEW_LINE> self.width = kwargs['width'] <NEW_LINE> self.height = kwargs['height'] <NEW_LINE> self.unit = kwargs['unit'] <NEW_LINE> self.lines = kwargs.get('lines', None) <NEW_LINE> self.selection_marks = kwargs.get('selection_marks', None)
|
Text extracted from a page in the input document.
All required parameters must be populated in order to send to Azure.
:ivar page: Required. The 1-based page number in the input document.
:vartype page: int
:ivar angle: Required. The general orientation of the text in clockwise direction, measured in
degrees between (-180, 180].
:vartype angle: float
:ivar width: Required. The width of the image/PDF in pixels/inches, respectively.
:vartype width: float
:ivar height: Required. The height of the image/PDF in pixels/inches, respectively.
:vartype height: float
:ivar unit: Required. The unit used by the width, height and boundingBox properties. For
images, the unit is "pixel". For PDF, the unit is "inch". Possible values include: "pixel",
"inch".
:vartype unit: str or ~azure.ai.formrecognizer.v2_1.models.LengthUnit
:ivar lines: When includeTextDetails is set to true, a list of recognized text lines. The
maximum number of lines returned is 300 per page. The lines are sorted top to bottom, left to
right, although in certain cases proximity is treated with higher priority. As the sorting
order depends on the detected text, it may change across images and OCR version updates. Thus,
business logic should be built upon the actual line location instead of order.
:vartype lines: list[~azure.ai.formrecognizer.v2_1.models.TextLine]
:ivar selection_marks: List of selection marks extracted from the page.
:vartype selection_marks: list[~azure.ai.formrecognizer.v2_1.models.SelectionMark]
|
62599013925a0f43d25e8d16
|
class FillArrayData(object): <NEW_LINE> <INDENT> def __init__(self, buff): <NEW_LINE> <INDENT> self.notes = [] <NEW_LINE> self.format_general_size = calcsize("=HHI") <NEW_LINE> self.ident = unpack("=H", buff[0:2])[0] <NEW_LINE> self.element_width = unpack("=H", buff[2:4])[0] <NEW_LINE> self.size = unpack("=I", buff[4:8])[0] <NEW_LINE> buf_len = self.size * self.element_width <NEW_LINE> if buf_len % 2: <NEW_LINE> <INDENT> buf_len += 1 <NEW_LINE> <DEDENT> self.data = buff[self.format_general_size:self.format_general_size + buf_len] <NEW_LINE> <DEDENT> def add_note(self, msg): <NEW_LINE> <INDENT> self.notes.append(msg) <NEW_LINE> <DEDENT> def get_notes(self): <NEW_LINE> <INDENT> return self.notes <NEW_LINE> <DEDENT> def get_op_value(self): <NEW_LINE> <INDENT> return self.ident <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> return self.data <NEW_LINE> <DEDENT> def get_output(self, idx=-1): <NEW_LINE> <INDENT> buff = "" <NEW_LINE> data = self.get_data() <NEW_LINE> buff += repr(data) + " | " <NEW_LINE> for i in range(0, len(data)): <NEW_LINE> <INDENT> buff += "\\x%02x" % ord(data[i]) <NEW_LINE> <DEDENT> return buff <NEW_LINE> <DEDENT> def get_operands(self, idx=-1): <NEW_LINE> <INDENT> return [(OPERAND_RAW, repr(self.get_data()))] <NEW_LINE> <DEDENT> def get_formatted_operands(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return "fill-array-data-payload" <NEW_LINE> <DEDENT> def show_buff(self, pos): <NEW_LINE> <INDENT> buff = self.get_name() + " " <NEW_LINE> for i in range(0, len(self.data)): <NEW_LINE> <INDENT> buff += "\\x%02x" % ord(self.data[i]) <NEW_LINE> <DEDENT> return buff <NEW_LINE> <DEDENT> def show(self, pos): <NEW_LINE> <INDENT> print (self.show_buff(pos), end='') <NEW_LINE> <DEDENT> def get_length(self): <NEW_LINE> <INDENT> return ((self.size * self.element_width + 1) / 2 + 4) * 2 <NEW_LINE> <DEDENT> def get_raw(self): <NEW_LINE> <INDENT> return pack("=H", self.ident) + pack("=H", self.element_width) + pack("=I", self.size) + self.data
|
This class can parse a FillArrayData instruction
:param buff: a Buff object which represents a buffer where the instruction is stored
|
6259901356b00c62f0fb3594
|
class _BaseElementOptions(_BaseOptions): <NEW_LINE> <INDENT> visible = properties.Boolean( 'Visibility of resource on/off', default=True, ) <NEW_LINE> opacity = properties.Instance( 'Default opacity options on the element', OptionsOpacity, default=OptionsOpacity, ) <NEW_LINE> color = properties.Instance( 'Default color options on the element', OptionsColor, default=OptionsColor, )
|
Base class for various element options
|
625990130a366e3fb87dd6c9
|
class OverdueFilter(TestCase): <NEW_LINE> <INDENT> fixtures = ['gtd-test.json', 'test-users.json', 'gtd-env.json'] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.node = Node.objects.get(pk=1) <NEW_LINE> <DEDENT> def test_filter_exists(self): <NEW_LINE> <INDENT> self.assertTrue(self.node.overdue, '__call__') <NEW_LINE> self.node.test_date = dt.datetime.now().date() <NEW_LINE> self.assertIn( self.node.overdue('test_date').__class__.__name__, ['str', 'unicode']) <NEW_LINE> self.node.none_field = None <NEW_LINE> self.assertEqual( self.node.overdue('none_field'), '' ) <NEW_LINE> <DEDENT> def test_simple_date(self): <NEW_LINE> <INDENT> self.node.yesterday = (dt.datetime.now() + dt.timedelta(-1)).date() <NEW_LINE> self.assertEqual( self.node.overdue( 'yesterday', future=True), '1 day ago') <NEW_LINE> self.node.yesterday = self.node.yesterday + dt.timedelta(-1) <NEW_LINE> self.assertEqual( self.node.overdue('yesterday', future=True), '2 days ago') <NEW_LINE> <DEDENT> def test_future_date(self): <NEW_LINE> <INDENT> self.node.tomorrow = (dt.datetime.now() + dt.timedelta(1)).date() <NEW_LINE> self.assertEqual( self.node.overdue('tomorrow', future=True), 'in 1 day') <NEW_LINE> self.node.tomorrow = self.node.tomorrow + dt.timedelta(1) <NEW_LINE> self.assertEqual( self.node.overdue('tomorrow', future=True), 'in 2 days')
|
Tests the `overdue` node method that makes dates into
prettier "in 1 day" strings, etc.
|
6259901321a7993f00c66c53
|
class GridHeaderMouseLeftUp(GridEvent, MouseEvent): <NEW_LINE> <INDENT> pass
|
Occurs when the left mouse button goes up in the header region.
|
62599013bf627c535bcb2188
|
class MouseButton: <NEW_LINE> <INDENT> def __init__(self, mouse): <NEW_LINE> <INDENT> self.mouse: Mouse = mouse <NEW_LINE> self.primed = False <NEW_LINE> self.primed_position = None <NEW_LINE> <DEDENT> def prime(self, position): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.mouse.active_object = self.mouse.mouse_interaction_group.get_sprites_at(position)[-1] <NEW_LINE> self.primed = True <NEW_LINE> self.primed_position = position <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def release(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.primed = False <NEW_LINE> self.primed_position = None
|
class that holds mouse button states, detects object collisions and handles clicks
|
62599013507cdc57c63a5a7a
|
class InvalidateChildTest(unittest.TestCase): <NEW_LINE> <INDENT> def testInvalidateChild(self): <NEW_LINE> <INDENT> parent = ObjectType() <NEW_LINE> child1 = ObjectType(parent) <NEW_LINE> child1.setObjectName('child1') <NEW_LINE> child2 = ObjectType.create() <NEW_LINE> child2.setParent(parent) <NEW_LINE> child2.setObjectName('child2') <NEW_LINE> self.assertEqual(parent.children(), [child1, child2]) <NEW_LINE> bbox = BlackBox() <NEW_LINE> bbox.keepObjectType(child1) <NEW_LINE> self.assertEqual(parent.children(), [child2]) <NEW_LINE> bbox.keepObjectType(child2) <NEW_LINE> self.assertEqual(parent.children(), []) <NEW_LINE> del parent <NEW_LINE> self.assertEqual(child1.objectName(), 'child1') <NEW_LINE> self.assertRaises(RuntimeError, child2.objectName)
|
Tests for invalidating a C++ created child that was already on the care of a parent.
|
625990138c3a8732951f723c
|
class HydraClassOp(): <NEW_LINE> <INDENT> def __init__(self, title, method, expects, returns, status): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.method = method <NEW_LINE> self.expects = expects <NEW_LINE> self.returns = returns <NEW_LINE> self.status = status <NEW_LINE> <DEDENT> def get_type(self, method): <NEW_LINE> <INDENT> if method == "POST": <NEW_LINE> <INDENT> return "http://schema.org/UpdateAction" <NEW_LINE> <DEDENT> elif method == "PUT": <NEW_LINE> <INDENT> return "http://schema.org/AddAction" <NEW_LINE> <DEDENT> elif method == "DELETE": <NEW_LINE> <INDENT> return "http://schema.org/DeleteAction" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "http://schema.org/FindAction" <NEW_LINE> <DEDENT> <DEDENT> def generate(self): <NEW_LINE> <INDENT> op = { "@type": self.get_type(self.method), "title": self.title, "method": self.method, "expects": self.expects, "returns": self.returns, "possibleStatus": self.status } <NEW_LINE> return op
|
Template for a new supportedOperation.
|
62599013507cdc57c63a5a82
|
class TestLoggingConfig(NamedModelTestCase): <NEW_LINE> <INDENT> def test_name_not_found(self): <NEW_LINE> <INDENT> logger.warning('Verify logger filtering') <NEW_LINE> name = 'myname' <NEW_LINE> with self.assertRaises(Category.DoesNotExist): <NEW_LINE> <INDENT> Category.objects.named_instance(name=name) <NEW_LINE> <DEDENT> self.assertTrue(CategoryModelFactory(name=constants.UNKNOWN)) <NEW_LINE> self.assertTrue(Category.objects.named_instance(name=name))
|
Logging configuration testcase class.
|
62599013462c4b4f79dbc6eb
|
class ImageOps: <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def resize_image(cls, image_body, size, fit_to_size=False): <NEW_LINE> <INDENT> image_file = StringIO(image_body) <NEW_LINE> try: <NEW_LINE> <INDENT> image = Image.open(image_file) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> format = image.format <NEW_LINE> image = cls.adjust_image_orientation(image) <NEW_LINE> if not fit_to_size: <NEW_LINE> <INDENT> image.thumbnail(PROFILE_PICTURE_SIZES[size], Image.ANTIALIAS) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> image = PILOps.fit(image, PROFILE_PICTURE_SIZES[size], method=Image.ANTIALIAS, centering=(0.5, 0.5)) <NEW_LINE> <DEDENT> output = StringIO() <NEW_LINE> if format.lower() == 'jpg': <NEW_LINE> <INDENT> format = 'jpeg' <NEW_LINE> <DEDENT> image.save(output, format=format, quality=95) <NEW_LINE> return output <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def adjust_image_orientation(cls, image): <NEW_LINE> <INDENT> if hasattr(image, '_getexif'): <NEW_LINE> <INDENT> exif = image._getexif() <NEW_LINE> if exif: <NEW_LINE> <INDENT> for tag, value in exif.items(): <NEW_LINE> <INDENT> decoded = TAGS.get(tag, tag) <NEW_LINE> if decoded == 'Orientation': <NEW_LINE> <INDENT> if value == 6: <NEW_LINE> <INDENT> image = image.rotate(-90) <NEW_LINE> <DEDENT> if value == 8: <NEW_LINE> <INDENT> image = image.rotate(90) <NEW_LINE> <DEDENT> if value == 3: <NEW_LINE> <INDENT> image = image.rotate(180) <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return image
|
Module that holds all image operations. Since there's no state,
everything is a classmethod.
|
6259901315fb5d323ce7fa22
|
class AllPosts(Feed): <NEW_LINE> <INDENT> title = 'Glader.ru: последние сообщения' <NEW_LINE> link = 'http://%s' % settings.DOMAIN <NEW_LINE> description = 'Свежие сообщения на сайте сноуборд-энциклопедии Glader.ru' <NEW_LINE> title_template = 'feeds/all_title.html' <NEW_LINE> description_template = 'feeds/all_description.html' <NEW_LINE> def items(self): <NEW_LINE> <INDENT> return Post.objects.filter(status='pub', type='post').order_by('-date_created')[:20] <NEW_LINE> <DEDENT> def item_pubdate(self, item): <NEW_LINE> <INDENT> return item.date_created <NEW_LINE> <DEDENT> def item_author_name(self, item): <NEW_LINE> <INDENT> author = item.author <NEW_LINE> return author and author.first_name or '' <NEW_LINE> <DEDENT> def item_link(self, item): <NEW_LINE> <INDENT> return item.get_absolute_url()
|
Свежие сообщения в блоге
|
62599013d164cc6175821c64
|
class StartupPagesRecordPageSet(story.StorySet): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(StartupPagesRecordPageSet, self).__init__( archive_data_file='data/startup_pages.json') <NEW_LINE> urls_list = [ 'http://bbc.co.uk', 'http://kapook.com', ] <NEW_LINE> for url in urls_list: <NEW_LINE> <INDENT> self.AddStory(StartupPagesRecordPage(url, self))
|
Pages to record data for testing starting Chrome with a URL.
We can't use startup_pages.json with record_wpr, since record_wpr
requires a default navigate step, which we don't want for startup
testing; but we do want to record the pages it uses. Also, record_wpr
fails on about:blank, which we want to include in startup testing.
|
625990130a366e3fb87dd6d9
|
class GradientTapeError(Exception): <NEW_LINE> <INDENT> pass
|
Raised when an inappropriate GradientTape event occurs.
|
62599013d18da76e235b77c1
|
class Logger(app.AppLogger): <NEW_LINE> <INDENT> observerFactory = log.CLILogObserver <NEW_LINE> def __init__(self, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> <DEDENT> def _getLogObserver(self): <NEW_LINE> <INDENT> return self.observerFactory(self.config) <NEW_LINE> <DEDENT> def _initialLog(self): <NEW_LINE> <INDENT> if hasattr(self.config, "program"): <NEW_LINE> <INDENT> log.debug("Starting logging for {0.config.program}".format(self)) <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self._observer is not None: <NEW_LINE> <INDENT> log.removeObserver(self._observer) <NEW_LINE> self._observer = None
|
CLI-oriented logger factory.
|
62599013be8e80087fbbfd5a
|
class CrossValidatorModel(Model, ValidatorParams): <NEW_LINE> <INDENT> def __init__(self, bestModel, avgMetrics=[]): <NEW_LINE> <INDENT> super(CrossValidatorModel, self).__init__() <NEW_LINE> self.bestModel = bestModel <NEW_LINE> self.avgMetrics = avgMetrics <NEW_LINE> <DEDENT> def _transform(self, dataset): <NEW_LINE> <INDENT> return self.bestModel.transform(dataset) <NEW_LINE> <DEDENT> @since("1.4.0") <NEW_LINE> def copy(self, extra=None): <NEW_LINE> <INDENT> if extra is None: <NEW_LINE> <INDENT> extra = dict() <NEW_LINE> <DEDENT> bestModel = self.bestModel.copy(extra) <NEW_LINE> avgMetrics = self.avgMetrics <NEW_LINE> return CrossValidatorModel(bestModel, avgMetrics)
|
Model from k-fold cross validation.
.. versionadded:: 1.4.0
|
6259901315fb5d323ce7fa26
|
class Solution2: <NEW_LINE> <INDENT> def threeSum(self, nums: List[int]) -> List[List[int]]: <NEW_LINE> <INDENT> result = set() <NEW_LINE> nums.sort() <NEW_LINE> for i in range(len(nums) - 2): <NEW_LINE> <INDENT> if nums[i] > 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if i > 0 and nums[i] == nums[i - 1]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> l, r = i + 1, len(nums) - 1 <NEW_LINE> while l < r: <NEW_LINE> <INDENT> elements = (nums[i], nums[l], nums[r]) <NEW_LINE> sum_elements = sum(elements) <NEW_LINE> if sum_elements < 0: <NEW_LINE> <INDENT> l += 1 <NEW_LINE> <DEDENT> elif sum_elements > 0: <NEW_LINE> <INDENT> r -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result.add(elements) <NEW_LINE> while l < r and nums[l] == nums[l + 1]: <NEW_LINE> <INDENT> l += 1 <NEW_LINE> <DEDENT> while l < r and nums[r] == nums[r - 1]: <NEW_LINE> <INDENT> r -= 1 <NEW_LINE> <DEDENT> l += 1 <NEW_LINE> r -= 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return [list(s) for s in result]
|
Runtime: 1132 ms, less than 33.53 % of python3.
Memory Usage: 17.4 MB, less than 19.96 % of python3.
Algorithm idea:
The way to think about it is since it's 3 sum, there's only going to be 3 numbers.
So to find the combinations of 3 numbers, we iterating through the list with
the first pointer, and then trying to find two extra numbers to sum to 0.
Since the list is ordered, the right pointer will always be higher than the
middle pointer. So if the sum is too large, you can move the right pointer back one.
On the other hand, if the sum is too small (below 0), then move the middle pointer up one.
|
625990139b70327d1c57fa69
|
class Debt_To_Equity_Ratio(CustomFactor): <NEW_LINE> <INDENT> inputs = [morningstar.balance_sheet.total_debt, morningstar.balance_sheet.common_stock_equity] <NEW_LINE> window_length = 1 <NEW_LINE> def compute(self, today, assets, out, debt, equity): <NEW_LINE> <INDENT> out[:] = debt[-1] / equity[-1]
|
Debt / Equity Ratio:
Total Debts divided by Common Stock Equity
https://www.pnc.com/content/dam/pnc-com/pdf/personal/wealth-investments/WhitePapers/FactorAnalysisFeb2014.pdf
Notes:
High value suggests that company is taking on debts to leverage
Low value suggests good financial health as little-to-no leveraging
Long Term Debt
|
62599013d18da76e235b77c2
|
class World(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def stacked_proxy_safe_get(stacked_proxy, key, default=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return getattr(stacked_proxy, key) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> <DEDENT> def current_user(self): <NEW_LINE> <INDENT> if c.user_is_loggedin: <NEW_LINE> <INDENT> return self.stacked_proxy_safe_get(c, 'user') <NEW_LINE> <DEDENT> <DEDENT> def current_subreddit(self): <NEW_LINE> <INDENT> site = self.stacked_proxy_safe_get(c, 'site') <NEW_LINE> if not site: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> return site.name <NEW_LINE> <DEDENT> def current_subdomain(self): <NEW_LINE> <INDENT> return self.stacked_proxy_safe_get(c, 'subdomain') <NEW_LINE> <DEDENT> def current_oauth_client(self): <NEW_LINE> <INDENT> client = self.stacked_proxy_safe_get(c, 'oauth2_client', None) <NEW_LINE> return getattr(client, '_id', None) <NEW_LINE> <DEDENT> def current_loid(self): <NEW_LINE> <INDENT> cookies = self.stacked_proxy_safe_get(request, 'cookies') <NEW_LINE> if not cookies: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return cookies.get("loid", None) <NEW_LINE> <DEDENT> def is_admin(self, user): <NEW_LINE> <INDENT> if not user or not hasattr(user, 'name'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return user.name in self.stacked_proxy_safe_get(g, 'admins', []) <NEW_LINE> <DEDENT> def is_employee(self, user): <NEW_LINE> <INDENT> if not user: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return user.employee <NEW_LINE> <DEDENT> def user_has_beta_enabled(self, user): <NEW_LINE> <INDENT> if not user: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return user.pref_beta <NEW_LINE> <DEDENT> def has_gold(self, user): <NEW_LINE> <INDENT> if not user: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return user.gold <NEW_LINE> <DEDENT> def is_user_loggedin(self): <NEW_LINE> <INDENT> if self.current_user(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def url_features(self): <NEW_LINE> <INDENT> return set(request.GET.getall('feature')) <NEW_LINE> <DEDENT> def live_config(self, name): <NEW_LINE> <INDENT> live = self.stacked_proxy_safe_get(g, 'live_config', {}) <NEW_LINE> return live.get(name)
|
A World is the proxy to the app/request state for Features.
Proxying through World allows for easy testing and caching if needed.
|
62599013bf627c535bcb219c
|
class ThreadedUnixSocketServer(SocketServer.ThreadingUnixStreamServer): <NEW_LINE> <INDENT> pass
|
multi-thread unix socket server class
|
62599013796e427e5384f46f
|
class Pagination: <NEW_LINE> <INDENT> def __init__(self, page_type=PAGE_TYPE_RANGE, pages=None, is_counted=False, page_len=None, start_empty=False, num_shift=0): <NEW_LINE> <INDENT> self.page_type = page_type <NEW_LINE> self.pages = pages <NEW_LINE> self.is_counted = is_counted <NEW_LINE> self.page_len = page_len <NEW_LINE> self.current_page = 0 <NEW_LINE> self.current_len = page_len <NEW_LINE> self.start_empty = start_empty <NEW_LINE> self.num_shift = num_shift <NEW_LINE> self.url = None <NEW_LINE> <DEDENT> def set_url(self, url): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> <DEDENT> def current(self): <NEW_LINE> <INDENT> if self.page_type == PAGE_TYPE_RANGE: <NEW_LINE> <INDENT> return str(self.pages[self.current]) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def currenturl(self): <NEW_LINE> <INDENT> if self.page_type == PAGE_TYPE_RANGE: <NEW_LINE> <INDENT> return self.url % str(self.pages[self.current]) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def set_length(self, curlen): <NEW_LINE> <INDENT> self.current_len = curlen <NEW_LINE> <DEDENT> def next(self, last_len=None): <NEW_LINE> <INDENT> if last_len: <NEW_LINE> <INDENT> self.set_length(last_len) <NEW_LINE> <DEDENT> result = None <NEW_LINE> if self.page_type == PAGE_TYPE_RANGE: <NEW_LINE> <INDENT> if len(self.pages) > self.current_page: <NEW_LINE> <INDENT> result = str(self.pages[self.current_page]) <NEW_LINE> <DEDENT> <DEDENT> elif self.page_type == PAGE_TYPE_PAGED: <NEW_LINE> <INDENT> if self.start_empty and self.current_page == 0: <NEW_LINE> <INDENT> result = '' <NEW_LINE> <DEDENT> elif self.current_len == self.page_len: <NEW_LINE> <INDENT> result = str(self.current_page + self.num_shift) <NEW_LINE> <DEDENT> <DEDENT> elif self.page_type == PAGE_TYPE_COUNTED: <NEW_LINE> <INDENT> if self.current_len == self.page_len: <NEW_LINE> <INDENT> result = str(self.current_page * self.page_len) <NEW_LINE> <DEDENT> <DEDENT> self.current_page += 1 <NEW_LINE> return result <NEW_LINE> <DEDENT> def nexturl(self, last_len=None): <NEW_LINE> <INDENT> page_num = self.next(last_len) <NEW_LINE> if page_num is not None: <NEW_LINE> <INDENT> url = self.url.replace('{{page}}', page_num) <NEW_LINE> return url <NEW_LINE> <DEDENT> return None
|
Pagination style
|
625990130a366e3fb87dd6e2
|
class ContainsAttributeValue(Comparator): <NEW_LINE> <INDENT> def __init__(self, key, value): <NEW_LINE> <INDENT> self._key = key <NEW_LINE> self._value = value <NEW_LINE> <DEDENT> def equals(self, rhs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return getattr(rhs, self._key) == self._value <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False
|
Checks whether passed parameter contains attributes with a given value.
Example:
mock_dao.UpdateSomething(ContainsAttribute('stevepm', stevepm_user_info))
|
62599013462c4b4f79dbc6f7
|
class RadarPlot(_BasePlot): <NEW_LINE> <INDENT> pass
|
A radar-style plot.
|
625990140a366e3fb87dd6e4
|
class CloseAndPull(CommandGroup): <NEW_LINE> <INDENT> def __init__(self, robot): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.addParallel(CloseClaw(robot=robot)) <NEW_LINE> self.addSequential(Pull(robot=robot))
|
Open claw and punch.
|
62599014462c4b4f79dbc6f9
|
class _Appearance(_Settings): <NEW_LINE> <INDENT> class _ColorSettings(_Settings): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.text = '' <NEW_LINE> self.prompt = color.Fore.TOGGLE_BRIGHT <NEW_LINE> self.selection = (color.Fore.TOGGLE_RED + color.Fore.TOGGLE_GREEN + color.Fore.TOGGLE_BLUE + color.Back.TOGGLE_RED + color.Back.TOGGLE_GREEN + color.Back.TOGGLE_BLUE) <NEW_LINE> self.search_filter = (color.Back.TOGGLE_RED + color.Back.TOGGLE_BLUE + color.Fore.TOGGLE_BRIGHT) <NEW_LINE> self.completion_match = color.Fore.TOGGLE_RED <NEW_LINE> self.dir_history_selection = (color.Fore.TOGGLE_BRIGHT + color.Back.TOGGLE_BRIGHT) <NEW_LINE> <DEDENT> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.prompt = abbrev_path_prompt <NEW_LINE> self.colors = self._ColorSettings() <NEW_LINE> <DEDENT> def sanitize(self): <NEW_LINE> <INDENT> if not callable(self.prompt): <NEW_LINE> <INDENT> print('Prompt function doesn\'t look like a callable; reverting to PyCmd\'s default prompt') <NEW_LINE> self.prompt = abbrev_path_prompt
|
Appearance settings
|
62599014507cdc57c63a5a92
|
class DataStore(object): <NEW_LINE> <INDENT> DS_RESOURCES = "resources" <NEW_LINE> DS_OBJECTS = "objects" <NEW_LINE> DS_EVENTS = "events" <NEW_LINE> DS_DIRECTORY = DS_RESOURCES <NEW_LINE> DS_STATE = "state" <NEW_LINE> DS_PROFILE_LIST = ['OBJECTS', 'RESOURCES', 'DIRECTORY', 'STATE', 'EVENTS', 'EXAMPLES', 'SCIDATA', 'FILESYSTEM', 'BASIC'] <NEW_LINE> DS_PROFILE = DotDict(zip(DS_PROFILE_LIST, DS_PROFILE_LIST)) <NEW_LINE> DS_PROFILE_MAPPING = { DS_RESOURCES: DS_PROFILE.RESOURCES, DS_OBJECTS: DS_PROFILE.OBJECTS, DS_EVENTS: DS_PROFILE.EVENTS, DS_STATE: DS_PROFILE.STATE, } <NEW_LINE> def close(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def create_datastore(self, datastore_name="", create_indexes=True): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def delete_datastore(self, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def list_datastores(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def info_datastore(self, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def datastore_exists(self, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def list_objects(self, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def list_object_revisions(self, object_id, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def create(self, obj, object_id=None, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def create_doc(self, obj, object_id=None, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def create_mult(self, objects, object_ids=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def create_doc_mult(self, docs, object_ids=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read(self, object_id, rev_id="", datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read_doc(self, object_id, rev_id="", datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read_mult(self, object_ids, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read_doc_mult(self, object_ids, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update(self, obj, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update_doc(self, obj, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def delete(self, obj, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def delete_doc(self, obj, datastore_name=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def find_objects(self, subject, predicate="", object_type="", id_only=False): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def find_subjects(self, subject_type="", predicate="", obj="", id_only=False): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def find_associations(self, subject="", predicate="", obj="", assoc_type='H2H', id_only=True): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _preload_create_doc(self, doc): <NEW_LINE> <INDENT> pass
|
Common utilities for datastores
|
625990145166f23b2e2440c2
|
class Xco2: <NEW_LINE> <INDENT> allowed = ('polygon', 'point', ) <NEW_LINE> def on_post(self, req, resp): <NEW_LINE> <INDENT> resp.status = falcon.HTTP_200 <NEW_LINE> data = req.context['geojson'] <NEW_LINE> coords = spatial.from_list_to_ewkt( spatial.coordinates_from_geojson(data) ) <NEW_LINE> print(coords) <NEW_LINE> controller = Controller(coords) <NEW_LINE> controller.which_areas_contains_this_polygon() <NEW_LINE> json = controller.serialize_features_from_database() <NEW_LINE> print(str(controller)) <NEW_LINE> print(json) <NEW_LINE> req.context['result'] = json
|
Long-living REST resource class.
Use only POST method.
|
62599014bf627c535bcb21a2
|
class Handler(handler.handler): <NEW_LINE> <INDENT> def dispatch(self, session): <NEW_LINE> <INDENT> req_body = self.context.request.body <NEW_LINE> resp_body = self.context.response.body <NEW_LINE> id = req_body.id <NEW_LINE> name = req_body.name <NEW_LINE> sort_order = req_body.sort_order <NEW_LINE> info = { 'name': name, 'sort_order': sort_order } <NEW_LINE> session.query(WechatshopSpecification).filter(WechatshopSpecification.id == id).update(info) <NEW_LINE> session.flush()
|
商品型号更新
|
62599014925a0f43d25e8d33
|
class ModulesHolder( ObjectHolder ): <NEW_LINE> <INDENT> idxName = "modules" <NEW_LINE> counterName = "MODULES" <NEW_LINE> _availableModules = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> ObjectHolder.__init__(self) <NEW_LINE> import MaKaC.modules.news as news <NEW_LINE> import MaKaC.modules.cssTpls as cssTpls <NEW_LINE> import MaKaC.modules.upcoming as upcoming <NEW_LINE> ModulesHolder._availableModules = { news.NewsModule.id:news.NewsModule, cssTpls.CssTplsModule.id:cssTpls.CssTplsModule, upcoming.UpcomingEventsModule.id:upcoming.UpcomingEventsModule } <NEW_LINE> <DEDENT> def _newId( self ): <NEW_LINE> <INDENT> id = ObjectHolder._newId( self ) <NEW_LINE> return "%s"%id <NEW_LINE> <DEDENT> def getById( self, id ): <NEW_LINE> <INDENT> if type(id) is int: <NEW_LINE> <INDENT> id = str(id) <NEW_LINE> <DEDENT> if self._getIdx().has_key(str(id)): <NEW_LINE> <INDENT> return self._getIdx()[str(id)] <NEW_LINE> <DEDENT> elif self._availableModules.has_key(id): <NEW_LINE> <INDENT> newmod=self._availableModules[id]() <NEW_LINE> self.add(newmod) <NEW_LINE> return newmod <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise MaKaCError( ("Module id %s does not exist") % str(id) )
|
Specialised ObjectHolder class which provides a wrapper for collections
based in a Catalog for indexing the objects. It allows to index some
declared attributes of the stored objects and then perform SQL-like
queries
|
62599014d18da76e235b77c7
|
class RoutingGroupRouteInfo(NetAppObject): <NEW_LINE> <INDENT> _routing_group = None <NEW_LINE> @property <NEW_LINE> def routing_group(self): <NEW_LINE> <INDENT> return self._routing_group <NEW_LINE> <DEDENT> @routing_group.setter <NEW_LINE> def routing_group(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('routing_group', val) <NEW_LINE> <DEDENT> self._routing_group = val <NEW_LINE> <DEDENT> _metric = None <NEW_LINE> @property <NEW_LINE> def metric(self): <NEW_LINE> <INDENT> return self._metric <NEW_LINE> <DEDENT> @metric.setter <NEW_LINE> def metric(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('metric', val) <NEW_LINE> <DEDENT> self._metric = val <NEW_LINE> <DEDENT> _vserver = None <NEW_LINE> @property <NEW_LINE> def vserver(self): <NEW_LINE> <INDENT> return self._vserver <NEW_LINE> <DEDENT> @vserver.setter <NEW_LINE> def vserver(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('vserver', val) <NEW_LINE> <DEDENT> self._vserver = val <NEW_LINE> <DEDENT> _gateway_address = None <NEW_LINE> @property <NEW_LINE> def gateway_address(self): <NEW_LINE> <INDENT> return self._gateway_address <NEW_LINE> <DEDENT> @gateway_address.setter <NEW_LINE> def gateway_address(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('gateway_address', val) <NEW_LINE> <DEDENT> self._gateway_address = val <NEW_LINE> <DEDENT> _destination_address = None <NEW_LINE> @property <NEW_LINE> def destination_address(self): <NEW_LINE> <INDENT> return self._destination_address <NEW_LINE> <DEDENT> @destination_address.setter <NEW_LINE> def destination_address(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('destination_address', val) <NEW_LINE> <DEDENT> self._destination_address = val <NEW_LINE> <DEDENT> _address_family = None <NEW_LINE> @property <NEW_LINE> def address_family(self): <NEW_LINE> <INDENT> return self._address_family <NEW_LINE> <DEDENT> @address_family.setter <NEW_LINE> def address_family(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('address_family', val) <NEW_LINE> <DEDENT> self._address_family = val <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_api_name(): <NEW_LINE> <INDENT> return "routing-group-route-info" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_desired_attrs(): <NEW_LINE> <INDENT> return [ 'routing-group', 'metric', 'vserver', 'gateway-address', 'destination-address', 'address-family', ] <NEW_LINE> <DEDENT> def describe_properties(self): <NEW_LINE> <INDENT> return { 'routing_group': { 'class': basestring, 'is_list': False, 'required': 'optional' }, 'metric': { 'class': int, 'is_list': False, 'required': 'optional' }, 'vserver': { 'class': basestring, 'is_list': False, 'required': 'optional' }, 'gateway_address': { 'class': basestring, 'is_list': False, 'required': 'optional' }, 'destination_address': { 'class': basestring, 'is_list': False, 'required': 'optional' }, 'address_family': { 'class': basestring, 'is_list': False, 'required': 'optional' }, }
|
Routing group route information
When returned as part of the output, all elements of this typedef
are reported, unless limited by a set of desired attributes
specified by the caller.
<p>
When used as input to specify desired attributes to return,
omitting a given element indicates that it shall not be returned
in the output. In contrast, by providing an element (even with
no value) the caller ensures that a value for that element will
be returned, given that the value can be retrieved.
<p>
When used as input to specify queries, any element can be omitted
in which case the resulting set of objects is not constrained by
any specific value of that attribute.
|
6259901456b00c62f0fb35b2
|
class Patient(object): <NEW_LINE> <INDENT> def __init__(self, viruses, maxPop): <NEW_LINE> <INDENT> self.viruses = viruses <NEW_LINE> self.maxPop = maxPop <NEW_LINE> <DEDENT> def getViruses(self): <NEW_LINE> <INDENT> return self.viruses <NEW_LINE> <DEDENT> def getMaxPop(self): <NEW_LINE> <INDENT> return self.maxPop <NEW_LINE> <DEDENT> def getTotalPop(self): <NEW_LINE> <INDENT> return len(self.viruses) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> for virus in self.viruses[:]: <NEW_LINE> <INDENT> if virus.doesClear(): <NEW_LINE> <INDENT> self.viruses.remove(virus) <NEW_LINE> <DEDENT> <DEDENT> popDensity = float(self.getTotalPop()) / self.getMaxPop() <NEW_LINE> new_viruses = [] <NEW_LINE> for virus in self.viruses: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> new_virus = virus.reproduce(popDensity) <NEW_LINE> self.new_viruses.append(new_virus) <NEW_LINE> <DEDENT> except NoChildException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> self.viruses += new_viruses <NEW_LINE> return self.getTotalPop()
|
Representation of a simplified patient. The patient does not take any drugs
and his/her virus populations have no drug resistance.
|
62599014507cdc57c63a5a96
|
class Is(StaticType): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def matches(self, value): <NEW_LINE> <INDENT> return self.value == value
|
A static type that matches a value if the value is equal, as determined by
the == operator, to a specified value.
|
6259901456b00c62f0fb35b4
|
class optimizer(): <NEW_LINE> <INDENT> def __init__(self, file_name): <NEW_LINE> <INDENT> self.file_name = file_name <NEW_LINE> self.file = self.load_file() <NEW_LINE> self.best = "" <NEW_LINE> self.find_best() <NEW_LINE> <DEDENT> def load_file(self): <NEW_LINE> <INDENT> with open(self.file_name, "r") as fi: <NEW_LINE> <INDENT> return json.load(fi) <NEW_LINE> <DEDENT> <DEDENT> def find_best(self): <NEW_LINE> <INDENT> highscore = 0 <NEW_LINE> for block in self.file: <NEW_LINE> <INDENT> cblock = self.file[block] <NEW_LINE> if cblock["efficiency"] and cblock["power"] and cblock["thrust"] and cblock["weight"] != "0": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> score = self.calculate_score( cblock["efficiency"], cblock["power"], cblock["thrust"], cblock["weight"]) <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> print(cblock) <NEW_LINE> <DEDENT> if score > highscore: <NEW_LINE> <INDENT> self.best = block <NEW_LINE> highscore = score <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> print(self.best) <NEW_LINE> <DEDENT> def calculate_score(self, eff, power, thrust, weight): <NEW_LINE> <INDENT> score = float(eff) / float(weight) + float(eff) / float(thrust) <NEW_LINE> return score
|
Find the most optimized motor based of a list of motors.
|
62599014507cdc57c63a5a98
|
class Regex(object): <NEW_LINE> <INDENT> def __init__(self, regex, flags=0): <NEW_LINE> <INDENT> self.regex = compile(regex, flags) <NEW_LINE> <DEDENT> def is_match(self, str): <NEW_LINE> <INDENT> return match(self.regex, str)
|
Wrapper class for regular expressions.
|
625990149b70327d1c57fa79
|
class LogNorm(Normalize): <NEW_LINE> <INDENT> def __call__(self, value, clip=None): <NEW_LINE> <INDENT> if clip is None: <NEW_LINE> <INDENT> clip = self.clip <NEW_LINE> <DEDENT> result, is_scalar = self.process_value(value) <NEW_LINE> result = np.ma.masked_less_equal(result, 0, copy=False) <NEW_LINE> self.autoscale_None(result) <NEW_LINE> vmin, vmax = self.vmin, self.vmax <NEW_LINE> if vmin > vmax: <NEW_LINE> <INDENT> raise ValueError("minvalue must be less than or equal to maxvalue") <NEW_LINE> <DEDENT> elif vmin <= 0: <NEW_LINE> <INDENT> raise ValueError("values must all be positive") <NEW_LINE> <DEDENT> elif vmin == vmax: <NEW_LINE> <INDENT> result.fill(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if clip: <NEW_LINE> <INDENT> mask = np.ma.getmask(result) <NEW_LINE> result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax), mask=mask) <NEW_LINE> <DEDENT> resdat = result.data <NEW_LINE> mask = result.mask <NEW_LINE> if mask is np.ma.nomask: <NEW_LINE> <INDENT> mask = (resdat <= 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mask |= resdat <= 0 <NEW_LINE> <DEDENT> np.copyto(resdat, 1, where=mask) <NEW_LINE> np.log(resdat, resdat) <NEW_LINE> resdat -= np.log(vmin) <NEW_LINE> resdat /= (np.log(vmax) - np.log(vmin)) <NEW_LINE> result = np.ma.array(resdat, mask=mask, copy=False) <NEW_LINE> <DEDENT> if is_scalar: <NEW_LINE> <INDENT> result = result[0] <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def inverse(self, value): <NEW_LINE> <INDENT> if not self.scaled(): <NEW_LINE> <INDENT> raise ValueError("Not invertible until scaled") <NEW_LINE> <DEDENT> vmin, vmax = self.vmin, self.vmax <NEW_LINE> if cbook.iterable(value): <NEW_LINE> <INDENT> val = np.ma.asarray(value) <NEW_LINE> return vmin * np.ma.power((vmax / vmin), val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return vmin * pow((vmax / vmin), value) <NEW_LINE> <DEDENT> <DEDENT> def autoscale(self, A): <NEW_LINE> <INDENT> A = np.ma.masked_less_equal(A, 0, copy=False) <NEW_LINE> self.vmin = np.ma.min(A) <NEW_LINE> self.vmax = np.ma.max(A) <NEW_LINE> <DEDENT> def autoscale_None(self, A): <NEW_LINE> <INDENT> if self.vmin is not None and self.vmax is not None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> A = np.ma.masked_less_equal(A, 0, copy=False) <NEW_LINE> if self.vmin is None: <NEW_LINE> <INDENT> self.vmin = np.ma.min(A) <NEW_LINE> <DEDENT> if self.vmax is None: <NEW_LINE> <INDENT> self.vmax = np.ma.max(A)
|
Normalize a given value to the 0-1 range on a log scale
|
62599014d164cc6175821c78
|
class Process(models.Model): <NEW_LINE> <INDENT> process = models.CharField(max_length=32, null=False, verbose_name='流程名', help_text='流程名', unique=True) <NEW_LINE> create_time = models.DateTimeField(auto_now_add=True, null=True, verbose_name='创建时间', help_text='创建时间') <NEW_LINE> remark = models.CharField(max_length=32, null=True, verbose_name='备注', help_text='备注') <NEW_LINE> flow = models.CharField(max_length=100, null=False, verbose_name='审批链条', help_text='审批链条') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = verbose_name = '审批流程' <NEW_LINE> db_table = 'process' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.process
|
审批流程表
|
62599014bf627c535bcb21aa
|
class ReleaseEventComboBox(Gtk.HBox): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ReleaseEventComboBox, self).__init__() <NEW_LINE> self.model = Gtk.ListStore(object, str) <NEW_LINE> self.combo = Gtk.ComboBox(model=self.model) <NEW_LINE> render = Gtk.CellRendererText() <NEW_LINE> self.combo.pack_start(render, True) <NEW_LINE> self.combo.add_attribute(render, "markup", 1) <NEW_LINE> self.combo.set_sensitive(False) <NEW_LINE> self.label = Gtk.Label(label=_("_Release:"), use_underline=True) <NEW_LINE> self.label.set_use_underline(True) <NEW_LINE> self.label.set_mnemonic_widget(self.combo) <NEW_LINE> self.pack_start(self.label, False, True, 0) <NEW_LINE> self.pack_start(self.combo, True, True, 0) <NEW_LINE> <DEDENT> def update(self, release): <NEW_LINE> <INDENT> self.model.clear() <NEW_LINE> events = release.getReleaseEvents() <NEW_LINE> events.sort(key=lambda e: (bool(not e.getCatalogNumber()), e.getDate() or '9999-12-31')) <NEW_LINE> for rel_event in events: <NEW_LINE> <INDENT> text = '%s %s: <b>%s</b> <i>(%s)</i>' % ( rel_event.getDate() or '', rel_event.getLabel() or '', rel_event.getCatalogNumber(), rel_event.getCountry()) <NEW_LINE> self.model.append((rel_event, text)) <NEW_LINE> <DEDENT> if len(events) > 0: <NEW_LINE> <INDENT> self.combo.set_active(0) <NEW_LINE> <DEDENT> self.combo.set_sensitive((len(events) > 0)) <NEW_LINE> text = ngettext("%d _release:", "%d _releases:", len(events)) <NEW_LINE> self.label.set_text(text % len(events)) <NEW_LINE> self.label.set_use_underline(True) <NEW_LINE> <DEDENT> def get_release_event(self): <NEW_LINE> <INDENT> itr = self.combo.get_active_iter() <NEW_LINE> if itr: <NEW_LINE> <INDENT> return self.model[itr][0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
|
A ComboBox for picking a release event.
|
625990149b70327d1c57fa7b
|
class Variety(models.Model): <NEW_LINE> <INDENT> variety = models.CharField(max_length=45, blank=False) <NEW_LINE> seed_color = models.CharField(max_length=75) <NEW_LINE> parts_to_harvest = models.TextField() <NEW_LINE> unique_characteristics = models.TextField() <NEW_LINE> planting_intructions = models.TextField() <NEW_LINE> scientific_name = models.ForeignKey(ScientificName) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.variety
|
TODO: Description of class
|
625990145166f23b2e2440cc
|
class Window (gtk.Window): <NEW_LINE> <INDENT> def __init__ (self, ident): <NEW_LINE> <INDENT> self.ident = ident <NEW_LINE> gtk.Window.__init__(self) <NEW_LINE> w, h = settings['win_size_{}'.format(ident)][:2] <NEW_LINE> self.set_default_size(w, h) <NEW_LINE> if settings['win_max_{}'.format(ident)]: <NEW_LINE> <INDENT> self.maximize() <NEW_LINE> <DEDENT> self.connect('size-allocate', self._size_cb) <NEW_LINE> self.connect('window-state-event', self._state_cb) <NEW_LINE> <DEDENT> def _size_cb (self, w, size): <NEW_LINE> <INDENT> if not settings['win_max_{}'.format(self.ident)]: <NEW_LINE> <INDENT> settings['win_size_{}'.format(self.ident)] = (size.width, size.height) <NEW_LINE> <DEDENT> <DEDENT> def _state_cb (self, w, e): <NEW_LINE> <INDENT> is_max = e.new_window_state & gdk.WindowState.MAXIMIZED <NEW_LINE> settings['win_max_{}'.format(self.ident)] = bool(is_max)
|
A Gtk.Window subclass that saves its size.
Takes a string identifier used in the setting keys.
|
62599014d164cc6175821c7a
|
class FirebirdTests(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> print('=' * 80) <NEW_LINE> print('Begin Firebird test') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> print('End Firebird test') <NEW_LINE> print('=' * 80) <NEW_LINE> <DEDENT> @skipUnless(db.backend_name == "firebird", "Firebird-only test") <NEW_LINE> def test_firebird_double_index_creation_1317(self): <NEW_LINE> <INDENT> Test = db.mock_model(model_name='Test', db_table='test5a', db_tablespace='', pk_field_name='ID', pk_field_type=models.AutoField, pk_field_args=[] ) <NEW_LINE> db.create_table("test5a", [('ID', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True))]) <NEW_LINE> db.create_table("test5b", [ ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('UNIQUE', models.ForeignKey(Test)), ]) <NEW_LINE> db.execute_deferred_sql()
|
Tests firebird related issues
|
6259901456b00c62f0fb35ba
|
class UserProfileManager(BaseUserManager): <NEW_LINE> <INDENT> def create_user(self, email, name, password=None): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError('Users must have an email address.') <NEW_LINE> <DEDENT> email = self.normalize_email(email) <NEW_LINE> user = self.model(email=email, name=name) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_superuser(self, email, name, password): <NEW_LINE> <INDENT> user = self.create_user(email, name, password) <NEW_LINE> user.is_superuser = True <NEW_LINE> user.is_staff = True <NEW_LINE> user.save(using=self._db)
|
Helps Django work with our custom user model
|
6259901421a7993f00c66c79
|
class ResourceMockView(View): <NEW_LINE> <INDENT> class MockForm(forms.Form): <NEW_LINE> <INDENT> foo = forms.BooleanField(required=False) <NEW_LINE> bar = forms.IntegerField(help_text='Must be an integer.') <NEW_LINE> baz = forms.CharField(max_length=32) <NEW_LINE> <DEDENT> form = MockForm
|
This is a resource-based mock view
|
625990149b70327d1c57fa7d
|
class Application(tk.Tk): <NEW_LINE> <INDENT> red, red_hover = "#e74c3c", "#c0392b" <NEW_LINE> orange, orange_hover = "#e67e22", "#d35400" <NEW_LINE> yellow, yellow_hover = "#f1c40f", "#f39c12" <NEW_LINE> green, green_hover = "#2ecc71", "#27ae60" <NEW_LINE> blue, blue_hover = "#3498db", "#2980b9" <NEW_LINE> gray, gray_hover = "#95a5a6", "#7f8c8d" <NEW_LINE> purple, purple_hover = "#9b59b6", "#8e44ad" <NEW_LINE> black = "#000000" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> tk.Tk.__init__(self) <NEW_LINE> self.title("Info") <NEW_LINE> self.info = tk.Label( master=self, text="--- / ---", font=("Helvetica", 24, "bold"), relief=tk.FLAT, disabledforeground=self.black, ) <NEW_LINE> self.info.pack(fill=tk.BOTH, expand=True) <NEW_LINE> self.info.bind("<Button-1>", self.show_details) <NEW_LINE> self.statustext = tk.StringVar() <NEW_LINE> self.statustext.set("status bar") <NEW_LINE> self.statusbar = tk.Label(master=self, textvariable=self.statustext, font=("Helvetica", 10)) <NEW_LINE> self.statusbar.pack(side=tk.BOTTOM, fill=tk.X, expand=True) <NEW_LINE> self.bind("<Key>", self.keypress) <NEW_LINE> self.set_neutral() <NEW_LINE> <DEDENT> def set_color(self, color, active_color, state=tk.NORMAL): <NEW_LINE> <INDENT> self.info["background"] = color <NEW_LINE> self.info["activebackground"] = active_color <NEW_LINE> self.info["state"] = state <NEW_LINE> <DEDENT> def set_error(self): <NEW_LINE> <INDENT> self.set_color(self.red, self.red_hover) <NEW_LINE> <DEDENT> def set_failure(self): <NEW_LINE> <INDENT> self.set_color(self.orange, self.orange_hover) <NEW_LINE> <DEDENT> def set_issues(self): <NEW_LINE> <INDENT> self.set_color(self.yellow, self.yellow_hover) <NEW_LINE> <DEDENT> def set_success(self): <NEW_LINE> <INDENT> self.set_color(self.green, self.green_hover, tk.DISABLED) <NEW_LINE> <DEDENT> def set_processing(self): <NEW_LINE> <INDENT> self.set_color(self.blue, self.blue_hover, tk.DISABLED) <NEW_LINE> <DEDENT> def set_neutral(self): <NEW_LINE> <INDENT> self.set_color(self.gray, self.gray_hover, tk.DISABLED) <NEW_LINE> <DEDENT> def keypress(self, event): <NEW_LINE> <INDENT> logging.info("Key [{}] pressed".format(event.char)) <NEW_LINE> if event.char == "r": <NEW_LINE> <INDENT> self.set_error() <NEW_LINE> <DEDENT> elif event.char == "o": <NEW_LINE> <INDENT> self.set_failure() <NEW_LINE> <DEDENT> elif event.char == "y": <NEW_LINE> <INDENT> self.set_issues() <NEW_LINE> <DEDENT> elif event.char == "g": <NEW_LINE> <INDENT> self.set_success() <NEW_LINE> <DEDENT> elif event.char == "b": <NEW_LINE> <INDENT> self.set_processing() <NEW_LINE> <DEDENT> elif event.char == "v": <NEW_LINE> <INDENT> self.set_color(self.purple, self.purple_hover) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.set_neutral() <NEW_LINE> <DEDENT> <DEDENT> def show_details(self, event): <NEW_LINE> <INDENT> interval = 3 <NEW_LINE> logging.info("showing details...") <NEW_LINE> self.statustext.set(datetime.datetime.now().isoformat())
|
Simple Application with a text entry controlled by two buttons.
|
62599014a8ecb03325871f1f
|
class Scenario(object): <NEW_LINE> <INDENT> def __init__(self, feature, name, line_number, example_converters=None, tags=None): <NEW_LINE> <INDENT> self.feature = feature <NEW_LINE> self.name = name <NEW_LINE> self.params = set() <NEW_LINE> self.steps = [] <NEW_LINE> self.example_params = [] <NEW_LINE> self.examples = [] <NEW_LINE> self.vertical_examples = [] <NEW_LINE> self.line_number = line_number <NEW_LINE> self.example_converters = example_converters <NEW_LINE> self.tags = tags or set() <NEW_LINE> self.failed = False <NEW_LINE> self.test_function = None <NEW_LINE> <DEDENT> def add_step(self, step): <NEW_LINE> <INDENT> self.params.update(step.params) <NEW_LINE> self.steps.append(step) <NEW_LINE> <DEDENT> def set_background(self, background): <NEW_LINE> <INDENT> for step in background.steps: <NEW_LINE> <INDENT> self.add_step(step) <NEW_LINE> <DEDENT> <DEDENT> def set_param_names(self, keys): <NEW_LINE> <INDENT> self.example_params = [str(key) for key in keys] <NEW_LINE> <DEDENT> def add_example(self, values): <NEW_LINE> <INDENT> self.examples.append(values) <NEW_LINE> <DEDENT> def add_example_row(self, param, values): <NEW_LINE> <INDENT> if param in self.example_params: <NEW_LINE> <INDENT> raise exceptions.ScenarioExamplesNotValidError( """Scenario "{0}" in the feature "{1}" has not valid examples. """ """Example rows should contain unique parameters. {2} appeared more than once.""".format( self.name, self.feature.filename, param, ) ) <NEW_LINE> <DEDENT> self.example_params.append(param) <NEW_LINE> self.vertical_examples.append(values) <NEW_LINE> <DEDENT> def get_params(self): <NEW_LINE> <INDENT> param_count = len(self.example_params) <NEW_LINE> if self.vertical_examples and not self.examples: <NEW_LINE> <INDENT> for value_index in range(len(self.vertical_examples[0])): <NEW_LINE> <INDENT> example = [] <NEW_LINE> for param_index in range(param_count): <NEW_LINE> <INDENT> example.append(self.vertical_examples[param_index][value_index]) <NEW_LINE> <DEDENT> self.examples.append(example) <NEW_LINE> <DEDENT> <DEDENT> if self.examples: <NEW_LINE> <INDENT> params = [] <NEW_LINE> for example in self.examples: <NEW_LINE> <INDENT> for index, param in enumerate(self.example_params): <NEW_LINE> <INDENT> if self.example_converters and param in self.example_converters: <NEW_LINE> <INDENT> example[index] = self.example_converters[param](example[index]) <NEW_LINE> <DEDENT> <DEDENT> params.append(example) <NEW_LINE> <DEDENT> return [self.example_params, params] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if self.params and self.example_params and self.params != set(self.example_params): <NEW_LINE> <INDENT> raise exceptions.ScenarioExamplesNotValidError( """Scenario "{0}" in the feature "{1}" has not valid examples. """ """Set of step parameters {2} should match set of example values {3}.""".format( self.name, self.feature.filename, sorted(self.params), sorted(self.example_params), ) )
|
Scenario.
|
62599014d18da76e235b77ce
|
class PyWcsaxes(PythonPackage): <NEW_LINE> <INDENT> homepage = "http://wcsaxes.readthedocs.io/en/latest/index.html" <NEW_LINE> url = "https://github.com/astrofrog/wcsaxes/archive/v0.8.tar.gz" <NEW_LINE> version('0.8', sha256='9c6addc1ec04cc99617850354b2c03dbd4099d2e43b45a81f8bc3069de9c8e83') <NEW_LINE> extends('python', ignore=r'bin/') <NEW_LINE> depends_on('py-setuptools', type='build') <NEW_LINE> depends_on('py-numpy', type=('build', 'run')) <NEW_LINE> depends_on('py-matplotlib', type=('build', 'run')) <NEW_LINE> depends_on('py-astropy', type=('build', 'run'))
|
WCSAxes is a framework for making plots of Astronomical data
in Matplotlib.
|
625990149b70327d1c57fa81
|
class TabCompletionRegistry(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._comp_dict = {} <NEW_LINE> <DEDENT> def register_tab_comp_context(self, context_words, comp_items): <NEW_LINE> <INDENT> if not isinstance(context_words, list): <NEW_LINE> <INDENT> raise TypeError("Incorrect type in context_list: Expected list, got %s" % type(context_words)) <NEW_LINE> <DEDENT> if not isinstance(comp_items, list): <NEW_LINE> <INDENT> raise TypeError("Incorrect type in comp_items: Expected list, got %s" % type(comp_items)) <NEW_LINE> <DEDENT> sorted_comp_items = sorted(comp_items) <NEW_LINE> for context_word in context_words: <NEW_LINE> <INDENT> self._comp_dict[context_word] = sorted_comp_items <NEW_LINE> <DEDENT> <DEDENT> def deregister_context(self, context_words): <NEW_LINE> <INDENT> for context_word in context_words: <NEW_LINE> <INDENT> if context_word not in self._comp_dict: <NEW_LINE> <INDENT> raise KeyError("Cannot deregister unregistered context word \"%s\"" % context_word) <NEW_LINE> <DEDENT> <DEDENT> for context_word in context_words: <NEW_LINE> <INDENT> del self._comp_dict[context_word] <NEW_LINE> <DEDENT> <DEDENT> def extend_comp_items(self, context_word, new_comp_items): <NEW_LINE> <INDENT> if context_word not in self._comp_dict: <NEW_LINE> <INDENT> raise KeyError("Context word \"%s\" has not been registered" % context_word) <NEW_LINE> <DEDENT> self._comp_dict[context_word].extend(new_comp_items) <NEW_LINE> self._comp_dict[context_word] = sorted(self._comp_dict[context_word]) <NEW_LINE> <DEDENT> def remove_comp_items(self, context_word, comp_items): <NEW_LINE> <INDENT> if context_word not in self._comp_dict: <NEW_LINE> <INDENT> raise KeyError("Context word \"%s\" has not been registered" % context_word) <NEW_LINE> <DEDENT> for item in comp_items: <NEW_LINE> <INDENT> self._comp_dict[context_word].remove(item) <NEW_LINE> <DEDENT> <DEDENT> def get_completions(self, context_word, prefix): <NEW_LINE> <INDENT> if context_word not in self._comp_dict: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> comp_items = self._comp_dict[context_word] <NEW_LINE> return sorted([item for item in comp_items if item.startswith(prefix)])
|
Registry for tab completion responses.
|
62599014bf627c535bcb21b2
|
class NestActivityZoneSensor(NestBinarySensor): <NEW_LINE> <INDENT> def __init__(self, structure, device, zone): <NEW_LINE> <INDENT> super(NestActivityZoneSensor, self).__init__(structure, device, "") <NEW_LINE> self.zone = zone <NEW_LINE> self._name = "{} {} activity".format(self._name, self.zone.name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self._state = self.device.has_ongoing_motion_in_zone(self.zone.zone_id)
|
Represents a Nest binary sensor for activity in a zone.
|
625990148c3a8732951f7265
|
class overridable_property(cachedproperty): <NEW_LINE> <INDENT> __unset__ = None <NEW_LINE> def __get__(self, obj, cls): <NEW_LINE> <INDENT> obj = self.__gettarget__(obj) <NEW_LINE> value = getattr(obj, self.__hidden_name__, self.__unset__) <NEW_LINE> return self.__func__(obj) if value is self.__unset__ else value
|
A property that works like a normal property, but can be overridden.
|
62599014507cdc57c63a5aa4
|
class ChooseAuthenticatorTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> zope.component.provideUtility(display_util.FileDisplay(sys.stdout)) <NEW_LINE> self.mock_apache = mock.Mock() <NEW_LINE> self.mock_stand = mock.Mock() <NEW_LINE> self.mock_apache().more_info.return_value = "Apache Info" <NEW_LINE> self.mock_stand().more_info.return_value = "Standalone Info" <NEW_LINE> self.auths = [self.mock_apache, self.mock_stand] <NEW_LINE> self.errs = {self.mock_apache: "This is an error message."} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _call(cls, auths, errs): <NEW_LINE> <INDENT> from letsencrypt.client.display.ops import choose_authenticator <NEW_LINE> return choose_authenticator(auths, errs) <NEW_LINE> <DEDENT> @mock.patch("letsencrypt.client.display.ops.util") <NEW_LINE> def test_successful_choice(self, mock_util): <NEW_LINE> <INDENT> mock_util().menu.return_value = (display_util.OK, 0) <NEW_LINE> ret = self._call(self.auths, {}) <NEW_LINE> self.assertEqual(ret, self.mock_apache) <NEW_LINE> <DEDENT> @mock.patch("letsencrypt.client.display.ops.util") <NEW_LINE> def test_more_info(self, mock_util): <NEW_LINE> <INDENT> mock_util().menu.side_effect = [ (display_util.HELP, 0), (display_util.HELP, 1), (display_util.OK, 1), ] <NEW_LINE> ret = self._call(self.auths, self.errs) <NEW_LINE> self.assertEqual(mock_util().notification.call_count, 2) <NEW_LINE> self.assertEqual(ret, self.mock_stand) <NEW_LINE> <DEDENT> @mock.patch("letsencrypt.client.display.ops.util") <NEW_LINE> def test_no_choice(self, mock_util): <NEW_LINE> <INDENT> mock_util().menu.return_value = (display_util.CANCEL, 0) <NEW_LINE> self.assertTrue(self._call(self.auths, {}) is None)
|
Test choose_authenticator function.
|
62599014507cdc57c63a5aa6
|
class CSRF(v.Validator): <NEW_LINE> <INDENT> name = "csrf" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def populate(self, name): <NEW_LINE> <INDENT> if flask.session.get("_csrf_token") is None: <NEW_LINE> <INDENT> token = base64.b64encode(os.urandom(24)) <NEW_LINE> flask.session["_csrf_token"] = token.decode('utf8') <NEW_LINE> <DEDENT> return { "name": name, "token": flask.session["_csrf_token"], "tag": '<input type="hidden" name="%s" value="%s" />' % ( name, flask.session["_csrf_token"]) } <NEW_LINE> <DEDENT> def validate(self, key, value): <NEW_LINE> <INDENT> token = flask.session.get("_csrf_token") <NEW_LINE> if token is None: <NEW_LINE> <INDENT> raise InvalidSessionError() <NEW_LINE> <DEDENT> elif value != token: <NEW_LINE> <INDENT> self.raise_error(key, value)
|
Create a CSRF token and ensure that the token exists (and matches that
of the form) when serving and processing forms.
Only usable with the Flask engine.
:usage:
@app.route("/")
@sb.validator({
"csrf": sb.CSRF(),
})
def index():
# Your code here
pass
|
6259901421a7993f00c66c81
|
class LocalDiscogsConnector(object): <NEW_LINE> <INDENT> def __init__(self, delegate_discogs_connector): <NEW_LINE> <INDENT> self.delegate = delegate_discogs_connector <NEW_LINE> <DEDENT> def fetch_release(self, release_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def fetch_release(self, release_id, source_dir): <NEW_LINE> <INDENT> dummy_response = DummyResponse(release_id, source_dir) <NEW_LINE> client = discogs.Client('Dummy Client - just for testing') <NEW_LINE> self.content = self.convert(json.loads(dummy_response.content)) <NEW_LINE> logger.debug('content: %s' % self.content) <NEW_LINE> release = discogs.Release(client, self.content) <NEW_LINE> return release <NEW_LINE> <DEDENT> def authenticate(self): <NEW_LINE> <INDENT> self.delegate.authenticate() <NEW_LINE> <DEDENT> def fetch_image(self, image_dir, image_url): <NEW_LINE> <INDENT> self.delegate.fetch_image(image_dir, image_url) <NEW_LINE> <DEDENT> def updateRateLimits(self, request): <NEW_LINE> <INDENT> self.delegate.updateRateLimits(request) <NEW_LINE> <DEDENT> def convert(self, input): <NEW_LINE> <INDENT> if isinstance(input, dict): <NEW_LINE> <INDENT> return {self.convert(key): self.convert(value) for key, value in input.iteritems()} <NEW_LINE> <DEDENT> elif isinstance(input, list): <NEW_LINE> <INDENT> return [self.convert(element) for element in input] <NEW_LINE> <DEDENT> elif isinstance(input, unicode): <NEW_LINE> <INDENT> return input.encode('utf-8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return input
|
use local json, do not fetch json from discogs, instead use the one in the source_directory
We will need to use the Original DiscogsConnector to allow the usage of the authentication
for fetching images.
|
62599014d18da76e235b77d0
|
class Track(object): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.trackId = None <NEW_LINE> self.trackfile = None <NEW_LINE> self.trackMinPressure = None <NEW_LINE> self.trackMaxWind = None <NEW_LINE> <DEDENT> def __getattr__(self, key): <NEW_LINE> <INDENT> if key.startswith('__') and key.endswith('__'): <NEW_LINE> <INDENT> return super(Track, self).__getattr__(key) <NEW_LINE> <DEDENT> return self.data[key] <NEW_LINE> <DEDENT> def inRegion(self, gridLimit): <NEW_LINE> <INDENT> xMin = gridLimit['xMin'] <NEW_LINE> xMax = gridLimit['xMax'] <NEW_LINE> yMin = gridLimit['yMin'] <NEW_LINE> yMax = gridLimit['yMax'] <NEW_LINE> return ((xMin <= np.min(self.Longitude)) and (np.max(self.Latitude) <= xMax) and (yMin <= np.min(self.Latitude)) and (np.max(self.Latitude) <= yMax))
|
A single tropical cyclone track.
The object exposes the track data through the object attributes.
For example, If `data` contains the tropical cyclone track data
(`numpy.array`) loaded with the :meth:`readTrackData` function,
then the central pressure column can be printed out with the
code::
t = Track(data)
print(t.CentralPressure)
:type data: numpy.ndarray
:param data: the tropical cyclone track data.
|
62599014d164cc6175821c84
|
class StockDataAnalysis(Data, metaclass=ABCMeta): <NEW_LINE> <INDENT> data_type = DataType.STOCK_DATA_ANALYSIS <NEW_LINE> def __init__(self, dependencies=None, visible=True): <NEW_LINE> <INDENT> super(StockDataAnalysis, self).__init__(dependencies, visible)
|
Base class for storing stock data analysis.
|
6259901456b00c62f0fb35c4
|
class FileStore: <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.path = os.path.abspath(path)
|
must exist
|
625990149b70327d1c57fa87
|
class ContactSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> resume = ResumesSerializer() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Contact <NEW_LINE> fields = [ 'id', 'resume', 'email', 'phone', 'social_networks', 'updated_at' ]
|
Serializer for contact resource.
|
62599014be8e80087fbbfd7a
|
class HostConfigurer(Configurable): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(HostConfigurer, self).__init__(*args, **kwargs) <NEW_LINE> self.setter = InteractiveConfigurationSetter("host", add_cwd=False, add_logging=False) <NEW_LINE> self.definition = None <NEW_LINE> self.host_config = None <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.setup() <NEW_LINE> self.load_template() <NEW_LINE> self.prompt() <NEW_LINE> self.write() <NEW_LINE> self.show() <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> super(HostConfigurer, self).setup() <NEW_LINE> <DEDENT> def load_template(self): <NEW_LINE> <INDENT> if self.config.preconfigured is None: template_path = raw_template_path <NEW_LINE> else: template_path = fs.join(hosts_config_path, self.config.preconfigured + ".cfg") <NEW_LINE> self.definition = ConfigurationDefinition.from_file(template_path, write_config=False) <NEW_LINE> <DEDENT> def prompt(self): <NEW_LINE> <INDENT> self.host_config = self.setter.run(self.definition, prompt_optional=True) <NEW_LINE> <DEDENT> def write(self): <NEW_LINE> <INDENT> self.write_config() <NEW_LINE> <DEDENT> def write_config(self): <NEW_LINE> <INDENT> path = fs.join(hosts_directory, self.config.name + ".cfg") <NEW_LINE> self.host_config.saveto(path) <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> log.info("Showing the settings ...") <NEW_LINE> kwargs = dict() <NEW_LINE> kwargs["round"] = True <NEW_LINE> kwargs["scientific"] = True <NEW_LINE> kwargs["ndigits"] = 3 <NEW_LINE> print("") <NEW_LINE> with fmt.print_in_columns(3, delimiter=" ", indent=" ", tostr_kwargs=kwargs) as print_row: <NEW_LINE> <INDENT> for name in self.host_config.keys(): <NEW_LINE> <INDENT> if name.startswith("_"): continue <NEW_LINE> if isinstance(self.host_config[name], Map): <NEW_LINE> <INDENT> prefix = name <NEW_LINE> for nname in self.host_config[name].keys(): <NEW_LINE> <INDENT> value = self.host_config[name][nname] <NEW_LINE> the_name = prefix + "/" + nname <NEW_LINE> print_row(the_name, ":", value) <NEW_LINE> <DEDENT> <DEDENT> else: print_row(name, ":", self.host_config[name]) <NEW_LINE> <DEDENT> <DEDENT> print("")
|
This class ...
|
62599014507cdc57c63a5aaa
|
class Buyer(Worker): <NEW_LINE> <INDENT> def __init__(self, db, buyer_name='Zissou', **kwargs): <NEW_LINE> <INDENT> super(Buyer, self).__init__(db, **kwargs) <NEW_LINE> self.buyer_name = str(buyer_name) <NEW_LINE> <DEDENT> def buy_item(self, row, date, price): <NEW_LINE> <INDENT> if not row.sale == 0: <NEW_LINE> <INDENT> raise RuntimeError('item already sold!') <NEW_LINE> <DEDENT> row.buyer_name = self.buyer_name <NEW_LINE> row.sell_date = AuctionHouse.validate_date(date) <NEW_LINE> row.sale = AuctionHouse.validate_price(price) <NEW_LINE> self.info('%s', row)
|
Auction House buyer.
:param db: database object
|
625990145166f23b2e2440da
|
class EffectiveRouteListResult(Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[EffectiveRoute]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(EffectiveRouteListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None)
|
Response for list effective route API service call.
:param value: A list of effective routes.
:type value: list[~azure.mgmt.network.v2016_12_01.models.EffectiveRoute]
:param next_link: The URL to get the next set of results.
:type next_link: str
|
625990149b70327d1c57fa89
|
class FixOrderingView(BrowserView): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> return "Aborted, fixing ordering is only necessary on python 2." <NEW_LINE> catalog = getToolByName(self.context, "portal_catalog") <NEW_LINE> for brain in catalog.unrestrictedSearchResults(QUERY): <NEW_LINE> <INDENT> folderish = brain.getObject() <NEW_LINE> ensure_child_ordering_object_ids_are_native_strings(folderish) <NEW_LINE> <DEDENT> return "Done."
|
Attempt to fix ordering for all potentially affected objects.
By default will fix ordering object ids for every object that considers
itself folderish.
The problem only exists with python 2 so we do nothing when we are
called on python 3 by mistake.
|
62599014462c4b4f79dbc713
|
class NetworkSecurityGroupRule(Model): <NEW_LINE> <INDENT> _validation = { 'priority': {'required': True}, 'access': {'required': True}, 'source_address_prefix': {'required': True}, } <NEW_LINE> _attribute_map = { 'priority': {'key': 'priority', 'type': 'int'}, 'access': {'key': 'access', 'type': 'NetworkSecurityGroupRuleAccess'}, 'source_address_prefix': {'key': 'sourceAddressPrefix', 'type': 'str'}, 'source_port_ranges': {'key': 'sourcePortRanges', 'type': '[str]'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(NetworkSecurityGroupRule, self).__init__(**kwargs) <NEW_LINE> self.priority = kwargs.get('priority', None) <NEW_LINE> self.access = kwargs.get('access', None) <NEW_LINE> self.source_address_prefix = kwargs.get('source_address_prefix', None) <NEW_LINE> self.source_port_ranges = kwargs.get('source_port_ranges', None)
|
A network security group rule to apply to an inbound endpoint.
All required parameters must be populated in order to send to Azure.
:param priority: Required. The priority for this rule. Priorities within a
Pool must be unique and are evaluated in order of priority. The lower the
number the higher the priority. For example, rules could be specified with
order numbers of 150, 250, and 350. The rule with the order number of 150
takes precedence over the rule that has an order of 250. Allowed
priorities are 150 to 4096. If any reserved or duplicate values are
provided the request fails with HTTP status code 400.
:type priority: int
:param access: Required. Possible values include: 'allow', 'deny'
:type access: str or ~azure.batch.models.NetworkSecurityGroupRuleAccess
:param source_address_prefix: Required. Valid values are a single IP
address (i.e. 10.10.10.10), IP subnet (i.e. 192.168.1.0/24), default tag,
or * (for all addresses). If any other values are provided the request
fails with HTTP status code 400.
:type source_address_prefix: str
:param source_port_ranges: Valid values are '*' (for all ports 0 - 65535),
a specific port (i.e. 22), or a port range (i.e. 100-200). The ports must
be in the range of 0 to 65535. Each entry in this collection must not
overlap any other entry (either a range or an individual port). If any
other values are provided the request fails with HTTP status code 400. The
default value is '*'.
:type source_port_ranges: list[str]
|
6259901421a7993f00c66c87
|
class ClippedReLU(function_node.FunctionNode): <NEW_LINE> <INDENT> _use_cudnn = False <NEW_LINE> def __init__(self, z): <NEW_LINE> <INDENT> if not isinstance(z, float): <NEW_LINE> <INDENT> raise TypeError('z must be float value') <NEW_LINE> <DEDENT> assert z > 0 <NEW_LINE> self.cap = z <NEW_LINE> <DEDENT> def check_type_forward(self, in_types): <NEW_LINE> <INDENT> type_check._argname(in_types, ('x',)) <NEW_LINE> x_type = in_types[0] <NEW_LINE> type_check.expect(x_type.dtype.kind == 'f') <NEW_LINE> <DEDENT> def forward_cpu(self, inputs): <NEW_LINE> <INDENT> self.retain_inputs((0,)) <NEW_LINE> x, = inputs <NEW_LINE> return utils.force_array(numpy.minimum(numpy.maximum(0, x), self.cap), x.dtype), <NEW_LINE> <DEDENT> def forward_gpu(self, inputs): <NEW_LINE> <INDENT> self.retain_inputs((0,)) <NEW_LINE> x, = inputs <NEW_LINE> if chainer.should_use_cudnn('==always') and x.flags.c_contiguous: <NEW_LINE> <INDENT> self._use_cudnn = True <NEW_LINE> y = cudnn.activation_forward(x, _mode, self.cap) <NEW_LINE> self.retain_outputs((0,)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cuda.elementwise( 'T x, T cap', 'T y', 'y = min(max(x, (T)0), cap)', 'clipped_relu_fwd')(x, self.cap), <NEW_LINE> <DEDENT> return y, <NEW_LINE> <DEDENT> def backward(self, indexes, grad_outputs): <NEW_LINE> <INDENT> x, = self.get_retained_inputs() <NEW_LINE> if chainer.should_use_cudnn('==always') and self._use_cudnn: <NEW_LINE> <INDENT> y = self.get_retained_outputs()[0] <NEW_LINE> return ClippedReLUGrad3(x.data, y.data, self.cap).apply( grad_outputs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ClippedReLUGrad2(x.data, self.cap).apply(grad_outputs)
|
Clipped Rectifier Unit function.
Clipped ReLU is written as
:math:`ClippedReLU(x, z) = \min(\max(0, x), z)`,
where :math:`z(>0)` is a parameter to cap return value of ReLU.
|
6259901456b00c62f0fb35ca
|
class ActionLong(Action): <NEW_LINE> <INDENT> def __init__(self, title, start_callback, stop_callback): <NEW_LINE> <INDENT> Action.__init__(self, title) <NEW_LINE> self.__actions = [start_callback, stop_callback] <NEW_LINE> <DEDENT> def Down(self): <NEW_LINE> <INDENT> self.__actions[0]() <NEW_LINE> <DEDENT> def Up(self): <NEW_LINE> <INDENT> self.__actions[1]()
|
Action with start and stop callbacks
|
62599014bf627c535bcb21bc
|
class MvCommand(Command): <NEW_LINE> <INDENT> command_spec = { COMMAND_NAME : 'mv', COMMAND_NAME_ALIASES : ['move', 'ren', 'rename'], MIN_ARGS : 2, MAX_ARGS : NO_MAX, SUPPORTED_SUB_ARGS : 'pv', FILE_URIS_OK : True, PROVIDER_URIS_OK : False, URIS_START_ARG : 0, } <NEW_LINE> help_spec = { HELP_NAME : 'mv', HELP_NAME_ALIASES : ['move', 'rename'], HELP_TYPE : HelpType.COMMAND_HELP, HELP_ONE_LINE_SUMMARY : 'Move/rename objects and/or subdirectories', HELP_TEXT : _detailed_help_text, } <NEW_LINE> def RunCommand(self): <NEW_LINE> <INDENT> for arg_to_check in self.args[0:-1]: <NEW_LINE> <INDENT> if self.suri_builder.StorageUri(arg_to_check).names_bucket(): <NEW_LINE> <INDENT> raise CommandException('You cannot move a source bucket using the mv ' 'command. If you meant to move\nall objects in ' 'the bucket, you can use a command like:\n' '\tgsutil mv %s/* %s' % (arg_to_check, self.args[-1])) <NEW_LINE> <DEDENT> <DEDENT> unparsed_args = ['-M'] <NEW_LINE> if self.recursion_requested: <NEW_LINE> <INDENT> unparsed_args.append('-R') <NEW_LINE> <DEDENT> unparsed_args.extend(self.unparsed_args) <NEW_LINE> self.command_runner.RunNamedCommand('cp', unparsed_args, self.headers, self.debug, self.parallel_operations) <NEW_LINE> return 0
|
Implementation of gsutil mv command.
Note that there is no atomic rename operation - this command is simply
a shorthand for 'cp' followed by 'rm'.
|
625990148c3a8732951f726f
|
class PluginBase(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> @abc.abstractmethod <NEW_LINE> def get_code(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.get_code()
|
Base class definition for plugin.
|
62599014be8e80087fbbfd7f
|
class F99(GenericCurve): <NEW_LINE> <INDENT> def __init__(self, var=False): <NEW_LINE> <INDENT> self.default_pars(var=var) <NEW_LINE> self._f = self.f_90 <NEW_LINE> <DEDENT> def default_pars(self, var=False): <NEW_LINE> <INDENT> p = {} <NEW_LINE> p['R_v'] = 3.1 + var * normal(0, 0.6) <NEW_LINE> p['ospline_x'] = 1e4 / np.array([4100., 4670., 5470., 6000., 12200, 26500, 3e8]) <NEW_LINE> p['ospline_x'][-1] = 0. <NEW_LINE> p['c3'] = 3.23 + var * normal(0, 1.0) <NEW_LINE> p['c4'] = 0.41 + var * normal(0, 0.16) <NEW_LINE> p['x0'] = 4.596 + var * normal(0, 0.025) <NEW_LINE> p['gamma'] = 0.99 + var * normal(0, 0.1) <NEW_LINE> self.pardict = p <NEW_LINE> self.selfupdate() <NEW_LINE> <DEDENT> def selfupdate(self, var=False): <NEW_LINE> <INDENT> p = {} <NEW_LINE> p['R_v'] = self.pardict['R_v'] <NEW_LINE> self.pardict['c2'] = (-0.824 + 4.717 / p['R_v'] + var*normal(0, 0.25)) <NEW_LINE> self.pardict['c1'] = (2.02 - 3.007 * self.pardict['c2'] + var * normal(0, 0.3)) <NEW_LINE> sk = np.array([1.208 + 0.0032 * p['R_v'] - 0.00033 * p['R_v']**2, 0.701 + 0.0016 * p['R_v'], -0.050 + 0.0016 * p['R_v'], -0.426 + 0.0044 * p['R_v'], (0.829 / 3.1 - 1) * p['R_v'], (0.265 / 3.1 - 1) * p['R_v'], -p['R_v']]) <NEW_LINE> self.pardict['ospline_k'] = sk <NEW_LINE> <DEDENT> def ecurve(self, x, pardict): <NEW_LINE> <INDENT> uv = self.fm_curve(x, **pardict) * (x > 3.8) <NEW_LINE> spline_x = np.array([1e4 / 2600, 1e4 / 2700] + pardict['ospline_x'].tolist()) <NEW_LINE> spline_k = np.array(self.fm_curve(spline_x[0:2], **pardict).tolist() + pardict['ospline_k'].tolist()) <NEW_LINE> optical = self.spline(x, spline_x=spline_x[::-1], spline_k=spline_k[::-1]) * (x <= 3.8) <NEW_LINE> return uv + optical
|
Fitzpatrick 1999 R_v dependent extinction curves. These are a
one parameter family, though in practice we allow the bump
strength to vary.
|
6259901456b00c62f0fb35cc
|
class IcmpCode(Field): <NEW_LINE> <INDENT> pass
|
A icmp-code field.
|
62599014462c4b4f79dbc717
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.