code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
@serialization.register("ColumnStorage") <NEW_LINE> class ColumnStorage(mapping.Configurations): <NEW_LINE> <INDENT> def __getitem__(self, key, dict_getitem=dict.__getitem__): <NEW_LINE> <INDENT> key = self._keychecker(key) <NEW_LINE> return dict_getitem(self, key) <NEW_LINE> <DEDENT> def insert_block(self, type_, *columns): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def remove_block(self, index): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _keychecker(self, item): <NEW_LINE> <INDENT> if isinstance(item, six.string_types): <NEW_LINE> <INDENT> return REPORTNAMES[item] <NEW_LINE> <DEDENT> return item
|
Column storage definitions
|
6259900f56b00c62f0fb3525
|
class Test_Readline(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.s = serial.serial_for_url(PORT, timeout=1) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.s.close() <NEW_LINE> <DEDENT> def test_readline(self): <NEW_LINE> <INDENT> self.s.write(serial.to_bytes(b"1\n2\n3\n")) <NEW_LINE> self.assertEqual(self.s.readline(), serial.to_bytes(b"1\n")) <NEW_LINE> self.assertEqual(self.s.readline(), serial.to_bytes(b"2\n")) <NEW_LINE> self.assertEqual(self.s.readline(), serial.to_bytes(b"3\n")) <NEW_LINE> self.assertEqual(self.s.readline(), serial.to_bytes("")) <NEW_LINE> <DEDENT> def test_readlines(self): <NEW_LINE> <INDENT> self.s.write(serial.to_bytes(b"1\n2\n3\n")) <NEW_LINE> self.assertEqual( self.s.readlines(), [serial.to_bytes(b"1\n"), serial.to_bytes(b"2\n"), serial.to_bytes(b"3\n")] ) <NEW_LINE> <DEDENT> def test_xreadlines(self): <NEW_LINE> <INDENT> if hasattr(self.s, 'xreadlines'): <NEW_LINE> <INDENT> self.s.write(serial.to_bytes(b"1\n2\n3\n")) <NEW_LINE> self.assertEqual( list(self.s), [serial.to_bytes(b"1\n"), serial.to_bytes(b"2\n"), serial.to_bytes(b"3\n")] ) <NEW_LINE> <DEDENT> <DEDENT> def test_for_in(self): <NEW_LINE> <INDENT> self.s.write(serial.to_bytes(b"1\n2\n3\n")) <NEW_LINE> lines = [] <NEW_LINE> for line in self.s: <NEW_LINE> <INDENT> lines.append(line) <NEW_LINE> <DEDENT> self.assertEqual( lines, [serial.to_bytes(b"1\n"), serial.to_bytes(b"2\n"), serial.to_bytes(b"3\n")] ) <NEW_LINE> <DEDENT> def test_alternate_eol(self): <NEW_LINE> <INDENT> if hasattr(self.s, 'xreadlines'): <NEW_LINE> <INDENT> self.s.write(serial.to_bytes("no\rno\nyes\r\n")) <NEW_LINE> self.assertEqual( self.s.readline(eol=serial.to_bytes("\r\n")), serial.to_bytes("no\rno\nyes\r\n"))
|
Test readline function
|
6259900f0a366e3fb87dd65a
|
class MPQFactory(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def create(): <NEW_LINE> <INDENT> return multiprocessing.Queue() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def destroy(queue): <NEW_LINE> <INDENT> pass
|
Creator pattern for multiprocessing.Queue, also include destruction
Note this is a singleton object
|
6259900fd18da76e235b7781
|
class UnauthenticatedTT(BaseTT): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(UnauthenticatedTT, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def get_locales(self, *args, **kwargs): <NEW_LINE> <INDENT> url = self.config['get_locales'] <NEW_LINE> return self.get_content(url, *args, **kwargs) <NEW_LINE> <DEDENT> def upload_token(self, *args, **kwargs): <NEW_LINE> <INDENT> url = self.config['upload_token'] <NEW_LINE> return self.request_json(url, method='POST', *args, **kwargs)['data']['upload_token']
|
This mixin provider the UNauthenticated API access for Toptranslation
|
6259900f56b00c62f0fb3527
|
class Singleton(type): <NEW_LINE> <INDENT> _instances = {} <NEW_LINE> def __call__(cls, *args, **kwargs): <NEW_LINE> <INDENT> if cls not in cls._instances: <NEW_LINE> <INDENT> cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) <NEW_LINE> <DEDENT> return cls._instances[cls]
|
This is a class for ensuring classes are not duplicated.
|
6259900fbf627c535bcb211a
|
class _DecoratorClass(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.function = None <NEW_LINE> <DEDENT> def __call__(self, function): <NEW_LINE> <INDENT> if self.function is not None: <NEW_LINE> <INDENT> raise ValueError("Already hooked to a function") <NEW_LINE> <DEDENT> if not callable(function): <NEW_LINE> <INDENT> raise ValueError("Function must be callable") <NEW_LINE> <DEDENT> self.function = function <NEW_LINE> if function.__doc__: <NEW_LINE> <INDENT> self.doc = function.__doc__.split('\n', 1)[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.doc = None <NEW_LINE> <DEDENT> if hasattr(function, "bot_hooks"): <NEW_LINE> <INDENT> function.bot_hooks.append(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> function.bot_hooks = [self] <NEW_LINE> <DEDENT> return function
|
:type function: callable
|
6259900f925a0f43d25e8cac
|
class IContentListingTileLayer(Interface): <NEW_LINE> <INDENT> pass
|
Layer (request marker interface) for content listing tile views
|
625990103cc13d1c6d4663b5
|
class BadgeManagementProxy(Badge): <NEW_LINE> <INDENT> @property <NEW_LINE> def can_revoke(self): <NEW_LINE> <INDENT> return self.person is None <NEW_LINE> <DEDENT> @property <NEW_LINE> def can_unrevoke(self): <NEW_LINE> <INDENT> return self.can_revoke <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> proxy = True
|
Contains extra methods for Badge used by the management views.
|
6259901056b00c62f0fb352d
|
class ITree(object): <NEW_LINE> <INDENT> def parent(self, vtx_id): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def children(self, vtx_id): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def nb_children(self, vtx_id): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def siblings(self, vtx_id): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def nb_siblings(self, vtx_id): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def is_leaf(self, vtx_id): <NEW_LINE> <INDENT> raise NotImplementedError
|
Rooted Tree interface.
depth(vid), depth() and sub_tree(vid) can be extenal algorithms.
|
62599010d18da76e235b7786
|
class GroupUpdateError(GroupSelectorWithTeamGroupError): <NEW_LINE> <INDENT> group_name_already_used = None <NEW_LINE> group_name_invalid = None <NEW_LINE> external_id_already_in_use = None <NEW_LINE> def is_group_name_already_used(self): <NEW_LINE> <INDENT> return self._tag == 'group_name_already_used' <NEW_LINE> <DEDENT> def is_group_name_invalid(self): <NEW_LINE> <INDENT> return self._tag == 'group_name_invalid' <NEW_LINE> <DEDENT> def is_external_id_already_in_use(self): <NEW_LINE> <INDENT> return self._tag == 'external_id_already_in_use' <NEW_LINE> <DEDENT> def _process_custom_annotations(self, annotation_type, processor): <NEW_LINE> <INDENT> super(GroupUpdateError, self)._process_custom_annotations(annotation_type, processor) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'GroupUpdateError(%r, %r)' % (self._tag, self._value)
|
This class acts as a tagged union. Only one of the ``is_*`` methods will
return true. To get the associated value of a tag (if one exists), use the
corresponding ``get_*`` method.
:ivar group_name_already_used: The requested group name is already being
used by another group.
:ivar group_name_invalid: Group name is empty or has invalid characters.
:ivar external_id_already_in_use: The requested external ID is already being
used by another group.
|
62599010bf627c535bcb2123
|
class FaxList(ListResource): <NEW_LINE> <INDENT> def __init__(self, version): <NEW_LINE> <INDENT> super(FaxList, self).__init__(version) <NEW_LINE> self._solution = {} <NEW_LINE> self._uri = '/Faxes'.format(**self._solution) <NEW_LINE> <DEDENT> def stream(self, from_=values.unset, to=values.unset, date_created_on_or_before=values.unset, date_created_after=values.unset, limit=None, page_size=None): <NEW_LINE> <INDENT> limits = self._version.read_limits(limit, page_size) <NEW_LINE> page = self.page( from_=from_, to=to, date_created_on_or_before=date_created_on_or_before, date_created_after=date_created_after, page_size=limits['page_size'], ) <NEW_LINE> return self._version.stream(page, limits['limit'], limits['page_limit']) <NEW_LINE> <DEDENT> def list(self, from_=values.unset, to=values.unset, date_created_on_or_before=values.unset, date_created_after=values.unset, limit=None, page_size=None): <NEW_LINE> <INDENT> return list(self.stream( from_=from_, to=to, date_created_on_or_before=date_created_on_or_before, date_created_after=date_created_after, limit=limit, page_size=page_size, )) <NEW_LINE> <DEDENT> def page(self, from_=values.unset, to=values.unset, date_created_on_or_before=values.unset, date_created_after=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): <NEW_LINE> <INDENT> params = values.of({ 'From': from_, 'To': to, 'DateCreatedOnOrBefore': serialize.iso8601_datetime(date_created_on_or_before), 'DateCreatedAfter': serialize.iso8601_datetime(date_created_after), 'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) <NEW_LINE> response = self._version.page( 'GET', self._uri, params=params, ) <NEW_LINE> return FaxPage(self._version, response, self._solution) <NEW_LINE> <DEDENT> def get_page(self, target_url): <NEW_LINE> <INDENT> response = self._version.domain.twilio.request( 'GET', target_url, ) <NEW_LINE> return FaxPage(self._version, response, self._solution) <NEW_LINE> <DEDENT> def create(self, to, media_url, quality=values.unset, status_callback=values.unset, from_=values.unset, sip_auth_username=values.unset, sip_auth_password=values.unset, store_media=values.unset, ttl=values.unset): <NEW_LINE> <INDENT> data = values.of({ 'To': to, 'MediaUrl': media_url, 'Quality': quality, 'StatusCallback': status_callback, 'From': from_, 'SipAuthUsername': sip_auth_username, 'SipAuthPassword': sip_auth_password, 'StoreMedia': store_media, 'Ttl': ttl, }) <NEW_LINE> payload = self._version.create( 'POST', self._uri, data=data, ) <NEW_LINE> return FaxInstance(self._version, payload, ) <NEW_LINE> <DEDENT> def get(self, sid): <NEW_LINE> <INDENT> return FaxContext(self._version, sid=sid, ) <NEW_LINE> <DEDENT> def __call__(self, sid): <NEW_LINE> <INDENT> return FaxContext(self._version, sid=sid, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Fax.V1.FaxList>'
|
PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.
|
625990103cc13d1c6d4663bb
|
class EXT(SEQ): <NEW_LINE> <INDENT> TYPE = TYPE_EXT <NEW_LINE> TAG = 8
|
ASN.1 context switching type EXTERNAL object
associated type:
[UNIVERSAL 8] IMPLICIT SEQUENCE {
identification [0] EXPLICIT CHOICE {
syntaxes [0] SEQUENCE {
abstract [0] OBJECT IDENTIFIER,
transfer [1] OBJECT IDENTIFIER
},
syntax [1] OBJECT IDENTIFIER,
presentation-context-id [2] INTEGER,
context-negotiation [3] SEQUENCE {
presentation-context-id [0] INTEGER,
transfer-syntax [1] OBJECT IDENTIFIER
},
transfer-syntax [4] OBJECT IDENTIFIER,
fixed [5] NULL
},
data-value-descriptor [1] ObjectDescriptor OPTIONAL,
data-value [2] OCTET STRING
} (WITH COMPONENTS {
...,
identification (WITH COMPONENTS {
...,
syntaxes ABSENT,
transfer-syntax ABSENT,
fixed ABSENT })
})
|
62599010925a0f43d25e8cb4
|
class RegistroH010(Registro): <NEW_LINE> <INDENT> campos = [ CampoFixo(1, 'REG', 'H010'), Campo(2, 'COD_ITEM'), Campo(3, 'UNID'), CampoNumerico(4, 'QTD'), CampoNumerico(5, 'VL_UNIT', precisao=2), CampoNumerico(6, 'VL_ITEM', precisao=2), Campo(7, 'IND_PROP'), Campo(8, 'COD_PART'), Campo(9, 'TXT_COMPL'), Campo(10, 'COD_CTA'), CampoNumerico(11, 'VL_ITEM_IR', precisao=2), ]
|
INVENTÁRIO
|
62599010627d3e7fe0e07b0e
|
class EKF(object): <NEW_LINE> <INDENT> def __init__(self,x,P,V,R=0,L=0.2): <NEW_LINE> <INDENT> self.L=L <NEW_LINE> self.x = x <NEW_LINE> self.P = P <NEW_LINE> self.V = V <NEW_LINE> self.R = R <NEW_LINE> <DEDENT> def Fx(self,x,u): <NEW_LINE> <INDENT> return np.array([[1,0,-u[0]*math.sin(x[2])], [0,1, u[0]*math.cos(x[2])], [0,0, 1 ]]) <NEW_LINE> <DEDENT> def Fu(self,x,u): <NEW_LINE> <INDENT> return np.array([[math.cos(x[2]), 0], [math.sin(x[2]), 0], [math.tan(u[1])/self.L, (u[0]/self.L)*(1/math.cos(u[1]))**2]]) <NEW_LINE> <DEDENT> def f(self,x,u): <NEW_LINE> <INDENT> return np.array([x[0]+u[0]*math.cos(x[2]), x[1]+u[0]*math.sin(x[2]), x[2]+((u[0]/self.L)*math.tan(u[1]))]) <NEW_LINE> <DEDENT> def H(self): <NEW_LINE> <INDENT> return np.eye(3) <NEW_LINE> <DEDENT> def h(self,x): <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> def Prediction(self,u): <NEW_LINE> <INDENT> x_ = self.x <NEW_LINE> P_ = self.P <NEW_LINE> self.x = self.f(x_,u) <NEW_LINE> self.P = self.Fx(x_,u).dot(P_).dot((self.Fx(x_,u)).T) + self.Fu(x_,u).dot(self.V).dot((self.Fu(x_,u)).T) <NEW_LINE> <DEDENT> def Update(self, z): <NEW_LINE> <INDENT> y = z - self.h(self.x) <NEW_LINE> K = self.P.dot(np.linalg.inv(self.P+self.R)) <NEW_LINE> self.x = self.x + K.dot(y) <NEW_LINE> self.P = (np.eye(3)-K).dot(self.P)
|
Implements an EKF to the localization of the famous bicycle model.
Ist control inputs must be in meters and radians, as well for its state.
|
6259901056b00c62f0fb3533
|
class MainDashboard(Component): <NEW_LINE> <INDENT> def __init__(self, parent, **props): <NEW_LINE> <INDENT> super(MainDashboard, self).__init__(parent, **props) <NEW_LINE> self.state = {} <NEW_LINE> self.status = StringVar() <NEW_LINE> self.dashboard = Frame(self, bg=BG_COLOR, frame=self.parent_frame, width=self.width, height=self.height) <NEW_LINE> self.label = Label(self, self.status, frame=self.dashboard, bg=BG_COLOR, foreground=TEXT_COLOR, font=("Helvetica", 30)) <NEW_LINE> self.nyquist_plot = Plot(self, frame=self.dashboard, width=self.width, height=self.height, x=self.x, y=0, data=self.props.data, freqs_explicit=self.props.freqs_explicit) <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> self.dashboard.pack(side='right', fill='y', padx=(1, 0)) <NEW_LINE> if self.props.is_device_connected and self.props.hive_record_ready: <NEW_LINE> <INDENT> title = "Nyquist Plot" <NEW_LINE> self.nyquist_plot.render() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> title = 'Loading user data...' if self.props.is_device_connected else 'No device detected' <NEW_LINE> <DEDENT> self.label.place(relwidth=1, height=100) <NEW_LINE> self.status.set(title)
|
MainDashboard Component.
The React Component that contains either the GUI's plot or a waiting screen if the device is not connected or the
.hive file is not ready.
Attributes:
status (react.widget_wrappers.StringVar): Stores the current title of the main dashboard.
dashboard (react.widget_wrappers.Frame): The frame where all main widgets will be contained.
label (react.widget_wrappers.Label): The title of the dashboard.
nyquist_plot (src.components.plot.Plot): The Nyquist Plot generated by the data returned by the EIS.
|
625990103cc13d1c6d4663be
|
class Base(object): <NEW_LINE> <INDENT> def __init__(self, driver): <NEW_LINE> <INDENT> self.driver = driver <NEW_LINE> <DEDENT> def base_find_element(self, loc, time_out=10, poll_fre=0.5): <NEW_LINE> <INDENT> element = WebDriverWait(self.driver, time_out, poll_fre).until(lambda x:x.find_element(*loc)) <NEW_LINE> return element <NEW_LINE> <DEDENT> def base_click_element(self, loc): <NEW_LINE> <INDENT> self.base_find_element(loc).click() <NEW_LINE> <DEDENT> def base_input_element(self, loc, text_input): <NEW_LINE> <INDENT> self.base_find_element(loc).clear().send_keys(text_input) <NEW_LINE> <DEDENT> def base_find_elements(self, loc, time_out=10, poll_fre=0.5): <NEW_LINE> <INDENT> elements = WebDriverWait(self.driver, time_out, poll_fre).until(lambda x:x.find_elements(*loc)) <NEW_LINE> return elements
|
定义一个基类
|
625990103cc13d1c6d4663c0
|
class RecoveryServicesClientConfiguration(Configuration): <NEW_LINE> <INDENT> def __init__( self, credential, subscription_id, **kwargs ): <NEW_LINE> <INDENT> if credential is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'credential' must not be None.") <NEW_LINE> <DEDENT> if subscription_id is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'subscription_id' must not be None.") <NEW_LINE> <DEDENT> super(RecoveryServicesClientConfiguration, self).__init__(**kwargs) <NEW_LINE> self.credential = credential <NEW_LINE> self.subscription_id = subscription_id <NEW_LINE> self.api_version = "2021-03-01" <NEW_LINE> self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) <NEW_LINE> kwargs.setdefault('sdk_moniker', 'mgmt-recoveryservices/{}'.format(VERSION)) <NEW_LINE> self._configure(**kwargs) <NEW_LINE> <DEDENT> def _configure( self, **kwargs ): <NEW_LINE> <INDENT> self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) <NEW_LINE> self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) <NEW_LINE> self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) <NEW_LINE> self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) <NEW_LINE> self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) <NEW_LINE> self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) <NEW_LINE> self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) <NEW_LINE> self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) <NEW_LINE> self.authentication_policy = kwargs.get('authentication_policy') <NEW_LINE> if self.credential and not self.authentication_policy: <NEW_LINE> <INDENT> self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
|
Configuration for RecoveryServicesClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: The subscription Id.
:type subscription_id: str
|
62599010627d3e7fe0e07b12
|
@admin.register(Friendship) <NEW_LINE> class FriendshipAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = [ "pk", "user_from", "user_to", "status" ] <NEW_LINE> search_fields = [ "user_from", "user_to", "status" ]
|
Friendship for the admin panel
|
625990106fece00bbaccc62f
|
class PyfacePythonWidget(PythonWidget): <NEW_LINE> <INDENT> def __init__(self, pyface_widget, *args, **kw): <NEW_LINE> <INDENT> self._pyface_widget = pyface_widget <NEW_LINE> super().__init__(*args, **kw) <NEW_LINE> <DEDENT> def keyPressEvent(self, event): <NEW_LINE> <INDENT> kstr = event.text() <NEW_LINE> try: <NEW_LINE> <INDENT> kcode = ord(str(kstr)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> kcode = 0 <NEW_LINE> <DEDENT> mods = event.modifiers() <NEW_LINE> self._pyface_widget.key_pressed = KeyPressedEvent( alt_down=((mods & QtCore.Qt.KeyboardModifier.AltModifier) == QtCore.Qt.KeyboardModifier.AltModifier), control_down=( (mods & QtCore.Qt.KeyboardModifier.ControlModifier) == QtCore.Qt.KeyboardModifier.ControlModifier ), shift_down=( (mods & QtCore.Qt.KeyboardModifier.ShiftModifier) == QtCore.Qt.KeyboardModifier.ShiftModifier ), key_code=kcode, event=event, ) <NEW_LINE> super().keyPressEvent(event)
|
A PythonWidget customized to support the IPythonShell interface.
|
62599010d164cc6175821bf6
|
class RedirectsPanel(Panel): <NEW_LINE> <INDENT> has_content = False <NEW_LINE> nav_title = _("Intercept redirects") <NEW_LINE> def process_request(self, request): <NEW_LINE> <INDENT> response = super().process_request(request) <NEW_LINE> if 300 <= response.status_code < 400: <NEW_LINE> <INDENT> redirect_to = response.get("Location") <NEW_LINE> if redirect_to: <NEW_LINE> <INDENT> status_line = "{} {}".format( response.status_code, response.reason_phrase ) <NEW_LINE> cookies = response.cookies <NEW_LINE> context = {"redirect_to": redirect_to, "status_line": status_line} <NEW_LINE> response = SimpleTemplateResponse( "debug_toolbar/redirect.html", context ) <NEW_LINE> response.cookies = cookies <NEW_LINE> response.render() <NEW_LINE> <DEDENT> <DEDENT> return response
|
Panel that intercepts redirects and displays a page with debug info.
|
62599010507cdc57c63a5a1a
|
class PowerTransformerEnd(TransformerEnd): <NEW_LINE> <INDENT> def __init__(self, g0=0.0, ratedS=0.0, b0=0.0, r0=0.0, connectionKind="Z", b=0.0, r=0.0, ratedU=0.0, x0=0.0, x=0.0, g=0.0, *args, **kw_args): <NEW_LINE> <INDENT> self.g0 = g0 <NEW_LINE> self.ratedS = ratedS <NEW_LINE> self.b0 = b0 <NEW_LINE> self.r0 = r0 <NEW_LINE> self.connectionKind = connectionKind <NEW_LINE> self.b = b <NEW_LINE> self.r = r <NEW_LINE> self.ratedU = ratedU <NEW_LINE> self.x0 = x0 <NEW_LINE> self.x = x <NEW_LINE> self.g = g <NEW_LINE> super(PowerTransformerEnd, self).__init__(*args, **kw_args) <NEW_LINE> <DEDENT> _attrs = ["g0", "ratedS", "b0", "r0", "connectionKind", "b", "r", "ratedU", "x0", "x", "g"] <NEW_LINE> _attr_types = {"g0": float, "ratedS": float, "b0": float, "r0": float, "connectionKind": str, "b": float, "r": float, "ratedU": float, "x0": float, "x": float, "g": float} <NEW_LINE> _defaults = {"g0": 0.0, "ratedS": 0.0, "b0": 0.0, "r0": 0.0, "connectionKind": "Z", "b": 0.0, "r": 0.0, "ratedU": 0.0, "x0": 0.0, "x": 0.0, "g": 0.0} <NEW_LINE> _enums = {"connectionKind": "WindingConnection"} <NEW_LINE> _refs = [] <NEW_LINE> _many_refs = []
|
A PowerTransformerEnd is associated with each Terminal of a PowerTransformer. The impdedance values r, r0, x, and x0 of a PowerTransformerEnd represents a star equivalentas follows 1) for a two Terminal PowerTransformer the high voltage PowerTransformerEnd has non zero values on r, r0, x, and x0 while the low voltage PowerTransformerEnd has zero values for r, r0, x, and x0. 2) for a three Terminal PowerTransformer the three PowerTransformerEnds represents a star equivalent with each leg in the star represented by r, r0, x, and x0 values. 3) for a PowerTransformer with more than three Terminals the PowerTransformerEnd impedance values cannot be used. Instead use the TransformerMeshImpedance or split the transformer into multiple PowerTransformers.
|
62599010462c4b4f79dbc683
|
class BaseSchemaField(BaseField): <NEW_LINE> <INDENT> def __init__(self, id='', default=None, enum=None, title=None, description=None, **kwargs): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.title = title <NEW_LINE> self.description = description <NEW_LINE> self._enum = enum <NEW_LINE> self._default = default <NEW_LINE> super(BaseSchemaField, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def get_enum(self, role=DEFAULT_ROLE): <NEW_LINE> <INDENT> enum = self.resolve_attr('_enum', role).value <NEW_LINE> if callable(enum): <NEW_LINE> <INDENT> enum = enum() <NEW_LINE> <DEDENT> return enum <NEW_LINE> <DEDENT> def get_default(self, role=DEFAULT_ROLE): <NEW_LINE> <INDENT> default = self.resolve_attr('_default', role).value <NEW_LINE> if callable(default): <NEW_LINE> <INDENT> default = default() <NEW_LINE> <DEDENT> return default <NEW_LINE> <DEDENT> def get_definitions_and_schema(self, role=DEFAULT_ROLE, res_scope=ResolutionScope(), ordered=False, ref_documents=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _update_schema_with_common_fields(self, schema, id='', role=DEFAULT_ROLE): <NEW_LINE> <INDENT> if id: <NEW_LINE> <INDENT> schema['id'] = id <NEW_LINE> <DEDENT> title = self.resolve_attr('title', role).value <NEW_LINE> if title is not None: <NEW_LINE> <INDENT> schema['title'] = title <NEW_LINE> <DEDENT> description = self.resolve_attr('description', role).value <NEW_LINE> if description is not None: <NEW_LINE> <INDENT> schema['description'] = description <NEW_LINE> <DEDENT> enum = self.get_enum(role=role) <NEW_LINE> if enum: <NEW_LINE> <INDENT> schema['enum'] = list(enum) <NEW_LINE> <DEDENT> default = self.get_default(role=role) <NEW_LINE> if default is not None: <NEW_LINE> <INDENT> schema['default'] = default <NEW_LINE> <DEDENT> return schema <NEW_LINE> <DEDENT> def iter_fields(self): <NEW_LINE> <INDENT> return iter([]) <NEW_LINE> <DEDENT> def walk(self, through_document_fields=False, visited_documents=frozenset()): <NEW_LINE> <INDENT> yield self <NEW_LINE> for field in self.iter_fields(): <NEW_LINE> <INDENT> for field_ in field.walk(through_document_fields=through_document_fields, visited_documents=visited_documents): <NEW_LINE> <INDENT> yield field_ <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def resolve_and_iter_fields(self, role=DEFAULT_ROLE): <NEW_LINE> <INDENT> return iter([]) <NEW_LINE> <DEDENT> def resolve_and_walk(self, role=DEFAULT_ROLE, through_document_fields=False, visited_documents=frozenset()): <NEW_LINE> <INDENT> yield self <NEW_LINE> for field in self.resolve_and_iter_fields(role=role): <NEW_LINE> <INDENT> field, field_role = field.resolve(role) <NEW_LINE> for field_ in field.resolve_and_walk(role=field_role, through_document_fields=through_document_fields, visited_documents=visited_documents): <NEW_LINE> <INDENT> yield field_
|
A base class for fields that directly map to JSON Schema validator.
:param required:
If the field is required. Defaults to ``False``.
:type required: bool or :class:`.Resolvable`
:param str id:
A string to be used as a value of the `"id" keyword`_ of the resulting schema.
:param default:
The default value for this field. May be a callable.
:type default: any JSON-representable object, a callable or a :class:`.Resolvable`
:param enum:
A list of valid choices. May be a callable.
:type enum: list, tuple, set, callable or :class:`.Resolvable`
:param title:
A short explanation about the purpose of the data described by this field.
:type title: str or :class:`.Resolvable`
:param description:
A detailed explanation about the purpose of the data described by this field.
:type description: str or :class:`.Resolvable`
.. _"id" keyword: https://tools.ietf.org/html/draft-zyp-json-schema-04#section-7.2
|
62599010627d3e7fe0e07b16
|
class ToppingForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = models.Topping <NEW_LINE> fields = { 'name', }
|
Define admin form view for Topping model.
|
6259901021a7993f00c66bfa
|
class MockResponse(object): <NEW_LINE> <INDENT> def __init__(self, json_data, status_code): <NEW_LINE> <INDENT> self.json_data = json_data <NEW_LINE> self.status_code = status_code <NEW_LINE> <DEDENT> def json(self): <NEW_LINE> <INDENT> return self.json_data
|
Mock response object for mocking
|
625990105166f23b2e244050
|
class FixedOffset(_dt.tzinfo, metaclass=utils.MetaClassForClassesWithEnums): <NEW_LINE> <INDENT> def __init__(self, offsetInMinutes=0): <NEW_LINE> <INDENT> _dt.tzinfo.__init__(self) <NEW_LINE> self.__offset = _dt.timedelta(minutes=offsetInMinutes) <NEW_LINE> <DEDENT> def utcoffset(self, unused): <NEW_LINE> <INDENT> return self.__offset <NEW_LINE> <DEDENT> def dst(self, unused): <NEW_LINE> <INDENT> return FixedOffset._dt.timedelta(0) <NEW_LINE> <DEDENT> def getOffsetInMinutes(self): <NEW_LINE> <INDENT> return self.__offset.days * 24 * 60 + self.__offset.seconds / 60 <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return self.getOffsetInMinutes() <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> return cmp(self.getOffsetInMinutes(), other.getOffsetInMinutes())
|
Time zone information.
Represents time zone information to be used with Python standard library
datetime classes.
FixedOffset(offsetInMinutes) creates an object that implements
datetime.tzinfo interface and represents a timezone with the specified
'offsetInMinutes' from UTC.
This class is intended to be used as 'tzinfo' for Python standard library
datetime.datetime and datetime.time classes. These classes are accepted by
the blpapi package to set DATE, TIME or DATETIME elements. For example, the
DATETIME element of a request could be set as:
value = datetime.datetime(1941, 6, 22, 4, 0, tzinfo=FixedOffset(4*60))
request.getElement("last_trade").setValue(value)
The TIME element could be set in a similar way:
value = datetime.time(9, 0, 1, tzinfo=FixedOffset(-5*60))
request.getElement("session_open").setValue(value)
Note that you could use any other implementations of datetime.tzinfo with
BLPAPI-Py, for example the widely used 'pytz' package
(http://pypi.python.org/pypi/pytz/).
For more details see datetime module documentation at
http://docs.python.org/library/datetime.html
|
625990105166f23b2e244054
|
class HelloAPIView(APIView): <NEW_LINE> <INDENT> serializer_class = serializers.HelloSerializer <NEW_LINE> def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ "Uses HTTP methods as function (get, post, patch, put, delete)", "Is similar to a traditional Django View", "Gives you the most control over you application logic", "Is mapped manually to URLs" ] <NEW_LINE> return Response({"message": "Hello!", "an_apiview": an_apiview}) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> serializer = self.serializer_class(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> name = serializer.validated_data.get('name') <NEW_LINE> message = f'Hello { name }' <NEW_LINE> return Response({"message": message}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> <DEDENT> def put(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method':'PUT'}) <NEW_LINE> <DEDENT> def patch(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method': 'PATCH'}) <NEW_LINE> <DEDENT> def delete(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method': 'DELETE'})
|
Test API View
|
625990106fece00bbaccc63b
|
class Link(Component): <NEW_LINE> <INDENT> @_explicitize_args <NEW_LINE> def __init__(self, children=None, block=Component.UNDEFINED, className=Component.UNDEFINED, color=Component.UNDEFINED, component=Component.UNDEFINED, href=Component.UNDEFINED, id=Component.UNDEFINED, style=Component.UNDEFINED, TypographyClasses=Component.UNDEFINED, underline=Component.UNDEFINED, variant=Component.UNDEFINED, **kwargs): <NEW_LINE> <INDENT> self._prop_names = ['children', 'block', 'className', 'color', 'component', 'href', 'id', 'style', 'TypographyClasses', 'underline', 'variant'] <NEW_LINE> self._type = 'Link' <NEW_LINE> self._namespace = 'dashmaterialui' <NEW_LINE> self._valid_wildcard_attributes = [] <NEW_LINE> self.available_properties = ['children', 'block', 'className', 'color', 'component', 'href', 'id', 'style', 'TypographyClasses', 'underline', 'variant'] <NEW_LINE> self.available_wildcard_properties = [] <NEW_LINE> _explicit_args = kwargs.pop('_explicit_args') <NEW_LINE> _locals = locals() <NEW_LINE> _locals.update(kwargs) <NEW_LINE> args = {k: _locals[k] for k in _explicit_args if k != 'children'} <NEW_LINE> for k in []: <NEW_LINE> <INDENT> if k not in args: <NEW_LINE> <INDENT> raise TypeError( 'Required argument `' + k + '` was not specified.') <NEW_LINE> <DEDENT> <DEDENT> super(Link, self).__init__(children=children, **args)
|
A Link component.
ExampleComponent is an example component.
It takes a property, `label`, and
displays it.
It renders an input with the property `value`
which is editable by the user.
Keyword arguments:
- children (a list of or a singular dash component, string or number; optional): The content of the link.
- block (boolean; optional): Controls whether the link is inline or not. When block is true the link is not inline when block is false it is.
- className (string; optional): Override or extend the styles applied to the component. See CSS API below for more details.
- color (a value equal to: 'error', 'inherit', 'primary', 'secondary', 'textPrimary', 'textSecondary'; optional): The color of the link.
- component (optional): The component used for the root node. Either a string to use a DOM element or a component.
- href (string; optional): The url to refer to
- id (string; optional): The components id
- style (dict; optional): Add style object
- TypographyClasses (dict; optional): classes property applied to the Typography element.
- underline (a value equal to: 'none', 'hover', 'always'; optional): Controls when the link should have an underline.
- variant (string; optional): Applies the theme typography styles.
|
625990105166f23b2e244056
|
class Bool(Type): <NEW_LINE> <INDENT> PACKER = struct.Struct('<c') <NEW_LINE> TRUE = chr(1) <NEW_LINE> FALSE = chr(0) <NEW_LINE> def check(self, value): <NEW_LINE> <INDENT> if not isinstance(value, bool): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> <DEDENT> def serialize(self, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> yield self.PACKER.pack(self.TRUE) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield self.PACKER.pack(self.FALSE) <NEW_LINE> <DEDENT> <DEDENT> def receive(self): <NEW_LINE> <INDENT> value_receiver = super(Bool, self).receive() <NEW_LINE> request = value_receiver.next() <NEW_LINE> while isinstance(request, Request): <NEW_LINE> <INDENT> value = yield request <NEW_LINE> request = value_receiver.send(value) <NEW_LINE> <DEDENT> if not isinstance(request, Result): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> value = request.value <NEW_LINE> if value == self.TRUE: <NEW_LINE> <INDENT> yield Result(True) <NEW_LINE> <DEDENT> elif value == self.FALSE: <NEW_LINE> <INDENT> yield Result(False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Unexpected bool value "0x%02x"' % ord(value))
|
Bool type
|
62599010bf627c535bcb2139
|
class UserData(DataDict[str, t.Any]): <NEW_LINE> <INDENT> id: int <NEW_LINE> username: str <NEW_LINE> discriminator: str <NEW_LINE> social: SocialData <NEW_LINE> color: str <NEW_LINE> supporter: bool <NEW_LINE> certified_dev: bool <NEW_LINE> mod: bool <NEW_LINE> web_mod: bool <NEW_LINE> admin: bool <NEW_LINE> def __init__(self, **kwargs: t.Any): <NEW_LINE> <INDENT> super().__init__(**parse_user_dict(kwargs))
|
Model that contains information about a top.gg user. The data this model contains can be found `here
<https://docs.top.gg/api/user/#structure>`__.
|
6259901056b00c62f0fb3547
|
class emulator(device): <NEW_LINE> <INDENT> def __init__(self, width, height, rotate, mode, transform, scale): <NEW_LINE> <INDENT> super(emulator, self).__init__(serial_interface=noop()) <NEW_LINE> try: <NEW_LINE> <INDENT> import pygame <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise RuntimeError("Emulator requires pygame to be installed") <NEW_LINE> <DEDENT> self._pygame = pygame <NEW_LINE> self.capabilities(width, height, rotate, mode) <NEW_LINE> self.scale = 1 if transform == "none" else scale <NEW_LINE> self._transform = getattr(transformer(pygame, width, height, scale), "none" if scale == 1 else transform) <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def to_surface(self, image): <NEW_LINE> <INDENT> im = image.convert("RGB") <NEW_LINE> mode = im.mode <NEW_LINE> size = im.size <NEW_LINE> data = im.tobytes() <NEW_LINE> del im <NEW_LINE> surface = self._pygame.image.fromstring(data, size, mode) <NEW_LINE> return self._transform(surface)
|
Base class for emulated display driver classes
|
62599010d18da76e235b7792
|
class BigWig(Binary): <NEW_LINE> <INDENT> edam_format = "format_3006" <NEW_LINE> edam_data = "data_3002" <NEW_LINE> track_type = "LineTrack" <NEW_LINE> data_sources = { "data_standalone": "bigwig" } <NEW_LINE> def __init__( self, **kwd ): <NEW_LINE> <INDENT> Binary.__init__( self, **kwd ) <NEW_LINE> self._magic = 0x888FFC26 <NEW_LINE> self._name = "BigWig" <NEW_LINE> <DEDENT> def _unpack( self, pattern, handle ): <NEW_LINE> <INDENT> return struct.unpack( pattern, handle.read( struct.calcsize( pattern ) ) ) <NEW_LINE> <DEDENT> def sniff( self, filename ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> magic = self._unpack( "I", open( filename ) ) <NEW_LINE> return magic[0] == self._magic <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def set_peek( self, dataset, is_multi_byte=False ): <NEW_LINE> <INDENT> if not dataset.dataset.purged: <NEW_LINE> <INDENT> dataset.peek = "Binary UCSC %s file" % self._name <NEW_LINE> dataset.blurb = nice_size( dataset.get_size() ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dataset.peek = 'file does not exist' <NEW_LINE> dataset.blurb = 'file purged from disk' <NEW_LINE> <DEDENT> <DEDENT> def display_peek( self, dataset ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return dataset.peek <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return "Binary UCSC %s file (%s)" % ( self._name, nice_size( dataset.get_size() ) )
|
Accessing binary BigWig files from UCSC.
The supplemental info in the paper has the binary details:
http://bioinformatics.oxfordjournals.org/cgi/content/abstract/btq351v1
|
625990105166f23b2e24405a
|
class DistributionManager: <NEW_LINE> <INDENT> def __init__(self, session): <NEW_LINE> <INDENT> self.session = session <NEW_LINE> self.client = self.session.client('cloudfront') <NEW_LINE> <DEDENT> def find_matching_dist(self, domain_name): <NEW_LINE> <INDENT> paginator = self.client.get_paginator('list_distributions') <NEW_LINE> dist = None <NEW_LINE> for page in paginator.paginate(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for dist in page['DistributionList']['Items']: <NEW_LINE> <INDENT> for alias in dist['Aliases']['Items']: <NEW_LINE> <INDENT> if alias == domain_name: <NEW_LINE> <INDENT> return dist <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> print("Distribution does not contain Aliases: %s" % (dist['DomainName'])) <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def create_dist(self, domain_name, cert): <NEW_LINE> <INDENT> origin_id = 'S3-' + domain_name <NEW_LINE> result = self.client.create_distribution( DistributionConfig={ 'CallerReference': str(uuid.uuid4()), 'Aliases': { 'Quantity': 1, 'Items': [domain_name] }, 'DefaultRootObject': 'index.html', 'Comment': 'Created by webotron', 'Enabled': True, 'Origins': { 'Quantity': 1, 'Items': [{ 'Id': origin_id, 'DomainName': '{}.s3.amazonaws.com'.format(domain_name), 'S3OriginConfig': { 'OriginAccessIdentity': '' } }] }, 'DefaultCacheBehavior': { 'TargetOriginId': origin_id, 'ViewerProtocolPolicy': 'redirect-to-https', 'TrustedSigners': { 'Quantity': 0, 'Enabled': False }, 'ForwardedValues': { 'Cookies': {'Forward': 'all'}, 'Headers': {'Quantity': 0}, 'QueryString': False, 'QueryStringCacheKeys': {'Quantity': 0} }, 'DefaultTTL': 86400, 'MinTTL': 3600 }, 'ViewerCertificate': { 'ACMCertificateArn': cert['CertificateArn'], 'SSLSupportMethod': 'sni-only', 'MinimumProtocolVersion': 'TLSv1.1_2016' } } ) <NEW_LINE> return result['Distribution'] <NEW_LINE> <DEDENT> def await_deploy(self, dist): <NEW_LINE> <INDENT> waiter = self.client.get_waiter('distribution_deployed') <NEW_LINE> waiter.wait(Id=dist['Id'], WaiterConfig={ 'Delay': 30, 'MaxAttempts': 50 })
|
Class for CDN Distribution.
|
625990103cc13d1c6d4663d4
|
class RateChanges(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> currencies = Currency.objects.exclude(code= u'EUR') <NEW_LINE> legend = ["Year"]; <NEW_LINE> rate_dict = collections.OrderedDict(); <NEW_LINE> for currency in currencies: <NEW_LINE> <INDENT> rates = currency.rates.order_by('date') <NEW_LINE> start_period_value = 0 <NEW_LINE> code = currency.code <NEW_LINE> legend.append(code) <NEW_LINE> for i, rate in enumerate(rates): <NEW_LINE> <INDENT> if str(rate.date) not in rate_dict: <NEW_LINE> <INDENT> rate_dict[str(rate.date)] = [str(rate.date)] <NEW_LINE> <DEDENT> if i == 0: <NEW_LINE> <INDENT> start_period_value = rate.value <NEW_LINE> <DEDENT> rate_dict[str(rate.date)].append(rate.value/start_period_value) <NEW_LINE> <DEDENT> <DEDENT> rate_list = list(rate_dict.values()) <NEW_LINE> rate_list.insert(0, legend) <NEW_LINE> return Response(rate_list)
|
Return dynamic of changes curencies
|
6259901015fb5d323ce7f9ca
|
class HanderUpdateOSServer(tornado.web.RequestHandler): <NEW_LINE> <INDENT> _thread_pool = ThreadPoolExecutor(3) <NEW_LINE> @run_on_executor(executor='_thread_pool') <NEW_LINE> def handler_update_task(self): <NEW_LINE> <INDENT> aliyun_ecs_update() <NEW_LINE> time.sleep(2) <NEW_LINE> aws_ec2_update() <NEW_LINE> time.sleep(2) <NEW_LINE> qcloud_cvm_update() <NEW_LINE> time.sleep(2) <NEW_LINE> huawei_ecs_update() <NEW_LINE> time.sleep(2) <NEW_LINE> ucloud_uhost_update() <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def get(self, *args, **kwargs): <NEW_LINE> <INDENT> yield self.handler_update_task() <NEW_LINE> return self.write(dict(code=0, msg='服务器信息拉取完成'))
|
前端手动触发从云厂商更新资产,使用异步方法
|
625990100a366e3fb87dd680
|
class OneTimeReportFactory(ReportFactory): <NEW_LINE> <INDENT> task = factory.SubFactory(OneTimeTaskFactory) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = OneTimeReport
|
Factory for ``OneTimeReport`` model
|
625990116fece00bbaccc643
|
class Users(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> username = db.Column(String(30), primary_key=True) <NEW_LINE> role = db.Column(String(30), nullable=False)
|
DB model representing a category associated with a building
|
62599011925a0f43d25e8cce
|
class FormTemplate(Base): <NEW_LINE> <INDENT> __tablename__ = "form_template" <NEW_LINE> id = id_column(__tablename__) <NEW_LINE> system_template_id = Column(Integer, unique=True, default=None) <NEW_LINE> system_template_name = Column(UnicodeText(32)) <NEW_LINE> @property <NEW_LINE> def system(self): <NEW_LINE> <INDENT> return True if self.system_template_id else False <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "FormTemplate (id = {0})".format(self.id) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.__repr__() <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> colors = {} <NEW_LINE> fonts = {} <NEW_LINE> for c in self.colors: <NEW_LINE> <INDENT> colors[c.place] = c.hexcode <NEW_LINE> <DEDENT> for f in self.fonts: <NEW_LINE> <INDENT> fonts[f.place] = dict(name=f.name, size=f.size, bold=f.bold, italic=f.italic) <NEW_LINE> <DEDENT> return {'formtemplate_id': self.id, 'system_template_id': self.system_template_id, 'system_template_name': self.system_template_name, 'colors': colors, 'fonts': fonts} <NEW_LINE> <DEDENT> def css_template_dicts(self): <NEW_LINE> <INDENT> fonts = dict() <NEW_LINE> for ftf in self.fonts: <NEW_LINE> <INDENT> fonts[ftf.place] = dict() <NEW_LINE> for attr in ('name', 'size', 'bold', 'italic'): <NEW_LINE> <INDENT> fonts[ftf.place][attr] = ftf.__getattribute__(attr) <NEW_LINE> <DEDENT> <DEDENT> colors = dict() <NEW_LINE> for ftc in self.colors: <NEW_LINE> <INDENT> colors[ftc.place] = ftc.hexcode <NEW_LINE> <DEDENT> return fonts, colors
|
Represents a visual template of a form.
|
6259901156b00c62f0fb354d
|
class AdminLoginForm(FlaskForm): <NEW_LINE> <INDENT> account = StringField( label="账号", validators=[DataRequired("请输入账号")], description="账号", render_kw={ "class": "form-control", "placeholder": "请输入账号", } ) <NEW_LINE> pwd = PasswordField( label="密码", validators=[DataRequired("请输入密码")], description="密码", render_kw={ "class": "form-control", "placeholder": "请输入密码", } ) <NEW_LINE> submit = SubmitField( "登录", render_kw={ "class": "btn btn-primary btn-block btn-flat", } ) <NEW_LINE> def validate_account(self, field): <NEW_LINE> <INDENT> account = field.data <NEW_LINE> admin_count = Admin.query.filter_by(name=account).count() <NEW_LINE> if admin_count == 0: <NEW_LINE> <INDENT> raise ValidationError("此账号不存在!")
|
管理员登录表单
|
62599011627d3e7fe0e07b28
|
class UploadCommand(Command): <NEW_LINE> <INDENT> description = 'Build and publish the package.' <NEW_LINE> user_options = [] <NEW_LINE> @staticmethod <NEW_LINE> def status(s): <NEW_LINE> <INDENT> print('\033[1m{0}\033[0m'.format(s)) <NEW_LINE> <DEDENT> def initialize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def finalize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.status('Removing previous builds…') <NEW_LINE> rmtree(os.path.join(here, 'dist')) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.status('Building Source and Wheel (universal) distribution…') <NEW_LINE> os.system('{0} setup.py sdist bdist_wheel --universal'.format( sys.executable)) <NEW_LINE> self.status('Uploading the package to PyPI via Twine…') <NEW_LINE> returned_error = os.system('twine upload dist/* ') <NEW_LINE> if returned_error: <NEW_LINE> <INDENT> raise ValueError('Pushing to PyPi failed.') <NEW_LINE> <DEDENT> self.status('Pushing git tags…') <NEW_LINE> current_commit = str( subprocess.check_output(['git', 'rev-parse', 'HEAD']), 'utf-8').strip() <NEW_LINE> g = Github(os.getenv('GITHUB_PAT')) <NEW_LINE> repo = g.get_repo(os.path.join(repo_owner, repo_name)) <NEW_LINE> repo.create_git_tag_and_release( tag=about['__version__'], tag_message='', release_name=about['__version__'], release_message='', object=current_commit, type='commit' ) <NEW_LINE> sys.exit()
|
Support setup.py upload.
|
625990115166f23b2e244060
|
class FBFCurveEditor (FBVisualComponent): <NEW_LINE> <INDENT> def FBFCurveEditor(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def AddAnimationNode(self,pNode): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Clear(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def RemoveAnimationNode(self,pNode): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> pass
|
FCurve editor.
|
62599011925a0f43d25e8cd0
|
class ManagedInstancePairInfo(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'primary_managed_instance_id': {'key': 'primaryManagedInstanceId', 'type': 'str'}, 'partner_managed_instance_id': {'key': 'partnerManagedInstanceId', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, primary_managed_instance_id: Optional[str] = None, partner_managed_instance_id: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(ManagedInstancePairInfo, self).__init__(**kwargs) <NEW_LINE> self.primary_managed_instance_id = primary_managed_instance_id <NEW_LINE> self.partner_managed_instance_id = partner_managed_instance_id
|
Pairs of Managed Instances in the failover group.
:ivar primary_managed_instance_id: Id of Primary Managed Instance in pair.
:vartype primary_managed_instance_id: str
:ivar partner_managed_instance_id: Id of Partner Managed Instance in pair.
:vartype partner_managed_instance_id: str
|
6259901115fb5d323ce7f9ce
|
class Graph: <NEW_LINE> <INDENT> def __init__(self, commodity_name, nodes: dict, arcs: dict): <NEW_LINE> <INDENT> self.commodity_name = commodity_name <NEW_LINE> self.arcs_cost_cap = arcs <NEW_LINE> self.nodes_demands = nodes <NEW_LINE> <DEDENT> def get_trip_arcs(self): <NEW_LINE> <INDENT> trip_arcs = [] <NEW_LINE> for arc in self.arcs_cost_cap.items(): <NEW_LINE> <INDENT> if arc[0].arc_type == ArcType.TRIP: <NEW_LINE> <INDENT> trip_arcs.append(arc) <NEW_LINE> <DEDENT> <DEDENT> return trip_arcs
|
arcs: dict Arc -> (cost, capacity)
|
625990118c3a8732951f71f3
|
class SponsorInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.SponsorOpenId = None <NEW_LINE> self.SponsorDeviceNumber = None <NEW_LINE> self.SponsorPhone = None <NEW_LINE> self.SponsorIp = None <NEW_LINE> self.CampaignUrl = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.SponsorOpenId = params.get("SponsorOpenId") <NEW_LINE> self.SponsorDeviceNumber = params.get("SponsorDeviceNumber") <NEW_LINE> self.SponsorPhone = params.get("SponsorPhone") <NEW_LINE> self.SponsorIp = params.get("SponsorIp") <NEW_LINE> self.CampaignUrl = params.get("CampaignUrl") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
|
网赚防刷相关参数
|
625990110a366e3fb87dd684
|
class Extension(object): <NEW_LINE> <INDENT> def __init__(self, name, supported, requires, comment=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.supported = set(supported or ()) <NEW_LINE> self.requires = requires <NEW_LINE> self.comment = comment <NEW_LINE> <DEDENT> def get_apis(self): <NEW_LINE> <INDENT> out = set() <NEW_LINE> out.update(x.api for x in self.requires if x.api) <NEW_LINE> return out <NEW_LINE> <DEDENT> def get_profiles(self): <NEW_LINE> <INDENT> return set(x.profile for x in self.requires if x.profile) <NEW_LINE> <DEDENT> def get_supports(self): <NEW_LINE> <INDENT> return set(self.supported) <NEW_LINE> <DEDENT> def get_requires(self, api=None, profile=None): <NEW_LINE> <INDENT> out = [] <NEW_LINE> for req in self.requires: <NEW_LINE> <INDENT> if (req.api and not api) or (req.api and api and req.api != api): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if ((req.profile and not profile) or (req.profile and profile and req.profile != profile)): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> out.append(req) <NEW_LINE> <DEDENT> return out <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return _repr(self, (self.name, self.supported, self.requires), (self.comment,))
|
Extension
|
625990118c3a8732951f71f5
|
class RteProcessor(DataProcessor): <NEW_LINE> <INDENT> def get_example_from_tensor_dict(self, tensor_dict): <NEW_LINE> <INDENT> return InputExample(tensor_dict['idx'].numpy(), tensor_dict['sentence1'].numpy().decode('utf-8'), tensor_dict['sentence2'].numpy().decode('utf-8'), str(tensor_dict['label'].numpy())) <NEW_LINE> <DEDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") <NEW_LINE> <DEDENT> def get_test_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> return ["entailment", "not_entailment"] <NEW_LINE> <DEDENT> def _create_examples(self, lines, set_type): <NEW_LINE> <INDENT> examples = [] <NEW_LINE> for (i, line) in enumerate(lines): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> guid = "%s-%s" % (set_type, line[0]) <NEW_LINE> text_a = line[1] <NEW_LINE> text_b = line[2] <NEW_LINE> if set_type != 'test': <NEW_LINE> <INDENT> label = line[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> label = self.get_labels()[0] <NEW_LINE> <DEDENT> examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) <NEW_LINE> <DEDENT> return examples
|
Processor for the RTE data set (GLUE version).
|
62599011925a0f43d25e8cd4
|
class Defaults: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def PolicyDocument(Version="2012-10-17", **kwargs): <NEW_LINE> <INDENT> return raw.PolicyDocument(**kwargs)
|
Standard implementation of all raw classes with sensible defaults
|
62599011bf627c535bcb2145
|
class EMNA(object): <NEW_LINE> <INDENT> def __init__(self, centroid, sigma, mu, lambda_): <NEW_LINE> <INDENT> self.dim = len(centroid) <NEW_LINE> self.centroid = numpy.array(centroid) <NEW_LINE> self.sigma = numpy.array(sigma) <NEW_LINE> self.lambda_ = lambda_ <NEW_LINE> self.mu = mu <NEW_LINE> <DEDENT> def generate(self, ind_init): <NEW_LINE> <INDENT> arz = self.centroid + self.sigma * numpy.random.randn(self.lambda_, self.dim) <NEW_LINE> return list(map(ind_init, arz)) <NEW_LINE> <DEDENT> def update(self, population): <NEW_LINE> <INDENT> sorted_pop = sorted(population, key=attrgetter("fitness"), reverse=True) <NEW_LINE> z = sorted_pop[:self.mu] - self.centroid <NEW_LINE> avg = numpy.mean(z, axis=0) <NEW_LINE> self.sigma = numpy.sqrt(numpy.sum(numpy.sum((z - avg)**2, axis=1)) / (self.mu*self.dim)) <NEW_LINE> self.centroid = self.centroid + avg
|
Estimation of Multivariate Normal Algorithm (EMNA) as described
by Algorithm 1 in:
Fabien Teytaud and Olivier Teytaud. 2009.
Why one must use reweighting in estimation of distribution algorithms.
In Proceedings of the 11th Annual conference on Genetic and
evolutionary computation (GECCO '09). ACM, New York, NY, USA, 453-460.
|
62599011462c4b4f79dbc69d
|
class ApplicationGatewayBackendHealthOnDemand(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'backend_address_pool': {'key': 'backendAddressPool', 'type': 'ApplicationGatewayBackendAddressPool'}, 'backend_health_http_settings': {'key': 'backendHealthHttpSettings', 'type': 'ApplicationGatewayBackendHealthHttpSettings'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayBackendHealthOnDemand, self).__init__(**kwargs) <NEW_LINE> self.backend_address_pool = kwargs.get('backend_address_pool', None) <NEW_LINE> self.backend_health_http_settings = kwargs.get('backend_health_http_settings', None)
|
Result of on demand test probe.
:param backend_address_pool: Reference of an ApplicationGatewayBackendAddressPool resource.
:type backend_address_pool:
~azure.mgmt.network.v2019_02_01.models.ApplicationGatewayBackendAddressPool
:param backend_health_http_settings: Application gateway BackendHealthHttp settings.
:type backend_health_http_settings:
~azure.mgmt.network.v2019_02_01.models.ApplicationGatewayBackendHealthHttpSettings
|
625990118c3a8732951f71f7
|
class TestCCT_to_xy_CIE_D(unittest.TestCase): <NEW_LINE> <INDENT> def test_CCT_to_xy_CIE_D(self): <NEW_LINE> <INDENT> np.testing.assert_almost_equal( CCT_to_xy_CIE_D(4000), (0.38234362499999996, 0.3837662610155782), decimal=7) <NEW_LINE> np.testing.assert_almost_equal( CCT_to_xy_CIE_D(7000), (0.3053574314868805, 0.3216463454745523), decimal=7) <NEW_LINE> np.testing.assert_almost_equal( CCT_to_xy_CIE_D(25000), (0.2498536704, 0.25479946421094446), decimal=7)
|
Defines :func:`colour.temperature.cct.CCT_to_xy_CIE_D` definition
unit tests methods.
|
6259901156b00c62f0fb3553
|
class MatchedRoute(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'properties': {'key': 'properties', 'type': 'RouteProperties'}, } <NEW_LINE> def __init__( self, *, properties: Optional["RouteProperties"] = None, **kwargs ): <NEW_LINE> <INDENT> super(MatchedRoute, self).__init__(**kwargs) <NEW_LINE> self.properties = properties
|
Routes that matched.
:ivar properties: Properties of routes that matched.
:vartype properties: ~azure.mgmt.iothub.v2019_03_22.models.RouteProperties
|
6259901121a7993f00c66c10
|
class TestSetup(unittest.TestCase): <NEW_LINE> <INDENT> layer = RJ_SITE_INTEGRATION_TESTING <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.portal = self.layer['portal'] <NEW_LINE> self.installer = api.portal.get_tool('portal_quickinstaller') <NEW_LINE> <DEDENT> def test_product_installed(self): <NEW_LINE> <INDENT> self.assertTrue(self.installer.isProductInstalled('rj.site')) <NEW_LINE> <DEDENT> def test_browserlayer(self): <NEW_LINE> <INDENT> from rj.site.interfaces import IRjSiteLayer <NEW_LINE> from plone.browserlayer import utils <NEW_LINE> self.assertIn(IRjSiteLayer, utils.registered_layers())
|
Test that rj.site is properly installed.
|
62599011925a0f43d25e8cd6
|
class DigitalOutput(MDigitalOutput): <NEW_LINE> <INDENT> def __init__(self, pin): <NEW_LINE> <INDENT> MDigitalOutput.__init__(self, pin) <NEW_LINE> output(pin) <NEW_LINE> <DEDENT> def set_low(self): <NEW_LINE> <INDENT> digitalWrite(self.pin, 0) <NEW_LINE> <DEDENT> def set_high(self): <NEW_LINE> <INDENT> digitalWrite(self.pin, 1)
|
Digital output pin.
|
625990118c3a8732951f71f9
|
class ZoneExists(DMSError): <NEW_LINE> <INDENT> def __init__(self, domain): <NEW_LINE> <INDENT> message = "Zone '%s' already exists, can't create it." % domain <NEW_LINE> super().__init__(message) <NEW_LINE> self.data['name'] = domain <NEW_LINE> self.jsonrpc_error = -31
|
For a DMI, can't create the requested zone as it already exists.
* JSONRPC Error: -31
* JSONRPC data keys:
* 'name' - domain name
|
62599011462c4b4f79dbc6a1
|
@dataclass <NEW_LINE> class E63BeginningofExistence(E5Event): <NEW_LINE> <INDENT> TYPE_URI = "http://erlangen-crm.org/current/E63_Beginning_of_Existence"
|
Scope note:
This class comprises events that bring into existence any instance of E77 Persistent Item.
It may be used for temporal reasoning about things (intellectual products, physical items, groups of people, living beings) beginning to exist; it serves as a hook for determination of a “terminus post quem” or “terminus ante quem”.
Examples:
- the birth of my child
- the birth of Snoopy, my dog
- the calving of the iceberg that sank the Titanic
- the construction of the Eiffel Tower (Tissandier, 1889)
In First Order Logic:
E63(x) ⊃ E5(x)
|
6259901156b00c62f0fb3557
|
class SV(object): <NEW_LINE> <INDENT> NamedTuple = collections.namedtuple('SV', ['prn', 'elev', 'azi', 'snr']) <NEW_LINE> def __init__(self, sv_data_tuple): <NEW_LINE> <INDENT> self.prn = sv_data_tuple[0] <NEW_LINE> self.elev = sv_data_tuple[1] <NEW_LINE> self.azi = sv_data_tuple[2] <NEW_LINE> self.snr = sv_data_tuple[3] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "SV PRN " + self.prn + ", elevation " + self.elev + ", azimuth " + self.azi + ", SNR " + self.snr <NEW_LINE> <DEDENT> def get_tuple(self): <NEW_LINE> <INDENT> return self.NamedTuple(self.prn, self.elev, self.azi, self.snr)
|
classdocs
|
62599011d164cc6175821c16
|
class DoExcel: <NEW_LINE> <INDENT> def __init__(self, file_name, sheet_name): <NEW_LINE> <INDENT> self.file_name = file_name <NEW_LINE> self.sheet_name = sheet_name <NEW_LINE> try: <NEW_LINE> <INDENT> self.wb = load_workbook(self.file_name) <NEW_LINE> self.sheet = self.wb[self.sheet_name] <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.info("读取excel报错:",e) <NEW_LINE> raise e <NEW_LINE> <DEDENT> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> cases = [] <NEW_LINE> for i in range(2, self.sheet.max_row + 1): <NEW_LINE> <INDENT> case = Cases() <NEW_LINE> case.case_id = self.sheet.cell(i, 1).value <NEW_LINE> case.module = self.sheet.cell(i, 2).value <NEW_LINE> case.title = self.sheet.cell(i, 3).value <NEW_LINE> case.method = self.sheet.cell(i, 4).value <NEW_LINE> case.url = self.sheet.cell(i, 5).value <NEW_LINE> case.data = self.sheet.cell(i, 6).value <NEW_LINE> case.expected = self.sheet.cell(i, 7).value <NEW_LINE> if type(case.expected) == int: <NEW_LINE> <INDENT> case.expected = str(case.expected) <NEW_LINE> <DEDENT> cases.append(case) <NEW_LINE> <DEDENT> return cases <NEW_LINE> <DEDENT> def write_back(self, row, actual_result, test_result): <NEW_LINE> <INDENT> self.sheet.cell(row, 8).value = actual_result <NEW_LINE> self.sheet.cell(row, 9).value = test_result <NEW_LINE> self.wb.save(self.file_name)
|
来获取excel对应表单数据的类
|
625990113cc13d1c6d4663e2
|
class Dpaste(BasePaste): <NEW_LINE> <INDENT> TITLE = 'Dpaste' <NEW_LINE> URL = 'http://dpaste.com/' <NEW_LINE> SYNTAX_DICT = { 'xml': 'XML', 'python': 'Python', 'rhtml': 'Ruby HTML (ERB)', 'pyconsol': 'Python Interactive/Traceback', 'js': 'JavaScript', 'haskell': 'Haskell', 'bash': 'Bash script', 'Sql': 'SQL', 'Apache': 'Apache Config', 'diff': 'Diff', 'ruby': 'Ruby', 'djtemplate': 'Django Template/HTML', 'css': 'CSS' } <NEW_LINE> def process_data(self): <NEW_LINE> <INDENT> self.data['hold'] = 'on' if self.data['hold'] else '' <NEW_LINE> self.data['language']= self.data['syntax'] <NEW_LINE> del self.data['syntax'] <NEW_LINE> return self.data <NEW_LINE> <DEDENT> def process_response(self): <NEW_LINE> <INDENT> return self.response.url
|
The django based `dpaste.com` paste service
|
6259901115fb5d323ce7f9d8
|
class ListApplicationsInputSet(InputSet): <NEW_LINE> <INDENT> def set_AccountSID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AccountSID', value) <NEW_LINE> <DEDENT> def set_AuthToken(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AuthToken', value) <NEW_LINE> <DEDENT> def set_FriendlyName(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'FriendlyName', value) <NEW_LINE> <DEDENT> def set_PageSize(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'PageSize', value) <NEW_LINE> <DEDENT> def set_Page(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Page', value) <NEW_LINE> <DEDENT> def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ResponseFormat', value)
|
An InputSet with methods appropriate for specifying the inputs to the ListApplications
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
|
62599011462c4b4f79dbc6a3
|
@registry.register_problem <NEW_LINE> class QuoraQuestionPairs(text_problems.TextConcat2ClassProblem): <NEW_LINE> <INDENT> _QQP_URL = ("https://firebasestorage.googleapis.com/v0/b/" "mtl-sentence-representations.appspot.com/o/" "data%2FQQP.zip?alt=media&token=700c6acf-160d-" "4d89-81d1-de4191d02cb5") <NEW_LINE> @property <NEW_LINE> def is_generate_per_split(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def dataset_splits(self): <NEW_LINE> <INDENT> return [{ "split": problem.DatasetSplit.TRAIN, "shards": 100, }, { "split": problem.DatasetSplit.EVAL, "shards": 1, }] <NEW_LINE> <DEDENT> @property <NEW_LINE> def approx_vocab_size(self): <NEW_LINE> <INDENT> return 2**15 <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_classes(self): <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> def class_labels(self, data_dir): <NEW_LINE> <INDENT> del data_dir <NEW_LINE> return ["not_duplicate", "duplicate"] <NEW_LINE> <DEDENT> def _maybe_download_corpora(self, tmp_dir): <NEW_LINE> <INDENT> qqp_filename = "QQP.zip" <NEW_LINE> qqp_finalpath = os.path.join(tmp_dir, "QQP") <NEW_LINE> if not tf.gfile.Exists(qqp_finalpath): <NEW_LINE> <INDENT> zip_filepath = generator_utils.maybe_download( tmp_dir, qqp_filename, self._QQP_URL) <NEW_LINE> zip_ref = zipfile.ZipFile(zip_filepath, "r") <NEW_LINE> zip_ref.extractall(tmp_dir) <NEW_LINE> zip_ref.close() <NEW_LINE> <DEDENT> return qqp_finalpath <NEW_LINE> <DEDENT> def example_generator(self, filename): <NEW_LINE> <INDENT> skipped = 0 <NEW_LINE> for idx, line in enumerate(tf.gfile.Open(filename, "rb")): <NEW_LINE> <INDENT> if idx == 0: continue <NEW_LINE> if six.PY2: <NEW_LINE> <INDENT> line = unicode(line.strip(), "utf-8") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> line = line.strip().decode("utf-8") <NEW_LINE> <DEDENT> split_line = line.split("\t") <NEW_LINE> if len(split_line) < 6: <NEW_LINE> <INDENT> skipped += 1 <NEW_LINE> tf.logging.info("Skipping %d" % skipped) <NEW_LINE> continue <NEW_LINE> <DEDENT> s1, s2, l = split_line[3:] <NEW_LINE> inputs = [[s1, s2], [s2, s1]] <NEW_LINE> for inp in inputs: <NEW_LINE> <INDENT> yield { "inputs": inp, "label": int(l) } <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def generate_samples(self, data_dir, tmp_dir, dataset_split): <NEW_LINE> <INDENT> qqp_dir = self._maybe_download_corpora(tmp_dir) <NEW_LINE> if dataset_split == problem.DatasetSplit.TRAIN: <NEW_LINE> <INDENT> filesplit = "train.tsv" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filesplit = "dev.tsv" <NEW_LINE> <DEDENT> filename = os.path.join(qqp_dir, filesplit) <NEW_LINE> for example in self.example_generator(filename): <NEW_LINE> <INDENT> yield example
|
Quora duplicate question pairs binary classification problems.
|
62599011d164cc6175821c18
|
class Example: <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> allowed_kwargs = {"clipnorm", "clipvalue"} <NEW_LINE> for k in kwargs: <NEW_LINE> <INDENT> if k not in allowed_kwargs: <NEW_LINE> <INDENT> raise TypeError( "Unexpected keyword argument passed to optimizer: " + str(k) ) <NEW_LINE> <DEDENT> <DEDENT> self.__dict__.update(kwargs)
|
Example of class with a restriction on allowed arguments
source: https://github.com/keras-team/keras/blob/master/keras/optimizers.py
|
625990110a366e3fb87dd68f
|
class ProposalSubmission(_ProposalHappening, Action, WorldAssembly): <NEW_LINE> <INDENT> def __init__(self, text, params): <NEW_LINE> <INDENT> match = re.match( '@@(.+?)@@ submitted a proposal to the ' '(General Assembly|Security Council) (.+?) Board entitled "(.+?)"', text ) <NEW_LINE> if not match: <NEW_LINE> <INDENT> raise _ParseError <NEW_LINE> <DEDENT> self.agent = aionationstates.Nation(match.group(1)) <NEW_LINE> self.proposal_council = match.group(2) <NEW_LINE> self.proposal_category = match.group(3) <NEW_LINE> self.proposal_name = match.group(4) <NEW_LINE> super().__init__(text, params)
|
A nation submitting a World Assembly proposal.
|
625990113cc13d1c6d4663e4
|
class ProjectsLocationsService(base_api.BaseApiService): <NEW_LINE> <INDENT> _NAME = u'projects_locations' <NEW_LINE> def __init__(self, client): <NEW_LINE> <INDENT> super(RunV1alpha1.ProjectsLocationsService, self).__init__(client) <NEW_LINE> self._upload_configs = { } <NEW_LINE> <DEDENT> def List(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('List') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) <NEW_LINE> <DEDENT> List.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/locations', http_method=u'GET', method_id=u'run.projects.locations.list', ordered_params=[u'name'], path_params=[u'name'], query_params=[u'filter', u'pageSize', u'pageToken'], relative_path=u'v1alpha1/{+name}/locations', request_field='', request_type_name=u'RunProjectsLocationsListRequest', response_type_name=u'ListLocationsResponse', supports_download=False, )
|
Service class for the projects_locations resource.
|
6259901156b00c62f0fb355b
|
class CalendarEvent(models.Model): <NEW_LINE> <INDENT> CSS_CLASS_CHOICES = ( ('', _('Ezer ez')), ('event-warning', _('Partida')), ('event-info', _('Jokoa')), ('event-success', _('Hitzaldia')), ('event-inverse', _('Lehiaketa')), ('event-special', _('Txapelketa')), ('event-important', _('Berezia')), ) <NEW_LINE> title = models.CharField(max_length=255, verbose_name=_('Title')) <NEW_LINE> desc = models.TextField(verbose_name=_('Description'), null=True, blank=True) <NEW_LINE> url = models.URLField(verbose_name=_('URL'), null=True, blank=True) <NEW_LINE> css_class = models.CharField(max_length=20, verbose_name=_('Type'), choices=CSS_CLASS_CHOICES) <NEW_LINE> start = models.DateTimeField(verbose_name=_('Start Date')) <NEW_LINE> end = models.DateTimeField(verbose_name=_('End Date'), null=True, blank=True) <NEW_LINE> all_day = models.BooleanField(verbose_name=_('All Day'),help_text=_('Mark this when the time is irrelevant')) <NEW_LINE> @property <NEW_LINE> def start_timestamp(self): <NEW_LINE> <INDENT> return datetime_to_timestamp(self.start) <NEW_LINE> <DEDENT> @property <NEW_LINE> def end_timestamp(self): <NEW_LINE> <INDENT> return datetime_to_timestamp(self.end) <NEW_LINE> <DEDENT> def getTwitText(self): <NEW_LINE> <INDENT> return '[AGENDA] ' + truncatechars(self.title,110) + ' ' + settings.HOST + 'agenda' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.title
|
Calendar Events
|
625990118c3a8732951f7201
|
class SignUp(Form): <NEW_LINE> <INDENT> first_name = StringField(validators=[DataRequired()], description='First Name', label="First Name") <NEW_LINE> last_name = StringField(validators=[DataRequired()], description='') <NEW_LINE> email = StringField(validators=[DataRequired(), Email()], description='', render_kw={'onblur': 'validate_email()'}) <NEW_LINE> password = PasswordField(validators=[ DataRequired(), EqualTo('confirm_password', message='Passwords must match.') ], description='') <NEW_LINE> confirm_password = PasswordField(validators=[DataRequired()], description='') <NEW_LINE> phone = StringField(validators=[DataRequired()], description='')
|
User signup form.
|
625990115166f23b2e244070
|
class PotentialTransformerInfo(AssetInfo): <NEW_LINE> <INDENT> def __init__(self, ptClass='', accuracyClass='', nominalRatio=None, primaryRatio=None, tertiaryRatio=None, PTs=None, secondaryRatio=None, *args, **kw_args): <NEW_LINE> <INDENT> self.ptClass = ptClass <NEW_LINE> self.accuracyClass = accuracyClass <NEW_LINE> self.nominalRatio = nominalRatio <NEW_LINE> self.primaryRatio = primaryRatio <NEW_LINE> self.tertiaryRatio = tertiaryRatio <NEW_LINE> self._PTs = [] <NEW_LINE> self.PTs = [] if PTs is None else PTs <NEW_LINE> self.secondaryRatio = secondaryRatio <NEW_LINE> super(PotentialTransformerInfo, self).__init__(*args, **kw_args) <NEW_LINE> <DEDENT> _attrs = ["ptClass", "accuracyClass"] <NEW_LINE> _attr_types = {"ptClass": str, "accuracyClass": str} <NEW_LINE> _defaults = {"ptClass": '', "accuracyClass": ''} <NEW_LINE> _enums = {} <NEW_LINE> _refs = ["nominalRatio", "primaryRatio", "tertiaryRatio", "PTs", "secondaryRatio"] <NEW_LINE> _many_refs = ["PTs"] <NEW_LINE> nominalRatio = None <NEW_LINE> primaryRatio = None <NEW_LINE> tertiaryRatio = None <NEW_LINE> def getPTs(self): <NEW_LINE> <INDENT> return self._PTs <NEW_LINE> <DEDENT> def setPTs(self, value): <NEW_LINE> <INDENT> for x in self._PTs: <NEW_LINE> <INDENT> x.PTInfo = None <NEW_LINE> <DEDENT> for y in value: <NEW_LINE> <INDENT> y._PTInfo = self <NEW_LINE> <DEDENT> self._PTs = value <NEW_LINE> <DEDENT> PTs = property(getPTs, setPTs) <NEW_LINE> def addPTs(self, *PTs): <NEW_LINE> <INDENT> for obj in PTs: <NEW_LINE> <INDENT> obj.PTInfo = self <NEW_LINE> <DEDENT> <DEDENT> def removePTs(self, *PTs): <NEW_LINE> <INDENT> for obj in PTs: <NEW_LINE> <INDENT> obj.PTInfo = None <NEW_LINE> <DEDENT> <DEDENT> secondaryRatio = None
|
Properties of potential transformer asset.Properties of potential transformer asset.
|
62599011d18da76e235b779d
|
class TargetPoolsAddInstanceRequest(_messages.Message): <NEW_LINE> <INDENT> instances = _messages.MessageField('InstanceReference', 1, repeated=True)
|
A TargetPoolsAddInstanceRequest object.
Fields:
instances: URLs of the instances to be added to targetPool.
|
62599011462c4b4f79dbc6a9
|
class UserQueries(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> email = models.EmailField() <NEW_LINE> subject = models.CharField(max_length=100) <NEW_LINE> message = models.TextField(max_length=255) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self. subject)
|
store users' feedback
|
625990118c3a8732951f7203
|
class CommandConsole(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.propertyname = 'test_propertyname' <NEW_LINE> self.id_number = 00000 <NEW_LINE> self.color = 'red' <NEW_LINE> <DEDENT> def set_member_value(self, obj, member, value): <NEW_LINE> <INDENT> original_type = type(vars(obj)[member]) <NEW_LINE> try: <NEW_LINE> <INDENT> val = int(value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> val = value <NEW_LINE> <DEDENT> new_type = type(val) <NEW_LINE> if new_type != original_type: <NEW_LINE> <INDENT> print("Entered value not compatible. (i.e. member should be a string and int was entered, or vice versa)") <NEW_LINE> return <NEW_LINE> <DEDENT> vars(obj)[member] = val <NEW_LINE> print("{0} changed to {1}".format(member, val)) <NEW_LINE> return <NEW_LINE> <DEDENT> def get_member_value(self, obj, member): <NEW_LINE> <INDENT> print('{0}: {1}'.format(member, vars(obj)[member])) <NEW_LINE> return
|
This class allows for editing of a particular object
Since it is an editing class, it should only need two functions:
- Get and Set of the various members
|
62599011d18da76e235b779e
|
class PEND(M4ACommand): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(CMD.PEND) <NEW_LINE> <DEDENT> def __call__(self, track: M4ATrack): <NEW_LINE> <INDENT> if track.call_stack: <NEW_LINE> <INDENT> return_ctr = track.call_stack.pop() <NEW_LINE> track.program_ctr = track.base_ctr = return_ctr <NEW_LINE> <DEDENT> track.program_ctr += 1
|
Denote end of pattern block.
|
62599011507cdc57c63a5a42
|
class _Node: <NEW_LINE> <INDENT> def __init__(self, parent, dep_parent, state, action, rules, used, breadth): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> self.dep_parent = dep_parent <NEW_LINE> self.state = state <NEW_LINE> self.action = action <NEW_LINE> self.rules = rules <NEW_LINE> self.used = used <NEW_LINE> self.breadth = breadth <NEW_LINE> self.depth = dep_parent.depth + 1 if dep_parent else 0 <NEW_LINE> self.length = parent.length + 1 if parent else 0
|
A node in a chain being generated.
Each node is aware of its position (depth, breadth) in the dependency tree
induced by the chain. To avoid duplication when generating parallel chains,
each node stores the actions that have already been used at that depth.
|
6259901121a7993f00c66c1e
|
class ResultItem(BaseResultItem, SyncModelMixin, ExportTrackingFieldsMixin, BaseUuidModel): <NEW_LINE> <INDENT> test_code = models.ForeignKey(TestCode, related_name='+') <NEW_LINE> result = models.ForeignKey(Result) <NEW_LINE> subject_type = models.CharField(max_length=25, null=True) <NEW_LINE> objects = ResultItemManager() <NEW_LINE> history = SyncHistoricalRecords() <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.subject_identifier = self.result.order.aliquot.receive.registered_subject.subject_identifier <NEW_LINE> self.subject_type = self.get_subject_type() <NEW_LINE> super(ResultItem, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return str(self.test_code) <NEW_LINE> <DEDENT> def natural_key(self): <NEW_LINE> <INDENT> return (self.subject_identifier) <NEW_LINE> <DEDENT> def result_value(self): <NEW_LINE> <INDENT> if self.result_item_value_as_float: <NEW_LINE> <INDENT> return self.result_item_value_as_float <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.result_item_value <NEW_LINE> <DEDENT> <DEDENT> def to_result(self): <NEW_LINE> <INDENT> reviewed = '' <NEW_LINE> result = ('<a href="/admin/lab_clinic_api/result/?q={result_identifier}">' 'result</a>').format(result_identifier=self.result.result_identifier) <NEW_LINE> if self.result.reviewed: <NEW_LINE> <INDENT> reviewed = ( """ <img src="/static/admin/img/icon_success.gif" width="10" height="10" alt="Reviewed"/>""") <NEW_LINE> <DEDENT> return '{result}{reviewed}'.format(result=result, reviewed=reviewed) <NEW_LINE> <DEDENT> to_result.allow_tags = True <NEW_LINE> def get_report_datetime(self): <NEW_LINE> <INDENT> return self.validation_datetime <NEW_LINE> <DEDENT> @property <NEW_LINE> def get_drawn_datetime(self): <NEW_LINE> <INDENT> return self.result.order.aliquot.receive.drawn_datetime <NEW_LINE> <DEDENT> def get_subject_type(self): <NEW_LINE> <INDENT> if not self.subject_type: <NEW_LINE> <INDENT> return self.result.order.aliquot.receive.registered_subject.subject_type <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.subject_type <NEW_LINE> <DEDENT> <DEDENT> def get_cls_reference_flag(self): <NEW_LINE> <INDENT> return ClinicReferenceFlag <NEW_LINE> <DEDENT> def get_cls_grade_flag(self): <NEW_LINE> <INDENT> return ClinicGradeFlag <NEW_LINE> <DEDENT> def get_test_code(self): <NEW_LINE> <INDENT> return self.test_code.code <NEW_LINE> <DEDENT> def get_result_datetime(self): <NEW_LINE> <INDENT> return self.result_item_datetime <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> app_label = 'td_lab' <NEW_LINE> ordering = ('-result_item_datetime', )
|
Stores each result item in a result in one-to-many relation with :class:`Result`.
|
625990115166f23b2e244074
|
class CreateMmsInstanceResp(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ReturnCode = None <NEW_LINE> self.ReturnMsg = None <NEW_LINE> self.InstanceId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ReturnCode = params.get("ReturnCode") <NEW_LINE> self.ReturnMsg = params.get("ReturnMsg") <NEW_LINE> self.InstanceId = params.get("InstanceId")
|
创建超级短信样例返回结果
|
62599011d18da76e235b77a0
|
class OpPost(object): <NEW_LINE> <INDENT> def __init__(self, script=None, callback_url=None): <NEW_LINE> <INDENT> self.swagger_types = { 'script': 'str', 'callback_url': 'str' } <NEW_LINE> self.attribute_map = { 'script': 'script', 'callback_url': 'callback_url' } <NEW_LINE> self._script = script <NEW_LINE> self._callback_url = callback_url <NEW_LINE> <DEDENT> @property <NEW_LINE> def script(self): <NEW_LINE> <INDENT> return self._script <NEW_LINE> <DEDENT> @script.setter <NEW_LINE> def script(self, script): <NEW_LINE> <INDENT> self._script = script <NEW_LINE> <DEDENT> @property <NEW_LINE> def callback_url(self): <NEW_LINE> <INDENT> return self._callback_url <NEW_LINE> <DEDENT> @callback_url.setter <NEW_LINE> def callback_url(self, callback_url): <NEW_LINE> <INDENT> self._callback_url = callback_url <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
|
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
|
6259901115fb5d323ce7f9e4
|
class SendmailHandlerBase(object): <NEW_LINE> <INDENT> def send(self, invitation, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError
|
Abstract class for Sendmail Handlers
|
6259901156b00c62f0fb3565
|
class VerbatimEnvironment(NoCharSubEnvironment): <NEW_LINE> <INDENT> blockType = True <NEW_LINE> captionable = True <NEW_LINE> def invoke(self, tex): <NEW_LINE> <INDENT> if self.macroMode == Environment.MODE_END: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> escape = self.ownerDocument.context.categories[0][0] <NEW_LINE> bgroup = self.ownerDocument.context.categories[1][0] <NEW_LINE> egroup = self.ownerDocument.context.categories[2][0] <NEW_LINE> self.ownerDocument.context.push(self) <NEW_LINE> self.parse(tex) <NEW_LINE> self.ownerDocument.context.setVerbatimCatcodes() <NEW_LINE> tokens = [self] <NEW_LINE> name = self.nodeName <NEW_LINE> if self.macroMode != Environment.MODE_NONE: <NEW_LINE> <INDENT> if self.ownerDocument.context.currenvir is not None: <NEW_LINE> <INDENT> name = self.ownerDocument.context.currenvir <NEW_LINE> <DEDENT> <DEDENT> endpattern = list(r'%send%s%s%s' % (escape, bgroup, name, egroup)) <NEW_LINE> endpattern2 = list(r'%send%s' % (escape, name)) <NEW_LINE> endlength = len(endpattern) <NEW_LINE> endlength2 = len(endpattern2) <NEW_LINE> for tok in tex: <NEW_LINE> <INDENT> tokens.append(tok) <NEW_LINE> if len(tokens) >= endlength: <NEW_LINE> <INDENT> if tokens[-endlength:] == endpattern: <NEW_LINE> <INDENT> tokens = tokens[:-endlength] <NEW_LINE> self.ownerDocument.context.pop(self) <NEW_LINE> end = self.ownerDocument.createElement(name) <NEW_LINE> end.parentNode = self.parentNode <NEW_LINE> end.macroMode = Environment.MODE_END <NEW_LINE> res = end.invoke(tex) <NEW_LINE> if res is None: <NEW_LINE> <INDENT> res = [end] <NEW_LINE> <DEDENT> tex.pushTokens(res) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if len(tokens) >= endlength2: <NEW_LINE> <INDENT> if tokens[-endlength2:] == endpattern2: <NEW_LINE> <INDENT> tokens = tokens[:-endlength2] <NEW_LINE> self.ownerDocument.context.pop(self) <NEW_LINE> end = self.ownerDocument.createElement(name) <NEW_LINE> end.parentNode = self.parentNode <NEW_LINE> end.macroMode = Environment.MODE_END <NEW_LINE> res = end.invoke(tex) <NEW_LINE> if res is None: <NEW_LINE> <INDENT> res = [end] <NEW_LINE> <DEDENT> tex.pushTokens(res) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return tokens
|
A subclass of Environment that prevents processing of the contents. This is
used for the verbatim environment.
It is also useful in cases where you want to leave the processing to the
renderer (e.g. via the imager) and the content is sufficiently complex that
we don't want plastex to deal with the commands within it.
For example, for tikzpicture, there are many Tikz commands and it would be
tedious to attempt to define all of them in the python file, when we are
not going to use them anyway.
|
62599011507cdc57c63a5a48
|
class ExcelLib(object): <NEW_LINE> <INDENT> READ_MODE = 'r' <NEW_LINE> WRITE_MODE = 'w' <NEW_LINE> def __init__(self, fileName = None, mode = READ_MODE): <NEW_LINE> <INDENT> if ExcelLib.READ_MODE == mode: <NEW_LINE> <INDENT> self.__operation = ExcelRead(fileName) <NEW_LINE> <DEDENT> elif ExcelLib.WRITE_MODE == mode: <NEW_LINE> <INDENT> self.__operation = ExcelWrite(fileName) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise UfException(Errors.INVALID_EXCEL_MODE, "Invalid operation mode, only %s and %s are accepted" % (ExcelLib.READ_MODE, ExcelLib.WRITE_MODE)) <NEW_LINE> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.__operation.pre() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> self.__operation.post() <NEW_LINE> return <NEW_LINE> <DEDENT> def openSheet(self, name): <NEW_LINE> <INDENT> self.__operation.openSheet(name) <NEW_LINE> <DEDENT> def readRow(self, row, startCol=0, endCol=-1): <NEW_LINE> <INDENT> return self.__operation.readRow(row, startCol, endCol) <NEW_LINE> <DEDENT> def readCol(self, col, startRow=0, endRow=-1): <NEW_LINE> <INDENT> return self.__operation.readCol(col, startRow, endRow) <NEW_LINE> <DEDENT> def readCell(self, row, col): <NEW_LINE> <INDENT> return self.__operation.readCell(row, col) <NEW_LINE> <DEDENT> def writeRow(self, row, values): <NEW_LINE> <INDENT> self.__operation.writeRow(row, values) <NEW_LINE> <DEDENT> def writeCell(self, row, col, value): <NEW_LINE> <INDENT> self.__operation.writeCell(row, col, value) <NEW_LINE> <DEDENT> def getOperation(self): <NEW_LINE> <INDENT> return self.__operation
|
lib for accessing excel
|
625990110a366e3fb87dd69d
|
class TimerField(TypedField): <NEW_LINE> <INDENT> def __init__(self, *other_types, attr_name=None): <NEW_LINE> <INDENT> super().__init__(str, int, float, *other_types, attr_name=attr_name) <NEW_LINE> <DEDENT> def __set__(self, obj, value): <NEW_LINE> <INDENT> value = remove_convertible(value) <NEW_LINE> self._check_type(value) <NEW_LINE> if isinstance(value, str): <NEW_LINE> <INDENT> time_match = re.match(r'^((?P<days>\d+)d)?' r'((?P<hours>\d+)h)?' r'((?P<minutes>\d+)m)?' r'((?P<seconds>\d+)s)?$', value) <NEW_LINE> if not time_match: <NEW_LINE> <INDENT> raise ValueError('invalid format for timer field') <NEW_LINE> <DEDENT> value = datetime.timedelta( **{k: int(v) for k, v in time_match.groupdict().items() if v} ).total_seconds() <NEW_LINE> <DEDENT> elif isinstance(value, float) or isinstance(value, int): <NEW_LINE> <INDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError('timer field value cannot be negative') <NEW_LINE> <DEDENT> <DEDENT> Field.__set__(self, obj, value)
|
Stores a timer in the form of a :class:`datetime.timedelta` object
|
62599011d18da76e235b77a2
|
class NBNSNameRegistrationRequest(NBNSRequest): <NEW_LINE> <INDENT> def __init__( self, name_trn_id, q_name, nb_address, for_group=False, ont=None, ttl=None, broadcast=False, ): <NEW_LINE> <INDENT> if broadcast: <NEW_LINE> <INDENT> ttl = 0 <NEW_LINE> <DEDENT> elif ttl is None: <NEW_LINE> <INDENT> raise ValueError("NBNSNameRegistrationRequest requires TTL value.") <NEW_LINE> <DEDENT> if broadcast: <NEW_LINE> <INDENT> ont = NB_NS_NB_FLAGS_ONT_B <NEW_LINE> <DEDENT> elif ont is None: <NEW_LINE> <INDENT> raise ValueError("NBNSNameRegistrationRequest requires ONT value.") <NEW_LINE> <DEDENT> nm_flags = ( NB_NS_NM_FLAGS_RD | (NB_NS_NM_FLAGS_BCAST if broadcast else NB_NS_NM_FLAGS_UCAST) ) <NEW_LINE> g = NB_NS_NB_FLAGS_GROUP if for_group else NB_NS_NB_FLAGS_UNIQUE <NEW_LINE> super().__init__( name_trn_id = name_trn_id, opcode = NB_NS_OPCODE_REGISTER, nm_flags = nm_flags, questions = [ NBNSQuestionEntry( q_name = q_name, q_type = NBNS_Q_TYPE_NB, q_class = NBNS_Q_CLASS_IN, ), ], additional_rrs = [ NBNSNameRegistrationResourceRecord( ttl = ttl, g = g, ont = ont, nb_address = nb_address, ), ], )
|
NetBIOS Name Service Name Registration request.
See also: section 4.2.2 of RFC 1002 (https://tools.ietf.org/html/rfc1002).
|
625990116fece00bbaccc660
|
class ProductAttributeSelectionOption(ModelSQL, ModelView): <NEW_LINE> <INDENT> __name__ = 'product.attribute.selection_option' <NEW_LINE> name = fields.Char("Name", required=True, select=True, translate=True) <NEW_LINE> attribute = fields.Many2One( "product.attribute", "Attribute", required=True, ondelete='CASCADE' )
|
Attribute Selection Option
|
625990115166f23b2e24407d
|
class StateViewer(wx.Window, garlicsim_wx.widgets.WorkspaceWidget): <NEW_LINE> <INDENT> def __init__(self, frame): <NEW_LINE> <INDENT> wx.Window.__init__(self, frame, style=wx.SUNKEN_BORDER) <NEW_LINE> garlicsim_wx.widgets.WorkspaceWidget.__init__(self, frame) <NEW_LINE> self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) <NEW_LINE> self.left = None <NEW_LINE> self.right = None <NEW_LINE> self.Bind(wx.EVT_PAINT, self.on_paint) <NEW_LINE> self.radius = 60 <NEW_LINE> self.gui_project.active_node_changed_or_modified_emitter.add_output( lambda: self.load_state(self.gui_project.get_active_state()) ) <NEW_LINE> <DEDENT> def on_paint(self, event): <NEW_LINE> <INDENT> event.Skip() <NEW_LINE> dc = wx.BufferedPaintDC(self) <NEW_LINE> dc.SetBackground(wx_tools.get_background_brush()) <NEW_LINE> dc.Clear() <NEW_LINE> dc.SetBrush(wx.Brush("white", wx.TRANSPARENT)) <NEW_LINE> for [side, pos] in [[self.left, (100, 100)], [self.right, (300, 100)]]: <NEW_LINE> <INDENT> dc.SetPen(wx.Pen("black", 2)) <NEW_LINE> dc.DrawCirclePoint(pos, self.radius) <NEW_LINE> if side is not None: <NEW_LINE> <INDENT> point = (pos[0] + math.cos(side) * self.radius, pos[1] + math.sin(side) * self.radius) <NEW_LINE> dc.SetPen(wx.Pen("red", 20)) <NEW_LINE> dc.DrawLinePoint(point, point) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def load_state(self, state): <NEW_LINE> <INDENT> if state is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.left, self.right = state.left, state.right <NEW_LINE> self.Refresh()
|
Widget for showing a state onscreen.
|
625990115166f23b2e24407f
|
class FlowcellsInfoDataHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> def get(self, flowcell): <NEW_LINE> <INDENT> self.set_header("Content-type", "application/json") <NEW_LINE> self.write(json.dumps(self.flowcell_info(flowcell))) <NEW_LINE> <DEDENT> def flowcell_info(self, flowcell): <NEW_LINE> <INDENT> fc_view = self.application.flowcells_db.view("info/summary", descending=True) <NEW_LINE> for row in fc_view[flowcell]: <NEW_LINE> <INDENT> flowcell_info = row.value <NEW_LINE> break <NEW_LINE> <DEDENT> return flowcell_info
|
Serves brief information about a given flowcell.
|
6259901221a7993f00c66c2a
|
class ResolveAliasResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.FleetId = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.FleetId = params.get("FleetId") <NEW_LINE> self.RequestId = params.get("RequestId")
|
ResolveAlias返回参数结构体
|
62599012d18da76e235b77a5
|
class UserUpdateTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> response = client.post('/users/', data=json.dumps({ "username": "test2", "password": "test2", "firstName": "test", "lastName": "test", }), content_type='application/json') <NEW_LINE> self.token = response.data['token'] <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> def test_invalid_signup(self): <NEW_LINE> <INDENT> response = client.post('/users/', data=json.dumps({ "username": "test2", }), content_type='application/json') <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_user_profile_update(self): <NEW_LINE> <INDENT> client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) <NEW_LINE> response = client.get('/users/current_user/', content_type='application/json') <NEW_LINE> user = response.data <NEW_LINE> user['username'] = "test3" <NEW_LINE> user['profile']['bio'] = "ABC" <NEW_LINE> user['profile']['education'] = "ABC" <NEW_LINE> user['profile']['experiance'] = "ABC" <NEW_LINE> user['profile']['birthDate'] = "2020-11-11" <NEW_LINE> response = client.put('/users/current_user/', data=json.dumps(user), content_type='application/json') <NEW_LINE> user = User.objects.get(username="test3") <NEW_LINE> serializer = UserSerializer(user) <NEW_LINE> self.assertEqual(response.data, serializer.data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> client.credentials() <NEW_LINE> <DEDENT> def test_invalid_user_profile_update(self): <NEW_LINE> <INDENT> client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) <NEW_LINE> response = client.get('/users/current_user/', content_type='application/json') <NEW_LINE> user = response.data <NEW_LINE> response = client.put('/users/current_user/', data=json.dumps(user), content_type='application/json') <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> client.credentials()
|
Test module to update user profile
|
6259901256b00c62f0fb356e
|
class IPermissionsDeclarationViewlet(IViewlet): <NEW_LINE> <INDENT> pass
|
Will return to the client side all of our security declaritives
|
625990120a366e3fb87dd6a3
|
class RandomHtmlDocumentProvider(RandomParagraphProvider): <NEW_LINE> <INDENT> def getValue(self): <NEW_LINE> <INDENT> html = '<html><body>' <NEW_LINE> for _ in range(random.randint(5, 10)): <NEW_LINE> <INDENT> html += '<h1>' + RandomPhraseProvider.getValue(self) + '</h1>' <NEW_LINE> html += '<p>' + RandomParagraphProvider.getValue(self) + '</p>' <NEW_LINE> <DEDENT> html += '</body></html>' <NEW_LINE> return html
|
Data provider that returns a random HTML document.
|
62599012d164cc6175821c2e
|
class APIError(Exception): <NEW_LINE> <INDENT> _default_status_code = 400 <NEW_LINE> def __init__(self, message, status_code=None): <NEW_LINE> <INDENT> Exception.__init__(self) <NEW_LINE> self.message = message <NEW_LINE> if status_code is None: <NEW_LINE> <INDENT> self.status_code = self._default_status_code <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.status_code = status_code
|
Исключение при обработке запроса.
|
62599012be8e80087fbbfd22
|
class ratelimit_access_token(RateLimitDecorator): <NEW_LINE> <INDENT> def normalize_key(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if self.path_in_key: <NEW_LINE> <INDENT> ret = "{}{}".format(request.access_token, request.path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret = request.access_token <NEW_LINE> <DEDENT> return ret
|
Limit by the requested client's access token, because certain endpoints can
only be requested a certain amount of times for the given access token
|
62599012d18da76e235b77a6
|
class TushareGateway(VtGateway): <NEW_LINE> <INDENT> def __init__(self, eventEngine, gatewayName='Tushare'): <NEW_LINE> <INDENT> super(TushareGateway, self).__init__(eventEngine, gatewayName) <NEW_LINE> self.mdConnected = False <NEW_LINE> self.tdConnected = False <NEW_LINE> self.qryEnabled = False <NEW_LINE> self.subSymbolList = [] <NEW_LINE> self.fileName = self.gatewayName + '_connect.json' <NEW_LINE> self.filePath = getJsonPath(self.fileName, __file__) <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.initQuery() <NEW_LINE> <DEDENT> def subscribe(self, subscribeReq): <NEW_LINE> <INDENT> self.subSymbolList.append(subscribeReq) <NEW_LINE> <DEDENT> def sendOrder(self, orderReq): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def cancelOrder(self, cancelOrderReq): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def qryAccount(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def qryPosition(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def qryRealtimeData(self): <NEW_LINE> <INDENT> for req in self.subSymbolList: <NEW_LINE> <INDENT> df = ts.get_realtime_quotes(req.symbol) <NEW_LINE> if not df.empty: <NEW_LINE> <INDENT> tick = VtTickData() <NEW_LINE> for key in tick_tushare_map.keys(): <NEW_LINE> <INDENT> tick.__dict__[key] = df.ix[0, tick_tushare_map[key]] <NEW_LINE> <DEDENT> tick.datetime = datetime.strptime(df.ix[0, 'date']+ ' ' + df.ix[0, 'time'], "%Y-%m-%d %H:%M:%S") <NEW_LINE> self.onTick(tick) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def initQuery(self): <NEW_LINE> <INDENT> if self.qryEnabled: <NEW_LINE> <INDENT> self.qryFunctionList = [self.qryRealtimeData] <NEW_LINE> self.qryCount = 0 <NEW_LINE> self.qryTrigger = 2 <NEW_LINE> self.qryNextFunction = 0 <NEW_LINE> self.startQuery() <NEW_LINE> <DEDENT> <DEDENT> def query(self, event): <NEW_LINE> <INDENT> self.qryCount += 1 <NEW_LINE> if self.qryCount > self.qryTrigger: <NEW_LINE> <INDENT> self.qryCount = 0 <NEW_LINE> function = self.qryFunctionList[self.qryNextFunction] <NEW_LINE> function() <NEW_LINE> self.qryNextFunction += 1 <NEW_LINE> if self.qryNextFunction == len(self.qryFunctionList): <NEW_LINE> <INDENT> self.qryNextFunction = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def startQuery(self): <NEW_LINE> <INDENT> self.eventEngine.register(EVENT_TIMER, self.query) <NEW_LINE> <DEDENT> def setQryEnabled(self, qryEnabled): <NEW_LINE> <INDENT> self.qryEnabled = qryEnabled
|
CTP接口
|
6259901215fb5d323ce7f9f0
|
class IssueCommentEdge(sgqlc.types.Type): <NEW_LINE> <INDENT> __schema__ = github_schema <NEW_LINE> __field_names__ = ('cursor', 'node') <NEW_LINE> cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name='cursor') <NEW_LINE> node = sgqlc.types.Field('IssueComment', graphql_name='node')
|
An edge in a connection.
|
62599012462c4b4f79dbc6bd
|
class User(model.Model, Storm): <NEW_LINE> <INDENT> __metaclass__ = model.MambaStorm <NEW_LINE> __storm_table__ = 'users' <NEW_LINE> name = Unicode(size=128) <NEW_LINE> realname = Unicode(size=256) <NEW_LINE> email = Unicode(primary=True, size=128) <NEW_LINE> key = Unicode(size=128) <NEW_LINE> access_level = Int(unsigned=True) <NEW_LINE> github_profile = Unicode(size=128) <NEW_LINE> bitbucket_profile = Unicode(size=128) <NEW_LINE> twitter = Unicode(size=64) <NEW_LINE> registered = DateTime() <NEW_LINE> last_login = DateTime() <NEW_LINE> posts = ReferenceSet('User.email', 'Post.author_email') <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(User, self).__init__() <NEW_LINE> <DEDENT> @transact <NEW_LINE> def sign_in(self, email, key): <NEW_LINE> <INDENT> store = self.database.store() <NEW_LINE> return store.find(User, User.email == email, User.key == key).one()
|
Users model for BlackMamba
|
62599012be8e80087fbbfd26
|
class OpenPGPKeys(object) : <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_ascii_armor(cls, keyAsc) : <NEW_LINE> <INDENT> return OpenPGPKeys(keyAsc) <NEW_LINE> <DEDENT> def __init__(self, keyAsc, encoding = 'utf-8'): <NEW_LINE> <INDENT> self._keyAsc = keyAsc <NEW_LINE> self._loadedKeys = load_keys(keyAsc) <NEW_LINE> self._encoding = 'utf-8' <NEW_LINE> return <NEW_LINE> <DEDENT> def GetUserIdentityEmails(self) : <NEW_LINE> <INDENT> return sorted(list(self._iterEmailsFromUserIdentities())) <NEW_LINE> <DEDENT> def _iterEmailsFromUserIdentities(self): <NEW_LINE> <INDENT> for k in self._loadedKeys : <NEW_LINE> <INDENT> for userId in k.userids : <NEW_LINE> <INDENT> email = userId.email <NEW_LINE> yield email.encode(self._encoding) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def GetFingerprints(self) : <NEW_LINE> <INDENT> return list(self._iterFingerprints()) <NEW_LINE> <DEDENT> def _iterFingerprints(self): <NEW_LINE> <INDENT> for k in self._loadedKeys : <NEW_LINE> <INDENT> fingerprint = k.fingerprint <NEW_LINE> yield fingerprint.replace(' ', '') <NEW_LINE> <DEDENT> return
|
Facade do decouple users of 'openpgp' from underlying implementation,
currently 'PGPy'.
|
6259901221a7993f00c66c30
|
class ModifyCharacterResponseSchema(schema.ResponseSchema): <NEW_LINE> <INDENT> fields = {}
|
ModifyCharacter - 修改角色
|
62599012925a0f43d25e8cf6
|
class _ReceiverThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, listen_port, client, callback_container, in_socket=None): <NEW_LINE> <INDENT> logging.info("NH: Thread created") <NEW_LINE> threading.Thread.__init__(self) <NEW_LINE> if in_socket is None: <NEW_LINE> <INDENT> self._network_socket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._network_socket = in_socket <NEW_LINE> <DEDENT> self._network_socket.bind(('', listen_port)) <NEW_LINE> self._network_socket.settimeout(0.2) <NEW_LINE> self._stop_thread = False <NEW_LINE> self._callback_container = callback_container <NEW_LINE> self._client = client <NEW_LINE> self._ping_checker = _PingChecker(self._command_abort) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> logging.info("NH: Thread started") <NEW_LINE> while not self._stop_thread: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data, sender = self._network_socket.recvfrom(1024) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self._client.ip = sender[0] <NEW_LINE> if data: <NEW_LINE> <INDENT> command, args, kwargs = _parse_command(data) <NEW_LINE> if command == "PING": <NEW_LINE> <INDENT> self._ping_checker.ping() <NEW_LINE> <DEDENT> elif command in self._callback_container: <NEW_LINE> <INDENT> logging.info( "NH: Received command: {} with arguments: {}, {}".format( command, args, kwargs)) <NEW_LINE> try: <NEW_LINE> <INDENT> self._callback_container[command](*args, **kwargs) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> logging.error("Invalid attributes for command: {}, received arguments: {}, {}".format( command, args, kwargs)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logging.warning("NH: Received invalid command: " + command) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self._ping_checker.stop() <NEW_LINE> self._stop_thread = True <NEW_LINE> <DEDENT> def _command_abort(self): <NEW_LINE> <INDENT> self._callback_container.get('LAND', lambda: None)()
|
Runs the network communication in a thread so that all other execution
remains unaffected.
|
62599012462c4b4f79dbc6bf
|
class Executor(object): <NEW_LINE> <INDENT> def submit(self, fn, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def map(self, fn, *iterables, timeout=None): <NEW_LINE> <INDENT> if timeout is not None: <NEW_LINE> <INDENT> end_time = timeout + time.time() <NEW_LINE> <DEDENT> fs = [self.submit(fn, *args) for args in zip(*iterables)] <NEW_LINE> def result_iterator(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for future in fs: <NEW_LINE> <INDENT> if timeout is None: <NEW_LINE> <INDENT> yield future.result() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield future.result(end_time - time.time()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> for future in fs: <NEW_LINE> <INDENT> future.cancel() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result_iterator() <NEW_LINE> <DEDENT> def shutdown(self, wait=True): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.shutdown(wait=True) <NEW_LINE> return False
|
This is an abstract base class for concrete asynchronous executors.
|
62599012be8e80087fbbfd28
|
@admin.register(Transaction) <NEW_LINE> class TransactionAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> date_hierarchy = 'request_ts' <NEW_LINE> list_filter = ('server', ResponseFilter, 'request_type', 'response_type') <NEW_LINE> list_display = ('admin_duid', 'admin_interface_id', 'admin_remote_id', 'server', 'admin_request_ts_ms', 'request_ll', 'request_type', 'response_type') <NEW_LINE> search_fields = ('client__duid', 'client__interface_id', 'client__remote_id', 'request', 'response') <NEW_LINE> readonly_fields = ('client_duid', 'client_duid_ll', 'client_duid_ll_org', 'request_ll', 'request_ll_mac', 'request_ll_mac_org', 'client_interface_id', 'client_remote_id', 'request_html', 'admin_request_ts_ms', 'response_html', 'admin_response_ts_ms') <NEW_LINE> fieldsets = ( ('Client', { 'fields': (('client_duid', 'client_duid_ll', 'client_duid_ll_org'), ('request_ll', 'request_ll_mac', 'request_ll_mac_org'), 'client_interface_id', 'client_remote_id'), }), ('Request', { 'fields': ('request_html', 'admin_request_ts_ms'), }), ('Response', { 'fields': ('response_html', 'admin_response_ts_ms'), }), ) <NEW_LINE> def admin_request_ts_ms(self, transaction: Transaction) -> str: <NEW_LINE> <INDENT> return "{:%Y-%m-%d %H:%M:%S.%f}".format(timezone.localtime(transaction.request_ts)) <NEW_LINE> <DEDENT> admin_request_ts_ms.short_description = _('last request') <NEW_LINE> admin_request_ts_ms.admin_order_field = 'request_ts' <NEW_LINE> def admin_response_ts_ms(self, transaction: Transaction) -> str: <NEW_LINE> <INDENT> return "{:%Y-%m-%d %H:%M:%S.%f}".format(timezone.localtime(transaction.response_ts)) <NEW_LINE> <DEDENT> admin_response_ts_ms.short_description = _('last request') <NEW_LINE> admin_response_ts_ms.admin_order_field = 'response_ts' <NEW_LINE> def admin_duid(self, transaction: Transaction) -> str: <NEW_LINE> <INDENT> return transaction.client.duid_ll or transaction.client.duid <NEW_LINE> <DEDENT> admin_duid.short_description = _('DUID / MAC') <NEW_LINE> admin_duid.admin_order_field = 'client__duid' <NEW_LINE> def admin_interface_id(self, transaction: Transaction) -> str: <NEW_LINE> <INDENT> return transaction.client.interface_id <NEW_LINE> <DEDENT> admin_interface_id.short_description = _('Interface ID') <NEW_LINE> admin_interface_id.admin_order_field = 'client__interface_id' <NEW_LINE> def admin_remote_id(self, transaction: Transaction) -> str: <NEW_LINE> <INDENT> return transaction.client.remote_id <NEW_LINE> <DEDENT> admin_remote_id.short_description = _('Remote ID') <NEW_LINE> admin_remote_id.admin_order_field = 'client__remote_id'
|
Admin interface for transactions
|
6259901256b00c62f0fb3576
|
class NewFilesHandler(): <NEW_LINE> <INDENT> def __init__(self, book): <NEW_LINE> <INDENT> self.book = book <NEW_LINE> self.add_new_files() <NEW_LINE> <DEDENT> def add_new_files(self): <NEW_LINE> <INDENT> self.template_readme() <NEW_LINE> self.copy_files() <NEW_LINE> <DEDENT> def template_readme(self): <NEW_LINE> <INDENT> templateFile = open('templates/README.md.j2').read() <NEW_LINE> template = jinja2.Template(templateFile) <NEW_LINE> readme_text = template.render( title=self.book.title, author=self.book.author, book_id=self.book.ID ) <NEW_LINE> readme_path = "{0}/{1}".format( self.book.textdir, 'README.md' ) <NEW_LINE> with codecs.open(readme_path, 'w', 'utf-8') as readme_file: <NEW_LINE> <INDENT> readme_file.write(readme_text) <NEW_LINE> <DEDENT> <DEDENT> def copy_files(self): <NEW_LINE> <INDENT> files = ['LICENSE.md', 'CONTRIBUTING.md'] <NEW_LINE> this_dir = sh.pwd().strip() <NEW_LINE> for _file in files: <NEW_LINE> <INDENT> sh.cp( '{0}/templates/{1}'.format(this_dir, _file), '{0}/'.format(self.book.textdir) )
|
NewFilesHandler - templates and copies additional files to book repos
|
62599012507cdc57c63a5a58
|
class Lookback: <NEW_LINE> <INDENT> STATS = ["mean", "max", "min", "std"] <NEW_LINE> def __init__(self, lookback_time: float = 0): <NEW_LINE> <INDENT> self.lookback_time = lookback_time <NEW_LINE> self._entries = collections.deque() <NEW_LINE> <DEDENT> def add(self, time: float, mode_amplitudes: np.ndarray): <NEW_LINE> <INDENT> if self._entries is None: <NEW_LINE> <INDENT> raise exceptions.LookbackIsFrozen( "this lookback is frozen; no more measurements can be added to it" ) <NEW_LINE> <DEDENT> self._entries.append((time, mode_amplitudes.copy())) <NEW_LINE> earliest_time = time - self.lookback_time <NEW_LINE> while earliest_time > self._entries[0][0]: <NEW_LINE> <INDENT> self._entries.popleft() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def _stacked(self) -> np.ndarray: <NEW_LINE> <INDENT> return np.vstack(e[1] for e in self._entries) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _stacked_magnitudes(self): <NEW_LINE> <INDENT> return np.abs(self._stacked) <NEW_LINE> <DEDENT> @freezeable_property <NEW_LINE> def mean(self) -> np.ndarray: <NEW_LINE> <INDENT> return np.mean(self._stacked_magnitudes, axis=0) <NEW_LINE> <DEDENT> @freezeable_property <NEW_LINE> def max(self) -> np.ndarray: <NEW_LINE> <INDENT> return np.max(self._stacked_magnitudes, axis=0) <NEW_LINE> <DEDENT> @freezeable_property <NEW_LINE> def min(self) -> np.ndarray: <NEW_LINE> <INDENT> return np.min(self._stacked_magnitudes, axis=0) <NEW_LINE> <DEDENT> @freezeable_property <NEW_LINE> def std(self) -> np.ndarray: <NEW_LINE> <INDENT> return np.std(self._stacked_magnitudes, axis=0) <NEW_LINE> <DEDENT> def freeze(self): <NEW_LINE> <INDENT> for stat in self.STATS: <NEW_LINE> <INDENT> self.__dict__[stat] = getattr(self, stat) <NEW_LINE> <DEDENT> self._entries = None
|
A helper class for a RamanSimulation that "looks backward" from the end of the simulation and collects summary data on the mode amplitudes.
|
6259901256b00c62f0fb3578
|
class MaxCubeHandle: <NEW_LINE> <INDENT> def __init__(self, cube, scan_interval): <NEW_LINE> <INDENT> self.cube = cube <NEW_LINE> self.scan_interval = scan_interval <NEW_LINE> self.mutex = Lock() <NEW_LINE> self._updatets = time.time() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> with self.mutex: <NEW_LINE> <INDENT> if (time.time() - self._updatets) >= self.scan_interval: <NEW_LINE> <INDENT> _LOGGER.debug("Updating") <NEW_LINE> try: <NEW_LINE> <INDENT> self.cube.update() <NEW_LINE> <DEDENT> except timeout: <NEW_LINE> <INDENT> _LOGGER.error("Max!Cube connection failed") <NEW_LINE> return False <NEW_LINE> <DEDENT> self._updatets = time.time() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _LOGGER.debug("Skipping update")
|
Keep the cube instance in one place and centralize the update.
|
62599012462c4b4f79dbc6c3
|
class TCellNaiveHelperRecruitmentBronchialByCytokine(RecruitmentBronchialByExternals): <NEW_LINE> <INDENT> def __init__(self, probability): <NEW_LINE> <INDENT> RecruitmentBronchialByExternals.__init__(self, probability, recruited_compartment=T_CELL_NAIVE_HELPER, external_compartments=CYTOKINE_PRODUCING_COMPARTMENTS, based_on_perfusion=True)
|
Naive helper T-cell recruited into bronchial tree based on cytokine levels
|
625990126fece00bbaccc672
|
class MultiCheckboxField(form.Field): <NEW_LINE> <INDENT> def __init__(self, name, values, value=None, **kwargs): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> value = [] <NEW_LINE> <DEDENT> if not isinstance(value, list): <NEW_LINE> <INDENT> raise Exception('Value must be a list for multi-checkbox field') <NEW_LINE> <DEDENT> super().__init__(name, allow_missing=True, value=value, **kwargs) <NEW_LINE> self.values = values <NEW_LINE> self._checked_select_values = [v.select_value for v in self.value] <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> return env.get_template('advanced/multicheckbox.html').render(field=self) <NEW_LINE> <DEDENT> def extract_value(self, data): <NEW_LINE> <INDENT> self._checked_select_values = data.getlist(self.name) <NEW_LINE> self.value = [v for v in self.values if v.select_value in self._checked_select_values]
|
This field renders as multiple checkboxes in a vertical column. The must pass in a list of
object with select_name and select_value properties defined. Each checkbox will have
select_name as a label, and select_value (which must be unique) will be submitted as the
value of the checkbox.
When reading form data, the original objects will be copied into a new list, with each
object that had its box ticked being present in the list.
|
62599012507cdc57c63a5a5c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.