code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class OrbitNorthernPole(OrbitEvent): <NEW_LINE> <INDENT> name = "Orbit.NorthernPole" <NEW_LINE> def _occur(self,message): <NEW_LINE> <INDENT> if self._ready(message): <NEW_LINE> <INDENT> m0 = self.prev.w <NEW_LINE> m1 = self.next.w <NEW_LINE> if (m0 >= 0 and m1 <= 0): <NEW_LINE> <INDENT> x0 = self.prev.epoch <NEW_LINE> x1 = self.next.epoch <NEW_LINE> dx = (x1 - x0).total_seconds() <NEW_LINE> p0 = self.prev.z <NEW_LINE> p1 = self.next.z <NEW_LINE> m0 *= dx <NEW_LINE> m1 *= dx <NEW_LINE> m = HERMITE_DERIVATIVE(p0,m0,p1,m1) <NEW_LINE> r = m.r <NEW_LINE> t = r[where((r > 0) & (r < 1))][0] <NEW_LINE> x = x0 + timedelta(seconds = t * dx) <NEW_LINE> epoch = EpochState(x) <NEW_LINE> logging.info("{0}: Achieved at {1}". format(self.name,epoch.epoch)) <NEW_LINE> return epoch | Story: Orbit northern pole
IN ORDER TO perform analyses at the northern pole
AS A generic segment
I WANT TO be notified when northern pole is reached | 62598fbabe383301e025396a |
class LeafEntity(Entity): <NEW_LINE> <INDENT> def __init__(self, car: Leaf) -> None: <NEW_LINE> <INDENT> self.car = car <NEW_LINE> <DEDENT> def log_registration(self) -> None: <NEW_LINE> <INDENT> _LOGGER.debug( "Registered %s integration for VIN %s", self.__class__.__name__, self.car.leaf.vin, ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def extra_state_attributes(self) -> dict[str, Any]: <NEW_LINE> <INDENT> return { "next_update": self.car.next_update, "last_attempt": self.car.last_check, "updated_on": self.car.last_battery_response, "update_in_progress": self.car.request_in_progress, "vin": self.car.leaf.vin, } <NEW_LINE> <DEDENT> async def async_added_to_hass(self) -> None: <NEW_LINE> <INDENT> self.log_registration() <NEW_LINE> self.async_on_remove( async_dispatcher_connect( self.car.hass, SIGNAL_UPDATE_LEAF, self._update_callback ) ) <NEW_LINE> <DEDENT> @callback <NEW_LINE> def _update_callback(self) -> None: <NEW_LINE> <INDENT> self.async_schedule_update_ha_state(True) | Base class for Nissan Leaf entity. | 62598fba1f5feb6acb162d8d |
class TestAppleUpdatesModule(mox.MoxTestBase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> mox.MoxTestBase.setUp(self) <NEW_LINE> self.stubs = stubout.StubOutForTesting() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.mox.UnsetStubs() <NEW_LINE> self.stubs.UnsetAll() <NEW_LINE> <DEDENT> def testGlobals(self): <NEW_LINE> <INDENT> self.assertTrue( type(getattr(appleupdates, 'DEFAULT_CATALOG_URLS', None)) is dict) | Test appleupdates module. | 62598fba091ae35668704d8f |
class PLSR(bases.ImplicitAlgorithm, bases.IterativeAlgorithm): <NEW_LINE> <INDENT> def __init__(self, max_iter=200, eps=consts.TOLERANCE, **kwargs): <NEW_LINE> <INDENT> super(PLSR, self).__init__(max_iter=max_iter, **kwargs) <NEW_LINE> self.eps = max(consts.TOLERANCE, float(eps)) <NEW_LINE> <DEDENT> def run(self, XY, wc=None): <NEW_LINE> <INDENT> X = XY[0] <NEW_LINE> Y = XY[1] <NEW_LINE> n, p = X.shape <NEW_LINE> if wc is not None: <NEW_LINE> <INDENT> w_new = wc[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> maxi = np.argmax(np.sum(Y ** 2.0, axis=0)) <NEW_LINE> u = Y[:, [maxi]] <NEW_LINE> w_new = np.dot(X.T, u) <NEW_LINE> w_new /= maths.norm(w_new) <NEW_LINE> <DEDENT> for i in range(self.max_iter): <NEW_LINE> <INDENT> w = w_new <NEW_LINE> c = np.dot(Y.T, np.dot(X, w)) <NEW_LINE> w_new = np.dot(X.T, np.dot(Y, c)) <NEW_LINE> normw = maths.norm(w_new) <NEW_LINE> if normw > 10.0 * consts.FLOAT_EPSILON: <NEW_LINE> <INDENT> w_new /= normw <NEW_LINE> <DEDENT> if maths.norm(w_new - w) < maths.norm(w) * self.eps: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> self.num_iter = i <NEW_LINE> t = np.dot(X, w) <NEW_LINE> tt = np.dot(t.T, t)[0, 0] <NEW_LINE> c = np.dot(Y.T, t) <NEW_LINE> if tt > consts.TOLERANCE: <NEW_LINE> <INDENT> c /= tt <NEW_LINE> <DEDENT> return w_new, c | A NIPALS implementation for PLS regresison.
Parameters
----------
max_iter : Non-negative integer. Maximum allowed number of iterations.
Default is 200.
eps : Positive float. The tolerance used in the stopping criterion.
Examples
--------
>>> from parsimony.algorithms.nipals import PLSR
>>> import numpy as np
>>> np.random.seed(42)
>>>
>>> X = np.random.rand(10, 10)
>>> Y = np.random.rand(10, 5)
>>> w = np.random.rand(10, 1)
>>> c = np.random.rand(5, 1)
>>> plsr = PLSR()
>>> w, c = plsr.run([X, Y], [w, c])
>>> w
array([[ 0.34682103],
[ 0.32576718],
[ 0.28909788],
[ 0.40036279],
[ 0.32321038],
[ 0.39060766],
[ 0.22351433],
[ 0.28643062],
[ 0.29060872],
[ 0.23712672]])
>>> c
array([[ 0.29443832],
[ 0.35886751],
[ 0.33847141],
[ 0.23526002],
[ 0.35910191]])
>>> C, S, W = np.linalg.svd(np.dot(Y.T, X))
>>> w_ = W[0, :].reshape(10, 1)
>>> w_ = -w_ if w_[0, 0] < 0.0 else w_
>>> w = -w if w[0, 0] < 0.0 else w
>>> np.linalg.norm(w - w_)
1.5288386388031829e-10
>>> np.dot(np.dot(X, w).T, np.dot(Y, c / np.linalg.norm(c)))[0, 0] - S[0]
0.0 | 62598fba3539df3088ecc41a |
class Node(dictobj.DictionaryObject): <NEW_LINE> <INDENT> def __init__(self, path, oid, **kwargs): <NEW_LINE> <INDENT> super(Node, self).__init__() <NEW_LINE> children = kwargs.get('children', {}) <NEW_LINE> if any(filter(lambda key: not isinstance(children[key], Node), children)): <NEW_LINE> <INDENT> raise TypeError( "One or more children were not instances of '%s'" % Node.__name__) <NEW_LINE> <DEDENT> if 'children' in kwargs: <NEW_LINE> <INDENT> del kwargs['children'] <NEW_LINE> <DEDENT> self._items['children'] = dictobj.MutableDictionaryObject(children) <NEW_LINE> if oid is not None: <NEW_LINE> <INDENT> li_attr = kwargs.get('li_attr', {}) <NEW_LINE> li_attr['id'] = oid <NEW_LINE> kwargs['li_attr'] = li_attr <NEW_LINE> <DEDENT> self._items.update(dictobj.DictionaryObject(**kwargs)) <NEW_LINE> self._items['text'] = path <NEW_LINE> <DEDENT> def jsonData(self): <NEW_LINE> <INDENT> children = [self.children[k].jsonData() for k in sorted(self.children)] <NEW_LINE> output = {} <NEW_LINE> for k in self._items: <NEW_LINE> <INDENT> if 'children' == k: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if isinstance(self._items[k], dictobj.DictionaryObject): <NEW_LINE> <INDENT> output[k] = self._items[k].asdict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output[k] = self._items[k] <NEW_LINE> <DEDENT> <DEDENT> if len(children): <NEW_LINE> <INDENT> output['children'] = children <NEW_LINE> <DEDENT> return output | This class exists as a helper to the jsTree. Its "jsonData" method can
generate sub-tree JSON without putting the logic directly into the jsTree.
This data structure is only semi-immutable. The jsTree uses a directly
iterative (i.e. no stack is managed) builder pattern to construct a
tree out of paths. Therefore, the children are not known in advance, and
we have to keep the children attribute mutable. | 62598fba4f88993c371f05c4 |
class ExcaliburInternalError(ExcaliburError): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ExcaliburInternalError, self).__init__(*args, **kwargs) | base exception for excalibur | 62598fba55399d3f05626681 |
class DeploymentValidateResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'error': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorResponse'}, 'properties': {'key': 'properties', 'type': 'DeploymentPropertiesExtended'}, } <NEW_LINE> def __init__( self, *, properties: Optional["DeploymentPropertiesExtended"] = None, **kwargs ): <NEW_LINE> <INDENT> super(DeploymentValidateResult, self).__init__(**kwargs) <NEW_LINE> self.error = None <NEW_LINE> self.properties = properties | Information from validate template deployment response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar error: The deployment validation error.
:vartype error: ~azure.mgmt.resource.resources.v2021_04_01.models.ErrorResponse
:ivar properties: The template deployment properties.
:vartype properties:
~azure.mgmt.resource.resources.v2021_04_01.models.DeploymentPropertiesExtended | 62598fba3617ad0b5ee062b4 |
class VertsDelDoublesNode(bpy.types.Node, SverchCustomTreeNode): <NEW_LINE> <INDENT> bl_idname = 'VertsDelDoublesNode' <NEW_LINE> bl_label = 'Delete Double vertices' <NEW_LINE> bl_icon = 'OUTLINER_OB_EMPTY' <NEW_LINE> def draw_buttons(self, context, layout): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def sv_init(self, context): <NEW_LINE> <INDENT> self.inputs.new('VerticesSocket', "vers", "vers") <NEW_LINE> self.outputs.new('VerticesSocket', "vers", "vers") <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> if 'vers' in self.outputs and len(self.outputs['vers'].links) > 0: <NEW_LINE> <INDENT> vers = SvGetSocketAnyType(self, self.inputs['vers']) <NEW_LINE> levs = levelsOflist(vers) <NEW_LINE> result = self.remdou(vers, levs) <NEW_LINE> SvSetSocketAnyType(self, 'vers', result) <NEW_LINE> <DEDENT> <DEDENT> def remdou(self, vers, levs): <NEW_LINE> <INDENT> out = [] <NEW_LINE> if levs >= 3: <NEW_LINE> <INDENT> levs -= 1 <NEW_LINE> for x in vers: <NEW_LINE> <INDENT> out.append(self.remdou(x, levs)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for x in vers: <NEW_LINE> <INDENT> if x not in out: <NEW_LINE> <INDENT> out.append(x) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return out | Delete doubles vertices | 62598fba5166f23b2e24354b |
class LMV(LyaInstruction): <NEW_LINE> <INDENT> _mnemonic = 'lmv' <NEW_LINE> def __init__(self, k): <NEW_LINE> <INDENT> super().__init__(k) <NEW_LINE> self.k = k | (’lmv’, k) # Load multiple values
t=M[sp]
for i in range(0,k-1):
M[sp+i]=M[t+i]
sp=sp + k - 1 | 62598fba66656f66f7d5a560 |
class RDBVocabulary(ObjectVocabulary): <NEW_LINE> <INDENT> implements(IRDBVocabulary) <NEW_LINE> select = None <NEW_LINE> def _load(self): <NEW_LINE> <INDENT> if self.select is not None: <NEW_LINE> <INDENT> self._v_skipObjectTypeCheckOnCreation = False <NEW_LINE> params = {} <NEW_LINE> return self.objectC.load_many(dbquery(self.select), **params) <NEW_LINE> <DEDENT> self._v_skipObjectTypeCheckOnCreation = True <NEW_LINE> return self.objectC.load_all() <NEW_LINE> <DEDENT> def _reload(self): <NEW_LINE> <INDENT> self.by_token = self._mappingFactory() <NEW_LINE> values = self._load() <NEW_LINE> self._reindex_by_token(values) <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> assert self.objectC is not None <NEW_LINE> values = self._load() <NEW_LINE> super(RDBVocabulary, self).__init__(values, *args, **kwargs) <NEW_LINE> <DEDENT> def _dict2token(self, token): <NEW_LINE> <INDENT> if isinstance(token, dict): <NEW_LINE> <INDENT> token = tuple([ token[p] for p in self.objectC.p_keys ]) <NEW_LINE> <DEDENT> return token <NEW_LINE> <DEDENT> def __getitem__(self, token): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(RDBVocabulary, self).__getitem__( self._dict2token(token)) <NEW_LINE> <DEDENT> except LookupError: <NEW_LINE> <INDENT> raise PersistenceError( 'Object `%s(%s)` is not found' % (self.objectC.__name__, token)) <NEW_LINE> <DEDENT> <DEDENT> def getTerm(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(RDBVocabulary, self).getTerm(value) <NEW_LINE> <DEDENT> except LookupError: <NEW_LINE> <INDENT> raise PersistenceError('Object `%s` is not found' % value) <NEW_LINE> <DEDENT> <DEDENT> def getTermByToken(self, token): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(RDBVocabulary, self).getTermByToken( self._dict2token(token)) <NEW_LINE> <DEDENT> except LookupError: <NEW_LINE> <INDENT> raise PersistenceError( 'Object `%s(%s)` is not found' % (self.objectC.__name__, token)) | Словарь объектов, загружаемых из БД | 62598fba851cf427c66b8424 |
class SaltApi(SaltDaemonScriptBase): <NEW_LINE> <INDENT> def get_script_args(self): <NEW_LINE> <INDENT> return ['-l', 'quiet'] <NEW_LINE> <DEDENT> def get_check_ports(self): <NEW_LINE> <INDENT> if 'rest_cherrypy' in self.config: <NEW_LINE> <INDENT> return [self.config['rest_cherrypy']['port']] <NEW_LINE> <DEDENT> if 'rest_tornado' in self.config: <NEW_LINE> <INDENT> return [self.config['rest_tornado']['port']] | Class which runs the salt-api daemon | 62598fba3317a56b869be605 |
class Negative(Dataset): <NEW_LINE> <INDENT> def __init__(self, sta_date_items): <NEW_LINE> <INDENT> self.sta_date_items = sta_date_items <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> train_paths_i, valid_paths_i = [], [] <NEW_LINE> sta_date, samples = self.sta_date_items[index] <NEW_LINE> net_sta, date = sta_date.split('_') <NEW_LINE> net, sta = net_sta.split('.') <NEW_LINE> date = UTCDateTime(date) <NEW_LINE> dtype = [('tp','O'),('ts','O')] <NEW_LINE> picks = np.array([tuple(sample[-3:-1]) for sample in samples if sample[-1]], dtype=dtype) <NEW_LINE> print('reading %s %s'%(net_sta, date.date)) <NEW_LINE> data_dict = get_data_dict(date, data_dir) <NEW_LINE> if net_sta not in data_dict: return train_paths_i, valid_paths_i <NEW_LINE> st_paths = data_dict[net_sta] <NEW_LINE> try: <NEW_LINE> <INDENT> stream = read(st_paths[0]) <NEW_LINE> stream += read(st_paths[1]) <NEW_LINE> stream += read(st_paths[2]) <NEW_LINE> <DEDENT> except: return train_paths_i, valid_paths_i <NEW_LINE> if to_filter: stream = preprocess(stream, samp_rate, freq_band) <NEW_LINE> if len(stream)!=3: return train_paths_i, valid_paths_i <NEW_LINE> for [samp_class, event_name, tp, ts, is_pick] in samples: <NEW_LINE> <INDENT> if sum(abs(picks['tp']-tp)<win_len)>0 and not is_pick: continue <NEW_LINE> out_dir = os.path.join(out_root, samp_class, 'negative', event_name) <NEW_LINE> samp_name = 'neg_%s_%s_%s'%(net,sta,event_name[:-3]) <NEW_LINE> n_aug = num_aug if samp_class=='train' else 1 <NEW_LINE> for aug_idx in range(n_aug): <NEW_LINE> <INDENT> start_time = tp + np.random.rand(1)[0]*min(rand_dt,2*(ts-tp)) <NEW_LINE> end_time = start_time + win_len <NEW_LINE> is_tp = (picks['tp']>max(ts, start_time)) * (picks['tp']<end_time) <NEW_LINE> is_ts = (picks['ts']>max(ts, start_time)) * (picks['ts']<end_time) <NEW_LINE> if sum(is_tp*is_ts)>0: continue <NEW_LINE> st = obspy_slice(stream, start_time, end_time) <NEW_LINE> if 0 in st.max() or len(st)!=3: continue <NEW_LINE> st = st.detrend('demean').normalize(global_max=global_max_norm) <NEW_LINE> if samp_class=='train': train_paths_i.append([]) <NEW_LINE> if samp_class=='valid': valid_paths_i.append([]) <NEW_LINE> for tr in st: <NEW_LINE> <INDENT> out_path = os.path.join(out_dir,'%s.%s.%s'%(aug_idx,samp_name,tr.stats.channel)) <NEW_LINE> tr.stats.sac.t1 = ts-start_time <NEW_LINE> tr.write(out_path, format='sac') <NEW_LINE> if samp_class=='train': train_paths_i[-1].append(out_path) <NEW_LINE> if samp_class=='valid': valid_paths_i[-1].append(out_path) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return train_paths_i, valid_paths_i <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.sta_date_items) | Dataset for cutting negative sample
| 62598fba377c676e912f6e27 |
class Resolver(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def resolve_srv(self, domain, service, protocol, callback): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def resolve_address(self, hostname, callback, allow_cname = True): <NEW_LINE> <INDENT> raise NotImplementedError | Abstract base class for asynchronous DNS resolvers to be used
with PyxMPP. | 62598fbafff4ab517ebcd951 |
class ModelInteritanceTestCase(unittest.TestCase): <NEW_LINE> <INDENT> @httpretty.activate <NEW_LINE> def test_inheritantce_full(self): <NEW_LINE> <INDENT> httpretty.register_uri( httpretty.GET, 'http://petstore.swagger.wordnik.com/api/user/mary', status=200, body=json.dumps(uwi_mary) ) <NEW_LINE> resp = client.request(app.op['getUserByName'](username='mary')) <NEW_LINE> self.assertTrue(isinstance(resp.data, Model)) <NEW_LINE> m = resp.data <NEW_LINE> self.assertEqual(m.id, 2) <NEW_LINE> self.assertEqual(m.username, 'mary') <NEW_LINE> self.assertEqual(m.email, 'm@a.ry') <NEW_LINE> self.assertEqual(m.phone, '123') <NEW_LINE> self.assertEqual(m.sub_type, 'UserWithInfo') <NEW_LINE> <DEDENT> @httpretty.activate <NEW_LINE> def test_inheritance_partial(self): <NEW_LINE> <INDENT> httpretty.register_uri( httpretty.GET, 'http://petstore.swagger.wordnik.com/api/user/kevin', status=200, body=json.dumps(uwi_kevin) ) <NEW_LINE> resp = client.request(app.op['getUserByName'](username='kevin')) <NEW_LINE> self.assertTrue(isinstance(resp.data, Model)) <NEW_LINE> m = resp.data <NEW_LINE> self.assertEqual(m.id, 3) <NEW_LINE> self.assertEqual(m.username, 'kevin') <NEW_LINE> self.assertEqual(m.email, None) <NEW_LINE> self.assertEqual(m.phone, None) <NEW_LINE> self.assertEqual(m.sub_type, 'UserWithInfo') <NEW_LINE> <DEDENT> def test_inheritance_root(self): <NEW_LINE> <INDENT> req, _ = app.op['createUser'](body=u_mission) <NEW_LINE> req.prepare() <NEW_LINE> self.assertTrue(isinstance(req._p['body']['body'], Model)) <NEW_LINE> m = req._p['body']['body'] <NEW_LINE> self.assertEqual(m.id, 1) <NEW_LINE> self.assertEqual(m.username, 'mission') <NEW_LINE> self.assertEqual(m.sub_type, 'User') <NEW_LINE> self.assertRaises(KeyError, getattr, m, 'email') <NEW_LINE> self.assertRaises(KeyError, getattr, m, 'email') | test cases for model inheritance | 62598fba656771135c4897dd |
class LimeTextExplainer(object): <NEW_LINE> <INDENT> def __init__(self, kernel_width=25, verbose=False, class_names=None, feature_selection='auto', split_expression=r'\W+', bow=True): <NEW_LINE> <INDENT> kernel = lambda d: np.sqrt(np.exp(-(d**2) / kernel_width ** 2)) <NEW_LINE> self.base = lime_base.LimeBase(kernel, verbose) <NEW_LINE> self.class_names = class_names <NEW_LINE> self.vocabulary = None <NEW_LINE> self.feature_selection = feature_selection <NEW_LINE> self.bow = bow <NEW_LINE> self.split_expression = split_expression <NEW_LINE> <DEDENT> def explain_instance(self, text_instance, classifier_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000): <NEW_LINE> <INDENT> indexed_string = IndexedString(text_instance, bow=self.bow, split_expression=self.split_expression) <NEW_LINE> domain_mapper = TextDomainMapper(indexed_string) <NEW_LINE> data, yss, distances = self.__data_labels_distances( indexed_string, classifier_fn, num_samples) <NEW_LINE> if self.class_names is None: <NEW_LINE> <INDENT> self.class_names = [str(x) for x in range(yss[0].shape[0])] <NEW_LINE> <DEDENT> ret_exp = explanation.Explanation(domain_mapper=domain_mapper, class_names=self.class_names) <NEW_LINE> ret_exp.predict_proba = yss[0] <NEW_LINE> if top_labels: <NEW_LINE> <INDENT> labels = np.argsort(yss[0])[-top_labels:] <NEW_LINE> ret_exp.top_labels = list(labels) <NEW_LINE> ret_exp.top_labels.reverse() <NEW_LINE> <DEDENT> for label in labels: <NEW_LINE> <INDENT> ret_exp.intercept[label], ret_exp.local_exp[label] = self.base.explain_instance_with_data( data, yss, distances, label, num_features, feature_selection=self.feature_selection) <NEW_LINE> <DEDENT> return ret_exp <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def __data_labels_distances(cls, indexed_string, classifier_fn, num_samples): <NEW_LINE> <INDENT> distance_fn = lambda x: sklearn.metrics.pairwise.cosine_distances(x[0], x)[0] * 100 <NEW_LINE> doc_size = indexed_string.num_words() <NEW_LINE> sample = np.random.randint(1, doc_size + 1, num_samples - 1) <NEW_LINE> data = np.ones((num_samples, doc_size)) <NEW_LINE> data[0] = np.ones(doc_size) <NEW_LINE> features_range = range(doc_size) <NEW_LINE> inverse_data = [indexed_string.raw_string()] <NEW_LINE> for i, size in enumerate(sample, start=1): <NEW_LINE> <INDENT> inactive = np.random.choice(features_range, size, replace=False) <NEW_LINE> data[i, inactive] = 0 <NEW_LINE> inverse_data.append(indexed_string.inverse_removing(inactive)) <NEW_LINE> <DEDENT> labels = classifier_fn(inverse_data) <NEW_LINE> distances = distance_fn(sp.sparse.csr_matrix(data)) <NEW_LINE> return data, labels, distances | Explains text classifiers.
Currently, we are using an exponential kernel on cosine distance, and
restricting explanations to words that are present in documents. | 62598fba498bea3a75a57c92 |
class Thing: <NEW_LINE> <INDENT> def draw(self, camera): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> pass | Base class for all entities that may contain behavior. | 62598fbad486a94d0ba2c13d |
class ProgBar(Prog): <NEW_LINE> <INDENT> def __init__(self, iterations, track_time=True, width=30, bar_char='#', stream=2, title='', monitor=False, update_interval=None): <NEW_LINE> <INDENT> Prog.__init__(self, iterations, track_time, stream, title, monitor, update_interval) <NEW_LINE> self.bar_width = width <NEW_LINE> self._adjust_width() <NEW_LINE> self.bar_char = bar_char <NEW_LINE> self.last_progress = 0 <NEW_LINE> self._print_labels() <NEW_LINE> self._print_progress_bar(0) <NEW_LINE> if monitor: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.process.cpu_percent() <NEW_LINE> self.process.memory_percent() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.process.get_cpu_percent() <NEW_LINE> self.process.get_memory_percent() <NEW_LINE> <DEDENT> <DEDENT> if self.item_id: <NEW_LINE> <INDENT> self._print_item_id() <NEW_LINE> <DEDENT> <DEDENT> def _adjust_width(self): <NEW_LINE> <INDENT> if self.bar_width > self.max_iter: <NEW_LINE> <INDENT> self.bar_width = int(self.max_iter) <NEW_LINE> <DEDENT> <DEDENT> def _print_labels(self): <NEW_LINE> <INDENT> self._stream_out('0% {} 100%\n'.format(' ' * (self.bar_width - 6))) <NEW_LINE> self._stream_flush() <NEW_LINE> <DEDENT> def _print_progress_bar(self, progress): <NEW_LINE> <INDENT> remaining = self.bar_width - progress <NEW_LINE> self._stream_out('[{}{}]'.format(self.bar_char * int(progress), ' ' * int(remaining))) <NEW_LINE> self._stream_flush() <NEW_LINE> <DEDENT> def _print(self, force_flush=False): <NEW_LINE> <INDENT> progress = floor(self._calc_percent() / 100 * self.bar_width) <NEW_LINE> if self.update_interval: <NEW_LINE> <INDENT> do_update = time.time() - self.last_time >= self.update_interval <NEW_LINE> <DEDENT> elif force_flush: <NEW_LINE> <INDENT> do_update = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> do_update = progress > self.last_progress <NEW_LINE> <DEDENT> if do_update and self.active: <NEW_LINE> <INDENT> self._stream_out('\r') <NEW_LINE> self._print_progress_bar(progress) <NEW_LINE> if self.track: <NEW_LINE> <INDENT> self._print_eta() <NEW_LINE> <DEDENT> if self.item_id: <NEW_LINE> <INDENT> self._print_item_id() <NEW_LINE> <DEDENT> <DEDENT> self.last_progress = progress | Initializes a progress bar object that allows visuzalization
of an iterational computation in the standard output screen.
Parameters
----------
iterations : `int`
Number of iterations for the iterative computation.
track_time : `bool` (default: `True`)
Prints elapsed time when loop has finished.
width : `int` (default: 30)
Sets the progress bar width in characters.
stream : `int` (default: 2).
Setting the output stream.
Takes `1` for stdout, `2` for stderr, or a custom stream object
title : `str` (default: `''`)
Setting a title for the progress bar.
monitor : `bool` (default: False)
Monitors CPU and memory usage if `True` (requires `psutil` package).
update_interval : float or int (default: None)
The update_interval in seconds controls how often the progress
is flushed to the screen.
Automatic mode if update_interval=None. | 62598fba627d3e7fe0e07021 |
class EnableWhenDialog(HasTraits): <NEW_LINE> <INDENT> bool_item = Bool(True) <NEW_LINE> labelled_item = Str("test") <NEW_LINE> unlabelled_item = Str("test") <NEW_LINE> traits_view = View( VGroup( Item("bool_item"), Item("labelled_item", enabled_when="bool_item"), Item( "unlabelled_item", enabled_when="bool_item", show_label=False ), ), resizable=True, ) | Test labels for enable when. | 62598fbaa8370b77170f054e |
class MultiDataframeAnalysis(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.logger = get_logger() <NEW_LINE> return super().__init__(**kwargs) <NEW_LINE> <DEDENT> def tiingo_fred_dataframe_merge(self, tiingo_symbol_list, tiingo_start_date, tiingo_end_date, class_of_data, local_symbol): <NEW_LINE> <INDENT> source = 'Tiingo' <NEW_LINE> tdo_df = TiingoDataObject(start_date = tiingo_start_date, end_date = tiingo_end_date, source = source, symbols = tiingo_symbol_list) <NEW_LINE> qdo_df = QuandlDataObject(class_of_data, local_symbol, '.csv').get_df() <NEW_LINE> return_df_dict = {} <NEW_LINE> for tiingo_symbol in tiingo_symbol_list: <NEW_LINE> <INDENT> tdo_df = tdo_df.get_px_data_df()[tiingo_symbol] <NEW_LINE> tdo_df = tdo_df.reset_index() <NEW_LINE> qdo_df = qdo_df.reset_index() <NEW_LINE> merged = pd.merge_asof(tdo_df, qdo_df, left_on = 'date', right_on = 'Date') <NEW_LINE> merged = merged.resample('Q', on='date')[['adjClose', 'adjHigh', 'adjLow', 'adjOpen', 'adjVolume']].ohlc() <NEW_LINE> return_df_dict[tiingo_symbol] = merged <NEW_LINE> <DEDENT> return (return_df_dict) | description of class | 62598fba097d151d1a2c11a2 |
class button(object): <NEW_LINE> <INDENT> def __init__(self, text = None, x = None, y = None, w = 10, h = 10, color = None, tColor = None, fnt = None): <NEW_LINE> <INDENT> self.rect = pygame.Rect(x, y, w, h) <NEW_LINE> self.x, self.y, self.w, self.h = x, y, w, h <NEW_LINE> self.text = text <NEW_LINE> self.color = color <NEW_LINE> self.tColor = tColor <NEW_LINE> self.fnt = fnt <NEW_LINE> <DEDENT> def draw(self, window): <NEW_LINE> <INDENT> pygame.draw.rect(window, self.color, self.rect) <NEW_LINE> txt = self.fnt.render(self.text, True, self.tColor) <NEW_LINE> window.blit(txt, (self.x + self.w / 2 - txt.get_width() / 2, self.y + self.h / 2 - txt.get_height() / 2)) <NEW_LINE> <DEDENT> def clicked(self, mpos): <NEW_LINE> <INDENT> if self.x < mpos[0] < self.x + self.w and self.y < mpos[1] < self.y + self.h: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Class to store and operate on button. | 62598fbaa8370b77170f054f |
class IndexConfig(object): <NEW_LINE> <INDENT> def __init__(self, ttl=1, line_config=None, key_config_list=None, all_keys_config=None): <NEW_LINE> <INDENT> if key_config_list is None: <NEW_LINE> <INDENT> key_config_list = {} <NEW_LINE> <DEDENT> self.ttl = ttl <NEW_LINE> self.all_keys_config = all_keys_config <NEW_LINE> self.line_config = line_config <NEW_LINE> self.key_config_list = key_config_list <NEW_LINE> self.modify_time = int(time.time()) <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> json_value = {} <NEW_LINE> if self.line_config is not None: <NEW_LINE> <INDENT> json_value["line"] = self.line_config.to_json() <NEW_LINE> <DEDENT> if len(self.key_config_list) != 0: <NEW_LINE> <INDENT> json_value["keys"] = dict((key, value.to_json()) for key, value in self.key_config_list.items()) <NEW_LINE> <DEDENT> if self.all_keys_config is not None: <NEW_LINE> <INDENT> json_value["all_keys"] = self.all_keys_config.to_json() <NEW_LINE> <DEDENT> return json_value <NEW_LINE> <DEDENT> def from_json(self, json_value): <NEW_LINE> <INDENT> self.ttl = json_value.get("ttl", 0) <NEW_LINE> if "all_keys" in json_value: <NEW_LINE> <INDENT> self.all_keys_config = IndexKeyConfig() <NEW_LINE> self.all_keys_config.from_json(json_value["all_keys"]) <NEW_LINE> <DEDENT> if "line" in json_value: <NEW_LINE> <INDENT> self.line_config = IndexLineConfig() <NEW_LINE> self.line_config.from_json(json_value["line"]) <NEW_LINE> <DEDENT> if "keys" in json_value: <NEW_LINE> <INDENT> self.key_config_list = {} <NEW_LINE> key_configs = json_value["keys"] <NEW_LINE> for key, value in key_configs.items(): <NEW_LINE> <INDENT> key_config = IndexKeyConfig() <NEW_LINE> key_config.from_json(value) <NEW_LINE> self.key_config_list[key] = key_config <NEW_LINE> <DEDENT> <DEDENT> self.modify_time = json_value.get("lastModifyTime", int(time.time())) | The index config of a logstore
:type ttl: int
:param ttl: this parameter is deprecated, the ttl is same as logstore's ttl
:type line_config: IndexLineConfig
:param line_config: the index config of the whole log line
:type key_config_list: dict
:param key_config_list: dict (string => IndexKeyConfig), the index key configs of the keys
:type all_keys_config: IndexKeyConfig
:param all_keys_config: the key config of all keys, the new create logstore should never user this param, it only used to compatible with old config | 62598fba5fc7496912d48333 |
class Renderer: <NEW_LINE> <INDENT> def __init__(self, map_size, fig_width=8): <NEW_LINE> <INDENT> self.fig_width = fig_width <NEW_LINE> self.map_size = map_size <NEW_LINE> scale = 1. / self.map_size <NEW_LINE> self.text_coordinates_scale_transform = np.array([ [scale[0], 0], [0, scale[1]] ]) <NEW_LINE> self.coordinate_switch_transform = np.array([ [0, 1], [1, 0] ]) <NEW_LINE> self.text_coordinates_offset = np.array([0.5*scale[1], 0.5*scale[0]]) <NEW_LINE> <DEDENT> def tile_to_text_coords(self, row, column): <NEW_LINE> <INDENT> grid_coords = np.array([self.map_size[0] - 1 - row, column]) <NEW_LINE> scaled_coords = np.dot(self.text_coordinates_scale_transform, grid_coords) <NEW_LINE> return np.dot(self.coordinate_switch_transform, scaled_coords) + self.text_coordinates_offset <NEW_LINE> <DEDENT> def draw_tile(self, ax, row, column, object_code, text=None): <NEW_LINE> <INDENT> verts = [ (column, row+1), (column, row), (column+1, row), (column+1, row+1), (column, row+1), ] <NEW_LINE> codes = [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] <NEW_LINE> path = Path(verts, codes) <NEW_LINE> ax.add_patch(patches.PathPatch(path, facecolor='white', lw=TILE_LINE_WIDTH)) <NEW_LINE> patch = patches.PathPatch(path, facecolor=OBJECT_COLORS[object_code], lw=TILE_LINE_WIDTH) <NEW_LINE> ax.add_patch(patch) <NEW_LINE> if text is not None: <NEW_LINE> <INDENT> coords = self.tile_to_text_coords(row, column) <NEW_LINE> ax.text( coords[0], coords[1], text, horizontalalignment='center', verticalalignment='center', fontsize=10, color='black', transform=ax.transAxes ) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def configure_axis_ticks(axis, set_lim, size): <NEW_LINE> <INDENT> axis.set_major_locator(ticker.NullLocator()) <NEW_LINE> axis.set_major_formatter(ticker.NullFormatter()) <NEW_LINE> axis.set_minor_locator(ticker.FixedLocator(0.5 + np.arange(size))) <NEW_LINE> axis.set_minor_formatter(ticker.FuncFormatter(lambda x, pos: '{}'.format(int(x-0.5)))) <NEW_LINE> set_lim(0, size) <NEW_LINE> <DEDENT> def render_matplotlib(self, ar): <NEW_LINE> <INDENT> fig_height = self.fig_width*float(self.map_size[0])/self.map_size[1] <NEW_LINE> fig = plt.figure(figsize=(self.fig_width, fig_height)) <NEW_LINE> fig.canvas.set_window_title(SIMULATION_NAME) <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> ax.grid() <NEW_LINE> self.configure_axis_ticks(ax.xaxis, ax.set_xlim, self.map_size[1]) <NEW_LINE> self.configure_axis_ticks(ax.yaxis, ax.set_ylim, self.map_size[0]) <NEW_LINE> ax.invert_yaxis() <NEW_LINE> ax.xaxis.tick_top() <NEW_LINE> for row in range(self.map_size[0]): <NEW_LINE> <INDENT> for column in range(self.map_size[1]): <NEW_LINE> <INDENT> self.draw_tile(ax, row, column, ar[row, column], text='{0}{1}'.format(row, column)) <NEW_LINE> <DEDENT> <DEDENT> plt.show() | Notes: Tile size is always (width=1, height=1) | 62598fbaf548e778e596b715 |
class TestReplenishment(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 testReplenishment(self): <NEW_LINE> <INDENT> pass | Replenishment unit test stubs | 62598fba851cf427c66b8426 |
class DefaultNonExpiringCacheKeyTests(SimpleTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.DEFAULT_TIMEOUT = caches[DEFAULT_CACHE_ALIAS].default_timeout <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> del(self.DEFAULT_TIMEOUT) <NEW_LINE> <DEDENT> def test_default_expiration_time_for_keys_is_5_minutes(self): <NEW_LINE> <INDENT> self.assertEqual(300, self.DEFAULT_TIMEOUT) <NEW_LINE> <DEDENT> def test_caches_with_unset_timeout_has_correct_default_timeout(self): <NEW_LINE> <INDENT> cache = caches[DEFAULT_CACHE_ALIAS] <NEW_LINE> self.assertEqual(self.DEFAULT_TIMEOUT, cache.default_timeout) <NEW_LINE> <DEDENT> @override_settings(CACHES=NEVER_EXPIRING_CACHES_SETTINGS) <NEW_LINE> def test_caches_set_with_timeout_as_none_has_correct_default_timeout(self): <NEW_LINE> <INDENT> cache = caches[DEFAULT_CACHE_ALIAS] <NEW_LINE> self.assertIsNone(cache.default_timeout) <NEW_LINE> self.assertIsNone(cache.get_backend_timeout()) <NEW_LINE> <DEDENT> @override_settings(CACHES=DEFAULT_MEMORY_CACHES_SETTINGS) <NEW_LINE> def test_caches_with_unset_timeout_set_expiring_key(self): <NEW_LINE> <INDENT> key = "my-key" <NEW_LINE> value = "my-value" <NEW_LINE> cache = caches[DEFAULT_CACHE_ALIAS] <NEW_LINE> cache.set(key, value) <NEW_LINE> cache_key = cache.make_key(key) <NEW_LINE> self.assertIsNotNone(cache._expire_info[cache_key]) <NEW_LINE> <DEDENT> @override_settings(CACHES=NEVER_EXPIRING_CACHES_SETTINGS) <NEW_LINE> def test_caches_set_with_timeout_as_none_set_non_expiring_key(self): <NEW_LINE> <INDENT> key = "another-key" <NEW_LINE> value = "another-value" <NEW_LINE> cache = caches[DEFAULT_CACHE_ALIAS] <NEW_LINE> cache.set(key, value) <NEW_LINE> cache_key = cache.make_key(key) <NEW_LINE> self.assertIsNone(cache._expire_info[cache_key]) | Tests that verify that settings having Cache arguments with a TIMEOUT
set to `None` will create Caches that will set non-expiring keys.
This fixes ticket #22085. | 62598fbad7e4931a7ef3c206 |
class Plotter: <NEW_LINE> <INDENT> def __init__(self, n_predictions): <NEW_LINE> <INDENT> self.fig = plt.axes() <NEW_LINE> self.legend = [] <NEW_LINE> self.n_predictions = n_predictions <NEW_LINE> self.fig.set_xticks(range(1,n_predictions)) <NEW_LINE> self.TARGET_FEATURE = 0 <NEW_LINE> <DEDENT> def plot(self,y_data,name,batch_size,batch_id=0): <NEW_LINE> <INDENT> y_data = y_data[:,:,self.TARGET_FEATURE] <NEW_LINE> plot_data = y_data.reshape((batch_size,self.n_predictions))[batch_id] <NEW_LINE> self.fig.plot(plot_data) <NEW_LINE> self.legend.append(name) <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> self.fig.legend(self.legend) <NEW_LINE> plt.show() | Responsible for plotting data | 62598fba9c8ee8231304022c |
class RequestSensingAgent(AbstractAgent): <NEW_LINE> <INDENT> def __init__(self, horizon, inventory_size, requests, environment, num_sequences=1000, seed=1): <NEW_LINE> <INDENT> super(RequestSensingAgent, self).__init__(horizon, inventory_size, requests, environment, num_sequences, seed) <NEW_LINE> self.actions = [ actions.AddEdge, actions.TakeEdge, actions.RemoveRequest, actions.AddRequest, actions.DoNothing ] <NEW_LINE> self.type = REQUEST_SENSING_AGENT <NEW_LINE> <DEDENT> def sense(self): <NEW_LINE> <INDENT> return self.filter(self.environment.routed_requests.keys()) <NEW_LINE> <DEDENT> def estimate_empowerment(self): <NEW_LINE> <INDENT> states = [] <NEW_LINE> for i in range(self.num_sequences): <NEW_LINE> <INDENT> actions = [] <NEW_LINE> for action in self.random_action_sequence(): <NEW_LINE> <INDENT> actions.append(action) <NEW_LINE> action.apply() <NEW_LINE> <DEDENT> state = self.sense() <NEW_LINE> self.add_new_reading(state, states) <NEW_LINE> actions.reverse() <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> action.rollback() <NEW_LINE> <DEDENT> <DEDENT> if self.sensing_threshold is None: <NEW_LINE> <INDENT> average_embedded = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if type(states[0]) == int: <NEW_LINE> <INDENT> average_embedded = np.mean(states) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> average_embedded = np.mean([a.size for a in states]) <NEW_LINE> <DEDENT> <DEDENT> return np.log(len(states)), average_embedded <NEW_LINE> <DEDENT> def choose_next_action(self): <NEW_LINE> <INDENT> best_actions = [] <NEW_LINE> best_empowerment = 0 <NEW_LINE> average_embedded = [] <NEW_LINE> for action_class in self.actions: <NEW_LINE> <INDENT> action = action_class(self) <NEW_LINE> action.apply() <NEW_LINE> empowerment, avg_embd = self.estimate_empowerment() <NEW_LINE> average_embedded.append(avg_embd) <NEW_LINE> action.rollback() <NEW_LINE> if empowerment == best_empowerment: <NEW_LINE> <INDENT> best_actions.append(action) <NEW_LINE> <DEDENT> elif empowerment > best_empowerment: <NEW_LINE> <INDENT> best_actions = [action] <NEW_LINE> best_empowerment = empowerment <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> if self.sensing_threshold is not None: <NEW_LINE> <INDENT> tmp = np.max(average_embedded) <NEW_LINE> if tmp > self.sensing_threshold: <NEW_LINE> <INDENT> self.sensing_threshold = tmp <NEW_LINE> <DEDENT> <DEDENT> return best_actions[self.random.randint(0, len(best_actions))], best_empowerment <NEW_LINE> <DEDENT> def choose_request_to_place(self): <NEW_LINE> <INDENT> return self.sample_request() <NEW_LINE> <DEDENT> def choose_request_to_remove(self): <NEW_LINE> <INDENT> return self.sample_request_to_remove() | Agent that can manipulate edges and requests. It perceives exactly the set
of requests that are currently served in the topology. | 62598fba442bda511e95c5cc |
class MainPage(AbstractPage): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> AbstractPage.__init__(self) <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> return render_template("main_page.html") | Main page of the site, where we can send a link | 62598fba7c178a314d78d60f |
class config(luigi.Config): <NEW_LINE> <INDENT> star = luigi.Parameter(description="Path to the STAR executable") <NEW_LINE> star_params = luigi.Parameter(description="Params for STAR") <NEW_LINE> star_load_params = luigi.Parameter(description="Params for STAR to load a genome file") <NEW_LINE> genome_dir = luigi.Parameter(description="The path to the star index dir") <NEW_LINE> seqtype = luigi.Parameter(description="Whether this is a targetted or wts experiment") <NEW_LINE> primer_file = luigi.Parameter(description="The primer file,if wts this is not applicable") <NEW_LINE> annotation_gtf = luigi.Parameter(description="Gencode annotation file") <NEW_LINE> ercc_bed = luigi.Parameter(description="ERCC bed file with coordinate information") <NEW_LINE> is_low_input = luigi.Parameter(description="Whether the sequencing protocol was for a low input application") <NEW_LINE> catalog_number = luigi.Parameter(description="The catalog number for this primer pool") <NEW_LINE> species = luigi.Parameter(description="The species name") <NEW_LINE> genome = luigi.Parameter(description="The reference genome build version",default="Unknown") <NEW_LINE> annotation = luigi.Parameter(description="The genome annotation version",default="Unknown") <NEW_LINE> editdist = luigi.IntParameter(description="Whether to allow a single base mismatch in the cell index") <NEW_LINE> cell_indices_used = luigi.Parameter(description="Comma delimeted list of Cell Ids to use , i.e. C1,C2,C3,etc. If using all cell indices in the file , please specify 'all' here.") <NEW_LINE> buffer_size = luigi.IntParameter(description="Read this many MB from fastq file to memory for each read pair for each cpu",default=16) | Initialize values from configuration file
| 62598fba10dbd63aa1c70d2a |
class UserDebugPanel(DebugPanel): <NEW_LINE> <INDENT> name = 'User' <NEW_LINE> has_content = True <NEW_LINE> def title(self): <NEW_LINE> <INDENT> return 'Users' <NEW_LINE> <DEDENT> def url(self): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> def process_request(self, request): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> <DEDENT> def content(self): <NEW_LINE> <INDENT> groups = Group.objects.all() <NEW_LINE> context = { 'groups': groups, 'active_user': self.request.user, 'all_users': get_debug_users(), } <NEW_LINE> return render_to_string('debug_toolbar/panels/users.html', context) <NEW_LINE> <DEDENT> def get_custom_permissions(self): <NEW_LINE> <INDENT> from django.contrib.contenttypes.models import ContentType <NEW_LINE> from django.db.models import get_models <NEW_LINE> permissions = [] <NEW_LINE> for klass in get_models(): <NEW_LINE> <INDENT> if klass._meta.permissions: <NEW_LINE> <INDENT> ctype = ContentType.objects.get_for_model(klass) <NEW_LINE> permissions.append((ctype, klass._meta.permissions )) <NEW_LINE> <DEDENT> <DEDENT> return permissions | A panel to show info about the current user and allow to switch user
access. | 62598fba656771135c4897de |
class TestUser(unittest.TestCase): <NEW_LINE> <INDENT> def test_City_inheritance(self): <NEW_LINE> <INDENT> new_city = City() <NEW_LINE> self.assertIsInstance(new_city, BaseModel) <NEW_LINE> <DEDENT> def test_City_attributes(self): <NEW_LINE> <INDENT> new_city = City() <NEW_LINE> self.assertTrue("state_id" in new_city.__dir__()) <NEW_LINE> self.assertTrue("name" in new_city.__dir__()) <NEW_LINE> <DEDENT> def test_City_type_name(self): <NEW_LINE> <INDENT> new_city = City() <NEW_LINE> name = getattr(new_city, "name") <NEW_LINE> self.assertIsInstance(name, str) <NEW_LINE> <DEDENT> def test_City_type_name(self): <NEW_LINE> <INDENT> new_city = City() <NEW_LINE> name = getattr(new_city, "state_id") <NEW_LINE> self.assertIsInstance(name, str) | Testing User class | 62598fba2c8b7c6e89bd3936 |
class Column(object): <NEW_LINE> <INDENT> def __init__(self, name, ctype, nullable, primary_key, autoincrement, server_default, symbols): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._ctype = ctype <NEW_LINE> self._nullable = nullable <NEW_LINE> self._primary_key = primary_key <NEW_LINE> self._autoincrement = autoincrement <NEW_LINE> self._server_default = server_default <NEW_LINE> self._symbols = symbols <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_sa(cls, column, symbols): <NEW_LINE> <INDENT> return cls( column.name, _type.Type.by_column(column, symbols), nullable=column.nullable, primary_key=column.primary_key, autoincrement=column.autoincrement, server_default=column.server_default, symbols=symbols, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> params = list(map(repr, (self._name, self._ctype))) <NEW_LINE> if not self._nullable: <NEW_LINE> <INDENT> params.append('nullable=%r' % (False,)) <NEW_LINE> <DEDENT> if not self._autoincrement and self._primary_key: <NEW_LINE> <INDENT> params.append('autoincrement=%r' % (False,)) <NEW_LINE> <DEDENT> if self._server_default is not None: <NEW_LINE> <INDENT> params.append('server_default=%r' % ( ServerDefault(self._server_default, self._symbols), )) <NEW_LINE> <DEDENT> return "%s(%s)" % ( self._symbols['column'], ', '.join(params) ) | Column container
Attributes:
_name (unicode):
Name
_ctype (SA type):
Column type
_nullable (bool):
Nullable?
_primary_key (bool):
Part of a primary key?
_autoincrement (bool):
Possible autoincrement?
_server_default (Default clause):
Default clause
_symbols (Symbols):
Symbol table | 62598fba167d2b6e312b70e6 |
class RiscoSensor(CoordinatorEntity): <NEW_LINE> <INDENT> def __init__(self, coordinator, category_id, excludes, name, entry_id) -> None: <NEW_LINE> <INDENT> super().__init__(coordinator) <NEW_LINE> self._event = None <NEW_LINE> self._category_id = category_id <NEW_LINE> self._excludes = excludes <NEW_LINE> self._name = name <NEW_LINE> self._entry_id = entry_id <NEW_LINE> self._entity_registry = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return f"Risco {self.coordinator.risco.site_name} {self._name} Events" <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return f"events_{self._name}_{self.coordinator.risco.site_uuid}" <NEW_LINE> <DEDENT> async def async_added_to_hass(self): <NEW_LINE> <INDENT> self._entity_registry = ( await self.hass.helpers.entity_registry.async_get_registry() ) <NEW_LINE> self.async_on_remove( self.coordinator.async_add_listener(self._refresh_from_coordinator) ) <NEW_LINE> <DEDENT> def _refresh_from_coordinator(self): <NEW_LINE> <INDENT> events = self.coordinator.data <NEW_LINE> for event in reversed(events): <NEW_LINE> <INDENT> if event.category_id in self._excludes: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if self._category_id is not None and event.category_id != self._category_id: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self._event = event <NEW_LINE> self.async_write_ha_state() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> if self._event is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._event.time <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> if self._event is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attrs = {atr: getattr(self._event, atr, None) for atr in EVENT_ATTRIBUTES} <NEW_LINE> if self._event.zone_id is not None: <NEW_LINE> <INDENT> zone_unique_id = binary_sensor_unique_id( self.coordinator.risco, self._event.zone_id ) <NEW_LINE> zone_entity_id = self._entity_registry.async_get_entity_id( BS_DOMAIN, DOMAIN, zone_unique_id ) <NEW_LINE> if zone_entity_id is not None: <NEW_LINE> <INDENT> attrs["zone_entity_id"] = zone_entity_id <NEW_LINE> <DEDENT> <DEDENT> return attrs <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_class(self): <NEW_LINE> <INDENT> return DEVICE_CLASS_TIMESTAMP | Sensor for Risco events. | 62598fbad486a94d0ba2c13f |
class NodeResize(Layer): <NEW_LINE> <INDENT> def __init__(self, index, cur_channels, start_size, tr_conv_kernel, fabric, **kwargs): <NEW_LINE> <INDENT> self.index = index <NEW_LINE> self.cur_channels = cur_channels <NEW_LINE> self.start_size = start_size <NEW_LINE> self.tr_conv_kernel = tr_conv_kernel <NEW_LINE> self.fabric_size = fabric.size <NEW_LINE> self.conv_param = dict( activation=None, kernel_size=3, padding='same', use_bias=False ) <NEW_LINE> self.output_dim = self.start_size / (2**(self.index[1])) <NEW_LINE> self.fabric = fabric <NEW_LINE> super(NodeResize, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> tensors = [] <NEW_LINE> for in_tensor in x: <NEW_LINE> <INDENT> shape = K.int_shape(in_tensor) <NEW_LINE> if shape[1] == self.output_dim: <NEW_LINE> <INDENT> tensor = Conv2D(self.cur_channels, strides=1, **self.conv_param)(in_tensor) <NEW_LINE> tensors.append(tensor) <NEW_LINE> <DEDENT> if shape[1] > self.output_dim: <NEW_LINE> <INDENT> tensor = Conv2D(self.cur_channels, strides=2, **self.conv_param)(in_tensor) <NEW_LINE> tensors.append(tensor) <NEW_LINE> <DEDENT> if shape[1] < self.output_dim: <NEW_LINE> <INDENT> tensor = Lambda( lambda x: K.resize_images(x, 2, 2, 'channels_last') )(in_tensor) <NEW_LINE> tensors.append(tensor) <NEW_LINE> <DEDENT> <DEDENT> if len(tensors) > 1: <NEW_LINE> <INDENT> tensor = Add()(tensors) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tensor = tensors[0] <NEW_LINE> <DEDENT> tensor = BatchNormalization()(tensor) <NEW_LINE> tensor = Activation('relu')(tensor) <NEW_LINE> return tensor <NEW_LINE> <DEDENT> def compute_output_shape(self, input_shape): <NEW_LINE> <INDENT> return (self.output_dim, self.output_dim, self.cur_channels) | Docstring for Node. | 62598fba091ae35668704d93 |
class Test_Wrappers( unittest.TestCase ): <NEW_LINE> <INDENT> def wrap_ok(self, wrapper, base): <NEW_LINE> <INDENT> print( wrapper ) <NEW_LINE> self.assertEqual( list(wrapper(iter(base))), list(base) ) <NEW_LINE> self.assertEqual( [i for i in wrapper(iter(base))], [i for i in base] ) <NEW_LINE> <DEDENT> def test_wrappers(self, base=range(3)): <NEW_LINE> <INDENT> for wrapper in wrappers: <NEW_LINE> <INDENT> self.wrap_ok( wrapper, base ) | Test the wrapping of iterator wrappers | 62598fbaa8370b77170f0551 |
class LogBuffer(eclib.OutputBuffer): <NEW_LINE> <INDENT> RE_WARN_MSG = re.compile(r'\[err\]|\[error\]|\[warn\]') <NEW_LINE> ERROR_STYLE = eclib.OPB_STYLE_MAX + 1 <NEW_LINE> def __init__(self, parent): <NEW_LINE> <INDENT> eclib.OutputBuffer.__init__(self, parent) <NEW_LINE> self._filter = SHOW_ALL_MSG <NEW_LINE> self._srcs = list() <NEW_LINE> self.SetLineBuffering(2000) <NEW_LINE> font = Profile_Get('FONT1', 'font', wx.Font(11, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) <NEW_LINE> self.SetFont(font) <NEW_LINE> style = (font.GetFaceName(), font.GetPointSize(), "#FF0000") <NEW_LINE> self.StyleSetSpec(LogBuffer.ERROR_STYLE, "face:%s,size:%d,fore:#FFFFFF,back:%s" % style) <NEW_LINE> ed_msg.Subscribe(self.UpdateLog, ed_msg.EDMSG_LOG_ALL) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> ed_msg.Unsubscribe(self.UpdateLog, ed_msg.EDMSG_LOG_ALL) <NEW_LINE> super(LogBuffer, self).__del__() <NEW_LINE> <DEDENT> def AddFilter(self, src): <NEW_LINE> <INDENT> if src not in self._srcs: <NEW_LINE> <INDENT> self._srcs.append(src) <NEW_LINE> self.GetParent().SetSources(self._srcs) <NEW_LINE> <DEDENT> <DEDENT> def ApplyStyles(self, start, txt): <NEW_LINE> <INDENT> for group in LogBuffer.RE_WARN_MSG.finditer(txt): <NEW_LINE> <INDENT> sty_s = start + group.start() <NEW_LINE> sty_e = start + group.end() <NEW_LINE> self.StartStyling(sty_s, 0xff) <NEW_LINE> self.SetStyling(sty_e - sty_s, LogBuffer.ERROR_STYLE) <NEW_LINE> <DEDENT> <DEDENT> def SetFilter(self, src): <NEW_LINE> <INDENT> if src in self._srcs: <NEW_LINE> <INDENT> self._filter = src <NEW_LINE> return True <NEW_LINE> <DEDENT> elif src == _("All"): <NEW_LINE> <INDENT> self._filter = SHOW_ALL_MSG <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def UpdateLog(self, msg): <NEW_LINE> <INDENT> if not self.IsRunning(): <NEW_LINE> <INDENT> if wx.Thread_IsMain(): <NEW_LINE> <INDENT> self.Start(150) <NEW_LINE> <DEDENT> <DEDENT> logmsg = msg.GetData() <NEW_LINE> org = logmsg.Origin <NEW_LINE> if org not in self._srcs: <NEW_LINE> <INDENT> self.AddFilter(org) <NEW_LINE> <DEDENT> if self._filter == SHOW_ALL_MSG: <NEW_LINE> <INDENT> self.AppendUpdate(unicode(logmsg) + os.linesep) <NEW_LINE> <DEDENT> elif self._filter == logmsg.Origin: <NEW_LINE> <INDENT> msg = u"[%s][%s]%s" % (logmsg.ClockTime, logmsg.Type, logmsg.Value) <NEW_LINE> self.AppendUpdate(msg + os.linesep) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass | Buffer for displaying log messages that are sent on Editra's
log channel.
@todo: make line buffering configurable through interface | 62598fba26068e7796d4cacb |
class LinkedStorageAccountsListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[LinkedStorageAccountsResource]'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["LinkedStorageAccountsResource"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(LinkedStorageAccountsListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value | The list linked storage accounts service operation response.
:ivar value: A list of linked storage accounts instances.
:vartype value: list[~azure.mgmt.loganalytics.models.LinkedStorageAccountsResource] | 62598fba236d856c2adc94f9 |
class Date(ArgTypeMixin, Enum): <NEW_LINE> <INDENT> All = 0 <NEW_LINE> Past12 = 1 <NEW_LINE> CurrentYear = 3 <NEW_LINE> LastYear = 4 | 0 = No date filter
1 = The last 12 months (eg. if today is 12 June 2016, then the range is 12 June 2015 to 12 June 2016)
2 = Not used
3 = This year (e.g. if today is between 1 January and 31 December 2016, then the year is 2016)
4 = Last year (e.g. if today is between 1 January and 31 December 2016, then last year is 2015) | 62598fba3d592f4c4edbb030 |
class RefundApproved(fsm.Event): <NEW_LINE> <INDENT> description: str = settings.Description.RefundApproved | 退款审核已经通过, 等待支付平台处理退款 | 62598fba99fddb7c1ca62ea4 |
class RainCloudSwitch(RainCloudEntity, SwitchEntity): <NEW_LINE> <INDENT> def __init__(self, default_watering_timer, *args): <NEW_LINE> <INDENT> super().__init__(*args) <NEW_LINE> self._default_watering_timer = default_watering_timer <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> if self._sensor_type == "manual_watering": <NEW_LINE> <INDENT> self.data.watering_time = self._default_watering_timer <NEW_LINE> <DEDENT> elif self._sensor_type == "auto_watering": <NEW_LINE> <INDENT> self.data.auto_watering = True <NEW_LINE> <DEDENT> self._state = True <NEW_LINE> <DEDENT> def turn_off(self, **kwargs): <NEW_LINE> <INDENT> if self._sensor_type == "manual_watering": <NEW_LINE> <INDENT> self.data.watering_time = "off" <NEW_LINE> <DEDENT> elif self._sensor_type == "auto_watering": <NEW_LINE> <INDENT> self.data.auto_watering = False <NEW_LINE> <DEDENT> self._state = False <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> _LOGGER.debug("Updating RainCloud switch: %s", self._name) <NEW_LINE> if self._sensor_type == "manual_watering": <NEW_LINE> <INDENT> self._state = bool(self.data.watering_time) <NEW_LINE> <DEDENT> elif self._sensor_type == "auto_watering": <NEW_LINE> <INDENT> self._state = self.data.auto_watering <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def extra_state_attributes(self): <NEW_LINE> <INDENT> return { ATTR_ATTRIBUTION: ATTRIBUTION, "default_manual_timer": self._default_watering_timer, "identifier": self.data.serial, } | A switch implementation for raincloud device. | 62598fba91f36d47f2230f63 |
class MiningViews(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> user = UserFactory(username='bob', email='bob@bob.net') <NEW_LINE> user.set_password('password') <NEW_LINE> user.save() <NEW_LINE> <DEDENT> def test_start_mining_on_page(self): <NEW_LINE> <INDENT> self.client.post(reverse_lazy('login'), { 'username': 'bob', 'password': 'password' }, follow=True) <NEW_LINE> response = self.client.get(reverse_lazy('mining_home')) <NEW_LINE> self.assertIn(b'Time to mine!', response.content) | Test mininig views. | 62598fba3346ee7daa337701 |
class n_c(Variable): <NEW_LINE> <INDENT> unit = mole | molar mass of gas in chamber | 62598fba10dbd63aa1c70d2c |
class LoadBalancerLoadBalancingRuleListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[LoadBalancingRule]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["LoadBalancingRule"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(LoadBalancerLoadBalancingRuleListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None | Response for ListLoadBalancingRule API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of load balancing rules in a load balancer.
:type value: list[~azure.mgmt.network.v2020_11_01.models.LoadBalancingRule]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str | 62598fba7cff6e4e811b5b94 |
class XspeedGateway(VtGateway): <NEW_LINE> <INDENT> def __init__(self, eventEngine, gatewayName='XSPEED'): <NEW_LINE> <INDENT> super(XspeedGateway, self).__init__(eventEngine, gatewayName) <NEW_LINE> self.mdApi = XspeedMdApi(self) <NEW_LINE> self.tdApi = XspeedTdApi(self) <NEW_LINE> self.mdConnected = False <NEW_LINE> self.tdConnected = False <NEW_LINE> self.qryEnabled = False <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> fileName = self.gatewayName + '_connect.json' <NEW_LINE> fileName = os.getcwd() + '/xspeedGateway/' + fileName <NEW_LINE> try: <NEW_LINE> <INDENT> f = file(fileName) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> log = VtLogData() <NEW_LINE> log.gatewayName = self.gatewayName <NEW_LINE> log.logContent = u'读取连接配置出错,请检查' <NEW_LINE> self.onLog(log) <NEW_LINE> return <NEW_LINE> <DEDENT> setting = json.load(f) <NEW_LINE> try: <NEW_LINE> <INDENT> accountID = str(setting['accountID']) <NEW_LINE> password = str(setting['password']) <NEW_LINE> tdAddress = str(setting['tdAddress']) <NEW_LINE> mdAddress = str(setting['mdAddress']) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> log = VtLogData() <NEW_LINE> log.gatewayName = self.gatewayName <NEW_LINE> log.logContent = u'连接配置缺少字段,请检查' <NEW_LINE> self.onLog(log) <NEW_LINE> return <NEW_LINE> <DEDENT> self.mdApi.connect(accountID, password, mdAddress) <NEW_LINE> self.tdApi.connect(accountID, password, tdAddress) <NEW_LINE> self.initQuery() <NEW_LINE> <DEDENT> def subscribe(self, subscribeReq): <NEW_LINE> <INDENT> self.mdApi.subscribe(subscribeReq) <NEW_LINE> <DEDENT> def sendOrder(self, orderReq): <NEW_LINE> <INDENT> return self.tdApi.sendOrder(orderReq) <NEW_LINE> <DEDENT> def cancelOrder(self, cancelOrderReq): <NEW_LINE> <INDENT> self.tdApi.cancelOrder(cancelOrderReq) <NEW_LINE> <DEDENT> def qryAccount(self): <NEW_LINE> <INDENT> self.tdApi.qryAccount() <NEW_LINE> <DEDENT> def qryPosition(self): <NEW_LINE> <INDENT> self.tdApi.qryPosition() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self.mdConnected: <NEW_LINE> <INDENT> self.mdApi.close() <NEW_LINE> <DEDENT> if self.tdConnected: <NEW_LINE> <INDENT> self.tdApi.close() <NEW_LINE> <DEDENT> <DEDENT> def initQuery(self): <NEW_LINE> <INDENT> if self.qryEnabled: <NEW_LINE> <INDENT> self.qryFunctionList = [self.qryAccount, self.qryPosition] <NEW_LINE> self.qryCount = 0 <NEW_LINE> self.qryTrigger = 2 <NEW_LINE> self.qryNextFunction = 0 <NEW_LINE> self.startQuery() <NEW_LINE> <DEDENT> <DEDENT> def query(self, event): <NEW_LINE> <INDENT> self.qryCount += 1 <NEW_LINE> if self.qryCount > self.qryTrigger: <NEW_LINE> <INDENT> self.qryCount = 0 <NEW_LINE> function = self.qryFunctionList[self.qryNextFunction] <NEW_LINE> function() <NEW_LINE> self.qryNextFunction += 1 <NEW_LINE> if self.qryNextFunction == len(self.qryFunctionList): <NEW_LINE> <INDENT> self.qryNextFunction = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def startQuery(self): <NEW_LINE> <INDENT> self.eventEngine.register(EVENT_TIMER, self.query) <NEW_LINE> <DEDENT> def setQryEnabled(self, qryEnabled): <NEW_LINE> <INDENT> self.qryEnabled = qryEnabled | XSPEED接口 | 62598fbaec188e330fdf8a04 |
class Left(Cell): <NEW_LINE> <INDENT> @profile <NEW_LINE> def __init__(self, cell): <NEW_LINE> <INDENT> self.x = cell.x - 1 <NEW_LINE> self.y = cell.y | docstring for Left | 62598fbaadb09d7d5dc0a6f0 |
class PeriodicCallback(object): <NEW_LINE> <INDENT> def __init__(self, callback, callback_time, io_loop=None): <NEW_LINE> <INDENT> self.callback = callback <NEW_LINE> if callback_time <= 0: <NEW_LINE> <INDENT> raise ValueError("Periodic callback must have a positive callback_time") <NEW_LINE> <DEDENT> self.callback_time = callback_time <NEW_LINE> self.io_loop = io_loop or IOLoop.current() <NEW_LINE> self._running = False <NEW_LINE> self._timeout = None <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self._running = True <NEW_LINE> self._next_timeout = self.io_loop.time() <NEW_LINE> self._schedule_next() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self._running = False <NEW_LINE> if self._timeout is not None: <NEW_LINE> <INDENT> self.io_loop.remove_timeout(self._timeout) <NEW_LINE> self._timeout = None <NEW_LINE> <DEDENT> <DEDENT> def is_running(self): <NEW_LINE> <INDENT> return self._running <NEW_LINE> <DEDENT> def _run(self): <NEW_LINE> <INDENT> if not self._running: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return self.callback() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.io_loop.handle_callback_exception(self.callback) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._schedule_next() <NEW_LINE> <DEDENT> <DEDENT> def _schedule_next(self): <NEW_LINE> <INDENT> if self._running: <NEW_LINE> <INDENT> current_time = self.io_loop.time() <NEW_LINE> if self._next_timeout <= current_time: <NEW_LINE> <INDENT> callback_time_sec = self.callback_time / 1000.0 <NEW_LINE> self._next_timeout += (math.floor((current_time - self._next_timeout) / callback_time_sec) + 1) * callback_time_sec <NEW_LINE> <DEDENT> self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run) | Schedules the given callback to be called periodically.
The callback is called every ``callback_time`` milliseconds.
Note that the timeout is given in milliseconds, while most other
time-related functions in Tornado use seconds.
If the callback runs for longer than ``callback_time`` milliseconds,
subsequent invocations will be skipped to get back on schedule.
`start` must be called after the `PeriodicCallback` is created.
定时回到任务
.. versionchanged:: 4.1
The ``io_loop`` argument is deprecated. | 62598fba627d3e7fe0e07025 |
class Deck(SimpleDeck): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.clear() <NEW_LINE> <DEDENT> def remove(self, card): <NEW_LINE> <INDENT> if self.cardcount[card.index()] > 0: <NEW_LINE> <INDENT> self.cardcount[card.index()] -= 1 <NEW_LINE> self.cardlist.remove(card) <NEW_LINE> <DEDENT> <DEDENT> def insert_card(self, card, location=0): <NEW_LINE> <INDENT> self.cardlist.insert(location, card) <NEW_LINE> self.cardcount[card.index()] += 1 <NEW_LINE> <DEDENT> def add_cards(self, cards): <NEW_LINE> <INDENT> for card in cards: <NEW_LINE> <INDENT> self.cardcount[card.index()] += 1 <NEW_LINE> <DEDENT> self.cardlist = self.cardlist + cards <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.cardlist = [] <NEW_LINE> self.cardcount = [0 for _ in range(Card.TOTAL_CARDS)] <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return sum(self.cardcount) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.cardlist) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.cardcount <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = str(self.cardcount[:Card.NUM_CARD_TYPES]) + '\n' <NEW_LINE> s += str(self.cardcount[Card.NUM_CARD_TYPES:2*Card.NUM_CARD_TYPES]) + '\n' <NEW_LINE> s += str(self.cardcount[Card.NUM_CARD_TYPES*2:]) <NEW_LINE> return s | A deck of cards. Holds both an ordered and unordered list. Used for decks, discard
piles, hands... 0 is the top, n is the bottom. | 62598fba091ae35668704d95 |
class BookCreateView(generics.CreateAPIView): <NEW_LINE> <INDENT> permission_classes = [permissions.IsAdminUser, permissions.IsAuthenticated] <NEW_LINE> queryset = Book.objects.all() <NEW_LINE> serializer_class = serializers.BookSerializer <NEW_LINE> def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> super(BookCreateView, self).create(request, args, kwargs) <NEW_LINE> response = {"status_code": status.HTTP_200_OK, "message": "Successfully added to books", "result": request.data} <NEW_LINE> return Response(response) | View to add a new book.
* Requires token authentication.
* Only admin users are able to access this view. | 62598fbaa8370b77170f0552 |
@properties(action_chance=1.0) <NEW_LINE> @mod_dep(Actor) <NEW_LINE> class ActionChance(Entity): <NEW_LINE> <INDENT> pass | Actor with actions having chance of succeeding | 62598fba21bff66bcd722ddd |
class RigidBody(common.Diff): <NEW_LINE> <INDENT> __slots__=[ 'name', 'english_name', 'bone_index', 'collision_group', 'no_collision_group', 'shape_type', 'shape_size', 'shape_position', 'shape_rotation', 'param', 'mode', ] <NEW_LINE> def __init__(self, name, english_name, bone_index, collision_group, no_collision_group, shape_type, shape_size, shape_position, shape_rotation, mass, linear_damping, angular_damping, restitution, friction, mode ): <NEW_LINE> <INDENT> self.name=name <NEW_LINE> self.english_name=english_name <NEW_LINE> self.bone_index=bone_index <NEW_LINE> self.collision_group=collision_group <NEW_LINE> self.no_collision_group=no_collision_group <NEW_LINE> self.shape_type=shape_type <NEW_LINE> self.shape_size=shape_size <NEW_LINE> self.shape_position=shape_position <NEW_LINE> self.shape_rotation=shape_rotation <NEW_LINE> self.param=RigidBodyParam(mass, linear_damping, angular_damping, restitution, friction) <NEW_LINE> self.mode=mode <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ("<pmx.RigidBody {name} shape:{type}>".format( name=self.english_name, type=self.shape_type )) <NEW_LINE> <DEDENT> def __eq__(self, rhs): <NEW_LINE> <INDENT> return ( self.name==rhs.name and self.english_name==rhs.english_name and self.bone_index==rhs.bone_index and self.collision_group==rhs.collision_group and self.no_collision_group==rhs.no_collision_group and self.shape_type==rhs.shape_type and self.shape_size==rhs.shape_size and self.param==rhs.param and self.mode==rhs.mode ) <NEW_LINE> <DEDENT> def __ne__(self, rhs): <NEW_LINE> <INDENT> return not self.__eq__(rhs) <NEW_LINE> <DEDENT> def diff(self, rhs): <NEW_LINE> <INDENT> self._diff(rhs, 'name') <NEW_LINE> self._diff(rhs, 'english_name') <NEW_LINE> self._diff(rhs, 'bone_index') <NEW_LINE> self._diff(rhs, 'collision_group') <NEW_LINE> self._diff(rhs, 'no_collision_group') <NEW_LINE> self._diff(rhs, 'shape_type') <NEW_LINE> if self.shape_type==SHAPE_SPHERE: <NEW_LINE> <INDENT> if self.shape_size.x!=rhs.shape_size.x: <NEW_LINE> <INDENT> print(self.shape_size) <NEW_LINE> print(rhs.shape_size) <NEW_LINE> raise DifferenceException('self.shape_size') <NEW_LINE> <DEDENT> <DEDENT> elif self.shape_type==SHAPE_BOX: <NEW_LINE> <INDENT> self._diff(rhs, 'shape_size') <NEW_LINE> <DEDENT> elif self.shape_type==SHAPE_CAPSULE: <NEW_LINE> <INDENT> if (self.shape_size.x!=rhs.shape_size.x or self.shape_size.y!=rhs.shape_size.y): <NEW_LINE> <INDENT> print(self.shape_size) <NEW_LINE> print(rhs.shape_size) <NEW_LINE> raise DifferenceException('self.shape_size') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> assert(False) <NEW_LINE> <DEDENT> self._diff(rhs, 'shape_position') <NEW_LINE> self._diff(rhs, 'shape_rotation') <NEW_LINE> self._diff(rhs, 'param') <NEW_LINE> self._diff(rhs, 'mode') | pmx rigidbody
Attributes:
name:
english_name:
bone_index:
collision_group:
no_collision_group:
shape:
param:
mode: | 62598fba4527f215b58ea049 |
class Sampler(Slicer): <NEW_LINE> <INDENT> def __init__(self, n_samples, duration, *ops, **kwargs): <NEW_LINE> <INDENT> super(Sampler, self).__init__(*ops) <NEW_LINE> self.n_samples = n_samples <NEW_LINE> self.duration = duration <NEW_LINE> random_state = kwargs.pop('random_state', None) <NEW_LINE> if random_state is None: <NEW_LINE> <INDENT> self.rng = np.random <NEW_LINE> <DEDENT> elif isinstance(random_state, int): <NEW_LINE> <INDENT> self.rng = np.random.RandomState(seed=random_state) <NEW_LINE> <DEDENT> elif isinstance(random_state, np.random.RandomState): <NEW_LINE> <INDENT> self.rng = random_state <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ParameterError('Invalid random_state={}'.format(random_state)) <NEW_LINE> <DEDENT> <DEDENT> def sample(self, data, interval): <NEW_LINE> <INDENT> data_slice = dict() <NEW_LINE> for key in data: <NEW_LINE> <INDENT> if '_valid' in key: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> index = [slice(None)] * data[key].ndim <NEW_LINE> index[0] = self.rng.randint(0, data[key].shape[0]) <NEW_LINE> index[0] = slice(index[0], index[0] + 1) <NEW_LINE> for tdim in self._time[key]: <NEW_LINE> <INDENT> index[tdim] = interval <NEW_LINE> <DEDENT> data_slice[key] = data[key][tuple(index)] <NEW_LINE> <DEDENT> return data_slice <NEW_LINE> <DEDENT> def indices(self, data): <NEW_LINE> <INDENT> duration = self.data_duration(data) <NEW_LINE> if self.duration > duration: <NEW_LINE> <INDENT> raise DataError('Data duration={} is less than ' 'sample duration={}'.format(duration, self.duration)) <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> yield self.rng.randint(0, duration - self.duration + 1) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, data): <NEW_LINE> <INDENT> if self.n_samples: <NEW_LINE> <INDENT> counter = range(self.n_samples) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> counter = count(0) <NEW_LINE> <DEDENT> for _, start in zip(counter, self.indices(data)): <NEW_LINE> <INDENT> yield self.sample(data, slice(start, start + self.duration)) | Generate samples uniformly at random from a pumpp data dict.
Attributes
----------
n_samples : int or None
the number of samples to generate.
If `None`, generate indefinitely.
duration : int > 0
the duration (in frames) of each sample
random_state : None, int, or np.random.RandomState
If int, random_state is the seed used by the random number
generator;
If RandomState instance, random_state is the random number
generator;
If None, the random number generator is the RandomState instance
used by np.random.
ops : array of pumpp.feature.FeatureExtractor or pumpp.task.BaseTaskTransformer
The operators to include when sampling data.
Examples
--------
>>> # Set up the parameters
>>> sr, n_fft, hop_length = 22050, 512, 2048
>>> # Instantiate some transformers
>>> p_stft = pumpp.feature.STFTMag('stft', sr=sr, n_fft=n_fft,
... hop_length=hop_length)
>>> p_beat = pumpp.task.BeatTransformer('beat', sr=sr,
... hop_length=hop_length)
>>> # Apply the transformers to the data
>>> data = pumpp.transform('test.ogg', 'test.jams', p_stft, p_beat)
>>> # We'll sample 10 patches of duration = 32 frames
>>> stream = pumpp.Sampler(10, 32, p_stft, p_beat)
>>> # Apply the streamer to the data dict
>>> for example in stream(data):
... process(data) | 62598fba5166f23b2e243551 |
class Documents(Base): <NEW_LINE> <INDENT> __tablename__ = 'Documents' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> handle = Column(String(256)) <NEW_LINE> document_type = Column(String(256)) <NEW_LINE> status = Column(String(256)) <NEW_LINE> summary = Column(Text) <NEW_LINE> created = Column(DateTime, default=now()) <NEW_LINE> modified = Column(DateTime, default=now()) <NEW_LINE> importance = Column(String(16)) <NEW_LINE> priority = Column(String(8)) <NEW_LINE> document_owners = relationship(User, secondary="DocumentOwners", backref='Documents') <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return self.handle | Requirements Documents. | 62598fba236d856c2adc94fa |
class CustomPageNumberPagination(PageNumberPagination): <NEW_LINE> <INDENT> page_size_query_param = "page_size" <NEW_LINE> max_page_size = 10000 <NEW_LINE> def get_paginated_response(self, data): <NEW_LINE> <INDENT> return Response( OrderedDict( [ ("page", self.page.number), ("total_page", self.page.paginator.num_pages), ("count", self.page.paginator.count), ("items", data), ] ) ) <NEW_LINE> <DEDENT> def get_paginated_data(self, data): <NEW_LINE> <INDENT> return OrderedDict( [ ("page", self.page.number), ("total_page", self.page.paginator.num_pages), ("count", self.page.paginator.count), ("items", data), ] ) | 自定义分页格式,综合页码和url | 62598fba099cdd3c6367549c |
class PolyIon(BaseIon): <NEW_LINE> <INDENT> pass | PolyIon is the base class for electrically charged polymers. | 62598fba63d6d428bbee2924 |
class user_search_infosharing(object): <NEW_LINE> <INDENT> def __init__(self, username, searchquery, realtime): <NEW_LINE> <INDENT> self.userName = username <NEW_LINE> self.userSearchQuery = searchquery <NEW_LINE> self.isSearchRealtime = realtime <NEW_LINE> self.tweetFetchComplete = False <NEW_LINE> self.metaModelComplete = False <NEW_LINE> self.threadsExecuting = [] <NEW_LINE> self.configSettings = {} <NEW_LINE> for i in xrange(0, 3): <NEW_LINE> <INDENT> self.threadsExecuting.append(None) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def user_name(self): <NEW_LINE> <INDENT> return self.userName <NEW_LINE> <DEDENT> @user_name.setter <NEW_LINE> def user_name(self, value): <NEW_LINE> <INDENT> self.userName = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def user_search_sentence(self): <NEW_LINE> <INDENT> return self.userSearchQuery <NEW_LINE> <DEDENT> @user_search_sentence.setter <NEW_LINE> def user_search_sentence(self, value): <NEW_LINE> <INDENT> self.userSearchQuery = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def realtime_search(self): <NEW_LINE> <INDENT> return self.isSearchRealtime <NEW_LINE> <DEDENT> @realtime_search.setter <NEW_LINE> def realtime_search(self, value): <NEW_LINE> <INDENT> self.isSearchRealtime = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def threads_in_use(self): <NEW_LINE> <INDENT> return self.threadsExecuting <NEW_LINE> <DEDENT> @threads_in_use.setter <NEW_LINE> def threads_in_use(self, value): <NEW_LINE> <INDENT> self.threadsExecuting = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def tweet_fetch_complete(self): <NEW_LINE> <INDENT> return self.tweetFetchComplete <NEW_LINE> <DEDENT> @tweet_fetch_complete.setter <NEW_LINE> def tweet_fetch_complete(self, value): <NEW_LINE> <INDENT> self.tweetFetchComplete = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def meta_model_complete(self): <NEW_LINE> <INDENT> return self.metaModelComplete <NEW_LINE> <DEDENT> @meta_model_complete.setter <NEW_LINE> def meta_model_complete(self, value): <NEW_LINE> <INDENT> self.metaModelComplete = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def configuration_parameters(self): <NEW_LINE> <INDENT> return self.configSettings <NEW_LINE> <DEDENT> @configuration_parameters.setter <NEW_LINE> def configuration_parameters(self, value): <NEW_LINE> <INDENT> self.configSettings = value | This is the object which will be created when user first time logs in and gives first
search string for the session. This class has all necessary information needed to
execute complete functionality. Object will be put in the user_searches_ongoing dictionary
along with the username as key. So every new search retrive from dictionary and modify
contents | 62598fba377c676e912f6e2a |
class TestCloc(TestCaseAnalyzer): <NEW_LINE> <INDENT> def test_initialization(self): <NEW_LINE> <INDENT> c = Cloc() <NEW_LINE> self.assertEqual(c.diff_timeout, DEFAULT_DIFF_TIMEOUT) <NEW_LINE> c = Cloc(diff_timeout=50) <NEW_LINE> self.assertEqual(c.diff_timeout, 50) <NEW_LINE> <DEDENT> def test_analyze(self): <NEW_LINE> <INDENT> cloc = Cloc() <NEW_LINE> kwargs = {'file_path': os.path.join(self.tmp_data_path, ANALYZER_TEST_FILE)} <NEW_LINE> result = cloc.analyze(**kwargs) <NEW_LINE> self.assertIn('blanks', result) <NEW_LINE> self.assertTrue(type(result['blanks']), int) <NEW_LINE> self.assertTrue(result['blanks'], 27) <NEW_LINE> self.assertIn('comments', result) <NEW_LINE> self.assertTrue(type(result['comments']), int) <NEW_LINE> self.assertTrue(result['comments'], 31) <NEW_LINE> self.assertIn('loc', result) <NEW_LINE> self.assertTrue(type(result['loc']), int) <NEW_LINE> self.assertTrue(result['loc'], 67) <NEW_LINE> <DEDENT> def test_analyze_repository_level(self): <NEW_LINE> <INDENT> cloc = Cloc() <NEW_LINE> kwargs = { 'file_path': self.origin_path, 'repository_level': True } <NEW_LINE> results = cloc.analyze(**kwargs) <NEW_LINE> result = results[next(iter(results))] <NEW_LINE> self.assertIn('blanks', result) <NEW_LINE> self.assertTrue(type(result['blanks']), int) <NEW_LINE> self.assertIn('comments', result) <NEW_LINE> self.assertTrue(type(result['comments']), int) <NEW_LINE> self.assertIn('loc', result) <NEW_LINE> self.assertTrue(type(result['loc']), int) <NEW_LINE> self.assertIn('total_files', result) <NEW_LINE> self.assertTrue(type(result['total_files']), int) <NEW_LINE> <DEDENT> @unittest.mock.patch('subprocess.check_output') <NEW_LINE> def test_analyze_error(self, check_output_mock): <NEW_LINE> <INDENT> check_output_mock.side_effect = subprocess.CalledProcessError(-1, "command", output=b'output') <NEW_LINE> cloc = Cloc() <NEW_LINE> kwargs = {'file_path': os.path.join(self.tmp_data_path, ANALYZER_TEST_FILE)} <NEW_LINE> with self.assertRaises(GraalError): <NEW_LINE> <INDENT> _ = cloc.analyze(**kwargs) | Cloc tests | 62598fbaf548e778e596b71a |
class MathematicalEvaluation(LogicAdapter): <NEW_LINE> <INDENT> def __init__(self, chatbot, **kwargs): <NEW_LINE> <INDENT> super().__init__(chatbot, **kwargs) <NEW_LINE> self.language = kwargs.get('language', languages.ENG) <NEW_LINE> self.cache = {} <NEW_LINE> <DEDENT> def can_process(self, statement): <NEW_LINE> <INDENT> response = self.process(statement) <NEW_LINE> self.cache[statement.text] = response <NEW_LINE> return response.confidence == 1 <NEW_LINE> <DEDENT> def process(self, statement, additional_response_selection_parameters=None): <NEW_LINE> <INDENT> from mathparse import mathparse <NEW_LINE> input_text = statement.text <NEW_LINE> if input_text in self.cache: <NEW_LINE> <INDENT> cached_result = self.cache[input_text] <NEW_LINE> self.cache = {} <NEW_LINE> return cached_result <NEW_LINE> <DEDENT> expression = mathparse.extract_expression(input_text, language=self.language.ISO_639.upper()) <NEW_LINE> response = Statement(text=expression) <NEW_LINE> try: <NEW_LINE> <INDENT> response.text = '{} = {}'.format( response.text, mathparse.parse(expression, language=self.language.ISO_639.upper()) ) <NEW_LINE> response.confidence = 1 <NEW_LINE> <DEDENT> except mathparse.PostfixTokenEvaluationException: <NEW_LINE> <INDENT> response.confidence = 0 <NEW_LINE> <DEDENT> return response | The MathematicalEvaluation logic adapter parses input to determine
whether the user is asking a question that requires math to be done.
If so, the equation is extracted from the input and returned with
the evaluated result.
For example:
User: 'What is three plus five?'
Bot: 'Three plus five equals eight'
:kwargs:
* *language* (``object``) --
The language is set to ``chatterbot.languages.ENG`` for English by default. | 62598fba7c178a314d78d613 |
class NSNitroNserrArpDisabled(NSNitro0x300Errors): <NEW_LINE> <INDENT> pass | Nitro error code 784
IP has arp disabled. | 62598fba4c3428357761a42f |
class DiskSize(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def _posix_size(path): <NEW_LINE> <INDENT> st = os.statvfs(path) <NEW_LINE> disk_info = DiskInfo() <NEW_LINE> disk_info.free = st.f_bavail * st.f_frsize <NEW_LINE> disk_info.used = (st.f_blocks - st.f_bfree) * st.f_frsize <NEW_LINE> disk_info.total = st.f_blocks * st.f_frsize <NEW_LINE> return disk_info <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _windows_size(path): <NEW_LINE> <INDENT> disk_info = DiskInfo() <NEW_LINE> dummy = ctypes.c_ulonglong() <NEW_LINE> total = ctypes.c_ulonglong() <NEW_LINE> free = ctypes.c_ulonglong() <NEW_LINE> called_function = ctypes.windll.kernel32.GetDiskFreeSpaceExA <NEW_LINE> if isinstance(path, unicode) or sys.version_info >= (3,): <NEW_LINE> <INDENT> called_function = ctypes.windll.kernel32.GetDiskFreeSpaceExW <NEW_LINE> <DEDENT> if called_function(path, ctypes.byref(dummy), ctypes.byref(total), ctypes.byref(free)) != 0: <NEW_LINE> <INDENT> disk_info.free = free.value <NEW_LINE> disk_info.total = total.value <NEW_LINE> disk_info.used = total.value - free.value <NEW_LINE> <DEDENT> return disk_info <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_size(path, unit, log_level=INFO): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> disk_info = DiskSize()._posix_size(path) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> disk_info = DiskSize()._windows_size(path) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise DiskutilsError('Unsupported platform') <NEW_LINE> <DEDENT> <DEDENT> disk_info._to(unit) <NEW_LINE> lvl = numeric_log_level(log_level) <NEW_LINE> log.log(lvl, msg="%s" % disk_info) <NEW_LINE> return disk_info | DiskSize object
| 62598fba10dbd63aa1c70d2e |
class reader(object): <NEW_LINE> <INDENT> fp = None <NEW_LINE> dialect = 'excel' <NEW_LINE> fmtparams = None <NEW_LINE> line_iterator = None <NEW_LINE> def __init__(self, csvfile, dialect='excel', **fmtparams): <NEW_LINE> <INDENT> self.fp = csvfile <NEW_LINE> self.dialect = dialect <NEW_LINE> self.fmtparams = fmtparams <NEW_LINE> self.line_iterator = iter(self.fp.readline, '') <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def seek(self, position): <NEW_LINE> <INDENT> self.fp.seek(position) <NEW_LINE> <DEDENT> def _get_csv_row_from_line(self, line): <NEW_LINE> <INDENT> return csv.reader([line], self.dialect, **self.fmtparams).next() <NEW_LINE> <DEDENT> def _get_next_row(self): <NEW_LINE> <INDENT> line = self.line_iterator.next() <NEW_LINE> return self._get_csv_row_from_line(line) <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> position = self.fp.tell() <NEW_LINE> row = self._get_next_row() <NEW_LINE> return position, row | Like `csv.reader`, but yield successive pairs of:
(
<int> file position,
<list> row,
) | 62598fba3346ee7daa337702 |
class DOHolder(object): <NEW_LINE> <INDENT> def __init__(self, rawclient): <NEW_LINE> <INDENT> self.raw = rawclient <NEW_LINE> <DEDENT> def __call__(self, term): <NEW_LINE> <INDENT> return DO(self.raw, term) <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> flags = self.raw.acop(unit=2) <NEW_LINE> states = parse_do_flags(flags) <NEW_LINE> return states['do'] | Holds the DOs. | 62598fba656771135c4897e2 |
class PartialView(TemplateView): <NEW_LINE> <INDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> if not self.request.is_ajax(): <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> context = super(PartialView, self).get_context_data(**kwargs) <NEW_LINE> return context | Class for processing requests for templates from the client | 62598fba8a349b6b436863b1 |
class Persona(): <NEW_LINE> <INDENT> def __init__(self, dni, nombre, edad): <NEW_LINE> <INDENT> self.dni = dni <NEW_LINE> self.nombre = nombre <NEW_LINE> self.edad = edad <NEW_LINE> <DEDENT> @property <NEW_LINE> def dni(self): <NEW_LINE> <INDENT> return self._dni <NEW_LINE> <DEDENT> @property <NEW_LINE> def nombre(self): <NEW_LINE> <INDENT> return self._nombre <NEW_LINE> <DEDENT> @property <NEW_LINE> def edad(self): <NEW_LINE> <INDENT> return self._edad <NEW_LINE> <DEDENT> @dni.setter <NEW_LINE> def dni(self,dni): <NEW_LINE> <INDENT> self._dni = dni <NEW_LINE> <DEDENT> @nombre.setter <NEW_LINE> def nombre(self,nombre): <NEW_LINE> <INDENT> self._nombre = nombre <NEW_LINE> <DEDENT> @edad.setter <NEW_LINE> def edad(self,edad): <NEW_LINE> <INDENT> if edad>0: <NEW_LINE> <INDENT> self._edad = edad <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Edad incorrecta") <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.dni.__str__() + " " +self.nombre + " " + str(self.edad) | A continuación creamos la clase Persona. Una persona tendrá un DNI, un nombre y una edad.
Creamos el constructor.
Crearemos también los métodos seters y getters.
Se debe definir el método __str__ para imprimir los objetos. | 62598fbad486a94d0ba2c143 |
class ModifyPasswordForm(forms.Form): <NEW_LINE> <INDENT> password = forms.CharField(required=True, min_length=5) <NEW_LINE> password_repeat = forms.CharField(required=True, min_length=5) | 修改密码 | 62598fba2c8b7c6e89bd393b |
class DocumentListView(generics.ListAPIView): <NEW_LINE> <INDENT> queryset = Document.objects.all() <NEW_LINE> serializer_class = DocumentSerializer <NEW_LINE> permission_classes = (AllowAny,) | List View for Documents | 62598fba0fa83653e46f5058 |
class PackageViewSet(ViewSet): <NEW_LINE> <INDENT> serializer_class = PackageSerializer <NEW_LINE> queryset = Package.objects.all() <NEW_LINE> renderer_class = JSONRenderer <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> def create(self, request): <NEW_LINE> <INDENT> serializer = PackageSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> data = save_serializer(serializer) <NEW_LINE> return Response(data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> data = { 'status': 'error' } <NEW_LINE> data.update({'data': serializer.errors}) <NEW_LINE> status_code = status.HTTP_400_BAD_REQUEST <NEW_LINE> return Response(data, status=status_code) <NEW_LINE> <DEDENT> def retrieve(self, request, pk=None): <NEW_LINE> <INDENT> return Response(*check_resource(Package, PackageSerializer, pk, request, "Package")) <NEW_LINE> <DEDENT> def destroy(self, request, pk=None): <NEW_LINE> <INDENT> package = resource_exists(Package, pk) <NEW_LINE> if not package: <NEW_LINE> <INDENT> response_attr = {'format_str': 'Package', 'error_key': 'not_found'} <NEW_LINE> data = get_response(**response_attr) <NEW_LINE> return Response(data, status=status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> package.delete() <NEW_LINE> data = { 'status': 'success', 'message': 'package deleted successfully' } <NEW_LINE> return Response(data, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> def partial_update(self, request, pk=None): <NEW_LINE> <INDENT> package = resource_exists(Package, pk) <NEW_LINE> if not package: <NEW_LINE> <INDENT> response_attr = {'error_key': 'not_found', 'format_str': 'Package'} <NEW_LINE> data = get_response(**response_attr) <NEW_LINE> return Response(data, status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> serializer = PackageSerializer(package, context={'request': request}, data=request.data, partial=True) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> data = save_serializer(serializer) <NEW_LINE> return Response(data, status.HTTP_200_OK) <NEW_LINE> <DEDENT> data = { 'status': 'error', 'error': serializer.errors, 'message': 'Package failed to edit due to the above error/s' } <NEW_LINE> return Response(data, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def list(self, request): <NEW_LINE> <INDENT> packages = Package.objects.all() <NEW_LINE> serializer = PackageSerializer(packages,many=True) <NEW_LINE> return Response(serializer.data, status.HTTP_200_OK) | Package viewset. | 62598fbaa8370b77170f0554 |
class SourceCatalog3FHL(SourceCatalog): <NEW_LINE> <INDENT> name = '3fhl' <NEW_LINE> description = 'LAT third high-energy source catalog' <NEW_LINE> source_object_class = SourceCatalogObject3FHL <NEW_LINE> def __init__(self, filename='$GAMMAPY_EXTRA/datasets/catalogs/fermi/gll_psch_v11.fit.gz'): <NEW_LINE> <INDENT> filename = str(make_path(filename)) <NEW_LINE> self.hdu_list = fits.open(filename) <NEW_LINE> self.extended_sources_table = Table(self.hdu_list['ExtendedSources'].data) <NEW_LINE> self.rois = Table(self.hdu_list['ROIs'].data) <NEW_LINE> table = Table(self.hdu_list['LAT_Point_Source_Catalog'].data) <NEW_LINE> self.energy_bounds_table = Table(self.hdu_list['EnergyBounds'].data) <NEW_LINE> self._add_flux_point_columns( table=table, energy_bounds_table=self.energy_bounds_table, ) <NEW_LINE> source_name_key = 'Source_Name' <NEW_LINE> source_name_alias = ('ASSOC1', 'ASSOC2', 'ASSOC_TEV', 'ASSOC_GAM') <NEW_LINE> super(SourceCatalog3FHL, self).__init__( table=table, source_name_key=source_name_key, source_name_alias=source_name_alias, ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _add_flux_point_columns(table, energy_bounds_table): <NEW_LINE> <INDENT> for idx, band in enumerate(energy_bounds_table): <NEW_LINE> <INDENT> col_flux_name = 'Flux{:d}_{:d}GeV'.format(int(band['LowerEnergy']), int(band['UpperEnergy'])) <NEW_LINE> col_flux_value = table['Flux_Band'][:, idx].data <NEW_LINE> col_flux = Column(col_flux_value, name=col_flux_name) <NEW_LINE> col_unc_flux_name = 'Unc_' + col_flux_name <NEW_LINE> col_unc_flux_value = table['Unc_Flux_Band'][:, idx].data <NEW_LINE> col_unc_flux = Column(col_unc_flux_value, name=col_unc_flux_name) <NEW_LINE> col_nufnu_name = 'nuFnu{:d}_{:d}GeV'.format(int(band['LowerEnergy']), int(band['UpperEnergy'])) <NEW_LINE> col_nufnu_value = table['nuFnu'][:, idx].data <NEW_LINE> col_nufnu = Column(col_nufnu_value, name=col_nufnu_name) <NEW_LINE> table.add_column(col_flux) <NEW_LINE> table.add_column(col_unc_flux) <NEW_LINE> table.add_column(col_nufnu) | Fermi-LAT 3FHL source catalog.
One source is represented by `~gammapy.catalog.SourceCatalogObject3FHL`. | 62598fbaad47b63b2c5a79c9 |
class TestMulticlass(TestCase): <NEW_LINE> <INDENT> def test_constructor(self): <NEW_LINE> <INDENT> char = Character(name='Multiclass', classes=['wizard', 'fighter'], levels=[5, 4]) <NEW_LINE> <DEDENT> def test_level(self): <NEW_LINE> <INDENT> char = Character(name='Multiclass', classes=['wizard', 'fighter'], levels=[5, 4]) <NEW_LINE> self.assertEqual(char.level, 9) <NEW_LINE> <DEDENT> def test_spellcasting(self): <NEW_LINE> <INDENT> char = Character(name='Multiclass', classes=['wizard', 'fighter'], levels=[5, 4]) <NEW_LINE> self.assertEqual(len(char.spellcasting_classes), 1) <NEW_LINE> char = Character(name='Multiclass', classes=['wizard', 'fighter'], subclasses=[None, 'Eldritch Knight'], levels=[5, 4]) <NEW_LINE> self.assertEqual(len(char.spellcasting_classes), 2) <NEW_LINE> self.assertEqual(char.spell_slots(spell_level=1), 4) <NEW_LINE> self.assertEqual(char.spell_slots(spell_level=2), 3) <NEW_LINE> self.assertEqual(char.spell_slots(spell_level=3), 3) <NEW_LINE> self.assertEqual(char.spell_slots(spell_level=4), 0) <NEW_LINE> <DEDENT> def test_proficiencies(self): <NEW_LINE> <INDENT> char1 = Character(name='Multiclass', classes=['wizard', 'fighter'], levels=[5, 4]) <NEW_LINE> for svt in ('intelligence', 'wisdom'): <NEW_LINE> <INDENT> self.assertIn(svt, char1.saving_throw_proficiencies) <NEW_LINE> <DEDENT> char2 = Character(name='Multiclass', classes=['wizard', 'rogue'], levels=[5, 4]) <NEW_LINE> char3 = Character(name='Multiclass', classes=['rogue', 'wizard'], levels=[4, 5]) <NEW_LINE> sword = Shortsword() <NEW_LINE> self.assertTrue(char1.is_proficient(sword)) <NEW_LINE> self.assertFalse(char2.is_proficient(sword)) <NEW_LINE> self.assertTrue(char3.is_proficient(sword)) | Tests for Multiclass character. | 62598fba01c39578d7f12ef0 |
@iso_register('CH-GL') <NEW_LINE> class Glarus(Switzerland): <NEW_LINE> <INDENT> include_berchtolds_day = True <NEW_LINE> include_all_saints = True <NEW_LINE> FIXED_HOLIDAYS = Switzerland.FIXED_HOLIDAYS + ( (4, 3, "Näfels Ride"), ) | Glarus (Glaris) | 62598fba26068e7796d4cacf |
class PositionViewSet(mixins.ListModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): <NEW_LINE> <INDENT> queryset = Position.objects.all() <NEW_LINE> serializer_class = PositionSerializer <NEW_LINE> pagination_class = DefaultPagination <NEW_LINE> filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) <NEW_LINE> filter_fields = ('po_code', 'is_active', 'warehouse') <NEW_LINE> search_fields = ('po_code',) <NEW_LINE> ordering_fields = ('po_code',) | 仓位列表 | 62598fba5166f23b2e243553 |
class ResourceParameterWidget(FloatParameterWidget): <NEW_LINE> <INDENT> def __init__(self, parameter, parent=None): <NEW_LINE> <INDENT> super(ResourceParameterWidget, self).__init__(parameter, parent) <NEW_LINE> self.set_unit() <NEW_LINE> <DEDENT> def get_parameter(self): <NEW_LINE> <INDENT> self._parameter.value = self._input.value() <NEW_LINE> return self._parameter <NEW_LINE> <DEDENT> def set_unit(self): <NEW_LINE> <INDENT> label = '' <NEW_LINE> if self._parameter.frequency: <NEW_LINE> <INDENT> label = self._parameter.frequency <NEW_LINE> <DEDENT> if self._parameter.unit.plural: <NEW_LINE> <INDENT> label = '%s %s' % (self._parameter.unit.plural, label) <NEW_LINE> <DEDENT> elif self._parameter.unit.name: <NEW_LINE> <INDENT> label = '%s %s' % (self._parameter.unit.name, label) <NEW_LINE> <DEDENT> self._unit_widget = QLabel(label) <NEW_LINE> if self._parameter.unit.help_text: <NEW_LINE> <INDENT> self._unit_widget.setToolTip(self._parameter.unit.help_text) | Widget class for Resource parameter. | 62598fba7047854f4633f54b |
class _RuntimeException(FSLException): <NEW_LINE> <INDENT> pass | errno (300, 400)
| 62598fba97e22403b383b07c |
class HasMemberOfType(ElementComparator): <NEW_LINE> <INDENT> def process(self, all_props, key, value, type, attribute, attribute_content): <NEW_LINE> <INDENT> errors = [] <NEW_LINE> if key == "extension": <NEW_LINE> <INDENT> value = all_props[attribute]["value"] <NEW_LINE> <DEDENT> if len(value) == 0: <NEW_LINE> <INDENT> errors.append(dict(index=0, detail=N_("Object has no member of type '%(type)s'."), type=type)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> index = PluginRegistry.getInstance("ObjectIndex") <NEW_LINE> query = {attribute_content: {"in_": value}} <NEW_LINE> if ObjectFactory.getInstance().isBaseType(type): <NEW_LINE> <INDENT> query["_type"] = type <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query["extension"] = type <NEW_LINE> <DEDENT> res = index.search(query, {"dn": 1}) <NEW_LINE> if len(res) > 0: <NEW_LINE> <INDENT> return len(errors) == 0, errors <NEW_LINE> <DEDENT> if len(index.currently_in_creation) > 0: <NEW_LINE> <INDENT> found_types = [x.__class__.__name__ for x in index.currently_in_creation if getattr(x, attribute_content) in value] <NEW_LINE> if type in found_types: <NEW_LINE> <INDENT> return True, errors <NEW_LINE> <DEDENT> <DEDENT> if self.traverse_groups(value, type, attribute, attribute_content): <NEW_LINE> <INDENT> return True, errors <NEW_LINE> <DEDENT> errors.append(dict(index=0, detail=N_("Object has no member of type '%(type)s'."), type=type)) <NEW_LINE> <DEDENT> return len(errors) == 0, errors <NEW_LINE> <DEDENT> def get_gui_information(self, all_props, key, value, type, attribute, attribute_content): <NEW_LINE> <INDENT> return {"HasMemberOfType": {"listenToProperty": attribute, "type": type, "propertyContent": attribute_content}} <NEW_LINE> <DEDENT> def traverse_groups(self, value, type, attribute, attribute_content, group_type="GroupOfNames"): <NEW_LINE> <INDENT> index = PluginRegistry.getInstance("ObjectIndex") <NEW_LINE> res = index.search({"_type": group_type, attribute_content: {"in_": value}}, {attribute: 1}) <NEW_LINE> sub_values = [x[attribute] for x in res] <NEW_LINE> res = [] <NEW_LINE> if len(sub_values): <NEW_LINE> <INDENT> query = {attribute_content: {"in_": sub_values}} <NEW_LINE> if ObjectFactory.getInstance().isBaseType(type): <NEW_LINE> <INDENT> query["_type"] = type <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query["extension"] = type <NEW_LINE> <DEDENT> res = index.search(query, {"dn": 1}) <NEW_LINE> <DEDENT> if len(res) == 0 and len(sub_values): <NEW_LINE> <INDENT> return self.traverse_groups(sub_values, type, attribute, attribute_content, group_type) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | Checks if a member of a certain ``type`` existing in the value list of attribute ``attribute``
Can be used e.g. as extension condition to allow an extension only if a certain type is member of a *GroupOfNames*
.. code-block::
<ExtensionCondition extension="GroupOfNames">
<Condition>
<Name>HasMemberOfType</Name>
<Param>PosixUser</Param>
<Param>member</Param>
<Param>dn</Param>
</Condition>
</ExtensionCondition> | 62598fba63b5f9789fe852e4 |
class RegisterForm(Form): <NEW_LINE> <INDENT> username = TextField( 'Username', validators=[Required(REQUIRED_FIELD % 'Username'), Length(min=2, max=20, message=LENGTH_FIELD % ('Username', 20))] ) <NEW_LINE> email = TextField( 'E-mail', validators=[Required(REQUIRED_FIELD % 'E-mail'), Email('Incorrect e-mail')]) <NEW_LINE> password = PasswordField( 'Password', validators=[Required(REQUIRED_FIELD % 'Password'), EqualTo('confirmpass', message='Passwords must match')] ) <NEW_LINE> confirmpass = PasswordField( 'Confirm password', validators=[Required('Confirm your password'), EqualTo('password', message='Passwords must match')] ) <NEW_LINE> submit = SubmitField('Confirm registration') <NEW_LINE> def validate_username(form, field): <NEW_LINE> <INDENT> if field.data: <NEW_LINE> <INDENT> allowed_set = set(string.ascii_letters + string.digits + '_-') <NEW_LINE> if set(field.data) - allowed_set: <NEW_LINE> <INDENT> raise ValidationError('Username can contain only letters,' 'digits, underscore and hyphen') <NEW_LINE> <DEDENT> user_mgr = UserAbstraction() <NEW_LINE> if not user_mgr.get_by_username(field.data) is None: <NEW_LINE> <INDENT> raise ValidationError('Such username already exists.') <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def validate_email(form, field): <NEW_LINE> <INDENT> if field.data: <NEW_LINE> <INDENT> user_mgr = UserAbstraction() <NEW_LINE> if not user_mgr.get_by_email(field.data) is None: <NEW_LINE> <INDENT> raise ValidationError('Such e-mail already exists.') <NEW_LINE> <DEDENT> return True | Register user form. Contains the following fields:
- username: TextField
- email: TextField
- password: PasswordField
- confirmpass: PasswordField
- submit: SubmitField | 62598fbabf627c535bcb161a |
class SlimGraphExecutor(object): <NEW_LINE> <INDENT> def __init__(self, place): <NEW_LINE> <INDENT> self.exe = executor.Executor(place) <NEW_LINE> self.place = place <NEW_LINE> <DEDENT> def run(self, graph, scope, data=None): <NEW_LINE> <INDENT> assert isinstance(graph, GraphWrapper) <NEW_LINE> feed = None <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> feeder = DataFeeder( feed_list=list(graph.in_nodes.values()), place=self.place, program=graph.program) <NEW_LINE> feed = feeder.feed(data) <NEW_LINE> <DEDENT> fetch_list = list(graph.out_nodes.values()) <NEW_LINE> program = graph.compiled_graph if graph.compiled_graph else graph.program <NEW_LINE> results = self.exe.run(program, scope=scope, fetch_list=fetch_list, feed=feed) <NEW_LINE> return results | Wrapper of executor used to run GraphWrapper. | 62598fbabe7bc26dc9251f17 |
@implementer(IEncodable, IRecord) <NEW_LINE> class SimpleRecord(tputil.FancyStrMixin, tputil.FancyEqMixin): <NEW_LINE> <INDENT> showAttributes = (('name', 'name', '%s'), 'ttl') <NEW_LINE> compareAttributes = ('name', 'ttl') <NEW_LINE> TYPE = None <NEW_LINE> name = None <NEW_LINE> def __init__(self, name=b'', ttl=None): <NEW_LINE> <INDENT> self.name = Name(name) <NEW_LINE> self.ttl = str2time(ttl) <NEW_LINE> <DEDENT> def encode(self, strio, compDict = None): <NEW_LINE> <INDENT> self.name.encode(strio, compDict) <NEW_LINE> <DEDENT> def decode(self, strio, length = None): <NEW_LINE> <INDENT> self.name = Name() <NEW_LINE> self.name.decode(strio) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.name) | A Resource Record which consists of a single RFC 1035 domain-name.
@type name: L{Name}
@ivar name: The name associated with this record.
@type ttl: L{int}
@ivar ttl: The maximum number of seconds which this record should be
cached. | 62598fbad7e4931a7ef3c20c |
class Atlanta(Team): <NEW_LINE> <INDENT> full_name: str = 'Atlanta Hawks' <NEW_LINE> tri_code: str = 'ATL' <NEW_LINE> team_id: str = '1610612737' <NEW_LINE> nick_name: str = 'Hawks' <NEW_LINE> url_name: str = 'hawks' | Represent `Atlanta Hawks` nba team. | 62598fbacc0a2c111447b183 |
class ProfileModelTests(TestCase): <NEW_LINE> <INDENT> def test_correct_team(self): <NEW_LINE> <INDENT> testuser = User.objects.create( username='testuser', password='password') <NEW_LINE> testuser.profile.fav_team = 'LAL' <NEW_LINE> self.assertEqual(testuser.profile.fav_team, 'LAL') <NEW_LINE> <DEDENT> def test_incorrect_team(self): <NEW_LINE> <INDENT> testuser = User.objects.create( username='testuser', password='password') <NEW_LINE> testuser.profile.fav_team = 'LAL' <NEW_LINE> self.assertNotEqual(testuser.profile.fav_team, 'GSW') <NEW_LINE> <DEDENT> def test_valid_birth_date(self): <NEW_LINE> <INDENT> testuser = User.objects.create( username='testuser', password='password') <NEW_LINE> testuser.profile.birth_date = date.today() <NEW_LINE> self.assertLessEqual(testuser.profile.birth_date, date.today()) <NEW_LINE> <DEDENT> def test_invalid_birth_date(self): <NEW_LINE> <INDENT> testuser = User.objects.create( username='testuser', password='password') <NEW_LINE> testuser.profile.birth_date = date.today() + timedelta(days=1) <NEW_LINE> self.assertGreater(testuser.profile.birth_date, date.today()) | Testing Profile model. | 62598fba97e22403b383b07d |
class Saver(object): <NEW_LINE> <INDENT> def __init__(self, save_prefix, num_max_keeping=1): <NEW_LINE> <INDENT> self.save_prefix = save_prefix.rstrip(".") <NEW_LINE> save_dir = os.path.dirname(self.save_prefix) <NEW_LINE> if not os.path.exists(save_dir): <NEW_LINE> <INDENT> os.mkdir(save_dir) <NEW_LINE> <DEDENT> self.save_dir = save_dir <NEW_LINE> if os.path.exists(self.save_prefix): <NEW_LINE> <INDENT> with open(self.save_prefix) as f: <NEW_LINE> <INDENT> save_list = f.readlines() <NEW_LINE> <DEDENT> save_list = [line.strip() for line in save_list] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> save_list = [] <NEW_LINE> <DEDENT> self.save_list = save_list <NEW_LINE> self.num_max_keeping = num_max_keeping <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def savable(obj): <NEW_LINE> <INDENT> if hasattr(obj, "state_dict") and hasattr(obj, "load_state_dict"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def save(self, global_step, **kwargs): <NEW_LINE> <INDENT> state_dict = dict() <NEW_LINE> for key, obj in kwargs.items(): <NEW_LINE> <INDENT> if self.savable(obj): <NEW_LINE> <INDENT> state_dict[key] = obj.state_dict() <NEW_LINE> <DEDENT> <DEDENT> saveto_path = '{0}.{1}'.format(self.save_prefix, global_step) <NEW_LINE> torch.save(state_dict, saveto_path) <NEW_LINE> self.save_list.append(os.path.basename(saveto_path)) <NEW_LINE> if len(self.save_list) > self.num_max_keeping: <NEW_LINE> <INDENT> out_of_date_state_dict = self.save_list.pop(0) <NEW_LINE> os.remove(os.path.join(self.save_dir, out_of_date_state_dict)) <NEW_LINE> <DEDENT> with open(self.save_prefix, "w") as f: <NEW_LINE> <INDENT> f.write("\n".join(self.save_list)) <NEW_LINE> <DEDENT> <DEDENT> def raw_save(self, **kwargs): <NEW_LINE> <INDENT> state_dict = dict() <NEW_LINE> for key, obj in kwargs.items(): <NEW_LINE> <INDENT> if self.savable(obj): <NEW_LINE> <INDENT> state_dict[key] = obj.state_dict() <NEW_LINE> <DEDENT> <DEDENT> save_to_path = '{0}.{1}'.format(self.save_prefix, "local") <NEW_LINE> torch.save(state_dict, save_to_path) <NEW_LINE> with open(self.save_prefix, "w") as f: <NEW_LINE> <INDENT> f.write(save_to_path) <NEW_LINE> <DEDENT> <DEDENT> def load_latest(self, **kwargs): <NEW_LINE> <INDENT> if len(self.save_list) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> latest_path = os.path.join(self.save_dir, self.save_list[-1]) <NEW_LINE> state_dict = torch.load(latest_path) <NEW_LINE> for name, obj in kwargs.items(): <NEW_LINE> <INDENT> if self.savable(obj): <NEW_LINE> <INDENT> if name not in state_dict: <NEW_LINE> <INDENT> print("Warning: {0} has no content saved!".format(name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Loading {0}".format(name)) <NEW_LINE> obj.load_state_dict(state_dict[name]) | Saver to save and restore objects.
Saver only accept objects which contain two method: ```state_dict``` and ```load_state_dict``` | 62598fba009cb60464d0169a |
class Log(Logn): <NEW_LINE> <INDENT> def __init__(self, dist): <NEW_LINE> <INDENT> super(Log, self).__init__(dist=dist, base=numpy.e) <NEW_LINE> self._repr_args = [dist] | Logarithm with base Euler's constant.
Args:
dist (Distribution):
Distribution to perform transformation on.
Example:
>>> distribution = chaospy.Log(chaospy.Uniform(1, 2))
>>> distribution
Log(Uniform(lower=1, upper=2)) | 62598fbaaad79263cf42e94b |
class ProjectorVersionTests(TestCase): <NEW_LINE> <INDENT> def test_version(self): <NEW_LINE> <INDENT> self.assertTrue(isinstance(projector.__version__, str)) <NEW_LINE> self.assertTrue(isinstance(projector.VERSION, tuple)) <NEW_LINE> VERSION_LENGTH = len(projector.VERSION) <NEW_LINE> self.assertTrue(3 <= VERSION_LENGTH and VERSION_LENGTH <= 5) | Checks if ``__version__`` and ``VERSION`` attributes
are set correctly in main module. | 62598fba7d43ff24874274bf |
class Pdpt(MMUTable): <NEW_LINE> <INDENT> addr_shift = 30 <NEW_LINE> addr_mask = 0x7FFFFFFFFFFFF000 <NEW_LINE> type_code = 'Q' <NEW_LINE> num_entries = 512 <NEW_LINE> supported_flags = INT_FLAGS | Page directory pointer table for IA-32e | 62598fba627d3e7fe0e07029 |
class TupleOfGenerators(ArbitraryInterface): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def arbitrary(cls): <NEW_LINE> <INDENT> return tuple([ arbitrary(generator) for generator in generators if generator is not tuple ]) | A closure class around the generators specified above, which
generates a tuple of the generators. | 62598fba60cbc95b063644b5 |
class GrrApplicationLogger(object): <NEW_LINE> <INDENT> def WriteFrontendLogEntry(self, event_id, request, response): <NEW_LINE> <INDENT> log_msg = "%s-%s %d: %s %s %s %d %s" % (event_id, request.source_ip, response.code, request.method, request.url, request.user_agent, response.size, request.user) <NEW_LINE> logging.info(log_msg) <NEW_LINE> <DEDENT> def GetNewEventId(self, event_time=None): <NEW_LINE> <INDENT> if event_time is None: <NEW_LINE> <INDENT> event_time = long(time.time() * 1e6) <NEW_LINE> <DEDENT> return "%s:%s:%s" % (event_time, socket.gethostname(), os.getpid()) <NEW_LINE> <DEDENT> def LogHttpApiCall(self, request, response): <NEW_LINE> <INDENT> return <NEW_LINE> log_msg = "API call [%s] by %s: %s [%d]" % (response.get("X-API-Method", "unknown"), request.user, request.path, response.status_code) <NEW_LINE> logging.info(log_msg) | The GRR application logger.
These records are used for machine readable authentication logging of security
critical events. | 62598fba97e22403b383b07e |
class NdarrayParam(Parameter): <NEW_LINE> <INDENT> equatable = True <NEW_LINE> def __init__(self, name, default=Unconfigurable, shape=None, optional=False, readonly=None): <NEW_LINE> <INDENT> if shape is not None: <NEW_LINE> <INDENT> assert shape.count('...') <= 1, ( "Cannot have more than one ellipsis") <NEW_LINE> <DEDENT> self.shape = shape <NEW_LINE> super(NdarrayParam, self).__init__(name, default, optional, readonly) <NEW_LINE> <DEDENT> @property <NEW_LINE> def coerce_defaults(self): <NEW_LINE> <INDENT> if self.shape is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return all(is_integer(dim) or dim in ('...', '*') for dim in self.shape) <NEW_LINE> <DEDENT> def hashvalue(self, instance): <NEW_LINE> <INDENT> return array_hash(self.__get__(instance, None)) <NEW_LINE> <DEDENT> def coerce(self, instance, value): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> value = self.coerce_ndarray(instance, value) <NEW_LINE> <DEDENT> return super(NdarrayParam, self).coerce(instance, value) <NEW_LINE> <DEDENT> def coerce_ndarray(self, instance, ndarray): <NEW_LINE> <INDENT> if isinstance(ndarray, np.ndarray): <NEW_LINE> <INDENT> ndarray = ndarray.view() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ndarray = np.array(ndarray, dtype=np.float64) <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> raise ValidationError( "Must be a float NumPy array (got type %r)" % type(ndarray).__name__, attr=self.name, obj=instance) <NEW_LINE> <DEDENT> <DEDENT> if self.readonly: <NEW_LINE> <INDENT> ndarray.setflags(write=False) <NEW_LINE> <DEDENT> if self.shape is None: <NEW_LINE> <INDENT> return ndarray <NEW_LINE> <DEDENT> if '...' in self.shape: <NEW_LINE> <INDENT> nfixed = len(self.shape) - 1 <NEW_LINE> n = ndarray.ndim - nfixed <NEW_LINE> if n < 0: <NEW_LINE> <INDENT> raise ValidationError("ndarray must be at least %dD (got %dD)" % (nfixed, ndarray.ndim), attr=self.name, obj=instance) <NEW_LINE> <DEDENT> i = self.shape.index('...') <NEW_LINE> shape = list(self.shape[:i]) + (['*'] * n) <NEW_LINE> if i < len(self.shape) - 1: <NEW_LINE> <INDENT> shape.extend(self.shape[i+1:]) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> shape = self.shape <NEW_LINE> <DEDENT> if ndarray.ndim != len(shape): <NEW_LINE> <INDENT> raise ValidationError("ndarray must be %dD (got %dD)" % (len(shape), ndarray.ndim), attr=self.name, obj=instance) <NEW_LINE> <DEDENT> for i, attr in enumerate(shape): <NEW_LINE> <INDENT> assert is_integer(attr) or is_string(attr), ( "shape can only be an int or str representing an attribute") <NEW_LINE> if attr == '*': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> desired = attr if is_integer(attr) else getattr(instance, attr) <NEW_LINE> if not is_integer(desired): <NEW_LINE> <INDENT> raise ValidationError( "%s not yet initialized; cannot determine if shape is " "correct. Consider using a distribution instead." % attr, attr=self.name, obj=instance) <NEW_LINE> <DEDENT> if ndarray.shape[i] != desired: <NEW_LINE> <INDENT> raise ValidationError("shape[%d] should be %d (got %d)" % (i, desired, ndarray.shape[i]), attr=self.name, obj=instance) <NEW_LINE> <DEDENT> <DEDENT> return ndarray | A parameter where the value is a NumPy ndarray.
If the passed value is an ndarray, a view onto that array is stored.
If the passed value is not an ndarray, it will be cast to an ndarray
of float64s and stored. | 62598fba4527f215b58ea04d |
class FrameType(Enum): <NEW_LINE> <INDENT> DATA = "data" <NEW_LINE> START = "start" <NEW_LINE> STOP = "stop" | Enum defining the message frame types | 62598fba99fddb7c1ca62ea7 |
class Punctuation(Tokenize): <NEW_LINE> <INDENT> punclist = [] <NEW_LINE> xlist = [" ", ""] <NEW_LINE> getstring = "" <NEW_LINE> def __init__(self, text): <NEW_LINE> <INDENT> Tokenize.__init__(self, text) <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> self.getstring = Tokenize.load(self) <NEW_LINE> self.punclist = re.split("\w+|[^a-z])", self.getstring) <NEW_LINE> self.filtered = [x for x in self.punclist if x not in self.xlist] <NEW_LINE> return self.filtered | делает токенизацию по символам | 62598fba91f36d47f2230f66 |
class TestSearchTMRequestDto(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 testSearchTMRequestDto(self): <NEW_LINE> <INDENT> pass | SearchTMRequestDto unit test stubs | 62598fba377c676e912f6e2c |
class BandwidthMeasuringProtocol(policies.ProtocolWrapper): <NEW_LINE> <INDENT> def write(self, data): <NEW_LINE> <INDENT> self.factory.registerWritten(len(data)) <NEW_LINE> policies.ProtocolWrapper.write(self, data) <NEW_LINE> <DEDENT> def writeSequence(self, seq): <NEW_LINE> <INDENT> self.factory.registerWritten(sum(map(len, seq))) <NEW_LINE> policies.ProtocolWrapper.writeSequence(self, seq) <NEW_LINE> <DEDENT> def dataReceived(self, data): <NEW_LINE> <INDENT> self.factory.registerRead(len(data)) <NEW_LINE> policies.ProtocolWrapper.dataReceived(self, data) | Wraps a Protocol and sends bandwidth stats to a BandwidthMeasuringFactory. | 62598fba63b5f9789fe852e6 |
class ParameterInversionManager(MethodManager): <NEW_LINE> <INDENT> def __init__(self, funct=None, fop=None, **kwargs): <NEW_LINE> <INDENT> if fop is not None: <NEW_LINE> <INDENT> if not isinstance(fop, pg.frameworks.ParameterModelling): <NEW_LINE> <INDENT> pg.critical("We need a fop if type ", pg.frameworks.ParameterModelling) <NEW_LINE> <DEDENT> <DEDENT> elif funct is not None: <NEW_LINE> <INDENT> fop = pg.frameworks.ParameterModelling(funct) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pg.critical("you should either give a valid fop or a function so " "I can create the fop for you") <NEW_LINE> <DEDENT> super(ParameterInversionManager, self).__init__(fop, **kwargs) <NEW_LINE> <DEDENT> def createInversionFramework(self, **kwargs): <NEW_LINE> <INDENT> return pg.frameworks.MarquardtInversion(**kwargs) <NEW_LINE> <DEDENT> def invert(self, data=None, err=None, **kwargs): <NEW_LINE> <INDENT> dataSpace = kwargs.pop(self.fop.dataSpaceName, None) <NEW_LINE> if dataSpace is not None: <NEW_LINE> <INDENT> self.fop.dataSpace = dataSpace <NEW_LINE> <DEDENT> limits = kwargs.pop('limits', {}) <NEW_LINE> for k, v in limits.items(): <NEW_LINE> <INDENT> self.fop.setRegionProperties(k, limits=v) <NEW_LINE> <DEDENT> startModel = kwargs.pop('startModel', {}) <NEW_LINE> if isinstance(startModel, dict): <NEW_LINE> <INDENT> for k, v in startModel.items(): <NEW_LINE> <INDENT> self.fop.setRegionProperties(k, startModel=v) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> kwargs['startModel'] = startModel <NEW_LINE> <DEDENT> return super(ParameterInversionManager, self).invert(data=data, err=err, **kwargs) | Framework to invert unconstrained parameters. | 62598fbad7e4931a7ef3c20e |
class StorageFolderLocation(object): <NEW_LINE> <INDENT> swagger_types = { 'storage': 'str', 'folder_path': 'str' } <NEW_LINE> attribute_map = { 'storage': 'storage', 'folder_path': 'folderPath' } <NEW_LINE> def __init__(self, storage: str = None, folder_path: str = None): <NEW_LINE> <INDENT> self._storage = None <NEW_LINE> self._folder_path = None <NEW_LINE> if storage is not None: <NEW_LINE> <INDENT> self.storage = storage <NEW_LINE> <DEDENT> if folder_path is not None: <NEW_LINE> <INDENT> self.folder_path = folder_path <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def storage(self) -> str: <NEW_LINE> <INDENT> return self._storage <NEW_LINE> <DEDENT> @storage.setter <NEW_LINE> def storage(self, storage: str): <NEW_LINE> <INDENT> self._storage = storage <NEW_LINE> <DEDENT> @property <NEW_LINE> def folder_path(self) -> str: <NEW_LINE> <INDENT> return self._folder_path <NEW_LINE> <DEDENT> @folder_path.setter <NEW_LINE> def folder_path(self, folder_path: str): <NEW_LINE> <INDENT> self._folder_path = folder_path <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> 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, StorageFolderLocation): <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 | A storage folder location information
| 62598fba7c178a314d78d617 |
class GitProfile(Resource): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> github_username, bitbucket_username = self.get_usernames() <NEW_LINE> if (github_username == None) or (bitbucket_username == None): <NEW_LINE> <INDENT> return { 'message': 'A merged user profile could not be returned. Please provide a github_username and a bitbucket_username key.'}, 400 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> git_hub_data = GetGitHubProfileData().call(github_username) <NEW_LINE> bit_bucket_data = GetBitBucketProfileData().call(bitbucket_username) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return { "message": "A merged profile could not be generated for the two usernames. Please check that you typed them right."} <NEW_LINE> <DEDENT> return MergeGitProfiles().call(git_hub_data, bit_bucket_data) <NEW_LINE> <DEDENT> def get_usernames(self): <NEW_LINE> <INDENT> parser = reqparse.RequestParser() <NEW_LINE> parser.add_argument('github_username') <NEW_LINE> parser.add_argument('bitbucket_username') <NEW_LINE> args = parser.parse_args() <NEW_LINE> github = args.get('github_username', None) <NEW_LINE> bitbucket = args.get('bitbucket_username', None) <NEW_LINE> return github, bitbucket | Return a merged git profile for a user.
Given a valid BitBucket and a valid GitHub usernames, the class will return a merged profile
of the user in JSON format. | 62598fba56ac1b37e6302365 |
class ExceptionLogger(object): <NEW_LINE> <INDENT> def __init__(self, logger, warn=None): <NEW_LINE> <INDENT> self.logger = logger <NEW_LINE> self.warn = warn <NEW_LINE> self.exception = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, type_, value, traceback): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> self.exception = value <NEW_LINE> if self.warn: <NEW_LINE> <INDENT> self.logger.warning(self.warn) <NEW_LINE> <DEDENT> self.logger.debug(value) <NEW_LINE> if is_debug(): <NEW_LINE> <INDENT> self.logger.exception(value) <NEW_LINE> <DEDENT> return True | Context that intercepts and logs exceptions.
Usage::
LOG = logging.getLogger(__name__)
...
def foobar():
with ExceptionLogger(LOG, "foobar warning") as e:
return house_of_raising_exception()
if e.exception:
raise e.exception # remove if not required | 62598fba56b00c62f0fb2a33 |
class PathModification(object): <NEW_LINE> <INDENT> FILENAME = 1 <NEW_LINE> EXTENSION = 2 <NEW_LINE> def __init__(self, path=None, range=None): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> if range is not None and range in [PathModification.FILENAME, PathModification.EXTENSION, PathModification.BASENAME]: <NEW_LINE> <INDENT> self.range = range <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.range = None <NEW_LINE> <DEDENT> <DEDENT> def get(self): <NEW_LINE> <INDENT> if self.range is PathModification.FILENAME: <NEW_LINE> <INDENT> return self.path.filename <NEW_LINE> <DEDENT> elif self.range is PathModification.EXTENSION: <NEW_LINE> <INDENT> return self.path.extension <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def set(self, newStr): <NEW_LINE> <INDENT> if self.range is PathModification.FILENAME: <NEW_LINE> <INDENT> self.path.filename = newStr <NEW_LINE> <DEDENT> elif self.range is PathModification.EXTENSION: <NEW_LINE> <INDENT> self.path.extension = newStr <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass | Modifier une partie du nom de fichier
@author: Julien | 62598fba10dbd63aa1c70d32 |
class ForumPortlet(AbstractPortlet): <NEW_LINE> <INDENT> def _query(self): <NEW_LINE> <INDENT> searcher = getAdapter(self.context, ICatalogSearch) <NEW_LINE> path = { 'query':model_path(self.context), } <NEW_LINE> total, docids, resolver = searcher( path=path, sort_index='modified_date', interfaces=[IForumTopic], reverse=True) <NEW_LINE> return resolver, list(docids) | Adapter for showing file entry data in views | 62598fba9f28863672818937 |
class Env(object): <NEW_LINE> <INDENT> def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> env = super(Env, cls).__new__(cls) <NEW_LINE> env._env_closer_id = env_closer.register(env) <NEW_LINE> env._closed = False <NEW_LINE> env.spec = None <NEW_LINE> return env <NEW_LINE> <DEDENT> metadata = {'render.modes': []} <NEW_LINE> reward_range = (-np.inf, np.inf) <NEW_LINE> def _close(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> action_space = None <NEW_LINE> observation_space = None <NEW_LINE> def _step(self, action): raise NotImplementedError <NEW_LINE> def _reset(self): raise NotImplementedError <NEW_LINE> def _render(self, mode='human', close=False): <NEW_LINE> <INDENT> if close: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def monitor(self): <NEW_LINE> <INDENT> if not hasattr(self, '_monitor'): <NEW_LINE> <INDENT> self._monitor = monitoring.Monitor(self) <NEW_LINE> <DEDENT> return self._monitor <NEW_LINE> <DEDENT> def step(self, action): <NEW_LINE> <INDENT> if not self.action_space.contains(action): <NEW_LINE> <INDENT> logger.warn("Action '{}' is not contained within action space '{}'.".format(action, self.action_space)) <NEW_LINE> <DEDENT> self.monitor._before_step(action) <NEW_LINE> observation, reward, done, info = self._step(action) <NEW_LINE> if not self.observation_space.contains(observation): <NEW_LINE> <INDENT> logger.warn("Observation '{}' is not contained within observation space '{}'.".format(observation, self.observation_space)) <NEW_LINE> <DEDENT> done = self.monitor._after_step(observation, reward, done, info) <NEW_LINE> return observation, reward, done, info <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.monitor._before_reset() <NEW_LINE> observation = self._reset() <NEW_LINE> self.monitor._after_reset(observation) <NEW_LINE> return observation <NEW_LINE> <DEDENT> def render(self, mode='human', close=False): <NEW_LINE> <INDENT> if close: <NEW_LINE> <INDENT> return self._render(close=close) <NEW_LINE> <DEDENT> modes = self.metadata.get('render.modes', []) <NEW_LINE> if len(modes) == 0: <NEW_LINE> <INDENT> raise error.UnsupportedMode('{} does not support rendering (requested mode: {})'.format(self, mode)) <NEW_LINE> <DEDENT> elif mode not in modes: <NEW_LINE> <INDENT> raise error.UnsupportedMode('Unsupported rendering mode: {}. (Supported modes for {}: {})'.format(mode, self, modes)) <NEW_LINE> <DEDENT> return self._render(mode=mode, close=close) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self._closed: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._close() <NEW_LINE> env_closer.unregister(self._env_closer_id) <NEW_LINE> self._closed = True <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '<{} instance>'.format(type(self).__name__) | The main OpenAI Gym class. It encapsulates an environment with
arbitrary behind-the-scenes dynamics. An environment can be
partially or fully observed.
The main API methods that users of this class need to know are:
reset
step
render
close
When implementing an environment, override the following methods
in your subclass:
_step
_reset
_render
And set the following attributes:
action_space: The Space object corresponding to valid actions
observation_space: The Space object corresponding to valid observations
reward_range: A tuple corresponding to the min and max possible rewards
The methods are accessed publicly as "step", "reset", etc.. The
non-underscored versions are wrapper methods to which we may add
functionality to over time. | 62598fba7cff6e4e811b5b9a |
class Address(object): <NEW_LINE> <INDENT> def __init__(self, address=None, pubkey=None, prefix="STM"): <NEW_LINE> <INDENT> self.prefix = prefix <NEW_LINE> if pubkey is not None: <NEW_LINE> <INDENT> self._pubkey = Base58(pubkey, prefix=prefix) <NEW_LINE> self._address = None <NEW_LINE> <DEDENT> elif address is not None: <NEW_LINE> <INDENT> self._pubkey = None <NEW_LINE> self._address = Base58(address, prefix=prefix) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Address has to be initialized by either the " + "pubkey or the address.") <NEW_LINE> <DEDENT> <DEDENT> def derivesha256address(self): <NEW_LINE> <INDENT> pkbin = unhexlify(repr(self._pubkey)) <NEW_LINE> addressbin = ripemd160(hexlify(hashlib.sha256(pkbin).digest())) <NEW_LINE> return Base58(hexlify(addressbin).decode('ascii')) <NEW_LINE> <DEDENT> def derivesha512address(self): <NEW_LINE> <INDENT> pkbin = unhexlify(repr(self._pubkey)) <NEW_LINE> addressbin = ripemd160(hexlify(hashlib.sha512(pkbin).digest())) <NEW_LINE> return Base58(hexlify(addressbin).decode('ascii')) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(self.derivesha512address()) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return format(self, self.prefix) <NEW_LINE> <DEDENT> def __format__(self, _format): <NEW_LINE> <INDENT> if self._address is None: <NEW_LINE> <INDENT> if _format.lower() == "btc": <NEW_LINE> <INDENT> return format(self.derivesha256address(), _format) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return format(self.derivesha512address(), _format) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return format(self._address, _format) <NEW_LINE> <DEDENT> <DEDENT> def __bytes__(self): <NEW_LINE> <INDENT> if self._address is None: <NEW_LINE> <INDENT> return compat_bytes(self.derivesha512address()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return compat_bytes(self._address) | Address class
This class serves as an address representation for Public Keys.
:param str address: Base58 encoded address (defaults to ``None``)
:param str pubkey: Base58 encoded pubkey (defaults to ``None``)
:param str prefix: Network prefix (defaults to ``GPH``)
Example::
Address("GPHFN9r6VYzBK8EKtMewfNbfiGCr56pHDBFi") | 62598fbae5267d203ee6ba79 |
class OsidOperableForm(OsidForm): <NEW_LINE> <INDENT> def get_enabled_metadata(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> enabled_metadata = property(fget=get_enabled_metadata) <NEW_LINE> def set_enabled(self, enabled): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def clear_enabled(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> enabled = property(fset=set_enabled, fdel=clear_enabled) <NEW_LINE> def get_disabled_metadata(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> disabled_metadata = property(fget=get_disabled_metadata) <NEW_LINE> def set_disabled(self, disabled): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def clear_disabled(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> disabled = property(fset=set_disabled, fdel=clear_disabled) | This form is used to create and update operables. | 62598fba0fa83653e46f505c |
class MSTRConstant: <NEW_LINE> <INDENT> _value = None <NEW_LINE> _dataType = None <NEW_LINE> def __init__(self, rootObj, dataType=None): <NEW_LINE> <INDENT> self._value = rootObj <NEW_LINE> self._dataType = self._detectdatatype(dataType) <NEW_LINE> <DEDENT> def _detectdatatype(self, dataType=None): <NEW_LINE> <INDENT> if dataType is None: <NEW_LINE> <INDENT> if isinstance(dataType, Number): <NEW_LINE> <INDENT> return 'Real' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Char' <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return dataType <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def _tomstrstr(self): <NEW_LINE> <INDENT> return str(self._value) <NEW_LINE> <DEDENT> def todict(self): <NEW_LINE> <INDENT> return dict(type="constant", dataType=self._dataType, value=self._tomstrstr) | Represents a constant in MSTR
The available typer are: Date, Time, TimeStamp, Real, Char | 62598fba091ae35668704d9b |
class RequestTooLongError(Fault): <NEW_LINE> <INDENT> def __init__(self, faultstring): <NEW_LINE> <INDENT> Fault.__init__(self, 'Client.RequestTooLong', faultstring) | Raised when the request is too long. | 62598fbaa219f33f346c697f |
class _Api(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def query(client, endpoint, **kwargs): <NEW_LINE> <INDENT> return client.post(endpoint=endpoint, **kwargs).json().get('data') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def tables_and_columns(client, endpoint, **kwargs): <NEW_LINE> <INDENT> return client.get(endpoint=endpoint, **kwargs).json().get('data') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def projects(client, endpoint, **kwargs): <NEW_LINE> <INDENT> return client.get(endpoint=endpoint, **kwargs).json().get('data') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def jobs(client, endpoint, **kwargs): <NEW_LINE> <INDENT> return client.get(endpoint=endpoint, **kwargs).json().get('data') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def resume_job(client, endpoint, **kwargs): <NEW_LINE> <INDENT> return client.put(endpoint=endpoint, **kwargs).json().get('data') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def tables(client, endpoint, **kwargs): <NEW_LINE> <INDENT> return client.get(endpoint=endpoint, **kwargs).json().get('data') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def cube_desc(client, endpoint, **kwargs): <NEW_LINE> <INDENT> return client.get(endpoint=endpoint, **kwargs).json().get('data') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def models(client, endpoint, **kwargs): <NEW_LINE> <INDENT> return client.get(endpoint=endpoint, **kwargs).json().get('data') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def cubes(client, endpoint, **kwargs): <NEW_LINE> <INDENT> return client.get(endpoint=endpoint, **kwargs).json().get('data') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def authentication(client, endpoint, **kwargs): <NEW_LINE> <INDENT> rv = client.get(endpoint=endpoint, **kwargs).json().get('data') <NEW_LINE> if rv == {}: <NEW_LINE> <INDENT> raise UnauthorizedError <NEW_LINE> <DEDENT> return rv | For testing convenience | 62598fba796e427e5384e90f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.