code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class HtmlPattern(Pattern): <NEW_LINE> <INDENT> def handleMatch(self, m): <NEW_LINE> <INDENT> rawhtml = self.unescape(m.group(2)) <NEW_LINE> place_holder = self.markdown.htmlStash.store(rawhtml) <NEW_LINE> return place_holder <NEW_LINE> <DEDENT> def unescape(self, text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> stash = self.markdown.treeprocessors['inline'].stashed_nodes <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> def get_stash(m): <NEW_LINE> <INDENT> id = m.group(1) <NEW_LINE> value = stash.get(id) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.markdown.serializer(value) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return r'\%s' % value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text) | Store raw inline html and return a placeholder. | 6259905b76e4537e8c3f0b96 |
class ItemSample(pg.GraphicsWidget): <NEW_LINE> <INDENT> def __init__(self, item): <NEW_LINE> <INDENT> pg.GraphicsWidget.__init__(self) <NEW_LINE> self.item = item <NEW_LINE> <DEDENT> def boundingRect(self): <NEW_LINE> <INDENT> return QtCore.QRectF(0, 0, 20, 20) <NEW_LINE> <DEDENT> def paint(self, p, *args): <NEW_LINE> <INDENT> opts = self.item.opts <NEW_LINE> if opts.get('fillLevel',None) is not None and opts.get('fillBrush',None) is not None: <NEW_LINE> <INDENT> p.setBrush(fn.mkBrush(opts['fillBrush'])) <NEW_LINE> p.setPen(fn.mkPen(None)) <NEW_LINE> p.drawPolygon(QtGui.QPolygonF([QtCore.QPointF(2,18), QtCore.QPointF(18,2), QtCore.QPointF(18,18)])) <NEW_LINE> <DEDENT> if not isinstance(self.item, pg.ScatterPlotItem): <NEW_LINE> <INDENT> p.setPen(fn.mkPen(opts['pen'])) <NEW_LINE> p.drawLine(2, 18, 18, 2) <NEW_LINE> <DEDENT> symbol = opts.get('symbol', None) <NEW_LINE> if symbol is not None: <NEW_LINE> <INDENT> if isinstance(self.item, PlotDataItem): <NEW_LINE> <INDENT> opts = self.item.scatter.opts <NEW_LINE> <DEDENT> pen = fn.mkPen(opts['pen']) <NEW_LINE> brush = fn.mkBrush(opts['brush']) <NEW_LINE> size = opts['size'] <NEW_LINE> p.translate(10,10) <NEW_LINE> path = pg.drawSymbol(p, symbol, size, pen, brush) | Class responsible for drawing a single item in a LegendItem (sans label).
| 6259905ba17c0f6771d5d6a7 |
class Meta(object): <NEW_LINE> <INDENT> db_table = "zd_zookeeper" | 表配置信息
| 6259905b55399d3f05627b29 |
class MemberViews(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Member.objects.all() <NEW_LINE> serializer_class = MemberSerializer | Dynamic View for the model
Arguments:
viewsets {[type]} -- [description] | 6259905b56ac1b37e63037ec |
class Meta: <NEW_LINE> <INDENT> model = Contact <NEW_LINE> fields = ('name','email','message') | Meta definition for MODELNAMEform. | 6259905b4a966d76dd5f04fc |
class OpenStackSyncStep(SyncStep): <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> SyncStep.__init__(self, **args) <NEW_LINE> return <NEW_LINE> <DEDENT> def __call__(self, **args): <NEW_LINE> <INDENT> return self.call(**args) | PlanetStack Sync step for copying data to OpenStack
| 6259905ba79ad1619776b5c2 |
class VesselType(object): <NEW_LINE> <INDENT> def __init__(self, id, panda): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.panda = panda | VesselType.py is a | 6259905ba8ecb03325872821 |
class RequiredError(Exception): <NEW_LINE> <INDENT> pass | Raised when a required named argument is not passed. | 6259905b004d5f362081faf3 |
class set_ugi_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.LIST, 'success', (TType.STRING,None), None, ), (1, TType.STRUCT, 'o1', (MetaException, MetaException.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, o1=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.o1 = o1 <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.success = [] <NEW_LINE> (_etype711, _size708) = iprot.readListBegin() <NEW_LINE> for _i712 in xrange(_size708): <NEW_LINE> <INDENT> _elem713 = iprot.readString(); <NEW_LINE> self.success.append(_elem713) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.o1 = MetaException() <NEW_LINE> self.o1.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('set_ugi_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.LIST, 0) <NEW_LINE> oprot.writeListBegin(TType.STRING, len(self.success)) <NEW_LINE> for iter714 in self.success: <NEW_LINE> <INDENT> oprot.writeString(iter714) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.o1 is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('o1', TType.STRUCT, 1) <NEW_LINE> self.o1.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- o1 | 6259905b4e4d562566373a12 |
class BindEipAclsRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.EipIdAclIdList = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("EipIdAclIdList") is not None: <NEW_LINE> <INDENT> self.EipIdAclIdList = [] <NEW_LINE> for item in params.get("EipIdAclIdList"): <NEW_LINE> <INDENT> obj = EipAclMap() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.EipIdAclIdList.append(obj) <NEW_LINE> <DEDENT> <DEDENT> 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)) | BindEipAcls请求参数结构体
| 6259905b009cb60464d02b40 |
class Solution: <NEW_LINE> <INDENT> def isMatch(self, s: str, p: str) -> bool: <NEW_LINE> <INDENT> self.s, self.p, self.cache = s, p, {} <NEW_LINE> return self.matching(0, 0) <NEW_LINE> <DEDENT> def matching(self, i, j): <NEW_LINE> <INDENT> if (i, j) not in self.cache: <NEW_LINE> <INDENT> if j == len(self.p): <NEW_LINE> <INDENT> res = i == len(self.s) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if j + 1 < len(self.p) and self.p[j + 1] == '*': <NEW_LINE> <INDENT> res = self.matching(i, j + 2) or ( (bool(self.s[i:]) and (self.p[j] == '.' or self.s[i] == self.p[j])) and self.matching(i + 1, j)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = (bool(self.s[i:]) and (self.p[j] == '.' or self.s[i] == self.p[j])) and self.matching(i + 1, j + 1) <NEW_LINE> <DEDENT> <DEDENT> self.cache[(i, j)] = res <NEW_LINE> <DEDENT> return self.cache[i, j] | Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial). | 6259905b32920d7e50bc7651 |
class DataTrainer(): <NEW_LINE> <INDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self._data <NEW_LINE> <DEDENT> @data.setter <NEW_LINE> def data(self, value): <NEW_LINE> <INDENT> if value is not None and not isinstance(value, data.TimedPoints): <NEW_LINE> <INDENT> raise TypeError("data should be of class TimedPoints") <NEW_LINE> <DEDENT> self._data = value | Base class for most "trainers": classes which take data and "train"
themselves (fit a statistical model, etc.) to the data. Can also be used
as a base for classes which can directly return a "prediction". | 6259905b01c39578d7f1423c |
class CTMDiagnosticInfo(object): <NEW_LINE> <INDENT> def __init__(self, diaginfo_file='', tracerinfo_file=''): <NEW_LINE> <INDENT> self.categories = RecordList([], key_attr='name', ref_classes=CTMCategory) <NEW_LINE> self.diagnostics = RecordList([], key_attr='number', ref_classes=CTMDiagnostic) <NEW_LINE> if diaginfo_file is not None: <NEW_LINE> <INDENT> if not diaginfo_file: <NEW_LINE> <INDENT> diaginfo_file = os.path.join(config.PACKAGE_DATA_PATH, "diaginfo.dat") <NEW_LINE> <DEDENT> self.load_diaginfo(diaginfo_file) <NEW_LINE> <DEDENT> if tracerinfo_file is not None: <NEW_LINE> <INDENT> if not tracerinfo_file: <NEW_LINE> <INDENT> tracerinfo_file = os.path.join(config.PACKAGE_DATA_PATH, "tracerinfo.dat") <NEW_LINE> <DEDENT> self.load_tracerinfo(tracerinfo_file) <NEW_LINE> <DEDENT> <DEDENT> def load_diaginfo(self, filename, clear=True): <NEW_LINE> <INDENT> data = diaginfo.read_diaginfo(filename) <NEW_LINE> if clear: <NEW_LINE> <INDENT> del self.categories[:] <NEW_LINE> <DEDENT> self.categories.extend(CTMCategory(**d) for d in data) <NEW_LINE> <DEDENT> def load_tracerinfo(self, filename, clear=True): <NEW_LINE> <INDENT> data = diaginfo.read_tracerinfo(filename) <NEW_LINE> if clear: <NEW_LINE> <INDENT> del self.diagnostics[:] <NEW_LINE> <DEDENT> for d in data: <NEW_LINE> <INDENT> if d['carbon_weight'] != 1: <NEW_LINE> <INDENT> d['hydrocarbon'] = True <NEW_LINE> d['molecular_weight'] = config.C_MOLECULAR_WEIGHT <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d['hydrocarbon'] = False <NEW_LINE> <DEDENT> d['chemical'] = bool(d['molecular_weight']) <NEW_LINE> <DEDENT> self.diagnostics.extend(CTMDiagnostic(**d) for d in data) <NEW_LINE> <DEDENT> def save_diaginfo(self, filename): <NEW_LINE> <INDENT> raise NotYetImplementedError() <NEW_LINE> <DEDENT> def save_tracerinfo(self, filename): <NEW_LINE> <INDENT> raise NotYetImplementedError() | Define all the diagnostics (and its metadata) that one can archive
with GEOS-Chem.
An instance of this class is commonly related to a couple
of diaginfo.dat and tracerinfo.dat files. The class provides methods to
read/write information from/to these files.
Parameters
----------
diaginfo_file : string or None
path to the 'diaginfo.dat' file.
If None, no file read (no category added)
If empty string, the instance is created using a default
diaginfo.dat file - located in the data folder of the module
installation path)
tracerinfo_file : string or None
path to the 'tracerinfo.dat' file (or None or empty string). | 6259905badb09d7d5dc0bb75 |
class StatExtFlagsLinux(rdfvalue.RDFInteger): <NEW_LINE> <INDENT> data_store_type = "unsigned_integer_32" | Extended file attributes as reported by `lsattr`. | 6259905b2ae34c7f260ac6f2 |
class TransitionEnd(Baseevents): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Baseevents.__init__(self) <NEW_LINE> self.name = 'TransitionEnd' <NEW_LINE> self.datain['name'] = None <NEW_LINE> self.datain['type'] = None <NEW_LINE> self.datain['duration'] = None <NEW_LINE> self.datain['to-scene'] = None <NEW_LINE> <DEDENT> def getName(self): <NEW_LINE> <INDENT> return self.datain['name'] <NEW_LINE> <DEDENT> def getType(self): <NEW_LINE> <INDENT> return self.datain['type'] <NEW_LINE> <DEDENT> def getDuration(self): <NEW_LINE> <INDENT> return self.datain['duration'] <NEW_LINE> <DEDENT> def getToScene(self): <NEW_LINE> <INDENT> return self.datain['to-scene'] | A transition (other than "cut") has ended.
Please note that the `from-scene` field is not available in TransitionEnd.
:Returns:
*name*
type: String
Transition name.
*type*
type: String
Transition type.
*duration*
type: int
Transition duration (in milliseconds).
*to_scene*
type: String
Destination scene of the transition
| 6259905b3617ad0b5ee07756 |
class QuietReporter(base): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.verbosity = 0 <NEW_LINE> self.showlongtestinfo = False <NEW_LINE> self.showfspath = False | A py.test reporter that only shows dots when running tests. | 6259905b30dc7b76659a0d86 |
class Artifact(SkeleYaml): <NEW_LINE> <INDENT> schema = Schema({ 'name': And(str, error='Artifact \'name\' must be a String'), 'file': And(str, error='Artifact \'file\' must be a String'), }, ignore_extra_keys=True) <NEW_LINE> name = None <NEW_LINE> file = None <NEW_LINE> def __init__(self, name, file): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.file = file | Artifact Class
Object contained within a list of the artifactory configuration in order to specify the
artifact files and artifact names | 6259905b004d5f362081faf4 |
class CorsAffordanceSetMap(_coll.HereditaryWebResourcePathMapping): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CorsAffordanceSetMap, self).__init__(*args, valuetype=CorsAffordanceSet, **kwargs) | A cross-origin resource sharing affordances map
This is a mapping from resource locations to specifications of their
cross-origin request sharing affordances. In addition to the basic
mutable mapping functionality, it also
* accepts path patterns in the form of strings or regular
expressions and
* ensures that that its items have valid types and values.
.. seealso::
:class:`~bedframe._collections.HereditaryResourcePathMapping` | 6259905b32920d7e50bc7652 |
class CodeUnit(object): <NEW_LINE> <INDENT> def __init__(self, morf, file_locator): <NEW_LINE> <INDENT> self.file_locator = file_locator <NEW_LINE> if hasattr(morf, '__file__'): <NEW_LINE> <INDENT> f = morf.__file__ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f = morf <NEW_LINE> <DEDENT> if f.endswith('.pyc'): <NEW_LINE> <INDENT> f = f[:-1] <NEW_LINE> <DEDENT> self.filename = self.file_locator.canonical_filename(f) <NEW_LINE> if hasattr(morf, '__name__'): <NEW_LINE> <INDENT> n = modname = morf.__name__ <NEW_LINE> self.relative = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n = os.path.splitext(morf)[0] <NEW_LINE> rel = self.file_locator.relative_filename(n) <NEW_LINE> if os.path.isabs(n): <NEW_LINE> <INDENT> self.relative = (rel != n) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.relative = True <NEW_LINE> <DEDENT> n = rel <NEW_LINE> modname = None <NEW_LINE> <DEDENT> self.name = n <NEW_LINE> self.modname = modname <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<CodeUnit name=%r filename=%r>" % (self.name, self.filename) <NEW_LINE> <DEDENT> def __lt__(self, other): return self.name < other.name <NEW_LINE> def __le__(self, other): return self.name <= other.name <NEW_LINE> def __eq__(self, other): return self.name == other.name <NEW_LINE> def __ne__(self, other): return self.name != other.name <NEW_LINE> def __gt__(self, other): return self.name > other.name <NEW_LINE> def __ge__(self, other): return self.name >= other.name <NEW_LINE> def flat_rootname(self): <NEW_LINE> <INDENT> if self.modname: <NEW_LINE> <INDENT> return self.modname.replace('.', '_') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> root = os.path.splitdrive(self.name)[1] <NEW_LINE> return root.replace('\\', '_').replace('/', '_').replace('.', '_') <NEW_LINE> <DEDENT> <DEDENT> def source_file(self): <NEW_LINE> <INDENT> if os.path.exists(self.filename): <NEW_LINE> <INDENT> return open_source(self.filename) <NEW_LINE> <DEDENT> source = self.file_locator.get_zip_data(self.filename) <NEW_LINE> if source is not None: <NEW_LINE> <INDENT> return StringIO(source) <NEW_LINE> <DEDENT> raise CoverageException( "No source for code %r." % self.filename ) <NEW_LINE> <DEDENT> def should_be_python(self): <NEW_LINE> <INDENT> _, ext = os.path.splitext(self.filename) <NEW_LINE> if ext.startswith('.py'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if not ext: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Code unit: a filename or module.
Instance attributes:
`name` is a human-readable name for this code unit.
`filename` is the os path from which we can read the source.
`relative` is a boolean. | 6259905b8a43f66fc4bf379a |
class Links(object): <NEW_LINE> <INDENT> deserialized_types = { 'object_self': 'ask_smapi_model.v1.link.Link' } <NEW_LINE> attribute_map = { 'object_self': 'self' } <NEW_LINE> supports_multiple_types = False <NEW_LINE> def __init__(self, object_self=None): <NEW_LINE> <INDENT> self.__discriminator_value = None <NEW_LINE> self.object_self = object_self <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.deserialized_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x.value if isinstance(x, Enum) else x, value )) <NEW_LINE> <DEDENT> elif isinstance(value, Enum): <NEW_LINE> <INDENT> result[attr] = value.value <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else (item[0], item[1].value) if isinstance(item[1], Enum) else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Links): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | :param object_self:
:type object_self: (optional) ask_smapi_model.v1.link.Link | 6259905be5267d203ee6cec6 |
class RegressionResults(LikelihoodModelResults): <NEW_LINE> <INDENT> def __init__(self, theta, Y, model, wY, wresid, cov=None, dispersion=1., nuisance=None): <NEW_LINE> <INDENT> LikelihoodModelResults.__init__(self, theta, Y, model, cov, dispersion, nuisance) <NEW_LINE> self.wY = wY <NEW_LINE> self.wresid = wresid <NEW_LINE> <DEDENT> @setattr_on_read <NEW_LINE> def resid(self): <NEW_LINE> <INDENT> return self.Y - self.predicted <NEW_LINE> <DEDENT> @setattr_on_read <NEW_LINE> def norm_resid(self): <NEW_LINE> <INDENT> return self.resid * pos_recipr(np.sqrt(self.dispersion)) <NEW_LINE> <DEDENT> @setattr_on_read <NEW_LINE> def predicted(self): <NEW_LINE> <INDENT> beta = self.theta <NEW_LINE> X = self.model.design <NEW_LINE> return np.dot(X, beta) <NEW_LINE> <DEDENT> @setattr_on_read <NEW_LINE> def SSE(self): <NEW_LINE> <INDENT> return (self.wresid ** 2).sum(0) <NEW_LINE> <DEDENT> @setattr_on_read <NEW_LINE> def MSE(self): <NEW_LINE> <INDENT> return self.SSE / self.df_resid | This class summarizes the fit of a linear regression model.
It handles the output of contrasts, estimates of covariance, etc. | 6259905b91f36d47f2231995 |
class incorrectDeviation(Error): <NEW_LINE> <INDENT> pass | Raised when the input value is too large | 6259905be64d504609df9ed5 |
class OneToThree(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def transform(self, scale, note): <NEW_LINE> <INDENT> new_note = copy.deepcopy(note) <NEW_LINE> if new_note.isRest: <NEW_LINE> <INDENT> new_stream = music21.stream.Stream() <NEW_LINE> new_stream.append(new_note) <NEW_LINE> return new_stream <NEW_LINE> <DEDENT> possible_durations = [ [ 0.5, 0.25, 0.25 ], [ 0.25, 0.5, 0.25 ], [ 0.25, 0.25, 0.5 ] ] <NEW_LINE> possible_steps = [ "ascending", "descending" ] <NEW_LINE> chosen_dur = random.choice(possible_durations) <NEW_LINE> chosen_step = random.choice(possible_steps) <NEW_LINE> new_note.quarterLength = chosen_dur[0]*note.quarterLength <NEW_LINE> new_stream = music21.stream.Stream() <NEW_LINE> new_stream.append(new_note) <NEW_LINE> new_note2 = music21.note.Note() <NEW_LINE> next_pitch = scale.next(new_note.pitch, direction=chosen_step) <NEW_LINE> new_note2.pitch = next_pitch <NEW_LINE> new_note2.quarterLength = chosen_dur[1]*note.quarterLength <NEW_LINE> new_stream.append(new_note2) <NEW_LINE> new_note3 = copy.deepcopy(new_note) <NEW_LINE> new_note3.quarterLength = chosen_dur[2]*note.quarterLength <NEW_LINE> new_stream.append(new_note3) <NEW_LINE> return new_stream | transformation that randomly transforms one note into three notes
* total duration is kept
* first note and last note equal the original note
* middle note is the neighbour note | 6259905ba219f33f346c7e12 |
class ClientCredentials(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.client_users = {} <NEW_LINE> <DEDENT> def InitializeFromConfig(self): <NEW_LINE> <INDENT> usernames = config_lib.CONFIG.Get("Dataserver.client_credentials") <NEW_LINE> self.client_users = {} <NEW_LINE> for user_spec in usernames: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user, pwd, perm = user_spec.split(":", 2) <NEW_LINE> self.client_users[user] = data_server.DataServerClientInformation( username=user, password=pwd, permissions=perm) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise errors.DataServerError( "User %s from Dataserver.client_credentials is not" " a valid specification" % user_spec) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def Encrypt(self, username, password): <NEW_LINE> <INDENT> creds = data_server.DataServerClientCredentials( users=self.client_users.values()) <NEW_LINE> result = data_server.DataServerEncryptedCreds() <NEW_LINE> result.SetPayload(creds.SerializeToString(), username, password) <NEW_LINE> return result.SerializeToString() <NEW_LINE> <DEDENT> def InitializeFromEncryption(self, string, username, password): <NEW_LINE> <INDENT> creds_cls = data_server.DataServerEncryptedCreds <NEW_LINE> encrypted_creds = creds_cls.FromSerializedString(string) <NEW_LINE> payload = encrypted_creds.GetPayload(username, password) <NEW_LINE> creds = data_server.DataServerClientCredentials.FromSerializedString( payload) <NEW_LINE> self.client_users = {} <NEW_LINE> for client in creds.users: <NEW_LINE> <INDENT> self.client_users[client.username] = client <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def HasUser(self, username): <NEW_LINE> <INDENT> return username in self.client_users <NEW_LINE> <DEDENT> def GetPassword(self, username): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.client_users[username].password <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def GetPermissions(self, username): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.client_users[username].permissions <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None | Holds information about client usernames and passwords. | 6259905b442bda511e95d860 |
class LogDevicePlugin(PluginInterface): <NEW_LINE> <INDENT> def create_context(self): <NEW_LINE> <INDENT> return Context() <NEW_LINE> <DEDENT> def validate_args(self, args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_commands(self): <NEW_LINE> <INDENT> commands = [Connect(), SelectCommand()] <NEW_LINE> return commands <NEW_LINE> <DEDENT> def get_opts_parser(self, add_help=True): <NEW_LINE> <INDENT> epilog = ( "NOTES: LIST types are given as comma separated values, " "eg. a,b,c,d. DICT types are given as semicolon separated " "key:value pairs (or key=value), e.g., a:b;c:d and if a dict " "takes a list as value it look like a:1,2;b:1" ) <NEW_LINE> opts_parser = argparse.ArgumentParser( description="LogDevice Shell Utility", epilog=epilog, formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=add_help, ) <NEW_LINE> opts_parser.add_argument( "-c", "--config-path", type=str, help="Connect to a cluster using config file path", ) <NEW_LINE> admin = opts_parser.add_mutually_exclusive_group(required=False) <NEW_LINE> admin.add_argument( "-s", "--admin-server-host", type=str, help="The admin server host address" ) <NEW_LINE> admin.add_argument( "-u", "--admin-server-unix-path", type=str, help="The admin server unix socket address", ) <NEW_LINE> opts_parser.add_argument( "--admin-server-port", type=int, default=6440, help="The admin server port" ) <NEW_LINE> opts_parser.add_argument( "--verbose", action="count", default=0, help="Increase ldshell verbosity, can be specified multiple times", ) <NEW_LINE> opts_parser.add_argument( "--loglevel", type=str, dest="loglevel", default="warning", choices=["none", "debug", "info", "warning", "error", "critical"], help="Controls the logging level", ) <NEW_LINE> opts_parser.add_argument( "--stderr", action="store_true", help="By default the logging output goes to a " "temporary file. This disables this feature " "by sending the logging output to stderr", ) <NEW_LINE> opts_parser.add_argument( "--command-timeout", required=False, type=int, default=DEFAULT_COMMAND_TIMEOUT, help="Timeout for commands (default %ds)" % DEFAULT_COMMAND_TIMEOUT, ) <NEW_LINE> opts_parser.add_argument( "--yes", "-y", action="count", default=0, help="Say YES to all prompts. " "Use with caution.", ) <NEW_LINE> return opts_parser <NEW_LINE> <DEDENT> def create_usage_logger(self, context): <NEW_LINE> <INDENT> return None | The PluginInterface class is a way to customize ldshell for every customer
use case. It allowes custom argument validation, control over command
loading, custom context objects, and much more. | 6259905b460517430c432b59 |
class NetworkManagerMerger(BaseMerger): <NEW_LINE> <INDENT> KEY_NAME = "uuid" | Network manager setting merger class
Policy: Overwrite same key with new value, create new keys | 6259905b15baa7234946359f |
class EstimateSurface: <NEW_LINE> <INDENT> def __init__(self, training_points, training_dists, gamma, noise_sd): <NEW_LINE> <INDENT> self.K11_ = self.Covariance(training_points, gamma, noise_sd) <NEW_LINE> self.K11_inv_ = np.linalg.inv(self.K11_) <NEW_LINE> self.mu_training_ = np.asarray(training_dists) <NEW_LINE> self.mu_training_ = np.asmatrix(self.mu_training_).T <NEW_LINE> self.training_points_ = training_points <NEW_LINE> <DEDENT> def RBF(self, p1, p2, gamma): <NEW_LINE> <INDENT> return np.exp(-gamma * p1.SquaredDistanceTo(p2)) <NEW_LINE> <DEDENT> def Covariance(self, points, gamma, noise_sd=0.0): <NEW_LINE> <INDENT> K = np.zeros((len(points), len(points))) <NEW_LINE> for ii, p1 in enumerate(points): <NEW_LINE> <INDENT> for jj, p2 in enumerate(points): <NEW_LINE> <INDENT> K[ii, jj] = self.RBF(p1, p2, gamma) <NEW_LINE> <DEDENT> <DEDENT> return np.asmatrix(K + noise_sd*noise_sd*np.eye(len(points))) <NEW_LINE> <DEDENT> def CrossCovariance(self, points1, points2, gamma): <NEW_LINE> <INDENT> K = np.zeros((len(points1), len(points2))) <NEW_LINE> for ii, p1 in enumerate(points1): <NEW_LINE> <INDENT> for jj, p2 in enumerate(points2): <NEW_LINE> <INDENT> K[ii, jj] = self.RBF(p1, p2, gamma) <NEW_LINE> <DEDENT> <DEDENT> return np.asmatrix(K) <NEW_LINE> <DEDENT> def SignedDistance(self, query, gamma, noise_sd): <NEW_LINE> <INDENT> K22 = self.Covariance([query], gamma, noise_sd) <NEW_LINE> K12 = self.CrossCovariance(self.training_points_, [query], gamma) <NEW_LINE> K21 = K12.T <NEW_LINE> mu_query = K21 * self.K11_inv_ * self.mu_training_ <NEW_LINE> K_query = K22 - K21 * self.K11_inv_ * K12 <NEW_LINE> return (mu_query, K_query) <NEW_LINE> <DEDENT> def CovarianceToUncertainty(self, K): <NEW_LINE> <INDENT> uncertainty = [] <NEW_LINE> for ii in range(K.shape[0]): <NEW_LINE> <INDENT> uncertainty.append(K[ii, ii]) <NEW_LINE> <DEDENT> return uncertainty | Generate covariance matrices and compute conditional expectation
and covariance for signed distance function. | 6259905b10dbd63aa1c72181 |
class PlayStrategyException(Exception): <NEW_LINE> <INDENT> pass | Base exception. | 6259905bcc0a2c111447c5d5 |
class InitTest(unittest.TestCase): <NEW_LINE> <INDENT> def testForBooleanType(self): <NEW_LINE> <INDENT> richBool = rich_bool.RichBool(True) <NEW_LINE> self.assertEqual(richBool.value, True) <NEW_LINE> richBool = rich_bool.RichBool(False) <NEW_LINE> self.assertEqual(richBool.value, False) <NEW_LINE> <DEDENT> def testForNonBooleanType(self): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> richBool = rich_bool.RichBool(object()) <NEW_LINE> <DEDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> richBool = rich_bool.RichBool([]) <NEW_LINE> <DEDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> richBool = rich_bool.RichBool(1) <NEW_LINE> <DEDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> richBool = rich_bool.RichBool(object(), extra=True) | Unit tests for the constructor of RichBool class. | 6259905be76e3b2f99fda00c |
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE, TIME_ZONE_DISPLAYED_FOR_DEADLINES="UTC") <NEW_LINE> class BaseDueDateTests(ModuleStoreTestCase): <NEW_LINE> <INDENT> __test__ = False <NEW_LINE> def get_text(self, course): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_up_course(self, **course_kwargs): <NEW_LINE> <INDENT> course = CourseFactory.create(**course_kwargs) <NEW_LINE> chapter = ItemFactory.create(category='chapter', parent_location=course.location) <NEW_LINE> section = ItemFactory.create(category='sequential', parent_location=chapter.location, due=datetime(2013, 9, 18, 11, 30, 00)) <NEW_LINE> vertical = ItemFactory.create(category='vertical', parent_location=section.location) <NEW_LINE> ItemFactory.create(category='problem', parent_location=vertical.location) <NEW_LINE> course = modulestore().get_course(course.id) <NEW_LINE> self.assertIsNotNone(course.get_children()[0].get_children()[0].due) <NEW_LINE> return course <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.request_factory = RequestFactory() <NEW_LINE> self.user = UserFactory.create() <NEW_LINE> self.request = self.request_factory.get("foo") <NEW_LINE> self.request.user = self.user <NEW_LINE> self.time_with_tz = "due Sep 18, 2013 at 11:30 UTC" <NEW_LINE> self.time_without_tz = "due Sep 18, 2013 at 11:30" <NEW_LINE> <DEDENT> def test_backwards_compatability(self): <NEW_LINE> <INDENT> course = self.set_up_course(due_date_display_format=None, show_timezone=False) <NEW_LINE> text = self.get_text(course) <NEW_LINE> self.assertIn(self.time_without_tz, text) <NEW_LINE> self.assertNotIn(self.time_with_tz, text) <NEW_LINE> self.assertTrue(course.show_timezone) <NEW_LINE> <DEDENT> def test_defaults(self): <NEW_LINE> <INDENT> course = self.set_up_course() <NEW_LINE> text = self.get_text(course) <NEW_LINE> self.assertIn(self.time_with_tz, text) <NEW_LINE> <DEDENT> def test_format_none(self): <NEW_LINE> <INDENT> course = self.set_up_course(due_date_display_format=None) <NEW_LINE> text = self.get_text(course) <NEW_LINE> self.assertIn(self.time_with_tz, text) <NEW_LINE> <DEDENT> def test_format_plain_text(self): <NEW_LINE> <INDENT> course = self.set_up_course(due_date_display_format="foobar") <NEW_LINE> text = self.get_text(course) <NEW_LINE> self.assertNotIn(self.time_with_tz, text) <NEW_LINE> self.assertIn("due foobar", text) <NEW_LINE> <DEDENT> def test_format_date(self): <NEW_LINE> <INDENT> course = self.set_up_course(due_date_display_format=u"%b %d %y") <NEW_LINE> text = self.get_text(course) <NEW_LINE> self.assertNotIn(self.time_with_tz, text) <NEW_LINE> self.assertIn("due Sep 18 13", text) <NEW_LINE> <DEDENT> def test_format_hidden(self): <NEW_LINE> <INDENT> course = self.set_up_course(due_date_display_format=u"") <NEW_LINE> text = self.get_text(course) <NEW_LINE> self.assertNotIn("due ", text) <NEW_LINE> <DEDENT> def test_format_invalid(self): <NEW_LINE> <INDENT> course = self.set_up_course(due_date_display_format=u"%%%", show_timezone=False) <NEW_LINE> text = self.get_text(course) <NEW_LINE> self.assertNotIn("%%%", text) <NEW_LINE> self.assertIn(self.time_with_tz, text) | Base class that verifies that due dates are rendered correctly on a page | 6259905b2ae34c7f260ac6f4 |
class Error(Exception): <NEW_LINE> <INDENT> pass | Base class for fallback of all exceptions | 6259905b16aa5153ce401af1 |
class GcamError(PygcamException): <NEW_LINE> <INDENT> pass | The gcamWrapper detected and error and terminated the model run. | 6259905b24f1403a926863d5 |
class Events(Service): <NEW_LINE> <INDENT> def list_by_issue(self, number, user=None, repo=None): <NEW_LINE> <INDENT> request = self.make_request('issues.events.list_by_issue', user=user, repo=repo, number=number) <NEW_LINE> return self._get_result(request) <NEW_LINE> <DEDENT> def list_by_repo(self, user=None, repo=None): <NEW_LINE> <INDENT> request = self.make_request('issues.events.list_by_repo', user=user, repo=repo) <NEW_LINE> return self._get_result(request) <NEW_LINE> <DEDENT> def get(self, id, user=None, repo=None): <NEW_LINE> <INDENT> request = self.make_request('issues.events.get', user=user, repo=repo, id=id) <NEW_LINE> return self._get(request) | Consume `Events API
<http://developer.github.com/v3/issues/events>`_ | 6259905bbaa26c4b54d508b3 |
class EnvironmentFile(Exception): <NEW_LINE> <INDENT> def __init__(self, msg): <NEW_LINE> <INDENT> Exception.__init__(self, msg) | Exception raised when the Alignak environment file is missing or corrupted | 6259905b3eb6a72ae038bc6d |
class DefaultView(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> return redirect('/home') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return redirect('/login') | Default view for error conditions of GET / | 6259905b45492302aabfdae6 |
class Labeling: <NEW_LINE> <INDENT> def __init__(self, dist, threshold): <NEW_LINE> <INDENT> self.dist = dist <NEW_LINE> self.threshold = threshold <NEW_LINE> <DEDENT> def is_true(self, x, y): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return np.array([self.dist.pdf(ix, iy) > self.threshold for ix, iy in zip(x, y)], dtype='bool') <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return self.dist.pdf(x, y) > self.threshold | Noisy labeling function | 6259905b99cbb53fe68324ee |
class BaseFederationRow: <NEW_LINE> <INDENT> TypeId = "" <NEW_LINE> @staticmethod <NEW_LINE> def from_data(data: JsonDict) -> "BaseFederationRow": <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def to_data(self) -> JsonDict: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def add_to_buffer(self, buff: "ParsedFederationStreamData") -> None: <NEW_LINE> <INDENT> raise NotImplementedError() | Base class for rows to be sent in the federation stream.
Specifies how to identify, serialize and deserialize the different types. | 6259905bb5575c28eb7137d3 |
class ChallengeUser(Player): <NEW_LINE> <INDENT> last_launched = models.DateTimeField(blank=True, null=True) <NEW_LINE> def is_eligible(self): <NEW_LINE> <INDENT> return God.user_is_eligible(self, ChallengeGame) <NEW_LINE> <DEDENT> def can_launch(self): <NEW_LINE> <INDENT> now = datetime.now() <NEW_LINE> today_start = datetime.combine(now, time()) <NEW_LINE> today_end = datetime.combine(now, time(23, 59, 59)) <NEW_LINE> if not self.last_launched: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if today_start <= self.last_launched <= today_end: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.magic.has_modifier('challenge-cannot-challenge'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def has_enough_points(self): <NEW_LINE> <INDENT> REQ_POINTS = 30 <NEW_LINE> return self.points >= REQ_POINTS <NEW_LINE> <DEDENT> def can_challenge(self, user): <NEW_LINE> <INDENT> user = user.get_extension(ChallengeUser) <NEW_LINE> if self.user == user.user: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if user.magic.has_modifier('challenge-cannot-be-challenged'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return God.user_can_interact_with(self, user, game=ChallengeGame) <NEW_LINE> <DEDENT> def has_one_more(self): <NEW_LINE> <INDENT> return self.magic.has_modifier('challenge-one-more') <NEW_LINE> <DEDENT> def do_one_more(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> modifier = self.magic.use_modifier('challenge-one-more', 1) <NEW_LINE> <DEDENT> except InsufficientAmount: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.set_last_launched(None) <NEW_LINE> self.save() <NEW_LINE> signal_msg = ugettext_noop('used {artifact} to enable one more challenge.') <NEW_LINE> signals.addActivity.send(sender=None, user_from=self, user_to=self, message=signal_msg, arguments=dict(artifact=modifier.artifact.title), game=ChallengeGame.get_instance()) <NEW_LINE> return True <NEW_LINE> <DEDENT> def can_play(self, challenge): <NEW_LINE> <INDENT> return challenge.can_play(self) <NEW_LINE> <DEDENT> def launch_against(self, destination): <NEW_LINE> <INDENT> destination = destination.get_extension(ChallengeUser) <NEW_LINE> if destination.id == self.id: <NEW_LINE> <INDENT> raise ChallengeException('Cannot launch against myself') <NEW_LINE> <DEDENT> if not self.can_launch(): <NEW_LINE> <INDENT> raise ChallengeException('Player cannot launch') <NEW_LINE> <DEDENT> if not self.can_challenge(destination): <NEW_LINE> <INDENT> raise ChallengeException('Player cannot launch against this opponent') <NEW_LINE> <DEDENT> return Challenge.create(user_from=self, user_to=destination) <NEW_LINE> <DEDENT> def set_last_launched(self, value): <NEW_LINE> <INDENT> self.last_launched = value <NEW_LINE> self.save() <NEW_LINE> <DEDENT> def get_all_challenges(self): <NEW_LINE> <INDENT> chall_total = Challenge.objects.exclude(status=u'L').filter(Q(user_from__user=self) | Q(user_to__user=self)) <NEW_LINE> return chall_total <NEW_LINE> <DEDENT> def get_won_challenges(self): <NEW_LINE> <INDENT> return self.get_all_challenges().filter(winner=self) <NEW_LINE> <DEDENT> def get_lost_challenges(self): <NEW_LINE> <INDENT> return self.get_all_challenges().exclude(winner=self) | Extension of the userprofile, customized for challenge | 6259905bd99f1b3c44d06caf |
class LoginUserView(generic.View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> collect_provider_data() <NEW_LINE> continuation_url = request.GET.get("continuation_url", "/no-login-continuation/") <NEW_LINE> login_post_url = request.session.get("login_post_url", None) <NEW_LINE> login_done_url = request.session.get("login_done_url", None) <NEW_LINE> user_profile_url = request.session.get("user_profile_url", None) <NEW_LINE> help_dir = request.session.get("help_dir", None) <NEW_LINE> recent_userid = request.session.get("login_recent_userid", "") <NEW_LINE> if ( (login_post_url is None) or (login_done_url is None) or (user_profile_url is None) or (help_dir is None) ): <NEW_LINE> <INDENT> log.warning( "LoginUserView: missing details "+ "login_post_url %s, login_done_url %s, user_profile_url %s, help_dir %s"% (login_post_url, login_done_url, user_profile_url, help_dir) ) <NEW_LINE> return HttpResponseRedirect(continuation_url) <NEW_LINE> <DEDENT> default_provider = "" <NEW_LINE> provider_tuples = ( [ ( p.get('provider_order', 5), (k, p.get('provider_label', k), p.get('provider_image', None)) ) for k, p in PROVIDER_DETAILS.items() ]) <NEW_LINE> provider_labels = [ p[1] for p in sorted(provider_tuples) ] <NEW_LINE> for p in PROVIDER_DETAILS: <NEW_LINE> <INDENT> if "default" in PROVIDER_DETAILS[p]: <NEW_LINE> <INDENT> default_provider = PROVIDER_DETAILS[p]["default"] <NEW_LINE> <DEDENT> <DEDENT> logindata = ( { "login_post_url": login_post_url , "login_done_url": login_done_url , "user_profile_url": user_profile_url , "continuation_url": continuation_url , "provider_keys": list(PROVIDER_DETAILS) , "provider_labels": provider_labels , "provider": default_provider , "suppress_user": True , "help_filename": "login-help" , "userid": request.GET.get("userid", recent_userid) , "info_head": request.GET.get("info_head", None) , "info_message": request.GET.get("info_message", None) , "error_head": request.GET.get("error_head", None) , "error_message": request.GET.get("error_message", None) }) <NEW_LINE> if "help_filename" in logindata: <NEW_LINE> <INDENT> help_filepath = help_dir + "%(help_filename)s.md"%(logindata) <NEW_LINE> if os.path.isfile(help_filepath): <NEW_LINE> <INDENT> with open(help_filepath, "r") as helpfile: <NEW_LINE> <INDENT> logindata["help_markdown"] = helpfile.read() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if "help_markdown" in logindata: <NEW_LINE> <INDENT> logindata["help_text"] = markdown.markdown(logindata["help_markdown"]) <NEW_LINE> <DEDENT> template = loader.get_template("login.html") <NEW_LINE> return HttpResponse(template.render(logindata, request=self.request)) | View class to present login form to gather user id and other login information.
The login page solicits a user id and an identity provider
The login page supports the following request parameters:
continuation_url={uri}
- a URL for a page that is displayed when the login process is complete. | 6259905b4e4d562566373a15 |
class MonitorTask(Task): <NEW_LINE> <INDENT> def __init__(self, name, topic, msg_type, msg_cb, wait_for_message=True, timeout=5): <NEW_LINE> <INDENT> super(MonitorTask, self).__init__(name) <NEW_LINE> self.topic = topic <NEW_LINE> self.msg_type = msg_type <NEW_LINE> self.timeout = timeout <NEW_LINE> self.msg_cb = msg_cb <NEW_LINE> rospy.loginfo("Subscribing to topic " + topic) <NEW_LINE> if wait_for_message: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rospy.wait_for_message(topic, msg_type, timeout=self.timeout) <NEW_LINE> rospy.loginfo("Connected.") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> rospy.loginfo("Timed out waiting for " + topic) <NEW_LINE> <DEDENT> <DEDENT> rospy.Subscriber(self.topic, self.msg_type, self._msg_cb) <NEW_LINE> <DEDENT> def _msg_cb(self, msg): <NEW_LINE> <INDENT> self.set_status(self.msg_cb(msg)) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> return self.status <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> pass | Turn a ROS subscriber into a Task. | 6259905b32920d7e50bc7654 |
class MedianFilter(MovingWindowFilter): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> MovingWindowFilter.__init__(self, **kwargs) <NEW_LINE> <DEDENT> def filteredValue(self): <NEW_LINE> <INDENT> return np.median(self._filtering_buffer.getElements()) | Returns the median value of the moving window.
Length must be odd. | 6259905b4e4d562566373a16 |
@macro <NEW_LINE> class AScan(SoftwareScan): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.motors = [] <NEW_LINE> self.limits = [] <NEW_LINE> try: <NEW_LINE> <INDENT> exposuretime = float(args[-1]) <NEW_LINE> self.intervals = int(args[-2]) <NEW_LINE> super(AScan, self).__init__(exposuretime) <NEW_LINE> for i in range(int((len(args) - 2) / 3)): <NEW_LINE> <INDENT> self.motors.append(args[3*i]) <NEW_LINE> self.limits.append([float(m) for m in args[3*i+1:3*i+3]]) <NEW_LINE> <DEDENT> self.n_positions = self.intervals + 1 <NEW_LINE> assert all_are_motors(self.motors) <NEW_LINE> assert (len(args) - 2) % 3 == 0 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise MacroSyntaxError <NEW_LINE> <DEDENT> <DEDENT> def _generate_positions(self): <NEW_LINE> <INDENT> positions = [] <NEW_LINE> for i in range(len(self.motors)): <NEW_LINE> <INDENT> positions.append(np.linspace(self.limits[i][0], self.limits[i][1], self.intervals+1)) <NEW_LINE> <DEDENT> for i in range(len(positions[0])): <NEW_LINE> <INDENT> yield {m.name: pos[i] for (m, pos) in zip(self.motors, positions)} | Software scan one or more motors in parallel. ::
ascan <motor1> <start> <stop> ... <intervals> <exp_time> | 6259905be5267d203ee6cec7 |
class HomeView(LoginRequiredMixin, TemplateView): <NEW_LINE> <INDENT> template_name = "coding/coding.html" <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(HomeView, self).get_context_data(**kwargs) <NEW_LINE> return context | Home view. | 6259905b379a373c97d9a633 |
class Email(object): <NEW_LINE> <INDENT> EMAIL_HOST = values.Value('localhost') <NEW_LINE> EMAIL_PORT = values.IntegerValue(25) <NEW_LINE> EMAIL_USE_TLS = values.BooleanValue(True) <NEW_LINE> EMAIL_HOST_USER = values.Value('{{ cookiecutter.email }}') <NEW_LINE> EMAIL_HOST_PASSWORD = values.SecretValue() | Email settings for public projects. | 6259905b8da39b475be047f5 |
class ArithmeticExpression(poc_tree.Tree): <NEW_LINE> <INDENT> def __init__(self, value, children, parent=None): <NEW_LINE> <INDENT> poc_tree.Tree.__init__(self, value, children) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if len(self.children) == 0: <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> ans = "(" <NEW_LINE> ans += str(self.children[0]) <NEW_LINE> ans += str(self.value) <NEW_LINE> ans += str(self.children[1]) <NEW_LINE> ans += ")" <NEW_LINE> return ans <NEW_LINE> <DEDENT> def evaluate(self): <NEW_LINE> <INDENT> if len(self.children) == 0: <NEW_LINE> <INDENT> if "." in self.value: <NEW_LINE> <INDENT> return float(self.value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return int(self.value) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return OPERATORS[self.value](self.children[0].evaluate(), self.children[1].evaluate()) | Basic operations on arithmetic expressions | 6259905b097d151d1a2c267c |
class CrouzeixRaviart(finite_element.CiarletElement): <NEW_LINE> <INDENT> def __init__(self, cell, degree): <NEW_LINE> <INDENT> if not (degree == 1): <NEW_LINE> <INDENT> raise Exception("Crouzeix-Raviart only defined for degree 1") <NEW_LINE> <DEDENT> space = polynomial_set.ONPolynomialSet(cell, 1) <NEW_LINE> dual = CrouzeixRaviartDualSet(cell, 1) <NEW_LINE> super(CrouzeixRaviart, self).__init__(space, dual, 1) | The Crouzeix-Raviart finite element:
K: Triangle/Tetrahedron
Polynomial space: P_1
Dual basis: Evaluation at facet midpoints | 6259905b38b623060ffaa356 |
class SpotSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> image = Base64ImageField() <NEW_LINE> plan_id = serializers.PrimaryKeyRelatedField(queryset=Plan.objects.all(), read_only=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Spot <NEW_LINE> fields = ("pk", "name", "order", "lat", "lon", "note", "plan_id", "image", "created_at", "map_url") <NEW_LINE> list_serializer_class = SpotListSerializer <NEW_LINE> extra_kwargs = { 'map_url': {'read_only': True}, 'order': {'read_only': True}, } <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> plan = validated_data.pop('plan_id') <NEW_LINE> return Spot.objects.create(**validated_data, plan=plan) <NEW_LINE> <DEDENT> def to_representation(self, instance): <NEW_LINE> <INDENT> data = super(SpotSerializer, self).to_representation(instance) <NEW_LINE> if self.context['request'].version == 'v2': <NEW_LINE> <INDENT> data['created_at'] = int(instance.created_at.strftime('%s')) <NEW_LINE> <DEDENT> return data | 単一のSpotを処理するSerializer | 6259905bbaa26c4b54d508b4 |
class Database: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def connect_dbs(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cnn = mysql.connector.connect( user='root', password='utpadmin', host='localhost', database='utpWallet_Prod') <NEW_LINE> print("\nSYSTEM MESSAGE : MYSQL DATABASE CONNECTED\n") <NEW_LINE> return cnn <NEW_LINE> <DEDENT> except mysql.connector.Error as e: <NEW_LINE> <INDENT> if e.errno == errorcode.ER_ACCESS_DENIED_ERROR: <NEW_LINE> <INDENT> print("Something is wrong with username or Password") <NEW_LINE> <DEDENT> elif e.errno == errorcode.ER_BAD_DB_ERROR: <NEW_LINE> <INDENT> print("DataBase does not exist") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(e) | This class is used to initialize the connection to the MySQL Database | 6259905bd6c5a102081e3730 |
class Module(MixedModule): <NEW_LINE> <INDENT> interpleveldefs = { 'calcsize': 'interp_struct.calcsize', 'pack': 'interp_struct.pack', 'unpack': 'interp_struct.unpack', } <NEW_LINE> appleveldefs = { 'error': 'app_struct.error', 'pack_into': 'app_struct.pack_into', 'unpack_from': 'app_struct.unpack_from', 'Struct': 'app_struct.Struct', } | Functions to convert between Python values and C structs.
Python strings are used to hold the data representing the C struct
and also as format strings to describe the layout of data in the C struct.
The optional first format char indicates byte order, size and alignment:
@: native order, size & alignment (default)
=: native order, std. size & alignment
<: little-endian, std. size & alignment
>: big-endian, std. size & alignment
!: same as >
The remaining chars indicate types of args and must match exactly;
these can be preceded by a decimal repeat count:
x: pad byte (no data);
c:char;
b:signed byte;
B:unsigned byte;
h:short;
H:unsigned short;
i:int;
I:unsigned int;
l:long;
L:unsigned long;
q:long long;
Q:unsigned long long
f:float;
d:double.
Special cases (preceding decimal count indicates length):
s:string (array of char); p: pascal string (with count byte).
Special case (only available in native format):
P:an integer type that is wide enough to hold a pointer.
Whitespace between formats is ignored.
The variable struct.error is an exception raised on errors. | 6259905b99cbb53fe68324ef |
class Equalize(BaseOperation): <NEW_LINE> <INDENT> def apply_numpy(self, x: np.ndarray, value: float) -> np.ndarray: <NEW_LINE> <INDENT> return np.stack( [cv2.equalizeHist(x[:, :, i]) for i in range(x.shape[-1])], axis=-1 ) <NEW_LINE> <DEDENT> def apply_tensor(self, x: torch.Tensor, value: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> x = x.clone() <NEW_LINE> origins = (x.detach().cpu().numpy() * 0xFF).astype(np.uint8) <NEW_LINE> for i, j in itertools.product(range(x.size(0)), range(x.size(1))): <NEW_LINE> <INDENT> ratio = cv2.equalizeHist(origins[i, j]) / (origins[i, j] + 1e-6) <NEW_LINE> x[i, j] *= torch.tensor(ratio, dtype=x.dtype, device=x.device) <NEW_LINE> <DEDENT> return torch.clamp(x, 0, 1) | Equalize the image histogram.
+---------------+-------------+-----------+
| | Input Image | Magnitude |
+===============+=============+===========+
| Equalize | ✔ | ✘ |
+---------------+-------------+-----------+
This class equalize the image histogram. It makes the histogram uniformly by
applying non-linear mapping to the pixels.
Since the histogram equalization is not differentiable, we use a trick which is to
multiply the equalization ratio to the input image. Although the derivative of this
operation is not strict, it can prevent gradient interruption.
Note:
This class does not use the magnitude value. So you do not need to specify the
range of the magnitude. | 6259905b10dbd63aa1c72182 |
class LowLevelCommands(object): <NEW_LINE> <INDENT> dpkg_repack = "/usr/bin/dpkg-repack" <NEW_LINE> def install_debs(self, debfiles, targetdir): <NEW_LINE> <INDENT> if not debfiles: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> install_cmd = ["dpkg", "-i"] <NEW_LINE> if targetdir != "/": <NEW_LINE> <INDENT> install_cmd.insert(0, "chroot") <NEW_LINE> install_cmd.insert(1, targetdir) <NEW_LINE> <DEDENT> ret = subprocess.call(install_cmd + debfiles) <NEW_LINE> return (ret == 0) <NEW_LINE> <DEDENT> def repack_deb(self, pkgname, targetdir): <NEW_LINE> <INDENT> if not os.path.exists(self.dpkg_repack): <NEW_LINE> <INDENT> raise IOError("no '%s' found" % self.dpkg_repack) <NEW_LINE> <DEDENT> repack_cmd = [self.dpkg_repack] <NEW_LINE> if not os.getuid() == 0: <NEW_LINE> <INDENT> if not os.path.exists("/usr/bin/fakeroot"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> repack_cmd = ["fakeroot", "-u"] + repack_cmd <NEW_LINE> <DEDENT> ret = subprocess.call(repack_cmd + [pkgname], cwd=targetdir) <NEW_LINE> return (ret == 0) <NEW_LINE> <DEDENT> def debootstrap(self, targetdir, distro=None): <NEW_LINE> <INDENT> if distro is None: <NEW_LINE> <INDENT> distro = lsb_release.get_distro_information()['CODENAME'] <NEW_LINE> <DEDENT> ret = subprocess.call(["debootstrap", distro, targetdir]) <NEW_LINE> return (ret == 0) <NEW_LINE> <DEDENT> def merge_keys(self, fromkeyfile, intokeyfile): <NEW_LINE> <INDENT> ret = subprocess.call(['apt-key', '--keyring', intokeyfile, 'add', fromkeyfile]) <NEW_LINE> return (ret == 0) <NEW_LINE> <DEDENT> def bind_mount(self, olddir, newdir): <NEW_LINE> <INDENT> ret = subprocess.call(["mount", "--bind", olddir, newdir]) <NEW_LINE> return (ret == 0) <NEW_LINE> <DEDENT> def bind_umount(self, binddir): <NEW_LINE> <INDENT> ret = subprocess.call(["umount", binddir]) <NEW_LINE> return (ret == 0) | calls to the lowlevel operations to install debs
or repack a deb | 6259905badb09d7d5dc0bb79 |
class SimPyException(Exception): <NEW_LINE> <INDENT> pass | Base class for all SimPy specific exceptions. | 6259905b3617ad0b5ee0775a |
class PSpace(object): <NEW_LINE> <INDENT> class _NoValue: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __slots__ = ['_store_', '_address_'] <NEW_LINE> def __init__(self, store, address): <NEW_LINE> <INDENT> object.__setattr__(self, '_store_', store) <NEW_LINE> object.__setattr__(self, '_address_', str(address)) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> return descend(self, index) <NEW_LINE> <DEDENT> def __setitem__(self, index, input_data): <NEW_LINE> <INDENT> if isinstance(input_data, PSpace): <NEW_LINE> <INDENT> copy_from_space(descend(self, index), input_data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> set_value(descend(self, index), input_data) <NEW_LINE> <DEDENT> <DEDENT> def __delitem__(self, index): <NEW_LINE> <INDENT> delete(descend(self, index), max_depth=0) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return descend(self, name) <NEW_LINE> <DEDENT> def __setattr__(self, name, input_data): <NEW_LINE> <INDENT> if isinstance(input_data, PSpace): <NEW_LINE> <INDENT> copy_from_space(descend(self, name), input_data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> set_value(descend(self, name), input_data) <NEW_LINE> <DEDENT> <DEDENT> def __delattr__(self, name): <NEW_LINE> <INDENT> delete(descend(self, name), max_depth=0) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return walk(self) <NEW_LINE> <DEDENT> def __call__(self, value=_NoValue): <NEW_LINE> <INDENT> if value is PSpace._NoValue: <NEW_LINE> <INDENT> key_value = utility.generate_one_or_none(walk(self, max_depth=0)) <NEW_LINE> return key_value[1] if key_value else None <NEW_LINE> <DEDENT> if isinstance(value, PSpace): <NEW_LINE> <INDENT> copy_from_space(self, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> set_value(self, value) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return to_string(self) | Provide scoped access to property data given a base address.
To avoid conflicts with property pseudo-attribute names there are no public
attributes or methods. The only methods are the overloaded "[]", ".", "()",
and iteration operators. | 6259905b21a7993f00c6757c |
class UnixSocketTooLong(Exception): <NEW_LINE> <INDENT> pass | Exception raised when unixsocket path is too long. | 6259905b7047854f463409cf |
class Averager: <NEW_LINE> <INDENT> def __init__(self, columns): <NEW_LINE> <INDENT> self.number = 0 <NEW_LINE> self.columns = columns <NEW_LINE> self.total = [0 for i in range(self.columns)] <NEW_LINE> <DEDENT> def record_point(self, values): <NEW_LINE> <INDENT> self.number += 1 <NEW_LINE> for i in range(self.columns): <NEW_LINE> <INDENT> self.total[i] += values[i] <NEW_LINE> <DEDENT> <DEDENT> def averages(self, default): <NEW_LINE> <INDENT> if self.number == 0: <NEW_LINE> <INDENT> return [default for i in range(self.columns)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [self.total[i] / self.number for i in range(self.columns)] | For each couple (receiver, sender) we gather
a number of measurement points that must be averaged
this is done through an instance of this Averager class
all measurement points will contain one, two or three values
depending on the number of antennas
each measurement point is recorded, and at the end
averages returns the right value(s) | 6259905ba17c0f6771d5d6aa |
class Spatial(BaseSimuran): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.timestamps = None <NEW_LINE> self.position = None <NEW_LINE> self.sampling_rate = None <NEW_LINE> self.speed = None <NEW_LINE> self.direction = None <NEW_LINE> self.source_file = "<unknown>" <NEW_LINE> <DEDENT> def load(self, *args, **kwargs): <NEW_LINE> <INDENT> super().load() <NEW_LINE> if not self.loaded(): <NEW_LINE> <INDENT> load_result = self.loader.load_spatial(self.source_file, **kwargs) <NEW_LINE> self.save_attrs(load_result) <NEW_LINE> self.last_loaded_source = self.source_file | Hold spatial information.
Attributes
----------
timestamps : array style object
The timestamps of the spatial sampling
positions : tuple of array style object
The value of the spatial at sample points.
Stored as (x_array, y_array) in cm units
speed : array style object
The speed in cm / s for each time point
direction : array style object
The head direction in degrees.
sampling_rate : int
The sampling rate of the signal in Hz
source_file : str
The path to a source file containing the spatial data. | 6259905b4a966d76dd5f0502 |
class CheckboxTextProblemTypeTest(ChoiceTextProbelmTypeTestBase, ProblemTypeTestMixin): <NEW_LINE> <INDENT> problem_name = 'CHECKBOX TEXT TEST PROBLEM' <NEW_LINE> problem_type = 'checkbox_text' <NEW_LINE> choice_type = 'checkbox' <NEW_LINE> factory = ChoiceTextResponseXMLFactory() <NEW_LINE> factory_kwargs = { 'question_text': 'The correct answer is Choice 0 and input 8', 'type': 'checkboxtextgroup', 'choices': [ ("true", {"answer": "8", "tolerance": "1"}), ("false", {"answer": "8", "tolerance": "1"}), ], } <NEW_LINE> def setUp(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CheckboxTextProblemTypeTest, self).setUp(*args, **kwargs) <NEW_LINE> self.problem_page.a11y_audit.config.set_rules({ 'ignore': [ 'section', 'label', 'checkboxgroup', ] }) | TestCase Class for Checkbox Text Problem Type | 6259905b30dc7b76659a0d88 |
class itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2(itkImageToImageMetricPython.itkImageToImageMetricIF2IF2): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkMeanReciprocalSquareDifferenceImageToImageMetricPython.itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def GetLambda(self): <NEW_LINE> <INDENT> return _itkMeanReciprocalSquareDifferenceImageToImageMetricPython.itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2_GetLambda(self) <NEW_LINE> <DEDENT> def SetLambda(self, *args): <NEW_LINE> <INDENT> return _itkMeanReciprocalSquareDifferenceImageToImageMetricPython.itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2_SetLambda(self, *args) <NEW_LINE> <DEDENT> def GetDelta(self): <NEW_LINE> <INDENT> return _itkMeanReciprocalSquareDifferenceImageToImageMetricPython.itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2_GetDelta(self) <NEW_LINE> <DEDENT> def SetDelta(self, *args): <NEW_LINE> <INDENT> return _itkMeanReciprocalSquareDifferenceImageToImageMetricPython.itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2_SetDelta(self, *args) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkMeanReciprocalSquareDifferenceImageToImageMetricPython.delete_itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkMeanReciprocalSquareDifferenceImageToImageMetricPython.itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkMeanReciprocalSquareDifferenceImageToImageMetricPython.itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New) | Proxy of C++ itkMeanReciprocalSquareDifferenceImageToImageMetricIF2IF2 class | 6259905b2ae34c7f260ac6f7 |
class ProductionConfig(BaseConfig): <NEW_LINE> <INDENT> pass | 生产环境 | 6259905b32920d7e50bc7656 |
class RequirementsNotFound(OpenPeerPowerError): <NEW_LINE> <INDENT> def __init__(self, domain: str, requirements: List) -> None: <NEW_LINE> <INDENT> super().__init__(f"Requirements for {domain} not found: {requirements}.") <NEW_LINE> self.domain = domain <NEW_LINE> self.requirements = requirements | Raised when a component is not found. | 6259905bb57a9660fecd308b |
class QuestAction(DialogueAction): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> DialogueAction.__init__(self, *args, **kwargs) <NEW_LINE> self.quest_id = kwargs['quest'] if 'quest' in kwargs else args[0] | Abstract base class for quest-related L{DialogueActions<DialogueAction>}. | 6259905b91f36d47f2231997 |
class ExceptionStackContext(object): <NEW_LINE> <INDENT> def __init__(self, exception_handler, delay_warning=False): <NEW_LINE> <INDENT> self.delay_warning = delay_warning <NEW_LINE> if not self.delay_warning: <NEW_LINE> <INDENT> warnings.warn( "StackContext is deprecated and will be removed in Tornado 6.0", DeprecationWarning) <NEW_LINE> <DEDENT> self.exception_handler = exception_handler <NEW_LINE> self.active = True <NEW_LINE> <DEDENT> def _deactivate(self): <NEW_LINE> <INDENT> self.active = False <NEW_LINE> <DEDENT> def exit(self, type, value, traceback): <NEW_LINE> <INDENT> if type is not None: <NEW_LINE> <INDENT> if self.delay_warning: <NEW_LINE> <INDENT> warnings.warn( "StackContext is deprecated and will be removed in Tornado 6.0", DeprecationWarning) <NEW_LINE> <DEDENT> return self.exception_handler(type, value, traceback) <NEW_LINE> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.old_contexts = _state.contexts <NEW_LINE> self.new_contexts = (self.old_contexts[0], self) <NEW_LINE> _state.contexts = self.new_contexts <NEW_LINE> return self._deactivate <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if type is not None: <NEW_LINE> <INDENT> return self.exception_handler(type, value, traceback) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> final_contexts = _state.contexts <NEW_LINE> _state.contexts = self.old_contexts <NEW_LINE> if final_contexts is not self.new_contexts: <NEW_LINE> <INDENT> raise StackContextInconsistentError( 'stack_context inconsistency (may be caused by yield ' 'within a "with StackContext" block)') <NEW_LINE> <DEDENT> self.new_contexts = None | Specialization of StackContext for exception handling.
The supplied ``exception_handler`` function will be called in the
event of an uncaught exception in this context. The semantics are
similar to a try/finally clause, and intended use cases are to log
an error, close a socket, or similar cleanup actions. The
``exc_info`` triple ``(type, value, traceback)`` will be passed to the
exception_handler function.
If the exception handler returns true, the exception will be
consumed and will not be propagated to other exception handlers.
.. versionadded:: 5.1
The ``delay_warning`` argument can be used to delay the emission
of DeprecationWarnings until an exception is caught by the
``ExceptionStackContext``, which facilitates certain transitional
use cases. | 6259905b8da39b475be047f7 |
class BeamSearch(object): <NEW_LINE> <INDENT> def __init__(self, model, beam_size, start_token, end_token, max_steps): <NEW_LINE> <INDENT> self._model = model <NEW_LINE> self._beam_size = beam_size <NEW_LINE> self._start_token = start_token <NEW_LINE> self._end_token = end_token <NEW_LINE> self._max_steps = max_steps <NEW_LINE> <DEDENT> def BeamSearch(self, sess, enc_inputs, enc_seqlen): <NEW_LINE> <INDENT> enc_top_states, dec_in_state = self._model.encode_top_state( sess, enc_inputs, enc_seqlen) <NEW_LINE> hyps = [Hypothesis([self._start_token], 0.0, dec_in_state) ] * self._beam_size <NEW_LINE> results = [] <NEW_LINE> steps = 0 <NEW_LINE> while steps < self._max_steps and len(results) < self._beam_size: <NEW_LINE> <INDENT> latest_tokens = [h.latest_token for h in hyps] <NEW_LINE> states = [h.state for h in hyps] <NEW_LINE> topk_ids, topk_log_probs, new_states = self._model.decode_topk( sess, latest_tokens, enc_top_states, states) <NEW_LINE> all_hyps = [] <NEW_LINE> num_beam_source = 1 if steps == 0 else len(hyps) <NEW_LINE> for i in xrange(num_beam_source): <NEW_LINE> <INDENT> h, ns = hyps[i], new_states[i] <NEW_LINE> for j in xrange(self._beam_size*2): <NEW_LINE> <INDENT> all_hyps.append(h.Extend(topk_ids[i, j], topk_log_probs[i, j], ns)) <NEW_LINE> <DEDENT> <DEDENT> hyps = [] <NEW_LINE> for h in self._BestHyps(all_hyps): <NEW_LINE> <INDENT> if h.latest_token == self._end_token: <NEW_LINE> <INDENT> results.append(h) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hyps.append(h) <NEW_LINE> <DEDENT> if len(hyps) == self._beam_size or len(results) == self._beam_size: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> steps += 1 <NEW_LINE> <DEDENT> if steps == self._max_steps: <NEW_LINE> <INDENT> results.extend(hyps) <NEW_LINE> <DEDENT> return self._BestHyps(results) <NEW_LINE> <DEDENT> def _BestHyps(self, hyps): <NEW_LINE> <INDENT> if FLAGS.normalize_by_length: <NEW_LINE> <INDENT> return sorted(hyps, key=lambda h: h.log_prob/len(h.tokens), reverse=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return sorted(hyps, key=lambda h: h.log_prob, reverse=True) | Beam search. | 6259905c498bea3a75a59105 |
class PulseCounter(GEMSensor): <NEW_LINE> <INDENT> def __init__( self, monitor_serial_number, number, name, counted_quantity, time_unit, counted_quantity_per_pulse, ): <NEW_LINE> <INDENT> super().__init__(monitor_serial_number, name, "pulse", number) <NEW_LINE> self._counted_quantity = counted_quantity <NEW_LINE> self._counted_quantity_per_pulse = counted_quantity_per_pulse <NEW_LINE> self._time_unit = time_unit <NEW_LINE> <DEDENT> def _get_sensor(self, monitor): <NEW_LINE> <INDENT> return monitor.pulse_counters[self._number - 1] <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return COUNTER_ICON <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> if not self._sensor or self._sensor.pulses_per_second is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return ( self._sensor.pulses_per_second * self._counted_quantity_per_pulse * self._seconds_per_time_unit ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _seconds_per_time_unit(self): <NEW_LINE> <INDENT> if self._time_unit == TIME_SECONDS: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if self._time_unit == TIME_MINUTES: <NEW_LINE> <INDENT> return 60 <NEW_LINE> <DEDENT> if self._time_unit == TIME_HOURS: <NEW_LINE> <INDENT> return 3600 <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return f"{self._counted_quantity}/{self._time_unit}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> if not self._sensor: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return {DATA_PULSES: self._sensor.pulses} | Entity showing rate of change in one pulse counter of the monitor. | 6259905c8e7ae83300eea69e |
class CapsType(object): <NEW_LINE> <INDENT> CAPSTYPE_GENERAL = 0x0001 <NEW_LINE> CAPSTYPE_BITMAP = 0x0002 <NEW_LINE> CAPSTYPE_ORDER = 0x0003 <NEW_LINE> CAPSTYPE_BITMAPCACHE = 0x0004 <NEW_LINE> CAPSTYPE_CONTROL = 0x0005 <NEW_LINE> CAPSTYPE_ACTIVATION = 0x0007 <NEW_LINE> CAPSTYPE_POINTER = 0x0008 <NEW_LINE> CAPSTYPE_SHARE = 0x0009 <NEW_LINE> CAPSTYPE_COLORCACHE = 0x000A <NEW_LINE> CAPSTYPE_SOUND = 0x000C <NEW_LINE> CAPSTYPE_INPUT = 0x000D <NEW_LINE> CAPSTYPE_FONT = 0x000E <NEW_LINE> CAPSTYPE_BRUSH = 0x000F <NEW_LINE> CAPSTYPE_GLYPHCACHE = 0x0010 <NEW_LINE> CAPSTYPE_OFFSCREENCACHE = 0x0011 <NEW_LINE> CAPSTYPE_BITMAPCACHE_HOSTSUPPORT = 0x0012 <NEW_LINE> CAPSTYPE_BITMAPCACHE_REV2 = 0x0013 <NEW_LINE> CAPSTYPE_VIRTUALCHANNEL = 0x0014 <NEW_LINE> CAPSTYPE_DRAWNINEGRIDCACHE = 0x0015 <NEW_LINE> CAPSTYPE_DRAWGDIPLUS = 0x0016 <NEW_LINE> CAPSTYPE_RAIL = 0x0017 <NEW_LINE> CAPSTYPE_WINDOW = 0x0018 <NEW_LINE> CAPSETTYPE_COMPDESK = 0x0019 <NEW_LINE> CAPSETTYPE_MULTIFRAGMENTUPDATE = 0x001A <NEW_LINE> CAPSETTYPE_LARGE_POINTER = 0x001B <NEW_LINE> CAPSETTYPE_SURFACE_COMMANDS = 0x001C <NEW_LINE> CAPSETTYPE_BITMAP_CODECS = 0x001D <NEW_LINE> CAPSSETTYPE_FRAME_ACKNOWLEDGE = 0x001E | Different type of capabilities
@see: http://msdn.microsoft.com/en-us/library/cc240486.aspx | 6259905c01c39578d7f1423f |
class TestTerminal(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> print("Preparando contexto para " + self.__class__.__name__) <NEW_LINE> self.terminal = Terminal() <NEW_LINE> self.sesion_tec = Sesion("10025580R", "TecnicoCalidad") <NEW_LINE> self.sesion_doc = Sesion("49251223B", "Docente") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> print("Destruyendo contexto para " + self.__class__.__name__) <NEW_LINE> del self.terminal <NEW_LINE> del self.sesion_tec <NEW_LINE> del self.sesion_doc <NEW_LINE> <DEDENT> def test_set_alumno_controller(self): <NEW_LINE> <INDENT> self.terminal.set_alumno_controller("Controlador") <NEW_LINE> self.assertEquals(self.terminal.get_alumno_controller(), "Controlador") <NEW_LINE> <DEDENT> def test_set_asignatura_controller(self): <NEW_LINE> <INDENT> self.terminal.set_asignatura_controller("Controlador") <NEW_LINE> self.assertEquals(self.terminal.get_asignatura_controller(), "Controlador") <NEW_LINE> <DEDENT> def test_set_centro_controller(self): <NEW_LINE> <INDENT> self.terminal.set_centro_controller("Controlador") <NEW_LINE> self.assertEquals(self.terminal.get_centro_controller(), "Controlador") <NEW_LINE> <DEDENT> def test_set_grado_controller(self): <NEW_LINE> <INDENT> self.terminal.set_grado_controller("Controlador") <NEW_LINE> self.assertEquals(self.terminal.get_grado_controller(), "Controlador") <NEW_LINE> <DEDENT> def test_set_sesion_controller(self): <NEW_LINE> <INDENT> self.terminal.set_sesion_controller("Controlador") <NEW_LINE> self.assertEquals(self.terminal.get_sesion_controller(), "Controlador") <NEW_LINE> <DEDENT> def test_set_sesion(self): <NEW_LINE> <INDENT> self.terminal.set_sesion(self.sesion_doc) <NEW_LINE> self.assertEquals(self.terminal.get_sesion(), self.sesion_doc) | Esta clase corresponde al caso de prueba de src.Terminal.
En ella solo se prueban aquellos métodos que no requieren de la interaccion del usuario. | 6259905cd6c5a102081e3732 |
class SparseGPRegression(SparseGP_MPI): <NEW_LINE> <INDENT> def __init__(self, X, Y, kernel=None, Z=None, num_inducing=10, X_variance=None, mean_function=None, normalizer=None, mpi_comm=None, name='sparse_gp'): <NEW_LINE> <INDENT> num_data, input_dim = X.shape <NEW_LINE> if kernel is None: <NEW_LINE> <INDENT> kernel = kern.RBF(input_dim) <NEW_LINE> <DEDENT> if Z is None: <NEW_LINE> <INDENT> i = np.random.permutation(num_data)[:min(num_inducing, num_data)] <NEW_LINE> Z = X.view(np.ndarray)[i].copy() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert Z.shape[1] == input_dim <NEW_LINE> <DEDENT> likelihood = likelihoods.Gaussian() <NEW_LINE> if not (X_variance is None): <NEW_LINE> <INDENT> X = NormalPosterior(X,X_variance) <NEW_LINE> <DEDENT> if mpi_comm is not None: <NEW_LINE> <INDENT> from ..inference.latent_function_inference.var_dtc_parallel import VarDTC_minibatch <NEW_LINE> infr = VarDTC_minibatch(mpi_comm=mpi_comm) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> infr = VarDTC() <NEW_LINE> <DEDENT> SparseGP_MPI.__init__(self, X, Y, Z, kernel, likelihood, mean_function=mean_function, inference_method=infr, normalizer=normalizer, mpi_comm=mpi_comm, name=name) <NEW_LINE> <DEDENT> def parameters_changed(self): <NEW_LINE> <INDENT> from ..inference.latent_function_inference.var_dtc_parallel import update_gradients_sparsegp,VarDTC_minibatch <NEW_LINE> if isinstance(self.inference_method,VarDTC_minibatch): <NEW_LINE> <INDENT> update_gradients_sparsegp(self, mpi_comm=self.mpi_comm) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(SparseGPRegression, self).parameters_changed() | Gaussian Process model for regression
This is a thin wrapper around the SparseGP class, with a set of sensible defalts
:param X: input observations
:param X_variance: input uncertainties, one per input X
:param Y: observed values
:param kernel: a GPy kernel, defaults to rbf+white
:param Z: inducing inputs (optional, see note)
:type Z: np.ndarray (num_inducing x input_dim) | None
:param num_inducing: number of inducing points (ignored if Z is passed, see note)
:type num_inducing: int
:rtype: model object
.. Note:: If no Z array is passed, num_inducing (default 10) points are selected from the data. Other wise num_inducing is ignored
.. Note:: Multiple independent outputs are allowed using columns of Y | 6259905c99cbb53fe68324f1 |
class Batch(BaseClient): <NEW_LINE> <INDENT> def __init__(self, transport, namespace): <NEW_LINE> <INDENT> self.transport = BufferedTransport(transport) <NEW_LINE> self.namespace = namespace <NEW_LINE> self.counters = {} <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, value, traceback): <NEW_LINE> <INDENT> self.flush() <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> for name, counter in self.counters.items(): <NEW_LINE> <INDENT> counter.send() <NEW_LINE> <DEDENT> self.transport.flush() <NEW_LINE> <DEDENT> def counter(self, name): <NEW_LINE> <INDENT> counter_name = _metric_join(self.namespace, name.encode("ascii")) <NEW_LINE> batch_counter = self.counters.get(counter_name) <NEW_LINE> if batch_counter is None: <NEW_LINE> <INDENT> batch_counter = BatchCounter(self.transport, counter_name) <NEW_LINE> self.counters[counter_name] = batch_counter <NEW_LINE> <DEDENT> return batch_counter | A batch of metrics to send to statsd.
The batch also supports the `context manager protocol`_, for use with
Python's ``with`` statement. When the context is exited, the batch will
automatically :py:meth:`flush`.
.. _context manager protocol:
https://docs.python.org/3/reference/datamodel.html#context-managers | 6259905cd268445f2663a665 |
class State(DashDependency): <NEW_LINE> <INDENT> allowed_wildcards = (MATCH, ALL, ALLSMALLER) | Use the value of a State in a callback but don't trigger updates. | 6259905c1f037a2d8b9e5374 |
class DiskIndependenceMode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> PERSISTENT = "persistent" <NEW_LINE> INDEPENDENT_PERSISTENT = "independent_persistent" <NEW_LINE> INDEPENDENT_NONPERSISTENT = "independent_nonpersistent" | Disk's independence mode type
| 6259905ca8ecb03325872829 |
class BiosVfLegacyUSBSupport(ManagedObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> ManagedObject.__init__(self, "BiosVfLegacyUSBSupport") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def class_id(): <NEW_LINE> <INDENT> return "biosVfLegacyUSBSupport" <NEW_LINE> <DEDENT> DN = "Dn" <NEW_LINE> RN = "Rn" <NEW_LINE> STATUS = "Status" <NEW_LINE> VP_LEGACY_USBSUPPORT = "VpLegacyUSBSupport" <NEW_LINE> CONST_VP_LEGACY_USBSUPPORT_AUTO = "Auto" <NEW_LINE> CONST_VP_LEGACY_USBSUPPORT_DISABLED = "Disabled" <NEW_LINE> CONST_VP_LEGACY_USBSUPPORT_ENABLED = "Enabled" <NEW_LINE> CONST__VP_LEGACY_USBSUPPORT_AUTO = "auto" <NEW_LINE> CONST__VP_LEGACY_USBSUPPORT_DISABLED = "disabled" <NEW_LINE> CONST__VP_LEGACY_USBSUPPORT_ENABLED = "enabled" <NEW_LINE> CONST_VP_LEGACY_USBSUPPORT_PLATFORM_DEFAULT = "platform-default" | This class contains the relevant properties and constant supported by this MO. | 6259905cdd821e528d6da489 |
class BrokerRabbitMQ: <NEW_LINE> <INDENT> def __init__(self, app=None): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.connection_handler = None <NEW_LINE> self.producer = None <NEW_LINE> self.url = None <NEW_LINE> self.exchange_name = None <NEW_LINE> self.application_id = None <NEW_LINE> self.delivery_mode = None <NEW_LINE> self.queues = None <NEW_LINE> self.on_message_callback = None <NEW_LINE> <DEDENT> def init_app(self, app, queues, on_message_callback): <NEW_LINE> <INDENT> self.url = app.config.get('RABBIT_MQ_URL', DEFAULT_URL) <NEW_LINE> self.exchange_name = app.config.get('EXCHANGE_NAME', DEFAULT_EXCHANGE) <NEW_LINE> self.application_id = app.config.get('APPLICATION_ID', DEFAULT_APP) <NEW_LINE> self.delivery_mode = app.config.get('DELIVERY_MODE', DEFAULT_DELIVERY) <NEW_LINE> self.queues = queues <NEW_LINE> self.on_message_callback = on_message_callback <NEW_LINE> self.connection_handler = ConnectionHandler(self.url) <NEW_LINE> connection = self.connection_handler.get_current_connection() <NEW_LINE> channel = ProducerChannel(connection, self.application_id, self.delivery_mode) <NEW_LINE> self.producer = Producer(channel, self.exchange_name) <NEW_LINE> self.producer.bootstrap(self.queues) <NEW_LINE> <DEDENT> def send(self, queue, context={}): <NEW_LINE> <INDENT> if queue not in self.queues: <NEW_LINE> <INDENT> error_msg = f'Queue ‘{queue}‘ is not registered' <NEW_LINE> raise UnknownQueueError(error_msg) <NEW_LINE> <DEDENT> message = { 'created_at': datetime.utcnow().isoformat(), 'queue': queue, 'context': context } <NEW_LINE> return self.producer.publish(queue, message) <NEW_LINE> <DEDENT> def list_queues(self): <NEW_LINE> <INDENT> for queue in self.queues: <NEW_LINE> <INDENT> print('Queue name : `%s`' % queue) <NEW_LINE> <DEDENT> <DEDENT> def start(self, queue): <NEW_LINE> <INDENT> if queue not in self.queues: <NEW_LINE> <INDENT> raise RuntimeError(f'Queue with name`{queue}` not found') <NEW_LINE> <DEDENT> worker = Worker(connection_handler=self.connection_handler, message_callback=self.on_message_callback, queue=queue) <NEW_LINE> print(f'Start consuming message on the queue `{queue}`') <NEW_LINE> worker.consume_message() | Message Broker based on RabbitMQ middleware | 6259905c0c0af96317c57868 |
class FunctionClassMember: <NEW_LINE> <INDENT> def __init__(self, type, name, attribute=None, default_value=None): <NEW_LINE> <INDENT> self.type = type <NEW_LINE> self.name = name <NEW_LINE> self.attribute = attribute <NEW_LINE> self.default_value = default_value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"<FunctionClassMember(type={self.type}, name={self.name}, attribute={self.attribute}, default_value={self.default_value})>" <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() | AST node representing getter function in a class definition.
Can optionally have a version attribute and a default value specified.
Getter functions should be used whenever it's needed to access private
members of a class. | 6259905cfff4ab517ebcee37 |
class Region(Base): <NEW_LINE> <INDENT> name = models.CharField(max_length=200, db_index=True) <NEW_LINE> display_name = models.CharField(max_length=200) <NEW_LINE> geoname_code = models.CharField(max_length=50, null=True, blank=True, db_index=True) <NEW_LINE> country = models.ForeignKey(Country) <NEW_LINE> class Meta(Base.Meta): <NEW_LINE> <INDENT> unique_together = (('country', 'name', 'deleted'), ('country', 'slug', 'deleted')) <NEW_LINE> verbose_name = _('region/state') <NEW_LINE> verbose_name_plural = _('regions/states') <NEW_LINE> <DEDENT> def get_display_name(self): <NEW_LINE> <INDENT> return '%s' % (self.name) | Region/State model. | 6259905c379a373c97d9a637 |
class Household(HouseholdIdentifierModelMixin, SearchSlugModelMixin, BaseUuidModel): <NEW_LINE> <INDENT> plot = models.ForeignKey(Plot, on_delete=models.PROTECT) <NEW_LINE> report_datetime = models.DateTimeField( verbose_name='Report Date/Time', default=get_utcnow) <NEW_LINE> comment = EncryptedTextField( max_length=250, help_text="You may provide a comment here or leave BLANK.", blank=True, null=True) <NEW_LINE> enrolled = models.BooleanField( default=False, editable=False, help_text=('Set to true if one member is consented. ' 'Updated by Household_structure post_save.')) <NEW_LINE> enrolled_datetime = models.DateTimeField( null=True, editable=False, help_text=('datetime that household is enrolled. ' 'Updated by Household_structure post_save.')) <NEW_LINE> objects = Manager() <NEW_LINE> history = HistoricalRecords() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.household_identifier <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.id: <NEW_LINE> <INDENT> self.report_datetime = self.plot.report_datetime <NEW_LINE> <DEDENT> super().save(*args, **kwargs) <NEW_LINE> <DEDENT> def natural_key(self): <NEW_LINE> <INDENT> return (self.household_identifier, ) + self.plot.natural_key() <NEW_LINE> <DEDENT> natural_key.dependencies = ['plot.plot'] <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['-household_identifier', ] | A system model that represents the household asset.
See also HouseholdStructure. | 6259905c0fa83653e46f64f8 |
class ParsedMembership(TimestampMixin, BaseParsedModel): <NEW_LINE> <INDENT> person = models.ForeignKey(ParsedPerson, related_name='memberships') <NEW_LINE> start_date = models.DateField(null=False) <NEW_LINE> end_date = models.DateField(null=True) <NEW_LINE> method_obtained = models.CharField(max_length=255) <NEW_LINE> position = models.CharField(max_length=255) <NEW_LINE> note = models.CharField(max_length=255, default='') <NEW_LINE> objects = MembershipManager() <NEW_LINE> not_overridable = ['person'] <NEW_LINE> RAW_MODEL = RawMember <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['-start_date'] <NEW_LINE> app_label = 'raw' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return '{}: {} - {}'.format(self.position, self.start_date, self.end_date) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def make_uid(person_obj, membership_parser): <NEW_LINE> <INDENT> member_uid = person_obj.uid <NEW_LINE> start_date = membership_parser.start_date.isoformat().replace('-', '') <NEW_LINE> slug = slugify(membership_parser.position) <NEW_LINE> return '{}.{}.{}'.format(member_uid, start_date, slug) | Model for each position and term that a person holds.
The UID for this should be something like '{member_uid}.m{start_date}.{position_slug}', however it is conceivable
that a person may begin to hold multiple offices at the same time. Currently, this is the case
for only one record, which appears to be erroneous, but that doesn't mean it can't happen in the future | 6259905ca219f33f346c7e18 |
class BINDServerRunner(fixtures.Fixture): <NEW_LINE> <INDENT> RNDC_PATH = "/usr/sbin/rndc" <NEW_LINE> def __init__(self, config): <NEW_LINE> <INDENT> super(BINDServerRunner, self).__init__() <NEW_LINE> self.config = config <NEW_LINE> self.process = None <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> super(BINDServerRunner, self).setUp() <NEW_LINE> self._start() <NEW_LINE> <DEDENT> def is_running(self): <NEW_LINE> <INDENT> if self.process is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.process.poll() is None <NEW_LINE> <DEDENT> <DEDENT> def _spawn(self): <NEW_LINE> <INDENT> env = dict(os.environ, HOME=self.config.homedir) <NEW_LINE> with open(self.config.log_file, "wb") as log_file: <NEW_LINE> <INDENT> with open(os.devnull, "rb") as devnull: <NEW_LINE> <INDENT> self.process = subprocess.Popen( [self.config.named_file, "-f", "-c", self.config.conf_file], stdin=devnull, stdout=log_file, stderr=log_file, close_fds=True, cwd=self.config.homedir, env=env, preexec_fn=preexec_fn) <NEW_LINE> <DEDENT> <DEDENT> self.addCleanup(self._stop) <NEW_LINE> open_log_file = open(self.config.log_file, "rb") <NEW_LINE> self.addDetail( os.path.basename(self.config.log_file), Content(UTF8_TEXT, lambda: open_log_file)) <NEW_LINE> <DEDENT> def rndc(self, command): <NEW_LINE> <INDENT> if isinstance(command, basestring): <NEW_LINE> <INDENT> command = (command,) <NEW_LINE> <DEDENT> ctl = subprocess.Popen( (self.RNDC_PATH, "-c", self.config.rndcconf_file) + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=preexec_fn) <NEW_LINE> outstr, errstr = ctl.communicate() <NEW_LINE> return outstr, errstr <NEW_LINE> <DEDENT> def is_server_running(self): <NEW_LINE> <INDENT> outdata, errdata = self.rndc("status") <NEW_LINE> return "server is up and running" in outdata <NEW_LINE> <DEDENT> def _start(self): <NEW_LINE> <INDENT> self._spawn() <NEW_LINE> timeout = time.time() + 15 <NEW_LINE> while time.time() < timeout and self.is_running(): <NEW_LINE> <INDENT> if self.is_server_running(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> time.sleep(0.3) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( "Timeout waiting for BIND server to start: log in %r." % (self.config.log_file,)) <NEW_LINE> <DEDENT> <DEDENT> def _request_stop(self): <NEW_LINE> <INDENT> outstr, errstr = self.rndc("stop") <NEW_LINE> if outstr: <NEW_LINE> <INDENT> self.addDetail('stop-out', Content(UTF8_TEXT, lambda: [outstr])) <NEW_LINE> <DEDENT> if errstr: <NEW_LINE> <INDENT> self.addDetail('stop-err', Content(UTF8_TEXT, lambda: [errstr])) <NEW_LINE> <DEDENT> <DEDENT> def _stop(self): <NEW_LINE> <INDENT> self._request_stop() <NEW_LINE> self.process.wait() | Run a BIND server. | 6259905c8e7ae83300eea6a0 |
class DocentesBolsones(models.Model): <NEW_LINE> <INDENT> _name = 'docentes.bolsones' <NEW_LINE> _order = 'nivel' <NEW_LINE> _description = 'Modelo para la entrega de bolsones a afiliados' <NEW_LINE> solicitud = fields.Many2one('docentes.solicitudes', string='Solicitud', ondelete='cascade') <NEW_LINE> menor = fields.Many2one('docentes.hijos', string='Menor') <NEW_LINE> nivel = fields.Selection(TIPO_BOLSON, 'Bolsón', required=True) <NEW_LINE> entregado = fields.Boolean('Entregado') | Gestión de bolsones escolares y por nacimiento para hijos de afiliades | 6259905c3539df3088ecd8af |
class DrgAttachmentFactsHelperGen(OCIResourceFactsHelperBase): <NEW_LINE> <INDENT> def get_required_params_for_get(self): <NEW_LINE> <INDENT> return ["drg_attachment_id"] <NEW_LINE> <DEDENT> def get_required_params_for_list(self): <NEW_LINE> <INDENT> return ["compartment_id"] <NEW_LINE> <DEDENT> def get_resource(self): <NEW_LINE> <INDENT> return oci_common_utils.call_with_backoff( self.client.get_drg_attachment, drg_attachment_id=self.module.params.get("drg_attachment_id"), ) <NEW_LINE> <DEDENT> def list_resources(self): <NEW_LINE> <INDENT> optional_list_method_params = ["vcn_id", "drg_id", "display_name"] <NEW_LINE> optional_kwargs = dict( (param, self.module.params[param]) for param in optional_list_method_params if self.module.params.get(param) is not None ) <NEW_LINE> return oci_common_utils.list_all_resources( self.client.list_drg_attachments, compartment_id=self.module.params.get("compartment_id"), **optional_kwargs ) | Supported operations: get, list | 6259905c99cbb53fe68324f3 |
class FuncallOp(loom.LoomOp): <NEW_LINE> <INDENT> def __init__(self, tf_fn, input_type, output_type): <NEW_LINE> <INDENT> self.tf_fn = tf_fn <NEW_LINE> in_ts = _get_typeshapes(input_type.terminal_types()) <NEW_LINE> out_ts = _get_typeshapes(output_type.terminal_types()) <NEW_LINE> super(FuncallOp, self).__init__(in_ts, out_ts) <NEW_LINE> self._unflatten_inputs = None <NEW_LINE> self._flatten_outputs = None <NEW_LINE> if (isinstance(input_type, tdt.TupleType) and any(isinstance(t, tdt.TupleType) for t in input_type)): <NEW_LINE> <INDENT> self._unflatten_inputs = input_type.unflatten <NEW_LINE> <DEDENT> if (not isinstance(output_type, tdt.TupleType) or any(isinstance(t, tdt.TupleType) for t in output_type)): <NEW_LINE> <INDENT> self._flatten_outputs = output_type.flatten <NEW_LINE> <DEDENT> <DEDENT> def instantiate_batch(self, inputs): <NEW_LINE> <INDENT> if self._unflatten_inputs: <NEW_LINE> <INDENT> inputs = self._unflatten_inputs(iter(inputs), None) <NEW_LINE> <DEDENT> outputs = self.tf_fn(*inputs) <NEW_LINE> return self._flatten_outputs(outputs) if self._flatten_outputs else outputs | Loom Op that wraps a Function. | 6259905c15baa723494635a5 |
class Comprobante(models.Model): <NEW_LINE> <INDENT> codigo = models.PositiveSmallIntegerField() <NEW_LINE> nombre = models.CharField(max_length=16) <NEW_LINE> descripcion = models.CharField(max_length=512) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.nombre <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "Comprobante" <NEW_LINE> verbose_name_plural = "Comprobantes" | Codificacion aprobada por SUNAT | 6259905c0a50d4780f7068c8 |
class Pages(db.EmbeddedDocument): <NEW_LINE> <INDENT> page = db.IntField() <NEW_LINE> sentences = db.ListField(db.StringField()) | Scenes and their component sentences | 6259905c379a373c97d9a638 |
class Move: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.move_valide = False <NEW_LINE> <DEDENT> def move_up(self, ply_pos, wall_list, passages): <NEW_LINE> <INDENT> self.predict_player_pos = (ply_pos[0], ply_pos[1]-40) <NEW_LINE> if self.predict_player_pos not in wall_list: <NEW_LINE> <INDENT> if self.predict_player_pos in passages: <NEW_LINE> <INDENT> self.move_valide = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.move_valide = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.move_valide = False <NEW_LINE> <DEDENT> return self.move_valide <NEW_LINE> <DEDENT> def move_down(self, ply_pos, wall_list, passages): <NEW_LINE> <INDENT> self.predict_player_pos = (ply_pos[0], ply_pos[1]+40) <NEW_LINE> if self.predict_player_pos not in wall_list: <NEW_LINE> <INDENT> if self.predict_player_pos in passages: <NEW_LINE> <INDENT> self.move_valide = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.move_valide = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.move_valide = False <NEW_LINE> <DEDENT> return self.move_valide <NEW_LINE> <DEDENT> def move_left(self, ply_pos, wall_list, passages): <NEW_LINE> <INDENT> self.predict_player_pos = (ply_pos[0]-40, ply_pos[1]) <NEW_LINE> if self.predict_player_pos not in wall_list: <NEW_LINE> <INDENT> if self.predict_player_pos in passages: <NEW_LINE> <INDENT> self.move_valide = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.move_valide = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.move_valide = False <NEW_LINE> <DEDENT> return self.move_valide <NEW_LINE> <DEDENT> def move_right(self, ply_pos, wall_list, passages): <NEW_LINE> <INDENT> self.predict_player_pos = (ply_pos[0]+40, ply_pos[1]) <NEW_LINE> if self.predict_player_pos not in wall_list: <NEW_LINE> <INDENT> if self.predict_player_pos in passages: <NEW_LINE> <INDENT> self.move_valide = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.move_valide = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.move_valide = False <NEW_LINE> <DEDENT> return self.move_valide | This class manages the player’s movements | 6259905ca8ecb0332587282b |
class Exhaust(prop.ideal_gas): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Exhaust, self).__init__() <NEW_LINE> self.enh_lib = enhancement <NEW_LINE> self.enh = None <NEW_LINE> self.T_ref = 300. <NEW_LINE> self.P = 101. <NEW_LINE> self.height = 1.5e-2 <NEW_LINE> self.ducts = 1 <NEW_LINE> self.sides = 2 <NEW_LINE> self.mdot_omega = 0.2 / 60. <NEW_LINE> self.Nu_coeff = 0.023 <NEW_LINE> functions.bind_functions(self) <NEW_LINE> <DEDENT> def set_fluid_props(self): <NEW_LINE> <INDENT> self.set_thermal_props() <NEW_LINE> self.c_p = self.c_p_air <NEW_LINE> self.k = self.k_air | Class for engine exhaust in heat exchanger.
Methods:
__init__
set_fluid_props | 6259905c4a966d76dd5f0506 |
class motorCaseCheckOffset(motorCaseBase): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> for motor in self.getMotors(): <NEW_LINE> <INDENT> self.diagnostic("motorCaseCheckOffset for motor " + str(motor) + "...", self.getDiag()) <NEW_LINE> pv_rbv = self.getPVBase() + motor + ".RBV" <NEW_LINE> pv_off = self.getPVBase() + motor + ".OFF" <NEW_LINE> pv_val = self.getPVBase() + motor + ".VAL" <NEW_LINE> pv_hlm = self.getPVBase() + motor + ".HLM" <NEW_LINE> pv_llm = self.getPVBase() + motor + ".LLM" <NEW_LINE> pv_rdbd = self.getPVBase() + motor + ".RDBD" <NEW_LINE> start_off = self.getPv(pv_off) <NEW_LINE> start_val = self.getPv(pv_val) <NEW_LINE> start_rbv = self.getPv(pv_rbv) <NEW_LINE> start_hlm = self.getPv(pv_hlm) <NEW_LINE> start_llm = self.getPv(pv_llm) <NEW_LINE> rdbd = self.getPv(pv_rdbd) <NEW_LINE> self.diagnostic("Increasing offset by 1.", self.getDiag()) <NEW_LINE> self.putPv(pv_off, start_off+1, wait=True, timeout=self.getTimeout()) <NEW_LINE> self.diagnostic("Now check the offset fields.", self.getDiag()) <NEW_LINE> self.verify(start_off+1, self.getPv(pv_off)) <NEW_LINE> self.verify(start_val+1, self.getPv(pv_val)) <NEW_LINE> self.verify(start_hlm+1, self.getPv(pv_hlm)) <NEW_LINE> self.verify(start_llm+1, self.getPv(pv_llm)) <NEW_LINE> self.verifyPvInRange(pv_val, start_val+1-rdbd, start_val+1+rdbd) <NEW_LINE> self.verifyPvInRange(pv_rbv, start_rbv+1-rdbd, start_rbv+1+rdbd) <NEW_LINE> self.diagnostic("Reset original offset.", self.getDiag()) <NEW_LINE> self.putPv(pv_off, start_off, wait=True, timeout=self.getTimeout()) | Class to check the use of offset. It checks
that soft limits and user coordinates are
offset correctly when setting an offset. | 6259905cb5575c28eb7137d6 |
class ModelConfigs: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def dump(model_config, output_dir): <NEW_LINE> <INDENT> model_config_filename = os.path.join(output_dir, Constants.MODEL_CONFIG_YAML_FILENAME) <NEW_LINE> if not gfile.Exists(output_dir): <NEW_LINE> <INDENT> gfile.MakeDirs(output_dir) <NEW_LINE> <DEDENT> with gfile.GFile(model_config_filename, "w") as file: <NEW_LINE> <INDENT> yaml.dump(model_config, file) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def load(model_dir): <NEW_LINE> <INDENT> model_config_filename = os.path.join(model_dir, Constants.MODEL_CONFIG_YAML_FILENAME) <NEW_LINE> if not gfile.Exists(model_config_filename): <NEW_LINE> <INDENT> raise OSError("Fail to find model config file: %s" % model_config_filename) <NEW_LINE> <DEDENT> with gfile.GFile(model_config_filename, "r") as file: <NEW_LINE> <INDENT> model_configs = yaml.load(file) <NEW_LINE> <DEDENT> return model_configs | A class for dumping and loading model configurations. | 6259905cd7e4931a7ef3d68e |
class TextureFile(): <NEW_LINE> <INDENT> def __init__(self, path, filename): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.filename = filename <NEW_LINE> self.mesh = '' <NEW_LINE> self.texture_set = '' <NEW_LINE> self.channel = '' <NEW_LINE> self.ext = '' <NEW_LINE> self.udim = '<UDIM>' <NEW_LINE> try: <NEW_LINE> <INDENT> self._partition() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print('No matching pattern for texture') <NEW_LINE> <DEDENT> <DEDENT> def _partition(self): <NEW_LINE> <INDENT> name, self.texture_set, self.ext = self.filename.split('.') <NEW_LINE> self.mesh, sep, self.channel = name.rpartition('_') <NEW_LINE> <DEDENT> def get_channels(self): <NEW_LINE> <INDENT> if self.texture_set.isdigit(): <NEW_LINE> <INDENT> return self.mesh, self.channel, self.udim, self.ext <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.mesh, self.channel, self.texture_set, self.ext | $mesh_Diffuse.$textureSet.$ext | 6259905ca79ad1619776b5c7 |
@register_reply('transfer_customer_service') <NEW_LINE> class TransferCustomerServiceReply(BaseReply): <NEW_LINE> <INDENT> type = 'transfer_customer_service' | 将消息转发到多客服
详情请参阅
http://mp.weixin.qq.com/wiki/5/ae230189c9bd07a6b221f48619aeef35.html | 6259905ce5267d203ee6ceca |
class SoVolumeRender(coin.SoShape): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def getClassTypeId(): <NEW_LINE> <INDENT> return _simvoleon.SoVolumeRender_getClassTypeId() <NEW_LINE> <DEDENT> getClassTypeId = staticmethod(getClassTypeId) <NEW_LINE> def getTypeId(self): <NEW_LINE> <INDENT> return _simvoleon.SoVolumeRender_getTypeId(self) <NEW_LINE> <DEDENT> def initClass(): <NEW_LINE> <INDENT> return _simvoleon.SoVolumeRender_initClass() <NEW_LINE> <DEDENT> initClass = staticmethod(initClass) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> this = _simvoleon.new_SoVolumeRender() <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> NEAREST = _simvoleon.SoVolumeRender_NEAREST <NEW_LINE> LINEAR = _simvoleon.SoVolumeRender_LINEAR <NEW_LINE> MAX_INTENSITY = _simvoleon.SoVolumeRender_MAX_INTENSITY <NEW_LINE> SUM_INTENSITY = _simvoleon.SoVolumeRender_SUM_INTENSITY <NEW_LINE> ALPHA_BLENDING = _simvoleon.SoVolumeRender_ALPHA_BLENDING <NEW_LINE> ALL = _simvoleon.SoVolumeRender_ALL <NEW_LINE> MANUAL = _simvoleon.SoVolumeRender_MANUAL <NEW_LINE> AUTOMATIC = _simvoleon.SoVolumeRender_AUTOMATIC <NEW_LINE> CONTINUE = _simvoleon.SoVolumeRender_CONTINUE <NEW_LINE> ABORT = _simvoleon.SoVolumeRender_ABORT <NEW_LINE> SKIP = _simvoleon.SoVolumeRender_SKIP <NEW_LINE> interpolation = _swig_property(_simvoleon.SoVolumeRender_interpolation_get, _simvoleon.SoVolumeRender_interpolation_set) <NEW_LINE> composition = _swig_property(_simvoleon.SoVolumeRender_composition_get, _simvoleon.SoVolumeRender_composition_set) <NEW_LINE> lighting = _swig_property(_simvoleon.SoVolumeRender_lighting_get, _simvoleon.SoVolumeRender_lighting_set) <NEW_LINE> lightDirection = _swig_property(_simvoleon.SoVolumeRender_lightDirection_get, _simvoleon.SoVolumeRender_lightDirection_set) <NEW_LINE> lightIntensity = _swig_property(_simvoleon.SoVolumeRender_lightIntensity_get, _simvoleon.SoVolumeRender_lightIntensity_set) <NEW_LINE> numSlicesControl = _swig_property(_simvoleon.SoVolumeRender_numSlicesControl_get, _simvoleon.SoVolumeRender_numSlicesControl_set) <NEW_LINE> numSlices = _swig_property(_simvoleon.SoVolumeRender_numSlices_get, _simvoleon.SoVolumeRender_numSlices_set) <NEW_LINE> viewAlignedSlices = _swig_property(_simvoleon.SoVolumeRender_viewAlignedSlices_get, _simvoleon.SoVolumeRender_viewAlignedSlices_set) <NEW_LINE> def setAbortCallback(self, *args): <NEW_LINE> <INDENT> return _simvoleon.SoVolumeRender_setAbortCallback(self, *args) | Proxy of C++ SoVolumeRender class | 6259905c379a373c97d9a639 |
class IPickleable(ITransformable): <NEW_LINE> <INDENT> pass | Pickle-able marker-interface. | 6259905ca8370b77170f19e2 |
@LuxRenderAddon.addon_register_class <NEW_LINE> class luxrender_TC_tex1_socket(bpy.types.NodeSocket): <NEW_LINE> <INDENT> bl_idname = 'luxrender_TC_tex1_socket' <NEW_LINE> bl_label = 'Texture 1 socket' <NEW_LINE> tex1 = bpy.props.FloatVectorProperty(name='Color 1', subtype='COLOR', min=0.0, soft_max=1.0) <NEW_LINE> def draw(self, context, layout, node, text): <NEW_LINE> <INDENT> if self.is_linked: <NEW_LINE> <INDENT> layout.label(text=self.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> layout.prop(self, 'tex1', text=self.name) <NEW_LINE> <DEDENT> <DEDENT> def draw_color(self, context, node): <NEW_LINE> <INDENT> return color_socket_color <NEW_LINE> <DEDENT> def get_paramset(self, make_texture): <NEW_LINE> <INDENT> tex_node = get_linked_node(self) <NEW_LINE> if tex_node: <NEW_LINE> <INDENT> if not check_node_export_texture(tex_node): <NEW_LINE> <INDENT> return ParamSet() <NEW_LINE> <DEDENT> tex_name = tex_node.export_texture(make_texture) <NEW_LINE> tex1_params = ParamSet().add_texture('tex1', tex_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tex1_params = ParamSet().add_color('tex1', self.tex1) <NEW_LINE> <DEDENT> return tex1_params | Texture 1 socket | 6259905ce64d504609df9ed9 |
class TestIPAddressInterface(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testIPAddressInterface(self): <NEW_LINE> <INDENT> pass | IPAddressInterface unit test stubs | 6259905c7d43ff2487427f1a |
class Manager(AbstractManager, BELNamespaceManagerMixin, FlaskMixin): <NEW_LINE> <INDENT> module_name = MODULE_NAME <NEW_LINE> namespace_model = Antibody <NEW_LINE> flask_admin_models = [Antibody] <NEW_LINE> _base = Base <NEW_LINE> def is_populated(self) -> bool: <NEW_LINE> <INDENT> return 0 < self.count_antibodies() <NEW_LINE> <DEDENT> def count_antibodies(self) -> int: <NEW_LINE> <INDENT> return self._count_model(Antibody) <NEW_LINE> <DEDENT> def summarize(self) -> Mapping[str, int]: <NEW_LINE> <INDENT> return dict(antibodies=self.count_antibodies()) <NEW_LINE> <DEDENT> def populate(self, url: Optional[str] = None) -> None: <NEW_LINE> <INDENT> chunks = df_getter(url=url) <NEW_LINE> for df in tqdm(chunks): <NEW_LINE> <INDENT> df = df[df.name.notna()] <NEW_LINE> df = df[df.antibodyregistry_id.notna()] <NEW_LINE> df = df[df.vendor.notna()] <NEW_LINE> df.to_sql(Antibody.__tablename__, con=self.engine, if_exists='append', index=False) <NEW_LINE> self.session.commit() <NEW_LINE> <DEDENT> <DEDENT> def get_antibody_by_antibodyregistry_id(self, antibodyregistry_id: str) -> Optional[Antibody]: <NEW_LINE> <INDENT> return self.session.query(Antibody).filter(Antibody.antibodyregistry_id == antibodyregistry_id).one_or_none() <NEW_LINE> <DEDENT> def _create_namespace_entry_from_model(self, model: Antibody, namespace: Namespace) -> NamespaceEntry: <NEW_LINE> <INDENT> return NamespaceEntry( namespace=namespace, identifier=model.antibodyregistry_id, name=model.name, encoding='A', ) | Manages the Bio2BEL Antibody Registry database. | 6259905c07f4c71912bb0a51 |
class TestPalindrome(unittest.TestCase): <NEW_LINE> <INDENT> def test_if_palindrome(self): <NEW_LINE> <INDENT> self.assertEqual(ash.if_palindrome("bob"), True) <NEW_LINE> self.assertEqual(ash.if_palindrome("Allah"), True) <NEW_LINE> self.assertEqual(ash.if_palindrome("to"), False) <NEW_LINE> self.assertEqual(ash.if_palindrome("jedyny"), False) <NEW_LINE> self.assertEqual(ash.if_palindrome("Bog"), False) <NEW_LINE> self.assertEqual(ash.if_palindrome("Papiez"), False) <NEW_LINE> self.assertEqual(ash.if_palindrome("polak"), False) <NEW_LINE> self.assertEqual(ash.if_palindrome("gwalcil"), False) <NEW_LINE> self.assertEqual(ash.if_palindrome("male"), False) <NEW_LINE> self.assertEqual(ash.if_palindrome("dzieci"), False) <NEW_LINE> self.assertEqual(ash.if_palindrome("konstantynopolitanczykowianeczka"), False) <NEW_LINE> self.assertEqual(ash.if_palindrome(""), False) <NEW_LINE> self.assertEqual(ash.if_palindrome("h"), True) <NEW_LINE> self.assertEqual(ash.if_palindrome("hhhaabbkkll"), True) <NEW_LINE> self.assertEqual(ash.if_palindrome("fffggg"), False) <NEW_LINE> self.assertEqual(ash.if_palindrome("hhhaabbkkll11"), True) <NEW_LINE> self.assertEqual(ash.if_palindrome("fffggg23"), False) | Test for if_palindrom function. I made a few simple test for checking all possiblity of function behavior.
I used some normal words , empty string, string with numbers and strings with random letters. | 6259905c462c4b4f79dbd01a |
class ResponseCookieHandler(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.cookie_headers = [] <NEW_LINE> <DEDENT> def add_cookie(self, key, value, expires=None, path=None, sign=True): <NEW_LINE> <INDENT> if path is None: <NEW_LINE> <INDENT> path = settings.SITE_ROOT or '/' <NEW_LINE> <DEDENT> cookie = '%s=%s' % (key, value) <NEW_LINE> if expires: <NEW_LINE> <INDENT> expires = expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT") <NEW_LINE> cookie += '; expires=%s' % expires <NEW_LINE> <DEDENT> if path: <NEW_LINE> <INDENT> cookie += '; path=%s' % path <NEW_LINE> <DEDENT> self.cookie_headers.append(('Set-Cookie', cookie)) <NEW_LINE> if sign: <NEW_LINE> <INDENT> if settings.SECRET_KEY is None: <NEW_LINE> <INDENT> raise CookieKeyMissing( 'Set SECRET_KEY in settings to use cookies') <NEW_LINE> <DEDENT> cookie_hash = hmac.HMAC(settings.SECRET_KEY, key + value, sha1).hexdigest() <NEW_LINE> cookie_hash = '%s_hash=%s' % (key, cookie_hash) <NEW_LINE> if expires: <NEW_LINE> <INDENT> cookie_hash += '; expires=%s' % expires <NEW_LINE> <DEDENT> if path: <NEW_LINE> <INDENT> cookie_hash += '; path=' + path <NEW_LINE> <DEDENT> self.cookie_headers.append(('Set-Cookie', cookie_hash)) <NEW_LINE> <DEDENT> <DEDENT> def add_unsigned_cookie(self, *args, **kwargs): <NEW_LINE> <INDENT> self.add_cookie(sign=False, *args, **kwargs) <NEW_LINE> <DEDENT> def del_cookie(self, key): <NEW_LINE> <INDENT> self.cookie_headers.append( ('Set-Cookie', "%s=null; expires=Thu, 01-Jan-1970 00:00:01 GMT" % key)) <NEW_LINE> self.cookie_headers.append( ('Set-Cookie', "%s_hash=null; expires=Thu, 01-Jan-1970 00:00:01 GMT" % key)) | Handle cookie adding to request. | 6259905c3c8af77a43b68a4b |
class SimpleResult(Result): <NEW_LINE> <INDENT> def toDict(self): <NEW_LINE> <INDENT> toReturn = {} <NEW_LINE> toReturn["data_version"] = Config.DATA_VERSION <NEW_LINE> if not self.data: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.data = [hit['_source'] for hit in self.res['hits']['hits']] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise AttributeError('some data is needed to be returned in a SimpleResult') <NEW_LINE> <DEDENT> <DEDENT> toReturn["data"] = self.data <NEW_LINE> if self.facets: <NEW_LINE> <INDENT> toReturn["facets"] = self.facets <NEW_LINE> <DEDENT> return toReturn | just need data to be passed and it will be returned as dict
| 6259905c2c8b7c6e89bd4e03 |
class Characteristic(dbus.service.Object): <NEW_LINE> <INDENT> def __init__(self, bus, index, uuid, flags, service): <NEW_LINE> <INDENT> self.path = service.path + '/char' + str(index) <NEW_LINE> self.bus = bus <NEW_LINE> if isinstance(uuid, int): <NEW_LINE> <INDENT> uuid = '0x%x' % uuid <NEW_LINE> <DEDENT> self.uuid = uuid <NEW_LINE> self.service = service <NEW_LINE> self.flags = flags <NEW_LINE> self.descriptors = [] <NEW_LINE> dbus.service.Object.__init__(self, bus, self.path) <NEW_LINE> <DEDENT> def get_properties(self): <NEW_LINE> <INDENT> return { GATT_CHRC_IFACE: { 'Service': self.service.get_path(), 'UUID': self.uuid, 'Flags': self.flags, 'Descriptors': dbus.Array( self.get_descriptor_paths(), signature='o') } } <NEW_LINE> <DEDENT> def get_path(self): <NEW_LINE> <INDENT> return dbus.ObjectPath(self.path) <NEW_LINE> <DEDENT> def add_descriptor(self, descriptor): <NEW_LINE> <INDENT> self.descriptors.append(descriptor) <NEW_LINE> <DEDENT> def get_descriptor_paths(self): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for desc in self.descriptors: <NEW_LINE> <INDENT> result.append(desc.get_path()) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def get_descriptors(self): <NEW_LINE> <INDENT> return self.descriptors <NEW_LINE> <DEDENT> @dbus.service.method(DBUS_PROP_IFACE, in_signature='s', out_signature='a{sv}') <NEW_LINE> def GetAll(self, interface): <NEW_LINE> <INDENT> if interface != GATT_CHRC_IFACE: <NEW_LINE> <INDENT> raise exceptions.InvalidArgsException() <NEW_LINE> <DEDENT> return self.get_properties()[GATT_CHRC_IFACE] <NEW_LINE> <DEDENT> @dbus.service.method(GATT_CHRC_IFACE, in_signature='a{sv}', out_signature='ay') <NEW_LINE> def ReadValue(self, options): <NEW_LINE> <INDENT> print('Default ReadValue called, returning error') <NEW_LINE> raise exceptions.NotSupportedException() <NEW_LINE> <DEDENT> @dbus.service.method(GATT_CHRC_IFACE, in_signature='aya{sv}') <NEW_LINE> def WriteValue(self, value, options): <NEW_LINE> <INDENT> print('Default WriteValue called, returning error') <NEW_LINE> raise exceptions.NotSupportedException() <NEW_LINE> <DEDENT> @dbus.service.method(GATT_CHRC_IFACE) <NEW_LINE> def StartNotify(self): <NEW_LINE> <INDENT> print('Default StartNotify called, returning error') <NEW_LINE> raise exceptions.NotSupportedException() <NEW_LINE> <DEDENT> @dbus.service.method(GATT_CHRC_IFACE) <NEW_LINE> def StopNotify(self): <NEW_LINE> <INDENT> print('Default StopNotify called, returning error') <NEW_LINE> raise exceptions.NotSupportedException() <NEW_LINE> <DEDENT> @dbus.service.signal(DBUS_PROP_IFACE, signature='sa{sv}as') <NEW_LINE> def PropertiesChanged(self, interface, changed, invalidated): <NEW_LINE> <INDENT> pass | org.bluez.GattCharacteristic1 interface implementation | 6259905c7b25080760ed87ea |
class KthLargest: <NEW_LINE> <INDENT> def __init__(self, k: int, nums: List[int]): <NEW_LINE> <INDENT> self.k = k <NEW_LINE> self.heap = sorted(nums, reverse=True)[:self.k] <NEW_LINE> <DEDENT> def add(self, val: int) -> int: <NEW_LINE> <INDENT> if len(self.heap) <= self.k: <NEW_LINE> <INDENT> self.heap += [val] <NEW_LINE> self.heap = sorted(self.heap, reverse=True)[:self.k] <NEW_LINE> <DEDENT> return self.heap[-1] | Time O(N) Space O(2N) | 6259905c3539df3088ecd8b1 |
class Selector(object): <NEW_LINE> <INDENT> def __init__(self, tree, pseudo_element=None): <NEW_LINE> <INDENT> self.parsed_tree = tree <NEW_LINE> if pseudo_element is not None and not isinstance( pseudo_element, FunctionalPseudoElement): <NEW_LINE> <INDENT> pseudo_element = ascii_lower(pseudo_element) <NEW_LINE> <DEDENT> self.pseudo_element = pseudo_element <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if isinstance(self.pseudo_element, FunctionalPseudoElement): <NEW_LINE> <INDENT> pseudo_element = repr(self.pseudo_element) <NEW_LINE> <DEDENT> elif self.pseudo_element: <NEW_LINE> <INDENT> pseudo_element = '::%s' % self.pseudo_element <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pseudo_element = '' <NEW_LINE> <DEDENT> return '%s[%r%s]' % ( self.__class__.__name__, self.parsed_tree, pseudo_element) <NEW_LINE> <DEDENT> def specificity(self): <NEW_LINE> <INDENT> a, b, c = self.parsed_tree.specificity() <NEW_LINE> if self.pseudo_element: <NEW_LINE> <INDENT> c += 1 <NEW_LINE> <DEDENT> return a, b, c <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, self.__class__): <NEW_LINE> <INDENT> return (self.pseudo_element == other.pseudo_element and self.parsed_tree == other.parsed_tree) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.pseudo_element) + hash(self.parsed_tree) | Represents a parsed selector.
:meth:`~GenericTranslator.selector_to_xpath` accepts this object,
but ignores :attr:`pseudo_element`. It is the user’s responsibility
to account for pseudo-elements and reject selectors with unknown
or unsupported pseudo-elements. | 6259905c67a9b606de5475ac |
class Regime(Behavioral): <NEW_LINE> <INDENT> def __init__(self, name, parent_behavioral, initial=False): <NEW_LINE> <INDENT> Behavioral.__init__(self) <NEW_LINE> self.name = name <NEW_LINE> self.parent_behavioral = parent_behavioral <NEW_LINE> self.initial = initial | Stores a single behavioral regime for a component type. | 6259905c3eb6a72ae038bc76 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.