code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class R2LogRRBF(RadialBasisFunction): <NEW_LINE> <INDENT> def __init__(self, c): <NEW_LINE> <INDENT> super(R2LogRRBF, self).__init__(c) <NEW_LINE> <DEDENT> def _apply(self, points, **kwargs): <NEW_LINE> <INDENT> euclidean_distance = cdist(points, self.c) <NEW_LINE> mask = euclidean_distance == 0 <NEW_LINE> with np.errstate(divide='ignore', invalid='ignore'): <NEW_LINE> <INDENT> u = euclidean_distance ** 2 * np.log(euclidean_distance) <NEW_LINE> <DEDENT> u[mask] = 0 <NEW_LINE> return u <NEW_LINE> <DEDENT> def apply(self, x, batch_size=None, **kwargs): <NEW_LINE> <INDENT> def transform(x_): <NEW_LINE> <INDENT> return self._apply_batched(x_, batch_size, **kwargs) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return x._transform(transform) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return self._apply_batched(x, batch_size, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> def _apply_batched(self, x, batch_size, **kwargs): <NEW_LINE> <INDENT> if batch_size is None: <NEW_LINE> <INDENT> return self._apply(x, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> outputs = [] <NEW_LINE> n_points = x.shape[0] <NEW_LINE> for lo_ind in range(0, n_points, batch_size): <NEW_LINE> <INDENT> hi_ind = lo_ind + batch_size <NEW_LINE> outputs.append(self._apply(x[lo_ind:hi_ind], **kwargs)) <NEW_LINE> <DEDENT> return np.vstack(outputs)
Calculates the :math:`r^2 \log{r}` basis function. The derivative of this function is :math:`r (1 + 2 \log{r})`. .. note:: :math:`r = \lVert x - c \rVert` Parameters ---------- c : ``(n_centres, n_dims)`` `ndarray` The set of centers that make the basis. Usually represents a set of source landmarks.
6259905a435de62698e9d3eb
class TestDataWriterVTK(TestComponent): <NEW_LINE> <INDENT> _class = DataWriterVTK <NEW_LINE> _factory = data_writer
Unit testing of DataWriterVTK object.
6259905abe8e80087fbc066a
class MoveToDynamicPoint(sm.SM): <NEW_LINE> <INDENT> forwardGain = 1.0 <NEW_LINE> rotationGain = 0.5 <NEW_LINE> maxVel = 0.5 <NEW_LINE> angleEps = 0.1 <NEW_LINE> def getNextValues(self, state, inp): <NEW_LINE> <INDENT> (goalPoint, sensors) = inp <NEW_LINE> return (None, actionToPoint(goalPoint, sensors.odometry, self.forwardGain, self.rotationGain, self.maxVel, self.angleEps))
Drive to a goal point in the frame defined by the odometry. Goal points are part of the input, in contrast to C{MoveToFixedPoint}, which takes a single goal point at initialization time. Assume inputs are C{(util.Point, io.SensorInput)} pairs This is really a pure function machine; defining its own class, though, so we can easily modify the parameters.
6259905a0fa83653e46f64cd
class WebDown(object): <NEW_LINE> <INDENT> def __init__(self, address=None, proxy=None,): <NEW_LINE> <INDENT> self.downLoadaddress = address <NEW_LINE> self.proxy = proxy <NEW_LINE> self.htmlbody = None <NEW_LINE> <DEDENT> def getParsingRootOfTree(self, address=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if address == None : address = self.downLoadaddress <NEW_LINE> htmlsource = urllib2.urlopen(address).read() <NEW_LINE> self.htmlbody = BeautifulSoup(htmlsource, "html.parser") <NEW_LINE> return self.htmlbody <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None
classdocs
6259905a21bff66bcd72424c
class NuSVC(SparseBaseLibSVM, BaseSVC): <NEW_LINE> <INDENT> def __init__(self, nu=0.5, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False, tol=1e-3, cache_size=200, class_weight=None, verbose=False, max_iter=-1): <NEW_LINE> <INDENT> if class_weight is not None: <NEW_LINE> <INDENT> warnings.warn("Parameter class_weight is not supported in NuSVC " "and will be ignored.", stacklevel=2) <NEW_LINE> <DEDENT> super(NuSVC, self).__init__( 'nu_svc', kernel, degree, gamma, coef0, tol, 0., nu, 0., shrinking, probability, cache_size, None, verbose, max_iter)
NuSVC for sparse matrices (csr). See :class:`sklearn.svm.NuSVC` for a complete list of parameters Notes ----- For best results, this accepts a matrix in csr format (scipy.sparse.csr), but should be able to convert from any array-like object (including other sparse representations). Examples -------- >>> import numpy as np >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) >>> y = np.array([1, 1, 2, 2]) >>> from sklearn.svm.sparse import NuSVC >>> clf = NuSVC() >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE NuSVC(cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, nu=0.5, probability=False, shrinking=True, tol=0.001, verbose=False) >>> print(clf.predict([[-0.8, -1]])) [1]
6259905a7d847024c075d9c4
class Ctx: <NEW_LINE> <INDENT> __shared_state = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.__dict__ = self.__shared_state <NEW_LINE> if self.__dict__: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.set_defaults() <NEW_LINE> <DEDENT> def set_defaults(self): <NEW_LINE> <INDENT> self.output_option = None <NEW_LINE> self.dry_run = False <NEW_LINE> self.revision_collector = None <NEW_LINE> self.revision_reader = None <NEW_LINE> self.svnadmin_executable = config.SVNADMIN_EXECUTABLE <NEW_LINE> self.trunk_only = False <NEW_LINE> self.include_empty_directories = False <NEW_LINE> self.prune = True <NEW_LINE> self.cvs_author_decoder = CVSTextDecoder(['ascii']) <NEW_LINE> self.cvs_log_decoder = CVSTextDecoder(['ascii'], eol_fix='\n') <NEW_LINE> self.cvs_filename_decoder = CVSTextDecoder(['ascii']) <NEW_LINE> self.decode_apple_single = False <NEW_LINE> self.symbol_info_filename = None <NEW_LINE> self.username = None <NEW_LINE> self.file_property_setters = [] <NEW_LINE> self.revision_property_setters = [] <NEW_LINE> self.tmpdir = 'cvs2svn-tmp' <NEW_LINE> self.skip_cleanup = False <NEW_LINE> self.keep_cvsignore = False <NEW_LINE> self.cross_project_commits = True <NEW_LINE> self.cross_branch_commits = True <NEW_LINE> self.retain_conflicting_attic_files = False <NEW_LINE> self.text_wrapper = textwrap.TextWrapper(width=76, break_long_words=False) <NEW_LINE> self.initial_project_commit_message = ( 'Standard project directories initialized by cvs2svn.' ) <NEW_LINE> self.post_commit_message = ( 'This commit was generated by cvs2svn to compensate for ' 'changes in r%(revnum)d, which included commits to RCS files ' 'with non-trunk default branches.' ) <NEW_LINE> self.symbol_commit_message = ( "This commit was manufactured by cvs2svn to create %(symbol_type)s " "'%(symbol_name)s'." ) <NEW_LINE> self.tie_tag_ancestry_message = ( "This commit was manufactured by cvs2svn to tie ancestry for " "tag '%(symbol_name)s' back to the source branch." ) <NEW_LINE> <DEDENT> def get_temp_filename(self, basename): <NEW_LINE> <INDENT> return os.path.join(self.tmpdir, basename) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> for attr in self.__dict__.keys(): <NEW_LINE> <INDENT> if (attr.startswith('_') and not attr.startswith('__') and not attr.startswith('_Ctx__')): <NEW_LINE> <INDENT> delattr(self, attr)
Session state for this run of cvs2svn. For example, run-time options are stored here. This class is a Borg (see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531).
6259905ab7558d5895464a1f
class TestNodeUserProperties(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 testNodeUserProperties(self): <NEW_LINE> <INDENT> pass
NodeUserProperties unit test stubs
6259905af7d966606f7493ac
class MergedAlnfileSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> filetype = serializers.StringRelatedField() <NEW_LINE> download = serializers.HyperlinkedIdentityField(view_name='api:mergedalnfile-download') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = MergedAlnfile <NEW_LINE> fields = ('filename_on_disk','checksum','filetype','download')
This MergedAlnfile serializer links back to the main UI file download view.
6259905a498bea3a75a590f0
class TestBasicAuthPolicy(MockServerTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestBasicAuthPolicy, self).setUp() <NEW_LINE> self.policy = auth.PypicloudSecurityPolicy() <NEW_LINE> self.request.access = MagicMock() <NEW_LINE> self.get_creds = patch("pypicloud.auth.get_basicauth_credentials").start() <NEW_LINE> self.get_creds.return_value = None <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(TestBasicAuthPolicy, self).tearDown() <NEW_LINE> patch.stopall() <NEW_LINE> <DEDENT> def test_auth_userid_no_credentials(self): <NEW_LINE> <INDENT> self.get_creds.return_value = None <NEW_LINE> userid = self.policy.authenticated_userid(self.request) <NEW_LINE> self.assertIsNone(userid) <NEW_LINE> <DEDENT> def test_auth_fail_verification(self): <NEW_LINE> <INDENT> self.get_creds.return_value = {"login": "dsa", "password": "foobar"} <NEW_LINE> self.request.access.verify_user.return_value = False <NEW_LINE> userid = self.policy.authenticated_userid(self.request) <NEW_LINE> self.assertIsNone(userid) <NEW_LINE> <DEDENT> def test_auth(self): <NEW_LINE> <INDENT> self.get_creds.return_value = {"login": "dsa", "password": "foobar"} <NEW_LINE> self.request.access.verify_user.return_value = True <NEW_LINE> userid = self.policy.authenticated_userid(self.request) <NEW_LINE> self.assertEqual(userid, "dsa") <NEW_LINE> <DEDENT> def test_remember(self): <NEW_LINE> <INDENT> headers = self.policy.remember(self.request, "principal") <NEW_LINE> self.assertEqual(headers, []) <NEW_LINE> <DEDENT> def test_forget(self): <NEW_LINE> <INDENT> with patch.object(self.request, "session"): <NEW_LINE> <INDENT> headers = self.policy.forget(self.request) <NEW_LINE> self.assertEqual(headers, [])
Tests for the BasicAuthPolicy
6259905acc0a2c111447c5c2
class LocaleMiddleware(object): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> a_l = get_accept_language(request) <NEW_LINE> lang, ov_lang = a_l, '' <NEW_LINE> stored_lang, stored_ov_lang = '', '' <NEW_LINE> remembered = request.COOKIES.get('lang') <NEW_LINE> if remembered: <NEW_LINE> <INDENT> chunks = remembered.split(',')[:2] <NEW_LINE> stored_lang = chunks[0] <NEW_LINE> try: <NEW_LINE> <INDENT> stored_ov_lang = chunks[1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if stored_lang.lower() in settings.LANGUAGE_URL_MAP: <NEW_LINE> <INDENT> lang = stored_lang <NEW_LINE> <DEDENT> if stored_ov_lang.lower() in settings.LANGUAGE_URL_MAP: <NEW_LINE> <INDENT> ov_lang = stored_ov_lang <NEW_LINE> <DEDENT> <DEDENT> if 'lang' in request.REQUEST: <NEW_LINE> <INDENT> ov_lang = a_l <NEW_LINE> lang = Prefixer(request).get_language() <NEW_LINE> <DEDENT> elif a_l != ov_lang: <NEW_LINE> <INDENT> lang = a_l <NEW_LINE> ov_lang = '' <NEW_LINE> <DEDENT> if lang != stored_lang or ov_lang != stored_ov_lang: <NEW_LINE> <INDENT> request.LANG_COOKIE = ','.join([lang, ov_lang]) <NEW_LINE> if (getattr(request, 'amo_user', None) and request.amo_user.lang != lang): <NEW_LINE> <INDENT> request.amo_user.lang = lang <NEW_LINE> request.amo_user.save() <NEW_LINE> <DEDENT> <DEDENT> request.LANG = lang <NEW_LINE> tower.activate(lang) <NEW_LINE> <DEDENT> def process_response(self, request, response): <NEW_LINE> <INDENT> if hasattr(request, 'LANG_COOKIE'): <NEW_LINE> <INDENT> response.set_cookie('lang', request.LANG_COOKIE) <NEW_LINE> <DEDENT> patch_vary_headers(response, ['Accept-Language', 'Cookie']) <NEW_LINE> return response
Figure out the user's locale and store it in a cookie.
6259905a3eb6a72ae038bc47
class DeploymentConfig(BaseConfig): <NEW_LINE> <INDENT> DEBUG = False
Deployment environment config
6259905a32920d7e50bc762e
class URL(TextBox): <NEW_LINE> <INDENT> def __init__(self, name, socket_io, change_callback=None, disabled=None, readonly=None, url=None, desc=None, prop=None, style=None, attr=None, css_cls=None): <NEW_LINE> <INDENT> TextBox.__init__(self, name, socket_io, text=url, desc=desc, prop=prop, style=style, attr=attr, css_cls=css_cls, change_callback=change_callback, disabled=disabled, readonly=readonly) <NEW_LINE> self.add_property('type', 'url')
URL widget is used to take website address as input from the user.
6259905ad53ae8145f919a4a
class NordpoolFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._errors = {} <NEW_LINE> <DEDENT> async def async_step_user( self, user_input=None ): <NEW_LINE> <INDENT> self._errors = {} <NEW_LINE> if user_input is not None: <NEW_LINE> <INDENT> if user_input["additional_costs"] == "": <NEW_LINE> <INDENT> user_input["additional_costs"] = DEFAULT_TEMPLATE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user_input["additional_costs"] = re.sub(r"\s{2,}", '', user_input["additional_costs"]) <NEW_LINE> if not is_template_string(user_input["additional_costs"]): <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> return self.async_create_entry(title="Nordpool", data=user_input) <NEW_LINE> <DEDENT> data_schema = { vol.Required("region", default=None): vol.In(regions), vol.Optional("friendly_name", default=""): str, vol.Optional("currency", default=""): vol.In(currencys), vol.Optional("VAT", default=True): bool, vol.Optional("precision", default=3): vol.Coerce(int), vol.Optional("low_price_cutoff", default=1.0): vol.Coerce(float), vol.Optional("price_in_cents", default=False): bool, vol.Optional("price_type", default="kWh"): vol.In(price_types), vol.Optional("additional_costs", default=""): str } <NEW_LINE> placeholders = { "region": regions, "currency": currencys, "price_type": price_types, "additional_costs": "{{0}}" } <NEW_LINE> return self.async_show_form( step_id="user", data_schema=vol.Schema(data_schema), description_placeholders=placeholders, errors=self._errors, ) <NEW_LINE> <DEDENT> async def async_step_import(self, user_input): <NEW_LINE> <INDENT> return self.async_create_entry(title="configuration.yaml", data={})
Config flow for Nordpool.
6259905abaa26c4b54d5088d
class TextBlock: <NEW_LINE> <INDENT> def __init__(self, text, blockType = BlockType.Plain, postText = ""): <NEW_LINE> <INDENT> self.InnerBlocks = [] <NEW_LINE> self.Text = text <NEW_LINE> self.Type = blockType <NEW_LINE> self.PostText = postText
Text block class.
6259905ad99f1b3c44d06c89
class SapHanaAuthenticationType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> BASIC = "Basic" <NEW_LINE> WINDOWS = "Windows"
The authentication type to be used to connect to the SAP HANA server.
6259905ad7e4931a7ef3d667
class FunctionScoreQuery(DslQuery): <NEW_LINE> <INDENT> def __init__(self, query, functions, maxBoost = None, scoreMode = None, boostMode = None, minScore = None, boost = None, matchedName = None): <NEW_LINE> <INDENT> body = { 'query': query, 'functions': functions } <NEW_LINE> if not maxBoost is None: <NEW_LINE> <INDENT> body['max_boost'] = maxBoost <NEW_LINE> <DEDENT> if not scoreMode is None: <NEW_LINE> <INDENT> body['score_mode'] = scoreMode <NEW_LINE> <DEDENT> if not boostMode is None: <NEW_LINE> <INDENT> body['boost_mode'] = boostMode <NEW_LINE> <DEDENT> if not minScore is None: <NEW_LINE> <INDENT> body['min_score'] = minScore <NEW_LINE> <DEDENT> super(FunctionScoreQuery, self).__init__('function_score', body, boost, matchedName)
The function score query
6259905a004d5f362081fae2
class SettlingState(HoveringState): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def getattr(): <NEW_LINE> <INDENT> attrs = {} <NEW_LINE> attrs.update(HoveringState.getattr()) <NEW_LINE> attrs.update({'planeThreshold' : 0.1, 'angleThreshold' : 5}) <NEW_LINE> return attrs <NEW_LINE> <DEDENT> def _compareChange(self, pvalues, dvalues): <NEW_LINE> <INDENT> errorAdj = self._bin.errorAdj() <NEW_LINE> return errorAdj[0] < self._planeThreshold and errorAdj[1] < self._planeThreshold and errorAdj[2] < self._angleThreshold <NEW_LINE> <DEDENT> def BIN_FOUND(self, event): <NEW_LINE> <INDENT> HoveringState.BIN_FOUND(self, event) <NEW_LINE> if self._earlyTimeout and self._currentBin(event): <NEW_LINE> <INDENT> if self._compareChange((event.x, event.y, event.angle), self._bin.changeOverTime()): <NEW_LINE> <INDENT> if self.timer is not None: <NEW_LINE> <INDENT> self.timer.stop() <NEW_LINE> <DEDENT> self.publish(self._eventType, core.Event()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def enter(self, eventType, eventTime, useMultiAngle = False, shouldRotate = True): <NEW_LINE> <INDENT> self._eventType = eventType <NEW_LINE> self._kp = self._config.get('kp', 1.0) <NEW_LINE> self._kd = self._config.get('kd', 1.0) <NEW_LINE> self._earlyTimeout = self.ai.data['config'].get('Bin', {}).get( 'earlyTimeout', False) <NEW_LINE> self.timer = self.timerManager.newTimer(eventType, eventTime) <NEW_LINE> self.timer.start() <NEW_LINE> HoveringState.enter(self, useMultiAngle, shouldRotate) <NEW_LINE> <DEDENT> def exit(self): <NEW_LINE> <INDENT> HoveringState.exit(self) <NEW_LINE> self.timer.stop()
A specialization of the hover state which hovers for the given time.
6259905a7d847024c075d9c6
class Main: <NEW_LINE> <INDENT> ADD_BOOK = BASE_URL+'/books' <NEW_LINE> ALL_BOOKS = BASE_URL+'/books' <NEW_LINE> MODIFY_BOOK = BASE_URL+'/books/<int:book_id>' <NEW_LINE> DELETE_BOOK = BASE_URL+'/books/<int:book_id>' <NEW_LINE> GET_BOOK = BASE_URL+'/books/<int:book_id>' <NEW_LINE> BORROW = BASE_URL+'/users/books/<int:book_id>' <NEW_LINE> RETURN = BASE_URL+'/users/books/<int:book_id>' <NEW_LINE> BORROWING_HISTORY = BASE_URL+'/users/books' <NEW_LINE> UNRETURNED = BASE_URL+'/users/books'
Main application endpoints
6259905a16aa5153ce401acc
class with_auth(object): <NEW_LINE> <INDENT> def __init__(self, username_key, password_key): <NEW_LINE> <INDENT> self.username_key = username_key <NEW_LINE> self.password_key = password_key <NEW_LINE> <DEDENT> def __call__(decorator, f): <NEW_LINE> <INDENT> def inner(self, *args): <NEW_LINE> <INDENT> from test_login import LoginTests <NEW_LINE> l = LoginTests(self.selenium, self.config, self.log) <NEW_LINE> try: <NEW_LINE> <INDENT> username = self.config.get(decorator.username_key) <NEW_LINE> password = self.config.get(decorator.password_key) <NEW_LINE> l.do_login(username, password) <NEW_LINE> f(self) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> l.do_logout() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return inner
Decorator to login before function, and logout afterwards
6259905af7d966606f7493ad
@deconstructible <NEW_LINE> class FDFSStorage(Storage): <NEW_LINE> <INDENT> def __init__(self, client_conf=None, base_url=None): <NEW_LINE> <INDENT> if client_conf is None: <NEW_LINE> <INDENT> client_conf = settings.FDFS_CLIENT_CONF <NEW_LINE> <DEDENT> self.client_conf = client_conf <NEW_LINE> if base_url is None: <NEW_LINE> <INDENT> base_url = settings.FDFS_NGINX_URL <NEW_LINE> <DEDENT> self.base_url = base_url <NEW_LINE> <DEDENT> def _save(self, name, content): <NEW_LINE> <INDENT> client = Fdfs_client(self.client_conf) <NEW_LINE> ret = client.upload_by_buffer(content.read()) <NEW_LINE> if ret.get('Status') != 'Upload successed.': <NEW_LINE> <INDENT> raise Exception('上传文件到FDFS失败') <NEW_LINE> <DEDENT> file_id = ret.get('Remote file_id') <NEW_LINE> return file_id <NEW_LINE> <DEDENT> def exists(self, name): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def url(self, name): <NEW_LINE> <INDENT> return self.base_url + name
FDFS文件存储类
6259905a10dbd63aa1c7216f
class LimitedSet(object): <NEW_LINE> <INDENT> def __init__(self, maxlen=None, expires=None, data=None, heap=None): <NEW_LINE> <INDENT> self.maxlen = maxlen <NEW_LINE> self.expires = expires <NEW_LINE> self._data = {} if data is None else data <NEW_LINE> self._heap = [] if heap is None else heap <NEW_LINE> self.__iter__ = self._data.__iter__ <NEW_LINE> self.__len__ = self._data.__len__ <NEW_LINE> self.__contains__ = self._data.__contains__ <NEW_LINE> <DEDENT> def add(self, value, now=time.time): <NEW_LINE> <INDENT> self.purge(1, offset=1) <NEW_LINE> inserted = now() <NEW_LINE> self._data[value] = inserted <NEW_LINE> heappush(self._heap, (inserted, value)) <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self._data.clear() <NEW_LINE> self._heap[:] = [] <NEW_LINE> <DEDENT> def discard(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> itime = self._data[value] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._heap.remove((value, itime)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self._data.pop(value, None) <NEW_LINE> <DEDENT> pop_value = discard <NEW_LINE> def purge(self, limit=None, offset=0, now=time.time): <NEW_LINE> <INDENT> H, maxlen = self._heap, self.maxlen <NEW_LINE> if not maxlen: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> limit = len(self) + offset if limit is None else limit <NEW_LINE> i = 0 <NEW_LINE> while len(self) + offset > maxlen: <NEW_LINE> <INDENT> if i >= limit: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> item = heappop(H) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if self.expires: <NEW_LINE> <INDENT> if now() < item[0] + self.expires: <NEW_LINE> <INDENT> heappush(H, item) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> self._data.pop(item[1]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> <DEDENT> def update(self, other, heappush=heappush): <NEW_LINE> <INDENT> if isinstance(other, self.__class__): <NEW_LINE> <INDENT> self._data.update(other._data) <NEW_LINE> self._heap.extend(other._heap) <NEW_LINE> heapify(self._heap) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for obj in other: <NEW_LINE> <INDENT> self.add(obj) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> return self._data <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self._heap == other._heap <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'LimitedSet({0})'.format(len(self)) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return (item[1] for item in self._heap) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._heap) <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self._data <NEW_LINE> <DEDENT> def __reduce__(self): <NEW_LINE> <INDENT> return self.__class__, ( self.maxlen, self.expires, self._data, self._heap, )
Kind-of Set with limitations. Good for when you need to test for membership (`a in set`), but the list might become to big. :keyword maxlen: Maximum number of members before we start evicting expired members. :keyword expires: Time in seconds, before a membership expires.
6259905a460517430c432b47
class OpenedTables(StatuBase): <NEW_LINE> <INDENT> statu_name="Opened_Tables"
The number of tables that have been opened. If Opened_tables is big, your table_open_cache value is probably too small.
6259905a56ac1b37e63037dc
class BoundFunctionWrapper(ObjectProxy): <NEW_LINE> <INDENT> __slots__ = ("instance", "wrapper", "binding", "parent") <NEW_LINE> def __init__(self, wrapped, instance, wrapper, binding, parent): <NEW_LINE> <INDENT> super().__init__(wrapped) <NEW_LINE> object.__setattr__(self, "instance", instance) <NEW_LINE> object.__setattr__(self, "wrapper", wrapper) <NEW_LINE> object.__setattr__(self, "binding", binding) <NEW_LINE> object.__setattr__(self, "parent", parent) <NEW_LINE> <DEDENT> def __get__(self, instance, owner): <NEW_LINE> <INDENT> if self.instance is None and self.binding == "function": <NEW_LINE> <INDENT> descriptor = self.parent.__wrapped__.__get__(instance, owner) <NEW_LINE> return BoundFunctionWrapper( descriptor, instance, self.wrapper, self.binding, self.parent ) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.binding == "function": <NEW_LINE> <INDENT> if self.instance is None: <NEW_LINE> <INDENT> instance, args = args[0], args[1:] <NEW_LINE> wrapped = functools.partial(self.__wrapped__, instance) <NEW_LINE> return self.wrapper(wrapped, instance, args, kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.wrapper(self.__wrapped__, self.instance, args, kwargs) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> instance = getattr(self.__wrapped__, "__self__", None) <NEW_LINE> return self.wrapper(self.__wrapped__, instance, args, kwargs)
A descriptor to emulate a bound function. This is used to create bound function decorators. It maintains all of the nice introspection that can normally be done on bound functions.
6259905a097d151d1a2c2657
class UserProfile(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length=255, unique=True) <NEW_LINE> name = models.CharField(max_length =255) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> objects = UserProfileManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = ['name'] <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email
Database model for users in the system
6259905ab5575c28eb7137c1
class ConstValueDict(dict): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> name = self.__class__.__name__ <NEW_LINE> content = super(ConstValueDict, self).__repr__() <NEW_LINE> return '{name}({content})'.format(name=name, content=content) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> if key in self and self[key] != value: <NEW_LINE> <INDENT> raise AssertionError('Values for key `%s` are inconsistent ' '(%s != %s).' % (key, self[key], value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(ConstValueDict, self).__setitem__(key, value) <NEW_LINE> <DEDENT> <DEDENT> def update(self, *args, **kwargs): <NEW_LINE> <INDENT> for key, value in six.iteritems(dict(*args, **kwargs)): <NEW_LINE> <INDENT> self[key] = value
represents a dictionary where values cannot be set to a new value when they have been set once. An `AssertionError` is raised if a value is attempted to be changed.
6259905a99cbb53fe68324ca
class FunctionKroneckerDelta(BuiltinFunction): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> BuiltinFunction.__init__(self, "kronecker_delta", nargs=2, conversions=dict(maxima='kron_delta', mathematica='KroneckerDelta')) <NEW_LINE> <DEDENT> def _eval_(self, m, n): <NEW_LINE> <INDENT> if bool(repr(m) > repr(n)): <NEW_LINE> <INDENT> return kronecker_delta(n, m) <NEW_LINE> <DEDENT> x = m - n <NEW_LINE> try: <NEW_LINE> <INDENT> approx_x = ComplexIntervalField()(x) <NEW_LINE> if bool(approx_x.imag() == 0): <NEW_LINE> <INDENT> if bool(approx_x.real() == 0): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> except StandardError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def _derivative_(self, *args, **kwds): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def _print_latex_(self, m, n, **kwds): <NEW_LINE> <INDENT> from sage.misc.latex import latex <NEW_LINE> return "\\delta_{%s,%s}"%(latex(m), latex(n))
The Kronecker delta function `\delta_{m,n}` (``kronecker_delta(m, n)``). INPUT: - ``m`` - a number or a symbolic expression - ``n`` - a number or a symbolic expression DEFINITION: Kronecker delta function `\delta_{m,n}` is defined as: `\delta_{m,n} = 0` for `m \ne n` and `\delta_{m,n} = 1` for `m = n` EXAMPLES:: sage: kronecker_delta(1,2) 0 sage: kronecker_delta(1,1) 1 sage: m,n=var('m,n') sage: kronecker_delta(m,n) kronecker_delta(m, n) REFERENCES: - http://en.wikipedia.org/wiki/Kronecker_delta
6259905add821e528d6da475
class RemoteClosedException(RabbitpyException): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Connection was closed by the remote server ' '({0}): {1}'.format(*self.args)
Raised if RabbitMQ closes the connection and the reply_code in the Connection.Close RPC request does not have a mapped exception in Rabbitpy.
6259905a23e79379d538dae6
class MapAgent(MapPosition, Agent): <NEW_LINE> <INDENT> def __init__( self, x: int = 0, y: int = 0, direction: DirectionType = 0, reverseY: bool = True, frame: Optional[Iterable[Iterable[Any]]] = None, xmin: Numeric = -inf, xmax: Numeric = inf, ymin: Numeric = -inf, ymax: Numeric = inf, occupied: Callable[[Position], bool] = lambda p: False ): <NEW_LINE> <INDENT> Agent.__init__( self, x, y, direction = direction, reverseY = reverseY ) <NEW_LINE> MapPosition.__init__( self, x, y, reverseY = reverseY, frame = frame, xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, occupied = occupied ) <NEW_LINE> self.direction = dirToNum(direction) <NEW_LINE> <DEDENT> def __add__(self, vector: Vector) -> MapAgent: <NEW_LINE> <INDENT> return MapAgent( self.x + vector.vx, self.y + vector.vy, reverseY = self.reverseY, direction = self.direction, xmin = self.xmin, xmax = self.xmax, ymin = self.ymin, ymax = self.ymax, occupied = self._occupiedFunction ) <NEW_LINE> <DEDENT> def __hash__(self) -> NoReturn: <NEW_LINE> <INDENT> raise(Exception("Class not hashable")) <NEW_LINE> <DEDENT> def move(self, n: int = 1, direction: Optional[DirectionType] = None) -> None: <NEW_LINE> <INDENT> if direction is None: <NEW_LINE> <INDENT> direction = self.direction <NEW_LINE> <DEDENT> if n != 1: <NEW_LINE> <INDENT> for _ in range(n): <NEW_LINE> <INDENT> self.move(n=1, direction=direction) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> v = VectorDir(direction=direction, reverseY=self.reverseY) <NEW_LINE> newpos = (self + v) <NEW_LINE> if newpos.isValid(): <NEW_LINE> <INDENT> super().move(n=1, direction=direction) <NEW_LINE> <DEDENT> <DEDENT> def mapPosition(self) -> MapPosition: <NEW_LINE> <INDENT> return MapPosition( self.x, self.y, reverseY = self.reverseY, xmin = self.xmin, xmax = self.xmax, ymin = self.ymin, ymax = self.ymax, occupied = self._occupiedFunction )
MapAgent class: represents an agent on a MapPosition. Inherits from MapPosition, Agent Syntax is MapAgent(x, y, direction=0, reverseY=True, frame=None, xmin=-inf, xmax=inf, ymin=-inf, xmax=inf, occupied=lambda p: False) [Not hashable] MapAgent inherits both from MapPosition and Agent, with the following changes: - A MapAgent has a mapPosition method returning the corresponding MapPosition - The move method now proceeds one step at a time and check for validity before moving.
6259905a32920d7e50bc7630
class HTTPClient(object): <NEW_LINE> <INDENT> def __init__(self, async_client_class=None, **kwargs): <NEW_LINE> <INDENT> self._io_loop = IOLoop(make_current=False) <NEW_LINE> if async_client_class is None: <NEW_LINE> <INDENT> async_client_class = AsyncHTTPClient <NEW_LINE> <DEDENT> self._async_client = async_client_class(self._io_loop, **kwargs) <NEW_LINE> self._closed = False <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if not self._closed: <NEW_LINE> <INDENT> self._async_client.close() <NEW_LINE> self._io_loop.close() <NEW_LINE> self._closed = True <NEW_LINE> <DEDENT> <DEDENT> def fetch(self, request, **kwargs): <NEW_LINE> <INDENT> response = self._io_loop.run_sync(functools.partial( self._async_client.fetch, request, **kwargs)) <NEW_LINE> return response
一个阻塞的 HTTP 客户端. 提供这个接口是为了方便使用和测试; 大多数运行于 IOLoop 的应用程序 会使用 `AsyncHTTPClient` 来替代它. 一般的用法就像这样 :: http_client = httpclient.HTTPClient() try: response = http_client.fetch("http://www.google.com/") print response.body except httpclient.HTTPError as e: # HTTPError is raised for non-200 responses; the response # can be found in e.response. print("Error: " + str(e)) except Exception as e: # Other errors are possible, such as IOError. print("Error: " + str(e)) http_client.close()
6259905a45492302aabfdac2
class RuleManager(RuleQueryMixin, models.Manager): <NEW_LINE> <INDENT> def get_query_set(self): <NEW_LINE> <INDENT> return RuleSet(self.model, using=self._db)
Manager with helpful methods for working with :class:`Rule`s.
6259905a379a373c97d9a60f
class Solution: <NEW_LINE> <INDENT> def groupingOptions(self, n, m): <NEW_LINE> <INDENT> if n < m: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> dp = [[0] * (m + 1) for _ in range(n + 1)] <NEW_LINE> for i in range(1, m + 1): <NEW_LINE> <INDENT> dp[i][i] = 1 <NEW_LINE> <DEDENT> for i in range(2, n + 1): <NEW_LINE> <INDENT> tmp = min(i, m) <NEW_LINE> for j in range(1, tmp + 1): <NEW_LINE> <INDENT> dp[i][j] = dp[i - 1][j - 1] + dp[i - j][j] <NEW_LINE> <DEDENT> <DEDENT> return dp[n][m]
@param n: the number of people @param m: the number of groups @return: the number of grouping options
6259905aa17c0f6771d5d697
class LineEffect: <NEW_LINE> <INDENT> base_params_keys = tuple() <NEW_LINE> optional_params_values = {"gaussian_sigma": 10, "contour_barrier": 0.01, "background_color": None, "line_width": 10, "barrier": 0.5, "facecolor": "none", "line_color": "white", "line_style": "solid", "line_alpha": 1} <NEW_LINE> def check_params_keys(self, params_keys): <NEW_LINE> <INDENT> for key in self.base_params_keys: <NEW_LINE> <INDENT> if key not in params_keys: <NEW_LINE> <INDENT> raise Exception("Wrong line effect params") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def apply(self, masks, img, params): <NEW_LINE> <INDENT> self.check_params_keys(params.keys()) <NEW_LINE> gaussian_sigma = params["gaussian_sigma"] if "gaussian_sigma" in params else self.optional_params_values[ "gaussian_sigma"] <NEW_LINE> contour_barrier = params["contour_barrier"] if "contour_barrier" in params else self.optional_params_values[ "contour_barrier"] <NEW_LINE> background_color = params["background_color"] if "background_color" in params else self.optional_params_values["background_color"] <NEW_LINE> line_width = params["line_width"] if "line_width" in params else self.optional_params_values["line_width"] <NEW_LINE> barrier = params["barrier"] if "barrier" in params else self.optional_params_values["barrier"] <NEW_LINE> facecolor = params["facecolor"] if "facecolor" in params else self.optional_params_values["facecolor"] <NEW_LINE> line_color = params["line_color"] if "line_color" in params else self.optional_params_values["line_color"] <NEW_LINE> line_style = params["line_style"] if "line_style" in params else self.optional_params_values["line_style"] <NEW_LINE> line_alpha = params["line_alpha"] if "line_alpha" in params else self.optional_params_values["line_alpha"] <NEW_LINE> my_dpi = get_dpi() <NEW_LINE> fig, ax = plt.subplots(1, figsize=(img.shape[1] / my_dpi, img.shape[0] / my_dpi), dpi=my_dpi) <NEW_LINE> ax.axis("off") <NEW_LINE> contours = get_contours(masks, gaussian_sigma=gaussian_sigma, contour_barrier=contour_barrier) <NEW_LINE> for verts in contours: <NEW_LINE> <INDENT> verts = np.fliplr(verts) - 1 <NEW_LINE> p = Polygon(verts, facecolor=facecolor, edgecolor=line_color, lw=line_width, closed=False, ls=line_style, snap=False, alpha=line_alpha) <NEW_LINE> ax.add_patch(p) <NEW_LINE> <DEDENT> img = img.astype(np.uint32).copy() <NEW_LINE> if background_color is not None: <NEW_LINE> <INDENT> img = fill_background(img, masks, color=background_color, alpha=1.0, barrier=barrier) <NEW_LINE> <DEDENT> ax.imshow(img.astype(np.uint8), aspect="auto") <NEW_LINE> plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) <NEW_LINE> s, (width, height) = fig.canvas.print_to_buffer() <NEW_LINE> data = np.frombuffer(s, np.uint8).reshape((height, width, 4)) <NEW_LINE> return data
Example: {"background": None, "line_width": 10, "barrier": 0.5, "gaussian_sigma": 10, "contour_barrier": 0.01, "line_color": "white", "line_style": "solid", "facecolor": "none"}
6259905a7cff6e4e811b702e
class ProjectExtraForm(ProjectForm): <NEW_LINE> <INDENT> class Meta(object): <NEW_LINE> <INDENT> model = Project <NEW_LINE> fields = ( 'description', 'documentation_type', 'language', 'programming_language', 'project_url', 'tags', ) <NEW_LINE> <DEDENT> description = forms.CharField( validators=[ClassifierValidator(raises=ProjectSpamError)], required=False, widget=forms.Textarea )
Additional project information form
6259905a91af0d3eaad3b413
class TProcessor(object): <NEW_LINE> <INDENT> def __init__(self, service, handler): <NEW_LINE> <INDENT> self._service = service <NEW_LINE> self._handler = handler <NEW_LINE> <DEDENT> def process_in(self, iprot): <NEW_LINE> <INDENT> api, type, seqid = iprot.read_message_begin() <NEW_LINE> if api not in self._service.thrift_services: <NEW_LINE> <INDENT> iprot.skip(TType.STRUCT) <NEW_LINE> iprot.read_message_end() <NEW_LINE> return api, seqid, TApplicationException(TApplicationException.UNKNOWN_METHOD), None <NEW_LINE> <DEDENT> args = getattr(self._service, api + "_args")() <NEW_LINE> args.read(iprot) <NEW_LINE> iprot.read_message_end() <NEW_LINE> result = getattr(self._service, api + "_result")() <NEW_LINE> api_args = [args.thrift_spec[k][1] for k in sorted(args.thrift_spec)] <NEW_LINE> call = lambda: getattr(self._handler, api)( *(args.__dict__[k] for k in api_args) ) <NEW_LINE> return api, seqid, result, call <NEW_LINE> <DEDENT> def send_exception(self, oprot, api, exc, seqid): <NEW_LINE> <INDENT> oprot.write_message_begin(api, TMessageType.EXCEPTION, seqid) <NEW_LINE> exc.write(oprot) <NEW_LINE> oprot.write_message_end() <NEW_LINE> oprot.trans.flush() <NEW_LINE> <DEDENT> def send_result(self, oprot, api, result, seqid): <NEW_LINE> <INDENT> oprot.write_message_begin(api, TMessageType.REPLY, seqid) <NEW_LINE> result.write(oprot) <NEW_LINE> oprot.write_message_end() <NEW_LINE> oprot.trans.flush() <NEW_LINE> <DEDENT> def handle_exception(self, e, result): <NEW_LINE> <INDENT> for k in sorted(result.thrift_spec): <NEW_LINE> <INDENT> if result.thrift_spec[k][1] == "success": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> _, exc_name, exc_cls, _ = result.thrift_spec[k] <NEW_LINE> if isinstance(e, exc_cls): <NEW_LINE> <INDENT> setattr(result, exc_name, e) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> def process(self, iprot, oprot): <NEW_LINE> <INDENT> api, seqid, result, call = self.process_in(iprot) <NEW_LINE> if isinstance(result, TApplicationException): <NEW_LINE> <INDENT> return self.send_exception(oprot, api, result, seqid) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result.success = call() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.handle_exception(e, result) <NEW_LINE> <DEDENT> if not result.oneway: <NEW_LINE> <INDENT> self.send_result(oprot, api, result, seqid)
Base class for procsessor, which works on two streams.
6259905a009cb60464d02b20
class HistoryMiddleware: <NEW_LINE> <INDENT> def __init__(self, get_response=None): <NEW_LINE> <INDENT> self.get_response = get_response <NEW_LINE> self.get_context = ( conf.REQUEST_CONTEXT if callable(conf.REQUEST_CONTEXT) else import_string(conf.REQUEST_CONTEXT) ) <NEW_LINE> <DEDENT> def __call__(self, request): <NEW_LINE> <INDENT> for prefix in conf.MIDDLEWARE_IGNORE: <NEW_LINE> <INDENT> if prefix and request.path.startswith(prefix): <NEW_LINE> <INDENT> return self.get_response(request) <NEW_LINE> <DEDENT> <DEDENT> backend = backends.get_backend() <NEW_LINE> context = self.get_context(request) or {} <NEW_LINE> with backend.session(**context): <NEW_LINE> <INDENT> return self.get_response(request)
Middleware that creates a temporary table for a connection and puts the current User ID in there.
6259905a23849d37ff8526b0
class Spider(pyclt.api.Api): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.__url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null' <NEW_LINE> <DEDENT> def getCmdResult(self,word): <NEW_LINE> <INDENT> dict_data = self.__getDictData(word) <NEW_LINE> string = (self.text['simple_header'] + '\n' + self.text['translation'] + '>>\t' + self.__DictData2Result(dict_data)) <NEW_LINE> return string <NEW_LINE> <DEDENT> def getGuiResult(self,word): <NEW_LINE> <INDENT> return self.getCmdResult(word) <NEW_LINE> <DEDENT> def __getDictData(self,word): <NEW_LINE> <INDENT> data = {} <NEW_LINE> data['type'] = 'AUTO' <NEW_LINE> data['i'] = str(word) <NEW_LINE> data['doctype'] = 'json' <NEW_LINE> data['xmlVersion'] = '1.8' <NEW_LINE> data['keyfrom'] = 'fanyi.web' <NEW_LINE> data['ue'] = 'UTF-8' <NEW_LINE> data['action'] = 'FT_BY_ENTER' <NEW_LINE> data = urllib.parse.urlencode(data).encode('utf-8') <NEW_LINE> head = {} <NEW_LINE> head['User-Agent'] = 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:48.0) Gecko/20100101 Firefox/48.0' <NEW_LINE> return json.loads(urllib.request.urlopen(self.__url,data).read().decode('utf-8')) <NEW_LINE> <DEDENT> def __DictData2Result(self,dict_data): <NEW_LINE> <INDENT> for key,value in dict_data.items(): <NEW_LINE> <INDENT> if key == 'translateResult': <NEW_LINE> <INDENT> for x_key,x_value in value[0][0].items(): <NEW_LINE> <INDENT> if x_key =='tgt': <NEW_LINE> <INDENT> return x_value
爬虫版翻译程序
6259905a45492302aabfdac3
class SelectIndexHandler(AskUserEventHandler): <NEW_LINE> <INDENT> def __init__(self, engine: Engine): <NEW_LINE> <INDENT> super().__init__(engine) <NEW_LINE> player = self.engine.player <NEW_LINE> engine.mouse_location = player.x, player.y <NEW_LINE> <DEDENT> def on_render(self, console: tcod.Console) -> None: <NEW_LINE> <INDENT> super().on_render(console) <NEW_LINE> highlight(console, self.engine.mouse_location) <NEW_LINE> <DEDENT> def ev_keydown(self, event: tcod.event.KeyDown) -> Optional[ActionOrHandler]: <NEW_LINE> <INDENT> key = event.sym <NEW_LINE> if key in MOVE_KEYS: <NEW_LINE> <INDENT> modifier = 1 <NEW_LINE> if event.mod & (tcod.event.KMOD_LSHIFT | tcod.event.KMOD_RSHIFT): <NEW_LINE> <INDENT> modifier *= 5 <NEW_LINE> <DEDENT> if event.mod & (tcod.event.KMOD_LCTRL | tcod.event.KMOD_RCTRL): <NEW_LINE> <INDENT> modifier *= 10 <NEW_LINE> <DEDENT> if event.mod & (tcod.event.KMOD_LALT | tcod.event.KMOD_RALT): <NEW_LINE> <INDENT> modifier *= 20 <NEW_LINE> <DEDENT> x, y = self.engine.mouse_location <NEW_LINE> dx, dy = MOVE_KEYS[key] <NEW_LINE> x += dx * modifier <NEW_LINE> y += dy * modifier <NEW_LINE> x = max(0, min(x, self.engine.game_map.width - 1)) <NEW_LINE> y = max(0, min(y, self.engine.game_map.height - 1)) <NEW_LINE> self.engine.mouse_location = x, y <NEW_LINE> return None <NEW_LINE> <DEDENT> elif key in CONFIRM_KEYS: <NEW_LINE> <INDENT> return self.on_index_selected(*self.engine.mouse_location) <NEW_LINE> <DEDENT> return super().ev_keydown(event) <NEW_LINE> <DEDENT> def ev_mousebuttondown(self, event: tcod.event.MouseButtonDown) -> Optional[ActionOrHandler]: <NEW_LINE> <INDENT> if self.engine.game_map.in_bounds(*event.tile): <NEW_LINE> <INDENT> if event.button == 1: <NEW_LINE> <INDENT> return self.on_index_selected(*event.tile) <NEW_LINE> <DEDENT> <DEDENT> return super().ev_mousebuttondown(event) <NEW_LINE> <DEDENT> def on_index_selected(self, x: int, y: int) -> Optional[ActionOrHandler]: <NEW_LINE> <INDENT> raise NotImplementedError()
Handles asking the user for an index on the map.
6259905a7d847024c075d9c8
class PublicUserSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> about = serializers.SerializerMethodField() <NEW_LINE> profile_pic = serializers.SerializerMethodField() <NEW_LINE> num_posts = serializers.SerializerMethodField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ( 'username', 'first_name', 'last_name', 'about', 'profile_pic', 'num_posts' ) <NEW_LINE> read_only_fields = ( 'username', 'first_name', 'last_name', 'about', 'profile_pic', 'num_posts' ) <NEW_LINE> <DEDENT> def get_about(self, obj): <NEW_LINE> <INDENT> return obj.profile.about <NEW_LINE> <DEDENT> def get_profile_pic(self, obj): <NEW_LINE> <INDENT> return obj.profile.profile_pic <NEW_LINE> <DEDENT> def get_num_posts(self, obj): <NEW_LINE> <INDENT> return obj.posts.count()
Serialized representation of a public user
6259905a097d151d1a2c2658
class EmailAddress(_Observable): <NEW_LINE> <INDENT> _type = 'email-addr' <NEW_LINE> _properties = OrderedDict([ ('type', TypeProperty(_type)), ('id', IDProperty(_type, spec_version='2.1')), ('value', StringProperty(required=True)), ('display_name', StringProperty()), ('belongs_to_ref', ReferenceProperty(valid_types='user-account', spec_version='2.1')), ('extensions', ExtensionsProperty(spec_version='2.1', enclosing_type=_type)), ('spec_version', StringProperty(fixed='2.1')), ('object_marking_refs', ListProperty(ReferenceProperty(valid_types='marking-definition', spec_version='2.1'))), ('granular_markings', ListProperty(GranularMarking)), ('defanged', BooleanProperty(default=lambda: False)), ]) <NEW_LINE> _id_contributing_properties = ["value"]
For more detailed information on this object's properties, see `the STIX 2.1 specification <link here>`__.
6259905a1b99ca400229002d
class FloatList(ItemList): <NEW_LINE> <INDENT> def __init__(self, items:Iterator, log:bool=False, **kwargs): <NEW_LINE> <INDENT> super().__init__(np.array(items, dtype=np.float32), **kwargs) <NEW_LINE> self.log = log <NEW_LINE> self.copy_new.append('log') <NEW_LINE> self.c = self.items.shape[1] if len(self.items.shape) > 1 else 1 <NEW_LINE> self.loss_func = MSELossFlat() <NEW_LINE> <DEDENT> def get(self, i): <NEW_LINE> <INDENT> o = super().get(i) <NEW_LINE> return FloatItem(np.log(o) if self.log else o) <NEW_LINE> <DEDENT> def reconstruct(self,t): return FloatItem(t.numpy())
`ItemList` suitable for storing the floats in items for regression. Will add a `log` if thif flag is `True`.
6259905a3cc13d1c6d466d2b
class Shape1D_pdf(PDF) : <NEW_LINE> <INDENT> def __init__ ( self , name , shape , xvar ) : <NEW_LINE> <INDENT> PDF.__init__ ( self , name , xvar ) <NEW_LINE> if isinstance ( shape , ROOT.TH1 ) and not isinstance ( shape , ROOT.TH2 ) : <NEW_LINE> <INDENT> self.histo = shape <NEW_LINE> shape = Ostap.Math.Histo1D ( shape ) <NEW_LINE> <DEDENT> self.__shape = shape <NEW_LINE> self.pdf = Ostap.Models.Shape1D.create ( self.roo_name ( 'shape1_' ) , "Shape-1D %s" % self.name , self.xvar , self.shape ) <NEW_LINE> self.config = { 'name' : self.name , 'shape' : self.shape , 'xvar' : self.xvar , } <NEW_LINE> <DEDENT> @property <NEW_LINE> def shape ( self ) : <NEW_LINE> <INDENT> return self.__shape
Generic 1D-shape from C++ callable - see Ostap::Models:Shape1D
6259905acc0a2c111447c5c4
class HeckeOperator(Morphism): <NEW_LINE> <INDENT> def __init__(self, abvar, n): <NEW_LINE> <INDENT> from .abvar import is_ModularAbelianVariety <NEW_LINE> n = ZZ(n) <NEW_LINE> if n <= 0: <NEW_LINE> <INDENT> raise ValueError("n must be positive") <NEW_LINE> <DEDENT> if not is_ModularAbelianVariety(abvar): <NEW_LINE> <INDENT> raise TypeError("abvar must be a modular abelian variety") <NEW_LINE> <DEDENT> self.__abvar = abvar <NEW_LINE> self.__n = n <NEW_LINE> sage.modules.matrix_morphism.MatrixMorphism_abstract.__init__(self, abvar.Hom(abvar)) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "Hecke operator T_%s on %s"%(self.__n, self.__abvar) <NEW_LINE> <DEDENT> def index(self): <NEW_LINE> <INDENT> return self.__n <NEW_LINE> <DEDENT> def n(self): <NEW_LINE> <INDENT> return self.index() <NEW_LINE> <DEDENT> def characteristic_polynomial(self, var='x'): <NEW_LINE> <INDENT> return self.__abvar.rational_homology().hecke_polynomial(self.__n, var).change_ring(ZZ) <NEW_LINE> <DEDENT> def charpoly(self, var='x'): <NEW_LINE> <INDENT> return self.characteristic_polynomial(var) <NEW_LINE> <DEDENT> def action_on_homology(self, R=ZZ): <NEW_LINE> <INDENT> return self.__abvar.homology(R).hecke_operator(self.index()) <NEW_LINE> <DEDENT> def matrix(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._matrix <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self._matrix = self.action_on_homology().matrix() <NEW_LINE> return self._matrix
A Hecke operator acting on a modular abelian variety.
6259905a24f1403a926863c4
class Flatten(layers.Layer): <NEW_LINE> <INDENT> def __init__(self, start_axis=1, stop_axis=-1): <NEW_LINE> <INDENT> super(Flatten, self).__init__() <NEW_LINE> self.start_axis = start_axis <NEW_LINE> self.stop_axis = stop_axis <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> out = paddle.tensor.manipulation.flatten( input, start_axis=self.start_axis, stop_axis=self.stop_axis) <NEW_LINE> return out
This interface is used to construct a callable object of the ``FLatten`` class. For more details, refer to code examples. It implements flatten a contiguous range of dims into a tensor. Parameters: start_axis(int): first dim to flatten (default = 1) stop_axis(int): last dim to flatten (default = -1). Returns: None Examples: .. code-block:: python import paddle import numpy as np inp_np = np.ones([5, 2, 3, 4]).astype('float32') inp_np = paddle.to_tensor(inp_np) flatten = paddle.nn.Flatten(start_axis=1, stop_axis=2) flatten_res = flatten(inp_np)
6259905a462c4b4f79dbcff1
class UARTConfig(Enum): <NEW_LINE> <INDENT> IdleHigh = 1 <NEW_LINE> IdleLow = 2
Enumeration of configuration settings
6259905a76e4537e8c3f0b78
class InvalidInputError(QTrioException): <NEW_LINE> <INDENT> pass
Raised when invalid input is provided such as via a dialog.
6259905a8e7ae83300eea679
class listasDetailForm(ModelForm): <NEW_LINE> <INDENT> _model_class = listas <NEW_LINE> _include = [listas.creation, listas.lista, listas.nome]
Form used to show entity details on app's admin page
6259905ad268445f2663a653
class Daughters(Relation): <NEW_LINE> <INDENT> def get_relatives(self, person_name, relation, family): <NEW_LINE> <INDENT> return [child.main_member.name for child in family.child_family if child.main_member.gender == FEMALE]
Get the daughters of the family.
6259905a99cbb53fe68324cc
class UserScanQR(BaseElement): <NEW_LINE> <INDENT> @property <NEW_LINE> def selector(self): <NEW_LINE> <INDENT> return (By.ID,"com.videochat.livu:id/item_qr_scan")
go to Scan page button
6259905a23e79379d538dae8
class _Timeout(object): <NEW_LINE> <INDENT> __slots__ = ['deadline', 'callback'] <NEW_LINE> def __init__(self, deadline, callback, io_loop): <NEW_LINE> <INDENT> if isinstance(deadline, numbers.Real): <NEW_LINE> <INDENT> self.deadline = deadline <NEW_LINE> <DEDENT> elif isinstance(deadline, datetime.timedelta): <NEW_LINE> <INDENT> now = io_loop.time() <NEW_LINE> try: <NEW_LINE> <INDENT> self.deadline = now + deadline.total_seconds() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.deadline = now + _Timeout.timedelta_to_seconds(deadline) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Unsupported deadline %r" % deadline) <NEW_LINE> <DEDENT> self.callback = callback <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def timedelta_to_seconds(td): <NEW_LINE> <INDENT> return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return ((self.deadline, id(self)) < (other.deadline, id(other))) <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return ((self.deadline, id(self)) <= (other.deadline, id(other)))
An IOLoop timeout, a UNIX timestamp and a callback
6259905a4e4d5625663739f4
class Message(object): <NEW_LINE> <INDENT> _names = { "mfrom" : "from", "to" : "to", "body" : "body", "media_urls" : "media_urls", "is_mms" : "is_mms" } <NEW_LINE> def __init__(self, mfrom=None, to=None, body=None, media_urls=None, is_mms=None): <NEW_LINE> <INDENT> self.mfrom = mfrom <NEW_LINE> self.to = to <NEW_LINE> self.body = body <NEW_LINE> self.media_urls = media_urls <NEW_LINE> self.is_mms = is_mms <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dictionary(cls, dictionary): <NEW_LINE> <INDENT> if dictionary is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> mfrom = dictionary.get("from") <NEW_LINE> to = dictionary.get("to") <NEW_LINE> body = dictionary.get("body") <NEW_LINE> media_urls = dictionary.get("media_urls") <NEW_LINE> is_mms = dictionary.get("is_mms") <NEW_LINE> return cls(mfrom, to, body, media_urls, is_mms)
Implementation of the 'Message' model. TODO: type model description here. Attributes: mfrom (string): TODO: type description here. to (string): TODO: type description here. body (string): TODO: type description here. media_urls (list of string): TODO: type description here. is_mms (bool): TODO: type description here.
6259905a507cdc57c63a6392
class Threads(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): <NEW_LINE> <INDENT> threading.Thread.__init__(self, group, target, name, args, kwargs) <NEW_LINE> self._target = target <NEW_LINE> self._args = args <NEW_LINE> self._kwargs = kwargs <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self._return = self._target(*self._args, **self._kwargs) <NEW_LINE> <DEDENT> def result(self): <NEW_LINE> <INDENT> return self._return
This class will execute a given function mentioned in "target" as a separate thread.
6259905aa17c0f6771d5d698
class MenuTest(BaseTest): <NEW_LINE> <INDENT> def test_menu_list_view(self): <NEW_LINE> <INDENT> resp = self.client.get('/') <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> self.assertTemplateUsed(resp, 'menu/list_all_current_menus.html') <NEW_LINE> self.assertEqual(len(Menu.objects.all()), 2) <NEW_LINE> <DEDENT> def test_menu_detail_view(self): <NEW_LINE> <INDENT> resp = self.client.get(reverse('menu:menu_detail', kwargs={'pk': self.menu_1.pk})) <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> self.assertTemplateUsed(resp, 'menu/menu_detail.html') <NEW_LINE> self.assertContains(resp, self.item_1.name) <NEW_LINE> self.assertContains(resp, self.menu_1.season) <NEW_LINE> <DEDENT> def test_create_new_menu_view(self): <NEW_LINE> <INDENT> resp = self.client.get(reverse('menu:menu_new')) <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> self.assertTemplateUsed(resp, 'menu/add_menu.html') <NEW_LINE> data = { 'season': 'Summer', 'items': [self.item_1.id, self.item_2.id], 'expiration_date': datetime.date.today() } <NEW_LINE> resp_2 = self.client.post('/menu/new/', data) <NEW_LINE> menu = Menu.objects.all().order_by('-id')[0] <NEW_LINE> self.assertEqual(resp_2.status_code, 302) <NEW_LINE> self.assertRedirects(resp_2, reverse('menu:menu_detail', kwargs={'pk': menu.id})) <NEW_LINE> <DEDENT> def test_edit_menu_view(self): <NEW_LINE> <INDENT> resp = self.client.get(reverse('menu:menu_edit', kwargs={'pk': self.menu_1.id})) <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> self.assertTemplateUsed(resp, 'menu/add_menu.html') <NEW_LINE> data = { 'season': 'Now this is Fall', 'items': [self.item_2.id], 'expiration_date': datetime.date.today() } <NEW_LINE> menu = Menu.objects.all().order_by('-id')[0] <NEW_LINE> resp_2 = self.client.post(reverse('menu:menu_edit', kwargs={'pk': menu.id}), data) <NEW_LINE> self.assertEqual(resp_2.status_code, 302) <NEW_LINE> <DEDENT> def test_delete_menu_view(self): <NEW_LINE> <INDENT> resp = self.client.get(reverse('menu:menu_delete', kwargs={'pk': self.menu_1.id})) <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> self.assertTemplateUsed(resp, 'menu/delete_menu.html') <NEW_LINE> resp_2 = self.client.post(reverse('menu:menu_delete', kwargs={'pk': self.menu_1.id})) <NEW_LINE> self.assertEqual(len(Menu.objects.all()), 1) <NEW_LINE> self.assertRedirects(resp_2, reverse('menu:menu_list'))
MenuTest test class Inherit: - BaseTest - 5 tests are created for all views testing.
6259905a3539df3088ecd888
class LanguageEngineMedical: <NEW_LINE> <INDENT> def __init__(self, region_name, language='en'): <NEW_LINE> <INDENT> self._region = region_name <NEW_LINE> self._language_code = language <NEW_LINE> self._comprehend = boto3.client( service_name='comprehendmedical', region_name=region_name) <NEW_LINE> <DEDENT> def get_entities(self, text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self._comprehend.detect_entities( Text=text) <NEW_LINE> entities = result['Entities'] <NEW_LINE> txt = '' <NEW_LINE> for entity in entities: <NEW_LINE> <INDENT> txt += f'{json.dumps(entity, sort_keys=True, indent=4)}\n' <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> txt = e <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return txt.strip()
A class for Natural Language Processing of Medical Information
6259905ad7e4931a7ef3d66b
class Context(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.start = None <NEW_LINE> self.end = None <NEW_LINE> <DEDENT> def cut(self, content): <NEW_LINE> <INDENT> raise Exception('Implement the get_context method in child class') <NEW_LINE> <DEDENT> def get_interval(self): <NEW_LINE> <INDENT> if self.start == None or self.end == None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return (self.start, self.end) <NEW_LINE> <DEDENT> def __and__(self, context): <NEW_LINE> <INDENT> return AndContext(self, context) <NEW_LINE> <DEDENT> def __or__(self, context): <NEW_LINE> <INDENT> return OrContext(self, context)
This class is an Abstract base class for Context objects A Context is used to limit the scope of a refactoring operation When a text is applied over a Context object through the cut method, the Context object must return the new content and set the interval that delimits the new content from the original content
6259905aa219f33f346c7df2
class TestCompareComplexString(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TestCompareComplexString, self).__init__() <NEW_LINE> <DEDENT> def test_error_string(self): <NEW_LINE> <INDENT> eq_(compare_complex_string(r"B\\1", "B2"), -2) <NEW_LINE> eq_(compare_complex_string(r"B1\\", "B2"), -2) <NEW_LINE> eq_(compare_complex_string(r"B\*1", "B2"), -2) <NEW_LINE> <DEDENT> def test_cmp_by_number(self): <NEW_LINE> <INDENT> eq_(compare_complex_string("B1", "B2"), -1) <NEW_LINE> eq_(compare_complex_string("B1", "B01"), -1) <NEW_LINE> eq_(compare_complex_string("B01", "B2"), -1) <NEW_LINE> eq_(compare_complex_string("B01", "B01"), 0) <NEW_LINE> eq_(compare_complex_string(r"1\A0", "750"), 0) <NEW_LINE> <DEDENT> def test_cmp_by_empty(self): <NEW_LINE> <INDENT> eq_(compare_complex_string("", ""), 0) <NEW_LINE> <DEDENT> def test_cmp_empty_and_string(self): <NEW_LINE> <INDENT> eq_(compare_complex_string("", "B"), -1) <NEW_LINE> eq_(compare_complex_string(r"\1", ""), 1) <NEW_LINE> <DEDENT> def test_cmp_string_and_number(self): <NEW_LINE> <INDENT> eq_(compare_complex_string("B", "1"), 1) <NEW_LINE> eq_(compare_complex_string("1", "B"), -1) <NEW_LINE> eq_(compare_complex_string("B", r"\B"), 1) <NEW_LINE> eq_(compare_complex_string(r"\B", "B"), -1) <NEW_LINE> eq_(compare_complex_string(r"B1\A0B", "B750B"), 0) <NEW_LINE> eq_(compare_complex_string(r"B1\A0B", "B750"), 1) <NEW_LINE> eq_(compare_complex_string(r"B1\A0", "B750B"), -1) <NEW_LINE> eq_(compare_complex_string(r"B1\A0B\1\2345", r"B750B\1\2345"), 0) <NEW_LINE> eq_(compare_complex_string(r"B1\A0B\1\23405", r"B750B\1\2345"), 1) <NEW_LINE> eq_(compare_complex_string(r"B1\A0B\1\234\A", r"B750B\1\23465"), -1)
Documentation for TestCompareComplexString
6259905a16aa5153ce401ad0
class CommandTesting(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> dispatch.init() <NEW_LINE> super().setUpClass() <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> dispatch.Tracker.append( data=dispatch.Case(index=64, client="PotatoClient", platform='ps', cr=False, system="Ki")) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> dispatch.database.pop(64) <NEW_LINE> <DEDENT> def test_system(self): <NEW_LINE> <INDENT> cmd = dispatch.CommandBase.getCommand('sys') <NEW_LINE> self.assertEqual(cmd.func( ['set_system', '64', 'some_random_data'],["", "64 some_random_data", "some_random_data"]), 3) <NEW_LINE> data = dispatch.database.get(64) <NEW_LINE> self.assertEqual(data.system, "some_random_data") <NEW_LINE> <DEDENT> def test_cr(self): <NEW_LINE> <INDENT> data = dispatch.database.get(64) <NEW_LINE> command = dispatch.CommandBase.getCommand('cr') <NEW_LINE> self.assertIsNotNone(data) <NEW_LINE> self.assertFalse(data.cr) <NEW_LINE> self.assertEqual(command.func(["cr", "64"],None,None), 3) <NEW_LINE> self.assertTrue(data.cr) <NEW_LINE> <DEDENT> def test_platform_valid(self): <NEW_LINE> <INDENT> expected_platforms = ['XB', 'PC', 'PS'] <NEW_LINE> command = dispatch.CommandBase.getCommand('platform') <NEW_LINE> data = dispatch.database.get(64) <NEW_LINE> for platform in expected_platforms: <NEW_LINE> <INDENT> with self.subTest(platform=platform): <NEW_LINE> <INDENT> self.assertEqual(command.func(['platform', '64', platform], None, None),3) <NEW_LINE> self.assertEqual(data.platform, platform) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_platform_invalid(self): <NEW_LINE> <INDENT> bad_platforms = ['xbox', "pee-cee","ps3","", None, 'xbone', 'pc master race'] <NEW_LINE> data = dispatch.database.get(64) <NEW_LINE> command = dispatch.CommandBase.getCommand('platform') <NEW_LINE> for platform in bad_platforms: <NEW_LINE> <INDENT> with self.subTest(platform=platform): <NEW_LINE> <INDENT> self.assertEqual(command.func(['platform', '64', platform], None, None),3) <NEW_LINE> <DEDENT> <DEDENT> self.assertEqual(data.platform, 'ps') <NEW_LINE> <DEDENT> def test_add_rats(self): <NEW_LINE> <INDENT> expected_rats = ["theunkn0wn1[pc]", "ninjaKiwi"] <NEW_LINE> command = ["append", "64"] + expected_rats <NEW_LINE> data = dispatch.database.get(64) <NEW_LINE> cmd_func = dispatch.CommandBase.getCommand('assign') <NEW_LINE> self.assertEqual(cmd_func.func(command,None),3) <NEW_LINE> self.assertEqual(data.rats, expected_rats) <NEW_LINE> <DEDENT> def test_say(self): <NEW_LINE> <INDENT> self.assertNotEqual(dispatch.stageBase.registered_commands, {}) <NEW_LINE> command = dispatch.stageBase.getCommand("say") <NEW_LINE> self.assertIsNotNone(command) <NEW_LINE> print(command) <NEW_LINE> self.assertEqual(command.func(message="test"), 3) <NEW_LINE> <DEDENT> def test_cmd_new_case(self): <NEW_LINE> <INDENT> cmd = dispatch.CommandBase.getCommand("new") <NEW_LINE> self.assertIsNotNone(cmd) <NEW_LINE> print("cmd = {}".format(cmd)) <NEW_LINE> self.assertEqual(cmd.func(['new', "2", "ki"], None, None), 3) <NEW_LINE> case = dispatch.Tracker.get_case(value=2) <NEW_LINE> self.assertIsNotNone(case) <NEW_LINE> <DEDENT> def test_find_by_alias(self): <NEW_LINE> <INDENT> commands = ['create', 'new', 'cr'] <NEW_LINE> for name in commands: <NEW_LINE> <INDENT> with self.subTest(cmd = name): <NEW_LINE> <INDENT> found = dispatch.CommandBase.getCommand(name=name) <NEW_LINE> self.assertIsNotNone(found)
For the testing of / commands
6259905a2ae34c7f260ac6d5
class EngineInitializationError(AbstractEngineError): <NEW_LINE> <INDENT> pass
Defines engine initialization exception.
6259905ae76e3b2f99fd9fec
class TestEmployee(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.my_employee = Employee("Benoit", "Masson-Bedeau", 36000) <NEW_LINE> <DEDENT> def test_give_default_raise(self): <NEW_LINE> <INDENT> self.my_employee.give_raise() <NEW_LINE> self.assertEqual(self.my_employee.annual_salary, 41000) <NEW_LINE> <DEDENT> def test_give_custom_raise(self): <NEW_LINE> <INDENT> self.my_employee.give_raise(1000) <NEW_LINE> self.assertEqual(self.my_employee.annual_salary, 37000)
Test for the class Employee.
6259905a3c8af77a43b68a37
class Slice(Base, AuditMixinNullable): <NEW_LINE> <INDENT> __tablename__ = 'slices' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> owners = relationship("User", secondary=slice_user)
Declarative class to do query in upgrade
6259905a24f1403a926863c5
class PostgresQuery(Query): <NEW_LINE> <INDENT> def _from_clause(self): <NEW_LINE> <INDENT> if isinstance(self.from_, Query): <NEW_LINE> <INDENT> from_clause = '( %s ) AS tmp' % self.from_.compile() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from_clause = self.from_ <NEW_LINE> <DEDENT> return from_clause
Simple PostgreSQL query wrapper.
6259905a8e7ae83300eea67b
class Conv2DTranspose(_ConvNDTranspose, base.Transposable): <NEW_LINE> <INDENT> def __init__(self, output_channels, output_shape=None, kernel_shape=None, stride=1, padding=SAME, use_bias=True, initializers=None, partitioners=None, regularizers=None, data_format=DATA_FORMAT_NHWC, custom_getter=None, name="conv_2d_transpose"): <NEW_LINE> <INDENT> if data_format not in SUPPORTED_2D_DATA_FORMATS: <NEW_LINE> <INDENT> raise ValueError("Invalid data_format {:s}. Allowed formats " "{}".format(data_format, SUPPORTED_2D_DATA_FORMATS)) <NEW_LINE> <DEDENT> super(Conv2DTranspose, self).__init__( output_channels=output_channels, output_shape=output_shape, kernel_shape=kernel_shape, stride=stride, padding=padding, use_bias=use_bias, initializers=initializers, partitioners=partitioners, regularizers=regularizers, data_format=data_format, custom_getter=custom_getter, name=name ) <NEW_LINE> <DEDENT> def transpose(self, name=None): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> name = self.module_name + "_transpose" <NEW_LINE> <DEDENT> if self._data_format == DATA_FORMAT_NHWC: <NEW_LINE> <INDENT> stride = self.stride[1:-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stride = self.stride[2:] <NEW_LINE> <DEDENT> return Conv2D(output_channels=lambda: self.input_channels, kernel_shape=self.kernel_shape, stride=stride, padding=self.padding, use_bias=self._use_bias, initializers=self.initializers, partitioners=self.partitioners, regularizers=self.regularizers, data_format=self._data_format, custom_getter=self._custom_getter, name=name)
Spatial transposed / reverse / up 2D convolution module, including bias. This acts as a light wrapper around the TensorFlow op `tf.nn.conv2d_transpose` abstracting away variable creation and sharing.
6259905aa79ad1619776b5b4
class LDAPSyncAttributeMap(models.Model): <NEW_LINE> <INDENT> sync_job = models.ForeignKey('LDAPSyncJob', related_name='attributes') <NEW_LINE> ldap_attribute_name = models.CharField(max_length=255, help_text="LDAP Attribute Name.") <NEW_LINE> model_attribute_name = models.CharField(max_length=255, help_text="Django Attribute Name.") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Synchronizer Attribute Map' <NEW_LINE> verbose_name_plural = 'Synchronizer Attribute Maps'
Maps LDAP attributes to Model Attributes.
6259905a7047854f463409ae
class TestCheck(Check): <NEW_LINE> <INDENT> __test__ = True <NEW_LINE> @property <NEW_LINE> def this_check(self): <NEW_LINE> <INDENT> return chk <NEW_LINE> <DEDENT> def test_smoke(self): <NEW_LINE> <INDENT> assert self.passes("""Smoke phrase with nothing flagged.""") <NEW_LINE> assert not self.passes("""What was the 'take-home message'?""")
The test class for misc.scare_quotes.
6259905a99cbb53fe68324ce
class SheetOutOfSyncException(Exception): <NEW_LINE> <INDENT> def __init__(self, coupon_gen_request, coupon_req_row, msg=None): <NEW_LINE> <INDENT> self.coupon_gen_request = coupon_gen_request <NEW_LINE> self.coupon_req_row = coupon_req_row <NEW_LINE> super().__init__(msg)
General exception for situations where the data in a spreadsheet does not reflect the state of the database
6259905ab57a9660fecd3069
@register <NEW_LINE> class regexed(Validator): <NEW_LINE> <INDENT> def setup(self, *regexes): <NEW_LINE> <INDENT> self.regexes = [(regex, re.compile(regex)) for regex in regexes] <NEW_LINE> <DEDENT> def validate(self, meta, val): <NEW_LINE> <INDENT> for spec, regex in self.regexes: <NEW_LINE> <INDENT> if not regex.match(val): <NEW_LINE> <INDENT> raise BadSpecValue("Expected value to match regex, it didn't", spec=spec, meta=meta, val=val) <NEW_LINE> <DEDENT> <DEDENT> return val
Usage .. code-block:: python regexed(regex1, ..., regexn).normalise(meta, val) This will match the ``val`` against all the ``regex``s and will complain if any of them fail, otherwise the ``val`` is returned.
6259905a097d151d1a2c265b
class RepresentableBlockPredictorResiduals(RepresentableBlockPredictor): <NEW_LINE> <INDENT> def predict( self, dataset: Dataset, num_samples: Optional[int] = None, num_workers: Optional[int] = None, num_prefetch: Optional[int] = None, **kwargs, ) -> Iterator[Forecast]: <NEW_LINE> <INDENT> inference_data_loader = InferenceDataLoader( dataset, transform=self.input_transform, batch_size=self.batch_size, ctx=self.ctx, dtype=self.dtype, num_workers=num_workers, num_prefetch=num_prefetch, **kwargs, ) <NEW_LINE> yield from self.forecast_generator( inference_data_loader=inference_data_loader, prediction_net=self.prediction_net, input_names=self.input_names, freq=self.freq, output_transform=self.output_transform, num_samples=num_samples, ) <NEW_LINE> self.prediction_net.residuals_complete = True
construct a RepresentableBlockPredictor object that will calculate the in-sample prediction residuals once and only once
6259905ad53ae8145f919a50
class InlineQuery(TelegramObject): <NEW_LINE> <INDENT> def __init__(self, id, from_user, query, offset, location=None, bot=None, **kwargs): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.from_user = from_user <NEW_LINE> self.query = query <NEW_LINE> self.offset = offset <NEW_LINE> self.location = location <NEW_LINE> self.bot = bot <NEW_LINE> self._id_attrs = (self.id,) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def de_json(cls, data, bot): <NEW_LINE> <INDENT> data = super(InlineQuery, cls).de_json(data, bot) <NEW_LINE> if not data: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> data['from_user'] = User.de_json(data.get('from'), bot) <NEW_LINE> data['location'] = Location.de_json(data.get('location'), bot) <NEW_LINE> return cls(bot=bot, **data) <NEW_LINE> <DEDENT> def answer(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.bot.answer_inline_query(self.id, *args, **kwargs)
This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results. Note: * In Python `from` is a reserved word, use `from_user` instead. Attributes: id (:obj:`str`): Unique identifier for this query. from_user (:class:`telegram.User`): Sender. location (:class:`telegram.Location`): Optional. Sender location, only for bots that request user location. query (:obj:`str`): Text of the query (up to 256 characters). offset (:obj:`str`): Offset of the results to be returned, can be controlled by the bot. Args: id (:obj:`str`): Unique identifier for this query. from_user (:class:`telegram.User`): Sender. location (:class:`telegram.Location`, optional): Sender location, only for bots that request user location. query (:obj:`str`): Text of the query (up to 256 characters). offset (:obj:`str`): Offset of the results to be returned, can be controlled by the bot. bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods. **kwargs (:obj:`dict`): Arbitrary keyword arguments.
6259905aa8ecb03325872805
class DelaySpectrum(ContainerBase): <NEW_LINE> <INDENT> _axes = ("baseline", "delay") <NEW_LINE> _dataset_spec = { "spectrum": { "axes": ["baseline", "delay"], "dtype": np.float64, "initialise": True, "distributed": True, "distributed_axis": "baseline", } } <NEW_LINE> @property <NEW_LINE> def spectrum(self): <NEW_LINE> <INDENT> return self.datasets["spectrum"]
Container for a delay spectrum.
6259905aa17c0f6771d5d699
class EVA(REST): <NEW_LINE> <INDENT> _url = "http://wwwdev.ebi.ac.uk/eva/webservices/rest/" <NEW_LINE> def __init__(self, verbose=False, cache=False): <NEW_LINE> <INDENT> super(EVA, self).__init__( name="EVA", url=EVA._url, verbose=verbose, cache=cache ) <NEW_LINE> self.version = "v1" <NEW_LINE> <DEDENT> def fetch_allinfo(self, name): <NEW_LINE> <INDENT> res = self.http_get(self.version + "/studies/" + name + "/summary") <NEW_LINE> return res
Interface to the `EVA <http://www.ebi.ac.uk/eva>`_ service * version: indicates the version of the API, this defines the available filters and JSON schema to be returned. Currently there is only version 'v1'. * category: this defines what objects we want to query. Currently there are five different categories: variants, segments, genes, files and studies. * resource: specifies the resource to be returned, therefore the JSON data model. * filters: each specific endpoint allows different filters.
6259905ae64d504609df9ec6
class Boundary(SpaceNode): <NEW_LINE> <INDENT> def __init__(self, from_cell, to_cell, sign=None): <NEW_LINE> <INDENT> SpaceNode.__init__(self, from_cell.space) <NEW_LINE> self._from = from_cell <NEW_LINE> self._to = to_cell <NEW_LINE> self._sign = sign <NEW_LINE> self._successors = {} <NEW_LINE> <DEDENT> @property <NEW_LINE> def from_(self): <NEW_LINE> <INDENT> return self._from <NEW_LINE> <DEDENT> @property <NEW_LINE> def to_(self): <NEW_LINE> <INDENT> return self._to <NEW_LINE> <DEDENT> @property <NEW_LINE> def members_dict(self): <NEW_LINE> <INDENT> return self._successors <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return bound_name(self._from, self._to) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, self.__class__): <NEW_LINE> <INDENT> if other.name == self.name: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '<{}>:{}'.format(self.__class__.__name__, self.name) <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self._successors.get(item, None) <NEW_LINE> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return item in self._successors <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def add_successor(self, bnd_or_balance): <NEW_LINE> <INDENT> self._successors[bnd_or_balance.name] = bnd_or_balance <NEW_LINE> <DEDENT> @property <NEW_LINE> def predecessors(self): <NEW_LINE> <INDENT> return [self.from_] <NEW_LINE> <DEDENT> @property <NEW_LINE> def successors(self): <NEW_LINE> <INDENT> return list(self._successors.values()) <NEW_LINE> <DEDENT> def state_space(self): <NEW_LINE> <INDENT> yield self <NEW_LINE> for boundary in list(self._successors.values()): <NEW_LINE> <INDENT> yield boundary <NEW_LINE> <DEDENT> <DEDENT> def connect(self, other): <NEW_LINE> <INDENT> if isinstance(other, Boundary): <NEW_LINE> <INDENT> self._successors[other.name] = other <NEW_LINE> return <NEW_LINE> <DEDENT> other_bndry = self._to[other] <NEW_LINE> if other_bndry is None: <NEW_LINE> <INDENT> other_bndry = self._to.bound_to(other) <NEW_LINE> <DEDENT> if other_bndry is not None: <NEW_LINE> <INDENT> self._successors[other.name] = other_bndry <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def add_flow(self, flow_or_id): <NEW_LINE> <INDENT> if isinstance(flow_or_id, int): <NEW_LINE> <INDENT> flow = self.get_datum(flow_or_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> flow = flow_or_id <NEW_LINE> <DEDENT> self.data.append(flow) <NEW_LINE> return flow
'Edge-Like' ----++------- || c1 || c2 || ----++-------
6259905a627d3e7fe0e0847a
class StateFactory(HasPrivateTraits): <NEW_LINE> <INDENT> def get_state_to_bind(self, obj, name, context): <NEW_LINE> <INDENT> raise NotImplementedError
The base class for all state factories. A state factory accepts an object and returns some data representing the object that is suitable for storing in a particular context.
6259905a442bda511e95d851
class NanoDasConnectionTCP(DasConnection): <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> host = settings.LocalHost <NEW_LINE> port = settings.LocalPort <NEW_LINE> def __init__(self, host=settings.LocalHost, port=settings.LocalPort): <NEW_LINE> <INDENT> super(NanoDasConnectionTCP, self).__init__() <NEW_LINE> try: <NEW_LINE> <INDENT> self.sock.connect((self.host, self.port)) <NEW_LINE> <DEDENT> except socket.error as err: <NEW_LINE> <INDENT> sys.stderr.write("Error %s when connecting to TCP port %s on host %s \n" % (err, self.port, self.host)) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.sock.close() <NEW_LINE> <DEDENT> def read(self, n=[]): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if n == []: <NEW_LINE> <INDENT> output = self.sock.recv() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output = self.sock.recv(n) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> sys.stderr.write("Error reading on TCP port %s on host %s \n" % (self.port, self.host)) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> output = self.sock.recv() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> sys.stderr.write("Error reading on TCP port %s on host %s \n" % (self.port, self.host)) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> def write(self,command): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.sock.send(command) <NEW_LINE> <DEDENT> except socket.error as err: <NEW_LINE> <INDENT> sys.stderr.write("Error %s when writing command on TCP port %s on host %s \n" % (err, self.port, self.host)) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> <DEDENT> def inwaiting(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> output=0 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> sys.stderr.write("inWaiting error on TCP port %s on host %s \n" % (self.port, self.host)) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> def flushinput(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.sock.recv(1024) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> sys.stderr.write("flushOutput error on TCP port %s on host %s \n" % (self.port, self.host)) <NEW_LINE> sys.exit(1)
A TCP DAS connection
6259905abe8e80087fbc0672
class doi(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GET(self, arg): <NEW_LINE> <INDENT> path = web.ctx.path <NEW_LINE> doi = path.lstrip('/') <NEW_LINE> lk = Looker.Looker('/proj/ads/abstracts/links/DOI.dat') <NEW_LINE> try: <NEW_LINE> <INDENT> bibcode = lk.look(doi+'\t').rstrip('\n').split('\t')[1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> bibcode = '' <NEW_LINE> <DEDENT> if bibcode != '': <NEW_LINE> <INDENT> return web.redirect(abstract_base_url+'/'+urllib.quote(bibcode), '302 Found') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return web.redirect(base_url, '302 Found')
Class that redirect to labs in case of a DOI
6259905ad7e4931a7ef3d66d
class ProfileCreateAPIView(ProfileRetrieveAPIView, generics.CreateAPIView): <NEW_LINE> <INDENT> serializer_class = ProfileCreateSerializer <NEW_LINE> permission_classes = (IsNotAuthenticated,) <NEW_LINE> throttle_classes = (ProfileCreateRateThrottle,) <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> if serializer.is_valid(): <NEW_LINE> <INDENT> password = serializer.validated_data['password'] <NEW_LINE> instance = serializer.save() <NEW_LINE> if instance: <NEW_LINE> <INDENT> instance.set_password(password) <NEW_LINE> instance.save()
Profile Create View
6259905a7d847024c075d9cc
class Rds_Config_Loader: <NEW_LINE> <INDENT> def unpack_rds_config_file(self, logger, rds_config_file): <NEW_LINE> <INDENT> result = None <NEW_LINE> try: <NEW_LINE> <INDENT> with open(rds_config_file) as f: <NEW_LINE> <INDENT> result = json.load(f) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> logger.info({MESSAGE:"Unable to load rds_config_file."}) <NEW_LINE> raise <NEW_LINE> <DEDENT> if result is not None and result[RDS_USER] != '' and result[RDS_PASSWORD] != '' and result[RDS_HOST] != '' and result[RDS_DATABASE] != '': <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
This class is used to load the RDS Config paramaters from file
6259905a8e71fb1e983bd0b9
class DataCollectionRuleResourceListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'required': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[DataCollectionRuleResource]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: List["DataCollectionRuleResource"], next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(DataCollectionRuleResourceListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link
A pageable list of resources. All required parameters must be populated in order to send to Azure. :ivar value: Required. A list of resources. :vartype value: list[~$(python-base-namespace).v2022_02_01_preview.models.DataCollectionRuleResource] :ivar next_link: The URL to use for getting the next set of results. :vartype next_link: str
6259905a2c8b7c6e89bd4ddd
class SlotHistoryWidget(QTreeView): <NEW_LINE> <INDENT> SLOT_NAME, SLOT_VALUE = range(2) <NEW_LINE> def __init__(self, parent): <NEW_LINE> <INDENT> super(SlotHistoryWidget, self).__init__(parent) <NEW_LINE> self.parent = parent <NEW_LINE> self.setRootIsDecorated(False) <NEW_LINE> self.setAlternatingRowColors(True) <NEW_LINE> self.model = QStandardItemModel(0, 2, self) <NEW_LINE> self.model.setHeaderData( self.SLOT_NAME, Qt.Horizontal, 'Slot') <NEW_LINE> self.model.setHeaderData( self.SLOT_VALUE, Qt.Horizontal, 'Previously entered value') <NEW_LINE> self.setModel(self.model) <NEW_LINE> self.setSelectionMode(QAbstractItemView.NoSelection) <NEW_LINE> self.setEditTriggers(QAbstractItemView.NoEditTriggers) <NEW_LINE> <DEDENT> def add(self, name, value): <NEW_LINE> <INDENT> self.model.insertRow(0) <NEW_LINE> self.model.setData(self.model.index(0, self.SLOT_NAME), name) <NEW_LINE> self.model.setData(self.model.index(0, self.SLOT_VALUE), value)
A list of previously filled slots in a treeview widget Extends: {QTreeView} Variables: SLOT_NAME, SLOT_VALUE {int} -- Column IDs for the slot history
6259905aadb09d7d5dc0bb59
class BaseEditor(WidgetWrap, metaclass=signals.MetaSignals): <NEW_LINE> <INDENT> signals = ['done'] <NEW_LINE> def __init__(self, prompt, content, done_signal_handler, cursor_position=None): <NEW_LINE> <INDENT> caption = _(u'{0} (Enter key twice to validate, ' u'Esc or Ctrl-C to cancel) \n>> ').format(prompt) <NEW_LINE> if content: <NEW_LINE> <INDENT> content += ' ' <NEW_LINE> <DEDENT> self.content = content <NEW_LINE> self.editor = Edit(caption=caption, edit_text=content, edit_pos=cursor_position) <NEW_LINE> self.last_key = None <NEW_LINE> connect_signal(self, 'done', done_signal_handler) <NEW_LINE> <DEDENT> def _wrap(self, widgets): <NEW_LINE> <INDENT> widgets = widgets if isinstance(widgets, list) else [widgets] <NEW_LINE> composed_widget = Columns(widgets) <NEW_LINE> widget = AttrMap(LineBox(composed_widget), 'editor') <NEW_LINE> super(BaseEditor, self).__init__(widget) <NEW_LINE> <DEDENT> def keypress(self, size, key): <NEW_LINE> <INDENT> if key == 'enter' and self.last_key == 'enter': <NEW_LINE> <INDENT> self.submit() <NEW_LINE> return <NEW_LINE> <DEDENT> elif key == 'esc': <NEW_LINE> <INDENT> self.cancel() <NEW_LINE> return <NEW_LINE> <DEDENT> self.last_key = key <NEW_LINE> size = size, <NEW_LINE> self.editor.keypress(size, key) <NEW_LINE> <DEDENT> def submit(self): <NEW_LINE> <INDENT> self.emit_done_signal(self.editor.get_edit_text()) <NEW_LINE> <DEDENT> def cancel(self): <NEW_LINE> <INDENT> self.emit_done_signal() <NEW_LINE> <DEDENT> def emit_done_signal(self, content=None): <NEW_LINE> <INDENT> emit_signal(self, 'done', content)
Base class for editors.
6259905ae76e3b2f99fd9fee
class ChahubOAuth2(BaseOAuth2): <NEW_LINE> <INDENT> name = 'chahub' <NEW_LINE> API_URL = '{}/api/v1/'.format(BASE_URL) <NEW_LINE> AUTHORIZATION_URL = '{}/oauth/authorize/'.format(BASE_URL) <NEW_LINE> ACCESS_TOKEN_URL = '{}/oauth/token/'.format(BASE_URL) <NEW_LINE> ACCESS_TOKEN_METHOD = 'POST' <NEW_LINE> ID_KEY = 'id' <NEW_LINE> def get_user_id(self, details, response): <NEW_LINE> <INDENT> return details.get('id') <NEW_LINE> <DEDENT> def get_user_details(self, response): <NEW_LINE> <INDENT> access_token = response['access_token'] <NEW_LINE> my_profile_url = "{}my_profile/".format(self.API_URL) <NEW_LINE> data = self.get_json(my_profile_url, headers={'Authorization': 'Bearer {}'.format(access_token)}) <NEW_LINE> return { 'username': data.get('username'), 'email': data.get('email'), 'name': data.get('name', ''), 'id': data.get('id'), 'github_info': data.get('github_info', {}) }
Chahub OAuth authentication backend
6259905b76e4537e8c3f0b7c
class Policy_Interface(object): <NEW_LINE> <INDENT> def get_cost(self, config): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_edge_cost(self, config1, config2): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_step(self, config): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_neighbors(self, config): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_graph_size(self, correct_for_size=True): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_limited_offset_neighbors(self, config, max_offset, min_offset=0): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_offset_neighbors(self, config, offset): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_offsets(self, config): <NEW_LINE> <INDENT> raise NotImplementedError
Interface showing required implemented functions for all policies This interface enumerates the functions that must be exposed by policies for M* to function correctly. A policy object with this interface provides a route for a single robot. Underneath the policy interface is a graph object which describes the configuration space through which robots can move. The underlying graph object does all of the work of calculating the configuration space based on the actual environment in which the robot is moving **All config inputs must be hashable**
6259905a460517430c432b4a
class ChineseScale(Scale): <NEW_LINE> <INDENT> def __init__(self, key: Sounds) -> None: <NEW_LINE> <INDENT> super(ChineseScale, self).__init__(key, [ Intervals.MAJOR_THIRD, Intervals.WHOLE_TONE, Intervals.HALF_TONE, Intervals.MAJOR_THIRD, Intervals.HALF_TONE, ])
As implied by its name, this scale is suitable for playing Chinese music (see also the Oriental Scale). The Chinese scales are sometimes used in jazz improvisation. The Chinese Scale has a quite uncommon feature in the two quadra-steps: first to second note and fourth to fifth note. Another peculiar detail is that a harmony note is added to every single note in the scale (see below). :link: https://www.pianoscales.org/chinese.html
6259905b10dbd63aa1c72172
class CMakeBuild(build_ext): <NEW_LINE> <INDENT> def build_extension(self, ext): <NEW_LINE> <INDENT> if isinstance(ext, CMakeExtension): <NEW_LINE> <INDENT> cwd = os.getcwd() <NEW_LINE> if not os.path.exists(self.build_temp): <NEW_LINE> <INDENT> os.makedirs(self.build_temp) <NEW_LINE> <DEDENT> lib_dir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) <NEW_LINE> if not os.path.exists(lib_dir): <NEW_LINE> <INDENT> os.makedirs(lib_dir) <NEW_LINE> <DEDENT> cmake_args = _CMAKE_FLAGS <NEW_LINE> cmake_args.append( "-DNETKET_PYTHON_VERSION={}.{}.{}".format(*sys.version_info[:3]) ) <NEW_LINE> cmake_args.append("-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={}".format(lib_dir)) <NEW_LINE> if not _generator_specified(cmake_args) and _have_ninja(): <NEW_LINE> <INDENT> cmake_args.append("-GNinja") <NEW_LINE> <DEDENT> def _decode(x): <NEW_LINE> <INDENT> if sys.version_info >= (3, 0): <NEW_LINE> <INDENT> return x.decode() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> <DEDENT> os.chdir(self.build_temp) <NEW_LINE> try: <NEW_LINE> <INDENT> output = subprocess.check_output( ["cmake", ext.sourcedir] + cmake_args, stderr=subprocess.STDOUT ) <NEW_LINE> if self.distribution.verbose: <NEW_LINE> <INDENT> log.info(_decode(output)) <NEW_LINE> <DEDENT> if not self.distribution.dry_run: <NEW_LINE> <INDENT> output = subprocess.check_output( ["cmake", "--build", "."], stderr=subprocess.STDOUT ) <NEW_LINE> if self.distribution.verbose: <NEW_LINE> <INDENT> log.info(_decode(output)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except subprocess.CalledProcessError as e: <NEW_LINE> <INDENT> if hasattr(ext, "optional"): <NEW_LINE> <INDENT> if not ext.optional: <NEW_LINE> <INDENT> self.warn(_decode(e.output)) <NEW_LINE> raise <NEW_LINE> <DEDENT> self.warn( 'building extension "{}" failed:\n{}'.format( ext.name, _decode(e.output) ) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.warn(_decode(e.output)) <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> os.chdir(cwd) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if sys.version_info >= (3, 0): <NEW_LINE> <INDENT> super().build_extension(ext) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(build_ext, self).build_extension(ext)
We extend setuptools to support building extensions with CMake. An extension is built with CMake if it inherits from ``CMakeExtension``.
6259905b8e7ae83300eea67d
class LdapDNS(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.lobj = ldap.initialize(CONF.ldap_dns_url) <NEW_LINE> self.lobj.simple_bind_s(CONF.ldap_dns_user, CONF.ldap_dns_password) <NEW_LINE> <DEDENT> def get_domains(self): <NEW_LINE> <INDENT> return DomainEntry._get_all_domains(self.lobj) <NEW_LINE> <DEDENT> def create_entry(self, name, address, type, domain): <NEW_LINE> <INDENT> if type.lower() != 'a': <NEW_LINE> <INDENT> raise exception.InvalidInput(_("This driver only supports " "type 'a' entries.")) <NEW_LINE> <DEDENT> dEntry = DomainEntry(self.lobj, domain) <NEW_LINE> dEntry.add_entry(name, address) <NEW_LINE> <DEDENT> def delete_entry(self, name, domain): <NEW_LINE> <INDENT> dEntry = DomainEntry(self.lobj, domain) <NEW_LINE> dEntry.remove_entry(name) <NEW_LINE> <DEDENT> def get_entries_by_address(self, address, domain): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dEntry = DomainEntry(self.lobj, domain) <NEW_LINE> <DEDENT> except exception.NotFound: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> entries = dEntry.subentries_with_ip(address) <NEW_LINE> names = [] <NEW_LINE> for entry in entries: <NEW_LINE> <INDENT> names.extend(entry.names) <NEW_LINE> <DEDENT> return names <NEW_LINE> <DEDENT> def get_entries_by_name(self, name, domain): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dEntry = DomainEntry(self.lobj, domain) <NEW_LINE> <DEDENT> except exception.NotFound: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> nEntry = dEntry.subentry_with_name(name) <NEW_LINE> if nEntry: <NEW_LINE> <INDENT> return [nEntry.ip] <NEW_LINE> <DEDENT> <DEDENT> def modify_address(self, name, address, domain): <NEW_LINE> <INDENT> dEntry = DomainEntry(self.lobj, domain) <NEW_LINE> nEntry = dEntry.subentry_with_name(name) <NEW_LINE> nEntry.modify_address(name, address) <NEW_LINE> <DEDENT> def create_domain(self, domain): <NEW_LINE> <INDENT> DomainEntry.create_domain(self.lobj, domain) <NEW_LINE> <DEDENT> def delete_domain(self, domain): <NEW_LINE> <INDENT> dEntry = DomainEntry(self.lobj, domain) <NEW_LINE> dEntry.delete() <NEW_LINE> <DEDENT> def delete_dns_file(self): <NEW_LINE> <INDENT> LOG.warn("This shouldn't be getting called except during testing.") <NEW_LINE> pass
Driver for PowerDNS using ldap as a back end. This driver assumes ldap-method=strict, with all domains in the top-level, aRecords only.
6259905b56ac1b37e63037df
class statistics_node(): <NEW_LINE> <INDENT> def __init__(self, _list): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.name = "/".join([_list[0].product, _list[0].release, _list[0].kernel_long_version]) <NEW_LINE> <DEDENT> except IndexError as err: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.data = _list <NEW_LINE> self.benchmarks = OrderedDict() <NEW_LINE> self.benchmarks_init() <NEW_LINE> <DEDENT> def benchmarks_init(self): <NEW_LINE> <INDENT> _tmp_dict=dict() <NEW_LINE> for tc in self.data: <NEW_LINE> <INDENT> for bm in tc.benchmark: <NEW_LINE> <INDENT> if bm.name in _tmp_dict: <NEW_LINE> <INDENT> _tmp_dict[bm.name].append(float(bm.value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _tmp_dict[bm.name] = [float(bm.value)] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for k, v in _tmp_dict.items(): <NEW_LINE> <INDENT> self.benchmarks[k]=OrderedDict() <NEW_LINE> self.benchmarks[k]['mean']=statistics.mean(v) <NEW_LINE> self.benchmarks[k]['sum']=sum(v) <NEW_LINE> self.benchmarks[k]['max']=max(v) <NEW_LINE> self.benchmarks[k]['min']=min(v) <NEW_LINE> self.benchmarks[k]['stddev']=statistics.stdev(v) <NEW_LINE> self.benchmarks[k]['count']=len(v) <NEW_LINE> <DEDENT> <DEDENT> def print_benchmarks(self): <NEW_LINE> <INDENT> print(self.benchmarks) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def values(self): <NEW_LINE> <INDENT> self.indexs=list() <NEW_LINE> values=list() <NEW_LINE> for k,v in self.benchmarks.items(): <NEW_LINE> <INDENT> for k1,v1 in v.items(): <NEW_LINE> <INDENT> self.indexs.append(str(k)+'/'+str(k1)) <NEW_LINE> values.append(v1) <NEW_LINE> <DEDENT> <DEDENT> return values <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> self.indexs=list() <NEW_LINE> values=list() <NEW_LINE> for k,v in self.benchmarks.items(): <NEW_LINE> <INDENT> for k1,v1 in v.items(): <NEW_LINE> <INDENT> self.indexs.append(str(k)+str(k1)) <NEW_LINE> values.append(v1) <NEW_LINE> <DEDENT> <DEDENT> return str(values) <NEW_LINE> <DEDENT> def mean(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _sum(self, _list): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def stddev(self, _list): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def cov(self, _list): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _min(self, _list): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _max(self, _list): <NEW_LINE> <INDENT> pass
this class will make a statistics node for the list, the list will be use for statistics table
6259905bfff4ab517ebcee14
class WindowFunction(ABC): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def apply_to_window(self, values): <NEW_LINE> <INDENT> pass
Abstract class for applying function in window.
6259905b91f36d47f2231987
class QueryFilter(Query): <NEW_LINE> <INDENT> def __init__(self, condition): <NEW_LINE> <INDENT> super(QueryFilter, self).__init__() <NEW_LINE> self.condition = condition <NEW_LINE> <DEDENT> def __call__(self, items): <NEW_LINE> <INDENT> return (item for item in items if self.condition.test(item)) <NEW_LINE> <DEDENT> def validate(self, properties): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.condition = normalize(properties, self.condition) <NEW_LINE> <DEDENT> except (KeyError, ValueError) as detail: <NEW_LINE> <INDENT> raise BadQueryException(self, detail) <NEW_LINE> <DEDENT> return properties <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Filter: %r" % self.condition
Query filtering a set of items. >>> from kalamar.request import Condition >>> cond = Condition("a", "=" , 12) >>> items = [{"a": 13, "b": 15}, {"a": 12, "b": 16}] >>> filter = QueryFilter(cond) >>> list(filter(items)) [{'a': 12, 'b': 16}]
6259905b435de62698e9d3f4
class EqConstraintSystem(SimpleSystem): <NEW_LINE> <INDENT> def setup_variables(self, resid_state_map=None): <NEW_LINE> <INDENT> super(EqConstraintSystem, self).setup_variables(resid_state_map) <NEW_LINE> nodemap = self.scope.name2collapsed <NEW_LINE> src = self._comp._exprobj.lhs.text <NEW_LINE> srcnode = nodemap.get(src, src) <NEW_LINE> dest = self._comp._exprobj.rhs.text <NEW_LINE> destnode = nodemap.get(dest, dest) <NEW_LINE> for _, state_node in resid_state_map.items(): <NEW_LINE> <INDENT> if state_node == srcnode: <NEW_LINE> <INDENT> self._comp._negate = True <NEW_LINE> break <NEW_LINE> <DEDENT> elif state_node == destnode: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def run(self, iterbase, case_label='', case_uuid=None): <NEW_LINE> <INDENT> if self.is_active(): <NEW_LINE> <INDENT> super(EqConstraintSystem, self).run(iterbase, case_label=case_label, case_uuid=case_uuid) <NEW_LINE> collapsed_name = self.scope.name2collapsed[self.name+'.out0'] <NEW_LINE> state = self._mapped_resids.get(collapsed_name) <NEW_LINE> if state: <NEW_LINE> <INDENT> self.vec['f'][state][:] = -self._comp.get_flattened_value('out0').real <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def evaluate(self, iterbase, case_label='', case_uuid=None): <NEW_LINE> <INDENT> self.run(iterbase, case_label=case_label, case_uuid=case_uuid)
A special system to handle mapping of states and residuals.
6259905bdd821e528d6da478
class RDInvest(HandleIndexContent): <NEW_LINE> <INDENT> def __init__(self, stk_cd_id, acc_per, indexno, indexcontent): <NEW_LINE> <INDENT> super(RDInvest, self).__init__(stk_cd_id, acc_per, indexno, indexcontent) <NEW_LINE> <DEDENT> def recognize(self): <NEW_LINE> <INDENT> indexnos = ['0402010300'] <NEW_LINE> pass <NEW_LINE> <DEDENT> def converse(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def logic(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> df,unit,instructi = recognize_df_and_instucti(self.indexcontent) <NEW_LINE> if df is not None and len(df) > 0: <NEW_LINE> <INDENT> expens = df.iloc[list(np.where((df.iloc[:, 0] == '本期费用化研发投入'))[0])[0],1] <NEW_LINE> capit = df.iloc[list(np.where((df.iloc[:, 0] == '本期资本化研发投入'))[0])[0],1] <NEW_LINE> total = df.iloc[list(np.where((df.iloc[:, 0] == '研发投入合计'))[0])[0],1] <NEW_LINE> proport_of_incom = df.iloc[list(np.where((df.iloc[:, 0].str.contains('研发投入总额占营业收入比例')))[0])[0],1] <NEW_LINE> staff_number = df.iloc[list(np.where((df.iloc[:, 0].str.contains('公司研发人员的数量')))[0])[0],1] <NEW_LINE> proport_of_staff = df.iloc[list(np.where((df.iloc[:, 0].str.contains('研发人员数量占公司总人数的比例')))[0])[0],1] <NEW_LINE> value_dict = dict( stk_cd_id=self.stk_cd_id, acc_per=self.acc_per, expens=num_to_decimal(expens, unit), capit=num_to_decimal(capit, unit), total=num_to_decimal(total, unit), proport_of_incom=num_to_decimal(proport_of_incom), staff_number=int(float(re.sub(',', '', str(staff_number)))), proport_of_staff=num_to_decimal(proport_of_staff), ) <NEW_LINE> create_and_update('RDInvest',**value_dict) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass
研发投入情况
6259905be64d504609df9ec7
class EventObject: <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_bytes(cls: Type[T], bytes_data: bytes) -> T: <NEW_LINE> <INDENT> return cls(**pickle.loads(bytes_data)) <NEW_LINE> <DEDENT> def to_bytes(self) -> bytes: <NEW_LINE> <INDENT> return pickle.dumps(asdict(self)) <NEW_LINE> <DEDENT> def __eq__(self, other: T) -> bool: <NEW_LINE> <INDENT> check = [] <NEW_LINE> for k, v in asdict(self).items(): <NEW_LINE> <INDENT> other_v = getattr(other, k) <NEW_LINE> if isinstance(v, np.ndarray): <NEW_LINE> <INDENT> check.append(np.array_equal(v, other_v)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> check.append(v == other_v) <NEW_LINE> <DEDENT> <DEDENT> return all(check) <NEW_LINE> <DEDENT> def _do_write_summary(self, value: Any, writer: SummaryWriter, global_step: int, namespace: Optional[Path]) -> None: <NEW_LINE> <INDENT> if isinstance(value, (int, float)): <NEW_LINE> <INDENT> writer.add_scalar(str(namespace), value, global_step) <NEW_LINE> <DEDENT> elif isinstance(value, (np.ndarray, np.generic)): <NEW_LINE> <INDENT> if value.ndim == 1 and len(value) == 1: writer.add_scalar(str(namespace), value, global_step) <NEW_LINE> writer.add_histogram(str(namespace), value, global_step) <NEW_LINE> <DEDENT> elif isinstance(value, (list, tuple)): <NEW_LINE> <INDENT> writer.add_histogram(str(namespace), np.array(value), global_step) <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> [self._do_write_summary(v, writer, global_step, namespace / k) for k, v in value.items()] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError(f"Invalid value type: {value}") <NEW_LINE> <DEDENT> <DEDENT> def write_summary(self, writer: SummaryWriter, global_step: int, namespace: Optional[Path] = None) -> None: <NEW_LINE> <INDENT> if namespace is None: namespace = Path(type(self).__name__) <NEW_LINE> for name, v in asdict(self).items(): <NEW_LINE> <INDENT> if v is None: continue <NEW_LINE> self._do_write_summary(v, writer, global_step, namespace / name) <NEW_LINE> <DEDENT> <DEDENT> def as_format_str(self) -> str: <NEW_LINE> <INDENT> return pprint.pformat(asdict(self), compact=True)
Serializable dataclass. Note that the all fields should be pickalable.
6259905b0fa83653e46f64d7
class PolyInitBlock(Chain): <NEW_LINE> <INDENT> def __init__(self, in_channels): <NEW_LINE> <INDENT> super(PolyInitBlock, self).__init__() <NEW_LINE> with self.init_scope(): <NEW_LINE> <INDENT> self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=32, stride=2, pad=0) <NEW_LINE> self.conv2 = conv3x3_block( in_channels=32, out_channels=32, pad=0) <NEW_LINE> self.conv3 = conv3x3_block( in_channels=32, out_channels=64) <NEW_LINE> self.block1 = PolyBlock3a() <NEW_LINE> self.block2 = PolyBlock4a() <NEW_LINE> self.block3 = PolyBlock5a() <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> x = self.conv1(x) <NEW_LINE> x = self.conv2(x) <NEW_LINE> x = self.conv3(x) <NEW_LINE> x = self.block1(x) <NEW_LINE> x = self.block2(x) <NEW_LINE> x = self.block3(x) <NEW_LINE> return x
PolyNet specific initial block. Parameters: ---------- in_channels : int Number of input channels.
6259905b16aa5153ce401ad4
class BaseAnalysisRule(object): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> @abc.abstractproperty <NEW_LINE> def for_topo_type(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> @abc.abstractproperty <NEW_LINE> def dict_key(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def execute(self, occshape_dict_list): <NEW_LINE> <INDENT> return
The base class for developing new analysis rule for analysing topologies in massing model. For more information please refer to Chen, Kian Wee, Patrick Janssen, and Leslie Norford. 2017. Automatic Generation of Semantic 3D City Models from Conceptual Massing Models. In Future Trajectories of Computation in Design, Proceedings of the 17th International Conference on Computer Aided Architectural Design Futures, pp 84 to 100. Istanbul, Turkey.
6259905b3539df3088ecd88d
class TestCase(testtools.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestCase, self).setUp()
Test case base class for all unit tests.
6259905b7b25080760ed87d8
class PrivateLogListHandler(base.BaseHandler): <NEW_LINE> <INDENT> PAGE_NAME_FOR_CSRF = 'editor' <NEW_LINE> def get(self): <NEW_LINE> <INDENT> self.values.update({ 'logs': [t.to_dict() for t in privatelog_services. get_all_privatelog(self.user_id)]}) <NEW_LINE> self.render_json(self.values)
处理个人日志请求列表
6259905b0a50d4780f7068b7
class LineRule(Rule): <NEW_LINE> <INDENT> pass
Class representing rules that act on a line by line basis
6259905be76e3b2f99fd9ff0
class PSO: <NEW_LINE> <INDENT> def __init__(self, layers: list, hyperparameters: dict, NN:NeuralNetwork, maxIter: int): <NEW_LINE> <INDENT> self.position_range = hyperparameters["position_range"] <NEW_LINE> self.velocity_range = hyperparameters["velocity_range"] <NEW_LINE> self.omega = hyperparameters["omega"] <NEW_LINE> self.c1 = hyperparameters["c1"] <NEW_LINE> self.c2 = hyperparameters["c2"] <NEW_LINE> self.vmax = hyperparameters["vmax"] <NEW_LINE> self.pop_size = hyperparameters["pop_size"] <NEW_LINE> self.layers = layers <NEW_LINE> self.NN = NN <NEW_LINE> self.population = [] <NEW_LINE> for i in range(self.pop_size): <NEW_LINE> <INDENT> self.population.append(Particle(self.position_range, self.velocity_range, layers)) <NEW_LINE> <DEDENT> self.gbest_fitness = float('inf') <NEW_LINE> self.gbest_position = None <NEW_LINE> self.max_t = maxIter <NEW_LINE> self.fitness_plot = [] <NEW_LINE> <DEDENT> def update_position_and_velocity(self): <NEW_LINE> <INDENT> for p in self.population: <NEW_LINE> <INDENT> v = p.velocity <NEW_LINE> w = self.omega <NEW_LINE> c1 = self.c1 <NEW_LINE> r1 = random.uniform(0,1) <NEW_LINE> c2 = self.c2 <NEW_LINE> r2 = random.uniform(0,1) <NEW_LINE> pb = p.pbest_position <NEW_LINE> gb = self.gbest_position <NEW_LINE> x = p.position <NEW_LINE> new_v = w*v + c1*r1*(pb - x) + c2*r2*(gb - x) <NEW_LINE> new_v[new_v > self.vmax] = self.vmax <NEW_LINE> new_v[new_v < -self.vmax] = -self.vmax <NEW_LINE> p.velocity = new_v <NEW_LINE> p.position += new_v <NEW_LINE> <DEDENT> <DEDENT> def update_fitness(self) -> None: <NEW_LINE> <INDENT> for p in self.population: <NEW_LINE> <INDENT> fitness = self.NN.fitness(p.position) <NEW_LINE> if p.pbest_fitness > fitness: <NEW_LINE> <INDENT> p.pbest_fitness = fitness <NEW_LINE> p.pbest_position = p.position <NEW_LINE> <DEDENT> if self.gbest_fitness > fitness: <NEW_LINE> <INDENT> self.gbest_fitness = fitness <NEW_LINE> self.gbest_position = p.position <NEW_LINE> <DEDENT> p.fitness = fitness <NEW_LINE> <DEDENT> self.fitness_plot.append(self.gbest_fitness)
this is the driver class for the PSO. For the given number of iterations or stopping condition it will update particle positions and velocities and track the global best position which is the position with the best fitness so far.
6259905b76e4537e8c3f0b7e
class TestWebPaymentItem(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 testWebPaymentItem(self): <NEW_LINE> <INDENT> pass
WebPaymentItem unit test stubs
6259905b1f037a2d8b9e5364
class CircularContour(Contour): <NEW_LINE> <INDENT> def __init__(self, centre, radius, integration_rule=TrapezoidalRule(20)): <NEW_LINE> <INDENT> self.centre = centre <NEW_LINE> self.radius = radius <NEW_LINE> self.integration_rule = integration_rule <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> d_theta = 2*np.pi <NEW_LINE> for x, w in self.integration_rule: <NEW_LINE> <INDENT> theta = 2*np.pi*x <NEW_LINE> s = np.exp(1j*theta)*self.radius+self.centre <NEW_LINE> ds_dtheta = 1j*np.exp(1j*theta)*self.radius <NEW_LINE> yield(s, w*ds_dtheta*d_theta) <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.integration_rule)
A circular contour in the complex frequency plane
6259905b0c0af96317c57858
class AceJumpAfterCommand(sublime_plugin.WindowCommand): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> global mode <NEW_LINE> mode = 0 if mode == 3 else 3
Modifier-command which lets you jump behind a character, word or line
6259905b4a966d76dd5f04e4
class JoinFriendDialog(wx.Dialog): <NEW_LINE> <INDENT> def __init__(self, parent, err_msg, default): <NEW_LINE> <INDENT> wx.Dialog.__init__(self, parent, wx.ID_ANY, "Connect to Friend") <NEW_LINE> text = makeHeading(self, "Waiting for Automatic Invitation.") <NEW_LINE> text2 = makeHint(self, "This prompt will disappear once automatic invitation is received.") <NEW_LINE> if err_msg: <NEW_LINE> <INDENT> err_msg_text = makeText(self, err_msg_text) <NEW_LINE> err_msg_text.SetForegroundColour("#663333") <NEW_LINE> err_msg_object = (err_msg_text, 0, wx.TOP | wx.LEFT | wx.RIGHT, 10) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> err_msg_object = (0, 0) <NEW_LINE> <DEDENT> hint = makeHint(self, "If you can't use automatic invites, enter invitation code.\n" "You probably received this in your IM client.\n" "Valid codes look like '[email protected]/1xwords1234ABCD'.") <NEW_LINE> self.join = wx.TextCtrl(self, wx.ID_ANY) <NEW_LINE> if default: <NEW_LINE> <INDENT> self.join.SetValue(default) <NEW_LINE> <DEDENT> btn_sizer = wx.StdDialogButtonSizer() <NEW_LINE> cancel = wx.Button(self, wx.ID_CANCEL) <NEW_LINE> btn_sizer.AddButton(cancel) <NEW_LINE> self.ok = ok = wx.Button(self, wx.ID_OK, label="Connect") <NEW_LINE> btn_sizer.AddButton(ok) <NEW_LINE> ok.SetDefault() <NEW_LINE> btn_sizer.Realize() <NEW_LINE> outer_sizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> outer_sizer.AddMany([ (text, 0, wx.TOP | wx.RIGHT | wx.LEFT, 20), (7, 7), (text2, 0, wx.LEFT | wx.RIGHT, 20), (10, 10), (hint, 0, wx.LEFT | wx.RIGHT, 20), (10, 10), err_msg_object, (10, 10), (self.join, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 20), (btn_sizer, 0, wx.ALIGN_RIGHT | wx.RIGHT | wx.LEFT | wx.TOP | wx.BOTTOM, 20) ]) <NEW_LINE> self.SetSizer(outer_sizer) <NEW_LINE> outer_sizer.Fit(self)
Dialog box that prompts to join a user. Ends in one of several ways: - manually canceled; caused disconnection - filled in by user; tries to join - system calls EndModal with JID of friend; this is done if we actually get the invite
6259905b91f36d47f2231988
class Completer(completer.BaseCompleter): <NEW_LINE> <INDENT> def __init__(self, stc_buffer): <NEW_LINE> <INDENT> completer.BaseCompleter.__init__(self, stc_buffer) <NEW_LINE> self.SetAutoCompKeys([ord(':'), ord('.') ]) <NEW_LINE> self.SetAutoCompStops(' {}#') <NEW_LINE> self.SetAutoCompFillups('') <NEW_LINE> self.SetCallTipKeys([ord('('), ]) <NEW_LINE> self.SetCallTipCancel([ord(')'), wx.WXK_RETURN]) <NEW_LINE> <DEDENT> def GetAutoCompList(self, command): <NEW_LINE> <INDENT> buff = self.GetBuffer() <NEW_LINE> keywords = buff.GetKeywords() <NEW_LINE> if command in [None, u'']: <NEW_LINE> <INDENT> return completer.CreateSymbols(keywords, completer.TYPE_UNKNOWN) <NEW_LINE> <DEDENT> cpos = buff.GetCurrentPos() <NEW_LINE> cline = buff.GetCurrentLine() <NEW_LINE> lstart = buff.PositionFromLine(cline) <NEW_LINE> tmp = buff.GetTextRange(lstart, cpos).rstrip() <NEW_LINE> if IsPsuedoClass(command, tmp): <NEW_LINE> <INDENT> return PSUEDO_SYMBOLS <NEW_LINE> <DEDENT> if tmp.endswith(u':'): <NEW_LINE> <INDENT> word = GetWordLeft(tmp.rstrip().rstrip(u':')) <NEW_LINE> comps = PROP_OPTS.get(word, list()) <NEW_LINE> comps = list(set(comps)) <NEW_LINE> comps.sort() <NEW_LINE> return completer.CreateSymbols(comps, completer.TYPE_PROPERTY) <NEW_LINE> <DEDENT> if tmp.endswith(u'.'): <NEW_LINE> <INDENT> classes = list() <NEW_LINE> if not buff.IsString(cpos): <NEW_LINE> <INDENT> txt = buff.GetText() <NEW_LINE> txt = RE_CSS_COMMENT.sub(u'', txt) <NEW_LINE> txt = RE_CSS_BLOCK.sub(u' ', txt) <NEW_LINE> for token in txt.split(): <NEW_LINE> <INDENT> if u'.' in token: <NEW_LINE> <INDENT> classes.append(token.split(u'.', 1)[-1]) <NEW_LINE> <DEDENT> <DEDENT> classes = list(set(classes)) <NEW_LINE> classes.sort() <NEW_LINE> <DEDENT> return completer.CreateSymbols(classes, completer.TYPE_CLASS) <NEW_LINE> <DEDENT> return completer.CreateSymbols(keywords, completer.TYPE_UNKNOWN) <NEW_LINE> <DEDENT> def GetCallTip(self, command): <NEW_LINE> <INDENT> if command == u'url': <NEW_LINE> <INDENT> return u'url(\'../path\')' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return u'' <NEW_LINE> <DEDENT> <DEDENT> def ShouldCheck(self, cpos): <NEW_LINE> <INDENT> buff = self.GetBuffer() <NEW_LINE> rval = True <NEW_LINE> if buff is not None: <NEW_LINE> <INDENT> if buff.IsComment(cpos): <NEW_LINE> <INDENT> rval = False <NEW_LINE> <DEDENT> <DEDENT> return rval
Code completer provider
6259905bac7a0e7691f73ad4