code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Image(IResource): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> for _s in [IResource]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{})) <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, Image, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> for _s in [IResource]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{})) <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, Image, name) <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> __swig_destroy__ = _fife.delete_Image <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def getSurface(self): <NEW_LINE> <INDENT> return _fife.Image_getSurface(self) <NEW_LINE> <DEDENT> def getWidth(self): <NEW_LINE> <INDENT> return _fife.Image_getWidth(self) <NEW_LINE> <DEDENT> def getHeight(self): <NEW_LINE> <INDENT> return _fife.Image_getHeight(self) <NEW_LINE> <DEDENT> def getArea(self): <NEW_LINE> <INDENT> return _fife.Image_getArea(self) <NEW_LINE> <DEDENT> def setXShift(self, *args): <NEW_LINE> <INDENT> return _fife.Image_setXShift(self, *args) <NEW_LINE> <DEDENT> def getXShift(self): <NEW_LINE> <INDENT> return _fife.Image_getXShift(self) <NEW_LINE> <DEDENT> def setYShift(self, *args): <NEW_LINE> <INDENT> return _fife.Image_setYShift(self, *args) <NEW_LINE> <DEDENT> def getYShift(self): <NEW_LINE> <INDENT> return _fife.Image_getYShift(self) <NEW_LINE> <DEDENT> def getPixelRGBA(self, *args): <NEW_LINE> <INDENT> return _fife.Image_getPixelRGBA(self, *args) <NEW_LINE> <DEDENT> def saveImage(self, *args): <NEW_LINE> <INDENT> return _fife.Image_saveImage(self, *args) <NEW_LINE> <DEDENT> def useSharedImage(self, *args): <NEW_LINE> <INDENT> return _fife.Image_useSharedImage(self, *args) <NEW_LINE> <DEDENT> def forceLoadInternal(self): <NEW_LINE> <INDENT> return _fife.Image_forceLoadInternal(self) <NEW_LINE> <DEDENT> def isSharedImage(self): <NEW_LINE> <INDENT> return _fife.Image_isSharedImage(self) <NEW_LINE> <DEDENT> def getSubImageRect(self): <NEW_LINE> <INDENT> return _fife.Image_getSubImageRect(self) <NEW_LINE> <DEDENT> def copySubimage(self, *args): <NEW_LINE> <INDENT> return _fife.Image_copySubimage(self, *args) | Proxy of C++ FIFE::Image class | 62598fa36fb2d068a7693d7d |
class ServiceTestCase(test.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(ServiceTestCase, self).setUp() <NEW_LINE> self.host = 'foo' <NEW_LINE> self.binary = 'nova-fake' <NEW_LINE> self.topic = 'fake' <NEW_LINE> self.mox.StubOutWithMock(service, 'db') <NEW_LINE> <DEDENT> def test_create(self): <NEW_LINE> <INDENT> app = service.Service.create(host=self.host, binary=self.binary, topic=self.topic) <NEW_LINE> self.assert_(app) <NEW_LINE> <DEDENT> def _service_start_mocks(self): <NEW_LINE> <INDENT> service_create = {'host': self.host, 'binary': self.binary, 'topic': self.topic, 'report_count': 0, 'availability_zone': 'nova'} <NEW_LINE> service_ref = {'host': self.host, 'binary': self.binary, 'topic': self.topic, 'report_count': 0, 'availability_zone': 'nova', 'id': 1} <NEW_LINE> service.db.service_get_by_args(mox.IgnoreArg(), self.host, self.binary).AndRaise(exception.NotFound()) <NEW_LINE> service.db.service_create(mox.IgnoreArg(), service_create).AndReturn(service_ref) <NEW_LINE> return service_ref <NEW_LINE> <DEDENT> def test_init_and_start_hooks(self): <NEW_LINE> <INDENT> self.manager_mock = self.mox.CreateMock(FakeManager) <NEW_LINE> self.mox.StubOutWithMock(sys.modules[__name__], 'FakeManager', use_mock_anything=True) <NEW_LINE> self.mox.StubOutWithMock(self.manager_mock, 'init_host') <NEW_LINE> self.mox.StubOutWithMock(self.manager_mock, 'pre_start_hook') <NEW_LINE> self.mox.StubOutWithMock(self.manager_mock, 'create_rpc_dispatcher') <NEW_LINE> self.mox.StubOutWithMock(self.manager_mock, 'post_start_hook') <NEW_LINE> FakeManager(host=self.host).AndReturn(self.manager_mock) <NEW_LINE> self.manager_mock.init_host() <NEW_LINE> self._service_start_mocks() <NEW_LINE> self.manager_mock.pre_start_hook() <NEW_LINE> self.manager_mock.create_rpc_dispatcher() <NEW_LINE> self.manager_mock.post_start_hook() <NEW_LINE> self.mox.ReplayAll() <NEW_LINE> serv = service.Service(self.host, self.binary, self.topic, 'nova.tests.test_service.FakeManager') <NEW_LINE> serv.start() <NEW_LINE> <DEDENT> def test_report_state_newly_disconnected(self): <NEW_LINE> <INDENT> self._service_start_mocks() <NEW_LINE> service.db.service_get(mox.IgnoreArg(), mox.IgnoreArg()).AndRaise(Exception()) <NEW_LINE> self.mox.ReplayAll() <NEW_LINE> serv = service.Service(self.host, self.binary, self.topic, 'nova.tests.test_service.FakeManager') <NEW_LINE> serv.start() <NEW_LINE> serv.report_state() <NEW_LINE> self.assert_(serv.model_disconnected) <NEW_LINE> <DEDENT> def test_report_state_newly_connected(self): <NEW_LINE> <INDENT> service_ref = self._service_start_mocks() <NEW_LINE> service.db.service_get(mox.IgnoreArg(), service_ref['id']).AndReturn(service_ref) <NEW_LINE> service.db.service_update(mox.IgnoreArg(), service_ref['id'], mox.ContainsKeyValue('report_count', 1)) <NEW_LINE> self.mox.ReplayAll() <NEW_LINE> serv = service.Service(self.host, self.binary, self.topic, 'nova.tests.test_service.FakeManager') <NEW_LINE> serv.start() <NEW_LINE> serv.model_disconnected = True <NEW_LINE> serv.report_state() <NEW_LINE> self.assert_(not serv.model_disconnected) | Test cases for Services | 62598fa344b2445a339b68b6 |
class OpenIdConnectBackend(ModelBackend): <NEW_LINE> <INDENT> def authenticate(self, **kwargs): <NEW_LINE> <INDENT> user = None <NEW_LINE> if not kwargs or 'sub' not in kwargs.keys(): <NEW_LINE> <INDENT> return user <NEW_LINE> <DEDENT> UserModel = get_user_model() <NEW_LINE> username = self.clean_username(kwargs['sub']) <NEW_LINE> if 'upn' in kwargs.keys(): <NEW_LINE> <INDENT> username = kwargs['upn'] <NEW_LINE> <DEDENT> openid_data = {'last_login': datetime.datetime.now()} <NEW_LINE> if 'first_name' in kwargs.keys(): <NEW_LINE> <INDENT> openid_data['first_name'] = kwargs['first_name'] <NEW_LINE> <DEDENT> if 'given_name' in kwargs.keys(): <NEW_LINE> <INDENT> openid_data['first_name'] = kwargs['given_name'] <NEW_LINE> <DEDENT> if 'christian_name' in kwargs.keys(): <NEW_LINE> <INDENT> openid_data['first_name'] = kwargs['christian_name'] <NEW_LINE> <DEDENT> if 'family_name' in kwargs.keys(): <NEW_LINE> <INDENT> openid_data['last_name'] = kwargs['family_name'] <NEW_LINE> <DEDENT> if 'last_name' in kwargs.keys(): <NEW_LINE> <INDENT> openid_data['last_name'] = kwargs['last_name'] <NEW_LINE> <DEDENT> if 'email' in kwargs.keys(): <NEW_LINE> <INDENT> openid_data['email'] = kwargs['email'] <NEW_LINE> <DEDENT> if getattr(settings, 'OIDC_CREATE_UNKNOWN_USER', True): <NEW_LINE> <INDENT> args = {UserModel.USERNAME_FIELD: username, 'defaults': openid_data, } <NEW_LINE> user, created = UserModel.objects.update_or_create(**args) <NEW_LINE> if created: <NEW_LINE> <INDENT> user = self.configure_user(user) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = UserModel.objects.get_by_natural_key(username) <NEW_LINE> <DEDENT> except UserModel.DoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> return user <NEW_LINE> <DEDENT> def clean_username(self, username): <NEW_LINE> <INDENT> return username <NEW_LINE> <DEDENT> def configure_user(self, user): <NEW_LINE> <INDENT> return user | This backend checks a previously performed OIDC authentication.
If it is OK and the user already exists in the database, it is returned.
If it is OK and user does not exist in the database, it is created and returned unless setting
OIDC_CREATE_UNKNOWN_USER is False.
In all other cases, None is returned. | 62598fa3097d151d1a2c0ebc |
class TypedSYMbolReference(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'component_type': 'str', 'symbol_ref': 'str' } <NEW_LINE> self.attribute_map = { 'component_type': 'componentType', 'symbol_ref': 'symbolRef' } <NEW_LINE> self._component_type = None <NEW_LINE> self._symbol_ref = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def component_type(self): <NEW_LINE> <INDENT> return self._component_type <NEW_LINE> <DEDENT> @component_type.setter <NEW_LINE> def component_type(self, component_type): <NEW_LINE> <INDENT> allowed_values = ["unknown", "fan", "battery", "powerSupply", "thermalSensor", "esm", "ups", "minihub", "gbic", "sfp", "interconnectCru", "supportCru", "alarm", "hostboard", "icSasExpander", "hostIoCard", "cacheBackupDevice", "cacheMemDimm", "procMemDimm", "channelPort", "drive", "controller", "ethernetInterface", "fibreInterface", "ibInterface", "iscsiInterface", "sasInterface", "tray", "storageArray", "drawer", "__UNDEFINED"] <NEW_LINE> if component_type not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `component_type`, must be one of {0}" .format(allowed_values) ) <NEW_LINE> <DEDENT> self._component_type = component_type <NEW_LINE> <DEDENT> @property <NEW_LINE> def symbol_ref(self): <NEW_LINE> <INDENT> return self._symbol_ref <NEW_LINE> <DEDENT> @symbol_ref.setter <NEW_LINE> def symbol_ref(self, symbol_ref): <NEW_LINE> <INDENT> self._symbol_ref = symbol_ref <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> if self is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if self is None or other is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> 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. | 62598fa39c8ee823130400b7 |
class Formatter(logging.Formatter): <NEW_LINE> <INDENT> def format(self, record): <NEW_LINE> <INDENT> style = '' <NEW_LINE> if record.levelno == logging.ERROR: <NEW_LINE> <INDENT> style = colorama.Fore.RED + colorama.Style.BRIGHT <NEW_LINE> <DEDENT> elif record.levelno == logging.WARNING: <NEW_LINE> <INDENT> style = colorama.Fore.YELLOW + colorama.Style.BRIGHT <NEW_LINE> <DEDENT> elif record.levelno == logging.INFO: <NEW_LINE> <INDENT> style = colorama.Fore.BLUE <NEW_LINE> <DEDENT> elif record.levelno == logging.DEBUG: <NEW_LINE> <INDENT> style = colorama.Fore.CYAN + colorama.Style.DIM <NEW_LINE> <DEDENT> return style + super(Formatter, self).format(record) | Caterpillar logging formatter.
Adds color to the logged information. | 62598fa30a50d4780f70526c |
class UnassignIpv6AddressesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.NetworkInterfaceId = None <NEW_LINE> self.Ipv6Addresses = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.NetworkInterfaceId = params.get("NetworkInterfaceId") <NEW_LINE> if params.get("Ipv6Addresses") is not None: <NEW_LINE> <INDENT> self.Ipv6Addresses = [] <NEW_LINE> for item in params.get("Ipv6Addresses"): <NEW_LINE> <INDENT> obj = Ipv6Address() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Ipv6Addresses.append(obj) | UnassignIpv6Addresses请求参数结构体
| 62598fa3d7e4931a7ef3bf2b |
class _NumberedMarginTokenCache(dict): <NEW_LINE> <INDENT> def __missing__(self, key): <NEW_LINE> <INDENT> width, line_number = key <NEW_LINE> if line_number is not None: <NEW_LINE> <INDENT> tokens = [(Token.LineNumber, u'%%%si ' % width % (line_number + 1))] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tokens = [(Token.LineNumber, ' ' * (width + 1))] <NEW_LINE> <DEDENT> self[key] = tokens <NEW_LINE> return tokens | Cache for numbered margins.
Maps (width, line_number) to a list of tokens. | 62598fa3ac7a0e7691f7239c |
class MovingAverage(Baseline): <NEW_LINE> <INDENT> def __init__(self,config,b=0.4): <NEW_LINE> <INDENT> self.meanRewards = np.zeros(config.max_length) <NEW_LINE> self.b = b <NEW_LINE> self.max_length = config.max_length <NEW_LINE> <DEDENT> def fit(self,rewards): <NEW_LINE> <INDENT> pad = self.max_length - len(rewards) <NEW_LINE> meanRewards = np.pad(rewards,(0,pad),'constant',constant_values=(0)) <NEW_LINE> self.meanRewards = (1-self.b)*self.meanRewards + self.b*meanRewards <NEW_LINE> <DEDENT> def predict(self,trajs): <NEW_LINE> <INDENT> if np.size(np.shape(trajs["reward"]))>1: <NEW_LINE> <INDENT> r = [] <NEW_LINE> for le in trajs["length"]: <NEW_LINE> <INDENT> b = self.meanRewards[:le] <NEW_LINE> pad = self.max_length - le <NEW_LINE> b = np.pad(b,(0,pad),'constant',constant_values=(0)) <NEW_LINE> r.append(b) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> r = self.meanRewards <NEW_LINE> <DEDENT> return r | time-dependent moving average baseline | 62598fa397e22403b383ad9d |
class AccountErrorsModule(UIModule): <NEW_LINE> <INDENT> def render(self, errors): <NEW_LINE> <INDENT> return self.render_string("modules/account/errors.html", errors=errors) | エラー処理用のモジュール
| 62598fa3fbf16365ca793f4d |
class ConnectionSharedKeyResult(Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': 'str'}, } <NEW_LINE> def __init__(self, *, value: str=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(ConnectionSharedKeyResult, self).__init__(**kwargs) <NEW_LINE> self.value = value | Response for CheckConnectionSharedKey Api servive call.
:param value: The virtual network connection shared key value
:type value: str | 62598fa38da39b475be03072 |
class Failed(FinalReply): <NEW_LINE> <INDENT> def __init__(self, document): <NEW_LINE> <INDENT> AsyncReply.__init__(self, document) <NEW_LINE> reply = Return(document.result) <NEW_LINE> self.exval = RemoteException.instance(reply) <NEW_LINE> self.xmodule = reply.xmodule, <NEW_LINE> self.xclass = reply.xclass <NEW_LINE> self.xstate = reply.xstate <NEW_LINE> self.xargs = reply.xargs <NEW_LINE> <DEDENT> def throw(self): <NEW_LINE> <INDENT> raise self.exval <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> s = list() <NEW_LINE> s.append(AsyncReply.__unicode__(self)) <NEW_LINE> s.append(' exval: %s' % unicode(self.exval)) <NEW_LINE> s.append(' xmodule: %s' % self.xmodule) <NEW_LINE> s.append(' xclass: %s' % self.xclass) <NEW_LINE> s.append(' xstate: %s' % self.xstate) <NEW_LINE> s.append(' xargs: %s' % self.xargs) <NEW_LINE> return '\n'.join(s) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return utf8(self) | Failed reply to asynchronous operation. This reply
indicates an exception was raised.
:ivar exval: The returned exception.
:type exval: object
:see: Failed.throw | 62598fa3656771135c489515 |
class CmdGive(MuxCommand): <NEW_LINE> <INDENT> key = "give" <NEW_LINE> locks = "cmd:all()" <NEW_LINE> def func(self): <NEW_LINE> <INDENT> caller = self.caller <NEW_LINE> if not self.args or not self.rhs: <NEW_LINE> <INDENT> caller.msg("Usage: give <inventory object> = <target>") <NEW_LINE> return <NEW_LINE> <DEDENT> to_give = caller.search(self.lhs) <NEW_LINE> target = caller.search(self.rhs) <NEW_LINE> if not (to_give and target): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if target == caller: <NEW_LINE> <INDENT> caller.msg("You keep %s to yourself." % to_give.key) <NEW_LINE> return <NEW_LINE> <DEDENT> if not to_give.location == caller: <NEW_LINE> <INDENT> caller.msg("You are not holding %s." % to_give.key) <NEW_LINE> return <NEW_LINE> <DEDENT> caller.msg("You give %s to %s." % (to_give.key, target.key)) <NEW_LINE> to_give.move_to(target, quiet=True) <NEW_LINE> target.msg("%s gives you %s." % (caller.key, to_give.key)) | give away something to someone
Usage:
give <inventory obj> = <target>
Gives an items from your inventory to another character,
placing it in their inventory. | 62598fa32c8b7c6e89bd3657 |
@benchmark.Owner(emails=['yukishiino@chromium.org', 'bashi@chromium.org', 'haraken@chromium.org']) <NEW_LINE> class DromaeoJslibAttrJquery(_BaseDromaeoBenchmark): <NEW_LINE> <INDENT> tag = 'jslibattrjquery' <NEW_LINE> query_param = 'jslib-attr-jquery' <NEW_LINE> @classmethod <NEW_LINE> def Name(cls): <NEW_LINE> <INDENT> return 'dromaeo.jslibattrjquery' | Dromaeo JSLib attr jquery JavaScript benchmark.
Tests setting and getting DOM node attributes using the jQuery JavaScript
Library. | 62598fa30c0af96317c56213 |
class S3EventActivityModel(S3Model): <NEW_LINE> <INDENT> names = ["event_activity"] <NEW_LINE> def model(self): <NEW_LINE> <INDENT> if not current.deployment_settings.has_module("project"): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> tablename = "event_activity" <NEW_LINE> table = self.define_table(tablename, self.event_event_id(empty=False), self.project_activity_id(empty=False), *s3_meta_fields()) <NEW_LINE> return dict() | Link Activities to Events | 62598fa391f36d47f2230deb |
class use_field_name_or_array(object): <NEW_LINE> <INDENT> def __init__(self, at_element): <NEW_LINE> <INDENT> self._at = at_element <NEW_LINE> <DEDENT> def __call__(self, func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def _wrapped(grid, vals, *args, **kwds): <NEW_LINE> <INDENT> if isinstance(vals, six.string_types): <NEW_LINE> <INDENT> vals = grid[self._at][vals] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> vals = np.asarray(vals).flatten() <NEW_LINE> <DEDENT> return func(grid, vals, *args, **kwds) <NEW_LINE> <DEDENT> return _wrapped | Decorate a function so that it accepts a field name or array.
Parameters
----------
func : function
A function that accepts a grid and array as arguments.
at_element : str
The element type that the field is defined on ('node', 'cell',
etc.)
Returns
-------
func
A wrapped function that accepts a grid and either a field name or
a numpy array.
Examples
--------
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5), spacing=(1, 2))
>>> def my_func(grid, vals):
... return grid.area_of_cell * vals
>>> my_func(grid, np.arange(grid.number_of_cells))
array([ 0., 2., 4., 6., 8., 10.])
Decorate the function so that the second argument can be array-like or
the name of a field contained withing the grid. The decorator takes a
single argument that is the name (as a `str`) of the grid element that
the values are defined on ("node", "cell", etc.).
>>> from landlab.utils.decorators import use_field_name_or_array
>>> @use_field_name_or_array('cell')
... def my_func(grid, vals):
... return grid.area_of_cell * vals
The array of values now can be list or anything that can be converted to
a numpy array.
>>> my_func(grid, [0, 1, 2, 3, 4, 5])
array([ 0., 2., 4., 6., 8., 10.])
The array of values doesn't have to be flat.
>>> vals = np.array([[0, 1, 2], [3, 4, 5]])
>>> my_func(grid, vals)
array([ 0., 2., 4., 6., 8., 10.])
The array of values can be a field name.
>>> _ = grid.add_field('cell', 'elevation', [0, 1, 2, 3, 4, 5])
>>> my_func(grid, 'elevation')
array([ 0., 2., 4., 6., 8., 10.]) | 62598fa324f1403a926857fc |
class UserResource(BaseResource, UserMixin): <NEW_LINE> <INDENT> __mts_route__ = [('/r/users', 'list')] <NEW_LINE> preparer = FieldsPreparer(fields={ 'id': 'id', 'email': 'email', }) <NEW_LINE> @gen.coroutine <NEW_LINE> def create(self): <NEW_LINE> <INDENT> u = User( email=self.r_handler.json_args.get('email'), password=self.runtime.hasher(self.r_handler.json_args.get('password')), ) <NEW_LINE> obj = u.to_dict() <NEW_LINE> ret = yield gen.Task(self.r_handler.wait_for_result, user.create_new_user.si(obj).delay()) <NEW_LINE> self.login_user(ret) <NEW_LINE> raise gen.Return(ret) <NEW_LINE> <DEDENT> def detail_list(self): <NEW_LINE> <INDENT> self.send_error(404) | User resource | 62598fa36e29344779b004ee |
class BotApprover(Verifier): <NEW_LINE> <INDENT> async def verify_member(self, ctx): <NEW_LINE> <INDENT> if ctx.member.bot: <NEW_LINE> <INDENT> ctx.add_approval_reason( 'User is an OAuth2 bot that can only be manually added.') | A override level verifier that approves other bots. | 62598fa3be383301e025368a |
class MessagesView(LoginRequiredMixin, View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> from_messages = user.from_messages.exclude(banned=True).order_by('-created_at') <NEW_LINE> to_messages = user.to_messages.exclude(banned=True).order_by('-created_at') <NEW_LINE> ctx = { 'from_messages': from_messages, 'to_messages': to_messages, } <NEW_LINE> return render(request, 'twitter/messages.html', ctx) | Display user messages | 62598fa356b00c62f0fb2744 |
class ReorderSourceFilter(Baserequests): <NEW_LINE> <INDENT> def __init__(self, sourceName, filterName, newIndex): <NEW_LINE> <INDENT> Baserequests.__init__(self) <NEW_LINE> self.name = 'ReorderSourceFilter' <NEW_LINE> self.dataout['sourceName'] = sourceName <NEW_LINE> self.dataout['filterName'] = filterName <NEW_LINE> self.dataout['newIndex'] = newIndex | Move a filter in the chain (absolute index positioning)
:Arguments:
*sourceName*
type: String
Name of the source to which the filter belongs
*filterName*
type: String
Name of the filter to reorder
*newIndex*
type: Integer
Desired position of the filter in the chain | 62598fa330dc7b766599f6e0 |
class FilterOperator(object): <NEW_LINE> <INDENT> Equals = 0 <NEW_LINE> IsNull = 1 <NEW_LINE> GreaterThan = 2 <NEW_LINE> LessThan = 3 <NEW_LINE> GreaterThanOrEqual = 4 <NEW_LINE> LessThanOrEqual = 5 <NEW_LINE> Like = 6 <NEW_LINE> Not = 7 <NEW_LINE> Between = 8 <NEW_LINE> InList = 9 <NEW_LINE> And = 10 <NEW_LINE> Or = 11 <NEW_LINE> Cast = 12 <NEW_LINE> InView = 13 <NEW_LINE> OfType = 14 <NEW_LINE> RelatedTo = 15 <NEW_LINE> BitwiseAnd = 16 <NEW_LINE> BitwiseOr = 17 | :ivar Equals:
:vartype Equals: 0
:ivar IsNull:
:vartype IsNull: 1
:ivar GreaterThan:
:vartype GreaterThan: 2
:ivar LessThan:
:vartype LessThan: 3
:ivar GreaterThanOrEqual:
:vartype GreaterThanOrEqual: 4
:ivar LessThanOrEqual:
:vartype LessThanOrEqual: 5
:ivar Like:
:vartype Like: 6
:ivar Not:
:vartype Not: 7
:ivar Between:
:vartype Between: 8
:ivar InList:
:vartype InList: 9
:ivar And:
:vartype And: 10
:ivar Or:
:vartype Or: 11
:ivar Cast:
:vartype Cast: 12
:ivar InView:
:vartype InView: 13
:ivar OfType:
:vartype OfType: 14
:ivar RelatedTo:
:vartype RelatedTo: 15
:ivar BitwiseAnd:
:vartype BitwiseAnd: 16
:ivar BitwiseOr:
:vartype BitwiseOr: 17 | 62598fa3097d151d1a2c0ebe |
class ServiceList(_kuber_definitions.Collection): <NEW_LINE> <INDENT> def __init__( self, items: typing.List["Service"] = None, metadata: "ListMeta" = None, ): <NEW_LINE> <INDENT> super(ServiceList, self).__init__(api_version="core/v1", kind="ServiceList") <NEW_LINE> self._properties = { "items": items if items is not None else [], "metadata": metadata if metadata is not None else ListMeta(), } <NEW_LINE> self._types = { "apiVersion": (str, None), "items": (list, Service), "kind": (str, None), "metadata": (ListMeta, None), } <NEW_LINE> <DEDENT> @property <NEW_LINE> def items(self) -> typing.List["Service"]: <NEW_LINE> <INDENT> return typing.cast( typing.List["Service"], self._properties.get("items"), ) <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items(self, value: typing.Union[typing.List["Service"], typing.List[dict]]): <NEW_LINE> <INDENT> cleaned: typing.List[Service] = [] <NEW_LINE> for item in value: <NEW_LINE> <INDENT> if isinstance(item, dict): <NEW_LINE> <INDENT> item = typing.cast( Service, Service().from_dict(item), ) <NEW_LINE> <DEDENT> cleaned.append(typing.cast(Service, item)) <NEW_LINE> <DEDENT> self._properties["items"] = cleaned <NEW_LINE> <DEDENT> @property <NEW_LINE> def metadata(self) -> "ListMeta": <NEW_LINE> <INDENT> return typing.cast( "ListMeta", self._properties.get("metadata"), ) <NEW_LINE> <DEDENT> @metadata.setter <NEW_LINE> def metadata(self, value: typing.Union["ListMeta", dict]): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> value = typing.cast( ListMeta, ListMeta().from_dict(value), ) <NEW_LINE> <DEDENT> self._properties["metadata"] = value <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_resource_api( api_client: client.ApiClient = None, **kwargs ) -> "client.CoreV1Api": <NEW_LINE> <INDENT> if api_client: <NEW_LINE> <INDENT> kwargs["apl_client"] = api_client <NEW_LINE> <DEDENT> return client.CoreV1Api(**kwargs) <NEW_LINE> <DEDENT> def __enter__(self) -> "ServiceList": <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> return False | ServiceList holds a list of services. | 62598fa30a50d4780f70526e |
class Group(DeclarativeBase): <NEW_LINE> <INDENT> __tablename__ = 'tg_group' <NEW_LINE> group_id = Column(Integer, autoincrement=True, primary_key=True) <NEW_LINE> group_name = Column(Unicode(16), unique=True, nullable=False) <NEW_LINE> group_description = Column(Unicode(100), nullable=True) <NEW_LINE> codproyecto = Column(u'proyecto', Integer, ForeignKey('proyecto.codproyecto'), nullable=True ) <NEW_LINE> users = relation('User', secondary=user_group_table, backref='groups') <NEW_LINE> proyecto = relation('Proyecto', backref='roles') <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return ('<Group: name=%s>' % self.group_name).encode('utf-8') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.group_name | Group definition for :mod:`repoze.what`.
Only the ``group_name`` column is required by :mod:`repoze.what`. | 62598fa3462c4b4f79dbb89f |
class ShardingSetup(object): <NEW_LINE> <INDENT> def __init__(self, context, uniresis): <NEW_LINE> <INDENT> self._ctx = context <NEW_LINE> self._uniresis = uniresis <NEW_LINE> self._logger = context.logger_setup.logger <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def get_state_route(self): <NEW_LINE> <INDENT> fallback_path = self._ctx.config.uuid_path <NEW_LINE> setup = self._ctx.config.sharding <NEW_LINE> uuid, path = yield self._get_route( setup, fallback_path, setup.state_subnode) <NEW_LINE> raise gen.Return((uuid, path)) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def get_feedback_route(self): <NEW_LINE> <INDENT> fallback_path = self._ctx.config.feedback.unicorn_path <NEW_LINE> setup = self._ctx.config.sharding <NEW_LINE> uuid, path = yield self._get_route( setup, fallback_path, setup.feedback_subnode) <NEW_LINE> raise gen.Return((uuid, path)) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def get_semaphore_route(self): <NEW_LINE> <INDENT> path = self._ctx.config.semaphore.locks_path <NEW_LINE> setup = self._ctx.config.sharding <NEW_LINE> if setup.enabled: <NEW_LINE> <INDENT> tag = yield self._get_dc_tag(setup.tag_key, setup.default_tag) <NEW_LINE> path = compose_path(setup.common_prefix, tag, setup.semaphore_subnode) <NEW_LINE> <DEDENT> raise gen.Return((None, path)) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def get_metrics_route(self): <NEW_LINE> <INDENT> fallback_path = self._ctx.config.metrics.path <NEW_LINE> setup = self._ctx.config.sharding <NEW_LINE> uuid, path = yield self._get_route( setup, fallback_path, setup.metrics_subnode) <NEW_LINE> raise gen.Return((uuid, path)) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def _get_route(self, setup, fallback_path, subnode): <NEW_LINE> <INDENT> tag_key = setup.tag_key <NEW_LINE> path = fallback_path <NEW_LINE> if setup.enabled: <NEW_LINE> <INDENT> tag = yield self._get_dc_tag(tag_key, setup.default_tag) <NEW_LINE> path = compose_path(setup.common_prefix, tag, subnode) <NEW_LINE> <DEDENT> uuid = yield self._uniresis.uuid() <NEW_LINE> path = '{}/{}'.format(path, uuid) <NEW_LINE> raise gen.Return((uuid, path)) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def _get_dc_tag(self, tag_key, default): <NEW_LINE> <INDENT> tag = default <NEW_LINE> try: <NEW_LINE> <INDENT> extra = yield self._uniresis.extra() <NEW_LINE> if not isinstance(extra, dict): <NEW_LINE> <INDENT> raise TypeError('incorrect uniresis extra field type') <NEW_LINE> <DEDENT> tag = extra.get(tag_key, default) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self._logger.debug( 'method uniresis::extra not implemented, ' 'using default tag [%s]', tag ) <NEW_LINE> <DEDENT> raise gen.Return(tag) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def uuid(self): <NEW_LINE> <INDENT> self._logger.debug( 'retrieving uuid from service %s', self._uniresis.service_name) <NEW_LINE> uuid = yield self._uniresis.uuid() <NEW_LINE> raise gen.Return(uuid) | Provides sharding environment routes. | 62598fa366656f66f7d5a283 |
class HalloweenClock: <NEW_LINE> <INDENT> def __init__(self, bot): <NEW_LINE> <INDENT> self.bot = bot <NEW_LINE> <DEDENT> @commands.command() <NEW_LINE> async def halloween(self): <NEW_LINE> <INDENT> now = datetime.datetime.now() <NEW_LINE> today = date(now.year, now.month, now.day) <NEW_LINE> year = now.year <NEW_LINE> if (now.month == 10 and now.day > 31): <NEW_LINE> <INDENT> year = now.year + 1 <NEW_LINE> <DEDENT> halloween = date(year, 10, 31) <NEW_LINE> delta = halloween - today <NEW_LINE> await self.bot.say("```" + str(delta.days) + " days left until Halloween!```") | Simple display of days left until next halloween | 62598fa3379a373c97d98ea4 |
class ConflictError: <NEW_LINE> <INDENT> def __init__(self, message=None, object=None, oid=None, serials=None, data=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_oid(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_class_name(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_old_serial(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_new_serial(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_serials(self): <NEW_LINE> <INDENT> pass | Two transactions tried to modify the same object at once.
This transaction should be resubmitted.
Instance attributes:
oid : string
the OID (8-byte packed string) of the object in conflict
class_name : string
the fully-qualified name of that object's class
message : string
a human-readable explanation of the error
serials : (string, string)
a pair of 8-byte packed strings; these are the serial numbers
related to conflict. The first is the revision of object that
is in conflict, the currently committed serial. The second is
the revision the current transaction read when it started.
data : string
The database record that failed to commit, used to put the
class name in the error message.
The caller should pass either object or oid as a keyword argument,
but not both of them. If object is passed, it should be a
persistent object with an _p_oid attribute. | 62598fa3cb5e8a47e493c0c0 |
class TypeManager(stevedore.named.NamedExtensionManager): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.drivers = {} <NEW_LINE> LOG.info(_("Configured type driver names: %s"), cfg.CONF.ml2.type_drivers) <NEW_LINE> super(TypeManager, self).__init__('neutron.ml2.type_drivers', cfg.CONF.ml2.type_drivers, invoke_on_load=True) <NEW_LINE> LOG.info(_("Loaded type driver names: %s"), self.names()) <NEW_LINE> self._register_types() <NEW_LINE> self._check_tenant_network_types(cfg.CONF.ml2.tenant_network_types) <NEW_LINE> <DEDENT> def _register_types(self): <NEW_LINE> <INDENT> for ext in self: <NEW_LINE> <INDENT> type = ext.obj.get_type() <NEW_LINE> if type in self.drivers: <NEW_LINE> <INDENT> LOG.error(_("Type driver '%(new_driver)s' ignored because type" " driver '%(old_driver)s' is already registered" " for type '%(type)s'"), {'new_driver': ext.name, 'old_driver': self.drivers[type].name, 'type': type}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.drivers[type] = ext <NEW_LINE> <DEDENT> <DEDENT> LOG.info(_("Registered types: %s"), self.drivers.keys()) <NEW_LINE> <DEDENT> def _check_tenant_network_types(self, types): <NEW_LINE> <INDENT> self.tenant_network_types = [] <NEW_LINE> for network_type in types: <NEW_LINE> <INDENT> if network_type in self.drivers: <NEW_LINE> <INDENT> self.tenant_network_types.append(network_type) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOG.error(_("No type driver for tenant network_type: %s. " "Service terminated!"), network_type) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> <DEDENT> LOG.info(_("Tenant network_types: %s"), self.tenant_network_types) <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> for type, driver in self.drivers.iteritems(): <NEW_LINE> <INDENT> LOG.info(_("Initializing driver for type '%s'"), type) <NEW_LINE> driver.obj.initialize() <NEW_LINE> <DEDENT> <DEDENT> def validate_provider_segment(self, segment): <NEW_LINE> <INDENT> network_type = segment[api.NETWORK_TYPE] <NEW_LINE> driver = self.drivers.get(network_type) <NEW_LINE> if driver: <NEW_LINE> <INDENT> driver.obj.validate_provider_segment(segment) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = _("network_type value '%s' not supported") % network_type <NEW_LINE> raise exc.InvalidInput(error_message=msg) <NEW_LINE> <DEDENT> <DEDENT> def reserve_provider_segment(self, session, segment): <NEW_LINE> <INDENT> network_type = segment.get(api.NETWORK_TYPE) <NEW_LINE> driver = self.drivers.get(network_type) <NEW_LINE> driver.obj.reserve_provider_segment(session, segment) <NEW_LINE> <DEDENT> def allocate_tenant_segment(self, session): <NEW_LINE> <INDENT> for network_type in self.tenant_network_types: <NEW_LINE> <INDENT> driver = self.drivers.get(network_type) <NEW_LINE> segment = driver.obj.allocate_tenant_segment(session) <NEW_LINE> if segment: <NEW_LINE> <INDENT> return segment <NEW_LINE> <DEDENT> <DEDENT> raise exc.NoNetworkAvailable() <NEW_LINE> <DEDENT> def release_segment(self, session, segment): <NEW_LINE> <INDENT> network_type = segment.get(api.NETWORK_TYPE) <NEW_LINE> driver = self.drivers.get(network_type) <NEW_LINE> driver.obj.release_segment(session, segment) | Manage network segment types using drivers. | 62598fa31f5feb6acb162ab5 |
class CF_spot4take5_f_Reader(Reader): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Reader.__init__(self) <NEW_LINE> <DEDENT> def get_maskname(self, filename): <NEW_LINE> <INDENT> if type(filename) == list: <NEW_LINE> <INDENT> mask_filename = [] <NEW_LINE> for elem in filename: <NEW_LINE> <INDENT> dirname = os.path.dirname(elem) <NEW_LINE> basename = os.path.basename(elem) <NEW_LINE> m_filename1 = basename[0:25]+'*_NUA.TIF' <NEW_LINE> m_filename = sorted(findfile(dirname+'/MASK/', m_filename1)) <NEW_LINE> mask_filename.append(str(m_filename[0])) <NEW_LINE> <DEDENT> <DEDENT> elif type(filename) == str: <NEW_LINE> <INDENT> dirname = os.path.dirname(elem) <NEW_LINE> basename = os.path.basename(elem) <NEW_LINE> m_filename1 = basename[0:25]+'*_NUA.TIF' <NEW_LINE> m_filename = sorted(findfile(dirname+'/MASK/', m_filename1)) <NEW_LINE> mask_filename = str(m_filename[0]) <NEW_LINE> <DEDENT> return mask_filename <NEW_LINE> <DEDENT> def get_filelist(self, input_params, settings): <NEW_LINE> <INDENT> target_date = input_params['toi'] <NEW_LINE> access_path1 = settings['dataset.'+input_params['dataset']] <NEW_LINE> pos1 = str.index(access_path1, '://') <NEW_LINE> access_path = access_path1[pos1+3:] <NEW_LINE> base_flist = [] <NEW_LINE> base_mask_flist = [] <NEW_LINE> gfp_flist = [] <NEW_LINE> gfpmask_flist = [] <NEW_LINE> base_fname_syntax = 'SPOT4_*' + target_date + '*_PENTE_*.TIF' <NEW_LINE> gfp_fname_syntax = 'SPOT4_*_PENTE_*.TIF' <NEW_LINE> base_flist = base_flist+sorted(findfile(access_path, base_fname_syntax)) <NEW_LINE> base_mask_flist = self.get_maskname(base_flist) <NEW_LINE> gfp_flist = gfp_flist+sorted(findfile(access_path, gfp_fname_syntax)) <NEW_LINE> gfp_flist = [item for item in gfp_flist if not item in base_flist] <NEW_LINE> gfpmask_flist = self.get_maskname(gfp_flist) <NEW_LINE> return base_flist, base_mask_flist, gfp_flist, gfpmask_flist <NEW_LINE> <DEDENT> def base_getcover(self, file_list, input_params, settings, temp_storage, mask): <NEW_LINE> <INDENT> pass | reader module for the spot4take5_f dataset
'_f' = means located at hard disk
'_w' = means accessible via WCS service | 62598fa3fbf16365ca793f4f |
class WebSocketConnection(WebSocketServerProtocol): <NEW_LINE> <INDENT> def onOpen(self): <NEW_LINE> <INDENT> log.info("Opened new connection") <NEW_LINE> self.protocol = ETGProtocol(self.factory.service, self.factory.simulation, Sender(self)) <NEW_LINE> self.factory.service.add_protocol(self.protocol) <NEW_LINE> <DEDENT> def onMessage(self, line, isBinary): <NEW_LINE> <INDENT> line = line.decode('utf-8') <NEW_LINE> if self.protocol.name == "": <NEW_LINE> <INDENT> if self.protocol.on_connection(line): <NEW_LINE> <INDENT> log.info("Player {name} connected", name=self.protocol.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.warn("Player connected with name {name}, but this name does not exist", name=line) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> log.debug("Got message {message}", message=line) <NEW_LINE> self.protocol.on_message(json.loads(line)) <NEW_LINE> <DEDENT> <DEDENT> def onClose(self, wasClean, code, reason): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name = self.protocol.name <NEW_LINE> self.factory.service.remove_protocol(self.protocol) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> name = "" <NEW_LINE> <DEDENT> log.info("Player {name} disconnected cleanly {clean} with code {code} and reason {reason}", name=name, clean=wasClean, code=code, reason=reason) | The class that does all the reading and writing to and from the websockets. | 62598fa3b7558d58954634c2 |
class Rotation(object): <NEW_LINE> <INDENT> def __call__(self, sample): <NEW_LINE> <INDENT> image, key_pts = sample['image'], sample['keypoints'] <NEW_LINE> image_copy = np.copy(image) <NEW_LINE> key_pts_copy = np.copy(key_pts) <NEW_LINE> image = cv2.cvtColor(image_copy, cv2.COLOR_BGR2RGB) <NEW_LINE> rows,cols,_ = image.shape <NEW_LINE> angle = random.choices([0, 45, 90,180,270],[0.4,0.2,0.2,0.1,0.1], k=1) <NEW_LINE> center = (cols/2,rows/2) <NEW_LINE> M = cv2.getRotationMatrix2D(center,angle[0],1) <NEW_LINE> image_copy = cv2.warpAffine(image,M,(cols,rows)) <NEW_LINE> theta = (angle[0]/180) * np.pi <NEW_LINE> rotMatrix = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) <NEW_LINE> center = np.array(center) <NEW_LINE> key_pts_copy -= center <NEW_LINE> key_pts_copy = key_pts_copy @ rotMatrix <NEW_LINE> key_pts_copy += center <NEW_LINE> return {'image': image_copy, 'keypoints': key_pts_copy} | Randomly rotate to 0,45,90,180,270 degrees. | 62598fa301c39578d7f12c13 |
class Message(six.text_type): <NEW_LINE> <INDENT> def __new__(cls, msgid, msgtext=None, params=None, domain='magnetodb', *args): <NEW_LINE> <INDENT> if not msgtext: <NEW_LINE> <INDENT> msgtext = Message._translate_msgid(msgid, domain) <NEW_LINE> <DEDENT> msg = super(Message, cls).__new__(cls, msgtext) <NEW_LINE> msg.msgid = msgid <NEW_LINE> msg.domain = domain <NEW_LINE> msg.params = params <NEW_LINE> return msg <NEW_LINE> <DEDENT> def translate(self, desired_locale=None): <NEW_LINE> <INDENT> translated_message = Message._translate_msgid(self.msgid, self.domain, desired_locale) <NEW_LINE> if self.params is None: <NEW_LINE> <INDENT> return translated_message <NEW_LINE> <DEDENT> translated_params = _translate_args(self.params, desired_locale) <NEW_LINE> translated_message = translated_message % translated_params <NEW_LINE> return translated_message <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _translate_msgid(msgid, domain, desired_locale=None): <NEW_LINE> <INDENT> if not desired_locale: <NEW_LINE> <INDENT> system_locale = locale.getdefaultlocale() <NEW_LINE> if not system_locale[0]: <NEW_LINE> <INDENT> desired_locale = 'en_US' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> desired_locale = system_locale[0] <NEW_LINE> <DEDENT> <DEDENT> locale_dir = os.environ.get(domain.upper() + '_LOCALEDIR') <NEW_LINE> lang = gettext.translation(domain, localedir=locale_dir, languages=[desired_locale], fallback=True) <NEW_LINE> if six.PY3: <NEW_LINE> <INDENT> translator = lang.gettext <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> translator = lang.ugettext <NEW_LINE> <DEDENT> translated_message = translator(msgid) <NEW_LINE> return translated_message <NEW_LINE> <DEDENT> def __mod__(self, other): <NEW_LINE> <INDENT> params = self._sanitize_mod_params(other) <NEW_LINE> unicode_mod = super(Message, self).__mod__(params) <NEW_LINE> modded = Message(self.msgid, msgtext=unicode_mod, params=params, domain=self.domain) <NEW_LINE> return modded <NEW_LINE> <DEDENT> def _sanitize_mod_params(self, other): <NEW_LINE> <INDENT> if other is None: <NEW_LINE> <INDENT> params = (other,) <NEW_LINE> <DEDENT> elif isinstance(other, dict): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if isinstance(self.params, dict): <NEW_LINE> <INDENT> for key, val in self.params.items(): <NEW_LINE> <INDENT> params[key] = self._copy_param(val) <NEW_LINE> <DEDENT> <DEDENT> for key, val in other.items(): <NEW_LINE> <INDENT> params[key] = self._copy_param(val) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> params = self._copy_param(other) <NEW_LINE> <DEDENT> return params <NEW_LINE> <DEDENT> def _copy_param(self, param): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return copy.deepcopy(param) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return six.text_type(param) <NEW_LINE> <DEDENT> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> msg = _('Message objects do not support addition.') <NEW_LINE> raise TypeError(msg) <NEW_LINE> <DEDENT> def __radd__(self, other): <NEW_LINE> <INDENT> return self.__add__(other) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> msg = _('Message objects do not support str() because they may ' 'contain non-ascii characters. ' 'Please use unicode() or translate() instead.') <NEW_LINE> raise UnicodeError(msg) | A Message object is a unicode object that can be translated.
Translation of Message is done explicitly using the translate() method.
For all non-translation intents and purposes, a Message is simply unicode,
and can be treated as such. | 62598fa3009cb60464d013b9 |
class UserStory22Test(unittest.TestCase): <NEW_LINE> <INDENT> def test_userStory22_1(self): <NEW_LINE> <INDENT> resultsList = userStory22("InputGedFiles/UserStory22_GED/testUserStory22-1.ged") <NEW_LINE> self.assertEqual([], resultsList) <NEW_LINE> <DEDENT> def test_userStor22_2(self): <NEW_LINE> <INDENT> resultsList = userStory22("InputGedFiles/UserStory22_GED/testUserStory22-2.ged") <NEW_LINE> self.assertEqual([], resultsList) <NEW_LINE> <DEDENT> def test_userStory22_3(self): <NEW_LINE> <INDENT> resultsList = userStory22("InputGedFiles/UserStory22_GED/testUserStory22-3.ged") <NEW_LINE> self.assertEqual([], resultsList) <NEW_LINE> <DEDENT> def test_userStory22_4(self): <NEW_LINE> <INDENT> resultsList = userStory22("InputGedFiles/UserStory22_GED/testUserStory22-4.ged") <NEW_LINE> self.maxDiff = None <NEW_LINE> self.assertEqual(["ERROR: INDIVIDUAL: US22: [27, 211]: The following are duplicate individual ID's ['I1', 'I1'].", "ERROR: FAMILY: US22: [454, 543]: The following are duplicate individual ID's ['F3', 'F12']."], resultsList) | Test the User Story 22 function | 62598fa30c0af96317c56216 |
class Convert(): <NEW_LINE> <INDENT> def __init__(self, dest_file_path, src_file_path, start_time, end_time): <NEW_LINE> <INDENT> command = self.build_command(dest_file_path, src_file_path, start_time, end_time) <NEW_LINE> print(command) <NEW_LINE> self.execute_command(command) <NEW_LINE> self.remove_original(src_file_path) <NEW_LINE> <DEDENT> def build_command(self, file_path, sub_file_path, start_time, end_time): <NEW_LINE> <INDENT> command = ('ffmpeg -i \"%s\" -ss %s -to %s -async 1 \"%s\"' %(sub_file_path, start_time, end_time, file_path)) <NEW_LINE> return command <NEW_LINE> <DEDENT> def execute_command(self, cmd): <NEW_LINE> <INDENT> proc = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) <NEW_LINE> proc.communicate() <NEW_LINE> <DEDENT> def remove_original(self, sub_file_path): <NEW_LINE> <INDENT> os.remove(sub_file_path) | Use ffmpeg to convert a media file | 62598fa324f1403a926857fd |
class TLSError(BaseTLSException): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self) | Base class for all TLS Lite exceptions. | 62598fa363d6d428bbee2646 |
class TransactionType(Enum): <NEW_LINE> <INDENT> ITEM_PURCHASE = 1 <NEW_LINE> CUSTOM_PAYMENT = 2 <NEW_LINE> ADMIN_CHANGE = 3 | Types of payment | 62598fa36e29344779b004f0 |
class ExpectimaxAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> legalActions = gameState.getLegalActions(0) <NEW_LINE> valueActionList = [(float("-inf"), None)] <NEW_LINE> for action in legalActions: <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(0, action) <NEW_LINE> value = self.ghostAvg(successor, 1, self.depth) <NEW_LINE> valueActionList.append((value, action)) <NEW_LINE> <DEDENT> pacmanAction = max(valueActionList)[1] <NEW_LINE> return pacmanAction <NEW_LINE> <DEDENT> def ghostAvg(self, gameState, ghostIndex, depth): <NEW_LINE> <INDENT> ghostActions = gameState.getLegalActions(ghostIndex) <NEW_LINE> lastGhost = gameState.getNumAgents() - 1 <NEW_LINE> avgValue = 0 <NEW_LINE> actionCount = 0 <NEW_LINE> if depth == 0 or len(ghostActions) == 0: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> for action in ghostActions: <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(ghostIndex, action) <NEW_LINE> if ghostIndex == lastGhost: <NEW_LINE> <INDENT> value = self.pacmanMax(successor, depth - 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = self.ghostAvg(successor, ghostIndex + 1, depth) <NEW_LINE> <DEDENT> avgValue += value <NEW_LINE> actionCount += 1 <NEW_LINE> <DEDENT> avgValue /= actionCount <NEW_LINE> return avgValue <NEW_LINE> <DEDENT> def pacmanMax(self, gameState, depth): <NEW_LINE> <INDENT> pacmanActions = gameState.getLegalActions(0) <NEW_LINE> valueList = [float("-inf")] <NEW_LINE> if depth == 0 or len(pacmanActions) == 0: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> for action in pacmanActions: <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(0, action) <NEW_LINE> value = self.ghostAvg(successor, 1, depth) <NEW_LINE> valueList.append(value) <NEW_LINE> <DEDENT> maxValue = max(valueList) <NEW_LINE> return maxValue | Your expectimax agent (question 4) | 62598fa356b00c62f0fb2746 |
class MainModelViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = models.MainModel.objects.all() <NEW_LINE> serializer_class = serializers.MainModelSerializer | A simple ViewSet for viewing and editing accounts. | 62598fa3e76e3b2f99fd88ca |
@public <NEW_LINE> @implementer(IAutoResponseRecord) <NEW_LINE> class AutoResponseRecord(Model): <NEW_LINE> <INDENT> __tablename__ = 'autoresponserecord' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> address_id = Column(Integer, ForeignKey('address.id'), index=True) <NEW_LINE> address = relationship('Address') <NEW_LINE> mailing_list_id = Column(Integer, ForeignKey('mailinglist.id'), index=True) <NEW_LINE> mailing_list = relationship('MailingList') <NEW_LINE> response_type = Column(Enum(Response)) <NEW_LINE> date_sent = Column(Date) <NEW_LINE> def __init__(self, mailing_list, address, response_type): <NEW_LINE> <INDENT> self.mailing_list = mailing_list <NEW_LINE> self.address = address <NEW_LINE> self.response_type = response_type <NEW_LINE> self.date_sent = today() | See `IAutoResponseRecord`. | 62598fa30a50d4780f705270 |
class MigrateSqlServerSqlDbTaskProperties(ProjectTaskProperties): <NEW_LINE> <INDENT> _validation = { 'errors': {'readonly': True}, 'state': {'readonly': True}, 'commands': {'readonly': True}, 'task_type': {'required': True}, 'output': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'errors': {'key': 'errors', 'type': '[ODataError]'}, 'state': {'key': 'state', 'type': 'str'}, 'commands': {'key': 'commands', 'type': '[CommandProperties]'}, 'task_type': {'key': 'taskType', 'type': 'str'}, 'input': {'key': 'input', 'type': 'MigrateSqlServerSqlDbTaskInput'}, 'output': {'key': 'output', 'type': '[MigrateSqlServerSqlDbTaskOutput]'}, } <NEW_LINE> def __init__(self, *, input=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(MigrateSqlServerSqlDbTaskProperties, self).__init__(**kwargs) <NEW_LINE> self.input = input <NEW_LINE> self.output = None <NEW_LINE> self.task_type = 'Migrate.SqlServer.SqlDb' | Properties for the task that migrates on-prem SQL Server databases to Azure
SQL Database.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:ivar errors: Array of errors. This is ignored if submitted.
:vartype errors: list[~azure.mgmt.datamigration.models.ODataError]
:ivar state: The state of the task. This is ignored if submitted. Possible
values include: 'Unknown', 'Queued', 'Running', 'Canceled', 'Succeeded',
'Failed', 'FailedInputValidation', 'Faulted'
:vartype state: str or ~azure.mgmt.datamigration.models.TaskState
:ivar commands: Array of command properties.
:vartype commands:
list[~azure.mgmt.datamigration.models.CommandProperties]
:param task_type: Required. Constant filled by server.
:type task_type: str
:param input: Task input
:type input:
~azure.mgmt.datamigration.models.MigrateSqlServerSqlDbTaskInput
:ivar output: Task output. This is ignored if submitted.
:vartype output:
list[~azure.mgmt.datamigration.models.MigrateSqlServerSqlDbTaskOutput] | 62598fa3aad79263cf42e674 |
class MultiBuffer: <NEW_LINE> <INDENT> def __init__(self, scoring: Callable[[T], int], items: Iterable[T] = None): <NEW_LINE> <INDENT> self._scoring = scoring <NEW_LINE> self._buffers: dict[int, list[T]] = {} <NEW_LINE> self._items_count = 0 <NEW_LINE> if items is not None: <NEW_LINE> <INDENT> self.extend(items) <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self._items_count <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return bool(len(self)) <NEW_LINE> <DEDENT> def __iter__(self) -> Iterable[tuple[int, T]]: <NEW_LINE> <INDENT> return ( (score, item) for score, items in self._buffers.items() for item in items ) <NEW_LINE> <DEDENT> def max_key(self) -> int: <NEW_LINE> <INDENT> return max(self._buffers.keys()) <NEW_LINE> <DEDENT> def min_key(self) -> int: <NEW_LINE> <INDENT> return min(self._buffers.keys()) <NEW_LINE> <DEDENT> def pop(self, index: int = -1) -> T: <NEW_LINE> <INDENT> return self.pop_max(index) <NEW_LINE> <DEDENT> def pop_max(self, index: int = -1) -> T: <NEW_LINE> <INDENT> return self.pop_by_score(self.max_key(), index) <NEW_LINE> <DEDENT> def pop_min(self, index: int = -1) -> T: <NEW_LINE> <INDENT> return self.pop_by_score(self.min_key(), index) <NEW_LINE> <DEDENT> def pop_by_score(self, score: int, index: int = -1) -> T: <NEW_LINE> <INDENT> buffer = self._buffers[score] <NEW_LINE> item = buffer.pop(index) <NEW_LINE> if not buffer: <NEW_LINE> <INDENT> del self._buffers[score] <NEW_LINE> <DEDENT> self._items_count -= 1 <NEW_LINE> return item <NEW_LINE> <DEDENT> def append(self, item: T): <NEW_LINE> <INDENT> score = self._scoring(item) <NEW_LINE> if score not in self._buffers: <NEW_LINE> <INDENT> self._buffers[score] = [] <NEW_LINE> <DEDENT> self._buffers[score].append(item) <NEW_LINE> self._items_count += 1 <NEW_LINE> <DEDENT> def extend(self, items: Iterable[T]): <NEW_LINE> <INDENT> for item in items: <NEW_LINE> <INDENT> self.append(item) | Multiple buffers by given criteria.
For example by length:
>>> mb = MultiBuffer(len)
>>> mb.append('dog')
>>> mb.extend(['cat', 'monkey', 'antelope', 'ox', 'spider'])
>>> len(mb)
6
Give me the shortest:
>>> mb.pop_min()
'ox'
>>> mb.pop_min()
'cat'
>>> len(mb)
4
Give me the longest:
>>> mb.pop_max()
'antelope'
>>> len(mb)
3
Etc ...
>>> mb.pop_min()
'dog'
>>> mb.pop_min()
'spider'
>>> len(mb)
1
>>> bool(mb)
True
>>> mb.pop_min()
'monkey'
>>> len(mb)
0
>>> bool(mb)
False | 62598fa356ac1b37e6302081 |
class ExtraDjangoSorter(DjangoSorter): <NEW_LINE> <INDENT> def _get_order_string(self): <NEW_LINE> <INDENT> return LOOKUP_SEP.join(chain(('extra_order',), self.identifiers)) <NEW_LINE> <DEDENT> def update_queryset(self, qs): <NEW_LINE> <INDENT> raise NotImplementedError | Special type of sorter that updates queryset using annotate or extra queryset method.
For this purpose must be implement updated_queryset method which returns queryset with new column
that is used for ordering. | 62598fa3cb5e8a47e493c0c1 |
class Teensy(object): <NEW_LINE> <INDENT> teensy_names = ["Teensy1", "Teensy2"] <NEW_LINE> def __init__(self, address, baud=38400): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> self.baud = baud <NEW_LINE> self.serial = None <NEW_LINE> self.name = None <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.serial = "serial.Serial(%s, %s)" % (self.address, self.baud) <NEW_LINE> result = False <NEW_LINE> response = self.teensy_names.pop() <NEW_LINE> if response.startswith("Teensy"): <NEW_LINE> <INDENT> self.name = response <NEW_LINE> logging.info("Connection to %s (%s) successful.", self.address, response) <NEW_LINE> result = True <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Teensy('%s', baud=%d)" % (self.address, self.baud) | Teensy micro-controller connection object class. | 62598fa33317a56b869be494 |
class AdvertisementOptions: <NEW_LINE> <INDENT> NO_ENCRYPTION = 0 <NEW_LINE> NULL_KEY = 1 <NEW_LINE> USER_KEY = 2 <NEW_LINE> DEVICE_KEY = 3 <NEW_LINE> _NULL_KEY = bytes(16) <NEW_LINE> _MAX_VOLTAGE_V1 = 0xFFFF <NEW_LINE> _MAX_BATTERY_LEVEL_V2 = 0xFF <NEW_LINE> _MAX_BROADCAST_ID = 7 <NEW_LINE> _MAX_UPDATE_COUNT = 31 <NEW_LINE> _MAX_ENCRYPTION_TYPE = 7 <NEW_LINE> _KEY_FLAG_MAP = { 'none': NO_ENCRYPTION, 'null': NULL_KEY, 'user': USER_KEY, 'device': DEVICE_KEY } <NEW_LINE> low_voltage = False <NEW_LINE> user_connected = False <NEW_LINE> has_data = False <NEW_LINE> voltage = 0xFFFF <NEW_LINE> robust_reports = True <NEW_LINE> fast_writes = True <NEW_LINE> battery_level = 0xFF <NEW_LINE> encryption_type = 0 <NEW_LINE> reboot_key = None <NEW_LINE> reboot_count = 0 <NEW_LINE> broadcast_id = 0 <NEW_LINE> update_count = 0 <NEW_LINE> broadcast_toggle = False <NEW_LINE> def validate_for_v1(self): <NEW_LINE> <INDENT> if self.voltage < 0 or self.voltage > self._MAX_VOLTAGE_V1: <NEW_LINE> <INDENT> raise ArgumentError("Out of range voltage for v1 advertisement: %s" % self.voltage) <NEW_LINE> <DEDENT> <DEDENT> def validate_for_v2(self): <NEW_LINE> <INDENT> if self.battery_level < 0 or self.battery_level > self._MAX_BATTERY_LEVEL_V2: <NEW_LINE> <INDENT> raise ArgumentError("Out of range battery_level for v2 advertisement: %s" % self.battery_level) <NEW_LINE> <DEDENT> self._validate_encryption_settings() <NEW_LINE> <DEDENT> def is_encrypted(self) -> bool: <NEW_LINE> <INDENT> return self.encryption_type != self.NO_ENCRYPTION <NEW_LINE> <DEDENT> def configure_encryption(self, type_: str = "none", reboot_key: Optional[bytes] = None, reboot_count: Optional[int] = None): <NEW_LINE> <INDENT> int_type = self._KEY_FLAG_MAP.get(type_) <NEW_LINE> if int_type is None: <NEW_LINE> <INDENT> raise ArgumentError("Unknown encryption type specified: %s" % type_) <NEW_LINE> <DEDENT> self.encryption_type = int_type <NEW_LINE> if reboot_count is not None: <NEW_LINE> <INDENT> self.reboot_count = reboot_count <NEW_LINE> <DEDENT> if type_ == 'none': <NEW_LINE> <INDENT> self.reboot_key = None <NEW_LINE> <DEDENT> elif type_ == 'null': <NEW_LINE> <INDENT> self.reboot_key = self._NULL_KEY <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.reboot_key = reboot_key <NEW_LINE> <DEDENT> self._validate_encryption_settings() <NEW_LINE> <DEDENT> def _validate_encryption_settings(self): <NEW_LINE> <INDENT> if self.encryption_type == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.encryption_type < 0 or self.encryption_type > self._MAX_ENCRYPTION_TYPE: <NEW_LINE> <INDENT> raise ArgumentError("Out of range encryption_type for v2 advertisement: %s" % self.encryption_type) <NEW_LINE> <DEDENT> if self.encryption_type == self.NULL_KEY and self.reboot_key != self._NULL_KEY: <NEW_LINE> <INDENT> raise ArgumentError("Invalid (non-null) encryption key specified for null encryption mode") <NEW_LINE> <DEDENT> if not isinstance(self.reboot_key, bytes) and len(self.reboot_key) != 16: <NEW_LINE> <INDENT> raise ArgumentError("Invalid reboot key specified, expected a length 16 bytes object, was: %r" % self.reboot_key) | Options to control how an advertisement is generated.
This class can be used for v1 and v2 advertisements. Not all options are
supported on both advertisement types. | 62598fa32ae34c7f260aaf76 |
class MLSDisabled(PolicyrepException): <NEW_LINE> <INDENT> pass | Exception when MLS is disabled. | 62598fa3442bda511e95c2f0 |
class SlotNotEmptyError(Error): <NEW_LINE> <INDENT> def __init__(self, slot, record, msg): <NEW_LINE> <INDENT> self.slot = slot <NEW_LINE> self.record = record <NEW_LINE> self.msg = msg | Exception raised for errors in the SlotNotEmptyError.
Attributes:
slot -- slot information
record -- explanation of the record
msg -- slot not available | 62598fa330bbd722464698c2 |
class SampledMeanBinaryCrossEntropy(DefaultDataSpecsMixin, Cost): <NEW_LINE> <INDENT> def __init__(self, L1, ratio): <NEW_LINE> <INDENT> self.random_stream = RandomStreams(seed=1) <NEW_LINE> self.L1 = L1 <NEW_LINE> self.one_ratio = ratio <NEW_LINE> <DEDENT> @wraps(Cost.expr) <NEW_LINE> def expr(self, model, data, ** kwargs): <NEW_LINE> <INDENT> self.get_data_specs(model)[0].validate(data) <NEW_LINE> X = data <NEW_LINE> X_dense = theano.sparse.dense_from_sparse(X) <NEW_LINE> noise = self.random_stream.binomial(size=X_dense.shape, n=1, prob=self.one_ratio, ndim=None) <NEW_LINE> P = noise + X_dense <NEW_LINE> P = theano.tensor.switch(P > 0, 1, 0) <NEW_LINE> P = tensor.cast(P, theano.config.floatX) <NEW_LINE> reg_units = theano.tensor.abs_(model.encode(X)).sum(axis=1).mean() <NEW_LINE> before_activation = model.reconstruct_without_dec_acti(X, P) <NEW_LINE> cost = (1 * X_dense * tensor.log(tensor.log(1 + tensor.exp(-1 * before_activation))) + (1 - X_dense) * tensor.log(1 + tensor.log(1 + tensor.exp(before_activation)))) <NEW_LINE> cost = (cost * P).sum(axis=1).mean() <NEW_LINE> cost = cost + self.L1 * reg_units <NEW_LINE> return cost | .. todo::
WRITEME properly
CE cost that goes with sparse autoencoder with L1 regularization on
activations
For theory:
Y. Dauphin, X. Glorot, Y. Bengio. ICML2011
Large-Scale Learning of Embeddings with Reconstruction Sampling
Parameters
----------
L1 : WRITEME
ratio : WRITEME | 62598fa399cbb53fe6830d69 |
class PlaylistViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = models.Playlist.objects.all() <NEW_LINE> serializer_class = serializers.PlaylistSerializer | API endpoint that allows Playlist to be viewed or edited. | 62598fa35fdd1c0f98e5de2d |
class PolynomialRecursiveNodesElementGroup(_MassMatrixQuadratureElementGroup): <NEW_LINE> <INDENT> def __init__(self, mesh_el_group, order, family, index=None): <NEW_LINE> <INDENT> super().__init__(mesh_el_group, order, index=index) <NEW_LINE> self.family = family <NEW_LINE> <DEDENT> @property <NEW_LINE> @memoize_method <NEW_LINE> def _interp_nodes(self): <NEW_LINE> <INDENT> dim = self.mesh_el_group.dim <NEW_LINE> from recursivenodes import recursive_nodes <NEW_LINE> result = recursive_nodes(dim, self.order, self.family, domain="biunit").T.copy() <NEW_LINE> dim2, _ = result.shape <NEW_LINE> assert dim2 == dim <NEW_LINE> return result <NEW_LINE> <DEDENT> def discretization_key(self): <NEW_LINE> <INDENT> return (type(self), self.dim, self.order, self.family) | Elemental discretization with a number of nodes matching the number of
polynomials in :math:`P^k`, hence usable for differentiation and
interpolation. Interpolation nodes edge-clustered for avoidance of Runge
phenomena. Depending on the *family* argument, nodes may be present on the
boundary of the simplex. See [Isaac20]_ for details.
Supports a choice of the base *family* of 1D nodes, see the documentation
of the *family* argument to :func:`recursivenodes.recursive_nodes`.
Requires :mod:`recursivenodes` to be installed.
.. [Isaac20] Tobin Isaac. Recursive, parameter-free, explicitly defined
interpolation nodes for simplices.
`Arxiv preprint <https://arxiv.org/abs/2002.09421>`__.
.. versionadded:: 2020.2 | 62598fa3fbf16365ca793f51 |
class SensorProcessedDataHeaders(Enum): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> ID = 'SENSOR_ID' <NEW_LINE> ACTIVITY = 'ACTIVITY' <NEW_LINE> START = 'START' <NEW_LINE> END = 'END' | This enumerable contains the headers (columns) of the processed sensors.csv file | 62598fa30c0af96317c56217 |
class Company(AbstractBaseModel): <NEW_LINE> <INDENT> name = models.CharField('Name', max_length=100) <NEW_LINE> about = models.TextField('About') <NEW_LINE> address = models.CharField('Address', max_length=200) <NEW_LINE> country = models.CharField('Country', max_length=100) <NEW_LINE> city = models.CharField('District', max_length=100) <NEW_LINE> state = models.CharField('State', max_length=100) <NEW_LINE> zipcode = models.CharField('Pincode / Zipcode', max_length=100) <NEW_LINE> phone_number = models.CharField('Phone Number', max_length=30) <NEW_LINE> industry_type = models.ManyToManyField(IndustryType) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name | Recruiter | 62598fa385dfad0860cbf9bf |
class SelectClause(object): <NEW_LINE> <INDENT> def __init__(self, select_items): <NEW_LINE> <INDENT> self.items = select_items <NEW_LINE> self.distinct = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def basic_items(self): <NEW_LINE> <INDENT> return SelectItemSubList(self.items, lambda item: item.is_basic) <NEW_LINE> <DEDENT> @property <NEW_LINE> def agg_items(self): <NEW_LINE> <INDENT> return SelectItemSubList(self.items, lambda item: item.is_agg) <NEW_LINE> <DEDENT> @property <NEW_LINE> def analytic_items(self): <NEW_LINE> <INDENT> return SelectItemSubList(self.items, lambda item: item.is_analytic) <NEW_LINE> <DEDENT> def __deepcopy__(self, memo): <NEW_LINE> <INDENT> other = SelectClause([deepcopy(item, memo) for item in self.items]) <NEW_LINE> other.distinct = self.distinct <NEW_LINE> return other | This encapsulates the SELECT part of a query. It is convenient to separate
non-agg items from agg items so that it is simple to know if the query
is an agg query or not. | 62598fa3627d3e7fe0e06d42 |
class STBMSAELoss(torch.nn.Module): <NEW_LINE> <INDENT> def __init__(self, spatial_weights = [1,2,5,10,30], thresholds = [20,30,40,50,80],time_weight_gap = 1, mse_w = 1,mae_w = 1): <NEW_LINE> <INDENT> super(STBMSAELoss,self).__init__() <NEW_LINE> assert len(spatial_weights) == len(thresholds) <NEW_LINE> scale = max(thresholds) <NEW_LINE> self.spatial_weights = spatial_weights <NEW_LINE> self.thresholds = [threshold/scale for threshold in thresholds] <NEW_LINE> self.time_weight_gap = time_weight_gap <NEW_LINE> self.mse_w = mse_w <NEW_LINE> self.mae_w = mae_w <NEW_LINE> <DEDENT> def forward(self,y_pre, y_true): <NEW_LINE> <INDENT> assert y_true.min() >= 0 <NEW_LINE> assert y_true.max() <= 1 <NEW_LINE> mse_loss = STBMSELoss(self.spatial_weights, self.thresholds, self.time_weight_gap).forward(y_pre, y_true) <NEW_LINE> mae_loss = STBMAELoss(self.spatial_weights, self.thresholds, self.time_weight_gap).forward(y_pre, y_true) <NEW_LINE> loss = self.mse_w * mse_loss + self.mae_w * mae_loss <NEW_LINE> return loss | func: MSE和MAE损失中给强回波处的误差更大的权重,同时将BMSE 和 BMAE按照不同权重累加起来
Parameter
---------
weights: list
default [1,2,5,10,30].权重列表,给不同的回波强度处对应的像素点的损失不同的权重
thresholds: list
阈值列表,即将回波强度按照范围分为若干段,不同段给与不同的损失权重
default [20,30,40,50,80].对应0~1之间的输入为: [0.25, 0.375, 0.5, 0.625, 1.0]
mse_w: float
mse权重, default 1
mae_w: float
mae权重, default 1 | 62598fa363d6d428bbee2647 |
class Signal(_Value): <NEW_LINE> <INDENT> def __init__(self, bits_sign=None, name=None, variable=False, reset=0, name_override=None, min=None, max=None, related=None): <NEW_LINE> <INDENT> from migen.fhdl.bitcontainer import bits_for <NEW_LINE> _Value.__init__(self) <NEW_LINE> if bits_sign is None: <NEW_LINE> <INDENT> if min is None: <NEW_LINE> <INDENT> min = 0 <NEW_LINE> <DEDENT> if max is None: <NEW_LINE> <INDENT> max = 2 <NEW_LINE> <DEDENT> max -= 1 <NEW_LINE> assert(min < max) <NEW_LINE> self.signed = min < 0 or max < 0 <NEW_LINE> self.nbits = _builtins.max(bits_for(min, self.signed), bits_for(max, self.signed)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert(min is None and max is None) <NEW_LINE> if isinstance(bits_sign, tuple): <NEW_LINE> <INDENT> self.nbits, self.signed = bits_sign <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.nbits, self.signed = bits_sign, False <NEW_LINE> <DEDENT> <DEDENT> if not isinstance(self.nbits, int) or self.nbits <= 0: <NEW_LINE> <INDENT> raise ValueError("Signal width must be a strictly positive integer") <NEW_LINE> <DEDENT> self.variable = variable <NEW_LINE> self.reset = reset <NEW_LINE> self.name_override = name_override <NEW_LINE> self.backtrace = _tracer.trace_back(name) <NEW_LINE> self.related = related <NEW_LINE> <DEDENT> def __setattr__(self, k, v): <NEW_LINE> <INDENT> if k == "reset": <NEW_LINE> <INDENT> v = wrap(v) <NEW_LINE> <DEDENT> _Value.__setattr__(self, k, v) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Signal " + (self.backtrace[-1][0] or "anonymous") + " at " + hex(id(self)) + ">" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def like(cls, other, **kwargs): <NEW_LINE> <INDENT> from migen.fhdl.bitcontainer import value_bits_sign <NEW_LINE> return cls(bits_sign=value_bits_sign(other), **kwargs) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return self.duid | A `_Value` that can change
The `Signal` object represents a value that is expected to change
in the circuit. It does exactly what Verilog's `wire` and
`reg` and VHDL's `signal` do.
A `Signal` can be indexed to access a subset of its bits. Negative
indices (`signal[-1]`) and the extended Python slicing notation
(`signal[start:stop:step]`) are supported.
The indices 0 and -1 are the least and most significant bits
respectively.
Parameters
----------
bits_sign : int or tuple
Either an integer `bits` or a tuple `(bits, signed)`
specifying the number of bits in this `Signal` and whether it is
signed (can represent negative values). `signed` defaults to
`False`.
name : str or None
Name hint for this signal. If `None` (default) the name is
inferred from the variable name this `Signal` is assigned to.
Name collisions are automatically resolved by prepending
names of objects that contain this `Signal` and by
appending integer sequences.
variable : bool
Deprecated.
reset : int
Reset (synchronous) or default (combinatorial) value.
When this `Signal` is assigned to in synchronous context and the
corresponding clock domain is reset, the `Signal` assumes the
given value. When this `Signal` is unassigned in combinatorial
context (due to conditional assignments not being taken),
the `Signal` assumes its `reset` value. Defaults to 0.
name_override : str or None
Do not use the inferred name but the given one.
min : int or None
max : int or None
If `bits_sign` is `None`, the signal bit width and signedness are
determined by the integer range given by `min` (inclusive,
defaults to 0) and `max` (exclusive, defaults to 2).
related : Signal or None | 62598fa3adb09d7d5dc0a420 |
class SearchDomainsRequest(proto.Message): <NEW_LINE> <INDENT> query = proto.Field( proto.STRING, number=1, ) <NEW_LINE> location = proto.Field( proto.STRING, number=2, ) | Request for the ``SearchDomains`` method.
Attributes:
query (str):
Required. String used to search for available
domain names.
location (str):
Required. The location. Must be in the format
``projects/*/locations/*``. | 62598fa3a8370b77170f026f |
class Window(object): <NEW_LINE> <INDENT> COLOR_ORANGE = 0 <NEW_LINE> spacing = 0 <NEW_LINE> total_columns = 0 <NEW_LINE> width = 0 <NEW_LINE> window = None <NEW_LINE> def __init__(self, refresh_interval, total_columns): <NEW_LINE> <INDENT> self.total_columns = total_columns <NEW_LINE> self.window = curses.initscr() <NEW_LINE> curses.start_color() <NEW_LINE> curses.use_default_colors() <NEW_LINE> for i in range(1, 5): <NEW_LINE> <INDENT> curses.init_pair(i, i, -1) <NEW_LINE> <DEDENT> if curses.COLORS == 256: <NEW_LINE> <INDENT> self.COLOR_ORANGE = 208 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.COLOR_ORANGE = curses.COLOR_MAGENTA <NEW_LINE> <DEDENT> curses.init_pair(self.COLOR_ORANGE, self.COLOR_ORANGE, -1) <NEW_LINE> curses.noecho() <NEW_LINE> curses.curs_set(0) <NEW_LINE> curses.halfdelay(refresh_interval) <NEW_LINE> self._update_dimensions() <NEW_LINE> <DEDENT> def _get_color(self, color_name): <NEW_LINE> <INDENT> if not color_name: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if color_name == 'ORANGE': <NEW_LINE> <INDENT> color = self.COLOR_ORANGE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> color = getattr(curses, 'COLOR_' + color_name) <NEW_LINE> <DEDENT> return curses.color_pair(color) <NEW_LINE> <DEDENT> def _update_dimensions(self): <NEW_LINE> <INDENT> _, self.width = self.window.getmaxyx() <NEW_LINE> self.spacing = self.width // self.total_columns <NEW_LINE> <DEDENT> def addstr(self, y, x, string, color_name='', bold=False): <NEW_LINE> <INDENT> color = self._get_color(color_name) <NEW_LINE> if bold: <NEW_LINE> <INDENT> color |= curses.A_BOLD <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.window.addstr(y, x, string, color) <NEW_LINE> <DEDENT> except curses.error: <NEW_LINE> <INDENT> raise RuntimeError('Terminal too small.') <NEW_LINE> <DEDENT> <DEDENT> def center(self, y, text): <NEW_LINE> <INDENT> text_length = len(text) <NEW_LINE> center = (self.width - text_length) // 2 <NEW_LINE> text_end = center + text_length <NEW_LINE> self.addstr(y, 0, ' ' * center) <NEW_LINE> self.addstr(y, center, text, bold=True) <NEW_LINE> self.addstr(y, text_end, ' ' * (self.width - text_end)) <NEW_LINE> <DEDENT> def clear_lines(self, y, lines=1): <NEW_LINE> <INDENT> for i in range(lines): <NEW_LINE> <INDENT> self.addstr(y + i, 0, ' ' * self.width) <NEW_LINE> <DEDENT> <DEDENT> def getch(self): <NEW_LINE> <INDENT> char = self.window.getch() <NEW_LINE> if char == curses.KEY_RESIZE: <NEW_LINE> <INDENT> self._update_dimensions() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return chr(char) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> def endwin(self): <NEW_LINE> <INDENT> curses.endwin() | Wrapper for the curses module. | 62598fa32c8b7c6e89bd365b |
class ItemRemoveRequest(ModelNormal): <NEW_LINE> <INDENT> allowed_values = { } <NEW_LINE> validations = { } <NEW_LINE> additional_properties_type = None <NEW_LINE> _nullable = False <NEW_LINE> @cached_property <NEW_LINE> def openapi_types(): <NEW_LINE> <INDENT> return { 'access_token': (str,), 'client_id': (str,), 'secret': (str,), } <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def discriminator(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attribute_map = { 'access_token': 'access_token', 'client_id': 'client_id', 'secret': 'secret', } <NEW_LINE> _composed_schemas = {} <NEW_LINE> required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) <NEW_LINE> @convert_js_args_to_python_args <NEW_LINE> def __init__(self, access_token, *args, **kwargs): <NEW_LINE> <INDENT> _check_type = kwargs.pop('_check_type', True) <NEW_LINE> _spec_property_naming = kwargs.pop('_spec_property_naming', False) <NEW_LINE> _path_to_item = kwargs.pop('_path_to_item', ()) <NEW_LINE> _configuration = kwargs.pop('_configuration', None) <NEW_LINE> _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) <NEW_LINE> if args: <NEW_LINE> <INDENT> raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) <NEW_LINE> <DEDENT> self._data_store = {} <NEW_LINE> self._check_type = _check_type <NEW_LINE> self._spec_property_naming = _spec_property_naming <NEW_LINE> self._path_to_item = _path_to_item <NEW_LINE> self._configuration = _configuration <NEW_LINE> self._visited_composed_classes = _visited_composed_classes + (self.__class__,) <NEW_LINE> self.access_token = access_token <NEW_LINE> for var_name, var_value in kwargs.items(): <NEW_LINE> <INDENT> if var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> setattr(self, var_name, var_value) | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values. | 62598fa3796e427e5384e62a |
class ConnectionMonitorResult(Model): <NEW_LINE> <INDENT> _validation = { 'name': {'readonly': True}, 'id': {'readonly': True}, 'type': {'readonly': True}, 'source': {'required': True}, 'destination': {'required': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'source': {'key': 'properties.source', 'type': 'ConnectionMonitorSource'}, 'destination': {'key': 'properties.destination', 'type': 'ConnectionMonitorDestination'}, 'auto_start': {'key': 'properties.autoStart', 'type': 'bool'}, 'monitoring_interval_in_seconds': {'key': 'properties.monitoringIntervalInSeconds', 'type': 'int'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, 'monitoring_status': {'key': 'properties.monitoringStatus', 'type': 'str'}, } <NEW_LINE> def __init__(self, *, source, destination, etag: str="A unique read-only string that changes whenever the resource is updated.", location: str=None, tags=None, auto_start: bool=True, monitoring_interval_in_seconds: int=60, provisioning_state=None, start_time=None, monitoring_status: str=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(ConnectionMonitorResult, self).__init__(**kwargs) <NEW_LINE> self.name = None <NEW_LINE> self.id = None <NEW_LINE> self.etag = etag <NEW_LINE> self.type = None <NEW_LINE> self.location = location <NEW_LINE> self.tags = tags <NEW_LINE> self.source = source <NEW_LINE> self.destination = destination <NEW_LINE> self.auto_start = auto_start <NEW_LINE> self.monitoring_interval_in_seconds = monitoring_interval_in_seconds <NEW_LINE> self.provisioning_state = provisioning_state <NEW_LINE> self.start_time = start_time <NEW_LINE> self.monitoring_status = monitoring_status | Information about the connection monitor.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:ivar name: Name of the connection monitor.
:vartype name: str
:ivar id: ID of the connection monitor.
:vartype id: str
:param etag: Default value: "A unique read-only string that changes
whenever the resource is updated." .
:type etag: str
:ivar type: Connection monitor type.
:vartype type: str
:param location: Connection monitor location.
:type location: str
:param tags: Connection monitor tags.
:type tags: dict[str, str]
:param source: Required.
:type source:
~azure.mgmt.network.v2017_10_01.models.ConnectionMonitorSource
:param destination: Required.
:type destination:
~azure.mgmt.network.v2017_10_01.models.ConnectionMonitorDestination
:param auto_start: Determines if the connection monitor will start
automatically once created. Default value: True .
:type auto_start: bool
:param monitoring_interval_in_seconds: Monitoring interval in seconds.
Default value: 60 .
:type monitoring_interval_in_seconds: int
:param provisioning_state: The provisioning state of the connection
monitor. Possible values include: 'Succeeded', 'Updating', 'Deleting',
'Failed'
:type provisioning_state: str or
~azure.mgmt.network.v2017_10_01.models.ProvisioningState
:param start_time: The date and time when the connection monitor was
started.
:type start_time: datetime
:param monitoring_status: The monitoring status of the connection monitor.
:type monitoring_status: str | 62598fa3eab8aa0e5d30bc1e |
class TestSorting(unittest.TestCase): <NEW_LINE> <INDENT> def test_empty(self): <NEW_LINE> <INDENT> argument = is_sorted([]) <NEW_LINE> expected = True <NEW_LINE> self.assertEqual(expected, argument, "The list is empty.") <NEW_LINE> <DEDENT> def test_running_one_item(self): <NEW_LINE> <INDENT> argument = is_sorted([5]) <NEW_LINE> expected = True <NEW_LINE> self.assertEqual(expected, argument, "The list contains two items.") <NEW_LINE> <DEDENT> def test_running_two_items(self): <NEW_LINE> <INDENT> argument = is_sorted([2, 5]) <NEW_LINE> expected = True <NEW_LINE> self.assertEqual(expected, argument, "The list contains two items.") <NEW_LINE> <DEDENT> def test_duplicate_items(self): <NEW_LINE> <INDENT> argument = is_sorted([2, 3, 3, 5]) <NEW_LINE> expected = True <NEW_LINE> self.assertEqual(expected, argument, "The list has duplicate values.") <NEW_LINE> <DEDENT> def test_not_sorted_list(self): <NEW_LINE> <INDENT> argument = is_sorted([3, 2, 5]) <NEW_LINE> expected = False <NEW_LINE> self.assertEqual(expected, argument, "The list is unsorted.") | Tests for is is_sorted. | 62598fa3e64d504609df9304 |
class EdgeType(): <NEW_LINE> <INDENT> label = 'EdgeType' <NEW_LINE> label_belongs = 'EdgeBelongsTo' <NEW_LINE> label_key = '_uniq_key' | Node describing :EdgeType in N4J | 62598fa3d6c5a102081e1fdd |
class BackToBpy(ApiNavigator, bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "api_navigator.back_to_bpy" <NEW_LINE> bl_label = "Back to bpy" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> fill_filter_mem() <NEW_LINE> if not bpy.context.window_manager.api_nav_props.path: <NEW_LINE> <INDENT> bpy.context.window_manager.api_nav_props.old_path = bpy.context.window_manager.api_nav_props.path = 'bpy' <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> bpy.context.window_manager.api_nav_props.old_path = bpy.context.window_manager.api_nav_props.path = 'bpy' <NEW_LINE> <DEDENT> update_filter() <NEW_LINE> self.generate_global_values() <NEW_LINE> self.doc_text_datablock() <NEW_LINE> return {'FINISHED'} | go back to module bpy | 62598fa34f88993c371f0455 |
class Policy: <NEW_LINE> <INDENT> def apply(self, context, global_section, patterns): <NEW_LINE> <INDENT> pass | Basic Policy skeleton. | 62598fa30a50d4780f705271 |
class AuthenticatedUserRelationshipView(APIView): <NEW_LINE> <INDENT> permission_classes = (IsAuthenticated,) <NEW_LINE> authentication_classes = (BasicAuthentication, TokenAuthentication) <NEW_LINE> def get(self, request, uuid): <NEW_LINE> <INDENT> auth_user = request.user.profile <NEW_LINE> if str(auth_user.uuid) == uuid: <NEW_LINE> <INDENT> return Response(data='The profile with the given UUID is your own.', status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> other_user = Profile.objects.get(uuid=uuid) <NEW_LINE> <DEDENT> except Profile.DoesNotExist: <NEW_LINE> <INDENT> return Response(data='No Relationship Found.', status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> site_name = Site.objects.get_current().domain <NEW_LINE> for friend in auth_user.friends: <NEW_LINE> <INDENT> if (friend.host != site_name): <NEW_LINE> <INDENT> verify_friends(friend, self.request.user.profile) <NEW_LINE> <DEDENT> <DEDENT> qs1 = UserRelationship.objects.filter(initiator=auth_user, receiver=other_user) <NEW_LINE> qs2 = UserRelationship.objects.filter(initiator=other_user, receiver=auth_user) <NEW_LINE> result = qs1 | qs2 <NEW_LINE> if result: <NEW_LINE> <INDENT> serializer = UserRelationshipSerializer(result[0]) <NEW_LINE> if serializer.is_valid: <NEW_LINE> <INDENT> return Response(data=serializer.data, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> return Response(data=serializer.errors) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response(data='No Relationship Found.', status=status.HTTP_200_OK) | returns the UserRelationship object with the current user and a specified user | 62598fa37047854f4633f26e |
class PostTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> user = User(password='potatoes', username='zach', email='zach@example.com') <NEW_LINE> user.save() <NEW_LINE> post = Post(body='The body of a post.', user=user) <NEW_LINE> post.save() <NEW_LINE> like = Like(post=post, user=user) <NEW_LINE> like.save() <NEW_LINE> dislike = Dislike(post=post, user=user) <NEW_LINE> dislike.save() <NEW_LINE> <DEDENT> def test_user_created_has_karma(self): <NEW_LINE> <INDENT> user = User.objects.get(username='zach') <NEW_LINE> self.assertEqual(user.profile.karma, 100) <NEW_LINE> self.assertEqual(user.profile.eligibility, 'Yes') <NEW_LINE> <DEDENT> def test_post_is_created_and_has_like_and_dislike(self): <NEW_LINE> <INDENT> post = Post.objects.get(id=1) <NEW_LINE> self.assertEqual(post.body, 'The body of a post.') <NEW_LINE> self.assertEqual(post.like.count(), 1) <NEW_LINE> self.assertEqual(post.dislike.count(), 1) <NEW_LINE> self.assertEqual(post.validated, 'NA') <NEW_LINE> self.assertEqual(post.like.all()[0].user.username, 'zach') | Test the post functionality. | 62598fa356ac1b37e6302082 |
class DeleteSecurityRulesResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RequestId = params.get("RequestId") | DeleteSecurityRules返回参数结构体
| 62598fa399fddb7c1ca62d33 |
class itkThinPlateR2LogRSplineKernelTransformD3(itkKernelTransformPython.itkKernelTransformD3): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> SpaceDimension = _itkThinPlateR2LogRSplineKernelTransformPython.itkThinPlateR2LogRSplineKernelTransformD3_SpaceDimension <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkThinPlateR2LogRSplineKernelTransformPython.itkThinPlateR2LogRSplineKernelTransformD3___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> __swig_destroy__ = _itkThinPlateR2LogRSplineKernelTransformPython.delete_itkThinPlateR2LogRSplineKernelTransformD3 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkThinPlateR2LogRSplineKernelTransformPython.itkThinPlateR2LogRSplineKernelTransformD3_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkThinPlateR2LogRSplineKernelTransformPython.itkThinPlateR2LogRSplineKernelTransformD3_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkThinPlateR2LogRSplineKernelTransformD3.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New) | Proxy of C++ itkThinPlateR2LogRSplineKernelTransformD3 class | 62598fa3e5267d203ee6b7a3 |
class Schema(marshmallow.Schema): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.additional_fields = kwargs.pop('fields', None) <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> if self.additional_fields: <NEW_LINE> <INDENT> self.declared_fields.update(copy.deepcopy(self.additional_fields)) <NEW_LINE> <DEDENT> self._update_fields(many=self.many) | Extends `Schema`.
This allows for dynamic creation of a schema which is needed to validate
arguments within scales. | 62598fa37047854f4633f26f |
class Frames(feature_computer.FeatureComputer): <NEW_LINE> <INDENT> def comp_feat(self, sig, rate): <NEW_LINE> <INDENT> sig = snip(sig, rate, float(self.conf['winlen']), float(self.conf['winstep'])) <NEW_LINE> if 'scipy' in self.conf and self.conf['scipy'] == 'True': <NEW_LINE> <INDENT> feat = base.frames_scipy(sig, rate, self.conf) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> feat = base.frames(sig, rate, self.conf) <NEW_LINE> <DEDENT> return feat <NEW_LINE> <DEDENT> def get_dim(self): <NEW_LINE> <INDENT> dim = int(self.conf['l']) <NEW_LINE> return dim | the feature computer class to compute frames | 62598fa355399d3f056263b9 |
class PreprocessData: <NEW_LINE> <INDENT> def preprocess(self,df): <NEW_LINE> <INDENT> df.drop(['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis=1, inplace=True) <NEW_LINE> df['label'] = df['class'].map( {'ham': 0, 'spam': 1}) <NEW_LINE> return df | Module for preprocessing data | 62598fa38a43f66fc4bf2013 |
class Function: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.result = Result(result_obj={}) <NEW_LINE> <DEDENT> def execute(self, input_result=Result(result_obj={}), globals_dict={}): <NEW_LINE> <INDENT> self.result = Result(result_obj={}) <NEW_LINE> raise Exception("This must be overriden by your implementation") | Base class for Function implementation. You need to override the execute() method and set self.result | 62598fa3d7e4931a7ef3bf31 |
class Unit(metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._health = MAX_UNIT_HEALTH <NEW_LINE> self._recharge = random.choice(UNIT_RECHARGE_RANGE) <NEW_LINE> self._next_attack_time = FIRST_ATTACK_TIME <NEW_LINE> self._armor = 0 <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def do_attack(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def take_damage(self, dmg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def calc_armor(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def get_power(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def can_attack(self): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> return now >= self._next_attack_time and self.is_alive() <NEW_LINE> <DEDENT> def is_alive(self): <NEW_LINE> <INDENT> return self._health > 0 <NEW_LINE> <DEDENT> def get_health(self): <NEW_LINE> <INDENT> return self._health <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{} has {} health'.format(self.__class__.__name__,self._health) | Abstract Unit class | 62598fa37cff6e4e811b58bd |
class SystemInstall(models.Model): <NEW_LINE> <INDENT> ip = models.CharField(max_length=20, verbose_name=u'待装机IP') <NEW_LINE> hostname = models.CharField(max_length=30, verbose_name=u'主机名') <NEW_LINE> macaddress = models.CharField(max_length=50, verbose_name=u'MAC地址') <NEW_LINE> system_version = models.CharField(max_length=20, verbose_name=u'操作系统') <NEW_LINE> install_date = models.DateTimeField(auto_now_add=True, verbose_name=u'安装时间') <NEW_LINE> profile = models.CharField(max_length=50, verbose_name=u'profile文件名') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s -- %s' %(self.ip, self.install_date) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = u'装机列表管理' | System Install Manage | 62598fa32ae34c7f260aaf77 |
class SupplierOrder(models.Model): <NEW_LINE> <INDENT> supplier = models.ForeignKey(Organization, verbose_name=_('Supplier')) <NEW_LINE> date_created = models.DateField(_("Date Created")) <NEW_LINE> order_sub_total = models.DecimalField(_("Subtotal"), max_digits=6, decimal_places=2) <NEW_LINE> order_shipping = models.DecimalField(_("Shipping"), max_digits=6, decimal_places=2) <NEW_LINE> order_tax = models.DecimalField(_("Tax"), max_digits=6, decimal_places=2) <NEW_LINE> order_notes = models.CharField(_("Notes"), max_length=200, blank=True) <NEW_LINE> order_total = models.DecimalField(_("Total"), max_digits=6, decimal_places=2) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return unicode(self.date_created) <NEW_LINE> <DEDENT> def _status(self): <NEW_LINE> <INDENT> return(self.supplierorderstatus_set.latest('date').status) <NEW_LINE> <DEDENT> status = property(_status) <NEW_LINE> def save(self, force_insert=False, force_update=False): <NEW_LINE> <INDENT> if not self.pk: <NEW_LINE> <INDENT> self.date_created = datetime.date.today() <NEW_LINE> <DEDENT> super(SupplierOrder, self).save(force_insert=force_insert, force_update=force_update) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _("Supplier Order") <NEW_LINE> verbose_name_plural = _("Supplier Orders") | An order the store owner places to a supplier for a raw good. | 62598fa3fff4ab517ebcd67b |
class mutateRow_result(object): <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRUCT, 'io', (IOError, IOError.thrift_spec), None, ), (2, TType.STRUCT, 'ia', (IllegalArgument, IllegalArgument.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, io=None, ia=None,): <NEW_LINE> <INDENT> self.io = io <NEW_LINE> self.ia = ia <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.io = IOError() <NEW_LINE> self.io.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ia = IllegalArgument() <NEW_LINE> self.ia.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('mutateRow_result') <NEW_LINE> if self.io is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('io', TType.STRUCT, 1) <NEW_LINE> self.io.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ia is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ia', TType.STRUCT, 2) <NEW_LINE> self.ia.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- io
- ia | 62598fa3d58c6744b42dc21f |
class ImportNameDeligate(qt4.QItemDelegate): <NEW_LINE> <INDENT> def __init__(self, parent, datanodes): <NEW_LINE> <INDENT> qt4.QItemDelegate.__init__(self, parent) <NEW_LINE> self.datanodes = datanodes <NEW_LINE> <DEDENT> def createEditor(self, parent, option, index): <NEW_LINE> <INDENT> w = qt4.QComboBox(parent) <NEW_LINE> w.setEditable(True) <NEW_LINE> node = index.internalPointer() <NEW_LINE> out = [] <NEW_LINE> tooltips = [] <NEW_LINE> for dn in (n for n in self.datanodes if n.toimport): <NEW_LINE> <INDENT> name = dn.name <NEW_LINE> out.append( (name, '') ) <NEW_LINE> if ( len(dn.shape) == 1 and node is not dn and dn.shape == node.shape and node.numeric and dn.numeric and name[-4:] != ' (+)' and name[-4:] != ' (-)' and name[-5:] != ' (+-)' ): <NEW_LINE> <INDENT> out.append( ('%s (+-)' % name, _("Import as symmetric error bar for '%s'" % name)) ) <NEW_LINE> out.append( ('%s (+)' % name, _("Import as positive error bar for '%s'" % name)) ) <NEW_LINE> out.append( ('%s (-)' % name, _("Import as negative error bar for '%s'" % name)) ) <NEW_LINE> <DEDENT> <DEDENT> out.sort() <NEW_LINE> last = None <NEW_LINE> i = 0 <NEW_LINE> while i < len(out): <NEW_LINE> <INDENT> if out[i] == last: <NEW_LINE> <INDENT> del out[i] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> last = out[i] <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> w.addItems([i[0] for i in out]) <NEW_LINE> for i, item in enumerate(out): <NEW_LINE> <INDENT> w.setItemData(i, item[1], qt4.Qt.ToolTipRole) <NEW_LINE> <DEDENT> return w <NEW_LINE> <DEDENT> def setEditorData(self, editor, index): <NEW_LINE> <INDENT> text = index.data(qt4.Qt.EditRole) <NEW_LINE> i = editor.findText(text) <NEW_LINE> if i != -1: <NEW_LINE> <INDENT> editor.setCurrentIndex(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> editor.setEditText(text) <NEW_LINE> <DEDENT> <DEDENT> def setModelData(self, editor, model, index): <NEW_LINE> <INDENT> model.setData(index, editor.currentText(), qt4.Qt.EditRole) <NEW_LINE> <DEDENT> def updateEditorGeometry(self, editor, option, index): <NEW_LINE> <INDENT> editor.setGeometry(option.rect) | This class is for choosing the import name. | 62598fa34428ac0f6e6583c2 |
class List2TestCase(SimTestCase): <NEW_LINE> <INDENT> _MENU = ["--propagate", "blockdev", "list"] <NEW_LINE> _POOLNAME = "deadpool" <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> command_line = ["pool", "create"] + [self._POOLNAME] + _DEVICE_STRATEGY() <NEW_LINE> RUNNER(command_line) <NEW_LINE> <DEDENT> def test_list(self): <NEW_LINE> <INDENT> command_line = self._MENU + [self._POOLNAME] <NEW_LINE> TEST_RUNNER(command_line) <NEW_LINE> <DEDENT> def test_list_empty(self): <NEW_LINE> <INDENT> command_line = self._MENU <NEW_LINE> TEST_RUNNER(command_line) <NEW_LINE> <DEDENT> def test_list_default(self): <NEW_LINE> <INDENT> command_line = self._MENU[:-1] <NEW_LINE> TEST_RUNNER(command_line) | Test listing devices in an existing pool. | 62598fa301c39578d7f12c16 |
class DiskUid(basestring): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_api_name(): <NEW_LINE> <INDENT> return "disk-uid" | Disk Unique Identifier | 62598fa3cb5e8a47e493c0c2 |
class ContactForm(forms.Form): <NEW_LINE> <INDENT> name = forms.CharField(max_length=100, label=_(u'Your name')) <NEW_LINE> email = forms.EmailField(max_length=200, label=_(u'Your email address')) <NEW_LINE> body = forms.CharField(widget=forms.Textarea, label=_(u'Your message')) <NEW_LINE> from_email = settings.DEFAULT_FROM_EMAIL <NEW_LINE> recipient_list = [mail_tuple[1] for mail_tuple in settings.MANAGERS] <NEW_LINE> subject_template_name = "contact_form/contact_form_subject.txt" <NEW_LINE> template_name = 'contact_form/contact_form.txt' <NEW_LINE> def __init__(self, data=None, files=None, request=None, recipient_list=None, *args, **kwargs): <NEW_LINE> <INDENT> if request is None: <NEW_LINE> <INDENT> raise TypeError("Keyword argument 'request' must be supplied") <NEW_LINE> <DEDENT> self.request = request <NEW_LINE> if recipient_list is not None: <NEW_LINE> <INDENT> self.recipient_list = recipient_list <NEW_LINE> <DEDENT> super(ContactForm, self).__init__(data=data, files=files, *args, **kwargs) <NEW_LINE> <DEDENT> def message(self): <NEW_LINE> <INDENT> if callable(self.template_name): <NEW_LINE> <INDENT> template_name = self.template_name() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> template_name = self.template_name <NEW_LINE> <DEDENT> return loader.render_to_string(template_name, self.get_context()) <NEW_LINE> <DEDENT> def subject(self): <NEW_LINE> <INDENT> subject = loader.render_to_string(self.subject_template_name, self.get_context()) <NEW_LINE> return ''.join(subject.splitlines()) <NEW_LINE> <DEDENT> def get_context(self): <NEW_LINE> <INDENT> if not self.is_valid(): <NEW_LINE> <INDENT> raise ValueError( "Cannot generate Context from invalid contact form" ) <NEW_LINE> <DEDENT> if Site._meta.installed: <NEW_LINE> <INDENT> site = Site.objects.get_current() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> site = RequestSite(self.request) <NEW_LINE> <DEDENT> return dict(self.cleaned_data, site=site) <NEW_LINE> <DEDENT> def get_message_dict(self): <NEW_LINE> <INDENT> if not self.is_valid(): <NEW_LINE> <INDENT> raise ValueError( "Message cannot be sent from invalid contact form" ) <NEW_LINE> <DEDENT> message_dict = {} <NEW_LINE> for message_part in ('from_email', 'message', 'recipient_list', 'subject'): <NEW_LINE> <INDENT> attr = getattr(self, message_part) <NEW_LINE> message_dict[message_part] = attr() if callable(attr) else attr <NEW_LINE> <DEDENT> return message_dict <NEW_LINE> <DEDENT> def save(self, fail_silently=False): <NEW_LINE> <INDENT> send_mail(fail_silently=fail_silently, **self.get_message_dict()) | The base contact form class from which all contact form classes
should inherit. | 62598fa397e22403b383ada3 |
class TestJobAbort(object): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> print('\n***** TestJobAbort *****') <NEW_LINE> <DEDENT> def assert_job_phase(self, jobid, phase): <NEW_LINE> <INDENT> url = '/rest/' + jobname + '/' + jobid + '/phase' <NEW_LINE> response = test_app.get(url) <NEW_LINE> assert (response.text == phase) <NEW_LINE> <DEDENT> def test_abort(self, jobid): <NEW_LINE> <INDENT> url = '/rest/' + jobname + '/' + jobid + '/phase' <NEW_LINE> post = {'PHASE': 'ABORT'} <NEW_LINE> response = test_app.post(url, post) <NEW_LINE> print(url + ' ' + str(post)) <NEW_LINE> print(' --> ' + response.status) <NEW_LINE> print(' --> ' + response.location) <NEW_LINE> assert (response.status_int == 303) <NEW_LINE> assert ('/' + jobname + '/' + jobid in response.location) <NEW_LINE> self.assert_job_phase(jobid, 'ABORTED') <NEW_LINE> jobid = create_job() <NEW_LINE> job = uws_server.Job(jobname, jobid, uws_server.User('test_', 'test_')) <NEW_LINE> job.change_status('EXECUTING') <NEW_LINE> job.storage.save(job) <NEW_LINE> print('Job phase is {}'.format(job.phase)) <NEW_LINE> url = '/rest/' + jobname + '/' + jobid + '/phase' <NEW_LINE> post = {'PHASE': 'ABORT'} <NEW_LINE> response = test_app.post(url, post) <NEW_LINE> print(url + ' ' + str(post)) <NEW_LINE> print(' --> ' + response.status) <NEW_LINE> print(' --> ' + response.location) <NEW_LINE> assert (response.status_int == 303) <NEW_LINE> assert ('/' + jobname + '/' + jobid in response.location) <NEW_LINE> self.assert_job_phase(jobid, 'ABORTED') <NEW_LINE> jobid = create_job() <NEW_LINE> job = uws_server.Job(jobname, jobid, uws_server.User('test_', 'test_')) <NEW_LINE> job.change_status('COMPLETED') <NEW_LINE> job.storage.save(job) <NEW_LINE> print('Job phase is {}'.format(job.phase)) <NEW_LINE> url = '/rest/' + jobname + '/' + jobid + '/phase' <NEW_LINE> post = {'PHASE': 'ABORT'} <NEW_LINE> response = test_app.post(url, post, status=500) <NEW_LINE> print(url + ' ' + str(post)) <NEW_LINE> print(' --> ' + response.status) <NEW_LINE> print(' --> ' + response.html.pre.string) <NEW_LINE> assert (response.status_int == 500) <NEW_LINE> self.assert_job_phase(jobid, 'COMPLETED') | Test abort command on jobs (COMPLETED jobs cannot be aborted) | 62598fa330bbd722464698c3 |
class Model(object): <NEW_LINE> <INDENT> def __init__(self, model_id, model_name, mesh, metadata=None): <NEW_LINE> <INDENT> self._model_id = model_id <NEW_LINE> self._model_name = model_name <NEW_LINE> self._mesh = mesh <NEW_LINE> if metadata is None: <NEW_LINE> <INDENT> metadata = {} <NEW_LINE> <DEDENT> self._metadata = metadata <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._model_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._model_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def mesh(self): <NEW_LINE> <INDENT> return self._mesh <NEW_LINE> <DEDENT> @property <NEW_LINE> def metadata(self): <NEW_LINE> <INDENT> return self._metadata <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return Model(self.id, self.name, self.mesh.copy(), copy.copy(self.metadata)) | A single model from a Thingiverse Thing.
| 62598fa30c0af96317c56219 |
class MasterMinion(object): <NEW_LINE> <INDENT> def __init__( self, opts, returners=True, states=True, rend=True, matcher=True, whitelist=None, ignore_config_errors=True): <NEW_LINE> <INDENT> self.opts = salt.config.minion_config( opts['conf_file'], ignore_config_errors=ignore_config_errors, role='master' ) <NEW_LINE> self.opts.update(opts) <NEW_LINE> self.whitelist = whitelist <NEW_LINE> self.opts['grains'] = salt.loader.grains(opts) <NEW_LINE> self.opts['pillar'] = {} <NEW_LINE> self.mk_returners = returners <NEW_LINE> self.mk_states = states <NEW_LINE> self.mk_rend = rend <NEW_LINE> self.mk_matcher = matcher <NEW_LINE> self.gen_modules(initial_load=True) <NEW_LINE> <DEDENT> def gen_modules(self, initial_load=False): <NEW_LINE> <INDENT> self.utils = salt.loader.utils(self.opts) <NEW_LINE> self.functions = salt.loader.minion_mods( self.opts, utils=self.utils, whitelist=self.whitelist, initial_load=initial_load) <NEW_LINE> self.serializers = salt.loader.serializers(self.opts) <NEW_LINE> if self.mk_returners: <NEW_LINE> <INDENT> self.returners = salt.loader.returners(self.opts, self.functions) <NEW_LINE> <DEDENT> if self.mk_states: <NEW_LINE> <INDENT> self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers) <NEW_LINE> <DEDENT> if self.mk_rend: <NEW_LINE> <INDENT> self.rend = salt.loader.render(self.opts, self.functions) <NEW_LINE> <DEDENT> if self.mk_matcher: <NEW_LINE> <INDENT> self.matchers = salt.loader.matchers(self.opts) <NEW_LINE> <DEDENT> self.functions['sys.reload_modules'] = self.gen_modules | Create a fully loaded minion function object for generic use on the
master. What makes this class different is that the pillar is
omitted, otherwise everything else is loaded cleanly. | 62598fa367a9b606de545e62 |
class TextGlobal: <NEW_LINE> <INDENT> defaults = {"stroke":"none", "fill":"black", "font-size":5} <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<TextGlobal %s at (%s, %s) %s>" % (repr(self.d), str(self.x), str(self.y), self.attr) <NEW_LINE> <DEDENT> def __init__(self, x, y, d, **attr): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.d = str(d) <NEW_LINE> self.attr = dict(self.defaults) <NEW_LINE> self.attr.update(attr) <NEW_LINE> <DEDENT> def SVG(self, trans=None): <NEW_LINE> <INDENT> return SVG("text", self.d, x=self.x, y=self.y, **self.attr) | Draws at text string at a specified point in global coordinates.
x, y required location of the point in global coordinates
d required text/Unicode string
attribute=value pairs keyword list SVG attributes | 62598fa385dfad0860cbf9c0 |
class WilliamsRIndicator(IndicatorMixin): <NEW_LINE> <INDENT> def __init__( self, high: pd.Series, low: pd.Series, close: pd.Series, lbp: int = 14, fillna: bool = False, ): <NEW_LINE> <INDENT> self._high = high <NEW_LINE> self._low = low <NEW_LINE> self._close = close <NEW_LINE> self._lbp = lbp <NEW_LINE> self._fillna = fillna <NEW_LINE> self._run() <NEW_LINE> <DEDENT> def _run(self): <NEW_LINE> <INDENT> min_periods = 0 if self._fillna else self._lbp <NEW_LINE> highest_high = self._high.rolling( self._lbp, min_periods=min_periods ).max() <NEW_LINE> lowest_low = self._low.rolling( self._lbp, min_periods=min_periods ).min() <NEW_LINE> self._wr = -100 * (highest_high - self._close) / (highest_high - lowest_low) <NEW_LINE> <DEDENT> def williams_r(self) -> pd.Series: <NEW_LINE> <INDENT> wr_series = self._check_fillna(self._wr, value=-50) <NEW_LINE> return pd.Series(wr_series, name="wr") | Williams %R
Developed by Larry Williams, Williams %R is a momentum indicator that is
the inverse of the Fast Stochastic Oscillator. Also referred to as %R,
Williams %R reflects the level of the close relative to the highest high
for the look-back period. In contrast, the Stochastic Oscillator reflects
the level of the close relative to the lowest low. %R corrects for the
inversion by multiplying the raw value by -100. As a result, the Fast
Stochastic Oscillator and Williams %R produce the exact same lines, only
the scaling is different. Williams %R oscillates from 0 to -100.
Readings from 0 to -20 are considered overbought. Readings from -80 to -100
are considered oversold.
Unsurprisingly, signals derived from the Stochastic Oscillator are also
applicable to Williams %R.
%R = (Highest High - Close)/(Highest High - Lowest Low) * -100
Lowest Low = lowest low for the look-back period
Highest High = highest high for the look-back period
%R is multiplied by -100 correct the inversion and move the decimal.
https://school.stockcharts.com/doku.php?id=technical_indicators:williams_r
The Williams %R oscillates from 0 to -100. When the indicator produces
readings from 0 to -20, this indicates overbought market conditions. When
readings are -80 to -100, it indicates oversold market conditions.
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
lbp(int): lookback period.
fillna(bool): if True, fill nan values with -50. | 62598fa3009cb60464d013bc |
class ProjectPluginNames(object): <NEW_LINE> <INDENT> IMAGES = "Images" <NEW_LINE> MESHES = "Meshes" <NEW_LINE> MODELS = "Models" <NEW_LINE> PATHS = "Paths" <NEW_LINE> SEGMENTATIONS = "Segmentations" <NEW_LINE> SIMULATIONS = "Simulations" <NEW_LINE> names = [ IMAGES, MESHES, MODELS, PATHS, SEGMENTATIONS, SIMULATIONS ] | This class stores the names of SV plugin categories.
| 62598fa3a8370b77170f0272 |
class Color(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'A': 'int', 'R': 'int', 'G': 'int', 'B': 'int' } <NEW_LINE> self.attributeMap = { 'A': 'A','R': 'R','G': 'G','B': 'B'} <NEW_LINE> self.A = None <NEW_LINE> self.R = None <NEW_LINE> self.G = None <NEW_LINE> self.B = None | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa3627d3e7fe0e06d43 |
class Border(object): <NEW_LINE> <INDENT> def __init__(self, use_unicode=True): <NEW_LINE> <INDENT> if use_unicode: <NEW_LINE> <INDENT> self.border_color = ANSI.fg('darkgrey') <NEW_LINE> self.color_off = ANSI.reset() <NEW_LINE> self.dash = '─' <NEW_LINE> self.thickdash = '─' <NEW_LINE> self.doubledash = '═' <NEW_LINE> self.pipe = self.border_color + '│' + self.color_off <NEW_LINE> self.junction = '┼' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.border_color = ANSI.fg('darkgrey') <NEW_LINE> self.color_off = ANSI.reset() <NEW_LINE> self.dash = '-' <NEW_LINE> self.thickdash = '-' <NEW_LINE> self.doubledash = '=' <NEW_LINE> self.pipe = self.border_color + '|' + self.color_off <NEW_LINE> self.junction = '|' | Holds border symbols.
Some unicode characters: '─' '┄' '╌' '═' '━' '─' | 62598fa338b623060ffa8f2c |
class Jabber(Channel): <NEW_LINE> <INDENT> def __init__(self, name, user_id, password, recipient_id, server, port, tls=False, ssl=True, reattempt=False): <NEW_LINE> <INDENT> super(Jabber, self).__init__(name) <NEW_LINE> self._logger = logging.getLogger(self.__class__.__name__) <NEW_LINE> self.user = user_id <NEW_LINE> self.password = password <NEW_LINE> self.server = server <NEW_LINE> self.recipient = recipient_id <NEW_LINE> self.port = port <NEW_LINE> self.tls = tls <NEW_LINE> self.ssl = ssl <NEW_LINE> self.reattempt = reattempt <NEW_LINE> <DEDENT> def notify(self, **kwargs): <NEW_LINE> <INDENT> message = kwargs.get('message') <NEW_LINE> try: <NEW_LINE> <INDENT> _ = XmppClient(self.user, self.password, self.recipient, message, self.server, self.port, self.tls, self.ssl, self.reattempt) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self._logger.exception() <NEW_LINE> return False <NEW_LINE> <DEDENT> return True | Models a channel for Jabber. | 62598fa391af0d3eaad39ca5 |
class BangoTracker(object): <NEW_LINE> <INDENT> zope.interface.implements(IMobileTracker) <NEW_LINE> def __init__(self, context, request): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.request = request <NEW_LINE> <DEDENT> def track(self, trackingId, debug): <NEW_LINE> <INDENT> referer = self.request.get_header("referer", "") <NEW_LINE> pageName = self.request["PATH_TRANSLATED"] <NEW_LINE> queryString = self.request["QUERY_STRING"] <NEW_LINE> imageSrcURL = "http://bango.net/id/111555005278.gif?page=" + pageName <NEW_LINE> if referer != "": <NEW_LINE> <INDENT> ba_referrer = "&referrer=" + urllib.urlencode({"referer":referer}) <NEW_LINE> imageSrcURL += ba_referrer <NEW_LINE> <DEDENT> img = """<img class="tracker" src="%s" alt="" height="1" width="1" />""" % imageSrcURL <NEW_LINE> return img | Bango tracking code generator.
https://bango.com
Bango inserts a hidden image which contains the page URI and referer.
Set "Page tracking code" given by Bango to mobile_properties.
Example::
<%
//********** Bango Page tracking code - JSP **********
//Specify the unique page name variable
//CHANGE THIS VALUE FOR EACH DIFFERENT PAGE YOU ADD THE CODE TO
String pageName = "example_page_title";
//Extract the referrer from the server variables
String referrer = request.getHeader("Referer");
String ba_referrer = "";
//Check to ensure there is a value in the referrer
if(referrer != null && !referrer.isEmpty())
{
ba_referrer = "&referrer=" + java.net.URLEncoder.encode(referrer, "UTF-8");
}
//Extract the query string if available
String queryString = request.getQueryString();
//Ensure pageName is URL Encoding safe
pageName = java.net.URLEncoder.encode(pageName, "UTF-8");
//Create the image source url
String imageSrcURL = "http://bango.net/id/111555005278.gif?page=" + pageName;
//Check to ensure there is a value in the referrer and add to the image source url
if(ba_referrer != null && !ba_referrer.isEmpty())
{
imageSrcURL += ba_referrer;
}
//Check to ensure there is a value in the query string and add to the image source url
if(queryString != null && !queryString.isEmpty())
{
imageSrcURL += "&" + queryString;
}
%>
<div>
<img src="<%= imageSrcURL%>" alt="" height="1" width="1" />
</div> | 62598fa3d53ae8145f918324 |
class SerialServer(): <NEW_LINE> <INDENT> def __init__(self, writerq, portT, stopEv , mailerFunc, bd = 1000000, to = None): <NEW_LINE> <INDENT> self.port = portT <NEW_LINE> self.stopEvent = stopEv <NEW_LINE> self.baudrate = bd <NEW_LINE> self.timeout = to <NEW_LINE> self.outQ = queue.Queue() <NEW_LINE> self.processor = ReadInputThread(self.outQ,writerq,mailerFunc) <NEW_LINE> self.processor.start() <NEW_LINE> <DEDENT> def serve(self): <NEW_LINE> <INDENT> with serial.Serial(port = self.port, baudrate= self.baudrate, timeout = self.timeout) as ser: <NEW_LINE> <INDENT> sleep(1) <NEW_LINE> ser.timeout = 0 <NEW_LINE> while ser.read(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> ser.timeout = self.timeout <NEW_LINE> sleep(1) <NEW_LINE> ser.write(b'|') <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.stopEvent.is_set(): <NEW_LINE> <INDENT> self.outQ.put(None) <NEW_LINE> print('\n* waiting for processor to finish...') <NEW_LINE> self.outQ.join() <NEW_LINE> break <NEW_LINE> <DEDENT> self.outQ.put(ser.read(900)) <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> self.stopEvent.set() | Implent the serving of the serial port,
reads blocks of 900 bytes, i.e. 100 structs and enqueues them for the helper thread to process | 62598fa392d797404e388ab1 |
class PGV(CaseTable, TableBase): <NEW_LINE> <INDENT> __tablename__ = 'pgv' <NEW_LINE> is_root = True <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> court_system = Column(String, enum=True) <NEW_LINE> case_description = Column(String) <NEW_LINE> case_type = Column(String, enum=True) <NEW_LINE> filing_date = Column(Date) <NEW_LINE> _filing_date_str = Column('filing_date_str',String) <NEW_LINE> case_status = Column(String, enum=True) <NEW_LINE> case = relationship('Case', backref=backref('pgv', uselist=False)) <NEW_LINE> __table_args__ = (Index('ixh_pgv_case_number', 'case_number', postgresql_using='hash'),) <NEW_LINE> @hybrid_property <NEW_LINE> def filing_date_str(self): <NEW_LINE> <INDENT> return self._filing_date_str <NEW_LINE> <DEDENT> @filing_date_str.setter <NEW_LINE> def filing_date_str(self,val): <NEW_LINE> <INDENT> self.filing_date = date_from_str(val) <NEW_LINE> self._filing_date_str = val | Prince George's County Circuit Court Civil Cases | 62598fa3dd821e528d6d8dcd |
class TestDecorator(TransactionCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.AccountAccount = self.env["account.account"] <NEW_LINE> self.AccountJournal = self.env["account.journal"] <NEW_LINE> self.user_accountant = self.env.ref("fiscal_company_base.user_accountant") <NEW_LINE> self.child_company = self.env.ref("fiscal_company_base.company_fiscal_child_1") <NEW_LINE> self.mother_company = self.env.ref("fiscal_company_base.company_fiscal_mother") <NEW_LINE> <DEDENT> def test_01_decorator_account_account(self): <NEW_LINE> <INDENT> self.user_accountant.company_id = self.child_company.id <NEW_LINE> res = self.AccountAccount.sudo(self.user_accountant).search( [("company_id", "=", self.mother_company.id)] ) <NEW_LINE> self.assertNotEqual( len(res), 0, "Searching accounts in a fiscal child company should return" " accounts of the mother company", ) <NEW_LINE> <DEDENT> def test_02_decorator_account_journal(self): <NEW_LINE> <INDENT> self.user_accountant.company_id = self.child_company.id <NEW_LINE> res = self.AccountJournal.sudo(self.user_accountant).search( [("company_id", "=", self.mother_company.id)] ) <NEW_LINE> self.assertNotEqual( len(res), 0, "Searching accounts in a fiscal child company should return" " accounts of the mother company", ) | Tests for Account Fiscal Company Module (Decorator) | 62598fa310dbd63aa1c70a48 |
class AnacondaDisableLinting(sublime_plugin.WindowCommand): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> if self.window.active_view().file_name() is not None: <NEW_LINE> <INDENT> ANACONDA['DISABLED'].append(self.window.active_view().file_name()) <NEW_LINE> <DEDENT> erase_lint_marks(self.window.active_view()) <NEW_LINE> <DEDENT> def is_enabled(self): <NEW_LINE> <INDENT> view = self.window.active_view() <NEW_LINE> if (view.file_name() in ANACONDA['DISABLED'] or not get_settings(view, 'anaconda_linting')): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> location = view.sel()[0].begin() <NEW_LINE> for lang in valid_languages(): <NEW_LINE> <INDENT> matcher = 'source.{}'.format(lang) <NEW_LINE> if view.match_selector(location, matcher) is True: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Disable the linting for the current buffer
| 62598fa3e76e3b2f99fd88ce |
class SmtpServerHarness(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setup_class(cls): <NEW_LINE> <INDENT> smtp_server = config.get('test_smtp_server') or config['smtp_server'] <NEW_LINE> if ':' in smtp_server: <NEW_LINE> <INDENT> host, port = smtp_server.split(':') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> host, port = smtp_server, 25 <NEW_LINE> <DEDENT> cls.port = port <NEW_LINE> cls.smtp_thread = MockSmtpServerThread(host, int(port)) <NEW_LINE> cls.smtp_thread.start() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def teardown_class(cls): <NEW_LINE> <INDENT> cls.smtp_thread.stop() <NEW_LINE> <DEDENT> def get_smtp_messages(self): <NEW_LINE> <INDENT> return self.smtp_thread.get_smtp_messages() <NEW_LINE> <DEDENT> def clear_smtp_messages(self): <NEW_LINE> <INDENT> return self.smtp_thread.clear_smtp_messages() | Derive from this class to run MockSMTP - a test harness that
records what email messages are requested to be sent by it. | 62598fa344b2445a339b68ba |
class CommunicationProblem(StandardError): <NEW_LINE> <INDENT> def __init__(self, proc): <NEW_LINE> <INDENT> StandardError.__init__(self) <NEW_LINE> self.proc = proc | Wrap a Process that wants to talk.
| 62598fa301c39578d7f12c18 |
class UpdatePasswordAPI(generics.GenericAPIView): <NEW_LINE> <INDENT> permission_classes = (permissions.IsAuthenticated, ) <NEW_LINE> serializer_class = ChangePasswordSerializer <NEW_LINE> def get_object(self, queryset=None): <NEW_LINE> <INDENT> return self.request.user <NEW_LINE> <DEDENT> def put(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.object = self.get_object() <NEW_LINE> serializer = ChangePasswordSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> old_password = serializer.data.get("old_password") <NEW_LINE> if not self.object.check_password(old_password): <NEW_LINE> <INDENT> return Response({"details": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> self.object.set_password(serializer.data.get("new_password")) <NEW_LINE> self.object.save() <NEW_LINE> return Response({"details":["Password Changed"]}, status=status.HTTP_204_NO_CONTENT) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | API endpoint for changing password. | 62598fa3be8e80087fbbeefa |
class EndpointInfo(DeviceInfo): <NEW_LINE> <INDENT> implements(IEndpointInfo) <NEW_LINE> adapts(Endpoint) <NEW_LINE> pool_count = RelationshipLengthProperty('pools') <NEW_LINE> host_count = RelationshipLengthProperty('hosts') <NEW_LINE> sr_count = RelationshipLengthProperty('srs') <NEW_LINE> network_count = RelationshipLengthProperty('networks') <NEW_LINE> vm_count = RelationshipLengthProperty('vms') <NEW_LINE> vmappliance_count = RelationshipLengthProperty('vmappliances') | API Info adapter factory for Datacenter. | 62598fa33539df3088ecc14d |
class EmotionPlugin(Analyser, models.EmotionPlugin): <NEW_LINE> <INDENT> minEmotionValue = 0 <NEW_LINE> maxEmotionValue = 1 <NEW_LINE> _terse_keys = Analyser._terse_keys + ['minEmotionValue', 'maxEmotionValue'] | Emotion plugins provide emotion annotation (using Onyx) | 62598fa367a9b606de545e64 |
class CallGraphNode(object): <NEW_LINE> <INDENT> def __init__(self, goal): <NEW_LINE> <INDENT> self.goal = goal <NEW_LINE> self.clear() <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.requires = set() <NEW_LINE> self.requiredby = set() <NEW_LINE> self.numrequiredby = 0 <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<CallGraphNode for {0}>".format(repr(str(self.goal))) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((CallGraphNode, self.goal)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, CallGraphNode) and self.goal == other.goal <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if self.__class__.__name__ == other.__class__.__name__: <NEW_LINE> <INDENT> return self.goal < other.goal <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__class__.__name__ < other.__class__.__name__ <NEW_LINE> <DEDENT> <DEDENT> def grow(self, table): <NEW_LINE> <INDENT> if self not in table: <NEW_LINE> <INDENT> table[self] = self <NEW_LINE> <DEDENT> if isinstance(self.goal, (histbook.expr.Const, histbook.expr.Name, histbook.expr.Predicate)): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif isinstance(self.goal, histbook.expr.Call): <NEW_LINE> <INDENT> for arg in self.goal.args: <NEW_LINE> <INDENT> if not isinstance(arg, histbook.expr.Const): <NEW_LINE> <INDENT> node = CallGraphNode(arg) <NEW_LINE> if node not in table: <NEW_LINE> <INDENT> table[node] = node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node = table[node] <NEW_LINE> <DEDENT> self.requires.add(node) <NEW_LINE> node.requiredby.add(self) <NEW_LINE> node.grow(table) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise AssertionError(repr(self.goal)) <NEW_LINE> <DEDENT> self.numrequiredby += 1 <NEW_LINE> <DEDENT> def sources(self, table): <NEW_LINE> <INDENT> if isinstance(self.goal, histbook.expr.Const): <NEW_LINE> <INDENT> return set() <NEW_LINE> <DEDENT> elif isinstance(self.goal, (histbook.expr.Name, histbook.expr.Predicate)): <NEW_LINE> <INDENT> return set([self]) <NEW_LINE> <DEDENT> elif isinstance(self.goal, histbook.expr.Call): <NEW_LINE> <INDENT> out = set() <NEW_LINE> for arg in self.goal.args: <NEW_LINE> <INDENT> if not isinstance(arg, histbook.expr.Const): <NEW_LINE> <INDENT> node = table[CallGraphNode(arg)] <NEW_LINE> out.update(node.sources(table)) <NEW_LINE> <DEDENT> <DEDENT> return out <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> <DEDENT> def rename(self, names): <NEW_LINE> <INDENT> return self.goal.rename(names) | Represents a node in a graph of dependencies among subexpressions in an :py:class:`Expr <histbook.expr.Expr>`. | 62598fa3a8ecb033258710a8 |
class ObjectCache(object): <NEW_LINE> <INDENT> def __init__(self, cfg=None, directory=None, fileformat="{dir}/{key}.tmp"): <NEW_LINE> <INDENT> self.config = cfg <NEW_LINE> self.fileformat = fileformat <NEW_LINE> if directory: <NEW_LINE> <INDENT> self.directory = directory <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.directory = cfg['cache_dir'] <NEW_LINE> <DEDENT> <DEDENT> def set(self, key, data): <NEW_LINE> <INDENT> if self.config['cache'] is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> filename = self.fileformat.format(dir=self.directory, key=hashed(key)) <NEW_LINE> pickle.dump(data, open(filename, "wb")) <NEW_LINE> return True <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filename = self.fileformat.format(dir=self.directory, key=hashed(key)) <NEW_LINE> data = pickle.load(open(filename, "rb")) <NEW_LINE> return data <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> <DEDENT> def rm(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filename = self.fileformat.format(dir=self.directory, key=hashed(key)) <NEW_LINE> os.remove(filename) <NEW_LINE> return True <NEW_LINE> <DEDENT> except (OSError, IOError): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def wipe(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for file, filepath in files_by_extension('tmp', self.directory): <NEW_LINE> <INDENT> os.remove(filepath) <NEW_LINE> <DEDENT> <DEDENT> except (OSError, IOError): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Handle caching for objects using picklet | 62598fa363d6d428bbee264b |
class MyCodec(object): <NEW_LINE> <INDENT> FORMAT = '>Hl8s' <NEW_LINE> def encode(self, is_originating, uri, args=None, kwargs=None): <NEW_LINE> <INDENT> payload = struct.pack(self.FORMAT, args[0], args[1], args[2]) <NEW_LINE> return EncodedPayload(payload, 'mqtt') <NEW_LINE> <DEDENT> def decode(self, is_originating, uri, encoded_payload): <NEW_LINE> <INDENT> return uri, struct.unpack(self.FORMAT, encoded_payload.payload), None | Our codec to encode/decode our custom binary payload. This is needed
in "payload transparency mode" (a WAMP AP / Crossbar.io feature), so
the app code is shielded, so you can write your code as usual in Autobahn/WAMP. | 62598fa307f4c71912baf2dd |
class SQLAlchemyError(Exception): <NEW_LINE> <INDENT> code = None <NEW_LINE> def __init__(self, *arg, **kw): <NEW_LINE> <INDENT> code = kw.pop("code", None) <NEW_LINE> if code is not None: <NEW_LINE> <INDENT> self.code = code <NEW_LINE> <DEDENT> super(SQLAlchemyError, self).__init__(*arg, **kw) <NEW_LINE> <DEDENT> def _code_str(self): <NEW_LINE> <INDENT> if not self.code: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ( "(Background on this error at: " "http://sqlalche.me/e/%s/%s)" % (_version_token, self.code,) ) <NEW_LINE> <DEDENT> <DEDENT> def _message(self, as_unicode=compat.py3k): <NEW_LINE> <INDENT> if len(self.args) == 1: <NEW_LINE> <INDENT> text = self.args[0] <NEW_LINE> if as_unicode and isinstance(text, compat.binary_types): <NEW_LINE> <INDENT> return compat.decode_backslashreplace(text, "utf-8") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.args[0] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return str(self.args) <NEW_LINE> <DEDENT> <DEDENT> def _sql_message(self, as_unicode): <NEW_LINE> <INDENT> message = self._message(as_unicode) <NEW_LINE> if self.code: <NEW_LINE> <INDENT> message = "%s %s" % (message, self._code_str()) <NEW_LINE> <DEDENT> return message <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._sql_message(compat.py3k) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self._sql_message(as_unicode=True) | Generic error class. | 62598fa316aa5153ce40039b |
class JSBeautifier(BeautifierBase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def _reindenting(cls, js, indent=2, srcIndent=2): <NEW_LINE> <INDENT> firstLine = js.split('\n', 1)[0] <NEW_LINE> offset = len(firstLine) - len(firstLine.lstrip()) <NEW_LINE> result = [] <NEW_LINE> lastLevel = 0 <NEW_LINE> for line in js.splitlines(): <NEW_LINE> <INDENT> extraIndent = 0 <NEW_LINE> text = line.lstrip() <NEW_LINE> currIndent = len(line) - len(text) <NEW_LINE> if currIndent < lastLevel * srcIndent + offset: <NEW_LINE> <INDENT> lastLevel = (currIndent - offset) // srcIndent <NEW_LINE> <DEDENT> elif currIndent == (lastLevel + 1) * srcIndent + offset: <NEW_LINE> <INDENT> lastLevel += 1 <NEW_LINE> <DEDENT> elif currIndent > (lastLevel + 1) * srcIndent + offset: <NEW_LINE> <INDENT> extraIndent = currIndent - offset - lastLevel * srcIndent <NEW_LINE> <DEDENT> finalIndent = offset + lastLevel * indent + extraIndent <NEW_LINE> result.append(' ' * finalIndent + text) <NEW_LINE> <DEDENT> return '\n'.join(result) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def beautify(cls, js, indent=2, encoding=None): <NEW_LINE> <INDENT> parser = slimit.parser.Parser() <NEW_LINE> tree = parser.parse(decodeText(js)) <NEW_LINE> text = tree.to_ecma() <NEW_LINE> return cls._reindenting(text, indent) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def beautifyTextInHTML(cls, html, indent=2, encoding=None): <NEW_LINE> <INDENT> return cls._findAndReplace(html, cls.reIndentAndScript, cls.beautify, (indent,), indent) | A Javascript Beautifier that pretty print Javascript | 62598fa385dfad0860cbf9c1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.