code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Date(Item, date): <NEW_LINE> <INDENT> def __new__(cls, year: int, month: int, day: int, *_: Any) -> date: <NEW_LINE> <INDENT> return date.__new__(cls, year, month, day) <NEW_LINE> <DEDENT> def __init__( self, year: int, month: int, day: int, trivia: Trivia, raw: str ) -> None: <NEW_LINE> <INDENT> super().__init__(trivia) <NEW_LINE> self._raw = raw <NEW_LINE> <DEDENT> @property <NEW_LINE> def discriminant(self) -> int: <NEW_LINE> <INDENT> return 6 <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self) -> date: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def as_string(self) -> str: <NEW_LINE> <INDENT> return self._raw <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> if PY38: <NEW_LINE> <INDENT> result = date(self.year, self.month, self.day).__add__(other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = super().__add__(other) <NEW_LINE> <DEDENT> return self._new(result) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> if PY38: <NEW_LINE> <INDENT> result = date(self.year, self.month, self.day).__sub__(other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = super().__sub__(other) <NEW_LINE> <DEDENT> if isinstance(result, date): <NEW_LINE> <INDENT> result = self._new(result) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def _new(self, result): <NEW_LINE> <INDENT> raw = result.isoformat() <NEW_LINE> return Date(result.year, result.month, result.day, self._trivia, raw) <NEW_LINE> <DEDENT> def _getstate(self, protocol=3): <NEW_LINE> <INDENT> return (self.year, self.month, self.day, self._trivia, self._raw)
A date literal.
62598fb85fc7496912d4831a
class ModuleStatusClient: <NEW_LINE> <INDENT> def __init__( self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter ) -> None: <NEW_LINE> <INDENT> self._reader = reader <NEW_LINE> self._writer = writer <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def connect( cls, host: str, port: int, retries: int = 3, interval_seconds: float = 0.1, ) -> ModuleStatusClient: <NEW_LINE> <INDENT> r: Optional[asyncio.StreamReader] = None <NEW_LINE> w: Optional[asyncio.StreamWriter] = None <NEW_LINE> for i in range(retries): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r, w = await asyncio.open_connection(host=host, port=port) <NEW_LINE> break <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> await asyncio.sleep(interval_seconds) <NEW_LINE> <DEDENT> <DEDENT> if r is not None and w is not None: <NEW_LINE> <INDENT> return ModuleStatusClient(reader=r, writer=w) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise IOError( f"Failed to connect to module_server at after {retries} retries." ) <NEW_LINE> <DEDENT> <DEDENT> async def read(self) -> Message: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> b = await self._reader.readuntil(MessageDelimiter) <NEW_LINE> m: Message = Message.parse_raw(b) <NEW_LINE> return m <NEW_LINE> <DEDENT> except LimitOverrunError as e: <NEW_LINE> <INDENT> raise ModuleServerClientError(str(e)) <NEW_LINE> <DEDENT> except IncompleteReadError: <NEW_LINE> <INDENT> raise ModuleServerDisconnected() <NEW_LINE> <DEDENT> <DEDENT> def close(self) -> None: <NEW_LINE> <INDENT> self._writer.close()
A module server client.
62598fb8a8370b77170f051c
class Polymer(Enum): <NEW_LINE> <INDENT> All = 'all' <NEW_LINE> DNAOnly = 'onlyDna' <NEW_LINE> ProteinDNA = 'protDna' <NEW_LINE> DrugDNA = 'drugDna' <NEW_LINE> HybridsChimera = 'hybNChimera' <NEW_LINE> PeptideNucleicAcid = 'pepNucAcid'
Enums to handle polymer in query :cvar All: all in query :cvar DNAOnly: DNA Only in query :cvar ProteinDNA: Protein DNA Complexes in query :cvar DrugDNA: Drug DNA Complexes in query :cvar HybridsChimera: Hybrids and Chimera in query :cvar PeptideNucleicAcid: Peptide Nucleic Acid / Mimetics in query
62598fb8009cb60464d01661
class SQLTableNoCache(SQLTableBase): <NEW_LINE> <INDENT> itemClass = SQLRow <NEW_LINE> keys = getKeys <NEW_LINE> __iter__ = iter_keys <NEW_LINE> def getID(self, t): <NEW_LINE> <INDENT> return t[0] <NEW_LINE> <DEDENT> def select(self, whereClause, params): <NEW_LINE> <INDENT> return SQLTableBase.select(self, whereClause, params, self.oclass, self._attrSQL('id')) <NEW_LINE> <DEDENT> def __getitem__(self, k): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._weakValueDict[k] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self._select('where %s=%%s' % self.primary_key, (k, ), self.primary_key) <NEW_LINE> t = self.cursor.fetchmany(2) <NEW_LINE> if len(t) == 0: <NEW_LINE> <INDENT> raise KeyError('id %s non-existent' % k) <NEW_LINE> <DEDENT> if len(t) > 1 and not self.allowNonUniqueID: <NEW_LINE> <INDENT> raise KeyError('id %s not unique' % k) <NEW_LINE> <DEDENT> o = self.itemClass(k) <NEW_LINE> self._weakValueDict[k] = o <NEW_LINE> return o <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, k, v): <NEW_LINE> <INDENT> if not self.writeable: <NEW_LINE> <INDENT> raise ValueError('this database is read only!') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if v.db is not self: <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError('object not bound to itemClass for this db!') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> del self[k] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> del self._weakValueDict[v.id] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self._update(v.id, self.primary_key, k) <NEW_LINE> v.cache_id(k) <NEW_LINE> self._weakValueDict[k] = v <NEW_LINE> <DEDENT> def addAttrAlias(self, **kwargs): <NEW_LINE> <INDENT> self.data.update(kwargs)
Provide on-the-fly access to rows in the database; values are simply an object interface (SQLRow) to back-end db query. Row data are not stored locally, but always accessed by querying the db
62598fb8be383301e025393a
class PageHeaders(headers): <NEW_LINE> <INDENT> def buildHeader(self): <NEW_LINE> <INDENT> urlArray = urlparse(self.url) <NEW_LINE> self.hostname = urlArray.hostname <NEW_LINE> path = urlArray.path <NEW_LINE> self.agent = random.choice(self.agentlist) <NEW_LINE> self.headers = { ':authority': self.hostname, ':method': 'GET', ':path': path, ':scheme': 'https', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6', 'cache-control': 'no-cache', 'pragma': 'no-cache', 'upgrade-insecure-requests': '1', 'user-agent': self.agent } <NEW_LINE> return self.headers
构建搜狐页面的headers类 :param headers: 父类,构建headers类
62598fb8379a373c97d99154
class DVS_Phenology_Wrapper(SimulationObject): <NEW_LINE> <INDENT> phenology = Instance(SimulationObject) <NEW_LINE> def initialize(self, day, kiosk, cropdata, soildata, sitedata, start_type, stop_type): <NEW_LINE> <INDENT> self.phenology = DVS_Phenology(day, kiosk, cropdata, start_type, stop_type) <NEW_LINE> <DEDENT> def calc_rates(self, day, drv): <NEW_LINE> <INDENT> self.phenology.calc_rates(day, drv) <NEW_LINE> <DEDENT> def integrate(self, day): <NEW_LINE> <INDENT> self.phenology.integrate(day)
This is wrapper class that wraps the DVS_phenology simulation object in such a way that it can run directly in the Engine. This means that it can be used direct in a configuration file:: CROP = DVS_Phenology_Wrapper This is useful for running only the phenology instead of the entire crop simulation.
62598fb83539df3088ecc3eb
class Indexer(): <NEW_LINE> <INDENT> def __init__(self, index_dir, mode, date_format='%Y-%m-%dT%H:%M:%S'): <NEW_LINE> <INDENT> self.store = FSDirectory.open(File(index_dir)) <NEW_LINE> self.analyzer = StandardAnalyzer(Version.LUCENE_CURRENT) <NEW_LINE> self.config = IndexWriterConfig(Version.LUCENE_CURRENT, self.analyzer) <NEW_LINE> self.mode = mode <NEW_LINE> self.date_format = date_format <NEW_LINE> if mode == 'create_or_append': <NEW_LINE> <INDENT> self.config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND) <NEW_LINE> <DEDENT> elif mode == 'create': <NEW_LINE> <INDENT> self.config.setOpenMode(IndexWriterConfig.OpenMode.CREATE) <NEW_LINE> <DEDENT> elif mode == 'append': <NEW_LINE> <INDENT> self.config.setOpenMode(IndexWriterConfig.OpenMode.APPEND) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid mode %s', mode) <NEW_LINE> <DEDENT> self.writer = IndexWriter(self.store, self.config) <NEW_LINE> <DEDENT> def index_one(self, article): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> date_published_str = article['date_published'].strftime( self.date_format) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.warning('Error when formating date_published %r: %s ', article['canonical_url'], e) <NEW_LINE> return <NEW_LINE> <DEDENT> doc = Document() <NEW_LINE> doc.add(IntField('group_id', article['group_id'], Field.Store.YES)) <NEW_LINE> doc.add(IntField('article_id', article['article_id'], Field.Store.YES)) <NEW_LINE> doc.add( StringField('date_published', date_published_str, Field.Store.YES)) <NEW_LINE> doc.add(StringField('domain', article['domain'], Field.Store.YES)) <NEW_LINE> doc.add(StringField('site_type', article['site_type'], Field.Store.YES)) <NEW_LINE> doc.add( TextField('canonical_url', article['canonical_url'], Field.Store.YES)) <NEW_LINE> doc.add(TextField('title', article['title'], Field.Store.YES)) <NEW_LINE> doc.add(TextField('meta', article['meta'], Field.Store.NO)) <NEW_LINE> doc.add(TextField('content', article['content'], Field.Store.NO)) <NEW_LINE> doc.add(StringField('uq_id_str', article['uq_id_str'], Field.Store.YES)) <NEW_LINE> self.writer.addDocument(doc) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.writer.close()
This class provide functions to index article stored in the database.
62598fb84f88993c371f05ac
class SingleNumberValueTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_single_number_value(self): <NEW_LINE> <INDENT> single_number_value_obj = SingleNumberValue() <NEW_LINE> self.assertNotEqual(single_number_value_obj, None)
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fb84527f215b58ea014
class ASTNestedNameElementEmpty(ASTBase): <NEW_LINE> <INDENT> def get_id_v1(self): <NEW_LINE> <INDENT> return u'' <NEW_LINE> <DEDENT> def get_id_v2(self): <NEW_LINE> <INDENT> return u'' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'' <NEW_LINE> <DEDENT> def describe_signature(self, signode, mode, env, prefix, parentScope): <NEW_LINE> <INDENT> pass
Used if a nested name starts with ::
62598fb83317a56b869be5ed
class AddBulkCaseForm(BaseAddCaseForm, BaseCaseForm): <NEW_LINE> <INDENT> cases = forms.CharField(widget=mtforms.BareTextarea) <NEW_LINE> def clean_cases(self): <NEW_LINE> <INDENT> data = model.BulkParser().parse(self.cleaned_data["cases"]) <NEW_LINE> for d in data: <NEW_LINE> <INDENT> if "error" in d: <NEW_LINE> <INDENT> raise forms.ValidationError(d["error"]) <NEW_LINE> <DEDENT> <DEDENT> return data <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> BaseCaseForm.clean(self) <NEW_LINE> BaseAddCaseForm.clean(self) <NEW_LINE> return self.cleaned_data <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> assert self.is_valid() <NEW_LINE> product = self.cleaned_data["product"] <NEW_LINE> idprefix = self.cleaned_data["idprefix"] <NEW_LINE> self.save_new_tags(product) <NEW_LINE> productversions = [self.cleaned_data["productversion"]] <NEW_LINE> if self.cleaned_data.get("and_later_versions"): <NEW_LINE> <INDENT> productversions.extend(product.versions.filter( order__gt=productversions[0].order)) <NEW_LINE> <DEDENT> initial_suite = self.cleaned_data.get("initial_suite") <NEW_LINE> cases = [] <NEW_LINE> for case_data in self.cleaned_data["cases"]: <NEW_LINE> <INDENT> case = model.Case.objects.create( product=product, user=self.user, idprefix=idprefix, ) <NEW_LINE> version_kwargs = case_data.copy() <NEW_LINE> steps_data = version_kwargs.pop("steps") <NEW_LINE> version_kwargs["case"] = case <NEW_LINE> version_kwargs["status"] = self.cleaned_data["status"] <NEW_LINE> version_kwargs["user"] = self.user <NEW_LINE> if initial_suite: <NEW_LINE> <INDENT> model.SuiteCase.objects.create( case=case, suite=initial_suite, user=self.user) <NEW_LINE> <DEDENT> for productversion in productversions: <NEW_LINE> <INDENT> this_version_kwargs = version_kwargs.copy() <NEW_LINE> this_version_kwargs["productversion"] = productversion <NEW_LINE> caseversion = model.CaseVersion.objects.create( **this_version_kwargs) <NEW_LINE> for i, step_kwargs in enumerate(steps_data, 1): <NEW_LINE> <INDENT> model.CaseStep.objects.create( user=self.user, caseversion=caseversion, number=i, **step_kwargs) <NEW_LINE> <DEDENT> self.save_tags(caseversion) <NEW_LINE> <DEDENT> cases.append(case) <NEW_LINE> <DEDENT> return cases
Form for adding test cases in bulk.
62598fb89c8ee82313040213
class Preferences(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> tm_identifier = getenv('TM_APP_IDENTIFIER', 'com.macromates.textmate') <NEW_LINE> CFPreferencesAppSynchronize(tm_identifier) <NEW_LINE> self.default_values = { 'latexAutoView': 1, 'latexEngine': "pdflatex", 'latexEngineOptions': "", 'latexVerbose': 0, 'latexUselatexmk': 1, 'latexViewer': "TextMate", 'latexKeepLogWin': 1, 'latexDebug': 0, } <NEW_LINE> self.prefs = self.default_values.copy() <NEW_LINE> for key in self.prefs: <NEW_LINE> <INDENT> preference_value = CFPreferencesCopyAppValue(key, tm_identifier) <NEW_LINE> if preference_value is not None: <NEW_LINE> <INDENT> self.prefs[key] = preference_value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.prefs.get(key, None) <NEW_LINE> <DEDENT> def defaults(self): <NEW_LINE> <INDENT> preference_items = [ '{} = {};'.format(preference, self.default_values[preference] if str(self.default_values[preference]) else '""') for preference in sorted(self.default_values)] <NEW_LINE> return '{{ {} }}'.format(' '.join(preference_items))
Process the current preferences of the LaTeX bundle. This class reads the LaTeX preferences and provides a dictionary-like interface to process them.
62598fb856b00c62f0fb29f9
class LeaveOneOut(object): <NEW_LINE> <INDENT> def __init__(self, n, indices=True): <NEW_LINE> <INDENT> self.n = n <NEW_LINE> self.indices = indices <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> n = self.n <NEW_LINE> for i in xrange(n): <NEW_LINE> <INDENT> test_index = np.zeros(n, dtype=np.bool) <NEW_LINE> test_index[i] = True <NEW_LINE> train_index = np.logical_not(test_index) <NEW_LINE> if self.indices: <NEW_LINE> <INDENT> ind = np.arange(n) <NEW_LINE> train_index = ind[train_index] <NEW_LINE> test_index = ind[test_index] <NEW_LINE> <DEDENT> yield train_index, test_index <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s.%s(n=%i)' % ( self.__class__.__module__, self.__class__.__name__, self.n, ) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.n
Leave-One-Out cross validation iterator. Provides train/test indices to split data in train test sets. Each sample is used once as a test set (singleton) while the remaining samples form the training set. Due to the high number of test sets (which is the same as the number of samples) this cross validation method can be very costly. For large datasets one should favor KFold, StratifiedKFold or ShuffleSplit. Parameters ---------- n : int Total number of elements in dataset. indices : boolean, optional (default True) Return train/test split as arrays of indices, rather than a boolean mask array. Integer indices are required when dealing with sparse matrices, since those cannot be indexed by boolean masks. Examples -------- >>> from sklearn import cross_validation >>> X = np.array([[1, 2], [3, 4]]) >>> y = np.array([1, 2]) >>> loo = cross_validation.LeaveOneOut(2) >>> len(loo) 2 >>> print(loo) sklearn.cross_validation.LeaveOneOut(n=2) >>> for train_index, test_index in loo: ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] ... print("%s %s %s %s" % (X_train, X_test, y_train, y_test)) TRAIN: [1] TEST: [0] [[3 4]] [[1 2]] [2] [1] TRAIN: [0] TEST: [1] [[1 2]] [[3 4]] [1] [2] See also -------- LeaveOneLabelOut for splitting the data according to explicit, domain-specific stratification of the dataset.
62598fb8d7e4931a7ef3c1d5
class FunctionFieldPlace(Element): <NEW_LINE> <INDENT> def __init__(self, parent, prime): <NEW_LINE> <INDENT> Element.__init__(self, parent) <NEW_LINE> self._prime = prime <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.function_field(), self._prime)) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> gens = self._prime.gens_two() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> gens = self._prime.gens() <NEW_LINE> <DEDENT> gens_str = ', '.join(repr(g) for g in gens) <NEW_LINE> return "Place ({})".format(gens_str) <NEW_LINE> <DEDENT> def _latex_(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> gens = self._prime.gens_two() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> gens = self._prime.gens() <NEW_LINE> <DEDENT> gens_str = ', '.join(g._latex_() for g in gens) <NEW_LINE> if self.is_infinite_place(): <NEW_LINE> <INDENT> return "({})\\mathcal{{O}}_\infty".format(gens_str) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "({})\\mathcal{{O}}".format(gens_str) <NEW_LINE> <DEDENT> <DEDENT> def _richcmp_(self, other, op): <NEW_LINE> <INDENT> return richcmp((self._prime.ring(), self._prime), (other._prime.ring(), other._prime), op) <NEW_LINE> <DEDENT> def _acted_upon_(self, other, self_on_left): <NEW_LINE> <INDENT> if self_on_left: <NEW_LINE> <INDENT> raise TypeError("only left multiplication by integers is allowed") <NEW_LINE> <DEDENT> return other * self.divisor() <NEW_LINE> <DEDENT> def _add_(self, other): <NEW_LINE> <INDENT> return prime_divisor(self.function_field(), self) + other <NEW_LINE> <DEDENT> def __radd__(self, other): <NEW_LINE> <INDENT> if other == 0: <NEW_LINE> <INDENT> return prime_divisor(self.function_field(), self) <NEW_LINE> <DEDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def function_field(self): <NEW_LINE> <INDENT> return self.parent()._field <NEW_LINE> <DEDENT> def prime_ideal(self): <NEW_LINE> <INDENT> return self._prime <NEW_LINE> <DEDENT> def divisor(self, multiplicity=1): <NEW_LINE> <INDENT> return prime_divisor(self.function_field(), self, multiplicity)
Places of function fields. INPUT: - ``field`` -- function field - ``prime`` -- prime ideal associated with the place EXAMPLES:: sage: K.<x>=FunctionField(GF(2)); _.<Y> = K[] sage: L.<y>=K.extension(Y^3 + x + x^3*Y) sage: L.places_finite()[0] Place (x, y)
62598fb867a9b606de546111
class MyFavorite(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(UserProfile, related_name='mf_user', verbose_name=u'用户') <NEW_LINE> course = models.ForeignKey(Course, verbose_name=u'课程') <NEW_LINE> date_favorite = models.DateTimeField(u'收藏时间', auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = u'我的收藏' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> unique_together = (('user', 'course'),) <NEW_LINE> db_table = 'my_favorite' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.id)
我的收藏
62598fb81b99ca400228f5d0
class Task(db.Model): <NEW_LINE> <INDENT> creator = db.UserProperty() <NEW_LINE> summary = db.StringProperty() <NEW_LINE> body = db.TextProperty() <NEW_LINE> reminder = db.DateTimeProperty()
A saved task.
62598fb8cc0a2c111447b14c
class ViewSocketHandler(tornado.websocket.WebSocketHandler): <NEW_LINE> <INDENT> def open(self, game, game_id): <NEW_LINE> <INDENT> self.is_open = True <NEW_LINE> stratumgs.game.get_game_runner(int(game_id)).add_view(self) <NEW_LINE> <DEDENT> def on_close(self): <NEW_LINE> <INDENT> self.is_open = False <NEW_LINE> <DEDENT> def on_message(self, message): <NEW_LINE> <INDENT> pass
Handles websocket connections for viewing games.
62598fb8ec188e330fdf89d0
class CRF1d(link.Link): <NEW_LINE> <INDENT> def __init__(self, n_label): <NEW_LINE> <INDENT> super(CRF1d, self).__init__(cost=(n_label, n_label)) <NEW_LINE> self.cost.data[...] = 0 <NEW_LINE> <DEDENT> def __call__(self, xs, ys): <NEW_LINE> <INDENT> return crf1d.crf1d(self.cost, xs, ys) <NEW_LINE> <DEDENT> def argmax(self, xs): <NEW_LINE> <INDENT> return crf1d.argmax_crf1d(self.cost, xs)
Linear-chain conditional random field loss layer. This link wraps the :func:`~chainer.functions.crf1d` function. It holds a transition cost matrix as a parameter. Args: n_label (int): Number of labels. .. seealso:: :func:`~chainer.functions.crf1d` for more detail. Attributes: cost (~chainer.Variable): Transition cost parameter.
62598fb82c8b7c6e89bd3904
class ItemDelegate(QtGui.QStyledItemDelegate): <NEW_LINE> <INDENT> EXTRA_ROW_HEIGHT = 7 <NEW_LINE> def __init__(self, treeview, *args, **kwargs): <NEW_LINE> <INDENT> QtGui.QStyledItemDelegate.__init__(self, *args, **kwargs) <NEW_LINE> self._pen = QtGui.QPen() <NEW_LINE> self._pen.setWidth(1) <NEW_LINE> self._pen.setColor(QtGui.QColor.fromRgb(128, 128, 128, 64)) <NEW_LINE> fontmetrics = QtGui.QFontMetrics(treeview.font()) <NEW_LINE> text_height = fontmetrics.height() <NEW_LINE> self.height = text_height + self.EXTRA_ROW_HEIGHT <NEW_LINE> <DEDENT> def sizeHint(self, *args): <NEW_LINE> <INDENT> size = QtGui.QStyledItemDelegate.sizeHint(self, *args) <NEW_LINE> return QtCore.QSize(size.width(), self.height) <NEW_LINE> <DEDENT> def paint(self, painter, option, index): <NEW_LINE> <INDENT> QtGui.QStyledItemDelegate.paint(self, painter, option, index) <NEW_LINE> if index.column() > 0: <NEW_LINE> <INDENT> painter.setPen(self._pen) <NEW_LINE> painter.drawLine(option.rect.topLeft(), option.rect.bottomLeft())
An item delegate with a fixed height and faint grey vertical lines between columns
62598fb8a05bb46b3848a9ab
class Pagination: <NEW_LINE> <INDENT> def __init__(self, query, page, per_page, total, items): <NEW_LINE> <INDENT> self.query = query <NEW_LINE> self.page = page <NEW_LINE> self.per_page = per_page <NEW_LINE> self.total = total <NEW_LINE> self.items = items <NEW_LINE> <DEDENT> @property <NEW_LINE> def pages(self): <NEW_LINE> <INDENT> if self.per_page == 0 or self.total is None: <NEW_LINE> <INDENT> pages = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pages = int(ceil(self.total / float(self.per_page))) <NEW_LINE> <DEDENT> return pages <NEW_LINE> <DEDENT> def prev(self, error_out=False): <NEW_LINE> <INDENT> assert ( self.query is not None ), "a query object is required for this method to work" <NEW_LINE> return self.query.paginate(self.page - 1, self.per_page, error_out) <NEW_LINE> <DEDENT> @property <NEW_LINE> def prev_num(self): <NEW_LINE> <INDENT> if not self.has_prev: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.page - 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_prev(self): <NEW_LINE> <INDENT> return self.page > 1 <NEW_LINE> <DEDENT> def next(self, error_out=False): <NEW_LINE> <INDENT> assert ( self.query is not None ), "a query object is required for this method to work" <NEW_LINE> return self.query.paginate(self.page + 1, self.per_page, error_out) <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_next(self): <NEW_LINE> <INDENT> return self.page < self.pages <NEW_LINE> <DEDENT> @property <NEW_LINE> def next_num(self): <NEW_LINE> <INDENT> if not self.has_next: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.page + 1 <NEW_LINE> <DEDENT> def iter_pages(self, left_edge=2, left_current=2, right_current=5, right_edge=2): <NEW_LINE> <INDENT> last = 0 <NEW_LINE> for num in range(1, self.pages + 1): <NEW_LINE> <INDENT> if ( num <= left_edge or ( num > self.page - left_current - 1 and num < self.page + right_current ) or num > self.pages - right_edge ): <NEW_LINE> <INDENT> if last + 1 != num: <NEW_LINE> <INDENT> yield None <NEW_LINE> <DEDENT> yield num <NEW_LINE> last = num
Internal helper class returned by :meth:`BaseQuery.paginate`. You can also construct it from any other SQLAlchemy query object if you are working with other libraries. Additionally it is possible to pass `None` as query object in which case the :meth:`prev` and :meth:`next` will no longer work.
62598fb85fc7496912d4831b
class GoogleLoginView(View): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> storage = Storage(CredentialsModel, 'id', self.request.user.pk, 'credential') <NEW_LINE> credential = storage.get() <NEW_LINE> if credential is None or credential.invalid: <NEW_LINE> <INDENT> FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, request.user) <NEW_LINE> authorize_url = FLOW.step1_get_authorize_url() <NEW_LINE> return HttpResponseRedirect(authorize_url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) <NEW_LINE> <DEDENT> return super(GoogleLoginView, self). get(request, **kwargs)
Google Login View
62598fb8cc40096d6161a279
class GenomeBuild(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255, unique=True) <NEW_LINE> affiliation = models.CharField(max_length=255, default='UCSC') <NEW_LINE> description = models.CharField(max_length=255) <NEW_LINE> species = models.ForeignKey(Taxon) <NEW_LINE> html_path = models.CharField(max_length=1024, blank=True, null=True) <NEW_LINE> source_name = models.CharField(max_length=1024, blank=True, null=True) <NEW_LINE> available = models.BooleanField(default=True) <NEW_LINE> default_build = models.BooleanField(default=False) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return "%s: %s" % (self.name, self.description)
Model that stores UCSC Genome Build Information
62598fb87d847024c075c4fc
class TestAddTransactionCreation(object): <NEW_LINE> <INDENT> def test_on_empty_block_transactions_length(self, sample_sut, sample_transaction_f): <NEW_LINE> <INDENT> sut = sample_sut() <NEW_LINE> sample_transaction = sample_transaction_f() <NEW_LINE> sut.add_transaction(**sample_transaction) <NEW_LINE> assert len(sut.current_transactions) == 1 <NEW_LINE> <DEDENT> def test_on_empty_block_transactions_value(self, sample_sut, sample_transaction_f): <NEW_LINE> <INDENT> sut = sample_sut() <NEW_LINE> sample_transaction = sample_transaction_f() <NEW_LINE> sut.add_transaction(**sample_transaction) <NEW_LINE> expected_transaction = { 'input': sample_transaction['unlock'], 'script': sample_transaction['lock'], 'output': None, } <NEW_LINE> assert sut.current_transactions[0] == expected_transaction <NEW_LINE> <DEDENT> def test_on_empty_block_custom_transactions_value(self, sample_sut, sample_transaction_f): <NEW_LINE> <INDENT> sut = sample_sut() <NEW_LINE> sample_transaction = sample_transaction_f(unlock='a = 1', lock='output = a') <NEW_LINE> sut.add_transaction(**sample_transaction) <NEW_LINE> expected_transaction = { 'input': sample_transaction['unlock'], 'script': sample_transaction['lock'], 'output': 1, } <NEW_LINE> assert sut.current_transactions[0] == expected_transaction <NEW_LINE> <DEDENT> def test_on_not_empty_block_transactions_length(self, w_current_transactions_f, sample_transaction_f): <NEW_LINE> <INDENT> current_transaction_number = random.randint(1, 10) <NEW_LINE> sut = w_current_transactions_f(current_transaction_number) <NEW_LINE> prev_len = len(sut.current_transactions) <NEW_LINE> sample_transaction = sample_transaction_f() <NEW_LINE> sut.add_transaction(**sample_transaction) <NEW_LINE> assert len(sut.current_transactions) == prev_len + 1 <NEW_LINE> <DEDENT> def test_on_not_empty_block_transactions_value(self, w_current_transactions_f, sample_transaction_f): <NEW_LINE> <INDENT> current_transaction_number = random.randint(1, 10) <NEW_LINE> sut = w_current_transactions_f(current_transaction_number) <NEW_LINE> sample_transaction = sample_transaction_f() <NEW_LINE> sut.add_transaction(**sample_transaction) <NEW_LINE> expected_transaction = { 'input': sample_transaction['unlock'], 'script': sample_transaction['lock'], 'output': None, } <NEW_LINE> assert sut.current_transactions[-1] == expected_transaction
Test the creation of a add transaction in a block
62598fb8851cf427c66b83f6
class CircularSymplecticEnsemble(CircularEnsemble): <NEW_LINE> <INDENT> def joint_eigen_distribution(self): <NEW_LINE> <INDENT> return self._compute_joint_eigen_distribution(S(4))
Represents Cicular Symplectic Ensembles. Examples ======== >>> from sympy.stats import CircularSymplecticEnsemble as CSE, density >>> from sympy.stats import joint_eigen_distribution >>> C = CSE('S', 1) >>> joint_eigen_distribution(C) Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k]))**4, (_j, _k + 1, 1), (_k, 1, 0))/(2*pi)) Note ==== As can be seen above in the example, density of CiruclarSymplecticEnsemble is not evaluated becuase the exact definition is based on haar measure of unitary group which is not unique.
62598fb823849d37ff8511f3
class Images(object): <NEW_LINE> <INDENT> def __init__(self, skin='default'): <NEW_LINE> <INDENT> self.image = pygame.image.load(resource_stream('robbo', 'skins/'+skin+'/icons.png')).convert_alpha() <NEW_LINE> self.digits = pygame.image.load(resource_stream('robbo', 'skins/'+skin+'/digits.png')).convert_alpha() <NEW_LINE> <DEDENT> def _get_icon_rect(self, n): <NEW_LINE> <INDENT> return pygame.Rect(34*(n%10)+2, 34*(n//10)+2, 32, 32) <NEW_LINE> <DEDENT> def get_icon(self, n): <NEW_LINE> <INDENT> rect = pygame.Rect(0,0, 32,32) <NEW_LINE> img = pygame.Surface((32,32)).convert_alpha() <NEW_LINE> img.fill((0,0,0,0)) <NEW_LINE> img.blit(self.image, rect, self._get_icon_rect(n)) <NEW_LINE> return img <NEW_LINE> <DEDENT> def _get_digit_rect(self, n): <NEW_LINE> <INDENT> return pygame.Rect(18*n,0,16,32) <NEW_LINE> <DEDENT> def get_digits(self): <NEW_LINE> <INDENT> digits = [] <NEW_LINE> rect = pygame.Rect(0,0, 16,32) <NEW_LINE> for n in range(10): <NEW_LINE> <INDENT> img = pygame.Surface((16,32)).convert_alpha() <NEW_LINE> img.fill((0,0,0,0)) <NEW_LINE> img.blit(self.digits, rect, self._get_digit_rect(n)) <NEW_LINE> digits.append(img) <NEW_LINE> <DEDENT> return digits
Class responsible for visuals managements Unlike sounds this is kept in class, so multiple skin pack can be selected.
62598fb860cbc95b06364480
class IPATests(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self._ipa = OsmoIPAccessProtocol(None) <NEW_LINE> self._writes = Mock() <NEW_LINE> def convert_memview_to_bytes(memview): <NEW_LINE> <INDENT> return self._writes(memview.tobytes()) <NEW_LINE> <DEDENT> self._transport = asyncio.Transport() <NEW_LINE> self._transport.write = Mock(side_effect=convert_memview_to_bytes) <NEW_LINE> self._ipa.connection_made(self._transport) <NEW_LINE> <DEDENT> def _check_reply(self, req_bytes, resp_bytes): <NEW_LINE> <INDENT> for step in range(1, len(req_bytes) + 1): <NEW_LINE> <INDENT> offset = 0 <NEW_LINE> while offset < len(req_bytes): <NEW_LINE> <INDENT> self._ipa.data_received(req_bytes[offset:offset + step]) <NEW_LINE> offset += step <NEW_LINE> <DEDENT> self._writes.assert_called_once_with(resp_bytes) <NEW_LINE> self._writes.reset_mock() <NEW_LINE> <DEDENT> <DEDENT> def _check_ping(self): <NEW_LINE> <INDENT> self._check_reply(b'\x00\x01\xfe\x00', b'\x00\x01\xfe\x01') <NEW_LINE> <DEDENT> def test_ping(self): <NEW_LINE> <INDENT> self._check_ping() <NEW_LINE> <DEDENT> def test_ignore_unknown(self): <NEW_LINE> <INDENT> self._ipa.data_received(b'\x00\x02\xee\x06\x01') <NEW_LINE> self._writes.assert_not_called() <NEW_LINE> self._check_ping()
Test class for osmo IPA protocols
62598fb84428ac0f6e658662
class SetPeerAddr(BaseNXObject): <NEW_LINE> <INDENT> def __init__(self, name, seq_no, version='v4', state='disabled', session=None, parent=None): <NEW_LINE> <INDENT> super(SetPeerAddr, self).__init__(name) <NEW_LINE> self._session= session <NEW_LINE> self._parent = parent <NEW_LINE> self.peer_obj = 'rtmapSetNhPeerAddr' <NEW_LINE> self.name = name <NEW_LINE> self.seq_no = seq_no <NEW_LINE> self.version = version <NEW_LINE> self.state = state <NEW_LINE> <DEDENT> def _get_attributes(self): <NEW_LINE> <INDENT> att = {} <NEW_LINE> if self.version == 'v4': <NEW_LINE> <INDENT> att['v4PeerAddr'] = self.state <NEW_LINE> <DEDENT> if self.version == 'v6': <NEW_LINE> <INDENT> att['v6PeerAddr'] = self.state <NEW_LINE> <DEDENT> return att <NEW_LINE> <DEDENT> def get_url(self): <NEW_LINE> <INDENT> return ('/api/node/mo/sys/rpm/rtmap-' + self.name + '/ent-' + self.seq_no + '/nhpa.json') <NEW_LINE> <DEDENT> def get_json(self): <NEW_LINE> <INDENT> return super(SetPeerAddr, self).get_json(obj_class=self.peer_obj, attributes=self._get_attributes())
This class defines set peer address configuration
62598fb832920d7e50bc618f
class TranslationMiddleware(Middleware): <NEW_LINE> <INDENT> def __init__(self, translator: MicrosoftTranslator, user_state: UserState): <NEW_LINE> <INDENT> self.translator = translator <NEW_LINE> self.language_preference_accessor = user_state.create_property( "LanguagePreference" ) <NEW_LINE> <DEDENT> async def on_turn( self, context: TurnContext, logic: Callable[[TurnContext], Awaitable] ): <NEW_LINE> <INDENT> translate = await self._should_translate(context) <NEW_LINE> if translate and context.activity.type == ActivityTypes.message: <NEW_LINE> <INDENT> context.activity.text = await self.translator.translate( context.activity.text, TranslationSettings.default_language.value ) <NEW_LINE> <DEDENT> async def aux_on_send( ctx: TurnContext, activities: List[Activity], next_send: Callable ): <NEW_LINE> <INDENT> user_language = await self.language_preference_accessor.get( ctx, TranslationSettings.default_language.value ) <NEW_LINE> should_translate = ( user_language != TranslationSettings.default_language.value ) <NEW_LINE> if should_translate: <NEW_LINE> <INDENT> for activity in activities: <NEW_LINE> <INDENT> await self._translate_message_activity(activity, user_language) <NEW_LINE> <DEDENT> <DEDENT> return await next_send() <NEW_LINE> <DEDENT> async def aux_on_update( ctx: TurnContext, activity: Activity, next_update: Callable ): <NEW_LINE> <INDENT> user_language = await self.language_preference_accessor.get( ctx, TranslationSettings.default_language.value ) <NEW_LINE> should_translate = ( user_language != TranslationSettings.default_language.value ) <NEW_LINE> if should_translate and activity.type == ActivityTypes.message: <NEW_LINE> <INDENT> await self._translate_message_activity(activity, user_language) <NEW_LINE> <DEDENT> return await next_update() <NEW_LINE> <DEDENT> context.on_send_activities(aux_on_send) <NEW_LINE> context.on_update_activity(aux_on_update) <NEW_LINE> await logic() <NEW_LINE> <DEDENT> async def _should_translate(self, turn_context: TurnContext) -> bool: <NEW_LINE> <INDENT> user_language = await self.language_preference_accessor.get( turn_context, TranslationSettings.default_language.value ) <NEW_LINE> return user_language != TranslationSettings.default_language.value <NEW_LINE> <DEDENT> async def _translate_message_activity(self, activity: Activity, target_locale: str): <NEW_LINE> <INDENT> if activity.type == ActivityTypes.message: <NEW_LINE> <INDENT> activity.text = await self.translator.translate( activity.text, target_locale )
Middleware for translating text between the user and bot. Uses the Microsoft Translator Text API.
62598fb8be7bc26dc9251efc
class SubmissionFileHandler(FileHandler): <NEW_LINE> <INDENT> @tornado_web.authenticated <NEW_LINE> @actual_phase_required(0, 3) <NEW_LINE> @multi_contest <NEW_LINE> def get(self, task_name, submission_num, filename): <NEW_LINE> <INDENT> if not self.contest.submissions_download_allowed: <NEW_LINE> <INDENT> raise tornado_web.HTTPError(404) <NEW_LINE> <DEDENT> task = self.get_task(task_name) <NEW_LINE> if task is None: <NEW_LINE> <INDENT> raise tornado_web.HTTPError(404) <NEW_LINE> <DEDENT> submission = self.get_submission(task, submission_num) <NEW_LINE> if submission is None: <NEW_LINE> <INDENT> raise tornado_web.HTTPError(404) <NEW_LINE> <DEDENT> stored_filename = filename <NEW_LINE> if submission.language is not None: <NEW_LINE> <INDENT> extension = get_language(submission.language).source_extension <NEW_LINE> stored_filename = re.sub(r'%s$' % extension, '.%l', filename) <NEW_LINE> <DEDENT> if stored_filename not in submission.files: <NEW_LINE> <INDENT> raise tornado_web.HTTPError(404) <NEW_LINE> <DEDENT> digest = submission.files[stored_filename].digest <NEW_LINE> self.sql_session.close() <NEW_LINE> mimetype = get_type_for_file_name(filename) <NEW_LINE> if mimetype is None: <NEW_LINE> <INDENT> mimetype = 'application/octet-stream' <NEW_LINE> <DEDENT> self.fetch(digest, mimetype, filename)
Send back a submission file.
62598fb871ff763f4b5e78b8
class Player(object): <NEW_LINE> <INDENT> def blast(self, enemy): <NEW_LINE> <INDENT> print("The Player shoots the enemy \n") <NEW_LINE> enemy.die()
The Player
62598fb84c3428357761a3fc
class MenuBar(BoxLayout): <NEW_LINE> <INDENT> file_menu = ObjectProperty(None) <NEW_LINE> see_menu = ObjectProperty(None) <NEW_LINE> def propagate_editor_container(self, editor_container): <NEW_LINE> <INDENT> self.editor_container = editor_container <NEW_LINE> self.file_menu.propagate_editor_container(editor_container) <NEW_LINE> self.see_menu.propagate_editor_container(editor_container)
Contains the main menus for the application. These menus include (more can be added or some can be removed): * File Menu: To create a new file, save a file... * See Menu: To select what to see (line numbers, for example)
62598fb8091ae35668704d61
class Robot(object): <NEW_LINE> <INDENT> def __init__(self, room, speed, capacity): <NEW_LINE> <INDENT> self.speed = speed <NEW_LINE> self.capacity = capacity <NEW_LINE> self.room = room <NEW_LINE> self.d = random.uniform(0, 360) <NEW_LINE> self.pos = Position(random.uniform(0, room.width), random.uniform(0, room.height)) <NEW_LINE> <DEDENT> def get_robot_position(self): <NEW_LINE> <INDENT> return self.pos <NEW_LINE> <DEDENT> def get_robot_direction(self): <NEW_LINE> <INDENT> return self.d <NEW_LINE> <DEDENT> def set_robot_position(self, position): <NEW_LINE> <INDENT> self.pos = position <NEW_LINE> return self.pos <NEW_LINE> <DEDENT> def set_robot_direction(self, direction): <NEW_LINE> <INDENT> self.d = direction <NEW_LINE> return self.d <NEW_LINE> <DEDENT> def update_position_and_clean(self): <NEW_LINE> <INDENT> raise NotImplementedError
Represents a robot cleaning a particular room. At all times, the robot has a particular position and direction in the room. The robot also has a fixed speed and a fixed cleaning capacity. Subclasses of Robot should provide movement strategies by implementing update_position_and_clean, which simulates a single time-step.
62598fb84a966d76dd5ef013
class HandleMysql: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> do_config = HandleConfig() <NEW_LINE> self.connt = pymysql.connect( host = do_config("mysql", "host"), port = do_config("mysql", "port"), db = do_config("mysql", "db"), user = do_config("mysql", "username"), password = do_config("mysql", "test"), charset = "utf8", cursorclass = pymysql.cursors.DictCursor) <NEW_LINE> self.cursor = self.connt.cursor() <NEW_LINE> <DEDENT> def __call__(self, sql, args=None, is_more=False): <NEW_LINE> <INDENT> self.cursor.execute(sql, args) <NEW_LINE> self.connt.commit() <NEW_LINE> if is_more: <NEW_LINE> <INDENT> result = self.cursor.fetchall() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = self.cursor.fetchone() <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_mobile(): <NEW_LINE> <INDENT> num_list = [133 , 149 , 153 , 173 , 177 , 180 , 181 , 189 , 191 , 199 , 130 , 131 , 132 , 145 , 155 , 156 , 166 , 171 , 175 , 176 , 185 , 186 , 134 , 135 , 136 , 137 , 138 , 139 , 147 , 150 , 151 , 152 , 157 , 158 , 159 , 172 , 178 , 182 , 183 , 184 , 187 , 188] <NEW_LINE> first_num = random.choice(num_list) <NEW_LINE> second_num = "".join(random.sample(string.digits,8)) <NEW_LINE> return str(first_num) + second_num <NEW_LINE> <DEDENT> def is_existed_mobile(self,mobile): <NEW_LINE> <INDENT> sql = "SELECT t.MobilePhone from member t where t.MobilePhone = %s;" <NEW_LINE> if self(sql, args=(mobile,)): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def create_not_existed_mobile(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> mobile = self.create_mobile() <NEW_LINE> if not self.is_existed_mobile(mobile): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return mobile <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.cursor.close() <NEW_LINE> self.connt.close()
我的mysql处理类
62598fb8f548e778e596b6e6
class ConcurrencePlotter(object): <NEW_LINE> <INDENT> def __init__(self, concurrence=None, labels=None, x_values=None): <NEW_LINE> <INDENT> self.concurrence = concurrence <NEW_LINE> self.labels = self.get_concurrence_labels(concurrence, labels) <NEW_LINE> self._x_values = x_values <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_concurrence_labels(concurrence, labels=None): <NEW_LINE> <INDENT> if labels is None: <NEW_LINE> <INDENT> if concurrence and concurrence.labels is not None: <NEW_LINE> <INDENT> labels = concurrence.labels <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> labels = [str(i) for i in range(len(concurrence.values))] <NEW_LINE> <DEDENT> <DEDENT> return labels <NEW_LINE> <DEDENT> @property <NEW_LINE> def x_values(self): <NEW_LINE> <INDENT> x_values = self._x_values <NEW_LINE> if x_values is None: <NEW_LINE> <INDENT> x_values = list(range(len(self.concurrence.values[0]))) <NEW_LINE> <DEDENT> return x_values <NEW_LINE> <DEDENT> @x_values.setter <NEW_LINE> def x_values(self, x_values): <NEW_LINE> <INDENT> self._x_values = x_values <NEW_LINE> <DEDENT> def plot(self, concurrence=None, **kwargs): <NEW_LINE> <INDENT> if not HAS_MATPLOTLIB: <NEW_LINE> <INDENT> raise ImportError("matplotlib not installed") <NEW_LINE> <DEDENT> if concurrence is None: <NEW_LINE> <INDENT> concurrence = self.concurrence <NEW_LINE> <DEDENT> labels = self.get_concurrence_labels(concurrence=concurrence) <NEW_LINE> x_values = self.x_values <NEW_LINE> fig = plt.figure(1) <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> plot_kwargs = {'markersize': 1} <NEW_LINE> plot_kwargs.update(kwargs) <NEW_LINE> y_val = -1.0 <NEW_LINE> for label, val_set in zip(labels, concurrence.values): <NEW_LINE> <INDENT> x_vals = [x for (x, y) in zip(x_values, val_set) if y] <NEW_LINE> ax.plot(x_vals, [y_val] * len(x_vals), '.', label=label, **plot_kwargs) <NEW_LINE> y_val -= 1.0 <NEW_LINE> <DEDENT> ax.set_ylim(top=0.0) <NEW_LINE> ax.set_xlim(left=min(x_values), right=max(x_values)) <NEW_LINE> ax.set_yticks([]) <NEW_LINE> lgd = ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) <NEW_LINE> return (fig, ax, lgd)
Plot manager for contact concurrences. Parameters ---------- concurrence : :class:`.Concurrence` concurrence to plot; default None allows to override later labels : list of string labels for the contact pairs, default None will use concurrence labels if available, integers if not x_values : list of numeric values to use for the time axis; default None uses integers starting at 0 (can be used to assign the actual simulation time to the x-axis)
62598fb8fff4ab517ebcd929
class PrintSponsorshipBvr(models.TransientModel): <NEW_LINE> <INDENT> _name = 'print.sponsorship.gift.bvr' <NEW_LINE> birthday_gift = fields.Boolean(default=True) <NEW_LINE> general_gift = fields.Boolean(default=True) <NEW_LINE> family_gift = fields.Boolean(default=True) <NEW_LINE> project_gift = fields.Boolean() <NEW_LINE> graduation_gift = fields.Boolean() <NEW_LINE> paper_format = fields.Selection([ ('report_compassion.3bvr_gift_sponsorship', '3 BVR'), ('report_compassion.2bvr_gift_sponsorship', '2 BVR'), ('report_compassion.bvr_gift_sponsorship', 'Single BVR') ], default='report_compassion.3bvr_gift_sponsorship') <NEW_LINE> draw_background = fields.Boolean() <NEW_LINE> state = fields.Selection([('new', 'new'), ('pdf', 'pdf')], default='new') <NEW_LINE> pdf = fields.Boolean() <NEW_LINE> pdf_name = fields.Char(default='fund.pdf') <NEW_LINE> pdf_download = fields.Binary(readonly=True) <NEW_LINE> preprinted = fields.Boolean( help='Enable if you print on a payment slip that already has company ' 'information printed on it.' ) <NEW_LINE> @api.onchange('pdf') <NEW_LINE> def onchange_pdf(self): <NEW_LINE> <INDENT> if self.pdf: <NEW_LINE> <INDENT> self.draw_background = True <NEW_LINE> self.preprinted = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.draw_background = False <NEW_LINE> <DEDENT> <DEDENT> @api.multi <NEW_LINE> def print_report(self): <NEW_LINE> <INDENT> product_search = list() <NEW_LINE> if self.birthday_gift: <NEW_LINE> <INDENT> product_search.append(GIFT_REF[0]) <NEW_LINE> <DEDENT> if self.general_gift: <NEW_LINE> <INDENT> product_search.append(GIFT_REF[1]) <NEW_LINE> <DEDENT> if self.family_gift: <NEW_LINE> <INDENT> product_search.append(GIFT_REF[2]) <NEW_LINE> <DEDENT> if self.project_gift: <NEW_LINE> <INDENT> product_search.append(GIFT_REF[3]) <NEW_LINE> <DEDENT> if self.graduation_gift: <NEW_LINE> <INDENT> product_search.append(GIFT_REF[4]) <NEW_LINE> <DEDENT> if not product_search: <NEW_LINE> <INDENT> raise odooWarning(_("Please select at least one gift type.")) <NEW_LINE> <DEDENT> products = self.env['product.product'].search([ ('default_code', 'in', product_search)]) <NEW_LINE> data = { 'doc_ids': self.env.context.get('active_ids'), 'product_ids': products.ids, 'background': self.draw_background, 'preprinted': self.preprinted, } <NEW_LINE> records = self.env[self.env.context.get('active_model')].browse( data['doc_ids']) <NEW_LINE> if self.pdf: <NEW_LINE> <INDENT> name = records.name if len(records) == 1 else _('gift payment slips') <NEW_LINE> self.pdf_name = name + '.pdf' <NEW_LINE> self.pdf_download = base64.b64encode( self.env['report'].with_context( must_skip_send_to_printer=True).get_pdf( records.ids, self.paper_format, data=data)) <NEW_LINE> self.state = 'pdf' <NEW_LINE> return { 'name': 'Download report', 'type': 'ir.actions.act_window', 'res_model': self._name, 'res_id': self.id, 'view_mode': 'form', 'target': 'new', 'context': self.env.context, } <NEW_LINE> <DEDENT> return self.env['report'].get_action( records.ids, self.paper_format, data )
Wizard for selecting a period and the format for printing payment slips of a sponsorship.
62598fb867a9b606de546112
class ServiceBusManagementClient(object): <NEW_LINE> <INDENT> def __init__( self, credentials, subscription_id, base_url=None): <NEW_LINE> <INDENT> self.config = ServiceBusManagementClientConfiguration(credentials, subscription_id, base_url) <NEW_LINE> self._client = ServiceClient(self.config.credentials, self.config) <NEW_LINE> client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} <NEW_LINE> self.api_version = '2017-04-01' <NEW_LINE> self._serialize = Serializer(client_models) <NEW_LINE> self._deserialize = Deserializer(client_models) <NEW_LINE> self.operations = Operations( self._client, self.config, self._serialize, self._deserialize) <NEW_LINE> self.namespaces = NamespacesOperations( self._client, self.config, self._serialize, self._deserialize) <NEW_LINE> self.disaster_recovery_configs = DisasterRecoveryConfigsOperations( self._client, self.config, self._serialize, self._deserialize) <NEW_LINE> self.queues = QueuesOperations( self._client, self.config, self._serialize, self._deserialize) <NEW_LINE> self.topics = TopicsOperations( self._client, self.config, self._serialize, self._deserialize) <NEW_LINE> self.subscriptions = SubscriptionsOperations( self._client, self.config, self._serialize, self._deserialize) <NEW_LINE> self.rules = RulesOperations( self._client, self.config, self._serialize, self._deserialize) <NEW_LINE> self.regions = RegionsOperations( self._client, self.config, self._serialize, self._deserialize) <NEW_LINE> self.premium_messaging_regions = PremiumMessagingRegionsOperations( self._client, self.config, self._serialize, self._deserialize) <NEW_LINE> self.event_hubs = EventHubsOperations( self._client, self.config, self._serialize, self._deserialize)
Azure Service Bus client :ivar config: Configuration for client. :vartype config: ServiceBusManagementClientConfiguration :ivar operations: Operations operations :vartype operations: azure.mgmt.servicebus.operations.Operations :ivar namespaces: Namespaces operations :vartype namespaces: azure.mgmt.servicebus.operations.NamespacesOperations :ivar disaster_recovery_configs: DisasterRecoveryConfigs operations :vartype disaster_recovery_configs: azure.mgmt.servicebus.operations.DisasterRecoveryConfigsOperations :ivar queues: Queues operations :vartype queues: azure.mgmt.servicebus.operations.QueuesOperations :ivar topics: Topics operations :vartype topics: azure.mgmt.servicebus.operations.TopicsOperations :ivar subscriptions: Subscriptions operations :vartype subscriptions: azure.mgmt.servicebus.operations.SubscriptionsOperations :ivar rules: Rules operations :vartype rules: azure.mgmt.servicebus.operations.RulesOperations :ivar regions: Regions operations :vartype regions: azure.mgmt.servicebus.operations.RegionsOperations :ivar premium_messaging_regions: PremiumMessagingRegions operations :vartype premium_messaging_regions: azure.mgmt.servicebus.operations.PremiumMessagingRegionsOperations :ivar event_hubs: EventHubs operations :vartype event_hubs: azure.mgmt.servicebus.operations.EventHubsOperations :param credentials: Credentials needed for the client to connect to Azure. :type credentials: :mod:`A msrestazure Credentials object<msrestazure.azure_active_directory>` :param subscription_id: Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. :type subscription_id: str :param str base_url: Service URL
62598fb87047854f4633f517
@adapter(Interface, ICopyAction, Interface) <NEW_LINE> @implementer(IExecutable) <NEW_LINE> class CopyActionExecutor(object): <NEW_LINE> <INDENT> def __init__(self, context, element, event): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.element = element <NEW_LINE> self.event = event <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> portal_url = getToolByName(self.context, 'portal_url', None) <NEW_LINE> if portal_url is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> obj = self.event.object <NEW_LINE> path = self.element.target_folder <NEW_LINE> if len(path) > 1 and path[0] == '/': <NEW_LINE> <INDENT> path = path[1:] <NEW_LINE> <DEDENT> target = portal_url.getPortalObject().unrestrictedTraverse( str(path), None, ) <NEW_LINE> if target is None: <NEW_LINE> <INDENT> self.error( obj, _( u'Target folder ${target} does not exist.', mapping={'target': path} ) ) <NEW_LINE> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> obj._notifyOfCopyTo(target, op=0) <NEW_LINE> <DEDENT> except ConflictError: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.error(obj, str(e)) <NEW_LINE> return False <NEW_LINE> <DEDENT> old_id = obj.getId() <NEW_LINE> new_id = self.generate_id(target, old_id) <NEW_LINE> orig_obj = obj <NEW_LINE> obj = obj._getCopy(target) <NEW_LINE> obj._setId(new_id) <NEW_LINE> notify(ObjectCopiedEvent(obj, orig_obj)) <NEW_LINE> target._setObject(new_id, obj) <NEW_LINE> obj = target._getOb(new_id) <NEW_LINE> obj.wl_clearLocks() <NEW_LINE> obj._postCopy(target, op=0) <NEW_LINE> OFS.subscribers.compatibilityCall('manage_afterClone', obj, obj) <NEW_LINE> notify(ObjectClonedEvent(obj)) <NEW_LINE> return True <NEW_LINE> <DEDENT> def error(self, obj, error): <NEW_LINE> <INDENT> request = getattr(self.context, 'REQUEST', None) <NEW_LINE> if request is not None: <NEW_LINE> <INDENT> title = utils.pretty_title_or_id(obj, obj) <NEW_LINE> message = _( u'Unable to copy ${name} as part of content rule ' u"'copy' action: ${error}", mapping={'name': title, 'error': error} ) <NEW_LINE> IStatusMessage(request).addStatusMessage(message, type='error') <NEW_LINE> <DEDENT> <DEDENT> def generate_id(self, target, old_id): <NEW_LINE> <INDENT> taken = getattr(aq_base(target), 'has_key', None) <NEW_LINE> if taken is None: <NEW_LINE> <INDENT> item_ids = set(target.objectIds()) <NEW_LINE> def taken(x): return x in item_ids <NEW_LINE> <DEDENT> if not taken(old_id): <NEW_LINE> <INDENT> return old_id <NEW_LINE> <DEDENT> idx = 1 <NEW_LINE> while taken('{0}.{1}'.format(old_id, idx)): <NEW_LINE> <INDENT> idx += 1 <NEW_LINE> <DEDENT> return '{0}.{1}'.format(old_id, idx)
The executor for this action.
62598fb88e7ae83300ee91e1
class Service(service.Service): <NEW_LINE> <INDENT> def __init__(self, executable_path, port=0, service_args=None, log_path="geckodriver.log", env=None): <NEW_LINE> <INDENT> log_file = open(log_path, "a+") if log_path is not None and log_path != "" else None <NEW_LINE> service.Service.__init__( self, executable_path, port=port, log_file=log_file, env=env) <NEW_LINE> self.service_args = service_args or [] <NEW_LINE> <DEDENT> def command_line_args(self): <NEW_LINE> <INDENT> return ["--port", "%d" % self.port] <NEW_LINE> <DEDENT> def send_remote_shutdown_command(self): <NEW_LINE> <INDENT> pass
Object that manages the starting and stopping of the GeckoDriver.
62598fb81b99ca400228f5d1
class DiceAttBlock(Chain): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels, reduction=4, **kwargs): <NEW_LINE> <INDENT> super(DiceAttBlock, self).__init__(**kwargs) <NEW_LINE> mid_channels = in_channels // reduction <NEW_LINE> with self.init_scope(): <NEW_LINE> <INDENT> self.conv1 = conv1x1( in_channels=in_channels, out_channels=mid_channels, use_bias=False) <NEW_LINE> self.activ = F.relu <NEW_LINE> self.conv2 = conv1x1( in_channels=mid_channels, out_channels=out_channels, use_bias=False) <NEW_LINE> self.sigmoid = F.sigmoid <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> w = F.average_pooling_2d(x, ksize=x.shape[2:]) <NEW_LINE> w = self.conv1(w) <NEW_LINE> w = self.activ(w) <NEW_LINE> w = self.conv2(w) <NEW_LINE> w = self.sigmoid(w) <NEW_LINE> return w
Pure attention part of DiCE block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. reduction : int, default 4 Squeeze reduction value.
62598fb897e22403b383b047
class Student: <NEW_LINE> <INDENT> def __init__(self, first_name, last_name, age): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return self.__dict__
Class Student.
62598fb8956e5f7376df571e
class _LasyConnection(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.connection = None <NEW_LINE> <DEDENT> def cursor(self): <NEW_LINE> <INDENT> if self.connection is None: <NEW_LINE> <INDENT> connection = engine.connect() <NEW_LINE> logging.info('open connection <%s>...' % hex(id(connection))) <NEW_LINE> self.connection = connection <NEW_LINE> <DEDENT> return self.connection.cursor() <NEW_LINE> <DEDENT> def commit(self): <NEW_LINE> <INDENT> self.connection.commit() <NEW_LINE> <DEDENT> def rollback(self): <NEW_LINE> <INDENT> self.connection.rollback() <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> if self.connection: <NEW_LINE> <INDENT> connection = self.connection <NEW_LINE> self.connection = None <NEW_LINE> logging.info('close connection <%s>...' % hex(id(connection))) <NEW_LINE> connection.close()
数据库连接类,只有当调用到cursor方法,也就是真正要操作数据库时,才会真正去连接数据库, 这样可以减小不必要的数据库连接,并且提供cleanup方法进行关闭数据库连接和清理。
62598fb8aad79263cf42e915
class ChooseChainTypeAction(argparse.Action): <NEW_LINE> <INDENT> chainTypes = { 'words': { 'chainjoiner':' ', 'eventjoiner':'', 'eventiterator':word_iter }, 'sentences': { 'chainjoiner':'\n', 'eventjoiner':' ', 'eventiterator':sentence_iter }, } <NEW_LINE> def __call__(self, parser, namespace, values, option_string=None): <NEW_LINE> <INDENT> for attr in self.chainTypes[values]: <NEW_LINE> <INDENT> setattr(namespace, attr, self.chainTypes[values][attr])
This class is used as an action for the argparser, and as a registry for the different types of chains supported by the program.
62598fb810dbd63aa1c70cfa
class Solution: <NEW_LINE> <INDENT> def isInterleave(self, s1, s2, s3): <NEW_LINE> <INDENT> n1, n2, n3 = len(s1), len(s2), len(s3) <NEW_LINE> if n1 + n2 != n3: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> f = [[False for _ in range(n2 + 1)] for _ in range(n1 + 1)] <NEW_LINE> f[0][0] = True <NEW_LINE> for i in range(1, n1 + 1): <NEW_LINE> <INDENT> if s1[i - 1] == s3[i - 1] and f[i - 1][0] == True: <NEW_LINE> <INDENT> f[i][0] = True <NEW_LINE> <DEDENT> <DEDENT> for j in range(1, n2 + 1): <NEW_LINE> <INDENT> if s2[j - 1] == s3[j - 1] and f[0][j - 1] == True: <NEW_LINE> <INDENT> f[0][j] = True <NEW_LINE> <DEDENT> <DEDENT> for i in range(1, n1 + 1): <NEW_LINE> <INDENT> for j in range(1, n2 + 1): <NEW_LINE> <INDENT> if (s3[i + j - 1] == s1[i - 1] and f[i - 1][j] == True) or (s3[i + j - 1] == s2[j - 1] and f[i][j - 1] == True): <NEW_LINE> <INDENT> f[i][j] = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return f[n1][n2]
@param s1: A string @param s2: A string @param s3: A string @return: Determine whether s3 is formed by interleaving of s1 and s2
62598fb8e1aae11d1e7ce8c5
class XRefs(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.code = set() <NEW_LINE> self.data = set() <NEW_LINE> <DEDENT> def __iadd__(self, other): <NEW_LINE> <INDENT> self.code.update(other.code) <NEW_LINE> self.data.update(other.data) <NEW_LINE> return self
Container for an instruction's code and data cross references.
62598fb8e5267d203ee6ba41
class GandiOption(click.Option): <NEW_LINE> <INDENT> def display_value(self, ctx, value): <NEW_LINE> <INDENT> gandi = ctx.obj <NEW_LINE> gandi.log('%s: %s' % (self.name, (value if value is not None else 'Not found'))) <NEW_LINE> <DEDENT> def get_default(self, ctx): <NEW_LINE> <INDENT> value = click.Option.get_default(self, ctx) <NEW_LINE> if not self.prompt: <NEW_LINE> <INDENT> self.display_value(ctx, value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def consume_value(self, ctx, opts): <NEW_LINE> <INDENT> value = click.Option.consume_value(self, ctx, opts) <NEW_LINE> if not value: <NEW_LINE> <INDENT> gandi = ctx.obj <NEW_LINE> value = gandi.get(self.name) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> self.display_value(ctx, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.default is None and self.required: <NEW_LINE> <INDENT> metavar = '' <NEW_LINE> if self.type.name not in ['integer', 'text']: <NEW_LINE> <INDENT> metavar = self.make_metavar() <NEW_LINE> <DEDENT> prompt = '%s %s' % (self.help, metavar) <NEW_LINE> gandi.echo(prompt) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> def handle_parse_result(self, ctx, opts, args): <NEW_LINE> <INDENT> value, args = click.Option.handle_parse_result(self, ctx, opts, args) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> if isinstance(self.type, GandiChoice): <NEW_LINE> <INDENT> value = self.type.convert_deprecated_value(value) <NEW_LINE> <DEDENT> gandi = ctx.obj <NEW_LINE> gandi.configure(True, self.name, value) <NEW_LINE> <DEDENT> return value, args
Custom command option class for handling configuration files. When no value was found on command line, try to pull it from configuration Display default or configuration value when needed
62598fb8be383301e025393e
class FileStorage(): <NEW_LINE> <INDENT> __file_path = "file.json" <NEW_LINE> __objects = {} <NEW_LINE> def all(self): <NEW_LINE> <INDENT> return (self.__objects) <NEW_LINE> <DEDENT> def new(self, obj): <NEW_LINE> <INDENT> self.__objects.update({"{}.{}".format(obj.__class__.__name__, obj.id): obj}) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> d1 = {} <NEW_LINE> with open(self.__file_path, mode="w") as f: <NEW_LINE> <INDENT> for k, v in self.__objects.items(): <NEW_LINE> <INDENT> d1[k] = v.to_dict() <NEW_LINE> <DEDENT> json.dump(d1, f) <NEW_LINE> <DEDENT> <DEDENT> def reload(self): <NEW_LINE> <INDENT> if os.path.exists(self.__file_path): <NEW_LINE> <INDENT> with open(self.__file_path, mode="r") as f: <NEW_LINE> <INDENT> readit = json.load(f) <NEW_LINE> for v in readit.values(): <NEW_LINE> <INDENT> a = eval("{}(**v)".format(v["__class__"])) <NEW_LINE> self.new(a)
Stores Python dictionaries as JSON files
62598fb863b5f9789fe852b0
class Bullet(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, start_x, start_y, dest_x, dest_y): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.image = pygame.Surface([4, 10]) <NEW_LINE> self.image.fill(WHITE) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = start_x <NEW_LINE> self.rect.y = start_y <NEW_LINE> self.floating_point_x = start_x <NEW_LINE> self.floating_point_y = start_y <NEW_LINE> x_diff = dest_x - start_x <NEW_LINE> y_diff = dest_y - start_y <NEW_LINE> angle = math.atan2(y_diff, x_diff); <NEW_LINE> velocity = 5 <NEW_LINE> self.change_x = math.cos(angle) * velocity <NEW_LINE> self.change_y = math.sin(angle) * velocity <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.floating_point_y += self.change_y <NEW_LINE> self.floating_point_x += self.change_x <NEW_LINE> self.rect.y = int(self.floating_point_y) <NEW_LINE> self.rect.x = int(self.floating_point_x) <NEW_LINE> if self.rect.x < 0 or self.rect.x > SCREEN_WIDTH or self.rect.y < 0 or self.rect.y > SCREEN_HEIGHT: <NEW_LINE> <INDENT> self.kill()
This class represents the bullet.
62598fb826068e7796d4ca9b
class InternalError(Exception): <NEW_LINE> <INDENT> pass
Raised on unrecoverable errors that abort task with 'internal error'.
62598fb83346ee7daa3376e9
class ListBindingHelper(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def GetList(*__args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def GetListItemProperties(*__args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def GetListItemType(*__args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def GetListName(list,listAccessors): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __all__=[ 'GetList', 'GetListItemProperties', 'GetListItemType', 'GetListName', ]
Provides functionality to discover a bindable list and the properties of the items contained in the list when they differ from the public properties of the object to which they bind.
62598fb891f36d47f2230f4a
class ColorTable(KaitaiStruct): <NEW_LINE> <INDENT> SEQ_FIELDS = ["entries"] <NEW_LINE> def __init__(self, _io, _parent=None, _root=None): <NEW_LINE> <INDENT> self._io = _io <NEW_LINE> self._parent = _parent <NEW_LINE> self._root = _root if _root else self <NEW_LINE> self._debug = collections.defaultdict(dict) <NEW_LINE> <DEDENT> def _read(self): <NEW_LINE> <INDENT> self._debug['entries']['start'] = self._io.pos() <NEW_LINE> self.entries = [] <NEW_LINE> i = 0 <NEW_LINE> while not self._io.is_eof(): <NEW_LINE> <INDENT> if not 'arr' in self._debug['entries']: <NEW_LINE> <INDENT> self._debug['entries']['arr'] = [] <NEW_LINE> <DEDENT> self._debug['entries']['arr'].append({'start': self._io.pos()}) <NEW_LINE> _t_entries = Gif.ColorTableEntry(self._io, self, self._root) <NEW_LINE> _t_entries._read() <NEW_LINE> self.entries.append(_t_entries) <NEW_LINE> self._debug['entries']['arr'][len(self.entries) - 1]['end'] = self._io.pos() <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> self._debug['entries']['end'] = self._io.pos()
.. seealso:: - section 19 - https://www.w3.org/Graphics/GIF/spec-gif89a.txt
62598fb871ff763f4b5e78ba
class RlModel(Model): <NEW_LINE> <INDENT> def step(self, observations) -> dict: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def evaluate(self, rollout: Rollout) -> Evaluator: <NEW_LINE> <INDENT> raise NotImplementedError
Reinforcement learning model
62598fb84c3428357761a3fe
class TestAutoContentTypeAndAcceptHeaders: <NEW_LINE> <INDENT> def test_GET_no_data_no_auto_headers(self, httpbin): <NEW_LINE> <INDENT> r = http('GET', httpbin.url + '/headers') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert r.json['headers']['Accept'] == '*/*' <NEW_LINE> assert 'Content-Type' not in r.json['headers'] <NEW_LINE> <DEDENT> def test_POST_no_data_no_auto_headers(self, httpbin): <NEW_LINE> <INDENT> r = http('POST', httpbin.url + '/post') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert '"Accept": "*/*"' in r <NEW_LINE> assert '"Content-Type": "application/json' not in r <NEW_LINE> <DEDENT> def test_POST_with_data_auto_JSON_headers(self, httpbin): <NEW_LINE> <INDENT> r = http('POST', httpbin.url + '/post', 'a=b') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert '"Accept": "application/json"' in r <NEW_LINE> assert '"Content-Type": "application/json' in r <NEW_LINE> <DEDENT> def test_GET_with_data_auto_JSON_headers(self, httpbin): <NEW_LINE> <INDENT> r = http('POST', httpbin.url + '/post', 'a=b') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert '"Accept": "application/json"' in r, r <NEW_LINE> assert '"Content-Type": "application/json' in r <NEW_LINE> <DEDENT> def test_POST_explicit_JSON_auto_JSON_accept(self, httpbin): <NEW_LINE> <INDENT> r = http('--json', 'POST', httpbin.url + '/post') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert r.json['headers']['Accept'] == 'application/json' <NEW_LINE> assert 'application/json' in r.json['headers']['Content-Type'] <NEW_LINE> <DEDENT> def test_GET_explicit_JSON_explicit_headers(self, httpbin): <NEW_LINE> <INDENT> r = http('--json', 'GET', httpbin.url + '/headers', 'Accept:application/xml', 'Content-Type:application/xml') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert '"Accept": "application/xml"' in r <NEW_LINE> assert '"Content-Type": "application/xml"' in r <NEW_LINE> <DEDENT> def test_POST_form_auto_Content_Type(self, httpbin): <NEW_LINE> <INDENT> r = http('--form', 'POST', httpbin.url + '/post') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert '"Content-Type": "application/x-www-form-urlencoded' in r <NEW_LINE> <DEDENT> def test_POST_form_Content_Type_override(self, httpbin): <NEW_LINE> <INDENT> r = http('--form', 'POST', httpbin.url + '/post', 'Content-Type:application/xml') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert '"Content-Type": "application/xml"' in r <NEW_LINE> <DEDENT> def test_print_only_body_when_stdout_redirected_by_default(self, httpbin): <NEW_LINE> <INDENT> env = TestEnvironment(stdin_isatty=True, stdout_isatty=False) <NEW_LINE> r = http('GET', httpbin.url + '/get', env=env) <NEW_LINE> assert 'HTTP/' not in r <NEW_LINE> <DEDENT> def test_print_overridable_when_stdout_redirected(self, httpbin): <NEW_LINE> <INDENT> env = TestEnvironment(stdin_isatty=True, stdout_isatty=False) <NEW_LINE> r = http('--print=h', 'GET', httpbin.url + '/get', env=env) <NEW_LINE> assert HTTP_OK in r
Test that Accept and Content-Type correctly defaults to JSON, but can still be overridden. The same with Content-Type when --form -f is used.
62598fb855399d3f05626656
class InstantAction(Operation): <NEW_LINE> <INDENT> pass
An instant action attached to a distributed RDataFrame graph node.
62598fb8a219f33f346c6948
class ServerInformation(Struct): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ServerInformation, self).__init__(Tags.SERVER_INFORMATION) <NEW_LINE> self.data = BytearrayStream() <NEW_LINE> self.validate() <NEW_LINE> <DEDENT> def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0): <NEW_LINE> <INDENT> super(ServerInformation, self).read(istream, kmip_version=kmip_version) <NEW_LINE> tstream = BytearrayStream(istream.read(self.length)) <NEW_LINE> self.data = BytearrayStream(tstream.read()) <NEW_LINE> self.is_oversized(tstream) <NEW_LINE> self.validate() <NEW_LINE> <DEDENT> def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0): <NEW_LINE> <INDENT> tstream = BytearrayStream() <NEW_LINE> tstream.write(self.data.buffer) <NEW_LINE> self.length = tstream.length() <NEW_LINE> super(ServerInformation, self).write( ostream, kmip_version=kmip_version ) <NEW_LINE> ostream.write(tstream.buffer) <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> self.__validate() <NEW_LINE> <DEDENT> def __validate(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, ServerInformation): <NEW_LINE> <INDENT> if len(self.data) != len(other.data): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif self.data != other.data: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if isinstance(other, ServerInformation): <NEW_LINE> <INDENT> return not (self == other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "ServerInformation()" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.data)
A structure containing vendor-specific fields and/or substructures. Returned by KMIP servers upon receipt of a Query request for server information. See Section 4.25 of the KMIP 1.1 specification for more information. Note: There are no example structures nor data encodings in the KMIP documentation of this object. Therefore this class handles encoding and decoding its data in a generic way, using a BytearrayStream for primary storage. The intent is for vendor-specific subclasses to decide how to decode this data from the stream attribute. Likewise, these subclasses must decide how to encode their data into the stream attribute. There are no arguments to the constructor and therefore no means by which to validate the object's contents.
62598fb85fdd1c0f98e5e0d2
class Template(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TemplateID = None <NEW_LINE> self.TemplateData = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TemplateID = params.get("TemplateID") <NEW_LINE> self.TemplateData = params.get("TemplateData") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
模板发送相关信息,包含模板ID,模板变量参数等信息
62598fb856b00c62f0fb29fd
class helloString_args(object): <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'word', 'UTF8', None, ), ) <NEW_LINE> def __init__(self, word=None,): <NEW_LINE> <INDENT> self.word = word <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 == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.word = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else 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._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('helloString_args') <NEW_LINE> if self.word is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('word', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.word.encode('utf-8') if sys.version_info[0] == 2 else self.word) <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: - word
62598fb899cbb53fe683101b
class Proxy(Pb2Base): <NEW_LINE> <INDENT> def __init__(self, data=None, **kwargs): <NEW_LINE> <INDENT> object.__setattr__(self, 'srcip_a', None) <NEW_LINE> super(Proxy, self).__init__(vxfld_pb2.Proxy, data=data, **kwargs) <NEW_LINE> <DEDENT> def add_proxy_ip(self, ip_addr): <NEW_LINE> <INDENT> if self._msg.proxy_ips and ip_addr not in self._msg.proxy_ips: <NEW_LINE> <INDENT> ele = self._msg.proxy_ips.add() <NEW_LINE> self._ipv4_pack(ele, ip_addr) <NEW_LINE> self._msg.proxy_hops += 1 <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def srcip(self): <NEW_LINE> <INDENT> if self.srcip_a is None: <NEW_LINE> <INDENT> self.srcip_a = self._ipv4_unpack(self._msg.srcip_n) <NEW_LINE> <DEDENT> return self.srcip_a <NEW_LINE> <DEDENT> @srcip.setter <NEW_LINE> def srcip(self, value): <NEW_LINE> <INDENT> self.srcip_a = value <NEW_LINE> self._ipv4_pack(self._msg.srcip_n, value)
Proxy message from vxsnd to vxsnd.
62598fb81b99ca400228f5d2
class FloatDeltaInterpolateNode(ArmLogicTreeNode): <NEW_LINE> <INDENT> bl_idname = 'LNFloatDeltaInterpolateNode' <NEW_LINE> bl_label = 'Float Delta Interpolate' <NEW_LINE> arm_version = 1 <NEW_LINE> def arm_init(self, context): <NEW_LINE> <INDENT> self.add_input('ArmFloatSocket', 'From', default_value=0.0) <NEW_LINE> self.add_input('ArmFloatSocket', 'To', default_value=1.0) <NEW_LINE> self.add_input('ArmFloatSocket', 'Delta Time') <NEW_LINE> self.add_input('ArmFloatSocket', 'Rate') <NEW_LINE> self.add_output('ArmFloatSocket', 'Result')
Linearly interpolate to a new value with specified interpolation `Rate`. @input From: Value to interpolate from. @input To: Value to interpolate to. @input Delta Time: Delta Time. @input Rate: Rate of interpolation.
62598fb8ec188e330fdf89d4
class ClassifiedsCategory(BaseBTreeFolder, BrowserDefaultMixin): <NEW_LINE> <INDENT> security = ClassSecurityInfo() <NEW_LINE> implements(interfaces.IClassifiedsCategory) <NEW_LINE> meta_type = 'ClassifiedsCategory' <NEW_LINE> _at_rename_after_creation = True <NEW_LINE> schema = ClassifiedsCategory_schema <NEW_LINE> def getPath(self): <NEW_LINE> <INDENT> path = '/'.join(self.getPhysicalPath()) <NEW_LINE> return path <NEW_LINE> <DEDENT> def hasImage(self): <NEW_LINE> <INDENT> if self.getCategoryimage(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def getImageTile(self, **kwargs): <NEW_LINE> <INDENT> if self.hasImage(): <NEW_LINE> <INDENT> portal_obj = getToolByName(self, 'portal_url').getPortalObject() <NEW_LINE> imgtileurl = self.getCategoryimage().absolute_url(1) + '_tile' <NEW_LINE> portal_url = portal_obj.absolute_url(1) <NEW_LINE> imgtileurl = imgtileurl.replace(portal_url, '') <NEW_LINE> if imgtileurl[0] == "/": <NEW_LINE> <INDENT> imgtileurl = imgtileurl.replace('/', '', 1) <NEW_LINE> <DEDENT> return imgtileurl <NEW_LINE> <DEDENT> return ''
Category which can contain Classifieds (such as books)
62598fb82c8b7c6e89bd3908
class Airport: <NEW_LINE> <INDENT> def __init__(self, iata, name, lat, long, currency, fuel): <NEW_LINE> <INDENT> self.iata = iata <NEW_LINE> self.name = name <NEW_LINE> self.lat = lat <NEW_LINE> self.long = long <NEW_LINE> self.currency = currency <NEW_LINE> self.fuel = fuel <NEW_LINE> <DEDENT> def get_lat(self): <NEW_LINE> <INDENT> return float(self.lat) <NEW_LINE> <DEDENT> def get_long(self): <NEW_LINE> <INDENT> return float(self.long) <NEW_LINE> <DEDENT> def get_fuel(self): <NEW_LINE> <INDENT> return self.fuel <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str("IATA: " + self.iata + ", AirportName: " + self.name + ", Lat: " + self.lat + ", Long: " + self.long + " , Currency: " + self.currency + " Fuel: " + self.fuel)
a class to store Airport objects
62598fb8e1aae11d1e7ce8c6
class NoDatabaseException(FaitoutException): <NEW_LINE> <INDENT> pass
Exception thrown when someone has requested to drop a database that does not exist.
62598fb8e5267d203ee6ba43
class Phase(LMatrix): <NEW_LINE> <INDENT> def __init__(self,phase,n=1): <NEW_LINE> <INDENT> LMatrix.__init__(self,"Gate") <NEW_LINE> self.phase = phase <NEW_LINE> ph = larray([[1,0],[0,np.exp(1j*phase)]]) <NEW_LINE> phn = ph <NEW_LINE> for i in range(n-1): <NEW_LINE> <INDENT> ph = tensor_lazy(ph,phn) <NEW_LINE> <DEDENT> self.array = larray(ph)
Phase gate. Applies complex phase shift to qubit.
62598fb82c8b7c6e89bd3909
@api.route('/logout') <NEW_LINE> class LogoutApi(Resource): <NEW_LINE> <INDENT> @api.doc('user logout') <NEW_LINE> def post(self): <NEW_LINE> <INDENT> log_infos: Dict = { 'level': logging.DEBUG, 'msg': 'Logout request.', 'filename': __name__, 'funcName': sys._getframe().f_code.co_name } <NEW_LINE> custom_log_message(app_logger, log_infos) <NEW_LINE> auth_header = request.headers.get('Authorization') <NEW_LINE> return Auth.logout_user(auth_header)
Logout resource
62598fb8d486a94d0ba2c111
class HiveDecimal(HiveStringTypeBase): <NEW_LINE> <INDENT> impl = types.DECIMAL <NEW_LINE> def process_result_value(self, value, dialect): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return decimal.Decimal(value)
Translates strings to decimals
62598fb801c39578d7f12ebe
@dataclasses.dataclass <NEW_LINE> class GridParallelXEBTrialResultParameters: <NEW_LINE> <INDENT> data_collection_id: str <NEW_LINE> layer: GridInteractionLayer <NEW_LINE> depth: int <NEW_LINE> circuit_index: int <NEW_LINE> @property <NEW_LINE> def filename(self) -> str: <NEW_LINE> <INDENT> return os.path.join( self.data_collection_id, 'data', f'{self.layer}', f'circuit-{self.circuit_index}', f'depth-{self.depth}.json', )
Parameters describing a trial result from a grid parallel XEB experiment. Attributes: data_collection_id: The data collection ID of the experiment. layer: The grid layer specifying the pattern of two-qubit interactions in a layer of two-qubit gates for the circuit used to obtain the trial result. depth: The number of cycles executed. A cycle consists of a layer of single-qubit gates followed by a layer of two-qubit gates. circuit_index: The index of the circuit from which the executed cycles are taken.
62598fb8cc40096d6161a27b
class MarzhauserRS232(RS232.RS232): <NEW_LINE> <INDENT> def __init__(self, **kwds): <NEW_LINE> <INDENT> self.live = True <NEW_LINE> self.unit_to_um = 1000.0 <NEW_LINE> self.um_to_unit = 1.0/self.unit_to_um <NEW_LINE> self.x = 0.0 <NEW_LINE> self.y = 0.0 <NEW_LINE> try: <NEW_LINE> <INDENT> super().__init__(**kwds) <NEW_LINE> test = self.commWithResp("?version") <NEW_LINE> if not test: <NEW_LINE> <INDENT> self.live = False <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> print(traceback.format_exc()) <NEW_LINE> self.live = False <NEW_LINE> print("Marzhauser Stage is not connected? Stage is not on?") <NEW_LINE> <DEDENT> <DEDENT> def goAbsolute(self, x, y): <NEW_LINE> <INDENT> x = x * self.um_to_unit <NEW_LINE> y = y * self.um_to_unit <NEW_LINE> self.writeline(" ".join(["!moa", str(x), str(y)])) <NEW_LINE> <DEDENT> def goRelative(self, x, y): <NEW_LINE> <INDENT> x = x * self.um_to_unit <NEW_LINE> y = y * self.um_to_unit <NEW_LINE> self.writeline(" ".join(["!mor", str(x), str(y)])) <NEW_LINE> <DEDENT> def jog(self, x_speed, y_speed): <NEW_LINE> <INDENT> vx = x_speed * self.um_to_unit <NEW_LINE> vy = y_speed * self.um_to_unit <NEW_LINE> self.writeline(" ".join(["!speed ", str(vx), str(vy)])) <NEW_LINE> <DEDENT> def joystickOnOff(self, on): <NEW_LINE> <INDENT> if on: <NEW_LINE> <INDENT> self.writeline("!joy 2") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.writeline("!joy 0") <NEW_LINE> <DEDENT> <DEDENT> def position(self): <NEW_LINE> <INDENT> self.writeline("?pos") <NEW_LINE> <DEDENT> def serialNumber(self): <NEW_LINE> <INDENT> return self.writeline("?readsn") <NEW_LINE> <DEDENT> def setVelocity(self, x_vel, y_vel): <NEW_LINE> <INDENT> self.writeline(" ".join(["!vel",str(x_vel),str(y_vel)])) <NEW_LINE> <DEDENT> def zero(self): <NEW_LINE> <INDENT> self.writeline("!pos 0 0")
Marzhauser RS232 interface class.
62598fb85fdd1c0f98e5e0d3
class CustomerCreateForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Customer <NEW_LINE> fields = ['firstName', 'lastName', 'additionalName', 'ssn', 'address', 'zipCode', 'city', 'telephone', 'email', 'status', 'therapyCategory', 'sessionprice', 'sessionpriceKelaRefund'] <NEW_LINE> labels = { 'firstName': _("Etunimi"), 'additionalName': _("Muut etunimet"), 'lastName': _("Sukunimi"), 'ssn': _("Sosiaaliturvatunnus"), 'address': _("Osoite"), 'zipCode': _("Postinumero"), 'city': _("Postitoimipaikka"), 'telephone': _("Puhelin"), 'email': _("Sähköposti"), 'status': _("Aktiivinen asiakas?"), 'therapyCategory': _("Terapialuokitus"), 'sessionprice': _("Tapaamisen perushinta"), 'sessionpriceKelaRefund': _("Kelan korvaus"), } <NEW_LINE> <DEDENT> therapyCategory = forms.TypedChoiceField( label=Meta.labels['therapyCategory'], choices=Customer.THERAPY_CATEGORY_CHOICES, widget=forms.Select, required=True )
Create Customer form. Field enhancements: * therapyCategory uses forms.TypedChoiceField.
62598fb8f9cc0f698b1c536f
class InMemoryNumpyDataset(indexed_dataset.IndexedDataset): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.buffer = None <NEW_LINE> self.offsets = None <NEW_LINE> self.sizes = None <NEW_LINE> <DEDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> assert i < self.__len__(), f"index {i} out of range!" <NEW_LINE> a = self.buffer[self.offsets[i] : self.offsets[i + 1]] <NEW_LINE> return torch.from_numpy(a) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.offsets.size - 1 <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def save(self, path): <NEW_LINE> <INDENT> assert self.buffer is not None <NEW_LINE> assert self.offsets is not None <NEW_LINE> np.savez(path, buffer=self.buffer, offsets=self.offsets) <NEW_LINE> <DEDENT> def load(self, path): <NEW_LINE> <INDENT> npz = np.load(path) <NEW_LINE> self.buffer = npz["buffer"] <NEW_LINE> self.offsets = npz["offsets"] <NEW_LINE> self.sizes = self.offsets[1:] - self.offsets[:-1] <NEW_LINE> <DEDENT> def parse(self, path, dict, reverse_order=False, append_eos=False): <NEW_LINE> <INDENT> array_list = [] <NEW_LINE> offsets = [0] <NEW_LINE> sizes = [] <NEW_LINE> with open(path, "r") as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> words = tokenizer.tokenize_line(line) <NEW_LINE> if reverse_order: <NEW_LINE> <INDENT> words.reverse() <NEW_LINE> <DEDENT> inds = [dict.index(w) for w in words] <NEW_LINE> if append_eos: <NEW_LINE> <INDENT> inds.append(dict.eos_index) <NEW_LINE> <DEDENT> array_list.append(np.array(inds, dtype=np.int32)) <NEW_LINE> offsets.append(offsets[-1] + len(inds)) <NEW_LINE> sizes.append(len(inds)) <NEW_LINE> <DEDENT> <DEDENT> self.buffer = np.concatenate(array_list) + 1 <NEW_LINE> self.offsets = np.array(offsets, dtype=np.int32) <NEW_LINE> self.sizes = np.array(sizes, dtype=np.int32) <NEW_LINE> del array_list <NEW_LINE> del offsets <NEW_LINE> del sizes <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_from_file(path): <NEW_LINE> <INDENT> result = InMemoryNumpyDataset() <NEW_LINE> result.load(path) <NEW_LINE> return result
analogous to fairseq.indexed_dataset.IndexedInMemoryDataset
62598fb8097d151d1a2c1176
class SatPrinter(object): <NEW_LINE> <INDENT> def __init__(self, vf, cc): <NEW_LINE> <INDENT> self.vf = vf <NEW_LINE> self.cc = cc <NEW_LINE> <DEDENT> def print_statistics(self): <NEW_LINE> <INDENT> print('Variables: ' + str(self.vf.count)) <NEW_LINE> print('Clauses: ' + str(len(self.cc.constraints))) <NEW_LINE> print('Xor Clauses: ' + str(len(self.cc.xor_constraints))) <NEW_LINE> print('Literals: ' + str(self.cc.literals_count)) <NEW_LINE> <DEDENT> def print(self, file): <NEW_LINE> <INDENT> file.write('p cnf ' + str(self.vf.count) + ' ' + str(len(self.cc.constraints) + len(self.cc.xor_constraints)) + '\n') <NEW_LINE> for constraint in self.cc.constraints: <NEW_LINE> <INDENT> for variable in constraint['positive']: <NEW_LINE> <INDENT> file.write(str(variable["number"]) + ' ') <NEW_LINE> <DEDENT> for variable in constraint['negative']: <NEW_LINE> <INDENT> file.write('-' + str(variable["number"]) + ' ') <NEW_LINE> <DEDENT> file.write('0 \n') <NEW_LINE> <DEDENT> for constraint in self.cc.xor_constraints: <NEW_LINE> <INDENT> file.write('x') <NEW_LINE> for variable in constraint['positive']: <NEW_LINE> <INDENT> file.write(str(variable["number"]) + ' ') <NEW_LINE> <DEDENT> for variable in constraint['negative']: <NEW_LINE> <INDENT> file.write('-' + str(variable["number"]) + ' ') <NEW_LINE> <DEDENT> file.write('0 \n') <NEW_LINE> <DEDENT> <DEDENT> def decode_output(self, file): <NEW_LINE> <INDENT> for line in file: <NEW_LINE> <INDENT> if line[0] == 'v': <NEW_LINE> <INDENT> values = line[1:].split() <NEW_LINE> for v in values: <NEW_LINE> <INDENT> variable_number = int(v) <NEW_LINE> if variable_number != 0: <NEW_LINE> <INDENT> self.vf.variables[abs(variable_number)-1]['value'] = variable_number > 0
A class for printing SAT input.
62598fb8167d2b6e312b70ba
class TestPathResolver(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._galaxy_home = None <NEW_LINE> self._lwr_home = None <NEW_LINE> self.galaxy_data = TEST_DATA_DIR <NEW_LINE> self.galaxy_tools = TEST_TOOLS_DIR <NEW_LINE> self.galaxy_indices = TEST_INDICES_DIR <NEW_LINE> <DEDENT> @property <NEW_LINE> def galaxy_home(self): <NEW_LINE> <INDENT> if not self._galaxy_home: <NEW_LINE> <INDENT> self._galaxy_home = mkdtemp() <NEW_LINE> cm_directory = join(dirname(__file__), pardir) <NEW_LINE> src = join(cm_directory, 'universe_wsgi.ini.cloud') <NEW_LINE> dest = join(self._galaxy_home, 'universe_wsgi.ini') <NEW_LINE> copyfile(src, dest) <NEW_LINE> copyfile(src, '%s.sample' % dest) <NEW_LINE> <DEDENT> return self._galaxy_home <NEW_LINE> <DEDENT> @property <NEW_LINE> def lwr_home(self): <NEW_LINE> <INDENT> if not self._lwr_home: <NEW_LINE> <INDENT> self._lwr_home = mkdtemp() <NEW_LINE> <DEDENT> return self._lwr_home
Dummy implementation of PathResolver for unit testing.
62598fb8e1aae11d1e7ce8c7
class AlwaysValidForm(forms.ModelForm): <NEW_LINE> <INDENT> def is_valid(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Parameter <NEW_LINE> fields = '__all__'
A workaround for inlines without change permission not returning all fields causing default ModelForm to complain. Data are unchanged so form might be assumed to be always valid.
62598fb8be383301e0253942
class Dice: <NEW_LINE> <INDENT> def __init__(self, sides: Optional[int] = 6): <NEW_LINE> <INDENT> if not isinstance(sides, int) or sides < 1: <NEW_LINE> <INDENT> raise DiceException('Invalid sides value received.') <NEW_LINE> <DEDENT> self.sides = sides <NEW_LINE> self.last_roll = None <NEW_LINE> <DEDENT> def roll(self) -> int: <NEW_LINE> <INDENT> self.last_roll = randint(1, self.sides) <NEW_LINE> return self.last_roll <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> last_roll = f'[{self.last_roll}]' if self.last_roll else '' <NEW_LINE> return f'D{self.sides}' + last_roll <NEW_LINE> <DEDENT> def __eq__(self, obj) -> bool: <NEW_LINE> <INDENT> if not isinstance(obj, Dice): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.sides == obj.sides <NEW_LINE> <DEDENT> def __len__(self) -> int: <NEW_LINE> <INDENT> return self.last_roll <NEW_LINE> <DEDENT> def __gt__(self, obj) -> bool: <NEW_LINE> <INDENT> if not isinstance(obj, Dice): <NEW_LINE> <INDENT> raise TypeError('Operation only allowed between Dice\'s instances') <NEW_LINE> <DEDENT> return self.sides > obj.sides <NEW_LINE> <DEDENT> def __ge__(self, obj) -> bool: <NEW_LINE> <INDENT> if not isinstance(obj, Dice): <NEW_LINE> <INDENT> raise TypeError('Operation only allowed between Dice\'s instances') <NEW_LINE> <DEDENT> return self.sides >= obj.sides <NEW_LINE> <DEDENT> def __mul__(self, n_rolls: int) -> List[int]: <NEW_LINE> <INDENT> if not isinstance(n_rolls, int): <NEW_LINE> <INDENT> raise TypeError('Unsupported operand type(s) for *') <NEW_LINE> <DEDENT> return [self.roll() for _ in range(n_rolls)]
The Dice object have some sides. Args: sides (int): The number of the sides of a dice instance. Attributes: last_roll (int|None): Result of the last roll of a dice instance. Don't let a dice fall from the table.
62598fb826068e7796d4ca9f
class Rows_worker(Worker): <NEW_LINE> <INDENT> def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): <NEW_LINE> <INDENT> super(self.__class__, self).__init__(hdf5_file, path, slice_queue) <NEW_LINE> self.N = N <NEW_LINE> self.g_rows_sum = g_rows_sum <NEW_LINE> <DEDENT> def process(self, rows_slice): <NEW_LINE> <INDENT> get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice)
The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'.
62598fb87d847024c075c502
class TextStats(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def fit(self, x, y=None): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def transform(self, message): <NEW_LINE> <INDENT> return [{'length': len(text) } for text in message]
Extract features from each document for DictVectorizer
62598fb892d797404e388c06
class IINet(IntervalModule, ColorRangeModule): <NEW_LINE> <INDENT> settings = ( "format", ("username", "Username for IINet"), ("password", "Password for IINet"), ("start_color", "Beginning color for color range"), ("end_color", "End color for color range") ) <NEW_LINE> format = '{percent_used}' <NEW_LINE> start_color = "#00FF00" <NEW_LINE> end_color = "#FF0000" <NEW_LINE> username = None <NEW_LINE> password = None <NEW_LINE> keyring_backend = None <NEW_LINE> def init(self): <NEW_LINE> <INDENT> self.token = None <NEW_LINE> self.service_token = None <NEW_LINE> self.colors = self.get_hex_color_range(self.start_color, self.end_color, 100) <NEW_LINE> <DEDENT> def set_tokens(self): <NEW_LINE> <INDENT> if not self.token or not self.service_token: <NEW_LINE> <INDENT> response = requests.get('https://toolbox.iinet.net.au/cgi-bin/api.cgi?' '_USERNAME=%(username)s&' '_PASSWORD=%(password)s' % self.__dict__).json() <NEW_LINE> if self.valid_response(response): <NEW_LINE> <INDENT> self.token = response['token'] <NEW_LINE> self.service_token = self.get_service_token(response['response']['service_list']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Failed to retrieve token for user: %s" % self.username) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_service_token(self, service_list): <NEW_LINE> <INDENT> for service in service_list: <NEW_LINE> <INDENT> if service['pk_v'] == self.username: <NEW_LINE> <INDENT> return service['s_token'] <NEW_LINE> <DEDENT> <DEDENT> raise Exception("Failed to retrieve service token for user: %s" % self.username) <NEW_LINE> <DEDENT> def valid_response(self, response): <NEW_LINE> <INDENT> return "success" in response and response['success'] == 1 <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.set_tokens() <NEW_LINE> usage = self.get_usage() <NEW_LINE> allocation = usage['allocation'] <NEW_LINE> used = usage['used'] <NEW_LINE> percent_used = self.percentage(used, allocation) <NEW_LINE> percent_avaliable = self.percentage(allocation - used, allocation) <NEW_LINE> color = self.get_gradient(percent_used, self.colors) <NEW_LINE> usage['percent_used'] = '{0:.2f}%'.format(percent_used) <NEW_LINE> usage['percent_available'] = '{0:.2f}%'.format(percent_avaliable) <NEW_LINE> usage['used'] = '{0:.2f}'.format(used / 1000 ** 3) <NEW_LINE> self.data = usage <NEW_LINE> self.output = { "full_text": self.format.format(**usage), "color": color } <NEW_LINE> <DEDENT> def get_usage(self): <NEW_LINE> <INDENT> response = requests.get('https://toolbox.iinet.net.au/cgi-bin/api.cgi?Usage&' '_TOKEN=%(token)s&' '_SERVICE=%(service_token)s' % self.__dict__).json() <NEW_LINE> if self.valid_response(response): <NEW_LINE> <INDENT> for traffic_type in response['response']['usage']['traffic_types']: <NEW_LINE> <INDENT> if traffic_type['name'] in ('anytime', 'usage'): <NEW_LINE> <INDENT> return traffic_type <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Failed to retrieve usage information for: %s" % self.username)
Check IINet Internet usage. Requires `requests` and `colour` Formatters: * `{percentage_used}` — percentage of your quota that is used * `{percentage_available}` — percentage of your quota that is available * `{used}` - GB of your quota used
62598fb8a8370b77170f0525
class _String(LabeledWidget, ValueWidget): <NEW_LINE> <INDENT> _model_module = Unicode('jupyter-js-widgets').tag(sync=True) <NEW_LINE> _view_module = Unicode('jupyter-js-widgets').tag(sync=True) <NEW_LINE> value = Unicode(help="String value").tag(sync=True) <NEW_LINE> disabled = Bool(False, help="Enable or disable user changes").tag(sync=True) <NEW_LINE> placeholder = Unicode("\u200b", help="Placeholder text to display when nothing has been typed").tag(sync=True) <NEW_LINE> def __init__(self, value=None, **kwargs): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> kwargs['value'] = value <NEW_LINE> <DEDENT> super(_String, self).__init__(**kwargs) <NEW_LINE> <DEDENT> _model_name = Unicode('StringModel').tag(sync=True)
Base class used to create widgets that represent a string.
62598fb844b2445a339b6a17
class ContainerServiceSshConfiguration(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'public_keys': {'required': True}, } <NEW_LINE> _attribute_map = { 'public_keys': {'key': 'publicKeys', 'type': '[ContainerServiceSshPublicKey]'}, } <NEW_LINE> def __init__( self, *, public_keys: List["ContainerServiceSshPublicKey"], **kwargs ): <NEW_LINE> <INDENT> super(ContainerServiceSshConfiguration, self).__init__(**kwargs) <NEW_LINE> self.public_keys = public_keys
SSH configuration for Linux-based VMs running on Azure. All required parameters must be populated in order to send to Azure. :ivar public_keys: Required. The list of SSH public keys used to authenticate with Linux-based VMs. A maximum of 1 key may be specified. :vartype public_keys: list[~azure.mgmt.containerservice.v2021_11_01_preview.models.ContainerServiceSshPublicKey]
62598fb8a219f33f346c694c
class PrmListe(Parametre): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Parametre.__init__(self, "liste", "list") <NEW_LINE> self.aide_courte = "liste les autoquêtes existantes" <NEW_LINE> self.aide_longue = "Cette commande liste les autoquêtes existantes." <NEW_LINE> <DEDENT> def interpreter(self, personnage, dic_masques): <NEW_LINE> <INDENT> pass
Commande 'autoquête liste'.
62598fb8097d151d1a2c1178
class TestCleanHeaders(TestCase): <NEW_LINE> <INDENT> def test_clean_headers(self): <NEW_LINE> <INDENT> request = HttpRequest() <NEW_LINE> wrapper = clean_headers('Vary', 'Accept-Encoding') <NEW_LINE> wrapped_view = wrapper(fake_view) <NEW_LINE> response = wrapped_view(request) <NEW_LINE> self.assertEqual(len(response.clean_headers), 2)
Test the `clean_headers` decorator.
62598fb821bff66bcd722db0
class SpanVdest(AciResourceBase): <NEW_LINE> <INDENT> identity_attributes = t.identity( ('vdg_name', t.name), ('name', t.name)) <NEW_LINE> other_attributes = t.other( ('monitored', t.bool), ('display_name', t.name)) <NEW_LINE> _aci_mo_name = 'spanVDest' <NEW_LINE> _tree_parent = SpanVdestGroup <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(SpanVdest, self).__init__({'monitored': False}, **kwargs)
Resource representing a ERSPAN VDest in ACI. Identity attributes are RNs for ERSPAN VDest.
62598fb897e22403b383b04c
class NodeRatingCount(models.Model): <NEW_LINE> <INDENT> node = models.OneToOneField(Node) <NEW_LINE> likes = models.IntegerField(default=0) <NEW_LINE> dislikes = models.IntegerField(default=0) <NEW_LINE> rating_count = models.IntegerField(default=0) <NEW_LINE> rating_avg = models.FloatField(default=0.0) <NEW_LINE> comment_count = models.IntegerField(default=0) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.node.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> app_label = 'participation' <NEW_LINE> db_table = 'participation_node_counts'
Node Rating Count Keep track of participation counts of nodes.
62598fb856b00c62f0fb2a01
class SymbolReferencedError(SymbolError): <NEW_LINE> <INDENT> pass
Symbol cannot be removed because it is still in use.
62598fb899cbb53fe683101f
class Attachment(fhirelement.FHIRElement): <NEW_LINE> <INDENT> resource_name = "Attachment" <NEW_LINE> def __init__(self, jsondict=None): <NEW_LINE> <INDENT> self.contentType = None <NEW_LINE> self.creation = None <NEW_LINE> self.data = None <NEW_LINE> self.hash = None <NEW_LINE> self.language = None <NEW_LINE> self.size = None <NEW_LINE> self.title = None <NEW_LINE> self.url = None <NEW_LINE> super(Attachment, self).__init__(jsondict) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(Attachment, self).elementProperties() <NEW_LINE> js.extend([ ("contentType", "contentType", str, False), ("creation", "creation", fhirdate.FHIRDate, False), ("data", "data", str, False), ("hash", "hash", str, False), ("language", "language", str, False), ("size", "size", int, False), ("title", "title", str, False), ("url", "url", str, False), ]) <NEW_LINE> return js
Content in a format defined elsewhere. For referring to data content defined in other formats.
62598fb8fff4ab517ebcd92f
class token_ (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = pyxb.binding.datatypes.token <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_SIMPLE <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'token') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('/tmp/pyxbdist.mqXn05k/PyXB-1.2.4/pyxb/bundles/wssplat/schemas/soapenc.xsd', 310, 2) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __id = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'id'), 'id', '__httpschemas_xmlsoap_orgsoapencoding_token__id', pyxb.binding.datatypes.ID) <NEW_LINE> __id._DeclarationLocation = pyxb.utils.utility.Location('/tmp/pyxbdist.mqXn05k/PyXB-1.2.4/pyxb/bundles/wssplat/schemas/soapenc.xsd', 62, 4) <NEW_LINE> __id._UseLocation = pyxb.utils.utility.Location('/tmp/pyxbdist.mqXn05k/PyXB-1.2.4/pyxb/bundles/wssplat/schemas/soapenc.xsd', 62, 4) <NEW_LINE> id = property(__id.value, __id.set, None, None) <NEW_LINE> __href = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'href'), 'href', '__httpschemas_xmlsoap_orgsoapencoding_token__href', pyxb.binding.datatypes.anyURI) <NEW_LINE> __href._DeclarationLocation = pyxb.utils.utility.Location('/tmp/pyxbdist.mqXn05k/PyXB-1.2.4/pyxb/bundles/wssplat/schemas/soapenc.xsd', 63, 4) <NEW_LINE> __href._UseLocation = pyxb.utils.utility.Location('/tmp/pyxbdist.mqXn05k/PyXB-1.2.4/pyxb/bundles/wssplat/schemas/soapenc.xsd', 63, 4) <NEW_LINE> href = property(__href.value, __href.set, None, None) <NEW_LINE> _AttributeWildcard = pyxb.binding.content.Wildcard(process_contents=pyxb.binding.content.Wildcard.PC_lax, namespace_constraint=(pyxb.binding.content.Wildcard.NC_not, 'http://schemas.xmlsoap.org/soap/encoding/')) <NEW_LINE> _ElementMap.update({ }) <NEW_LINE> _AttributeMap.update({ __id.name() : __id, __href.name() : __href })
Complex type {http://schemas.xmlsoap.org/soap/encoding/}token with content type SIMPLE
62598fb82c8b7c6e89bd390d
class ListOfCategoryDescriptions(APIView): <NEW_LINE> <INDENT> permission_classes = [permissions.IsAuthenticatedOrReadOnly] <NEW_LINE> def get_object(self, id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Category.objects.get(id=id) <NEW_LINE> <DEDENT> except Product.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> <DEDENT> def get(self, request, id, format=None): <NEW_LINE> <INDENT> category_descriptions = (self.get_object(id)).category_descriptions.all() <NEW_LINE> serializer = CategoryDescriptionSerializer(category_descriptions, many=True, context={'request': request}) <NEW_LINE> return Response(serializer.data)
Retrouvez la liste des descriptions d'une catégorie
62598fb8796e427e5384e8dd
class InformationDescriptor(object): <NEW_LINE> <INDENT> _connection_pool = weakref.WeakValueDictionary() <NEW_LINE> def __init__(self, model): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> self.backrefs = {} <NEW_LINE> self.primary_key_field = None <NEW_LINE> db_name, host, port = self.model._meta.get('database') <NEW_LINE> try: <NEW_LINE> <INDENT> self.connection = self.connect(host, port) <NEW_LINE> <DEDENT> except ConnectionException: <NEW_LINE> <INDENT> self.connection = MockConnection(host, port) <NEW_LINE> <DEDENT> self.db = self.connection[db_name] if db_name else MockDatabase(self.connection) <NEW_LINE> self.collection = getattr(self.db, self.model.__name__) <NEW_LINE> <DEDENT> def __get__(self, document, model=None): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __set__(self, document, value): <NEW_LINE> <INDENT> raise NotImplementedError('Cannot overwrite pynch') <NEW_LINE> <DEDENT> def connect(self, host, port): <NEW_LINE> <INDENT> key = (host, port) <NEW_LINE> if key not in self._connection_pool: <NEW_LINE> <INDENT> connection = pymongo.MongoClient(host=host, port=port) <NEW_LINE> return self._connection_pool.setdefault(key, connection) <NEW_LINE> <DEDENT> return self._connection_pool[key] <NEW_LINE> <DEDENT> @property <NEW_LINE> def objects(self): <NEW_LINE> <INDENT> return QueryManager(self.model) <NEW_LINE> <DEDENT> @property <NEW_LINE> def fields(self): <NEW_LINE> <INDENT> values = dir_(self.model).values() <NEW_LINE> return tuple(v for v in values if isinstance(v, Field)) <NEW_LINE> <DEDENT> def _raw_find(self, dictionary): <NEW_LINE> <INDENT> for fieldname in dictionary.keys(): <NEW_LINE> <INDENT> field = getattr(self.model, fieldname) <NEW_LINE> if field.primary_key and field.name != '_id': <NEW_LINE> <INDENT> dictionary['_id'] = dictionary.pop(fieldname) <NEW_LINE> <DEDENT> <DEDENT> return self.collection.find(dictionary) <NEW_LINE> <DEDENT> def find(self, dictionary): <NEW_LINE> <INDENT> results = self._raw_find(dictionary) <NEW_LINE> if results is not None: <NEW_LINE> <INDENT> return (self.model.to_python(x) for x in results) <NEW_LINE> <DEDENT> raise QueryException('No matching documents') <NEW_LINE> <DEDENT> def get(self, **kwargs): <NEW_LINE> <INDENT> results = self._raw_find(kwargs) <NEW_LINE> if results is None: <NEW_LINE> <INDENT> raise QueryException('No matching documents') <NEW_LINE> <DEDENT> if results.count() > 1: <NEW_LINE> <INDENT> raise QueryException('Multiple objects fouund') <NEW_LINE> <DEDENT> return self.model.to_python(results.next())
Among other things, is responsible for generating and managing pynch connections to the database.
62598fb8f548e778e596b6ed
class _stdform1(object): <NEW_LINE> <INDENT> def __init__(self, x, t): <NEW_LINE> <INDENT> self.rows = 1 <NEW_LINE> self.cols = 1 <NEW_LINE> self.optvars = set((x, t)) <NEW_LINE> self.x = x <NEW_LINE> self.t = t <NEW_LINE> <DEDENT> def indomain(self): <NEW_LINE> <INDENT> if value(self.x > 0): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def getdomain(self): <NEW_LINE> <INDENT> return [self.x > 0] <NEW_LINE> <DEDENT> def setindomain(self): <NEW_LINE> <INDENT> self.x.value = ones(size(self.x)) <NEW_LINE> self.t.value = 2 <NEW_LINE> <DEDENT> def value(self): <NEW_LINE> <INDENT> return -eval(value(self.x)) + value(self.t) <NEW_LINE> <DEDENT> def jacobian(self, var): <NEW_LINE> <INDENT> if var is self.x: <NEW_LINE> <INDENT> return transpose(cvxopt.base.log(value(self.x))) + 1 <NEW_LINE> <DEDENT> elif var is self.t: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise OptimizationError('illegal jacobian') <NEW_LINE> <DEDENT> <DEDENT> def hessianz(self, firstvar, secondvar, z): <NEW_LINE> <INDENT> x = value(self.x) <NEW_LINE> t = value(self.t) <NEW_LINE> if firstvar is secondvar is self.x: <NEW_LINE> <INDENT> return z*diag(x**-1) <NEW_LINE> <DEDENT> elif firstvar is secondvar is self.t: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> elif firstvar is self.x and secondvar is self.t: <NEW_LINE> <INDENT> return zeros(rows(x), rows(t)) <NEW_LINE> <DEDENT> elif firstvar is self.t and secondvar is self.x: <NEW_LINE> <INDENT> return zeros(rows(t), rows(x)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise OptimizationError('illegal hessian')
An F() standard form for -entropy(x) + t <= 0.
62598fb83d592f4c4edbb006
class APIError(APIException): <NEW_LINE> <INDENT> def __init__(self, event): <NEW_LINE> <INDENT> reason = event.get("error_reason") <NEW_LINE> if reason: <NEW_LINE> <INDENT> suffix = " ({})".format(reason) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> suffix = "" <NEW_LINE> <DEDENT> APIException.__init__(self, "{}{}".format(event["error_type"], suffix), event)
Raised by operations which check if an "error" API event happened. .. attribute:: event Dict[str, Any]
62598fb83346ee7daa3376ec
class UsageManager(base.ManagerWithFind): <NEW_LINE> <INDENT> resource_class = Usage <NEW_LINE> usage_prefix = 'os-simple-tenant-usage' <NEW_LINE> def _usage_query(self, start, end, marker=None, limit=None, detailed=None): <NEW_LINE> <INDENT> query = "?start=%s&end=%s" % (start.isoformat(), end.isoformat()) <NEW_LINE> if limit: <NEW_LINE> <INDENT> query = "%s&limit=%s" % (query, int(limit)) <NEW_LINE> <DEDENT> if marker: <NEW_LINE> <INDENT> query = "%s&marker=%s" % (query, marker) <NEW_LINE> <DEDENT> if detailed is not None: <NEW_LINE> <INDENT> query = "%s&detailed=%s" % (query, int(bool(detailed))) <NEW_LINE> <DEDENT> return query <NEW_LINE> <DEDENT> @api_versions.wraps("2.0", "2.39") <NEW_LINE> def list(self, start, end, detailed=False): <NEW_LINE> <INDENT> query_string = self._usage_query(start, end, detailed=detailed) <NEW_LINE> url = '/%s%s' % (self.usage_prefix, query_string) <NEW_LINE> return self._list(url, 'tenant_usages') <NEW_LINE> <DEDENT> @api_versions.wraps("2.40") <NEW_LINE> def list(self, start, end, detailed=False, marker=None, limit=None): <NEW_LINE> <INDENT> query_string = self._usage_query(start, end, marker, limit, detailed) <NEW_LINE> url = '/%s%s' % (self.usage_prefix, query_string) <NEW_LINE> return self._list(url, 'tenant_usages') <NEW_LINE> <DEDENT> @api_versions.wraps("2.0", "2.39") <NEW_LINE> def get(self, tenant_id, start, end): <NEW_LINE> <INDENT> query_string = self._usage_query(start, end) <NEW_LINE> url = '/%s/%s%s' % (self.usage_prefix, tenant_id, query_string) <NEW_LINE> return self._get(url, 'tenant_usage') <NEW_LINE> <DEDENT> @api_versions.wraps("2.40") <NEW_LINE> def get(self, tenant_id, start, end, marker=None, limit=None): <NEW_LINE> <INDENT> query_string = self._usage_query(start, end, marker, limit) <NEW_LINE> url = '/%s/%s%s' % (self.usage_prefix, tenant_id, query_string) <NEW_LINE> return self._get(url, 'tenant_usage')
Manage :class:`Usage` resources.
62598fb8851cf427c66b83fe
class SolveLevelTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def callServer(self,level='SAD1.lvl', strategy='bfs', ma=False): <NEW_LINE> <INDENT> if ma: <NEW_LINE> <INDENT> client = 'main.py' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> client = 'searchclient.py' <NEW_LINE> <DEDENT> args = str(r'java -jar server.jar -l ' + level + ' -c "python src/searchclient -s ' + strategy + '"') <NEW_LINE> print(''.join(args)) <NEW_LINE> argsarr = shlex.split(args) <NEW_LINE> solution = {} <NEW_LINE> with subprocess.Popen(argsarr, stderr=subprocess.PIPE) as proc: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> line = str(proc.stderr.readline()) <NEW_LINE> solutionfoundregex = re.match("^.*Found solution of length (?P<length>\d+)\..*$",line) <NEW_LINE> failregex = re.match(".*(Exception|Error).*",line) <NEW_LINE> if solutionfoundregex: <NEW_LINE> <INDENT> solution['length'] = int(solutionfoundregex.group('length')) <NEW_LINE> line = str(proc.stderr.readline()) <NEW_LINE> statisticsregex = re.match('^.*#Explored:\s*(?P<explored>\d+).*#Frontier:\s*(?P<frontier>\d+).*Time:\s*(?P<time>\d+\.?\d*)\s*s,.*Alloc:\s*(?P<alloc>\d+\.?\d*)\s*MB,\s*MaxAlloc:\s*(?P<maxalloc>\d+\.?\d*)\s*MB.*\..*$',line) <NEW_LINE> if statisticsregex: <NEW_LINE> <INDENT> solution['explored'] = int(statisticsregex.group('explored')) <NEW_LINE> solution['frontier'] = int(statisticsregex.group('frontier')) <NEW_LINE> solution['time'] = float(statisticsregex.group('time')) <NEW_LINE> solution['alloc'] = float(statisticsregex.group('alloc')) <NEW_LINE> solution['maxalloc'] = float(statisticsregex.group('maxalloc')) <NEW_LINE> proc.stderr.close() <NEW_LINE> proc.kill() <NEW_LINE> return solution <NEW_LINE> <DEDENT> <DEDENT> elif failregex: <NEW_LINE> <INDENT> proc.stderr.close() <NEW_LINE> proc.kill() <NEW_LINE> raise Exception('Error found') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> unittest.TestCase.setUp(self) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> unittest.TestCase.tearDown(self)
Application tests for solving levels.
62598fb84c3428357761a404
class Literal: <NEW_LINE> <INDENT> datatype = "int" <NEW_LINE> uom = None <NEW_LINE> type = "literal" <NEW_LINE> def set_value(self,value): <NEW_LINE> <INDENT> if self.datatype == "int": <NEW_LINE> <INDENT> self.value = int(value) <NEW_LINE> <DEDENT> elif self.datatype == "float": <NEW_LINE> <INDENT> self.value = float(value) <NEW_LINE> <DEDENT> elif self.datatype == "string": <NEW_LINE> <INDENT> self.value = str(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.value = None <NEW_LINE> <DEDENT> return self.value <NEW_LINE> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def set_datatype(self,datatype): <NEW_LINE> <INDENT> if datatype in ["int","float","string"] and self.value is not None: <NEW_LINE> <INDENT> self.datatype = datatype <NEW_LINE> self.set_value(self.value)
Basic literal input or output object
62598fb8be7bc26dc9251f00
class ThreadPool(object): <NEW_LINE> <INDENT> def __init__(self, max_num, max_task_num=None): <NEW_LINE> <INDENT> if max_task_num: <NEW_LINE> <INDENT> self.q = queue.Queue(max_task_num) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.q = queue.Queue() <NEW_LINE> <DEDENT> self.max_num = max_num <NEW_LINE> self.cancel = False <NEW_LINE> self.terminal = False <NEW_LINE> self.generate_list = [] <NEW_LINE> self.free_list = [] <NEW_LINE> <DEDENT> def run(self, func, args, callback=None): <NEW_LINE> <INDENT> if self.cancel: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if len(self.free_list) == 0 and len(self.generate_list) < self.max_num: <NEW_LINE> <INDENT> self.generate_thread() <NEW_LINE> <DEDENT> w = (func, args, callback,) <NEW_LINE> self.q.put(w) <NEW_LINE> <DEDENT> def generate_thread(self): <NEW_LINE> <INDENT> t = threading.Thread(target=self.call) <NEW_LINE> t.start() <NEW_LINE> <DEDENT> def call(self): <NEW_LINE> <INDENT> current_thread = threading.currentThread() <NEW_LINE> self.generate_list.append(current_thread) <NEW_LINE> event = self.q.get() <NEW_LINE> while event != StopEvent: <NEW_LINE> <INDENT> func, arguments, callback = event <NEW_LINE> try: <NEW_LINE> <INDENT> result = func(*arguments) <NEW_LINE> success = True <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> success = False <NEW_LINE> result = None <NEW_LINE> <DEDENT> if callback is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> callback(success, result) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> with self.worker_state(self.free_list, current_thread): <NEW_LINE> <INDENT> if self.terminal: <NEW_LINE> <INDENT> event = StopEvent <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> event = self.q.get() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.generate_list.remove(current_thread) <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.cancel = True <NEW_LINE> full_size = len(self.generate_list) <NEW_LINE> while full_size: <NEW_LINE> <INDENT> self.q.put(StopEvent) <NEW_LINE> full_size -= 1 <NEW_LINE> <DEDENT> <DEDENT> def terminate(self): <NEW_LINE> <INDENT> self.terminal = True <NEW_LINE> while self.generate_list: <NEW_LINE> <INDENT> self.q.put(StopEvent) <NEW_LINE> <DEDENT> self.q.queue.clear() <NEW_LINE> <DEDENT> @contextlib.contextmanager <NEW_LINE> def worker_state(self, state_list, worker_thread): <NEW_LINE> <INDENT> state_list.append(worker_thread) <NEW_LINE> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> state_list.remove(worker_thread)
定义一个线程池类。
62598fb855399d3f0562665c
class Cheshire3OaiMetadataWriter(object): <NEW_LINE> <INDENT> def __init__(self, txr): <NEW_LINE> <INDENT> self.txr = txr <NEW_LINE> <DEDENT> def __call__(self, element, rec): <NEW_LINE> <INDENT> if self.txr: <NEW_LINE> <INDENT> doc = self.txr.process_record(session, rec) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> doc = StringDocument(rec.get_xml(session)) <NEW_LINE> <DEDENT> lxmlRec = lxmlParser.process_document(session, doc) <NEW_LINE> dom = lxmlRec.get_dom(session) <NEW_LINE> return element.append(dom)
Cheshire3 Transforming MetadataWriter. An implementation of a 'MetadataWriter' complying with the oaipmh module's API.
62598fb8a219f33f346c694e
class ExperimentDescriptionListSerializer( ExperimentDescriptionBaseSerializer, ExperimentDescriptionRelationBaseSerializer, ExperimentDescriptionFieldMethodSerializer ): <NEW_LINE> <INDENT> url = hyperlinked_identity('research_api:experiment_description_detail', 'slug') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = ExperimentDescription <NEW_LINE> fields =ExperimentDescriptionBaseSerializer.Meta.fields + ['url', ] + ExperimentDescriptionRelationBaseSerializer.Meta.fields
Serialize all records in given fields into an API
62598fb85fdd1c0f98e5e0d8
class Heading(Entity): <NEW_LINE> <INDENT> content: Array["InlineContent"] <NEW_LINE> depth: Optional[Integer] = None <NEW_LINE> def __init__( self, content: Array["InlineContent"], depth: Optional[Integer] = None, id: Optional[String] = None, meta: Optional[Object] = None ) -> None: <NEW_LINE> <INDENT> super().__init__( id=id, meta=meta ) <NEW_LINE> if content is not None: <NEW_LINE> <INDENT> self.content = content <NEW_LINE> <DEDENT> if depth is not None: <NEW_LINE> <INDENT> self.depth = depth
A heading.
62598fb8d7e4931a7ef3c1de
class CreateUsagePlanRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.UsagePlanName = None <NEW_LINE> self.UsagePlanDesc = None <NEW_LINE> self.MaxRequestNum = None <NEW_LINE> self.MaxRequestNumPreSec = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.UsagePlanName = params.get("UsagePlanName") <NEW_LINE> self.UsagePlanDesc = params.get("UsagePlanDesc") <NEW_LINE> self.MaxRequestNum = params.get("MaxRequestNum") <NEW_LINE> self.MaxRequestNumPreSec = params.get("MaxRequestNumPreSec")
CreateUsagePlan request structure.
62598fb8283ffb24f3cf39cc
class lsmon_py(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.refresh() <NEW_LINE> <DEDENT> def query_lsmon(self): <NEW_LINE> <INDENT> lsmon = subprocess.Popen( LSM_LOCATION, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) <NEW_LINE> stdout_value, stderr_value = lsmon.communicate('\r\n'.encode()) <NEW_LINE> buffer = str(stdout_value) <NEW_LINE> buffer = buffer.replace('\\t','') <NEW_LINE> buffer = buffer.replace('"','') <NEW_LINE> return buffer.split('\\r\\n') <NEW_LINE> <DEDENT> def parse(self, option_string): <NEW_LINE> <INDENT> options = re.findall( '[\s]*\|-[\s]*' '([\w\d\s()]+)' '[\s]*:[\s]*' '([\w\d\s]+)' '(\\t)*' ,option_string) <NEW_LINE> if options: <NEW_LINE> <INDENT> return [options[0][0].strip(), options[0][1].strip()] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def refresh(self): <NEW_LINE> <INDENT> self.max_licences = 0 <NEW_LINE> self.used_licences = 0 <NEW_LINE> self.users = [] <NEW_LINE> polling = False <NEW_LINE> solver_poll = False <NEW_LINE> self.max_solver = 0 <NEW_LINE> self.used_solver = 0 <NEW_LINE> for response in self.query_lsmon(): <NEW_LINE> <INDENT> option = self.parse(response) <NEW_LINE> if not option: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> token = option[0] <NEW_LINE> value = option[1] <NEW_LINE> if token == LSM_FEATURE: <NEW_LINE> <INDENT> if value == LSM_KEYID: <NEW_LINE> <INDENT> polling = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> polling = False <NEW_LINE> <DEDENT> if value == LSS_KEYID: <NEW_LINE> <INDENT> solver_poll = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> solver_poll = False <NEW_LINE> <DEDENT> <DEDENT> if polling: <NEW_LINE> <INDENT> if token == LSM_MAX_LICENCES: <NEW_LINE> <INDENT> self.max_licences = value <NEW_LINE> <DEDENT> elif token == LSM_USED_LICENCES: <NEW_LINE> <INDENT> self.used_licences = value <NEW_LINE> <DEDENT> elif token == LSM_USER: <NEW_LINE> <INDENT> self.users.append(value) <NEW_LINE> <DEDENT> <DEDENT> if solver_poll: <NEW_LINE> <INDENT> if token == LSM_MAX_LICENCES: <NEW_LINE> <INDENT> self.max_solver = value <NEW_LINE> <DEDENT> elif token == LSM_USED_LICENCES: <NEW_LINE> <INDENT> self.used_solver = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if int(self.used_licences) < int(self.max_licences): <NEW_LINE> <INDENT> self.free = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.free = False
Provides an interface between LUSAS licence monitor and Python.
62598fb8fff4ab517ebcd931
class DescribeAllTableInfoForDbRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v2"): <NEW_LINE> <INDENT> super(DescribeAllTableInfoForDbRequest, self).__init__( '/regions/{regionId}/instance/{instanceGid}/allTableInfoForDb', 'GET', header, version) <NEW_LINE> self.parameters = parameters
获取指定库下的所有表名
62598fb899cbb53fe6831021
class DatetimeOptions(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "Format": (str, True), "LocaleCode": (str, False), "TimezoneOffset": (str, False), }
`DatetimeOptions <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-databrew-dataset-datetimeoptions.html>`__
62598fb8cc0a2c111447b155
class JobLogConfigModifyIterInfo(NetAppObject): <NEW_LINE> <INDENT> _error_code = None <NEW_LINE> @property <NEW_LINE> def error_code(self): <NEW_LINE> <INDENT> return self._error_code <NEW_LINE> <DEDENT> @error_code.setter <NEW_LINE> def error_code(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('error_code', val) <NEW_LINE> <DEDENT> self._error_code = val <NEW_LINE> <DEDENT> _error_message = None <NEW_LINE> @property <NEW_LINE> def error_message(self): <NEW_LINE> <INDENT> return self._error_message <NEW_LINE> <DEDENT> @error_message.setter <NEW_LINE> def error_message(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('error_message', val) <NEW_LINE> <DEDENT> self._error_message = val <NEW_LINE> <DEDENT> _job_log_config_key = None <NEW_LINE> @property <NEW_LINE> def job_log_config_key(self): <NEW_LINE> <INDENT> return self._job_log_config_key <NEW_LINE> <DEDENT> @job_log_config_key.setter <NEW_LINE> def job_log_config_key(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('job_log_config_key', val) <NEW_LINE> <DEDENT> self._job_log_config_key = val <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_api_name(): <NEW_LINE> <INDENT> return "job-log-config-modify-iter-info" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_desired_attrs(): <NEW_LINE> <INDENT> return [ 'error-code', 'error-message', 'job-log-config-key', ] <NEW_LINE> <DEDENT> def describe_properties(self): <NEW_LINE> <INDENT> return { 'error_code': { 'class': int, 'is_list': False, 'required': 'optional' }, 'error_message': { 'class': basestring, 'is_list': False, 'required': 'optional' }, 'job_log_config_key': { 'class': JobLogConfigInfo, 'is_list': False, 'required': 'required' }, }
Information about the modify operation that was attempted/performed against job-log-config object. not modified due to some error. due to some error. This element will be returned only if input element 'return-failure-list' is true.
62598fb810dbd63aa1c70d02
class TestSetCheckbox(TestCase): <NEW_LINE> <INDENT> def test_initializer(self): <NEW_LINE> <INDENT> set_checkbox = SetCheckbox(ANY_CSS_PATH, ANY_HINT, True) <NEW_LINE> self.assertEqual(set_checkbox.css_path, ANY_CSS_PATH) <NEW_LINE> self.assertEqual(set_checkbox.hint, ANY_HINT) <NEW_LINE> self.assertEqual(set_checkbox.checked, True) <NEW_LINE> <DEDENT> def test_run_set_checkbox(self): <NEW_LINE> <INDENT> driver_testable = DriverTestable() <NEW_LINE> set_checkbox = SetCheckbox(ANY_CSS_PATH, ANY_HINT, True) <NEW_LINE> with patch.object(driver_testable, 'set_checkbox') as driver_mock: <NEW_LINE> <INDENT> step_result = set_checkbox.run(driver_testable) <NEW_LINE> driver_mock.assert_called_with(set_checkbox.css_path, set_checkbox.hint, set_checkbox.checked) <NEW_LINE> self.assertEqual(step_result.step, set_checkbox) <NEW_LINE> self.assertTrue(step_result.success) <NEW_LINE> self.assertIsNone(step_result.exception) <NEW_LINE> <DEDENT> <DEDENT> def test_run_set_checkbox_exception(self): <NEW_LINE> <INDENT> driver_testable = DriverTestable() <NEW_LINE> set_checkbox = SetCheckbox(ANY_CSS_PATH, ANY_HINT, True) <NEW_LINE> with patch.object(driver_testable, 'set_checkbox') as driver_mock: <NEW_LINE> <INDENT> exception = Exception() <NEW_LINE> driver_mock.side_effect = exception <NEW_LINE> step_result = set_checkbox.run(driver_testable) <NEW_LINE> self.assertEqual(step_result.step, set_checkbox) <NEW_LINE> self.assertFalse(step_result.success) <NEW_LINE> self.assertEqual(step_result.exception, exception)
Has unit tests for the set checkbox class
62598fb8167d2b6e312b70be