code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class DevelopmentConfig(Config): <NEW_LINE> <INDENT> DEBUG =True <NEW_LINE> SQLALCHEMY_ECHO=True | Develpoment configurations | 62599063379a373c97d9a71a |
class ExportAsCombineAPIHandler(APIHandler): <NEW_LINE> <INDENT> @web.authenticated <NEW_LINE> def get(self): <NEW_LINE> <INDENT> log.warning("Export as combine function has not been cleaned up") <NEW_LINE> self.finish() <NEW_LINE> <DEDENT> @web.authenticated <NEW_LINE> def post(self): <NEW_LINE> <INDENT> log.warning("Export as combine w/meta data function has not been cleaned up") <NEW_LINE> self.finish() | ##############################################################################
Handler for exporting a project or part of a project as a COMBINE archive
############################################################################## | 6259906391f36d47f2231a0d |
class SaltLoadPillar(ioflo.base.deeding.Deed): <NEW_LINE> <INDENT> Ioinits = {'opts': '.salt.opts', 'pillar': '.salt.pillar', 'grains': '.salt.grains', 'modules': '.salt.loader.modules', 'pillar_refresh': '.salt.var.pillar_refresh', 'road_stack': '.salt.road.manor.stack', 'master_estate_name': '.salt.track.master_estate_name', } <NEW_LINE> def action(self): <NEW_LINE> <INDENT> available_masters = [remote for remote in list(self.road_stack.value.remotes.values()) if remote.allowed] <NEW_LINE> while not available_masters: <NEW_LINE> <INDENT> available_masters = [remote for remote in self.road_stack.value.remotes.values() if remote.allowed] <NEW_LINE> time.sleep(0.1) <NEW_LINE> <DEDENT> random_master = self.opts.value.get('random_master') <NEW_LINE> if random_master: <NEW_LINE> <INDENT> master = available_masters[random.randint(0, len(available_masters) - 1)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> master = available_masters[0] <NEW_LINE> <DEDENT> self.master_estate_name.value = master.name <NEW_LINE> route = {'src': (self.road_stack.value.local.name, None, None), 'dst': (master.name, None, 'remote_cmd')} <NEW_LINE> load = {'id': self.opts.value['id'], 'grains': self.grains.value, 'saltenv': self.opts.value['saltenv'], 'ver': '2', 'cmd': '_pillar'} <NEW_LINE> self.road_stack.value.transmit({'route': route, 'load': load}, uid=master.uid) <NEW_LINE> self.road_stack.value.serviceAll() <NEW_LINE> while True: <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> while self.road_stack.value.rxMsgs: <NEW_LINE> <INDENT> msg, sender = self.road_stack.value.rxMsgs.popleft() <NEW_LINE> self.pillar.value = msg.get('return', {}) <NEW_LINE> if self.pillar.value is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.opts.value['pillar'] = self.pillar.value <NEW_LINE> self.pillar_refresh.value = False <NEW_LINE> return <NEW_LINE> <DEDENT> self.road_stack.value.serviceAll() | Load up the initial pillar for the minion
do salt load pillar | 6259906355399d3f05627c1c |
class V1ListMeta(object): <NEW_LINE> <INDENT> swagger_types = { '_continue': 'str', 'resource_version': 'str', 'self_link': 'str' } <NEW_LINE> attribute_map = { '_continue': 'continue', 'resource_version': 'resourceVersion', 'self_link': 'selfLink' } <NEW_LINE> def __init__(self, _continue=None, resource_version=None, self_link=None): <NEW_LINE> <INDENT> self.__continue = None <NEW_LINE> self._resource_version = None <NEW_LINE> self._self_link = None <NEW_LINE> self.discriminator = None <NEW_LINE> if _continue is not None: <NEW_LINE> <INDENT> self._continue = _continue <NEW_LINE> <DEDENT> if resource_version is not None: <NEW_LINE> <INDENT> self.resource_version = resource_version <NEW_LINE> <DEDENT> if self_link is not None: <NEW_LINE> <INDENT> self.self_link = self_link <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def _continue(self): <NEW_LINE> <INDENT> return self.__continue <NEW_LINE> <DEDENT> @_continue.setter <NEW_LINE> def _continue(self, _continue): <NEW_LINE> <INDENT> self.__continue = _continue <NEW_LINE> <DEDENT> @property <NEW_LINE> def resource_version(self): <NEW_LINE> <INDENT> return self._resource_version <NEW_LINE> <DEDENT> @resource_version.setter <NEW_LINE> def resource_version(self, resource_version): <NEW_LINE> <INDENT> self._resource_version = resource_version <NEW_LINE> <DEDENT> @property <NEW_LINE> def self_link(self): <NEW_LINE> <INDENT> return self._self_link <NEW_LINE> <DEDENT> @self_link.setter <NEW_LINE> def self_link(self, self_link): <NEW_LINE> <INDENT> self._self_link = self_link <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1ListMeta): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 625990635166f23b2e244acf |
class ViewFavouriteIdeasSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> user_profile = UserProfileSerializer() <NEW_LINE> idea_feed = IdeaFeedItemSerializer() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = UserFavouriteIdeas <NEW_LINE> fields = ('id', 'user_profile', 'idea_feed') <NEW_LINE> extra_kwargs = {'user_profile': {'read_only': True}} | Serializes user favourite ideas | 6259906399cbb53fe68325df |
class ValidationResults(namedtuple('ValidationResults', _validation_fields)): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return ("Correct: " + str(len(self.correct)) + "\n" + "False positive: " + str(len(self.false_positive)) + "\n" + "False negative: " + str(len(self.false_negative))) | Object returned by validation.
Results from comparing frames identified by a proposed state definition
to the frames identified by the user. Checks for correct results, false
positives (proposed definition finds frames the user didn't) and false
negatives (user finds frames the proposed definition didn't).
Parameters
----------
correct : list of ``paths.Snapshot``
the snapshots which were correctly identified as in the state
false_positive : list of ``paths.Snapshot``
the snapshots which were identified as in the state by the volume
function, but not by the annotation
false_negative : list of ``paths.Snapshot``
the snapshots which were not identified as in the state by the
volume, but were in the state according to the annotation. | 6259906366673b3332c31af9 |
class SettingsMixin(object): <NEW_LINE> <INDENT> settings = db.Column(JSONEncodedDict()) <NEW_LINE> settings_default = {} <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.settings = dict(self.settings_default) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if self.settings is not None and key in self.settings: <NEW_LINE> <INDENT> return self.settings[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if key in self.settings_default: <NEW_LINE> <INDENT> return self.settings_default.get(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError(key) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.update({key: value}) <NEW_LINE> <DEDENT> def update(self, mapping): <NEW_LINE> <INDENT> if self.settings is None: <NEW_LINE> <INDENT> new_settings = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_settings = dict(self.settings) <NEW_LINE> <DEDENT> new_settings.update(mapping) <NEW_LINE> self.settings = new_settings | A mixin class for SQLAlchemy Model classes that provides a
JSON-encoded dictionary of free-form *settings*. These values are
accessed by subscripting the model object. | 62599063435de62698e9d505 |
class EOLModeSelect(BufferBusyActionMixin, RadioAction): <NEW_LINE> <INDENT> name = "Line Endings" <NEW_LINE> inline = False <NEW_LINE> localize_items = True <NEW_LINE> default_menu = ("Transform", -999) <NEW_LINE> items = ['Unix (LF)', 'DOS/Windows (CRLF)', 'Old-style Apple (CR)'] <NEW_LINE> modes = [wx.stc.STC_EOL_LF, wx.stc.STC_EOL_CRLF, wx.stc.STC_EOL_CR] <NEW_LINE> def getIndex(self): <NEW_LINE> <INDENT> eol = self.mode.GetEOLMode() <NEW_LINE> return EOLModeSelect.modes.index(eol) <NEW_LINE> <DEDENT> def getItems(self): <NEW_LINE> <INDENT> return EOLModeSelect.items <NEW_LINE> <DEDENT> def action(self, index=-1, multiplier=1): <NEW_LINE> <INDENT> self.mode.ConvertEOLs(EOLModeSelect.modes[index]) <NEW_LINE> Publisher().sendMessage('resetStatusBar') | Switch line endings
Converts all line endings to the specified line ending. This can be used
if there are multiple styles of line endings in the file. | 625990638e7ae83300eea78b |
class TestQuoteResponse(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return QuoteResponse( name = 'Opłata za wystawienie.', fee = allegro_api.models.price.Price( amount = '123.45', currency = 'PLN', ), cycle_duration = 'PT240H', classifieds_package = allegro_api.models.classified_package.ClassifiedPackage( id = 'e76d443b-c088-4da5-95f7-cc9aaf73bf7b', ) ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return QuoteResponse( ) <NEW_LINE> <DEDENT> <DEDENT> def testQuoteResponse(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True) | QuoteResponse unit test stubs | 62599063a8370b77170f1acb |
class NewClient(object): <NEW_LINE> <INDENT> def __init__(self, facade_lab): <NEW_LINE> <INDENT> self.lab = facade_lab <NEW_LINE> <DEDENT> def start_lab(self): <NEW_LINE> <INDENT> if self.lab.can_be_started(): <NEW_LINE> <INDENT> print("start lab") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("can not start lab") | 新的客户类 | 625990634428ac0f6e659c30 |
class McLaneResponse(BaseEnum): <NEW_LINE> <INDENT> HOME = re.compile(r'Port: 00') <NEW_LINE> PORT = re.compile(r'Port: (\d+)') <NEW_LINE> READY = re.compile(r'(\d+/\d+/\d+\s+\d+:\d+:\d+\s+)(RAS|PPS)\s+(.*)>') <NEW_LINE> PUMP = re.compile(r'(Status|Result).*(\d+)' + NEWLINE) <NEW_LINE> BATTERY = re.compile(r'Battery:\s+(\d*\.\d+)V\s+\[.*\]') <NEW_LINE> CAPACITY = re.compile(r'Capacity:\s(Maxon|Pittman)\s+(\d+)mL') <NEW_LINE> VERSION = re.compile( r'McLane .*$' + NEWLINE + r'CF2 .*$' + NEWLINE + r'Version\s+(\S+)\s+of\s+(.*)$' + NEWLINE + r'.*$' ) | Expected device response strings | 6259906399cbb53fe68325e0 |
class Visualizer(object): <NEW_LINE> <INDENT> def __init__(self, env='default', **kwargs): <NEW_LINE> <INDENT> self.vis = visdom.Visdom(env=env, **kwargs) <NEW_LINE> self.index = {} <NEW_LINE> self.log_text = '' <NEW_LINE> <DEDENT> def reinit(self, env='default', **kwargs): <NEW_LINE> <INDENT> self.vis = visdom.Visdom(env=env, **kwargs) <NEW_LINE> return self <NEW_LINE> <DEDENT> def plot_many(self, d): <NEW_LINE> <INDENT> for k, v in d.iteritems(): <NEW_LINE> <INDENT> self.plot(k, v) <NEW_LINE> <DEDENT> <DEDENT> def img_many(self, d): <NEW_LINE> <INDENT> for k, v in d.iteritems(): <NEW_LINE> <INDENT> self.img(k, v) <NEW_LINE> <DEDENT> <DEDENT> def plot(self, name, y, **kwargs): <NEW_LINE> <INDENT> x = self.index.get(name, 0) <NEW_LINE> self.vis.line(Y=np.array([y]), X=np.array([x]), win=name, opts=dict(title=name), update=None if x == 0 else 'append', **kwargs ) <NEW_LINE> self.index[name] = x + 1 <NEW_LINE> <DEDENT> def img(self, name, img_, **kwargs): <NEW_LINE> <INDENT> self.vis.images(img_, win=name, opts=dict(title=name), **kwargs ) <NEW_LINE> <DEDENT> def log(self, info, win='log_text'): <NEW_LINE> <INDENT> self.log_text += ('[{time}] {info} <br>'.format( time=time.strftime('%m%d_%H%M%S'), info=info)) <NEW_LINE> self.vis.text(self.log_text, win) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self.vis, name) | 封装了visdom的基本操作,但是你仍然可以通过`self.vis.function`
或者`self.function`调用原生的visdom接口
比如
self.text('hello visdom')
self.histogram(t.randn(1000))
self.line(t.arange(0, 10),t.arange(1, 11)) | 62599063f548e778e596cc86 |
class UserForm(forms.Form): <NEW_LINE> <INDENT> usr = forms.CharField(min_length=2, max_length=20, widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': '用户名'})) <NEW_LINE> pwd = forms.CharField(min_length=3, widget=widgets.PasswordInput(attrs={'class': 'form-control', 'placeholder': '密码(不少于3位)'})) <NEW_LINE> r_pwd = forms.CharField(min_length=3, widget=widgets.PasswordInput(attrs={'class': 'form-control', 'placeholder': '确认密码'})) <NEW_LINE> def clean_usr(self): <NEW_LINE> <INDENT> val = self.cleaned_data.get('usr') <NEW_LINE> ret = User.objects.filter(username=val) <NEW_LINE> if not ret: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValidationError('用户已注册') <NEW_LINE> <DEDENT> <DEDENT> def clean(self): <NEW_LINE> <INDENT> pwd = self.cleaned_data.get('pwd') <NEW_LINE> r_pwd = self.cleaned_data.get('r_pwd') <NEW_LINE> if pwd == r_pwd: <NEW_LINE> <INDENT> return self.cleaned_data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValidationError('密码不一致') | forms组件:注册 | 62599063009cb60464d02c35 |
class AssociationDefinition(EntityDefinition): <NEW_LINE> <INDENT> def __init__(self, definition_dict = dict(), src_alias = "", dst_alias = "", edm_api = None, entity_sets_api = None): <NEW_LINE> <INDENT> super().__init__(definition_dict = definition_dict, edm_api = edm_api, entity_sets_api = entity_sets_api) <NEW_LINE> self.src_alias = src_alias if src_alias else (definition_dict["src"] if "src" in definition_dict.keys() else "") <NEW_LINE> self.dst_alias = dst_alias if dst_alias else (definition_dict["dst"] if "dst" in definition_dict.keys() else "") <NEW_LINE> self.association_type = None <NEW_LINE> <DEDENT> def get_association_type(self): <NEW_LINE> <INDENT> if not self.association_type: <NEW_LINE> <INDENT> self.load_association_type() <NEW_LINE> <DEDENT> return self.association_type <NEW_LINE> <DEDENT> def get_entity_type(self): <NEW_LINE> <INDENT> if not self.association_type: <NEW_LINE> <INDENT> self.load_association_type() <NEW_LINE> <DEDENT> return self.association_type.entity_type <NEW_LINE> <DEDENT> def load_association_type(self, edm = None): <NEW_LINE> <INDENT> fqn = self.fqn.split(".") <NEW_LINE> if len(fqn) < 2: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.association_type = self.edm_api.get_association_type( self.edm_api.get_entity_type_id(namespace=fqn[0], name=fqn[1])) <NEW_LINE> <DEDENT> except openlattice.rest.ApiException as exc: <NEW_LINE> <INDENT> self.association_type = openlattice.AssociationType( entity_type = openlattice.EntityType( type = openlattice.FullQualifiedName(), key = [], properties = [] ), src = [], dst = [] ) <NEW_LINE> <DEDENT> self.entity_type = self.association_type.entity_type <NEW_LINE> <DEDENT> def necessary_components_validation(self, log_level = "none"): <NEW_LINE> <INDENT> report = clean.report.ValidationReport( title = f"Necessary Components Validation for Association {self.name}", ) <NEW_LINE> entity_report = super().necessary_components_validation(log_level = log_level) <NEW_LINE> special_report = clean.report.ValidationReport( title = f"Source and Destination Defined for Association {self.name}" ) <NEW_LINE> if not self.src_alias: <NEW_LINE> <INDENT> special_report.validated = False <NEW_LINE> special_report.issues.append("Source not defined.") <NEW_LINE> <DEDENT> if not self.dst_alias: <NEW_LINE> <INDENT> special_report.validated = False <NEW_LINE> special_report.issues.append("Destination not defined.") <NEW_LINE> <DEDENT> special_report.print_status(log_level = log_level) <NEW_LINE> report.sub_reports = [entity_report, special_report] <NEW_LINE> report.validate() <NEW_LINE> report.print_status(log_level = log_level) <NEW_LINE> return report <NEW_LINE> <DEDENT> def get_schema(self): <NEW_LINE> <INDENT> out = super().get_schema() <NEW_LINE> out.update({ "src": self.src_alias, "dst": self.dst_alias }) <NEW_LINE> return out | A class representing an association definition
An AssociationDefinition is an EntityDefinition with a defined source and destination. | 62599063f548e778e596cc87 |
class Pattern(Unit): <NEW_LINE> <INDENT> def set(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> <DEDENT> def _draw_label_text(self, l): <NEW_LINE> <INDENT> l.set_text(">") <NEW_LINE> <DEDENT> def _draw_image(self, pbuff, gc, size): <NEW_LINE> <INDENT> ps = [(self._x, self._y), (self._x + size, self._y + size / 2), (self._x, self._y + size)] <NEW_LINE> pbuff.draw_polygon(gc, False, ps) | A unit for pattern feeding the neural network. | 62599063435de62698e9d506 |
class ApplicationRate(object): <NEW_LINE> <INDENT> swagger_types = { 'interval': 'ApplicationIntervals', 'indexer': 'Indexer', 'customers': 'Customer' } <NEW_LINE> attribute_map = { 'interval': 'interval', 'indexer': 'indexer', 'customers': 'customers' } <NEW_LINE> def __init__(self, interval=None, indexer=None, customers=None): <NEW_LINE> <INDENT> self._interval = None <NEW_LINE> self._indexer = None <NEW_LINE> self._customers = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.interval = interval <NEW_LINE> self.indexer = indexer <NEW_LINE> self.customers = customers <NEW_LINE> <DEDENT> @property <NEW_LINE> def interval(self): <NEW_LINE> <INDENT> return self._interval <NEW_LINE> <DEDENT> @interval.setter <NEW_LINE> def interval(self, interval): <NEW_LINE> <INDENT> if interval is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `interval`, must not be `None`") <NEW_LINE> <DEDENT> self._interval = interval <NEW_LINE> <DEDENT> @property <NEW_LINE> def indexer(self): <NEW_LINE> <INDENT> return self._indexer <NEW_LINE> <DEDENT> @indexer.setter <NEW_LINE> def indexer(self, indexer): <NEW_LINE> <INDENT> if indexer is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `indexer`, must not be `None`") <NEW_LINE> <DEDENT> self._indexer = indexer <NEW_LINE> <DEDENT> @property <NEW_LINE> def customers(self): <NEW_LINE> <INDENT> return self._customers <NEW_LINE> <DEDENT> @customers.setter <NEW_LINE> def customers(self, customers): <NEW_LINE> <INDENT> if customers is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `customers`, must not be `None`") <NEW_LINE> <DEDENT> self._customers = customers <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(ApplicationRate, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ApplicationRate): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259906324f1403a9268644d |
class BMSBackupSummariesQueryObject(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, type: Optional[Union[str, "Type"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(BMSBackupSummariesQueryObject, self).__init__(**kwargs) <NEW_LINE> self.type = type | Query parameters to fetch backup summaries.
:ivar type: Backup management type for this container. Possible values include: "Invalid",
"BackupProtectedItemCountSummary", "BackupProtectionContainerCountSummary".
:vartype type: str or ~azure.mgmt.recoveryservicesbackup.passivestamp.models.Type | 62599063b7558d5895464aad |
@implementer(IAddress) <NEW_LINE> class SSHTransportAddress(util.FancyEqMixin, object): <NEW_LINE> <INDENT> compareAttributes = ('address',) <NEW_LINE> def __init__(self, address): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'SSHTransportAddress(%r)' % (self.address,) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(('SSH', self.address)) | Object representing an SSH Transport endpoint.
This is used to ensure that any code inspecting this address and
attempting to construct a similar connection based upon it is not
mislead into creating a transport which is not similar to the one it is
indicating.
@ivar address: A instance of an object which implements I{IAddress} to
which this transport address is connected. | 625990635fdd1c0f98e5f682 |
class AceCard (PlayingCard): <NEW_LINE> <INDENT> def __init__(self, suit): <NEW_LINE> <INDENT> self.value = 14 <NEW_LINE> self.suit = suit <NEW_LINE> self.card = (14, suit) <NEW_LINE> <DEDENT> def give_value(self): <NEW_LINE> <INDENT> return (self.value) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "(" + str(self.value) + str(self.suit) + ")" | Class for an Ace | 6259906332920d7e50bc7745 |
class CatkeysFile(base.TranslationStore): <NEW_LINE> <INDENT> Name = "Haiku catkeys file" <NEW_LINE> Mimetypes = ["application/x-catkeys"] <NEW_LINE> Extensions = ["catkeys"] <NEW_LINE> def __init__(self, inputfile=None, unitclass=CatkeysUnit): <NEW_LINE> <INDENT> self.UnitClass = unitclass <NEW_LINE> base.TranslationStore.__init__(self, unitclass=unitclass) <NEW_LINE> self.filename = '' <NEW_LINE> self.header = CatkeysHeader() <NEW_LINE> self._encoding = 'utf-8' <NEW_LINE> if inputfile is not None: <NEW_LINE> <INDENT> self.parse(inputfile) <NEW_LINE> <DEDENT> <DEDENT> def settargetlanguage(self, newlang): <NEW_LINE> <INDENT> self.header.settargetlanguage(newlang) <NEW_LINE> <DEDENT> def parse(self, input): <NEW_LINE> <INDENT> if hasattr(input, 'name'): <NEW_LINE> <INDENT> self.filename = input.name <NEW_LINE> <DEDENT> elif not getattr(self, 'filename', ''): <NEW_LINE> <INDENT> self.filename = '' <NEW_LINE> <DEDENT> if hasattr(input, "read"): <NEW_LINE> <INDENT> tmsrc = input.read() <NEW_LINE> input.close() <NEW_LINE> input = tmsrc <NEW_LINE> <DEDENT> for header in csv.DictReader(input.split("\n")[:1], fieldnames=FIELDNAMES_HEADER, dialect="catkeys"): <NEW_LINE> <INDENT> self.header = CatkeysHeader(header) <NEW_LINE> <DEDENT> lines = csv.DictReader(input.split("\n")[1:], fieldnames=FIELDNAMES, dialect="catkeys") <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> newunit = CatkeysUnit() <NEW_LINE> newunit.dict = line <NEW_LINE> self.addunit(newunit) <NEW_LINE> <DEDENT> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> output = csv.StringIO() <NEW_LINE> writer = csv.DictWriter(output, fieldnames=FIELDNAMES_HEADER, dialect="catkeys") <NEW_LINE> writer.writerow(self.header._header_dict) <NEW_LINE> writer = csv.DictWriter(output, fieldnames=FIELDNAMES, dialect="catkeys") <NEW_LINE> for unit in self.units: <NEW_LINE> <INDENT> writer.writerow(unit.dict) <NEW_LINE> <DEDENT> return output.getvalue() | A catkeys translation memory file | 62599063442bda511e95d8d9 |
class MQConnectionError( Exception ): <NEW_LINE> <INDENT> pass | specialized exception
| 6259906356b00c62f0fb3fcb |
class Event(object): <NEW_LINE> <INDENT> def __init__(self, topic, data): <NEW_LINE> <INDENT> self.__topic = topic <NEW_LINE> self.__data = data <NEW_LINE> <DEDENT> @property <NEW_LINE> def topic(self): <NEW_LINE> <INDENT> return self.__topic <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self.__data | PUB/SUB event container
this is an opaque data structure that represents a single, entire
event: ``topic`` and ``data`` | 625990630c0af96317c578de |
class CognitiveServicesAccountKeys(Model): <NEW_LINE> <INDENT> _attribute_map = { 'key1': {'key': 'key1', 'type': 'str'}, 'key2': {'key': 'key2', 'type': 'str'}, } <NEW_LINE> def __init__(self, key1=None, key2=None): <NEW_LINE> <INDENT> self.key1 = key1 <NEW_LINE> self.key2 = key2 | The access keys for the cognitive services account.
:param key1: Gets the value of key 1.
:type key1: str
:param key2: Gets the value of key 2.
:type key2: str | 62599063d6c5a102081e3823 |
class Gardener(Smarter): <NEW_LINE> <INDENT> def action(self, player, game): <NEW_LINE> <INDENT> LOGGER.info('player has %d action(s)', player.actions) <NEW_LINE> candidate = super().action(player, game) <NEW_LINE> if not candidate: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif candidate.actions or Thief not in player.hand: <NEW_LINE> <INDENT> return candidate <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Thief(player, game, to_gain={Gold, Silver, Copper}) <NEW_LINE> <DEDENT> <DEDENT> def buy(self, player, game): <NEW_LINE> <INDENT> LOGGER.info('player has %d buy(s) and %d money', player.buys, player.money) <NEW_LINE> if player.money == 5 and game.supply.get(Festival) and player.counter[Festival] < 3: <NEW_LINE> <INDENT> card = Festival(player, game) <NEW_LINE> <DEDENT> elif player.money == 5 and not game.supply.get(Festival) and game.supply.get(Market) and player.counter[Festival] + player.counter[Market] < 3: <NEW_LINE> <INDENT> card = Market(player, game) <NEW_LINE> <DEDENT> elif 4 <= player.money <= 5 and game.supply.get(Thief) and player.counter[Thief] < 3: <NEW_LINE> <INDENT> card = Thief(player, game) <NEW_LINE> <DEDENT> elif 4 <= player.money <= 5 and game.supply.get(Gardens): <NEW_LINE> <INDENT> card = Gardens(player, game) <NEW_LINE> <DEDENT> elif player.money == 3 and game.supply.get(Woodcutter) and player.counter[Woodcutter] < 2: <NEW_LINE> <INDENT> card = Woodcutter(player, game) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> card = super().buy(player, game) <NEW_LINE> if (card is None or isinstance(card, Curse)) and game.supply.get(Copper): <NEW_LINE> <INDENT> card = Copper(player, game) <NEW_LINE> <DEDENT> <DEDENT> return card | bloat your deck as much as possible to make points with gardens | 62599063fff4ab517ebcef27 |
class ProjectCommentForm(wtf.Form): <NEW_LINE> <INDENT> objid = wtforms.TextField( 'Ticket/Request id', [wtforms.validators.Required()] ) <NEW_LINE> useremail = wtforms.TextField( 'Email', [wtforms.validators.Required()] ) | Form to represent project. | 625990634f6381625f19a023 |
class UpdateProfilePic(APIView): <NEW_LINE> <INDENT> schema = schemas.ManualSchema(fields=[ coreapi.Field( "profile_pic", required=False, location="form", schema=coreschema.Object( description="Test this API with Postmen" ) ) ]) <NEW_LINE> permission_classes = (permissions.IsAuthenticated,) <NEW_LINE> def post(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(id=request.user.id) <NEW_LINE> <DEDENT> except ValidationError as v: <NEW_LINE> <INDENT> return Response( { 'status': status.HTTP_401_UNAUTHORIZED, 'message': 'invalid token', 'data': '' } ) <NEW_LINE> <DEDENT> if 'profile_pic' not in self.request.data: <NEW_LINE> <INDENT> return Response( { 'status': status.HTTP_400_BAD_REQUEST, 'message': 'Invalid file given', 'data': '' }, status=status.HTTP_400_BAD_REQUEST ) <NEW_LINE> <DEDENT> file_name = self.request.data['profile_pic'] <NEW_LINE> if not file_name.name.lower().endswith(('.jpg', '.jpeg')): <NEW_LINE> <INDENT> return Response( { 'status': status.HTTP_400_BAD_REQUEST, 'message': 'Invalid image format is given', 'data': '' }, status=status.HTTP_400_BAD_REQUEST ) <NEW_LINE> <DEDENT> rndm = random.randint(100000, 9999999) <NEW_LINE> upload_dir = make_dir( settings.MEDIA_ROOT + settings.CUSTOM_DIRS.get('USER_IMAGE') + '/' + str(rndm) + '/' ) <NEW_LINE> file_name = file_upload_handler(file_name, upload_dir) <NEW_LINE> profile_pic = settings.MEDIA_URL + settings.CUSTOM_DIRS.get('USER_IMAGE') + '/' + str( rndm) + '/' + file_name <NEW_LINE> user.profile_pic = profile_pic <NEW_LINE> user.save() <NEW_LINE> return Response( { 'status': status.HTTP_201_CREATED, 'message': 'Profile picture updated.', 'data': { 'profile_pic': profile_pic, 'user_name': user.username } }, status=status.HTTP_201_CREATED ) | post:
API for update user profile picture. Auth token required. | 62599063f548e778e596cc88 |
class Rows(CustomRows): <NEW_LINE> <INDENT> def __init__(self, rowcls): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.rowcls = rowcls <NEW_LINE> <DEDENT> def instanciate_row(self, rows, request, subdata): <NEW_LINE> <INDENT> rows.append( self.rowcls( request=request, post_data=subdata, parent=rows)) | This is not a decorator, but a plain descriptor to be used to host a list of
elements in a :class:`Form`. The elements are instances of *rowcls*, or of
the form itself, if *rowcls* is passed as :data:`None`. | 62599063ac7a0e7691f73be4 |
class _ldau_TLUJ(Keyword): <NEW_LINE> <INDENT> name = "ldau_TLUJ" <NEW_LINE> ptype = dict <NEW_LINE> atype = "numbers" | on site coulomb interaction (`mandatory`). Units: ``.
.. warning:: This keyword is still listed as development level. Use it
knowing that it is subject to change or removal.
Returns:
list: This vector of numbers contains the parameters of the DFT+U calculations, based on a corrective functional inspired by the Hubbard model.
| 625990633d592f4c4edbc5dc |
class Frazione(models.Model): <NEW_LINE> <INDENT> nome = models.CharField(max_length=30) <NEW_LINE> comune = models.ForeignKey(Comune) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.nome <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.nome | Modello che implementa l'entità Frazione di appartenenza di un monitor nel db | 625990637d847024c075dad5 |
class FakeCheckingDhcpThread(FakeAmpqThread): <NEW_LINE> <INDENT> def _get_message(self, mac): <NEW_LINE> <INDENT> nodes = [{'uid': '90', 'status': 'ready', 'data': [{'mac': mac, 'server_id': '10.20.0.20', 'yiaddr': '10.20.0.133', 'iface': 'eth0'}]}, {'uid': '91', 'status': 'ready', 'data': [{'mac': mac, 'server_id': '10.20.0.20', 'yiaddr': '10.20.0.131', 'iface': 'eth0'}]}] <NEW_LINE> return {'task_uuid': self.task_uuid, 'error': '', 'status': 'ready', 'progress': 100, 'nodes': nodes} <NEW_LINE> <DEDENT> def message_gen(self): <NEW_LINE> <INDENT> self.sleep(self.tick_interval) <NEW_LINE> if self.params.get("dhcp_error"): <NEW_LINE> <INDENT> return self.error_message_gen() <NEW_LINE> <DEDENT> elif 'rogue_dhcp_mac' in self.params: <NEW_LINE> <INDENT> return (self._get_message(self.params['rogue_dhcp_mac']),) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self._get_message(settings.ADMIN_NETWORK['mac']),) | Thread to be used with test_task_managers.py | 6259906376e4537e8c3f0c82 |
class inputSrv(Thread): <NEW_LINE> <INDENT> def out(self, _txt): <NEW_LINE> <INDENT> self.utils_c.echo("inputSrv:> "+_txt) <NEW_LINE> <DEDENT> def __init__(self, _utils_c, _refresh=1): <NEW_LINE> <INDENT> super(inputSrv,self).__init__() <NEW_LINE> self.utils_c = _utils_c <NEW_LINE> self.refreshRate = _refresh <NEW_LINE> self.out("init inputSrv") <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.out("stop inputSrv") <NEW_LINE> storageCtrl.removeThreadToStop(self) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.out("start inputSrv") <NEW_LINE> storageCtrl.addThreadToStop(self) <NEW_LINE> working_device = None <NEW_LINE> while storageCtrl.getStopRequested() == False: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] <NEW_LINE> for device in devices: <NEW_LINE> <INDENT> if device.fn.find("Keyboard") != -1: <NEW_LINE> <INDENT> working_device = device; <NEW_LINE> <DEDENT> print(device.fn, device.name, device.phys) <NEW_LINE> <DEDENT> if working_device: <NEW_LINE> <INDENT> for event in device.read_loop(): <NEW_LINE> <INDENT> my_key = None <NEW_LINE> if event.type == evdev.ecodes.EV_KEY: <NEW_LINE> <INDENT> print(categorize(event)) <NEW_LINE> if categorize(event).find("KEY_") and categorize(event).find("up") : <NEW_LINE> <INDENT> my_key = categorize(event).split(" (KEY_")[1].split("),")[0].lower() <NEW_LINE> <DEDENT> <DEDENT> if storageCtrl.getStopRequested() == True: <NEW_LINE> <INDENT> break; <NEW_LINE> <DEDENT> if my_key: <NEW_LINE> <INDENT> allKWandCommands = storageCtrl.getkeywordsAndCommands() <NEW_LINE> for [kw, kb, command, gpio] in allKWandCommands: <NEW_LINE> <INDENT> if my_key == kb: <NEW_LINE> <INDENT> if command != "": <NEW_LINE> <INDENT> storageCtrl.pushWebRequest(command) <NEW_LINE> <DEDENT> elif gpio != "": <NEW_LINE> <INDENT> storageCtrl.pushGpioRequest(gpio) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> CMD = "echo -e 'power on\nconnect \t \nquit' | bluetoothctl" <NEW_LINE> self.utils_c.execute_cmd(CMD) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.out("Error on keypressed") <NEW_LINE> <DEDENT> sleep(self.refreshRate) <NEW_LINE> <DEDENT> my_kb.set_normal_term() <NEW_LINE> storageCtrl.stopAcheived = storageCtrl.getStopAcheived() - 1 | classdocs | 625990634e4d562566373b07 |
class FieldArray(BaseField): <NEW_LINE> <INDENT> def __init__(self, substructure, length_provider=None, **kwargs): <NEW_LINE> <INDENT> BaseField.__init__(self, **kwargs) <NEW_LINE> self.substructure = substructure <NEW_LINE> self._value = list() <NEW_LINE> if isinstance(length_provider, FieldPlaceholder): <NEW_LINE> <INDENT> self.length_provider = self._ph2f(length_provider) <NEW_LINE> self.length_provider.associate_length_consumer(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.length_provider = None <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def bytes_required(self): <NEW_LINE> <INDENT> if self.length_provider is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.length_provider.get_adjusted_length() <NEW_LINE> <DEDENT> <DEDENT> def pack(self, stream): <NEW_LINE> <INDENT> for structure in self._value: <NEW_LINE> <INDENT> stream.write(structure.pack()) <NEW_LINE> <DEDENT> <DEDENT> def unpack(self, data, **kwargs): <NEW_LINE> <INDENT> length = self.bytes_required <NEW_LINE> if length == 0 or (data == b"" and length is None): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> kwargs['trailing'] = True <NEW_LINE> while True: <NEW_LINE> <INDENT> structure = self.substructure() <NEW_LINE> data = structure.unpack(data, **kwargs).read() <NEW_LINE> self._value.append(structure) <NEW_LINE> if data == b"": <NEW_LINE> <INDENT> break | Field which contains a list of some other field.
In some protocols, there exist repeated substructures which are present in a
variable number. The variable nature of these fields make a DispatchField
and DispatchTarget combination unsuitable; instead a FieldArray may be
used to pack/unpack these fields to/from a list.
:param substructure: The type of the array element. Must not be a greedy
field, or else the array will only ever have one element containing
the entire contents of the array.
:param length_provider: The field providing a length value binding this
message (if any). Set this field to None to leave unconstrained.
For example, one can imagine a message listing the zipcodes covered by
a telephone area code. Depending on the population density, the number
of zipcodes per area code could vary greatly. One implementation of this
data structure could be::
from suitcase.structure import Structure
from suitcase.fields import UBInt16, FieldArray
class ZipcodeStructure(Structure):
zipcode = UBInt16()
class TelephoneZipcodes(Structure):
areacode = UBInt16()
zipcodes = FieldArray(ZipcodeStructure) # variable number of zipcodes | 62599063e5267d203ee6cf3e |
class ReadBlocks(Reader): <NEW_LINE> <INDENT> def __init__(self,src,isEndBlock=lambda line:line=="\n"): <NEW_LINE> <INDENT> Reader.__init__(self,src) <NEW_LINE> self.isEndBlock = isEndBlock <NEW_LINE> <DEDENT> def rowGenerator(self): <NEW_LINE> <INDENT> buf = [] <NEW_LINE> for line in sys.stdin: <NEW_LINE> <INDENT> if self.isEndBlock(line): <NEW_LINE> <INDENT> yield buf <NEW_LINE> buf = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> buf.append(line) <NEW_LINE> <DEDENT> <DEDENT> if buf: <NEW_LINE> <INDENT> yield buf <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'ReadBlocks("%s")' % self.src + self.showExtras() | Returns blocks of non-empty lines, separated by empty lines | 62599063f548e778e596cc89 |
class FlexRequest(Request): <NEW_LINE> <INDENT> def __init__(self, prognosis: Prognosis, requested_flexibility: Series = None, **kwargs): <NEW_LINE> <INDENT> self.requested_flexibility = requested_flexibility <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> self.prognosis = prognosis | A FlexRequest describes requested commitments to deviate from a prognosis.
A commitment for a certain timeslot of e.g. 10 MW indicates a request to increase consumption (or decrease
production) by 10 MW.
A nan value indicates availability to deviate by any amount. | 6259906345492302aabfdbdb |
class ClientCutText(CompositeType): <NEW_LINE> <INDENT> def __init__(self, text = ""): <NEW_LINE> <INDENT> CompositeType.__init__(self) <NEW_LINE> self.padding = (UInt16Be(), UInt8()) <NEW_LINE> self.size = UInt32Be(len(text)) <NEW_LINE> self.message = String(text) | Client cut text message message
Use to simulate copy paste (ctrl-c ctrl-v) only for text | 6259906332920d7e50bc7746 |
class DirectoryServiceSettingsResponse(object): <NEW_LINE> <INDENT> swagger_types = { 'pagination_info': 'PaginationInfo', 'items': 'list[DirectoryServiceSettings]' } <NEW_LINE> attribute_map = { 'pagination_info': 'pagination_info', 'items': 'items' } <NEW_LINE> def __init__(self, pagination_info=None, items=None): <NEW_LINE> <INDENT> self._pagination_info = None <NEW_LINE> self._items = None <NEW_LINE> if pagination_info is not None: <NEW_LINE> <INDENT> self.pagination_info = pagination_info <NEW_LINE> <DEDENT> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def pagination_info(self): <NEW_LINE> <INDENT> return self._pagination_info <NEW_LINE> <DEDENT> @pagination_info.setter <NEW_LINE> def pagination_info(self, pagination_info): <NEW_LINE> <INDENT> self._pagination_info = pagination_info <NEW_LINE> <DEDENT> @property <NEW_LINE> def items(self): <NEW_LINE> <INDENT> return self._items <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items(self, items): <NEW_LINE> <INDENT> self._items = items <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, DirectoryServiceSettingsResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62599063adb09d7d5dc0bc6a |
class PowerFeatures(SpectralSource): <NEW_LINE> <INDENT> def __init__(self, fftLn = 512, windowLen = 320, windowShift = 160): <NEW_LINE> <INDENT> SpectralSource.__init__(self, fftLn) <NEW_LINE> self._windowLen = windowLen <NEW_LINE> self._windowShift = windowShift <NEW_LINE> self._normalizer = (2.0**16-1)**2 / 4 * self._windowLen <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> sampleBlock = self._sampleIter.next() <NEW_LINE> while(1): <NEW_LINE> <INDENT> while (len(sampleBlock) < self._windowLen): <NEW_LINE> <INDENT> sampleBlock = concatenate((sampleBlock, self._sampleIter.next())) <NEW_LINE> <DEDENT> yield array(sum(sampleBlock[:self._windowLen].astype(float)**2)/self._normalizer) <NEW_LINE> sampleBlock = sampleBlock[self._windowShift:] <NEW_LINE> <DEDENT> <DEDENT> def nextUtt(self, soundSource): <NEW_LINE> <INDENT> self.__soundSource = soundSource <NEW_LINE> self._sampleIter = self.__soundSource.__iter__() | Delivers the averaged power over segments of speech of deignated length for use in Janus | 625990639c8ee82313040d08 |
class Profile(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.systran_types = { 'id': 'str', 'private': 'bool' } <NEW_LINE> self.attribute_map = { 'id': 'id', 'private': 'private' } <NEW_LINE> self.id = None <NEW_LINE> self.private = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> properties = [] <NEW_LINE> for p in self.__dict__: <NEW_LINE> <INDENT> if p != 'systran_types' and p != 'attribute_map': <NEW_LINE> <INDENT> properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) <NEW_LINE> <DEDENT> <DEDENT> return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) | NOTE: This class is auto generated by the systran code generator program.
Do not edit the class manually. | 6259906324f1403a9268644e |
class ObtainSocialTokenPairView(generics.CreateAPIView): <NEW_LINE> <INDENT> authentication_classes = [] <NEW_LINE> permission_classes = [] <NEW_LINE> serializer_class = ObtainSocialTokenPairSerializer <NEW_LINE> def create(self, req, *args, **kwargs): <NEW_LINE> <INDENT> body = json.loads(str(req.body, encoding='utf-8')) <NEW_LINE> try: <NEW_LINE> <INDENT> end_user = EndUser.objects.get(email=body['email']) <NEW_LINE> if end_user.check_password(body['password']): <NEW_LINE> <INDENT> return Response(data={}, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> end_user.set_password(body['password']) <NEW_LINE> end_user.save() <NEW_LINE> return Response(data={}, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> authy_id = "209891210" <NEW_LINE> end_user = EndUser.objects.create_user(body['email'], body['password'], authy_id) <NEW_LINE> volunteer = Volunteer.objects.create(first_name=body['first_name'], last_name=body['last_name'], birthday='3000-1-1', phone_number='7654263668', end_user_id=end_user.id) <NEW_LINE> serializer = VolunteerSerializer(volunteer) <NEW_LINE> return Response(data=serializer.data, status=status.HTTP_201_CREATED) | Class View for user to obtain JWT token | 625990638da39b475be048e9 |
class BindProductsResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RequestId = params.get("RequestId") | BindProducts返回参数结构体
| 62599063097d151d1a2c276b |
class IndexView(generic.ListView): <NEW_LINE> <INDENT> template_name = 'polls/index.html' <NEW_LINE> context_object_name = 'latest_question_list' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] | Django generic view for the index page. | 62599063796e427e5384fe76 |
class Vectorizer: <NEW_LINE> <INDENT> mels = 1 <NEW_LINE> mfccs = 2 <NEW_LINE> speechpy_mfccs = 3 | Chooses which function to call to vectorize audio
Options:
mels: Convert to a compressed Mel spectrogram
mfccs: Convert to a MFCC spectrogram
speechpy_mfccs: Legacy option to convert to MFCCs using old library | 625990632ae34c7f260ac7e8 |
class AdminMatchEdit(LoggedInHandler): <NEW_LINE> <INDENT> def get(self, match_key): <NEW_LINE> <INDENT> self._require_admin() <NEW_LINE> match = Match.get_by_id(match_key) <NEW_LINE> self.template_values.update({ "match": match }) <NEW_LINE> path = os.path.join(os.path.dirname(__file__), '../../templates/admin/match_edit.html') <NEW_LINE> self.response.out.write(template.render(path, self.template_values)) <NEW_LINE> <DEDENT> def post(self, match_key): <NEW_LINE> <INDENT> self._require_admin() <NEW_LINE> alliances_json = self.request.get("alliances_json") <NEW_LINE> alliances = json.loads(alliances_json) <NEW_LINE> team_key_names = list() <NEW_LINE> for alliance in alliances: <NEW_LINE> <INDENT> team_key_names.extend(alliances[alliance].get('teams', None)) <NEW_LINE> <DEDENT> match = Match( id=match_key, event=Event.get_by_id(self.request.get("event_key_name")).key, game=self.request.get("game"), set_number=int(self.request.get("set_number")), match_number=int(self.request.get("match_number")), comp_level=self.request.get("comp_level"), team_key_names=team_key_names, alliances_json=alliances_json, ) <NEW_LINE> match = MatchManipulator.createOrUpdate(match) <NEW_LINE> self.redirect("/admin/match/" + match.key_name) | Edit a Match. | 62599063d268445f2663a6dd |
class IsSuperUserOrReadOnly(permissions.IsAdminUser): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return bool(request.user and request.user.is_superuser) | For use with admin-level change views. | 625990634e4d562566373b08 |
class StandardizeFloatCols(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def __init__(self, cols=None): <NEW_LINE> <INDENT> pdu._is_cols_input_valid(cols) <NEW_LINE> self.cols = cols <NEW_LINE> self.standard_scaler = StandardScaler() <NEW_LINE> self._is_fitted = False <NEW_LINE> <DEDENT> def transform(self, df, **transform_params): <NEW_LINE> <INDENT> if not self._is_fitted: <NEW_LINE> <INDENT> raise NotFittedError("Fitting was not preformed") <NEW_LINE> <DEDENT> pdu._is_cols_subset_of_df_cols(self.cols, df) <NEW_LINE> df = df.copy() <NEW_LINE> standartize_cols = pd.DataFrame( self.standard_scaler.transform(df[self.cols]), columns=self.cols, index=df.index ) <NEW_LINE> df = df.drop(self.cols, axis=1) <NEW_LINE> df = pd.concat([df, standartize_cols], axis=1) <NEW_LINE> return df <NEW_LINE> <DEDENT> def fit(self, df, y=None, **fit_params): <NEW_LINE> <INDENT> pdu._is_cols_subset_of_df_cols(self.cols, df) <NEW_LINE> self.standard_scaler.fit(df[self.cols]) <NEW_LINE> self._is_fitted = True <NEW_LINE> return self | Standard-scale the columns in the data frame.
Apply sklearn.preprocessing.StandardScaler_ to `cols`
.. _sklearn.preprocessing.StandardScaler : https://is.gd/cdMuLr
Attributes
----------
cols : list
List of columns in the data to be scaled | 625990637d847024c075dad7 |
class UserViewSet(BaseViewSet): <NEW_LINE> <INDENT> permission_code = 'user' <NEW_LINE> queryset = User.objects.all().prefetch_related('groups') <NEW_LINE> serializer_class = UserSerializer <NEW_LINE> filter_class = UserFilter <NEW_LINE> filter_backends = (DjangoFilterBackend, OrderingFilter) <NEW_LINE> def perform_destroy(self, serializer): <NEW_LINE> <INDENT> errors = {} <NEW_LINE> user = User.objects.get(id=self.kwargs['pk']) <NEW_LINE> user.is_active = False <NEW_LINE> user.save() | Vista maestro de usuarios
FILTROS:
username: coicidencia o valor exacto
first_name: coicidencia o valor exacto
last_name: coicidencia o valor exacto
is_active: valor exacto | 62599063a219f33f346c7f08 |
class ReceiveInput(Event): <NEW_LINE> <INDENT> pass | Some input arrived (fieldcode or other input) | 6259906324f1403a9268644f |
class Solution: <NEW_LINE> <INDENT> def longestPalindrome(self, s): <NEW_LINE> <INDENT> ret = [0, 0, 1] <NEW_LINE> for i in range(len(s)): <NEW_LINE> <INDENT> r1 = find_longest_alindrome(s, i, i) <NEW_LINE> r2 = find_longest_alindrome(s, i, i + 1) <NEW_LINE> if r1[0] > ret[0]: <NEW_LINE> <INDENT> ret = r1 <NEW_LINE> <DEDENT> if r2[0] > ret[0]: <NEW_LINE> <INDENT> ret = r2 <NEW_LINE> <DEDENT> <DEDENT> return s[ret[1]:ret[2] + 1] | @param s: input string
@return: the longest palindromic substring | 625990634f88993c371f10a0 |
class CharNode(Node): <NEW_LINE> <INDENT> def __init__(self, *, is_captured: bool=False, **kwargs) -> None: <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.is_captured = is_captured | A node that is meant to be matched against regular text characters
:ivar is_captured: set this node for capturing
:private: | 62599063a8ecb0332587291a |
class Logger(object): <NEW_LINE> <INDENT> def __init__(self, name, fields, directory=".", delimiter=',', resume=True): <NEW_LINE> <INDENT> self.filename = name + ".csv" <NEW_LINE> self.directory = process(path.join(directory), True) <NEW_LINE> self.file = path.join(self.directory, self.filename) <NEW_LINE> self.fields = fields <NEW_LINE> self.logger = logging.getLogger(name) <NEW_LINE> self.logger.setLevel(logging.INFO) <NEW_LINE> self.logger.propagate = False <NEW_LINE> if not resume or not path.exists(self.file): <NEW_LINE> <INDENT> with open(self.file, 'w') as f: <NEW_LINE> <INDENT> f.write(delimiter.join(fields)+ '\n') <NEW_LINE> <DEDENT> <DEDENT> file_handler = logging.FileHandler(self.file) <NEW_LINE> field_tmpl = delimiter.join(['%({0})s'.format('_' + x) for x in fields]) <NEW_LINE> file_handler.setFormatter(logging.Formatter(field_tmpl)) <NEW_LINE> self.logger.addHandler(file_handler) <NEW_LINE> <DEDENT> def __call__(self, values): <NEW_LINE> <INDENT> self.log(values) <NEW_LINE> <DEDENT> def _create_dict(self, values): <NEW_LINE> <INDENT> ret = {'_' + key: '' for key in self.fields} <NEW_LINE> ret.update({'_' + key: val.item() if is_tensor(val) else val for key, val in values.items()}) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def log(self, values): <NEW_LINE> <INDENT> self.logger.info('', extra=self._create_dict(values)) | Logs values in a csv file.
Args:
name (str): Filename without extension.
fields (list or tuple): Field names (column headers).
directory (str, optional): Directory to save file (default '.').
delimiter (str, optional): Delimiter for values (default ',').
resume (bool, optional): If True it appends to an already existing
file (default True). | 625990632ae34c7f260ac7e9 |
class BaseLeapTest(unittest.TestCase): <NEW_LINE> <INDENT> __name__ = "leap_test" <NEW_LINE> _system = platform.system() <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.old_path = os.environ['PATH'] <NEW_LINE> cls.old_home = os.environ['HOME'] <NEW_LINE> cls.tempdir = tempfile.mkdtemp(prefix="leap_tests-") <NEW_LINE> cls.home = cls.tempdir <NEW_LINE> bin_tdir = os.path.join( cls.tempdir, 'bin') <NEW_LINE> os.environ["PATH"] = bin_tdir <NEW_LINE> os.environ["HOME"] = cls.tempdir <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> os.environ["PATH"] = cls.old_path <NEW_LINE> os.environ["HOME"] = cls.old_home <NEW_LINE> leap_assert( cls.tempdir.startswith('/tmp/leap_tests-'), "beware! tried to remove a dir which does not " "live in temporal folder!") <NEW_LINE> shutil.rmtree(cls.tempdir) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> raise NotImplementedError("abstract base class") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> raise NotImplementedError("abstract base class") <NEW_LINE> <DEDENT> def _missing_test_for_plat(self, do_raise=False): <NEW_LINE> <INDENT> if do_raise: <NEW_LINE> <INDENT> raise NotImplementedError( "This test is not implemented " "for the running platform: %s" % self._system) <NEW_LINE> <DEDENT> <DEDENT> def get_tempfile(self, filename): <NEW_LINE> <INDENT> return os.path.join(self.tempdir, filename) <NEW_LINE> <DEDENT> def touch(self, filepath): <NEW_LINE> <INDENT> folder, filename = os.path.split(filepath) <NEW_LINE> if not os.path.isdir(folder): <NEW_LINE> <INDENT> mkdir_p(folder) <NEW_LINE> <DEDENT> self.assertTrue(os.path.isdir(folder)) <NEW_LINE> with open(filepath, 'w') as fp: <NEW_LINE> <INDENT> fp.write(' ') <NEW_LINE> <DEDENT> self.assertTrue(os.path.isfile(filepath)) <NEW_LINE> <DEDENT> def chmod600(self, filepath): <NEW_LINE> <INDENT> check_and_fix_urw_only(filepath) | Base Leap TestCase | 62599063379a373c97d9a720 |
class XLBook: <NEW_LINE> <INDENT> def __init__(self, file): <NEW_LINE> <INDENT> self.workbook = xlrd.open_workbook(file) <NEW_LINE> self.mysheets = {} <NEW_LINE> for name in self.workbook.sheet_names(): <NEW_LINE> <INDENT> data = to_array(XLSheet( self.workbook.sheet_by_name(name))) <NEW_LINE> self.mysheets[name] = data <NEW_LINE> <DEDENT> <DEDENT> def sheets(self): <NEW_LINE> <INDENT> return self.mysheets | XLSBook reader
It reads xls, xlsm, xlsx work book | 62599063097d151d1a2c276d |
class DuplicateVariables(Exception): <NEW_LINE> <INDENT> def __init__(self, variables): <NEW_LINE> <INDENT> super().__init__( 'Variable/s "{}" used more than once in a utility' ' definition'.format(variables) ) | Exception for duplicate parameters in a utility definition. | 6259906356ac1b37e6303868 |
class StorageLoggerDecorator(StorageDecorator): <NEW_LINE> <INDENT> def put(self, key: str, data: str): <NEW_LINE> <INDENT> print(' - put "%s:%s"' % (key, data)) <NEW_LINE> return self._component.put(key, data) <NEW_LINE> <DEDENT> def get(self, key: str) -> str: <NEW_LINE> <INDENT> data = self._component.get(key) <NEW_LINE> print(' - get "%s" key ("%s" data)' % (key, data)) <NEW_LINE> return data | Logging decorator class, for Storage class.
Log to console when put() and get() methods are called. | 62599063796e427e5384fe78 |
class BillItem(db.Model): <NEW_LINE> <INDENT> __tablename__ = "bill_items" <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> bill_id = db.Column(db.Integer,db.ForeignKey('bills.id')) <NEW_LINE> item_id = db.Column(db.Integer,db.ForeignKey('items.id')) <NEW_LINE> item_price = db.Column(db.DECIMAL(10,2)) <NEW_LINE> quantity = db.Column(db.Integer) <NEW_LINE> discount = db.Column(db.DECIMAL(10,2),default=0.00) <NEW_LINE> total_price = db.Column(db.DECIMAL(10,2)) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<BillItem: {}>'.format(self.bill_id) | Create a Bill Items table | 625990631f037a2d8b9e53ec |
class JFS(FS): <NEW_LINE> <INDENT> _type = "jfs" <NEW_LINE> _mkfs = "mkfs.jfs" <NEW_LINE> _modules = ["jfs"] <NEW_LINE> _labelfs = fslabeling.JFSLabeling() <NEW_LINE> _defaultFormatOptions = ["-q"] <NEW_LINE> _maxSize = Size("8 TiB") <NEW_LINE> _formattable = True <NEW_LINE> _linuxNative = True <NEW_LINE> _dump = True <NEW_LINE> _check = True <NEW_LINE> _infofs = "jfs_tune" <NEW_LINE> _defaultInfoOptions = ["-l"] <NEW_LINE> _existingSizeFields = ["Physical block size:", "Aggregate size:"] <NEW_LINE> partedSystem = fileSystemType["jfs"] <NEW_LINE> @property <NEW_LINE> def supported(self): <NEW_LINE> <INDENT> supported = self._supported <NEW_LINE> if flags.jfs: <NEW_LINE> <INDENT> supported = self.utilsAvailable <NEW_LINE> <DEDENT> return supported | JFS filesystem | 625990630c0af96317c578e0 |
class MnistReader(object): <NEW_LINE> <INDENT> def __init__(self, role): <NEW_LINE> <INDENT> self.__dict__.update(mnist_constants) <NEW_LINE> if role not in ['train', 'test']: <NEW_LINE> <INDENT> raise ValueError('Invalid Role: {}'.format(role)) <NEW_LINE> <DEDENT> if role == 'train': <NEW_LINE> <INDENT> train_data_filename = self.check_download('train-images-idx3-ubyte.gz') <NEW_LINE> train_labels_filename = self.check_download('train-labels-idx1-ubyte.gz') <NEW_LINE> self.data = self.extract_data(train_data_filename, 60000) <NEW_LINE> self.labels = self.extract_labels(train_labels_filename, 60000) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> test_data_filename = self.check_download('t10k-images-idx3-ubyte.gz') <NEW_LINE> test_labels_filename = self.check_download('t10k-labels-idx1-ubyte.gz') <NEW_LINE> self.data = self.extract_data(test_data_filename, 10000) <NEW_LINE> self.labels = self.extract_labels(test_labels_filename, 10000) <NEW_LINE> <DEDENT> self.datasize = self.data.shape[0] <NEW_LINE> <DEDENT> def check_download(self, filename): <NEW_LINE> <INDENT> WORK_DIRECTORY = MnistConfig.DATA_PATH <NEW_LINE> if not tf.gfile.Exists(WORK_DIRECTORY): <NEW_LINE> <INDENT> tf.gfile.MakeDirs(WORK_DIRECTORY) <NEW_LINE> <DEDENT> filepath = os.path.join(WORK_DIRECTORY, filename) <NEW_LINE> if not tf.gfile.Exists(filepath): <NEW_LINE> <INDENT> filepath, _ = urllib.request.urlretrieve(self.SOURCE_URL + filename, filepath) <NEW_LINE> with tf.gfile.GFile(filepath) as f: <NEW_LINE> <INDENT> size = f.Size() <NEW_LINE> <DEDENT> tf.logging.info('Successfully downloaded {}, {} bytes'.format(filename, size)) <NEW_LINE> <DEDENT> return filepath <NEW_LINE> <DEDENT> def extract_data(self, filename, num_images): <NEW_LINE> <INDENT> tf.logging.info('Extracting {}'.format(filename)) <NEW_LINE> with gzip.open(filename) as bytestream: <NEW_LINE> <INDENT> bytestream.read(16) <NEW_LINE> buf = bytestream.read(self.IMAGE_SIZE * self.IMAGE_SIZE * num_images) <NEW_LINE> data = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.float32) <NEW_LINE> data = (data - (self.PIXEL_DEPTH / 2.0)) / self.PIXEL_DEPTH <NEW_LINE> data = data.reshape(num_images, self.IMAGE_SIZE, self.IMAGE_SIZE, 1) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def extract_labels(self, filename, num_images): <NEW_LINE> <INDENT> print('Extracting', filename) <NEW_LINE> with gzip.open(filename) as bytestream: <NEW_LINE> <INDENT> bytestream.read(8) <NEW_LINE> buf = bytestream.read(1 * num_images) <NEW_LINE> labels = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.int64) <NEW_LINE> <DEDENT> return labels <NEW_LINE> <DEDENT> def get_meta_info(self): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def get_all_data(self): <NEW_LINE> <INDENT> return {'data': self.data, 'label': self.labels} <NEW_LINE> <DEDENT> def get_data_size(self): <NEW_LINE> <INDENT> return self.datasize | Mnist Reader reads mnist dataset from downloaded files.
| 6259906366673b3332c31aff |
class SourceStructure(BaseAnnotation): <NEW_LINE> <INDENT> data = True <NEW_LINE> def __init__(self, doc): <NEW_LINE> <INDENT> super().__init__(io.STRUCTURE_FILE, doc) <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> return io.read_data(self.doc, self) <NEW_LINE> <DEDENT> def write(self, structure): <NEW_LINE> <INDENT> structure.sort() <NEW_LINE> io.write_data(self.doc, self, "\n".join(structure)) | Every annotation available in a source document. | 6259906345492302aabfdbde |
class RedisComponent(Component): <NEW_LINE> <INDENT> def __init__(self, connections: Dict[str, Dict[str, Any]] = None, **default_client_args): <NEW_LINE> <INDENT> assert check_argument_types() <NEW_LINE> if not connections: <NEW_LINE> <INDENT> default_client_args.setdefault('context_attr', 'redis') <NEW_LINE> connections = {'default': default_client_args} <NEW_LINE> <DEDENT> self.clients: List[Tuple[str, str, dict]] = [] <NEW_LINE> for resource_name, config in connections.items(): <NEW_LINE> <INDENT> config = merge_config(default_client_args, config or {}) <NEW_LINE> context_attr = config.pop('context_attr', resource_name) <NEW_LINE> client_args = self.configure_client(**config) <NEW_LINE> self.clients.append((resource_name, context_attr, client_args)) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def configure_client( cls, address: Union[str, Path] = 'localhost', port: int = 6379, db: int = 0, username: Optional[str] = None, password: Optional[str] = None, ssl: bool = False, **client_args) -> Dict[str, Any]: <NEW_LINE> <INDENT> assert check_argument_types() <NEW_LINE> if username or password: <NEW_LINE> <INDENT> credentials = f'{username or ""}:{password or ""}@' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> credentials = '' <NEW_LINE> <DEDENT> if isinstance(address, Path) or address.startswith('/'): <NEW_LINE> <INDENT> client_args['url'] = f'unix://{credentials}{address}?db={db}' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> scheme = 'rediss' if ssl else 'redis' <NEW_LINE> client_args['url'] = f'{scheme}://{credentials}{address}:{port}/{db}' <NEW_LINE> <DEDENT> return client_args <NEW_LINE> <DEDENT> @context_teardown <NEW_LINE> async def start(self, ctx: Context): <NEW_LINE> <INDENT> clients = [] <NEW_LINE> for resource_name, context_attr, config in self.clients: <NEW_LINE> <INDENT> redis = from_url(**config) <NEW_LINE> clients.append((resource_name, redis)) <NEW_LINE> ctx.add_resource(redis, resource_name, context_attr) <NEW_LINE> logger.info('Configured Redis client (%s / ctx.%s; url=%s)', resource_name, context_attr, config['url']) <NEW_LINE> <DEDENT> yield <NEW_LINE> for resource_name, redis in clients: <NEW_LINE> <INDENT> await redis.close() <NEW_LINE> await redis.connection_pool.disconnect() <NEW_LINE> logger.info('Redis client (%s) shut down', resource_name) | Creates one or more :class:`aioredis.Redis` resources.
If ``connections`` is given, a Redis client resource will be published for each key in the
dictionary, using the key as the resource name. Any extra keyword arguments to the component
constructor will be used as defaults for omitted configuration values.
If ``connections`` is omitted, a single Redis client resource (``default`` / ``ctx.redis``)
is published using any extra keyword arguments passed to the component.
The client(s) will not connect to the target database until they're used for the first time.
:param connections: a dictionary of resource name ⭢ :meth:`configure_client` arguments
:param default_client_args: default values for omitted :meth:`configure_client`
arguments | 6259906363d6d428bbee3e0a |
class TestRevisionedResource(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testRevisionedResource(self): <NEW_LINE> <INDENT> pass | RevisionedResource unit test stubs | 62599063d7e4931a7ef3d707 |
class Timer(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Timer, self).__init__() <NEW_LINE> self.old_time = 0 <NEW_LINE> self.new_time = 0 <NEW_LINE> self.last_time = 0 <NEW_LINE> self.diff_time = 0 <NEW_LINE> self.speed_factor = 0 <NEW_LINE> self.num_frames = 0 <NEW_LINE> self.frames = 0 <NEW_LINE> <DEDENT> def on_update(self): <NEW_LINE> <INDENT> self.new_time = pygame.time.get_ticks() <NEW_LINE> self.diff_time = self.new_time - self.last_time <NEW_LINE> if self.new_time > self.old_time + 1000.: <NEW_LINE> <INDENT> self.old_time = self.new_time <NEW_LINE> self.frames = self.num_frames <NEW_LINE> self.num_frames = 0 <NEW_LINE> <DEDENT> self.speed_factor = self.diff_time / 1000. * 32. <NEW_LINE> if self.speed_factor > 1: <NEW_LINE> <INDENT> self.speed_factor = 1 <NEW_LINE> <DEDENT> self.last_time = self.new_time <NEW_LINE> self.num_frames += 1 | A class that updates fps and speedfactor
requires: pygame | 625990630a50d4780f706941 |
class GetRspvs(Resource): <NEW_LINE> <INDENT> @jwt_required <NEW_LINE> def get(self, rspv_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rspv_id = int(rspv_id) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return { "status": 404, "error": "Url need an integer" }, 404 <NEW_LINE> <DEDENT> new_rspv = repv_views.get_a_specific_rspvs(id=rspv_id) <NEW_LINE> if not new_rspv: <NEW_LINE> <INDENT> return { "status": 404, "error": "RSPV of id {} not found".format(rspv_id) }, 404 <NEW_LINE> <DEDENT> return { "status": 200, "data": new_rspv }, 200 | Class to get all RSPVS | 625990637047854f46340ac2 |
class AutoCompleteSelectWidget(forms.widgets.TextInput): <NEW_LINE> <INDENT> add_link = None <NEW_LINE> def __init__(self, channel, help_text = u'', show_help_text = True, plugin_options = {}, *args, **kwargs): <NEW_LINE> <INDENT> self.plugin_options = plugin_options <NEW_LINE> super(forms.widgets.TextInput, self).__init__(*args, **kwargs) <NEW_LINE> self.channel = channel <NEW_LINE> self.help_text = help_text <NEW_LINE> self.show_help_text = show_help_text <NEW_LINE> <DEDENT> def render(self, name, value, attrs=None): <NEW_LINE> <INDENT> value = value or '' <NEW_LINE> final_attrs = self.build_attrs(attrs) <NEW_LINE> self.html_id = final_attrs.pop('id', name) <NEW_LINE> current_repr = '' <NEW_LINE> initial = None <NEW_LINE> lookup = get_lookup(self.channel) <NEW_LINE> if value: <NEW_LINE> <INDENT> objs = lookup.get_objects([value]) <NEW_LINE> try: <NEW_LINE> <INDENT> obj = objs[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise Exception("%s cannot find object:%s" % (lookup, value)) <NEW_LINE> <DEDENT> current_repr = lookup.format_item_display(obj) <NEW_LINE> initial = [current_repr,obj.pk] <NEW_LINE> <DEDENT> if self.show_help_text: <NEW_LINE> <INDENT> help_text = self.help_text <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> help_text = u'' <NEW_LINE> <DEDENT> context = { 'name': name, 'html_id': self.html_id, 'current_id': value, 'current_repr': current_repr, 'help_text': help_text, 'extra_attrs': mark_safe(flatatt(final_attrs)), 'func_slug': self.html_id.replace("-",""), 'add_link': self.add_link, } <NEW_LINE> context.update(plugin_options(lookup,self.channel,self.plugin_options,initial)) <NEW_LINE> context.update(bootstrap()) <NEW_LINE> return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),context)) <NEW_LINE> <DEDENT> def value_from_datadict(self, data, files, name): <NEW_LINE> <INDENT> got = data.get(name, None) <NEW_LINE> if len(got) == 36: <NEW_LINE> <INDENT> return got <NEW_LINE> <DEDENT> elif got: <NEW_LINE> <INDENT> return long(got) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def id_for_label(self, id_): <NEW_LINE> <INDENT> return '%s_text' % id_ | widget to select a model and return it as text | 62599063f548e778e596cc8d |
class Boolean(odoorpc_Boolean, BaseField): <NEW_LINE> <INDENT> pass | Equivalent of the `fields.Boolean` class. | 6259906345492302aabfdbdf |
class rnn_model: <NEW_LINE> <INDENT> def __init__(self, model_def): <NEW_LINE> <INDENT> def create_lstm(model_def): <NEW_LINE> <INDENT> cell = rnn.BasicLSTMCell(model_def.hidden_size, forget_bias=0.0, state_is_tuple=True, reuse=tf.get_variable_scope().reuse) <NEW_LINE> if model_def.keep_prob < 1 : <NEW_LINE> <INDENT> cell = tf.contrib.rnn.DropoutWrapper( cell, output_keep_prob=model_def.keep_prob) <NEW_LINE> <DEDENT> return cell <NEW_LINE> <DEDENT> self.x = tf.placeholder(tf.float32, [None, model_def.steps, code_data.vocabulary_size]) <NEW_LINE> self.y = tf.placeholder(tf.float32, [None, code_data.vocabulary_size]) <NEW_LINE> weights = { 'out': tf.Variable(tf.random_normal([model_def.hidden_size, code_data.vocabulary_size])) } <NEW_LINE> biases = { 'out': tf.Variable(tf.random_normal([code_data.vocabulary_size])) } <NEW_LINE> lstm_cell = rnn.MultiRNNCell([create_lstm(model_def) for _ in range(model_def.LTSM_layers)], state_is_tuple=True) <NEW_LINE> _x = tf.unstack(self.x, model_def.steps, 1) <NEW_LINE> outputs, states = rnn.static_rnn(lstm_cell, _x, dtype=tf.float32) <NEW_LINE> self.pred = tf.matmul(outputs[-1], weights['out']) + biases['out'] <NEW_LINE> self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.pred, labels=self.y)) <NEW_LINE> correct_pred = tf.equal(tf.argmax(self.pred, 1), tf.argmax(self.y, 1)) <NEW_LINE> self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) | define a cnn model | 625990634a966d76dd5f05f9 |
class BuildIOTable(BuildTasksTable): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(BuildIOTable, self).__init__(*args, **kwargs) <NEW_LINE> self.default_orderby = "-disk_io" <NEW_LINE> <DEDENT> def setup_columns(self, *args, **kwargs): <NEW_LINE> <INDENT> super(BuildIOTable, self).setup_columns(**kwargs) <NEW_LINE> self.columns[self.toggle_columns['order']]['hidden'] = True <NEW_LINE> self.columns[self.toggle_columns['order']]['hideable'] = True <NEW_LINE> self.columns[self.toggle_columns['sstate_result']]['hidden'] = True <NEW_LINE> self.columns[self.toggle_columns['disk_io']]['hidden'] = False | Same as tasks table but the Disk IO column is default displayed | 6259906324f1403a92686450 |
class ImportHelper: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def import_error_handling(import_this_module, modulescope): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> exec("import %s " % import_this_module) in modulescope <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> print("This program requires %s in order to run. Please run" % import_this_module) <NEW_LINE> print("pip install %s" % import_this_module) <NEW_LINE> print("To install the missing component") <NEW_LINE> sys.exit() | This class simply allows for the dynamic loading of modules which are not apart of the stdlib.
It specifies which module cannot be imported and provides the proper pip install command as output to the user. | 625990635166f23b2e244ad7 |
class deleteTable_args(object): <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'tableName', None, None, ), ) <NEW_LINE> def __init__(self, tableName=None,): <NEW_LINE> <INDENT> self.tableName = tableName <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.tableName = iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('deleteTable_args') <NEW_LINE> if self.tableName is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('tableName', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.tableName) <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 __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.tableName) <NEW_LINE> return value <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:
- tableName: name of table to delete | 625990637b25080760ed8863 |
class Arbeitgeber(Base): <NEW_LINE> <INDENT> __tablename__ = "arbeitgeber" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String) | an employer can have more than one addresses and offer more than one jobs | 6259906338b623060ffaa3d3 |
class DualPointEstimateTracer(PointEstimateTracer): <NEW_LINE> <INDENT> def __init__(self, model: FilteredStateSpaceModelFreeProposal): <NEW_LINE> <INDENT> super().__init__(model) <NEW_LINE> <DEDENT> def append(self, ζ, η, objective): <NEW_LINE> <INDENT> super().append(torch.cat([ζ, η]), objective) | Tracer for dual optimization algorithms. | 62599063442bda511e95d8dc |
class HistogramValidator(object): <NEW_LINE> <INDENT> def __init__(self, product, sensor, fdr=_BASE_DIR): <NEW_LINE> <INDENT> super(HistogramValidator, self).__init__() <NEW_LINE> try: <NEW_LINE> <INDENT> info = _MEMBER_INFO[product] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise NotImplementedError( f"Invalid product: {product}\nAvailable choices: " + ", ".join(_MEMBER_INFO.keys()) ) <NEW_LINE> <DEDENT> if sensor not in info: <NEW_LINE> <INDENT> raise NotImplementedError( f"Invalid sensor for {product}: {sensor}\nAvailable choices: " + ", ".join(info.keys()) ) <NEW_LINE> <DEDENT> if not os.path.isdir(fdr): <NEW_LINE> <INDENT> raise ValueError(f"Invalid folder: {fdr}") <NEW_LINE> <DEDENT> product_fdr = os.path.join(fdr, product) <NEW_LINE> if not os.path.isdir(product_fdr): <NEW_LINE> <INDENT> raise ValueError(f"Product folder unavailable: {product_fdr}") <NEW_LINE> <DEDENT> self._product = product <NEW_LINE> self._sensor = sensor <NEW_LINE> self._fdr = product_fdr <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"Product {self._product} evaluating {self._sensor} at {self._fdr}" <NEW_LINE> <DEDENT> def __getitem__(self, offset): <NEW_LINE> <INDENT> if offset not in self.offset_range: <NEW_LINE> <INDENT> raise IndexError(f"Index {offset} outside {self.offset_range}") <NEW_LINE> <DEDENT> return HistogramValidation( self._product, self._sensor, offset, self._fdr ) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for offset in self.offset_range: <NEW_LINE> <INDENT> yield HistogramValidation( self._product, self._sensor, offset, self._fdr ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def offset_range(self): <NEW_LINE> <INDENT> i, j, _, _ = _MEMBER_INFO[self._product][self._sensor] <NEW_LINE> return range(i, j+1) | Convience for iterating over a set of histograms | 625990633eb6a72ae038bd64 |
class Combination: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> dices = [] <NEW_LINE> self.dices = dices <NEW_LINE> order = [] <NEW_LINE> self.order = order <NEW_LINE> calc_string = "" <NEW_LINE> self.calc_string = calc_string <NEW_LINE> self.result = 0 <NEW_LINE> self.calc_rule = 1 <NEW_LINE> self.dice = [] <NEW_LINE> self.pos1 = 0 <NEW_LINE> self.pos2 = 0 <NEW_LINE> self.string1 = "" <NEW_LINE> self.string2 = "" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.calc_string <NEW_LINE> <DEDENT> def get_result(self): <NEW_LINE> <INDENT> return self.result, self.calc_string <NEW_LINE> <DEDENT> def add_dice(self, dice, reverse=False): <NEW_LINE> <INDENT> if self.result < 100: <NEW_LINE> <INDENT> self.dice = dice <NEW_LINE> self.dices.append(self.dice) <NEW_LINE> if len(self.dices) > 2 and self.dice.calc > self.calc_rule: <NEW_LINE> <INDENT> self.calc_string = "(" + self.calc_string + ")" <NEW_LINE> <DEDENT> if self.dice.fact: <NEW_LINE> <INDENT> string_dice = str(self.dice.side) + "!" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> string_dice = str(self.dice.side) <NEW_LINE> <DEDENT> if reverse: <NEW_LINE> <INDENT> self.pos1 = self.dice.worth <NEW_LINE> self.pos2 = self.result <NEW_LINE> self.string1 = string_dice <NEW_LINE> self.string2 = self.calc_string <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.pos2 = self.dice.worth <NEW_LINE> self.pos1 = self.result <NEW_LINE> self.string2 = string_dice <NEW_LINE> self.string1 = self.calc_string <NEW_LINE> <DEDENT> if self.dice.calc == 0: <NEW_LINE> <INDENT> self.result = self.pos1 + self.pos2 <NEW_LINE> if self.calc_string == "": <NEW_LINE> <INDENT> self.calc_string = self.string2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.calc_string = self.string1 + "+" + self.string2 <NEW_LINE> self.calc_rule = 1 <NEW_LINE> <DEDENT> <DEDENT> elif self.dice.calc == 1: <NEW_LINE> <INDENT> self.result = self.pos1 - self.pos2 <NEW_LINE> self.calc_string = self.string1 + "-" + self.string2 <NEW_LINE> self.calc_rule = 1 <NEW_LINE> <DEDENT> elif self.dice.calc == 2: <NEW_LINE> <INDENT> self.result = self.pos1 * self.pos2 <NEW_LINE> self.calc_string = self.string1 + "*" + self.string2 <NEW_LINE> self.calc_rule = 3 <NEW_LINE> <DEDENT> elif self.dice.calc == 3: <NEW_LINE> <INDENT> self.result = self.pos1 / self.pos2 <NEW_LINE> self.calc_string = self.string1 + "/" + self.string2 <NEW_LINE> self.calc_rule = 3 <NEW_LINE> <DEDENT> elif self.dice.calc == 4: <NEW_LINE> <INDENT> if self.pos2 < 100: <NEW_LINE> <INDENT> self.result = self.pos1 ** self.pos2 <NEW_LINE> self.calc_string = self.string1 + "**" + self.string2 <NEW_LINE> self.calc_rule = 4 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print("Error") | a Combination consists of up to 4 dices and a result | 625990638e71fb1e983bd1d0 |
class FindUsersInputSet(InputSet): <NEW_LINE> <INDENT> def set_Email(self, value): <NEW_LINE> <INDENT> super(FindUsersInputSet, self)._set_input('Email', value) <NEW_LINE> <DEDENT> def set_FacebookID(self, value): <NEW_LINE> <INDENT> super(FindUsersInputSet, self)._set_input('FacebookID', value) <NEW_LINE> <DEDENT> def set_Name(self, value): <NEW_LINE> <INDENT> super(FindUsersInputSet, self)._set_input('Name', value) <NEW_LINE> <DEDENT> def set_OauthToken(self, value): <NEW_LINE> <INDENT> super(FindUsersInputSet, self)._set_input('OauthToken', value) <NEW_LINE> <DEDENT> def set_Phone(self, value): <NEW_LINE> <INDENT> super(FindUsersInputSet, self)._set_input('Phone', value) <NEW_LINE> <DEDENT> def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> super(FindUsersInputSet, self)._set_input('ResponseFormat', value) <NEW_LINE> <DEDENT> def set_TwitterSource(self, value): <NEW_LINE> <INDENT> super(FindUsersInputSet, self)._set_input('TwitterSource', value) <NEW_LINE> <DEDENT> def set_Twitter(self, value): <NEW_LINE> <INDENT> super(FindUsersInputSet, self)._set_input('Twitter', value) | An InputSet with methods appropriate for specifying the inputs to the FindUsers
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 62599063498bea3a75a59182 |
class JsonFileInteractiveLevelReader: <NEW_LINE> <INDENT> def __init__(self, message='Enter with a level path: '): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> level_path = input(self.message) <NEW_LINE> return JsonFileLevelReader(level_path).read() | JSON File interactive level reader. | 6259906316aa5153ce401be1 |
@symbolic_multi <NEW_LINE> class Chain(IParameterized): <NEW_LINE> <INDENT> def __init__(self, *processors): <NEW_LINE> <INDENT> self._processors = processors <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> out = args <NEW_LINE> for p in self._processors: <NEW_LINE> <INDENT> out = p.to_format(symbolic_multi)(*out) <NEW_LINE> <DEDENT> return out <NEW_LINE> <DEDENT> @property <NEW_LINE> def parameters(self): <NEW_LINE> <INDENT> return sum([p.parameters for p in self._processors if isinstance(p, IParameterized)], []) | A composition of symbolic functions:
Chain(f, g, h)(x) is f(g(h(x)))
tuple_of_output_tensors = my_chain(input_tensor_0, input_tensor_1, ...)
If the last function in the chain returns just a single output, Chain can also be called in the
symbolic_simple format:
output_tensor = my_chain.symbolic_simple(input_0, input_1, ...)
If, however, the last function returns multiple updates, this will raise an Exception. | 62599063cb5e8a47e493cd07 |
class Status(enum.Enum): <NEW_LINE> <INDENT> Unknown = -1 <NEW_LINE> Shutdown = 0 <NEW_LINE> Standby = 1 <NEW_LINE> Pause = 2 <NEW_LINE> Appointment = 3 <NEW_LINE> Cooking = 4 <NEW_LINE> Preheat = 5 <NEW_LINE> Cooked = 6 <NEW_LINE> PreheatFinish = 7 <NEW_LINE> PreheatPause = 8 <NEW_LINE> Pause2 = 9 | Status | 62599063f548e778e596cc8e |
class W27(VOSIWarning, XMLWarning): <NEW_LINE> <INDENT> message_template = "The form element must not occur more than once" | The `form` element must not occur more than once. | 625990638a43f66fc4bf3894 |
class IRowTypesCriterionSettings(Interface): <NEW_LINE> <INDENT> type_name = schema.TextLine( title=_(u"General type name"), description=_(u"A descriptive name for the content type you want to define"), default=u"", missing_value=u"", required=True, ) <NEW_LINE> types_matched = schema.Tuple( title=_(u'Select all native content types that match'), description=_('help_types_matched', default=u"Select all primitive content types that will be queried when this new " u"general type will be selected."), required=True, default=(), missing_value=(), value_type=schema.Choice(vocabulary=u'plone.app.vocabularies.ReallyUserFriendlyTypes'), ) | Single configuration entry for types criterion | 62599063627d3e7fe0e08590 |
class problemBase(object): <NEW_LINE> <INDENT> def __init__(self, name, noseed=False): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> if not noseed: <NEW_LINE> <INDENT> np.random.seed(seed=0) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def A(self): <NEW_LINE> <INDENT> return self._A <NEW_LINE> <DEDENT> @property <NEW_LINE> def M(self): <NEW_LINE> <INDENT> return self._M <NEW_LINE> <DEDENT> @property <NEW_LINE> def B(self): <NEW_LINE> <INDENT> return self._B <NEW_LINE> <DEDENT> @property <NEW_LINE> def b(self): <NEW_LINE> <INDENT> return self._b <NEW_LINE> <DEDENT> @property <NEW_LINE> def signal(self): <NEW_LINE> <INDENT> return self._signal <NEW_LINE> <DEDENT> @property <NEW_LINE> def x0(self): <NEW_LINE> <INDENT> return self._x0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def signal_shape(self): <NEW_LINE> <INDENT> return self._signal_shape <NEW_LINE> <DEDENT> def _completeOps(self): <NEW_LINE> <INDENT> if not hasattr(self, '_A') and not hasattr(self, '_M') and not hasattr(self, '_B'): <NEW_LINE> <INDENT> raise Exception('At least one of the operator fileds _A, _M or _B is required.') <NEW_LINE> <DEDENT> if not hasattr(self, '_A'): <NEW_LINE> <INDENT> if not hasattr(self, '_M'): <NEW_LINE> <INDENT> self._M = opDirac(self._B.shape[0]) <NEW_LINE> operators = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> operators = [self._M] <NEW_LINE> <DEDENT> if not hasattr(self, '_B'): <NEW_LINE> <INDENT> self._B = opDirac(self._M.shape[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> operators.append(self._B) <NEW_LINE> <DEDENT> if len(operators) > 1: <NEW_LINE> <INDENT> self._A = opFoG(operators) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._A = operators[0] <NEW_LINE> <DEDENT> <DEDENT> if not hasattr(self, '_x0'): <NEW_LINE> <INDENT> self._x0 = None <NEW_LINE> <DEDENT> if not hasattr(self, '_signal_shape'): <NEW_LINE> <INDENT> if not hasattr(self, '_signal'): <NEW_LINE> <INDENT> raise Exception('At least one of the fields _signal or _signal_shape is required.') <NEW_LINE> <DEDENT> self._signal_shape = self._signal.shape <NEW_LINE> <DEDENT> <DEDENT> def reconstruct(self, x): <NEW_LINE> <INDENT> y = self._B(x).reshape(self._signal_shape) <NEW_LINE> return y | Base class for all CS problems. The problems follow
the quation below:
.. math::
A x = b
A = M B
where :math:`A` is an operator acting on a sparse signal :math:`x`
and :math:`b` is the observation vector. :math:`A` can be factored
into :math:`M` which represents the system response and :math:`B`
basis that sparsifies the signal.
Attributes
----------
name : string
Name of problem.
A : Instance of a subclass of opBase
The :math:`A` matrix of the problem.
M : Instance of a subclass of opBase
:math:`M`, sampling matrix of the problem.
B : Instance of a subclass of opBase
:math:`B`, sparsifying basis matrix of the problem.
b : array of arbitrary shape
:math:'b', observation array.
signal : array of arbitrary shape
Signal in original basis (Not in the sparsifying basis)
signal_shape : tuple of integers
:math:'b', Shape of the signal in the sparsifying basis.
Methods
-------
reconstruct : Reconstruct signal from sparse coefficients. | 62599063009cb60464d02c3d |
class OccupantQuantityType(BSElement): <NEW_LINE> <INDENT> element_type = "xs:string" <NEW_LINE> element_enumerations = [ "Peak total occupants", "Adults", "Children", "Average residents", "Workers on main shift", "Full-time equivalent workers", "Average daily salaried labor hours", "Registered students", "Staffed beds", "Licensed beds", "Capacity", "Capacity percentage", "Normal occupancy", ] | Type of quantitative measure for capturing occupant information about the premises. The value is captured by the Occupant Quantity term. | 62599063d7e4931a7ef3d708 |
class NN(object): <NEW_LINE> <INDENT> def __init__(self, network_architecture,learning_rate=0.001, batch_size=100): <NEW_LINE> <INDENT> self.sess = tf.InteractiveSession() <NEW_LINE> self.network_architecture = network_architecture <NEW_LINE> self.learning_rate = learning_rate <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.x = tf.placeholder(tf.float32, [None, network_architecture["n_input"]]) <NEW_LINE> self.y = tf.placeholder(tf.float32, [None, network_architecture["n_classes"]]) <NEW_LINE> W1 = tf.Variable(xavier_init(network_architecture["n_input"], network_architecture["n_hidden1"])) <NEW_LINE> W2 = tf.Variable(xavier_init(network_architecture["n_hidden1"], network_architecture["n_hidden2"])) <NEW_LINE> W3 = tf.Variable(xavier_init(network_architecture["n_hidden2"], network_architecture["n_hidden3"])) <NEW_LINE> W4 = tf.Variable(xavier_init(network_architecture["n_hidden3"], network_architecture["n_classes"])) <NEW_LINE> b1 = tf.Variable(tf.ones([network_architecture["n_hidden1"]], dtype=tf.float32)) <NEW_LINE> b2 = tf.Variable(tf.ones([network_architecture["n_hidden2"]], dtype=tf.float32)) <NEW_LINE> b3 = tf.Variable(tf.ones([network_architecture["n_hidden3"]], dtype=tf.float32)) <NEW_LINE> b4 = tf.Variable(tf.ones([network_architecture["n_classes"]], dtype=tf.float32)) <NEW_LINE> self.h1 = tf.nn.softmax(tf.add(tf.matmul(self.x, W1), b1)) <NEW_LINE> self.h2 = tf.nn.softmax(tf.add(tf.matmul(self.h1, W2), b2)) <NEW_LINE> self.h3 = tf.nn.softmax(tf.add(tf.matmul(self.h2, W3), b3)) <NEW_LINE> self.output = tf.nn.softmax(tf.add(tf.matmul(self.h3, W4),b4)) <NEW_LINE> with tf.name_scope("loss") as scope: <NEW_LINE> <INDENT> self.cost = tf.reduce_mean(tf.square(self.y - self.output)) <NEW_LINE> <DEDENT> with tf.name_scope("train") as scope: <NEW_LINE> <INDENT> self.optimizer = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(self.cost) <NEW_LINE> <DEDENT> self.merged = tf.merge_all_summaries() <NEW_LINE> self.writer = tf.train.SummaryWriter("/tmp/mnist_logs", self.sess.graph_def) <NEW_LINE> correct_prediction = tf.equal(tf.argmax(self.y, 1), tf.argmax(self.output, 1)) <NEW_LINE> self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) <NEW_LINE> tf.initialize_all_variables().run() <NEW_LINE> <DEDENT> def log_stats(self, X): <NEW_LINE> <INDENT> result = self.sess.run(self.merged, feed_dict={self.x: X, self.y: Y}) <NEW_LINE> self.writer.add_summary(result) <NEW_LINE> <DEDENT> def train(self, X, Y): <NEW_LINE> <INDENT> self.sess.run(self.optimizer, feed_dict={self.x: X, self.y: Y}) <NEW_LINE> return self.sess.run(self.cost, feed_dict={self.x: X, self.y: Y}) <NEW_LINE> <DEDENT> def predict(self, X, Y): <NEW_LINE> <INDENT> return self.sess.run(self.output,feed_dict={self.x: X, self.y: Y}), self.sess.run(self.cost,feed_dict={self.x: X, self.y: Y}) | Denoising Autoencoder with an sklearn-like interface implemented using TensorFlow.
adapted from https://jmetzen.github.io/2015-11-27/vae.html | 625990638e71fb1e983bd1d1 |
class AttributeVisitor(ast.NodeVisitor): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.is_usable = True <NEW_LINE> self.name = [] <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return '.'.join(self.name) <NEW_LINE> <DEDENT> def visit_Attribute(self, node): <NEW_LINE> <INDENT> self.generic_visit(node) <NEW_LINE> self.name.append(node.attr) <NEW_LINE> <DEDENT> def visit_Name(self, node): <NEW_LINE> <INDENT> self.name.append(node.id) <NEW_LINE> <DEDENT> def visit_Load(self, node): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def generic_visit(self, node): <NEW_LINE> <INDENT> if not isinstance(node, ast.Attribute): <NEW_LINE> <INDENT> self.is_usable = False <NEW_LINE> <DEDENT> ast.NodeVisitor.generic_visit(self, node) | Process attribute node and build the name of the attribute if possible.
Currently only simple expressions are supported (like `foo.bar.baz`).
If it is not possible to get attribute name as string `is_usable` is
set to `True`.
After `visit()` method call `get_name()` method can be used to get
attribute name if `is_usable` == `True`. | 6259906307f4c71912bb0b3d |
class GenericSelect(QDialog, Ui_Dialog): <NEW_LINE> <INDENT> ADD, SEARCH = range(2) <NEW_LINE> def __init__(self, parent=None): <NEW_LINE> <INDENT> super(GenericSelect, self).__init__(parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self._stackedWidget = QStackedWidget() <NEW_LINE> self.contentsPlaceholder.addWidget(self._stackedWidget) <NEW_LINE> self.setup_add() <NEW_LINE> self.setup_search() <NEW_LINE> self._record = None <NEW_LINE> self._searchForm.viewSearch.doubleClicked.disconnect() <NEW_LINE> self._searchForm.viewSearch.doubleClicked.connect(self.on_btnSelect_clicked) <NEW_LINE> self._function = None <NEW_LINE> self.toggle_function() <NEW_LINE> self.adjustSize() <NEW_LINE> <DEDENT> def setup_add(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setup_search(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def toggle_function(self): <NEW_LINE> <INDENT> if self._function == self.SEARCH: <NEW_LINE> <INDENT> self._function = self.ADD <NEW_LINE> self.btnToggleFuncion.setText("Voltar") <NEW_LINE> self.btnToggleFuncion.setIcon(QIcon(":icons/search.png")) <NEW_LINE> self.btnSelect.setText("Salvar") <NEW_LINE> self.btnSelect.setIcon(QIcon(":icons/save.png")) <NEW_LINE> self._stackedWidget.setCurrentWidget(self._addForm) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._function = self.SEARCH <NEW_LINE> self.btnToggleFuncion.setText("Cadastrar") <NEW_LINE> self.btnSelect.setText("Selecionar") <NEW_LINE> self.btnSelect.setIcon(QIcon(":icons/conn_succeeded.png")) <NEW_LINE> self._stackedWidget.setCurrentWidget(self._searchForm) <NEW_LINE> self._searchForm.refresh() <NEW_LINE> <DEDENT> <DEDENT> def selected_record(self, index): <NEW_LINE> <INDENT> self._record = self._searchForm.get_record_at(index) <NEW_LINE> <DEDENT> def added_record(self): <NEW_LINE> <INDENT> self._record = self._addForm.get_added_record() <NEW_LINE> <DEDENT> def get_record(self): <NEW_LINE> <INDENT> return self._record <NEW_LINE> <DEDENT> @QtCore.Slot() <NEW_LINE> def on_btnToggleFuncion_clicked(self): <NEW_LINE> <INDENT> self.toggle_function() <NEW_LINE> <DEDENT> @QtCore.Slot() <NEW_LINE> def on_btnCancel_clicked(self): <NEW_LINE> <INDENT> self.reject() <NEW_LINE> <DEDENT> @QtCore.Slot() <NEW_LINE> def on_btnSelect_clicked(self): <NEW_LINE> <INDENT> if self._function == self.SEARCH: <NEW_LINE> <INDENT> index = self._searchForm.get_current_index() <NEW_LINE> if index.isValid(): <NEW_LINE> <INDENT> self.selected_record(index) <NEW_LINE> self.accept() <NEW_LINE> <DEDENT> <DEDENT> elif self._function == self.ADD: <NEW_LINE> <INDENT> ok = self._addForm.submit_data() <NEW_LINE> if ok: <NEW_LINE> <INDENT> self.added_record() <NEW_LINE> self.accept() | Common selection interface | 6259906345492302aabfdbe1 |
class Layer(ABC, Thread): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass | Abstract class for Layer | 625990637d847024c075dadc |
class TestCSInsertUserRequest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testCSInsertUserRequest(self): <NEW_LINE> <INDENT> pass | CSInsertUserRequest unit test stubs | 6259906324f1403a92686451 |
class UngriddedBoundedCube(UngriddedCube): <NEW_LINE> <INDENT> def __init__(self, data, metadata, coords): <NEW_LINE> <INDENT> from cis.data_io.Coord import CoordList <NEW_LINE> from cis.utils import listify <NEW_LINE> def getmask(arr): <NEW_LINE> <INDENT> mask = np.ma.getmaskarray(arr) <NEW_LINE> try: <NEW_LINE> <INDENT> mask |= np.isnan(arr) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return mask <NEW_LINE> <DEDENT> data = listify(data) <NEW_LINE> metadata = listify(metadata) <NEW_LINE> if isinstance(coords, list): <NEW_LINE> <INDENT> self._coords = CoordList(coords) <NEW_LINE> <DEDENT> elif isinstance(coords, CoordList): <NEW_LINE> <INDENT> self._coords = coords <NEW_LINE> <DEDENT> elif isinstance(coords, Coord): <NEW_LINE> <INDENT> self._coords = CoordList([coords]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Invalid Coords type") <NEW_LINE> <DEDENT> combined_mask = np.zeros(data[0].shape, dtype=bool) <NEW_LINE> for coord in self._coords: <NEW_LINE> <INDENT> combined_mask |= getmask(coord.data) <NEW_LINE> for bound in np.moveaxis(coord.bounds, -1, 0): <NEW_LINE> <INDENT> combined_mask |= getmask(bound) <NEW_LINE> <DEDENT> coord.update_shape() <NEW_LINE> coord.update_range() <NEW_LINE> <DEDENT> if combined_mask.any(): <NEW_LINE> <INDENT> keep = np.logical_not(combined_mask) <NEW_LINE> data = [variable[keep] for variable in data] <NEW_LINE> for coord in self._coords: <NEW_LINE> <INDENT> coord.data = coord.data[keep] <NEW_LINE> new_bounds = np.array([ bound[keep] for bound in np.moveaxis(coord.bounds, -1, 0) ]) <NEW_LINE> coord.bounds = np.moveaxis(new_bounds, 0, -1) <NEW_LINE> coord.update_shape() <NEW_LINE> coord.update_range() <NEW_LINE> <DEDENT> <DEDENT> super(UngriddedCube, self).__init__(zip(data, metadata)) <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> data, meta = list.__getitem__(self, item) <NEW_LINE> return UngriddedBoundedData(data, meta, self._coords) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for data, meta in list.__iter__(self): <NEW_LINE> <INDENT> yield UngriddedBoundedData(data, meta, self._coords) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def bounds_flattened(self): <NEW_LINE> <INDENT> all_coords = self.coords().find_standard_coords() <NEW_LINE> return [ c.bounds.reshape(-1, c.bounds.shape[-1]) if c is not None else None for c in all_coords ] <NEW_LINE> <DEDENT> def get_all_bounded_points(self): <NEW_LINE> <INDENT> return UngriddedArrayPointView(self.bounds_flattened, self.data_flattened) <NEW_LINE> <DEDENT> def get_non_masked_bounded_points(self): <NEW_LINE> <INDENT> return UngriddedArrayPointView(self.bounds_flattened, self.data_flattened, non_masked_iteration=True) | Cube of variables that share a set of ungridded coordinates.
Definitely not lazy in data management. Mostly copies UngriddedData except,
Methods:
__init__: Fork of cis.read_data_list to open necessary data and applies quality control.
data_flattened: A 2D array where each variable is flattened.
bounds_flattened: The bounds of all coordinates, as a list of lists. Used to calculate pixel borders.
get_all_bounded_points: HyperPointView that gives bounds of each coordinate.
get_non_masked_bounded_points: As above, but skips points with only masked values. | 62599063a8ecb0332587291e |
class TrackNode(_Node): <NEW_LINE> <INDENT> def __init__(self, path=None, parent=None): <NEW_LINE> <INDENT> super(TrackNode, self).__init__(path, parent) <NEW_LINE> if path: <NEW_LINE> <INDENT> path = os.path.join(self._path, u'.meta') <NEW_LINE> self.metadata = json.loads(open(path, 'r').read()) <NEW_LINE> (self.metadata[u"tracknumber"], self.metadata[u"title"]) = self.fn_decode(self._path) <NEW_LINE> _ = self.metadata[u'__filename__'] <NEW_LINE> if len(_) > 1: <NEW_LINE> <INDENT> self.metadata[u'__filename__'] = _[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> del self.metadata[u'__filename__'] <NEW_LINE> <DEDENT> self.filename = _[0] <NEW_LINE> self._parent.images = os.path.dirname(self.filename) <NEW_LINE> self.updateHeaders() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.metadata = dict() <NEW_LINE> <DEDENT> <DEDENT> def update(self, meta=None): <NEW_LINE> <INDENT> if meta: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _ = meta[u'__filename__'] <NEW_LINE> if len(_) > 1: <NEW_LINE> <INDENT> meta[u'__filename__'] = _[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> del meta[u'__filename__'] <NEW_LINE> <DEDENT> self.filename = _[0] <NEW_LINE> self._parent.images = os.path.dirname(self.filename) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> super(TrackNode, self).update(meta) <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> self._fclear((self.metadata[u'tracknumber'], self.metadata[u'title'])) <NEW_LINE> metadata = self.metadata.copy() <NEW_LINE> del metadata[u'tracknumber'] <NEW_LINE> del metadata[u'title'] <NEW_LINE> try: <NEW_LINE> <INDENT> _ = metadata[u'__filename__'] <NEW_LINE> metadata[u'__filename__'] = [self.filename, _] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> metadata[u'__filename__'] = [self.filename] <NEW_LINE> <DEDENT> self._fsave(metadata) <NEW_LINE> <DEDENT> def fn_encode(self, fn): <NEW_LINE> <INDENT> fn1, fn2 = fn <NEW_LINE> return urlsafe_b64encode("{0}.{1}".format(fn1, fn2)) <NEW_LINE> <DEDENT> def fn_decode(self, fn): <NEW_LINE> <INDENT> fn = unicode( urlsafe_b64decode(os.path.basename(fn.encode(u'utf-8'))) ).split(u'.') <NEW_LINE> return (fn[0], fn[1]) | Track node. | 625990632ae34c7f260ac7ed |
class CmdSyntaxError(FTPCmdError): <NEW_LINE> <INDENT> errorCode = SYNTAX_ERR | Raised when a command syntax is wrong. | 6259906391f36d47f2231a12 |
class issueOTP_result(object): <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.STRUCT, 'success', (OTPResult, OTPResult.thrift_spec), None, ), (1, TType.STRUCT, 'e', (ChannelException, ChannelException.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, e=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.e = e <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = OTPResult() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e = ChannelException() <NEW_LINE> self.e.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('issueOTP_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.e is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e', TType.STRUCT, 1) <NEW_LINE> self.e.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- e | 62599063460517430c432bd7 |
class PostsViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> permission_classes = (IsAuthenticated,) <NEW_LINE> queryset = Posts.objects.all().filter().order_by("-published") <NEW_LINE> serializer_class = PostsSerializer <NEW_LINE> def retrieve(self, request, *args, **kwargs): <NEW_LINE> <INDENT> postId = kwargs['pk'] <NEW_LINE> host = request.query_params.get('host', None) <NEW_LINE> post = None <NEW_LINE> if host: <NEW_LINE> <INDENT> find = False <NEW_LINE> servers = Server.objects.all() <NEW_LINE> server_serializer = ServerSerializer(instance=servers, context={'request': request}, many=True) <NEW_LINE> for server in server_serializer.data: <NEW_LINE> <INDENT> if host == server["domain"]: <NEW_LINE> <INDENT> find = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if find: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = '{}posts'.format(host) <NEW_LINE> response = requests.get(url=url) <NEW_LINE> data = response.json() <NEW_LINE> posts = data['posts'] <NEW_LINE> for i in posts: <NEW_LINE> <INDENT> if str(i["id"]) == str(postId): <NEW_LINE> <INDENT> post = i <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not post: <NEW_LINE> <INDENT> raise Exception("Cannot get the post with id = {}".format(postId)) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return Response(e.args, status=500) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return Response("The host {} is not in the server list, the access is denied".format(host), status=400) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> queryset = Posts.objects.get(id=postId) <NEW_LINE> serializer_class = PostsSerializer(instance=queryset, context={'request': request}) <NEW_LINE> post = serializer_class.data <NEW_LINE> <DEDENT> response = { "query": "getPost", "count": 1, "size": None, "next": None, "previous": None, "post": post } <NEW_LINE> return Response(response) | API endpoint that allows users to be viewed or edited. | 6259906392d797404e3896e0 |
class ScriptIntentHandler(intent.IntentHandler): <NEW_LINE> <INDENT> def __init__(self, intent_type, config): <NEW_LINE> <INDENT> self.intent_type = intent_type <NEW_LINE> self.config = config <NEW_LINE> <DEDENT> @asyncio.coroutine <NEW_LINE> def async_handle(self, intent_obj): <NEW_LINE> <INDENT> speech = self.config.get(CONF_SPEECH) <NEW_LINE> card = self.config.get(CONF_CARD) <NEW_LINE> action = self.config.get(CONF_ACTION) <NEW_LINE> is_async_action = self.config.get(CONF_ASYNC_ACTION) <NEW_LINE> slots = {key: value['value'] for key, value in intent_obj.slots.items()} <NEW_LINE> if action is not None: <NEW_LINE> <INDENT> if is_async_action: <NEW_LINE> <INDENT> intent_obj.hass.async_add_job(action.async_run(slots)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield from action.async_run(slots) <NEW_LINE> <DEDENT> <DEDENT> response = intent_obj.create_response() <NEW_LINE> if speech is not None: <NEW_LINE> <INDENT> response.async_set_speech(speech[CONF_TEXT].async_render(slots), speech[CONF_TYPE]) <NEW_LINE> <DEDENT> if card is not None: <NEW_LINE> <INDENT> response.async_set_card( card[CONF_TITLE].async_render(slots), card[CONF_CONTENT].async_render(slots), card[CONF_TYPE]) <NEW_LINE> <DEDENT> return response | Respond to an intent with a script. | 6259906332920d7e50bc774d |
class AlgorithmApplicationRunExit(RunExit): <NEW_LINE> <INDENT> @property <NEW_LINE> def state(self) -> str: <NEW_LINE> <INDENT> return 'application' <NEW_LINE> <DEDENT> def deepcopy(self): <NEW_LINE> <INDENT> return AlgorithmApplicationRunExit(self.reason) | Run Exit of Algorithm is Application specific | 625990631f5feb6acb1642f1 |
@dataclasses.dataclass <NEW_LINE> class ValidationIssue: <NEW_LINE> <INDENT> type: str <NEW_LINE> identifier: str <NEW_LINE> value: Any | None = None | Error or warning message. | 62599063a79ad1619776b640 |
class EnforceVolumeBackedForZeroDiskFlavorTestCase( test.TestCase, integrated_helpers.InstanceHelperMixin): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(EnforceVolumeBackedForZeroDiskFlavorTestCase, self).setUp() <NEW_LINE> self.glance = self.useFixture(nova_fixtures.GlanceFixture(self)) <NEW_LINE> self.useFixture(nova_fixtures.NeutronFixture(self)) <NEW_LINE> self.policy_fixture = ( self.useFixture(nova_fixtures.RealPolicyFixture())) <NEW_LINE> api_fixture = self.useFixture(nova_fixtures.OSAPIFixture( api_version='v2.1')) <NEW_LINE> self.api = api_fixture.api <NEW_LINE> self.admin_api = api_fixture.admin_api <NEW_LINE> flavor_req = { "flavor": { "name": "zero-disk-flavor", "ram": 1024, "vcpus": 2, "disk": 0 } } <NEW_LINE> self.zero_disk_flavor = self.admin_api.post_flavor(flavor_req) <NEW_LINE> <DEDENT> def test_create_image_backed_server_with_zero_disk_fails(self): <NEW_LINE> <INDENT> self.policy_fixture.set_rules({ servers_policies.ZERO_DISK_FLAVOR: base_policies.RULE_ADMIN_API}, overwrite=False) <NEW_LINE> server_req = self._build_server( image_uuid=self.glance.auto_disk_config_enabled_image['id'], flavor_id=self.zero_disk_flavor['id']) <NEW_LINE> ex = self.assertRaises(api_client.OpenStackApiException, self.api.post_server, {'server': server_req}) <NEW_LINE> self.assertIn('Only volume-backed servers are allowed for flavors ' 'with zero disk.', str(ex)) <NEW_LINE> self.assertEqual(403, ex.response.status_code) <NEW_LINE> <DEDENT> def test_create_volume_backed_server_with_zero_disk_allowed(self): <NEW_LINE> <INDENT> self.useFixture(func_fixtures.PlacementFixture()) <NEW_LINE> self.useFixture(nova_fixtures.CinderFixture(self)) <NEW_LINE> self.start_service('conductor') <NEW_LINE> self.start_service('scheduler') <NEW_LINE> server_req = self._build_server( flavor_id=self.zero_disk_flavor['id']) <NEW_LINE> server_req.pop('imageRef', None) <NEW_LINE> server_req['block_device_mapping_v2'] = [{ 'uuid': nova_fixtures.CinderFixture.IMAGE_BACKED_VOL, 'source_type': 'volume', 'destination_type': 'volume', 'boot_index': 0 }] <NEW_LINE> server = self.admin_api.post_server({'server': server_req}) <NEW_LINE> server = self._wait_for_state_change(server, 'ERROR') <NEW_LINE> self.assertIn('No valid host', server['fault']['message']) | Tests for the os_compute_api:servers:create:zero_disk_flavor policy rule
These tests explicitly rely on microversion 2.1. | 625990634428ac0f6e659c3a |
class InitializeOAuthResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_AuthorizationURL(self): <NEW_LINE> <INDENT> return self._output.get('AuthorizationURL', None) <NEW_LINE> <DEDENT> def get_CallbackID(self): <NEW_LINE> <INDENT> return self._output.get('CallbackID', None) <NEW_LINE> <DEDENT> def get_OAuthTokenSecret(self): <NEW_LINE> <INDENT> return self._output.get('OAuthTokenSecret', None) | A ResultSet with methods tailored to the values returned by the InitializeOAuth Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 62599063fff4ab517ebcef2f |
class DBConnector_Basic(db.RealDatabaseMixin, unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> d = self.setUpRealDatabase() <NEW_LINE> def make_dbc(_): <NEW_LINE> <INDENT> self.dbc = connector.DBConnector(mock.Mock(), self.db_url, os.path.abspath('basedir')) <NEW_LINE> self.dbc.start() <NEW_LINE> <DEDENT> d.addCallback(make_dbc) <NEW_LINE> return d <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.dbc.stop() <NEW_LINE> return self.tearDownRealDatabase() <NEW_LINE> <DEDENT> def test_runQueryNow_simple(self): <NEW_LINE> <INDENT> self.assertEqual(list(self.dbc.runQueryNow("SELECT 1")), [(1,)]) <NEW_LINE> <DEDENT> def test_runQueryNow_exception(self): <NEW_LINE> <INDENT> self.assertRaises(Exception, lambda : self.dbc.runQueryNow("EAT * FROM cookies")) <NEW_LINE> <DEDENT> def test_runInterationNow_simple(self): <NEW_LINE> <INDENT> def inter(cursor, *args, **kwargs): <NEW_LINE> <INDENT> cursor.execute("SELECT 1") <NEW_LINE> self.assertEqual(list(cursor.fetchall()), [(1,)]) <NEW_LINE> <DEDENT> self.dbc.runInteractionNow(inter) <NEW_LINE> <DEDENT> def test_runInterationNow_args(self): <NEW_LINE> <INDENT> def inter(cursor, *args, **kwargs): <NEW_LINE> <INDENT> self.assertEqual((args, kwargs), ((1, 2), dict(three=4))) <NEW_LINE> cursor.execute("SELECT 1") <NEW_LINE> <DEDENT> self.dbc.runInteractionNow(inter, 1, 2, three=4) <NEW_LINE> <DEDENT> def test_runInterationNow_exception(self): <NEW_LINE> <INDENT> def inter(cursor): <NEW_LINE> <INDENT> cursor.execute("GET * WHERE golden") <NEW_LINE> <DEDENT> self.assertRaises(Exception, lambda : self.dbc.runInteractionNow(inter)) <NEW_LINE> <DEDENT> def test_runQuery_simple(self): <NEW_LINE> <INDENT> d = self.dbc.runQuery("SELECT 1") <NEW_LINE> def cb(res): <NEW_LINE> <INDENT> self.assertEqual(list(res), [(1,)]) <NEW_LINE> <DEDENT> d.addCallback(cb) <NEW_LINE> return d <NEW_LINE> <DEDENT> def test_getPropertiesFromDb(self): <NEW_LINE> <INDENT> d = self.createTestTables(['changes', 'change_properties', 'change_links', 'change_files', 'patches', 'sourcestamps', 'buildset_properties', 'buildsets' ]) <NEW_LINE> d.addCallback(lambda _ : self.insertTestData([ fakedb.Change(changeid=13), fakedb.ChangeProperty(changeid=13, property_name='foo', property_value='"my prop"'), fakedb.SourceStamp(id=23), fakedb.Buildset(id=33, sourcestampid=23), fakedb.BuildsetProperty(buildsetid=33, property_name='bar', property_value='["other prop", "BS"]'), ])) <NEW_LINE> def do_test(_): <NEW_LINE> <INDENT> cprops = self.dbc.get_properties_from_db("change_properties", "changeid", 13) <NEW_LINE> bprops = self.dbc.get_properties_from_db("buildset_properties", "buildsetid", 33) <NEW_LINE> self.assertEqual(cprops.asList() + bprops.asList(), [ ('foo', 'my prop', 'Change'), ('bar', 'other prop', 'BS')]) <NEW_LINE> <DEDENT> d.addCallback(do_test) <NEW_LINE> return d | Basic tests of the DBConnector class - all start with an empty DB | 625990638a43f66fc4bf3896 |
class ExtractFeature(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def __init__(self, function, on, new): <NEW_LINE> <INDENT> self.function = function <NEW_LINE> self.on = on <NEW_LINE> self.new = new <NEW_LINE> <DEDENT> def fit(self, X, y=None): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def transform(self, X): <NEW_LINE> <INDENT> new_X = X.copy() <NEW_LINE> new_X[self.new] = new_X[self.on].apply(self.function) <NEW_LINE> return new_X | Apply a arbitrary function on a dataframe column and create a new
column to save the result. | 62599063cc0a2c111447c653 |
class TestBrocadeMechDriverV2(test_db_plugin.NeutronDbPluginV2TestCase): <NEW_LINE> <INDENT> _mechanism_name = MECHANISM_NAME <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> _mechanism_name = MECHANISM_NAME <NEW_LINE> ml2_opts = { 'mechanism_drivers': ['brocade'], 'tenant_network_types': ['vlan']} <NEW_LINE> for opt, val in ml2_opts.items(): <NEW_LINE> <INDENT> ml2_config.cfg.CONF.set_override(opt, val, 'ml2') <NEW_LINE> <DEDENT> def mocked_brocade_init(self): <NEW_LINE> <INDENT> self._driver = mock.MagicMock() <NEW_LINE> <DEDENT> with mock.patch.object(brocademechanism.BrocadeMechanism, 'brocade_init', new=mocked_brocade_init): <NEW_LINE> <INDENT> super(TestBrocadeMechDriverV2, self).setUp() <NEW_LINE> self.mechanism_driver = importutils.import_object(_mechanism_name) | Test Brocade VCS/VDX mechanism driver.
| 62599063009cb60464d02c3f |
class DataFrameSelector(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def __init__(self, data_type=None): <NEW_LINE> <INDENT> if data_type == None: <NEW_LINE> <INDENT> self.data_type = [np.number] <NEW_LINE> <DEDENT> self.data_type = data_type <NEW_LINE> self.attribute_names = None <NEW_LINE> <DEDENT> def fit(self, X, y=None): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def transform(self, X): <NEW_LINE> <INDENT> x_num = X.select_dtypes(include = self.data_type) <NEW_LINE> self.attribute_names = list(x_num.columns) <NEW_LINE> return x_num.values | Select columns from a dataframe according to datatypes.
See pandas.DataFrame.select_dtypes(include=[], exclude=[]):
For all numeric types use the numpy dtype numpy.number
For strings you must use the object dtype
For datetimes, use np.datetime64, ‘datetime’ or ‘datetime64’
For timedeltas, use np.timedelta64, ‘timedelta’ or ‘timedelta64’
For Pandas categorical dtypes, use ‘category’
For Pandas datetimetz dtypes, use ‘datetimetz’, or a ‘datetime64[ns, tz]’
Notes:
This class inherits the fit_transform from TransformerMixin
args:
pandas dataframe
returns:
subset for the requested dtype converted to numpy array. | 62599063627d3e7fe0e08592 |
class UserIDSchema(ma.Schema): <NEW_LINE> <INDENT> id = fields.Str(required=True) <NEW_LINE> @validates("id") <NEW_LINE> def validate_id(self, value): <NEW_LINE> <INDENT> user = User.query.filter_by(id=value).first() <NEW_LINE> if not user: <NEW_LINE> <INDENT> raise ValidationError(f"User id {value} does not exist.") | Validate user id | 6259906376e4537e8c3f0c8a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.