code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@registry.register_problem <NEW_LINE> class GymWrappedBreakoutRandom(GymDiscreteProblem): <NEW_LINE> <INDENT> @property <NEW_LINE> def env_name(self): <NEW_LINE> <INDENT> return "T2TBreakoutWarmUp20RewSkip500Steps-v1" <NEW_LINE> <DEDENT> @property <NEW_LINE> def min_reward(self): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_rewards(self): <NEW_LINE> <INDENT> return 3
Pong game, random actions.
625990602c8b7c6e89bd4e9a
class SetBookmark(MarkerAction): <NEW_LINE> <INDENT> name = "Set Bookmark" <NEW_LINE> default_menu = (("Tools/Bookmarks", 260), 100) <NEW_LINE> key_bindings = {'emacs': 'C-c C-b C-s'} <NEW_LINE> def action(self, index=-1, multiplier=1): <NEW_LINE> <INDENT> line = self.mode.GetCurrentLine() <NEW_LINE> self.mode.MarkerAdd(line, self.mode.bookmark_marker_number)
Set a bookmark on the current line in the buffer.
625990603539df3088ecd948
class SetupDirectories(PipelineTask): <NEW_LINE> <INDENT> def init(self,dirs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> for dirn in self.args.dirs: <NEW_LINE> <INDENT> dirn = os.path.abspath(dirn) <NEW_LINE> if os.path.exists(dirn): <NEW_LINE> <INDENT> print("%s: already exists" % dirn) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("%s: making directory" % dirn) <NEW_LINE> mkdir(dirn)
Create directories Given a list of directories, check for and if necessary create each one
6259906007f4c71912bb0ae9
class EditorItemWidget(QtGui.QWidget): <NEW_LINE> <INDENT> def __init__(self, parent=None, ei=None): <NEW_LINE> <INDENT> super(EditorItemWidget, self).__init__(parent) <NEW_LINE> self.item = ei
Wrapper class for :class:`EditorItem` so that an :class:`EditorItem` can be configured and automatically used with :class:`EditorItemDelegate`
6259906099cbb53fe683258d
class Building(): <NEW_LINE> <INDENT> def __init__(self, x_point, y_point, width, height, color): <NEW_LINE> <INDENT> self.x_point = x_point <NEW_LINE> self.y_point= y_point <NEW_LINE> self.width= width <NEW_LINE> self.height= height <NEW_LINE> self.color= color <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> pygame.draw.rect(screen, self.color, (self.x_point, self.y_point, self.width, self.height)) <NEW_LINE> <DEDENT> def move(self, speed): <NEW_LINE> <INDENT> self.x_point += speed <NEW_LINE> if self.x_point <= -50: <NEW_LINE> <INDENT> self.x_point = 810
This class will be used to create the building objects. It takes: x_point - an integer that represents where along the x-axis the building will be drawn y_point - an integer that represents where along the y-axis the building will be drawn Together the x_point and y_point represent the top, left corner of the building width - an integer that represents how wide the building will be in pixels. A positive integer draws the building right to left(->). A negative integer draws the building left to right (<-). height - an integer that represents how tall the building will be in pixels A positive integer draws the building up A negative integer draws the building down color - a tuple of three elements which represents the color of the building Each element being a number from 0 - 255 that represents how much red, green and blue the color should have. It depends on: pygame being initialized in the environment. It depends on a "screen" global variable that represents the surface where the buildings will be drawn
6259906055399d3f05627bcb
class GpsFix(object): <NEW_LINE> <INDENT> def __init__(self, timestamp=None, latitude=None, longitude=None, altitude=None, heading=None, velocity=None): <NEW_LINE> <INDENT> self.timestamp = timestamp <NEW_LINE> self.latitude = latitude <NEW_LINE> self.longitude = longitude <NEW_LINE> self.altitude = altitude <NEW_LINE> self.heading = heading <NEW_LINE> self.velocity = velocity <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "t: {}, lat: {}, lon: {}, alt: {}, hdg: {}, vel: {}" .format(self.timestamp, self.latitude, self.longitude, self.altitude, self.heading, self.velocity) <NEW_LINE> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> return OrderedDict(( ("gps_time", self.timestamp), ("latitude", self.latitude), ("longitude", self.longitude), ("altitude", self.altitude), ("heading", self.heading), ("velocity", self.velocity))) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_phidget(gps): <NEW_LINE> <INDENT> t = gps.getTime() <NEW_LINE> d = gps.getDate() <NEW_LINE> timestamp = datetime(d.year, d.month, d.day, t.hour, t.min, t.sec, t.ms * 1000) <NEW_LINE> return GpsFix(timestamp=timestamp, latitude=gps.getLatitude(), longitude=gps.getLongitude(), altitude=gps.getAltitude(), heading=wrap_exception_with_none(gps.getHeading), velocity=wrap_exception_with_none(gps.getVelocity))
Contains info from a GPS position
6259906015baa7234946363f
class Rubric(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=20, db_index=True, unique=True, verbose_name='Название') <NEW_LINE> order = models.IntegerField(default=0, db_index=True, verbose_name='Порядок') <NEW_LINE> super_rubric = models.ForeignKey('SuperRubric', on_delete=models.PROTECT, null=True, blank=True, verbose_name='Надрубрика')
Модель рубрик
62599060097d151d1a2c271b
class MapsOperationsValueItemPaged(Paged): <NEW_LINE> <INDENT> _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'str'}, 'current_page': {'key': 'value', 'type': '[MapsOperationsValueItem]'} } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(MapsOperationsValueItemPaged, self).__init__(*args, **kwargs)
A paging container for iterating over a list of :class:`MapsOperationsValueItem <azure.mgmt.maps.models.MapsOperationsValueItem>` object
62599060462c4b4f79dbd0b1
class VideoViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Video.objects.all() <NEW_LINE> serializer_class = VideoSerializer <NEW_LINE> permission_classes = (IsAuthenticatedOrReadOnly, IsSystemUserOrReadOnly, ) <NEW_LINE> filter_backends = (DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter,) <NEW_LINE> filter_class = VideoFilter <NEW_LINE> ordering_fields = ('name',) <NEW_LINE> ordering = ('name',) <NEW_LINE> search_fields = ('name',) <NEW_LINE> def update(self, request, *args, **kwargs): <NEW_LINE> <INDENT> partial = True <NEW_LINE> instance = self.get_object() <NEW_LINE> serializer = self.get_serializer(instance, data=request.data, partial=partial) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> self.perform_update(serializer) <NEW_LINE> return Response(serializer.data)
用于进行 game管理。 对应 Game 模型,通过过滤器对不同的软件提供不同的接口。 提供返回某一apk的版本,或者返回某一apk的最新版本。 只有systemuser可以增加、修改、删除apk版本信息。 其他普通用户和未登录用户只有查看权限。
625990604428ac0f6e659bdf
class hr_attendance(osv.Model): <NEW_LINE> <INDENT> _inherit = 'hr.attendance' <NEW_LINE> _columns = { 'working_id': fields.many2one( 'hr.working.template', 'Working Template', help='Working Template'), 'contract_id': fields.many2one( 'hr.contract', 'Contract', help='Contract'), }
Inherit the hr.attendance model.
62599060be8e80087fbc0732
class flea(PowerUp): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(flea, self).__init__((255,255,0), (0,0), 20, 0, pygame.image.load(os.path.join('.', 'images', 'flea.png')), 'flea') <NEW_LINE> self.sizeScale = settings.jayhawk.image.get_width() <NEW_LINE> <DEDENT> def effect(self): <NEW_LINE> <INDENT> Jayhawk.gravity_accel = 0.5 <NEW_LINE> self.sizeScale -= 5 <NEW_LINE> if(self.sizeScale < 10): <NEW_LINE> <INDENT> self.sizeScale = 10 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> settings.jayhawk.set_image(pygame.image.load(os.path.join('.', 'images', 'jayhawk.png')), (self.sizeScale, self.sizeScale)) <NEW_LINE> <DEDENT> <DEDENT> def effect_expire(self): <NEW_LINE> <INDENT> Jayhawk.gravity_accel = settings.gravity_accel <NEW_LINE> self.sizeScale += 5 <NEW_LINE> if(self.sizeScale > 60): <NEW_LINE> <INDENT> self.sizeScale = 60 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> settings.jayhawk.set_image(pygame.image.load(os.path.join('.', 'images', 'jayhawk.png')), (self.sizeScale, self.sizeScale))
You become a flea and jump really high
62599060379a373c97d9a6d0
class GKEStartPodOperator(KubernetesPodOperator): <NEW_LINE> <INDENT> template_fields = {'project_id', 'location', 'cluster_name'} | set(KubernetesPodOperator.template_fields) <NEW_LINE> @apply_defaults <NEW_LINE> def __init__( self, *, location: str, cluster_name: str, use_internal_ip: bool = False, project_id: Optional[str] = None, gcp_conn_id: str = 'google_cloud_default', **kwargs, ) -> None: <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.project_id = project_id <NEW_LINE> self.location = location <NEW_LINE> self.cluster_name = cluster_name <NEW_LINE> self.gcp_conn_id = gcp_conn_id <NEW_LINE> self.use_internal_ip = use_internal_ip <NEW_LINE> if self.gcp_conn_id is None: <NEW_LINE> <INDENT> raise AirflowException( "The gcp_conn_id parameter has become required. If you want to use Application Default " "Credentials (ADC) strategy for authorization, create an empty connection " "called `google_cloud_default`.", ) <NEW_LINE> <DEDENT> <DEDENT> def execute(self, context) -> Optional[str]: <NEW_LINE> <INDENT> hook = GoogleBaseHook(gcp_conn_id=self.gcp_conn_id) <NEW_LINE> self.project_id = self.project_id or hook.project_id <NEW_LINE> if not self.project_id: <NEW_LINE> <INDENT> raise AirflowException( "The project id must be passed either as " "keyword project_id parameter or as project_id extra " "in Google Cloud connection definition. Both are not set!" ) <NEW_LINE> <DEDENT> with tempfile.NamedTemporaryFile() as conf_file, patch_environ( {KUBE_CONFIG_ENV_VAR: conf_file.name} ), hook.provide_authorized_gcloud(): <NEW_LINE> <INDENT> cmd = [ "gcloud", "container", "clusters", "get-credentials", self.cluster_name, "--zone", self.location, "--project", self.project_id, ] <NEW_LINE> if self.use_internal_ip: <NEW_LINE> <INDENT> cmd.append('--internal-ip') <NEW_LINE> <DEDENT> execute_in_subprocess(cmd) <NEW_LINE> self.config_file = os.environ[KUBE_CONFIG_ENV_VAR] <NEW_LINE> return super().execute(context)
Executes a task in a Kubernetes pod in the specified Google Kubernetes Engine cluster This Operator assumes that the system has gcloud installed and has configured a connection id with a service account. The **minimum** required to define a cluster to create are the variables ``task_id``, ``project_id``, ``location``, ``cluster_name``, ``name``, ``namespace``, and ``image`` .. seealso:: For more detail about Kubernetes Engine authentication have a look at the reference: https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl#internal_ip .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:GKEStartPodOperator` :param location: The name of the Google Kubernetes Engine zone in which the cluster resides, e.g. 'us-central1-a' :type location: str :param cluster_name: The name of the Google Kubernetes Engine cluster the pod should be spawned in :type cluster_name: str :param use_internal_ip: Use the internal IP address as the endpoint. :param project_id: The Google Developers Console project id :type project_id: str :param gcp_conn_id: The google cloud connection id to use. This allows for users to specify a service account. :type gcp_conn_id: str
62599060f548e778e596cc35
class itkMaximumProjectionImageFilterIUS2IUS2_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterIUS2IUS2): <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> InputImageDimension = _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIUS2IUS2_Superclass_InputImageDimension <NEW_LINE> OutputImageDimension = _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIUS2IUS2_Superclass_OutputImageDimension <NEW_LINE> ImageDimensionCheck = _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIUS2IUS2_Superclass_ImageDimensionCheck <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIUS2IUS2_Superclass___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def SetProjectionDimension(self, *args): <NEW_LINE> <INDENT> return _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIUS2IUS2_Superclass_SetProjectionDimension(self, *args) <NEW_LINE> <DEDENT> def GetProjectionDimension(self): <NEW_LINE> <INDENT> return _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIUS2IUS2_Superclass_GetProjectionDimension(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkMaximumProjectionImageFilterPython.delete_itkMaximumProjectionImageFilterIUS2IUS2_Superclass <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIUS2IUS2_Superclass_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIUS2IUS2_Superclass_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkMaximumProjectionImageFilterIUS2IUS2_Superclass.__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++ itkMaximumProjectionImageFilterIUS2IUS2_Superclass class
6259906032920d7e50bc76f2
class RedisOptions(DataStoreOptions): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(geowave_pkg.datastore.redis.config.RedisOptions()) <NEW_LINE> <DEDENT> def set_address(self, address): <NEW_LINE> <INDENT> self._java_ref.setAddress(address) <NEW_LINE> <DEDENT> def get_address(self): <NEW_LINE> <INDENT> return self._java_ref.getAddress() <NEW_LINE> <DEDENT> def set_compression(self, compression): <NEW_LINE> <INDENT> converter = geowave_pkg.datastore.redis.config.RedisOptions.CompressionConverter() <NEW_LINE> self._java_ref.setCompression(converter.convert(compression)) <NEW_LINE> <DEDENT> def get_compression(self): <NEW_LINE> <INDENT> return self._java_ref.getCompression().name() <NEW_LINE> <DEDENT> def set_username(self, username): <NEW_LINE> <INDENT> self._java_ref.setUsername(username) <NEW_LINE> <DEDENT> def get_username(self): <NEW_LINE> <INDENT> return self._java_ref.getUsername() <NEW_LINE> <DEDENT> def set_password(self, password): <NEW_LINE> <INDENT> self._java_ref.setPassword(password) <NEW_LINE> <DEDENT> def get_password(self): <NEW_LINE> <INDENT> return self._java_ref.getPassword()
Redis data store options.
625990600c0af96317c578b5
class ViewCityCodeTotals(APIView): <NEW_LINE> <INDENT> daily_totals = PiecesPerMeterLocation.city_code_totals.all() <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> pieces = self.daily_totals <NEW_LINE> def make_dict(self,a): <NEW_LINE> <INDENT> new={} <NEW_LINE> for element in a: <NEW_LINE> <INDENT> if element['location__city'] in list(new.keys()): <NEW_LINE> <INDENT> new[element['location__city']].append({'code':element['code'], 'total':element['total']}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new.update({element['location__city']:[{'code':element['code'], 'total':element['total']}]}) <NEW_LINE> <DEDENT> <DEDENT> return new <NEW_LINE> <DEDENT> piecesX = make_dict(self, pieces) <NEW_LINE> pieceKeys = list(piecesX.keys()) <NEW_LINE> theJson = [{'location':x, 'results':piecesX[x]} for x in pieceKeys] <NEW_LINE> return Response(theJson)
Returns an array of city code total objects. Each object contains the total count for the MLW codes indentified within a city limit: [{ "location": "Montreux", //name of the city "results": [ { "code": "G100", "total": 185 }, { "code": "G11", "total": 11 } .... {"for all MLW codes identified within city limits"}, }..{"for all cities"}]
62599060796e427e5384fe23
class S3EmailProviderModel(S3Model): <NEW_LINE> <INDENT> names = ("setup_email", "setup_email_id", ) <NEW_LINE> def model(self): <NEW_LINE> <INDENT> T = current.T <NEW_LINE> db = current.db <NEW_LINE> email_types = Storage(setup_google_email = T("Google"), ) <NEW_LINE> tablename = "setup_email" <NEW_LINE> self.super_entity(tablename, "email_id", email_types, Field("name", ), Field("description", ), ) <NEW_LINE> represent = S3Represent(lookup = tablename) <NEW_LINE> email_id = S3ReusableField("email_id", "reference %s" % tablename, label = T("Email Group Provider"), ondelete = "SET NULL", represent = represent, requires = IS_EMPTY_OR( IS_ONE_OF(db, "setup_email.email_id", represent, sort = True ), ), comment = DIV(_class="tooltip", _title="%s|%s" % (T("Email Group Provider"), T("If you use an Email Group Provider configuration then you can create/update the Email Sender entry automatically as part of the deployment.") ), ), ) <NEW_LINE> return {"setup_email_id": email_id, }
Email Providers (we just use Groups currently) - super-entity
625990608e71fb1e983bd178
class Reduction(Enum): <NEW_LINE> <INDENT> SUM = 'sum' <NEW_LINE> SUM_OVER_BATCH_SIZE = 'sum_over_batch_size' <NEW_LINE> WEIGHTED_MEAN = 'weighted_mean'
Types of metrics reduction. Contains the following values: * `SUM`: Scalar sum of weighted values. * `SUM_OVER_BATCH_SIZE`: Scalar sum of weighted values divided by number of elements. * `WEIGHTED_MEAN`: Scalar sum of weighted values divided by sum of weights.
62599060442bda511e95d8b0
class PropertyOptionHandler(OptionHandler): <NEW_LINE> <INDENT> availableOptions = { 'islink': False, }
Class holding options for a param-property pair.
625990601f5feb6acb164298
class CompactBlocksConnectionTest(BitcoinTestFramework): <NEW_LINE> <INDENT> def set_test_params(self): <NEW_LINE> <INDENT> self.setup_clean_chain = True <NEW_LINE> self.num_nodes = 6 <NEW_LINE> <DEDENT> def peer_info(self, from_node, to_node): <NEW_LINE> <INDENT> for peerinfo in self.nodes[from_node].getpeerinfo(): <NEW_LINE> <INDENT> if "(testnode%i)" % to_node in peerinfo['subver']: <NEW_LINE> <INDENT> return peerinfo <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def setup_network(self): <NEW_LINE> <INDENT> self.setup_nodes() <NEW_LINE> self.sync_all() <NEW_LINE> <DEDENT> def relay_block_through(self, peer): <NEW_LINE> <INDENT> self.connect_nodes(peer, 0) <NEW_LINE> self.nodes[0].generate(1) <NEW_LINE> self.sync_blocks() <NEW_LINE> self.disconnect_nodes(peer, 0) <NEW_LINE> status_to = [self.peer_info(1, i)['bip152_hb_to'] for i in range(2, 6)] <NEW_LINE> status_from = [self.peer_info(i, 1)['bip152_hb_from'] for i in range(2, 6)] <NEW_LINE> assert_equal(status_to, status_from) <NEW_LINE> return status_to <NEW_LINE> <DEDENT> def run_test(self): <NEW_LINE> <INDENT> self.log.info("Testing reserved high-bandwidth mode slot for outbound peer...") <NEW_LINE> for i in range(1, 6): <NEW_LINE> <INDENT> self.connect_nodes(i, 0) <NEW_LINE> <DEDENT> self.nodes[0].generate(2) <NEW_LINE> self.sync_blocks() <NEW_LINE> for i in range(1, 6): <NEW_LINE> <INDENT> self.disconnect_nodes(i, 0) <NEW_LINE> <DEDENT> self.connect_nodes(3, 1) <NEW_LINE> self.connect_nodes(4, 1) <NEW_LINE> self.connect_nodes(5, 1) <NEW_LINE> self.connect_nodes(1, 2) <NEW_LINE> for nodeid in range(3, 6): <NEW_LINE> <INDENT> status = self.relay_block_through(nodeid) <NEW_LINE> assert_equal(status, [False, nodeid >= 3, nodeid >= 4, nodeid >= 5]) <NEW_LINE> <DEDENT> for nodeid in range(3, 6): <NEW_LINE> <INDENT> status = self.relay_block_through(nodeid) <NEW_LINE> assert_equal(status, [False, True, True, True]) <NEW_LINE> <DEDENT> status = self.relay_block_through(2) <NEW_LINE> assert_equal(status[0], True) <NEW_LINE> assert_equal(sum(status), 3) <NEW_LINE> for nodeid in range(3, 6): <NEW_LINE> <INDENT> status = self.relay_block_through(nodeid) <NEW_LINE> assert status[0] <NEW_LINE> assert status[nodeid - 2] <NEW_LINE> assert_equal(sum(status), 3) <NEW_LINE> <DEDENT> self.disconnect_nodes(1, 2) <NEW_LINE> self.connect_nodes(1, 2) <NEW_LINE> for nodeid in range(3, 6): <NEW_LINE> <INDENT> status = self.relay_block_through(nodeid) <NEW_LINE> assert not status[0] <NEW_LINE> assert status[nodeid - 2] <NEW_LINE> <DEDENT> assert_equal(status, [False, True, True, True])
Test class for verifying selection of HB peer connections.
62599060e5267d203ee6cf16
class SampledFromConverter(Converter): <NEW_LINE> <INDENT> def __init__(self, choices): <NEW_LINE> <INDENT> self.choices = tuple(choices) <NEW_LINE> <DEDENT> def to_basic(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return real_index(self.choices, value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise WrongFormat('%r is not in %r' % (value, self.choices,)) <NEW_LINE> <DEDENT> <DEDENT> def from_basic(self, value): <NEW_LINE> <INDENT> check_data_type(integer_types, value) <NEW_LINE> if value < 0 or value >= len(self.choices): <NEW_LINE> <INDENT> raise BadData('Invalid index %d into %d elements' % ( value, len(self.choices) )) <NEW_LINE> <DEDENT> return self.choices[value]
A SampledFrom instance is simply stored as an integer index into the list of values sampled from.
62599060ac7a0e7691f73b91
class SpaceFiller(object): <NEW_LINE> <INDENT> name = "space" <NEW_LINE> def __call__(self, N): <NEW_LINE> <INDENT> return ' ' * N
fill random spaces with spaces ;)
625990608e7ae83300eea73b
class char(Command): <NEW_LINE> <INDENT> args = 'char:Number' <NEW_LINE> def invoke(self, tex): <NEW_LINE> <INDENT> return tex.textTokens(chr(self.parse(tex)['char']))
\char
62599060097d151d1a2c271d
class AuthTokenSerializer(serializers.Serializer): <NEW_LINE> <INDENT> name = serializers.CharField() <NEW_LINE> password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) <NEW_LINE> def validate(self, attrs): <NEW_LINE> <INDENT> name = attrs.get('name') <NEW_LINE> password = attrs.get('password') <NEW_LINE> user = authenticate( request=self.context.get('request'), username=name, password=password ) <NEW_LINE> if not user: <NEW_LINE> <INDENT> msg = 'Unable to authenticate with provided credentials' <NEW_LINE> raise serializers.ValidationError(msg, code='authentication') <NEW_LINE> <DEDENT> attrs['user'] = user <NEW_LINE> return attrs
Serializer para el objeto de autenticación
6259906038b623060ffaa3a7
class ProgressBar(object): <NEW_LINE> <INDENT> def __init__(self, minValue=0, maxValue=10, totalWidth=None): <NEW_LINE> <INDENT> self._progBar = "[]" <NEW_LINE> self._oldProgBar = "" <NEW_LINE> self._min = int(minValue) <NEW_LINE> self._max = int(maxValue) <NEW_LINE> self._span = self._max - self._min <NEW_LINE> self._width = totalWidth if totalWidth else conf.progressWidth <NEW_LINE> self._amount = 0 <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def _convertSeconds(self, value): <NEW_LINE> <INDENT> seconds = value <NEW_LINE> minutes = seconds / 60 <NEW_LINE> seconds = seconds - (minutes * 60) <NEW_LINE> return "%.2d:%.2d" % (minutes, seconds) <NEW_LINE> <DEDENT> def update(self, newAmount=0): <NEW_LINE> <INDENT> if newAmount < self._min: <NEW_LINE> <INDENT> newAmount = self._min <NEW_LINE> <DEDENT> elif newAmount > self._max: <NEW_LINE> <INDENT> newAmount = self._max <NEW_LINE> <DEDENT> self._amount = newAmount <NEW_LINE> diffFromMin = float(self._amount - self._min) <NEW_LINE> percentDone = (diffFromMin / float(self._span)) * 100.0 <NEW_LINE> percentDone = round(percentDone) <NEW_LINE> percentDone = int(percentDone) <NEW_LINE> allFull = self._width - 2 <NEW_LINE> numHashes = (percentDone / 100.0) * allFull <NEW_LINE> numHashes = int(round(numHashes)) <NEW_LINE> if numHashes == 0: <NEW_LINE> <INDENT> self._progBar = "[>%s]" % (" " * (allFull - 1)) <NEW_LINE> <DEDENT> elif numHashes == allFull: <NEW_LINE> <INDENT> self._progBar = "[%s]" % ("=" * allFull) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._progBar = "[%s>%s]" % ("=" * (numHashes - 1), " " * (allFull - numHashes)) <NEW_LINE> <DEDENT> percentString = getUnicode(percentDone) + "%" <NEW_LINE> self._progBar = "%s %s" % (percentString, self._progBar) <NEW_LINE> <DEDENT> def draw(self, eta=0): <NEW_LINE> <INDENT> if self._progBar != self._oldProgBar: <NEW_LINE> <INDENT> self._oldProgBar = self._progBar <NEW_LINE> if eta and self._amount < self._max: <NEW_LINE> <INDENT> dataToStdout("\r%s %d/%d ETA %s" % (self._progBar, self._amount, self._max, self._convertSeconds(int(eta)))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> blank = " " * (80 - len("\r%s %d/%d" % (self._progBar, self._amount, self._max))) <NEW_LINE> dataToStdout("\r%s %d/%d%s" % (self._progBar, self._amount, self._max, blank)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return getUnicode(self._progBar)
This class defines methods to update and draw a progress bar
62599060f548e778e596cc36
class UpgradeRPC(BMCManagerServerCommand): <NEW_LINE> <INDENT> oob_method = "firmware_upgrade_rpc" <NEW_LINE> all_stages = range(1, 11) <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super().get_parser(prog_name) <NEW_LINE> parser.add_argument( "--timeout", type=int, default=60, help="advanced; seconds before failing because of timeout", ) <NEW_LINE> parser.add_argument( "--handle", type=int, default=None, help="advanced; Use this handle for upgrade [Lenovo]", ) <NEW_LINE> parser.add_argument( "--bundle", required=True, type=argparse.FileType("rb"), help="Bundle file to use for firmware upgrade", ) <NEW_LINE> parser.add_argument( "--stages", nargs="+", default=self.all_stages, type=int_in_range_argument(self.all_stages), help="advanced; Only perform specific upgrade stages [Lenovo]", ) <NEW_LINE> return parser
perform firmware upgrade using RPC
6259906076e4537e8c3f0c3b
class TCPHandler(tornado_util.TCPHandler, ForwardHandler): <NEW_LINE> <INDENT> def __init__(self, sock, addr): <NEW_LINE> <INDENT> super(TCPHandler, self).__init__(sock) <NEW_LINE> self._init_handler() <NEW_LINE> self.addr = addr <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return "TCPSocketProxy:%s:%s" % (str(self.addr[0]), self.rpc_key) <NEW_LINE> <DEDENT> def send_data(self, message, binary=True): <NEW_LINE> <INDENT> self.write_message(message, True) <NEW_LINE> <DEDENT> def on_message(self, message): <NEW_LINE> <INDENT> self.on_data(message) <NEW_LINE> <DEDENT> def on_close(self): <NEW_LINE> <INDENT> logging.info("RPCProxy: on_close %s ...", self.name()) <NEW_LINE> self._close_process = True <NEW_LINE> if self.forward_proxy: <NEW_LINE> <INDENT> self.forward_proxy.signal_close() <NEW_LINE> self.forward_proxy = None <NEW_LINE> <DEDENT> self.on_close_event()
Event driven TCP handler.
62599060f548e778e596cc37
class TeamFolderCreateArg(bb.Struct): <NEW_LINE> <INDENT> __slots__ = [ '_name_value', '_sync_setting_value', ] <NEW_LINE> _has_required_fields = True <NEW_LINE> def __init__(self, name=None, sync_setting=None): <NEW_LINE> <INDENT> self._name_value = bb.NOT_SET <NEW_LINE> self._sync_setting_value = bb.NOT_SET <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if sync_setting is not None: <NEW_LINE> <INDENT> self.sync_setting = sync_setting <NEW_LINE> <DEDENT> <DEDENT> name = bb.Attribute("name") <NEW_LINE> sync_setting = bb.Attribute("sync_setting", nullable=True, user_defined=True) <NEW_LINE> def _process_custom_annotations(self, annotation_type, field_path, processor): <NEW_LINE> <INDENT> super(TeamFolderCreateArg, self)._process_custom_annotations(annotation_type, field_path, processor)
:ivar team.TeamFolderCreateArg.name: Name for the new team folder. :ivar team.TeamFolderCreateArg.sync_setting: The sync setting to apply to this team folder. Only permitted if the team has team selective sync enabled.
625990601f037a2d8b9e53c2
class Row(BoxLayout): <NEW_LINE> <INDENT> txt = StringProperty() <NEW_LINE> def __init__(self, row, **kwargs): <NEW_LINE> <INDENT> super(Row, self).__init__(**kwargs) <NEW_LINE> self.txt = row
Row for each Label in the Table (from above class)
6259906091f36d47f22319e6
class Site(LazyWsgi): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.channel = channel <NEW_LINE> <DEDENT> def setup(self, environ): <NEW_LINE> <INDENT> cfg = environ['pulsar.cfg'] <NEW_LINE> self.store = create_store(cfg.data_store) <NEW_LINE> pubsub = self.store.pubsub() <NEW_LINE> return WsgiHandler([Router('/', get=self.home_page), FileRouter('/favicon.ico', FAVICON), WebSocket('/message', TweetsWsHandler(pubsub, self.channel))]) <NEW_LINE> <DEDENT> def home_page(self, request): <NEW_LINE> <INDENT> doc = request.html_document <NEW_LINE> head = doc.head <NEW_LINE> head.title = 'Pulsar Twitter Stream' <NEW_LINE> head.links.append('bootstrap_css') <NEW_LINE> head.scripts.append('require') <NEW_LINE> head.scripts.require('jquery') <NEW_LINE> data = open(path.join(STATIC_DIR, 'home.html')).read() <NEW_LINE> doc.body.append(data) <NEW_LINE> return doc.http_response(request)
A simple web site for displaying tweets
62599060d268445f2663a6b4
class ReviewResource(BaseReviewResource): <NEW_LINE> <INDENT> uri_object_key = 'review_id' <NEW_LINE> model_parent_key = 'review_request' <NEW_LINE> item_child_resources = [ resources.review_diff_comment, resources.review_reply, resources.review_screenshot_comment, resources.review_file_attachment_comment, ] <NEW_LINE> list_child_resources = [ resources.review_draft, ] <NEW_LINE> @webapi_check_local_site <NEW_LINE> @augment_method_from(BaseReviewResource) <NEW_LINE> def get_list(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_base_reply_to_field(self, *args, **kwargs): <NEW_LINE> <INDENT> return { 'base_reply_to__isnull': True, }
Provides information on reviews made on a review request. Each review can contain zero or more comments on diffs, screenshots or file attachments. It may also have text preceding the comments (the ``body_top`` field), and text following the comments (``body_bottom``). If the ``text_type`` field is set to ``markdown``, then the ``body_top`` and ``body_bottom`` fields should be interpreted by the client as Markdown text. The returned text in the payload can be provided in a different format by passing ``?force-text-type=`` in the request. This accepts all the possible values listed in the ``text_type`` field below. A review may have replies made. Replies are flat, not threaded. Like a review, there may be body text and there may be comments (which are replies to comments on the parent review). If the ``ship_it`` field is true, then the reviewer has given their approval of the change, once all issues raised on comments have been addressed.
625990604e4d562566373ab6
class AlexOutputBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_channels, classes): <NEW_LINE> <INDENT> super(AlexOutputBlock, self).__init__() <NEW_LINE> mid_channels = 4096 <NEW_LINE> self.fc1 = AlexDense( in_channels=in_channels, out_channels=mid_channels) <NEW_LINE> self.fc2 = AlexDense( in_channels=mid_channels, out_channels=mid_channels) <NEW_LINE> self.fc3 = nn.Linear( in_features=mid_channels, out_features=classes) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.fc1(x) <NEW_LINE> x = self.fc2(x) <NEW_LINE> x = self.fc3(x) <NEW_LINE> return x
AlexNet specific output block. Parameters: ---------- in_channels : int Number of input channels. classes : int Number of classification classes.
6259906097e22403b383c5bb
class BandwidthXHRTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> Bandwidth.objects.all().delete() <NEW_LINE> self.b = Bandwidth.objects.create(link=1, time=1., rx=1, tx=1) <NEW_LINE> <DEDENT> def test_xhr_request(self): <NEW_LINE> <INDENT> from django.core.urlresolvers import reverse <NEW_LINE> import json <NEW_LINE> r = self.client.get(reverse('xhr_bw', args=(self.b.pk, )), HTTP_X_REQUESTED_WITH='XMLHttpRequest') <NEW_LINE> j = json.loads(r.content) <NEW_LINE> self.assertTrue(j.has_key('rx')) <NEW_LINE> self.assertTrue(j.has_key('tx'))
Test XMLHttpRequests
6259906067a9b606de5475f9
class SetStaticRewardsDialog(wx.Dialog): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> wx.Dialog.__init__( self, None, title="Praemien setzen", size=(230, 770)) <NEW_LINE> sizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> self.ticker_ctrls = {} <NEW_LINE> ticker_items = [] <NEW_LINE> for i in range(18): <NEW_LINE> <INDENT> ticker_items.append(readConfig('config.ini', i + 1, 'static')) <NEW_LINE> <DEDENT> counter = 0 <NEW_LINE> for item in ticker_items: <NEW_LINE> <INDENT> ctrl = wx.TextCtrl(self, value=item, name=item) <NEW_LINE> sizer.Add(ctrl, 0, wx.ALL | wx.CENTER, 5) <NEW_LINE> self.ticker_ctrls[counter] = ctrl <NEW_LINE> if counter >= int(readConfig('config.ini', '1', 'maxPlayerReward')): <NEW_LINE> <INDENT> self.ticker_ctrls[counter].Disable() <NEW_LINE> <DEDENT> counter = counter + 1 <NEW_LINE> <DEDENT> okBtn = wx.Button(self, wx.ID_OK) <NEW_LINE> sizer.Add(okBtn, 0, wx.ALL | wx.CENTER, 5) <NEW_LINE> self.SetSizer(sizer)
Class for static reward dialog.
62599060fff4ab517ebceed6
class MultilayerPerceptronClassificationModel(_JavaProbabilisticClassificationModel, _MultilayerPerceptronParams, JavaMLWritable, JavaMLReadable, HasTrainingSummary): <NEW_LINE> <INDENT> @property <NEW_LINE> @since("2.0.0") <NEW_LINE> def weights(self): <NEW_LINE> <INDENT> return self._call_java("weights") <NEW_LINE> <DEDENT> @since("3.1.0") <NEW_LINE> def summary(self): <NEW_LINE> <INDENT> if self.hasSummary: <NEW_LINE> <INDENT> return MultilayerPerceptronClassificationTrainingSummary( super(MultilayerPerceptronClassificationModel, self).summary) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError("No training summary available for this %s" % self.__class__.__name__) <NEW_LINE> <DEDENT> <DEDENT> def evaluate(self, dataset): <NEW_LINE> <INDENT> if not isinstance(dataset, DataFrame): <NEW_LINE> <INDENT> raise ValueError("dataset must be a DataFrame but got %s." % type(dataset)) <NEW_LINE> <DEDENT> java_mlp_summary = self._call_java("evaluate", dataset) <NEW_LINE> return MultilayerPerceptronClassificationSummary(java_mlp_summary)
Model fitted by MultilayerPerceptronClassifier. .. versionadded:: 1.6.0
6259906099cbb53fe6832591
class UserStore(Timestamp): <NEW_LINE> <INDENT> store = models.ForeignKey(Store, on_delete=models.CASCADE) <NEW_LINE> user = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f"{self.user} -- {self.store}"
This model is mapping the relation between the store manager and the restaurant, hotel store.
625990602ae34c7f260ac796
class DeclarativeDocumenter(EnamlDocstringSignatureMixin, EnamlComponentDocumenter): <NEW_LINE> <INDENT> objtype = 'enaml_decl' <NEW_LINE> member_order = 35 <NEW_LINE> @classmethod <NEW_LINE> def can_document_member(cls, member, membername, isattr, parent): <NEW_LINE> <INDENT> return isinstance(member, Declarative) <NEW_LINE> <DEDENT> def format_args(self): <NEW_LINE> <INDENT> return ' (derives from {0})'.format(self.object.__base__) <NEW_LINE> <DEDENT> def document_members(self, all_members=False): <NEW_LINE> <INDENT> pass
Specialized Documenter subclass for Enaml declarations.
62599060097d151d1a2c271f
class L1Loss(HybridBlock): <NEW_LINE> <INDENT> def __init__(self, weight=None, batch_axis=0, **kwargs): <NEW_LINE> <INDENT> super(L1Loss, self).__init__(**kwargs) <NEW_LINE> self._weight = weight <NEW_LINE> self._batch_axis = batch_axis <NEW_LINE> <DEDENT> def hybrid_forward(self, F, output, label, sample_weight=None): <NEW_LINE> <INDENT> if F is ndarray: <NEW_LINE> <INDENT> loss = ndarray.abs(output - label.reshape(output.shape)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loss = symbol.abs(output - label.reshape(())) <NEW_LINE> <DEDENT> loss = _apply_weighting(F, loss, self._weight, sample_weight) <NEW_LINE> return F.mean(loss, axis=self._batch_axis, exclude=True)
Calculate the mean absolute error between output and label: .. math:: L = \frac{1}{2}\sum_i \vert {output}_i - {label}_i \vert. output and label must have the same shape. Parameters ---------- weight : float or None global scalar weight for loss sample_weight : Symbol or None per sample weighting. Must be broadcastable to the same shape as loss. For example, if loss has shape (64, 10) and you want to weight each sample in the batch, sample_weight should have shape (64, 1) batch_axis : int, default 0 The axis that represents mini-batch.
62599060097d151d1a2c2720
class Group(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=250, unique=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['name'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def _get_dictionary(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'name': self.name, } <NEW_LINE> <DEDENT> dictionary = property(_get_dictionary)
Group of feeds.
625990604428ac0f6e659be3
class Line(object): <NEW_LINE> <INDENT> def __init__(self, p1, p2): <NEW_LINE> <INDENT> self.p1 = p1 <NEW_LINE> self.p2 = p2 <NEW_LINE> if p1.x == p2.x: <NEW_LINE> <INDENT> self.slope = None <NEW_LINE> self.intercept = None <NEW_LINE> self.vertical = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.slope = float(p2.y - p1.y) / (p2.x - p1.x) <NEW_LINE> self.intercept = p1.y - self.slope * p1.x <NEW_LINE> self.vertical = False <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.vertical: <NEW_LINE> <INDENT> return "x = " + str(self.p1.x) <NEW_LINE> <DEDENT> return "y = " + str(self.slope) + "x + " + str(self.intercept) <NEW_LINE> <DEDENT> def __eq__(self, line): <NEW_LINE> <INDENT> if self.vertical != line.vertical: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.vertical: <NEW_LINE> <INDENT> return self.p1.x == line.p1.x <NEW_LINE> <DEDENT> return self.slope == line.slope and self.intercept == line.intercept <NEW_LINE> <DEDENT> def at_x(self, x): <NEW_LINE> <INDENT> if self.vertical: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return Point(x, self.slope * x + self.intercept) <NEW_LINE> <DEDENT> def at_y(self, y): <NEW_LINE> <INDENT> return Point((y - self.intercept) / self.slope, y) <NEW_LINE> <DEDENT> def dist(self, point): <NEW_LINE> <INDENT> return sqrt(self.dist2(point)) <NEW_LINE> <DEDENT> def dist2(self, point): <NEW_LINE> <INDENT> numerator = float(self.p2.x - self.p1.x) * (self.p1.y - point.y) - (self.p1.x - point.x) * (self.p2.y - self.p1.y) <NEW_LINE> numerator *= numerator <NEW_LINE> denominator = float(self.p2.x - self.p1.x) * (self.p2.x - self.p1.x) + (self.p2.y - self.p1.y) * (self.p2.y - self.p1.y) <NEW_LINE> return numerator / denominator <NEW_LINE> <DEDENT> def intersection(self, line): <NEW_LINE> <INDENT> if line.slope == self.slope: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if self.vertical: <NEW_LINE> <INDENT> return line.at_x(self.p1.x) <NEW_LINE> <DEDENT> elif line.vertical: <NEW_LINE> <INDENT> return self.at_x(line.p1.x) <NEW_LINE> <DEDENT> x = float(self.intercept - line.intercept) / (line.slope - self.slope) <NEW_LINE> return self.at_x(x) <NEW_LINE> <DEDENT> def midpoint(self): <NEW_LINE> <INDENT> x = float(self.p1.x + self.p2.x) / 2 <NEW_LINE> y = float(self.p1.y + self.p2.y) / 2 <NEW_LINE> return Point(x, y)
Definition of a line in 2-D Cartesian space.
625990606e29344779b01cff
class TemplateManager(object): <NEW_LINE> <INDENT> def list_templates(self): <NEW_LINE> <INDENT> return loader.list_template_dirs() <NEW_LINE> <DEDENT> def get_template_detail(self,template_name): <NEW_LINE> <INDENT> parallel_file = loader.get_parallel_file(template_name) <NEW_LINE> data = None <NEW_LINE> if parallel_file: <NEW_LINE> <INDENT> data = parallel_file.description() <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def render_template_to_data(self,template_name,context_str): <NEW_LINE> <INDENT> template = loader.get_template(template_name) <NEW_LINE> parallel = loader.get_parallel_file(template_name) <NEW_LINE> makefile = loader.get_makefile(template_name) <NEW_LINE> data = None <NEW_LINE> if template and parallel and makefile: <NEW_LINE> <INDENT> context = metadata.Context(context_str) <NEW_LINE> source_code = template.render(context) <NEW_LINE> data = [ { 'name': source_code.file_name, 'ftype': source_code.file_type, 'text': source_code.file_text }, { 'name': parallel.file_name, 'ftype': parallel.file_type, 'text': parallel.source }, { 'name': makefile.file_name, 'ftype': makefile.file_type, 'text': makefile.source }, ] <NEW_LINE> <DEDENT> return data
A facade to access the ``metadata.Template```functionalities.
625990600fa83653e46f6598
class DiffableQuery(Diffable): <NEW_LINE> <INDENT> def __init__(self, name, diffable_targets, threshold): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.threshold = threshold <NEW_LINE> self.diffable_targets = diffable_targets <NEW_LINE> <DEDENT> def _measure_non_equal_pts_percentage( self, diffable_targets1, diffable_targets2, threshold ): <NEW_LINE> <INDENT> if not diffable_targets1 or not diffable_targets2: <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> target_dissymmetry = diffable_targets1.measure_dissymmetry(diffable_targets2) <NEW_LINE> if not target_dissymmetry: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> val_diff_measures = target_dissymmetry.measures <NEW_LINE> count = 0 <NEW_LINE> for val_diff_measure in val_diff_measures: <NEW_LINE> <INDENT> if val_diff_measure > threshold: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> return float(count) / len(val_diff_measures) <NEW_LINE> <DEDENT> def measure_dissymmetry(self, other): <NEW_LINE> <INDENT> diffable_target_tuples = _outer_join_diffables( self.diffable_targets, other.diffable_targets ) <NEW_LINE> if not diffable_target_tuples: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> diff_measures = [ self._measure_non_equal_pts_percentage( diffable_target1, diffable_target2, self.threshold ) for diffable_target1, diffable_target2 in diffable_target_tuples ] <NEW_LINE> return Dissymmetry(self.name, diff_measures)
DiffableQuery.
62599060009cb60464d02be7
class E1_Results(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.irf_stderr = np.array([[[.125, 0.546, 0.664 ], [0.032, 0.139, 0.169], [0.026, 0.112, 0.136]], [[0.129, 0.547, 0.663], [0.032, 0.134, 0.163], [0.026, 0.108, 0.131]], [[0.084, .385, .479], [.016, .079, .095], [.016, .078, .103]]]) <NEW_LINE> self.cum_irf_stderr = np.array([[[.125, 0.546, 0.664 ], [0.032, 0.139, 0.169], [0.026, 0.112, 0.136]], [[0.149, 0.631, 0.764], [0.044, 0.185, 0.224], [0.033, 0.140, 0.169]], [[0.099, .468, .555], [.038, .170, .205], [.033, .150, .185]]]) <NEW_LINE> self.lr_stderr = np.array([[.134, .645, .808], [.048, .230, .288], [.043, .208, .260]])
Results from Lutkepohl (2005) using E2 dataset
625990600c0af96317c578b7
class SetVolume(command.Command): <NEW_LINE> <INDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(SetVolume, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'volume', metavar='<volume>', help='Volume to change (name or ID)', ) <NEW_LINE> parser.add_argument( '--name', metavar='<name>', help='New volume name', ) <NEW_LINE> parser.add_argument( '--description', metavar='<description>', help='New volume description', ) <NEW_LINE> parser.add_argument( '--size', metavar='<size>', type=int, help='Extend volume size in GB', ) <NEW_LINE> parser.add_argument( '--property', metavar='<key=value>', action=parseractions.KeyValueAction, help='Property to add or modify for this volume ' '(repeat option to set multiple properties)', ) <NEW_LINE> parser.add_argument( '--bootable', metavar='<boolean>', type=utils.parse_bool, choices=[True, False], help='Update bootable status of a volume.' ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> volume_client = self.app.client_manager.volume <NEW_LINE> volume = utils.find_resource(volume_client.volumes, parsed_args.volume) <NEW_LINE> if parsed_args.size: <NEW_LINE> <INDENT> if volume.status != 'available': <NEW_LINE> <INDENT> self.app.log.error("Volume is in %s state, it must be " "available before size can be extended" % volume.status) <NEW_LINE> return <NEW_LINE> <DEDENT> if parsed_args.size <= volume.size: <NEW_LINE> <INDENT> self.app.log.error("New size must be greater than %s GB" % volume.size) <NEW_LINE> return <NEW_LINE> <DEDENT> volume_client.volumes.extend(volume.id, parsed_args.size) <NEW_LINE> <DEDENT> if parsed_args.property: <NEW_LINE> <INDENT> volume_client.volumes.set_metadata(volume.id, parsed_args.property) <NEW_LINE> <DEDENT> if parsed_args.bootable is not None: <NEW_LINE> <INDENT> volume_client.volumes.set_bootable(volume.id, parsed_args.bootable) <NEW_LINE> <DEDENT> kwargs = {} <NEW_LINE> if parsed_args.name: <NEW_LINE> <INDENT> kwargs['display_name'] = parsed_args.name <NEW_LINE> <DEDENT> if parsed_args.description: <NEW_LINE> <INDENT> kwargs['display_description'] = parsed_args.description <NEW_LINE> <DEDENT> if kwargs: <NEW_LINE> <INDENT> volume_client.volumes.update(volume.id, **kwargs) <NEW_LINE> <DEDENT> if not kwargs and not parsed_args.property and not parsed_args.size and not parsed_args.bootable: <NEW_LINE> <INDENT> self.app.log.error("No changes requested\n")
Set volume properties
625990603539df3088ecd94d
class XSBCompileError(Exception): <NEW_LINE> <INDENT> pass
Exception raised if loaded module has compile errors.
62599060d268445f2663a6b5
class PrivateUserApiTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> self.user = create_user(email="[email protected]", password="test123", name="Hippo") <NEW_LINE> self.client.force_authenticate(user=self.user) <NEW_LINE> <DEDENT> def test_retrieve_profile_success(self): <NEW_LINE> <INDENT> res = self.client.get(ME_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, { "name": self.user.name, "email": self.user.email, }) <NEW_LINE> <DEDENT> def test_post_me_not_allowed(self): <NEW_LINE> <INDENT> res = self.client.post(ME_URL, {}) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> <DEDENT> def test_update_user_profile(self): <NEW_LINE> <INDENT> payload = { "name": "new_name", "password": "new_password", } <NEW_LINE> res = self.client.patch(ME_URL, payload) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.assertEqual(self.user.name, payload["name"]) <NEW_LINE> self.assertTrue(self.user.check_password(payload["password"])) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK)
Test API requests that require authentication
62599060a8ecb033258728c8
class UserProfile(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(User, unique=True) <NEW_LINE> phone = models.CharField(max_length=14, null=True) <NEW_LINE> mobile_phone = models.CharField(max_length=14, null=True) <NEW_LINE> home_address = models.CharField(max_length=255, null=True) <NEW_LINE> home_address2 = models.CharField(max_length=255, null=True) <NEW_LINE> home_zipcode = models.CharField(max_length=16, null=True) <NEW_LINE> home_city = models.CharField(max_length=255, null=True) <NEW_LINE> alert = models.BooleanField(default=False) <NEW_LINE> driver_km_price = models.DecimalField( max_digits=5, decimal_places=2, null=True ) <NEW_LINE> driver_smokers_accepted = models.NullBooleanField() <NEW_LINE> driver_pets_accepted = models.NullBooleanField() <NEW_LINE> driver_place_for_luggage = models.NullBooleanField() <NEW_LINE> driver_car_type = models.ForeignKey( CarType, null=True, related_name='driver_car_type_set' ) <NEW_LINE> driver_seats_available = models.PositiveIntegerField(null=True) <NEW_LINE> passenger_max_km_price = models.DecimalField( max_digits=5, decimal_places=2, null=True ) <NEW_LINE> passenger_smokers_accepted = models.BooleanField(default=False) <NEW_LINE> passenger_pets_accepted = models.BooleanField(default=False) <NEW_LINE> passenger_place_for_luggage = models.BooleanField(default=False) <NEW_LINE> passenger_car_type = models.ForeignKey( CarType, null=True, related_name='passenger_car_type_set' ) <NEW_LINE> passenger_min_remaining_seats = models.PositiveIntegerField(null=True) <NEW_LINE> validation = models.ForeignKey(EmailValidation, null=True) <NEW_LINE> language = models.CharField(max_length=2, choices=settings.LANGUAGES, default='fr', null=True) <NEW_LINE> def set_email(self, email): <NEW_LINE> <INDENT> if self.user.email and self.user.email == email: <NEW_LINE> <INDENT> if self.validation: <NEW_LINE> <INDENT> validation = self.validation <NEW_LINE> self.validation = None <NEW_LINE> self.save() <NEW_LINE> validation.delete() <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> key = ''.join([choice(_ALPHABET) for i in range(50)]) <NEW_LINE> if self.validation: <NEW_LINE> <INDENT> if self.validation.email == email: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.validation.key = key <NEW_LINE> self.validation.email = email <NEW_LINE> self.validation.save() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> validation = EmailValidation(key=key, email=email) <NEW_LINE> validation.save() <NEW_LINE> self.validation = validation <NEW_LINE> <DEDENT> self.save() <NEW_LINE> return True
User profile
6259906099cbb53fe6832592
class ImportanceTracker: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.mean = 0 <NEW_LINE> self.sum_squares = 0 <NEW_LINE> self.N = 0 <NEW_LINE> <DEDENT> def update(self, scores, num_samples=None): <NEW_LINE> <INDENT> if num_samples is None: <NEW_LINE> <INDENT> self.N += len(scores) <NEW_LINE> diff = scores - self.mean <NEW_LINE> self.mean += np.sum(diff, axis=0) / self.N <NEW_LINE> diff2 = scores - self.mean <NEW_LINE> self.sum_squares += np.sum(diff * diff2, axis=0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert num_samples.shape == scores.shape[1:] <NEW_LINE> self.N = self.N + num_samples <NEW_LINE> num_void = len(scores) - num_samples <NEW_LINE> orig_mean = np.copy(self.mean) <NEW_LINE> diff = scores - self.mean <NEW_LINE> self.mean += ( np.sum(diff, axis=0) + self.mean * num_void) / np.maximum(self.N, 1) <NEW_LINE> diff2 = scores - self.mean <NEW_LINE> self.sum_squares += ( np.sum(diff * diff2, axis=0) - orig_mean * self.mean * num_void) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def values(self): <NEW_LINE> <INDENT> return self.mean <NEW_LINE> <DEDENT> @property <NEW_LINE> def var(self): <NEW_LINE> <INDENT> return self.sum_squares / (np.maximum(self.N, 1) ** 2) <NEW_LINE> <DEDENT> @property <NEW_LINE> def std(self): <NEW_LINE> <INDENT> return self.var ** 0.5
For tracking feature importance using a dynamic average.
625990604a966d76dd5f05a4
class LiveRailAuth(AuthBase): <NEW_LINE> <INDENT> def __init__(self, token): <NEW_LINE> <INDENT> self.token = token <NEW_LINE> <DEDENT> def __call__(self, request): <NEW_LINE> <INDENT> url = request.url.split('?') <NEW_LINE> if request.body: <NEW_LINE> <INDENT> request.body += "&token={}".format(self.token) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request.body = "&token={}".format(self.token) <NEW_LINE> <DEDENT> params = {'token':self.token} <NEW_LINE> if len(url)>1: <NEW_LINE> <INDENT> existing_params = dict([x.split('=') for x in url[1].split("&")]) <NEW_LINE> params.update(existing_params) <NEW_LINE> <DEDENT> params = "&".join(["{}={}".format(x, y) for x,y in params.iteritems()]) <NEW_LINE> request.url = "{}?{}".format(url[0], params) <NEW_LINE> return request
Does the authentication for Console requests.
62599060d486a94d0ba2d679
class PrimaryPathBTreeFolder2(BTreeFolder2): <NEW_LINE> <INDENT> def _setObject(self, id, obj, roles=None, user=None, set_owner=1): <NEW_LINE> <INDENT> obj.__primary_parent__ = aq_base(self) <NEW_LINE> return ObjectManager._setObject(self, id, obj, roles, user, set_owner) <NEW_LINE> <DEDENT> def _delObject(self, id, dp=1, suppress_events=False): <NEW_LINE> <INDENT> obj = self._getOb(id) <NEW_LINE> ObjectManager._delObject(self, id, dp, suppress_events) <NEW_LINE> obj.__primary_parent__ = None
BTreeFolder2 PrimaryPathObjectManager.
62599060435de62698e9d4b8
class PageScreenDialog(QDialog, Ui_PageScreenDialog): <NEW_LINE> <INDENT> def __init__(self, view, visibleOnly=False, parent=None): <NEW_LINE> <INDENT> super(PageScreenDialog, self).__init__(parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.setWindowFlags(Qt.Window) <NEW_LINE> self.__view = view <NEW_LINE> self.__createPixmap(visibleOnly) <NEW_LINE> self.pageScreenLabel.setPixmap(self.__pagePixmap) <NEW_LINE> <DEDENT> def __createPixmap(self, visibleOnly): <NEW_LINE> <INDENT> page = self.__view.page() <NEW_LINE> origSize = page.viewportSize() <NEW_LINE> if not visibleOnly: <NEW_LINE> <INDENT> page.setViewportSize(page.mainFrame().contentsSize()) <NEW_LINE> <DEDENT> image = QImage(page.viewportSize(), QImage.Format_ARGB32) <NEW_LINE> painter = QPainter(image) <NEW_LINE> page.mainFrame().render(painter) <NEW_LINE> painter.end() <NEW_LINE> self.__pagePixmap = QPixmap.fromImage(image) <NEW_LINE> page.setViewportSize(origSize) <NEW_LINE> <DEDENT> def __savePageScreen(self): <NEW_LINE> <INDENT> fileName = E5FileDialog.getSaveFileName( self, self.tr("Save Page Screen"), self.tr("screen.png"), self.tr("Portable Network Graphics File (*.png)"), E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite)) <NEW_LINE> if not fileName: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if QFileInfo(fileName).exists(): <NEW_LINE> <INDENT> res = E5MessageBox.yesNo( self, self.tr("Save Page Screen"), self.tr("<p>The file <b>{0}</b> already exists." " Overwrite it?</p>").format(fileName), icon=E5MessageBox.Warning) <NEW_LINE> if not res: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> file = QFile(fileName) <NEW_LINE> if not file.open(QFile.WriteOnly): <NEW_LINE> <INDENT> E5MessageBox.warning( self, self.tr("Save Page Screen"), self.tr("Cannot write file '{0}:\n{1}.") .format(fileName, file.errorString())) <NEW_LINE> return False <NEW_LINE> <DEDENT> res = self.__pagePixmap.save(file) <NEW_LINE> file.close() <NEW_LINE> if not res: <NEW_LINE> <INDENT> E5MessageBox.warning( self, self.tr("Save Page Screen"), self.tr("Cannot write file '{0}:\n{1}.") .format(fileName, file.errorString())) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> @pyqtSlot(QAbstractButton) <NEW_LINE> def on_buttonBox_clicked(self, button): <NEW_LINE> <INDENT> if button == self.buttonBox.button(QDialogButtonBox.Cancel): <NEW_LINE> <INDENT> self.reject() <NEW_LINE> <DEDENT> elif button == self.buttonBox.button(QDialogButtonBox.Save): <NEW_LINE> <INDENT> if self.__savePageScreen(): <NEW_LINE> <INDENT> self.accept()
Class documentation goes here.
62599060442bda511e95d8b2
class FloatField(BaseField): <NEW_LINE> <INDENT> def __init__(self, required=True, default=None, label=None, value=None): <NEW_LINE> <INDENT> self.required, self.default, self.label, self.value = required, default, label, value <NEW_LINE> if self.default is not None: <NEW_LINE> <INDENT> self.value = self.default <NEW_LINE> <DEDENT> <DEDENT> def valid(self): <NEW_LINE> <INDENT> flag = True <NEW_LINE> if self.required: <NEW_LINE> <INDENT> if not self.value: <NEW_LINE> <INDENT> raise PfigAttributeError(Messages.AMOUNT_REQUIRED.format(self.label)) <NEW_LINE> <DEDENT> <DEDENT> if self.value is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.value = float(self.value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise PfigAttributeError(Messages.FLOAT_INVALID) <NEW_LINE> <DEDENT> <DEDENT> return flag <NEW_LINE> <DEDENT> def is_valid(self): <NEW_LINE> <INDENT> return True if self.valid() else False
Class to generate Float field types.
625990603c8af77a43b68a9a
class BTNotificationDebugParams(object): <NEW_LINE> <INDENT> openapi_types = { 'debug_submitted': 'bool' } <NEW_LINE> attribute_map = { 'debug_submitted': 'debugSubmitted' } <NEW_LINE> def __init__(self, debug_submitted=None): <NEW_LINE> <INDENT> self._debug_submitted = None <NEW_LINE> self.discriminator = None <NEW_LINE> if debug_submitted is not None: <NEW_LINE> <INDENT> self.debug_submitted = debug_submitted <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def debug_submitted(self): <NEW_LINE> <INDENT> return self._debug_submitted <NEW_LINE> <DEDENT> @debug_submitted.setter <NEW_LINE> def debug_submitted(self, debug_submitted): <NEW_LINE> <INDENT> self._debug_submitted = debug_submitted <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, BTNotificationDebugParams): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62599060adb09d7d5dc0bc1c
class ViewFeedback(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> base = Container() <NEW_LINE> mh.set_language_from_settings(request) <NEW_LINE> base.form = forms.FeedbackForm() <NEW_LINE> base.form.action_url_name = "feedback_page" <NEW_LINE> base.utc_comment = "utc_empty_FeedBackForm" <NEW_LINE> endow_base_object(base, request) <NEW_LINE> context = {"base": base} <NEW_LINE> return render(request, "sober/main_feedback_page.html", context) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> base = Container() <NEW_LINE> mh.set_language_from_settings(request) <NEW_LINE> fb_form = forms.FeedbackForm(request.POST) <NEW_LINE> domainname = request.META["HTTP_HOST"] <NEW_LINE> if fb_form.is_valid(): <NEW_LINE> <INDENT> fb_dict = fb_form.save() <NEW_LINE> self.send_feedback_home(fb_dict, domainname) <NEW_LINE> base.fom = None <NEW_LINE> msg1 = _("Your Feedback has been successfully processed.") <NEW_LINE> base.message = msg1 <NEW_LINE> base.debug_message = str(fb_dict) <NEW_LINE> endow_base_object(base, request) <NEW_LINE> context = {"base": base} <NEW_LINE> return render(request, "sober/main_feedback_page.html", context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> base.content = mh.handle_form_errors(fb_form) <NEW_LINE> context = {"pagetype": "Feedback_Form", "sp": base} <NEW_LINE> return render(request, "sober/main_simple_page.html", context) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def send_feedback_home(fb_dict, domainname="sober"): <NEW_LINE> <INDENT> subject_txt = "new feedback from {}".format(domainname) <NEW_LINE> body_txt = str(fb_dict) <NEW_LINE> utils.send_mail(subject_txt, body_txt)
Show and Process the Feedback-Form
62599060e64d504609df9f27
class VendingMachine(object): <NEW_LINE> <INDENT> def __init__(self, name, product_price): <NEW_LINE> <INDENT> self.stock = 0 <NEW_LINE> self.price = product_price <NEW_LINE> self.balance = 0 <NEW_LINE> self.change = 0 <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def restock(self, amount): <NEW_LINE> <INDENT> self.stock = self.stock + amount <NEW_LINE> print('Current', self.name, 'stock:',self.stock) <NEW_LINE> <DEDENT> def deposit(self, money): <NEW_LINE> <INDENT> if self.stock > 0: <NEW_LINE> <INDENT> self.balance = self.balance + money <NEW_LINE> print('Current balance: $',self.balance) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Machine is out of stock. Here is your $',money,'.') <NEW_LINE> <DEDENT> <DEDENT> def vend(self): <NEW_LINE> <INDENT> if self.stock > 0: <NEW_LINE> <INDENT> if self.balance >= self.price: <NEW_LINE> <INDENT> self.stock = self.stock - 1 <NEW_LINE> self.change = self.balance - self.price <NEW_LINE> self.balance = 0 <NEW_LINE> print('Here is your', self.name, 'and $', self.change, 'change.') <NEW_LINE> <DEDENT> elif self.balance < self.price: <NEW_LINE> <INDENT> print('You must deposit $',self.price - self.balance, 'more.') <NEW_LINE> <DEDENT> <DEDENT> elif self.stock == 0: <NEW_LINE> <INDENT> print('Machine is out of stock.')
A vending machine that vends some product for some price. >>> v = VendingMachine('candy', 10) >>> v.vend() 'Machine is out of stock.' >>> v.restock(2) 'Current candy stock: 2' >>> v.vend() 'You must deposit $10 more.' >>> v.deposit(7) 'Current balance: $7' >>> v.vend() 'You must deposit $3 more.' >>> v.deposit(5) 'Current balance: $12' >>> v.vend() 'Here is your candy and $2 change.' >>> v.deposit(10) 'Current balance: $10' >>> v.vend() 'Here is your candy.' >>> v.deposit(15) 'Machine is out of stock. Here is your $15.'
625990604428ac0f6e659be4
class DynamicWidget(object): <NEW_LINE> <INDENT> def __init__(self, default): <NEW_LINE> <INDENT> self.default = default <NEW_LINE> <DEDENT> def connectValueChanged(self, callback, *args): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def setWidgetValue(self, value): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def getWidgetValue(self, value): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def getWidgetDefault(self): <NEW_LINE> <INDENT> return self.default <NEW_LINE> <DEDENT> def setWidgetToDefault(self): <NEW_LINE> <INDENT> if self.default is not None: <NEW_LINE> <INDENT> self.setWidgetValue(self.default)
An interface which provides a uniform way to get, set, and observe widget properties
6259906038b623060ffaa3a9
class MarshmallowMongoengineError(Exception): <NEW_LINE> <INDENT> pass
Base exception class from which all exceptions related to marshmallow-mongoengine inherit.
6259906063d6d428bbee3de1
class ShiftPaned(gtk.VBox): <NEW_LINE> <INDENT> _state = SHOW_BOTH <NEW_LINE> _left_args = () <NEW_LINE> _left_kwargs = {} <NEW_LINE> _right_args = () <NEW_LINE> _right_kwargs = {} <NEW_LINE> left_widget = None <NEW_LINE> right_widget = None <NEW_LINE> def has_both_widgets(self): <NEW_LINE> <INDENT> return self.right_widget is not None and self.left_widget is not None <NEW_LINE> <DEDENT> def __init__(self, paned_factory=gtk.HPaned): <NEW_LINE> <INDENT> self.paned = paned_factory() <NEW_LINE> self.paned.show() <NEW_LINE> super(ShiftPaned, self).__init__() <NEW_LINE> <DEDENT> def update_children(self): <NEW_LINE> <INDENT> if self.has_both_widgets(): <NEW_LINE> <INDENT> _remove_all(self) <NEW_LINE> _remove_all(self.paned) <NEW_LINE> if self._state == SHOW_BOTH: <NEW_LINE> <INDENT> self.add(self.paned) <NEW_LINE> self.paned.pack1( self.left_widget, *self._left_args, **self._left_kwargs ) <NEW_LINE> self.paned.pack2( self.right_widget, *self._right_args, **self._right_kwargs ) <NEW_LINE> <DEDENT> elif self._state == SHOW_LEFT: <NEW_LINE> <INDENT> self.add(self.left_widget) <NEW_LINE> <DEDENT> elif self._state == SHOW_RIGHT: <NEW_LINE> <INDENT> self.add(self.right_widget) <NEW_LINE> <DEDENT> <DEDENT> elif len(self.get_children()) >= 1: <NEW_LINE> <INDENT> self.remove(self.get_children()[0]) <NEW_LINE> <DEDENT> <DEDENT> def pack1(self, widget, *args, **kwargs): <NEW_LINE> <INDENT> assert widget is not None <NEW_LINE> self._left_args = args <NEW_LINE> self._left_kwargs = kwargs <NEW_LINE> self.left_widget = widget <NEW_LINE> self.update_children() <NEW_LINE> <DEDENT> def pack2(self, widget, *args, **kwargs): <NEW_LINE> <INDENT> assert widget is not None <NEW_LINE> self._right_args = args <NEW_LINE> self._right_kwargs = kwargs <NEW_LINE> self.right_widget = widget <NEW_LINE> self.update_children() <NEW_LINE> <DEDENT> def set_state(self, state): <NEW_LINE> <INDENT> if state == self._state: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._state = state <NEW_LINE> self.update_children() <NEW_LINE> <DEDENT> def get_state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> def set_position(self, position): <NEW_LINE> <INDENT> self.paned.set_position(position) <NEW_LINE> <DEDENT> def get_position(self): <NEW_LINE> <INDENT> return self.paned.get_position()
A ShiftPaned is a gtk.Paned that can hide one of its child widgets, therefore hiding the pane division.
6259906045492302aabfdb8c
class KAR_030a: <NEW_LINE> <INDENT> play = Summon(CONTROLLER, "KAR_030")
Pantry Spider
6259906076e4537e8c3f0c3f
class MessageAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> model = Message <NEW_LINE> list_display = ('url', 'subject') <NEW_LINE> search_display = ('url', 'subject') <NEW_LINE> fields = ('url', 'subject', 'email_body', 'slack_body')
Admin for the Message model.
625990604f6381625f199ffc
class TestViewExamcreate(TestCase): <NEW_LINE> <INDENT> expected_status_code = 200 <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.res = self.client.get(reverse("choice:exam-create")) <NEW_LINE> <DEDENT> def test_should_return_expected_return_code(self): <NEW_LINE> <INDENT> self.assertEqual(self.res.status_code, self.expected_status_code)
Test view choice:exam-create
62599060a8370b77170f1a80
@attr('shard_2') <NEW_LINE> class TestCheckoutWithEcommerceService(ModuleStoreTestCase): <NEW_LINE> <INDENT> @httpretty.activate <NEW_LINE> @override_settings(ECOMMERCE_API_URL=TEST_API_URL, ECOMMERCE_API_SIGNING_KEY=TEST_API_SIGNING_KEY) <NEW_LINE> def test_create_basket(self): <NEW_LINE> <INDENT> user = UserFactory.create(username="test-username") <NEW_LINE> course_mode = CourseModeFactory.create(sku="test-sku").to_tuple() <NEW_LINE> expected_payment_data = {'foo': 'bar'} <NEW_LINE> httpretty.register_uri( httpretty.POST, "{}/baskets/".format(TEST_API_URL), body=json.dumps({'payment_data': expected_payment_data}), content_type="application/json", ) <NEW_LINE> with mock.patch('lms.djangoapps.verify_student.views.audit_log') as mock_audit_log: <NEW_LINE> <INDENT> actual_payment_data = checkout_with_ecommerce_service( user, 'dummy-course-key', course_mode, 'test-processor' ) <NEW_LINE> self.assertTrue(mock_audit_log.called) <NEW_LINE> <DEDENT> self.assertEqual(json.loads(httpretty.last_request().body), { 'products': [{'sku': 'test-sku'}], 'checkout': True, 'payment_processor_name': 'test-processor', }) <NEW_LINE> self.assertEqual(actual_payment_data, expected_payment_data)
Ensures correct behavior in the function `checkout_with_ecommerce_service`.
62599060435de62698e9d4b9
class WReN(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_channels: int = 32, use_object_triples: bool = False, use_layer_norm: bool = False): <NEW_LINE> <INDENT> super(WReN, self).__init__() <NEW_LINE> if use_object_triples: <NEW_LINE> <INDENT> self.group_objects = GroupObjectsIntoTriples(num_objects=8) <NEW_LINE> self.group_objects_with = GroupObjectsIntoTriplesWith() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.group_objects = GroupObjectsIntoPairs(num_objects=8) <NEW_LINE> self.group_objects_with = GroupObjectsIntoPairsWith() <NEW_LINE> <DEDENT> self.cnn = nn.Sequential( ConvBNReLU(1, num_channels, kernel_size=3, stride=2), ConvBNReLU(num_channels, num_channels, kernel_size=3, stride=2), ConvBNReLU(num_channels, num_channels, kernel_size=3, stride=2), ConvBNReLU(num_channels, num_channels, kernel_size=3, stride=2) ) <NEW_LINE> self.object_size = num_channels * 9 * 9 <NEW_LINE> self.object_tuple_size = (3 if use_object_triples else 2) * (self.object_size + 9) <NEW_LINE> self.tag_panel_embeddings = TagPanelEmbeddings() <NEW_LINE> self.g = relation_network.G( depth=3, in_size=self.object_tuple_size, out_size=self.object_tuple_size, use_layer_norm=False ) <NEW_LINE> self.norm = nn.LayerNorm(self.object_tuple_size) if use_layer_norm else Identity() <NEW_LINE> self.f = relation_network.F( depth=2, object_size=self.object_tuple_size, out_size=1 ) <NEW_LINE> <DEDENT> def forward(self, x: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> batch_size, num_panels, height, width = x.size() <NEW_LINE> x = x.view(batch_size * num_panels, 1, height, width) <NEW_LINE> x = self.cnn(x) <NEW_LINE> x = x.view(batch_size, num_panels, self.object_size) <NEW_LINE> x = self.tag_panel_embeddings(x) <NEW_LINE> context_objects = x[:, :8, :] <NEW_LINE> choice_objects = x[:, 8:, :] <NEW_LINE> context_pairs = self.group_objects(context_objects) <NEW_LINE> context_g_out = self.g(context_pairs) <NEW_LINE> f_out = torch.zeros(batch_size, 8, device=x.device).type_as(x) <NEW_LINE> for i in range(8): <NEW_LINE> <INDENT> context_choice_pairs = self.group_objects_with(context_objects, choice_objects[:, i, :]) <NEW_LINE> context_choice_g_out = self.g(context_choice_pairs) <NEW_LINE> relations = context_g_out + context_choice_g_out <NEW_LINE> relations = self.norm(relations) <NEW_LINE> f_out[:, i] = self.f(relations).squeeze() <NEW_LINE> <DEDENT> return f_out
Wild Relation Network (WReN) [1] for solving Raven's Progressive Matrices. The originally proposed model uses a Relation Network (RN) [2] which works on object pairs. This implementation allows to extend the RN to work on object triples (by setting use_object_triples=True). Using larger tuples is impractical, as the memory requirement grows exponentially, with complexity O(num_objects ^ rn_tuple_size). After extension to triples, the model resembles the Logic Embedding Network (LEN) [3]. [1] Santoro, Adam, et al. "Measuring abstract reasoning in neural networks." ICML 2018 [2] Santoro, Adam, et al. "A simple neural network module for relational reasoning." NeurIPS 2017 [3] Zheng, Kecheng, Zheng-Jun Zha, and Wei Wei. "Abstract reasoning with distracting features." NeurIPS 2019
6259906024f1403a92686427
class TestCompareXLSXFiles(ExcelComparisonTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.maxDiff = None <NEW_LINE> filename = 'rich_string12.xlsx' <NEW_LINE> test_dir = 'xlsxwriter/test/comparison/' <NEW_LINE> self.got_filename = test_dir + '_test_' + filename <NEW_LINE> self.exp_filename = test_dir + 'xlsx_files/' + filename <NEW_LINE> self.ignore_files = [] <NEW_LINE> self.ignore_elements = {} <NEW_LINE> <DEDENT> def test_create_file(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.set_column('A:A', 30) <NEW_LINE> worksheet.set_row(2, 60) <NEW_LINE> bold = workbook.add_format({'bold': 1}) <NEW_LINE> italic = workbook.add_format({'italic': 1}) <NEW_LINE> wrap = workbook.add_format({'text_wrap': 1}) <NEW_LINE> worksheet.write('A1', 'Foo', bold) <NEW_LINE> worksheet.write('A2', 'Bar', italic) <NEW_LINE> worksheet.write_rich_string('A3', "This is\n", bold, "bold\n", "and this is\n", italic, 'italic', wrap) <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual()
Test file created by XlsxWriter against a file created by Excel.
625990608e71fb1e983bd17d
class IssueViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Issue.objects.all() <NEW_LINE> serializer_class = IssueSerializer <NEW_LINE> permission_classes = (permissions.IsAuthenticatedOrReadOnly,) <NEW_LINE> def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if(request.query_params): <NEW_LINE> <INDENT> serializer = self.get_serializer(data=request.query_params) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> serializer = self.get_serializer(data=request.data) <NEW_LINE> <DEDENT> serializer.is_valid(raise_exception=True) <NEW_LINE> self.perform_create(serializer) <NEW_LINE> headers = self.get_success_headers(serializer.data) <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) <NEW_LINE> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(created_by=APIUser.objects.get(id=self.request.user.id)) <NEW_LINE> <DEDENT> def update(self, request, *args, **kwargs): <NEW_LINE> <INDENT> partial = kwargs.pop('partial', False) <NEW_LINE> instance = self.get_object() <NEW_LINE> if(request.query_params): <NEW_LINE> <INDENT> serializer = self.get_serializer(instance, data=request.query_params, partial=partial) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> serializer = self.get_serializer(instance, data=request.data, partial=partial) <NEW_LINE> <DEDENT> serializer.is_valid(raise_exception=True) <NEW_LINE> self.perform_update(serializer) <NEW_LINE> return Response(serializer.data)
This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions.
625990607cff6e4e811b70f8
class JSONParser(Parser): <NEW_LINE> <INDENT> options = [ 'property', ] <NEW_LINE> def __init__(self, loader, force_parse=False, property=None): <NEW_LINE> <INDENT> self.__loader = loader <NEW_LINE> self.__property = property <NEW_LINE> self.__force_parse = force_parse <NEW_LINE> self.__extended_rows = None <NEW_LINE> self.__encoding = None <NEW_LINE> self.__bytes = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def closed(self): <NEW_LINE> <INDENT> return self.__bytes is None or self.__bytes.closed <NEW_LINE> <DEDENT> def open(self, source, encoding=None): <NEW_LINE> <INDENT> self.close() <NEW_LINE> self.__encoding = encoding <NEW_LINE> self.__bytes = self.__loader.load(source, mode='b', encoding=encoding) <NEW_LINE> if self.__encoding: <NEW_LINE> <INDENT> self.__encoding.lower() <NEW_LINE> <DEDENT> self.reset() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if not self.closed: <NEW_LINE> <INDENT> self.__bytes.close() <NEW_LINE> <DEDENT> <DEDENT> def reset(self): <NEW_LINE> <INDENT> helpers.reset_stream(self.__bytes) <NEW_LINE> self.__extended_rows = self.__iter_extended_rows() <NEW_LINE> <DEDENT> @property <NEW_LINE> def encoding(self): <NEW_LINE> <INDENT> return self.__encoding <NEW_LINE> <DEDENT> @property <NEW_LINE> def extended_rows(self): <NEW_LINE> <INDENT> return self.__extended_rows <NEW_LINE> <DEDENT> def __iter_extended_rows(self): <NEW_LINE> <INDENT> path = 'item' <NEW_LINE> if self.__property is not None: <NEW_LINE> <INDENT> path = '%s.item' % self.__property <NEW_LINE> <DEDENT> items = ijson.items(self.__bytes, path) <NEW_LINE> for row_number, item in enumerate(items, start=1): <NEW_LINE> <INDENT> if isinstance(item, (tuple, list)): <NEW_LINE> <INDENT> yield (row_number, None, list(item)) <NEW_LINE> <DEDENT> elif isinstance(item, dict): <NEW_LINE> <INDENT> keys = [] <NEW_LINE> values = [] <NEW_LINE> for key in sorted(item.keys()): <NEW_LINE> <INDENT> keys.append(key) <NEW_LINE> values.append(item[key]) <NEW_LINE> <DEDENT> yield (row_number, list(keys), list(values)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not self.__force_parse: <NEW_LINE> <INDENT> message = 'JSON item has to be list or dict' <NEW_LINE> raise exceptions.SourceError(message) <NEW_LINE> <DEDENT> yield (row_number, None, [])
Parser to parse JSON data format.
625990600a50d4780f706918
class CurrentSiteThemeMiddleware(object): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> request.site_theme = SiteTheme.get_theme(request.site)
Middleware that sets `site_theme` attribute to request object.
6259906099cbb53fe6832594
class GrokUILayout(grok.Layout): <NEW_LINE> <INDENT> grok.context(IGrokUIRealm) <NEW_LINE> title = u"Grok User Interface" <NEW_LINE> def update(self): <NEW_LINE> <INDENT> resource.grok_css.need() <NEW_LINE> resource.favicon.need() <NEW_LINE> self.baseurl = absoluteURL(self.context, self.request) + '/'
The general layout for the administration
6259906001c39578d7f1428e
class IOSampleReceived(XBeeEvent): <NEW_LINE> <INDENT> pass
This event is fired when a XBee receives an IO packet. This includes: 1. IO data sample RX indicator packet. 2. RX IO 16 packet. 3. RX IO 64 packet. The callbacks that handle this event will receive the following arguments: 1. io_sample (:class:`.IOSample`): the received IO sample. 2. sender (:class:`.RemoteXBeeDevice`): the remote XBee device who has sent the packet. 3. time (Integer): the time in which the packet was received. .. seealso:: | :class:`.IOSample` | :class:`.RemoteXBeeDevice` | :class:`.XBeeEvent`
625990602ae34c7f260ac799
class DecryptResource: <NEW_LINE> <INDENT> def on_post(self, req, resp): <NEW_LINE> <INDENT> data = req.media['data'] <NEW_LINE> password = req.media['password'] <NEW_LINE> result = decryptData(data, password) <NEW_LINE> resp.media = { "OK": "true", "result": { "decrypted": json.loads(result['decrypted']), "timeMs": result['timeMs'] } } <NEW_LINE> <DEDENT> def on_get(self, req, resp): <NEW_LINE> <INDENT> pass
handles decryption
6259906067a9b606de5475fb
class camera_list(authorized_event): <NEW_LINE> <INDENT> pass
A new camera event has been generated by the client
62599060004d5f362081fb49
class DocumentsUnit(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.documents_unit={ "_id":"", "title":"", "court":"", "url":"", "content":"", "criminal":"", "date":"" }
the class in define a dict of userinfo,include:
6259906007f4c71912bb0af1
class AggregateOutputs(luigi.Task): <NEW_LINE> <INDENT> task_namespace = 'output' <NEW_LINE> host = luigi.Parameter() <NEW_LINE> job = luigi.Parameter() <NEW_LINE> launch_id = luigi.Parameter() <NEW_LINE> state = luigi.Parameter() <NEW_LINE> outputs = luigi.ListParameter() <NEW_LINE> def requires(self): <NEW_LINE> <INDENT> for item in self.outputs: <NEW_LINE> <INDENT> if item == 'crawl.log': <NEW_LINE> <INDENT> stage = 'final' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stage = item[-22:] <NEW_LINE> <DEDENT> yield AssembleOutput(self.host, self.job, self.launch_id, stage) <NEW_LINE> <DEDENT> <DEDENT> def output(self): <NEW_LINE> <INDENT> return luigi.LocalTarget( '{}/{}'.format(state().folder, target_name('04.assembled', self.job, self.launch_id, "%s.%s" %(len(self.outputs), self.state)))) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> aggregate = {} <NEW_LINE> if isinstance(self.input(), list): <NEW_LINE> <INDENT> inputs = self.input() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inputs = [ self.input() ] <NEW_LINE> <DEDENT> for input in inputs: <NEW_LINE> <INDENT> logger.info("Reading %s" % input.path) <NEW_LINE> item = json.load(input.open()) <NEW_LINE> for key in item.keys(): <NEW_LINE> <INDENT> if isinstance(item[key],list): <NEW_LINE> <INDENT> current = aggregate.get(key, []) <NEW_LINE> current.extend(item[key]) <NEW_LINE> <DEDENT> elif isinstance(item[key], dict): <NEW_LINE> <INDENT> current = aggregate.get(key, {}) <NEW_LINE> current.update(item[key]) <NEW_LINE> <DEDENT> elif item[key]: <NEW_LINE> <INDENT> current = item[key] <NEW_LINE> <DEDENT> aggregate[key] = current <NEW_LINE> <DEDENT> <DEDENT> logger.info("Aggregate: %s" % aggregate) <NEW_LINE> with self.output().open('w') as f: <NEW_LINE> <INDENT> f.write('{}'.format(json.dumps(aggregate, indent=4)))
Takes the results of the ordered series of checkpoints/crawl stages and builds versioned aggregated packages from them.
6259906066673b3332c31ab0
class Dataset(object): <NEW_LINE> <INDENT> data_model = None <NEW_LINE> def __init__(self, queryset, context): <NEW_LINE> <INDENT> self.queryset = queryset <NEW_LINE> self.context = context <NEW_LINE> self.models = [] <NEW_LINE> for item in queryset: <NEW_LINE> <INDENT> self.models.append(self.data_model(item))
Dataset is a class to gather relative items into a group.
625990618da39b475be0489c
class Request: <NEW_LINE> <INDENT> def to_bytes(self): <NEW_LINE> <INDENT> result = io.BytesIO() <NEW_LINE> result.write(ServerIO.HEADER) <NEW_LINE> ServerIO.write_bytes(result, ServerIO.PROTOCOL_VERSION) <NEW_LINE> return result.getvalue() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_from_bytes(bytes_): <NEW_LINE> <INDENT> input_ = io.BytesIO(bytes_) <NEW_LINE> header = input_.read(len(ServerIO.HEADER)) <NEW_LINE> if header != ServerIO.HEADER: <NEW_LINE> <INDENT> raise ServerError('Invalid request payload') <NEW_LINE> <DEDENT> version = ServerIO.read_bytes(input_) <NEW_LINE> if version != ServerIO.PROTOCOL_VERSION: <NEW_LINE> <INDENT> raise ServerError( 'Version mismatch. The server is running a different version ' 'of the eink-server code than the Inkplate device is.') <NEW_LINE> <DEDENT> return Request()
A parsed object representation of a request payload.
62599061baa26c4b54d50956
class UniformSpaceSampler(SpaceSampler): <NEW_LINE> <INDENT> with_zero_values = Bool(False) <NEW_LINE> def generate_space_sample(self, **kwargs): <NEW_LINE> <INDENT> yield from self._get_sample_point() <NEW_LINE> <DEDENT> def _get_sample_point(self): <NEW_LINE> <INDENT> n_combinations = self.resolution <NEW_LINE> if not self.with_zero_values: <NEW_LINE> <INDENT> n_combinations += self.dimension <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> scaling = 1.0 / (n_combinations - 1) <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> yield [1.0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for int_w in self._int_weights(): <NEW_LINE> <INDENT> yield [scaling * val for val in int_w] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _int_weights(self, resolution=None, dimension=None): <NEW_LINE> <INDENT> if dimension is None: <NEW_LINE> <INDENT> dimension = self.dimension <NEW_LINE> <DEDENT> if resolution is None: <NEW_LINE> <INDENT> resolution = self.resolution <NEW_LINE> if not self.with_zero_values: <NEW_LINE> <INDENT> resolution += dimension <NEW_LINE> <DEDENT> <DEDENT> if dimension == 1: <NEW_LINE> <INDENT> yield [resolution - 1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.with_zero_values: <NEW_LINE> <INDENT> integers = np.arange(resolution - 1, -1, -1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> integers = np.arange(resolution - 2, 0, -1) <NEW_LINE> <DEDENT> for i in integers: <NEW_LINE> <INDENT> for entry in self._int_weights(resolution - i, dimension - 1): <NEW_LINE> <INDENT> yield [i] + entry
UniformSpaceSampler provides all possible combinations of weights adding to 1, such that the sampling points are uniformly distributed along each axis. For example, a dimension 3 will give all combinations (x, y, z), where $ x + y + z = 1.0, and (x, y, z) can realise only specified equidistant values. The `resolution` parameter indicates how many divisions along a single dimension will be performed. For example `resolution = 3` will evaluate for x being 0.0, 0.5 and 1.0. Parameter `with_zero_values` controls the presence of zero valued entries. If `with_zero_values` parameter is set to False, then no zero valued weights will be included, though the number of points sampled will remain the same.
62599061379a373c97d9a6d8
class PyAssocCObject(object): <NEW_LINE> <INDENT> def __new__(cls): <NEW_LINE> <INDENT> raise Exception('This class just for typing, can not be instanced!')
An internal class.
6259906124f1403a92686428
class BDPC_Sensor(vw.vw_Base): <NEW_LINE> <INDENT> def __init__(self, master, model, sensor, **kwargs): <NEW_LINE> <INDENT> vw.vw_Base.__init__(self, master, 8, 2) <NEW_LINE> self.instr = model <NEW_LINE> self.sensor = sensor <NEW_LINE> name = self.instr.getSensorDescription(sensor) <NEW_LINE> units = self.instr.getSensorUnits(sensor) <NEW_LINE> self.f_top = Tk.Frame(self) <NEW_LINE> self.l_name = Tk.Label(self.f_top, width=25, font=("Purisa", 12), text=name, anchor=Tk.W, justify=Tk.LEFT) <NEW_LINE> self.l_name.pack(side=Tk.LEFT) <NEW_LINE> self.f_top.grid(row=0, column=0, sticky=Tk.N+Tk.E+Tk.W) <NEW_LINE> self.f_bottom = Tk.Frame(self) <NEW_LINE> self.l_units = Tk.Label(self.f_bottom, width=2, font=("Purisa", 12), text=units) <NEW_LINE> self.l_units.pack(side=Tk.RIGHT) <NEW_LINE> self.val = Tk.StringVar() <NEW_LINE> self.val.set("0") <NEW_LINE> self.l_data = Tk.Label(self.f_bottom, width=6, font=("Purisa", 10), textvariable=self.val, relief=Tk.RIDGE) <NEW_LINE> self.l_data.pack(side=Tk.RIGHT) <NEW_LINE> self.l_calibrate = Tk.Button(self.f_bottom, text="Calibrate", font=("Purisa", 10), state=Tk.DISABLED) <NEW_LINE> self.l_calibrate.pack(side=Tk.LEFT) <NEW_LINE> self.f_bottom.grid(row=1, column=0, sticky=Tk.E+Tk.S+Tk.W) <NEW_LINE> self.update_interval = kwargs.get('update_interval', None) <NEW_LINE> self._schedule_update() <NEW_LINE> <DEDENT> def cb_update(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val = self.instr.getSensorValue(self.sensor) <NEW_LINE> val = "{:.2f}".format(val) <NEW_LINE> self.val.set(val) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.l_data.config(bg="red") <NEW_LINE> <DEDENT> <DEDENT> def get(self): <NEW_LINE> <INDENT> return self.val.get()
ICP Sensor Class is a specific type of register for sensors. TODO: Add Calibration editor
62599061dd821e528d6da4db
class StackedResidual(Model): <NEW_LINE> <INDENT> INCEPT_TYPE = 'incept' <NEW_LINE> STACKED_CONV_TYPE = 'stacked_conv' <NEW_LINE> @configurable(get_configs_view(), with_name=True) <NEW_LINE> def __init__(self, name, input_tensor, *, nb_layers=None, block_type=None, **config): <NEW_LINE> <INDENT> super().__init__(name, inputs=input_tensor, nb_layers=nb_layers, block_type=block_type, **config) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _default_config(cls): <NEW_LINE> <INDENT> from dxpy.collections.dicts import combine_dicts <NEW_LINE> return combine_dicts({ 'nb_layers': 10, 'block_type': cls.INCEPT_TYPE, }, super()._default_config()) <NEW_LINE> <DEDENT> def _kernel(self, feeds): <NEW_LINE> <INDENT> x = feeds[NodeKeys.INPUT] <NEW_LINE> for i in range(self.param('nb_layers')): <NEW_LINE> <INDENT> name = self.name / 'res_{}'.format(i) <NEW_LINE> if self.param('block_type') == self.INCEPT_TYPE: <NEW_LINE> <INDENT> x = ResidualIncept(name, x)() <NEW_LINE> <DEDENT> elif self.param('block_type') == self.STACKED_CONV_TYPE: <NEW_LINE> <INDENT> x = ResidualStackedConv(name, x)() <NEW_LINE> <DEDENT> <DEDENT> return x
Sub model name: sub_{0..nb_layers}
62599061460517430c432bad
class Product(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(100), unique=True) <NEW_LINE> description = db.Column(db.String(200)) <NEW_LINE> price = db.Column(db.Float) <NEW_LINE> qty = db.Column(db.Integer)
class to hold product data
6259906132920d7e50bc76fa
class Match(object): <NEW_LINE> <INDENT> @property <NEW_LINE> def match(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @match.setter <NEW_LINE> def match(self, value): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.match == getattr(other, 'match', None) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s(%s)" % (self.__class__.__name__, self.match) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__()
Represent match action in a route map
6259906132920d7e50bc76fb
class DKPro: <NEW_LINE> <INDENT> def __init__(self, jar, xms="4g"): <NEW_LINE> <INDENT> self.jar = jar <NEW_LINE> self.xms = xms <NEW_LINE> self._check() <NEW_LINE> <DEDENT> def process(self, **parameters): <NEW_LINE> <INDENT> return dkpro.core.call(self.jar, self.xms, **parameters) <NEW_LINE> <DEDENT> def _check(self): <NEW_LINE> <INDENT> jar = Path(self.jar) <NEW_LINE> configs = Path(jar.parent, "configs") <NEW_LINE> if not jar.exists() or jar.suffix != ".jar": <NEW_LINE> <INDENT> raise OSError("DARIAH-DKPro-Wrapper JAR file not found.") <NEW_LINE> <DEDENT> if not configs.exists(): <NEW_LINE> <INDENT> raise OSError("DARIAH-DKPro-Wrapper configs folder not found.")
DARIAH DKPro-Wrapper.
62599061a219f33f346c7ebb
class FmtFontsize(TableFormatter): <NEW_LINE> <INDENT> def __init__(self, fontsize, format='px', rows=None, columns=None, apply_to_header_and_index=True): <NEW_LINE> <INDENT> super(FmtFontsize, self).__init__(rows, columns) <NEW_LINE> self.fontsize = fontsize <NEW_LINE> self.format = format <NEW_LINE> return <NEW_LINE> <DEDENT> def _create_cell_level_css(self, data): <NEW_LINE> <INDENT> return 'font-size:' + str(self.fontsize) + self.format
Set fontsize in table cells.
6259906107f4c71912bb0af2
class Selector(ABC, Generic[AnyStr]): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def __call__(self, _entry: "os.DirEntry[AnyStr]") -> bool: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> def __or__(self, other: "Selector") -> "SelectAny": <NEW_LINE> <INDENT> parts: List[Selector] = [] <NEW_LINE> for s in [self, other]: <NEW_LINE> <INDENT> if isinstance(s, SelectAny): <NEW_LINE> <INDENT> parts.extend(s.selectors) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parts.append(s) <NEW_LINE> <DEDENT> <DEDENT> return SelectAny(parts)
.. versionadded:: 0.3.0 Base class for selectors
625990614f88993c371f1079
class LongitudinalCE: <NEW_LINE> <INDENT> def __init__(self, model_files, labels=None): <NEW_LINE> <INDENT> self.models = [kenlm.Model(f) for f in model_files] <NEW_LINE> self.labels = labels or range(len(self.models)) <NEW_LINE> <DEDENT> def score(self, sent): <NEW_LINE> <INDENT> return [cross_entropy(model.score(sent)) for model in self.models] <NEW_LINE> <DEDENT> def plot(self, sentences): <NEW_LINE> <INDENT> if isinstance(sentences, basestring): <NEW_LINE> <INDENT> sentences = [sentences] <NEW_LINE> <DEDENT> x = range(len(self.labels))[4:-2] <NEW_LINE> ax = plt.subplot() <NEW_LINE> ax.set_color_cycle(colors.mpl_colors) <NEW_LINE> for sentence in sentences: <NEW_LINE> <INDENT> scores = self.score(sentence) <NEW_LINE> plt.plot(x, smooth(scores, 6)[4:-2], lw=2) <NEW_LINE> <DEDENT> spacedLabels = [label if i % 6==0 else '' for i, label in enumerate(self.labels)][4:-2] <NEW_LINE> plt.xticks(x, spacedLabels, rotation='vertical') <NEW_LINE> plt.legend(sentences, loc=0) <NEW_LINE> plt.xlabel("Time") <NEW_LINE> plt.ylabel("Cross-entropy (less-surprising is lower)") <NEW_LINE> plt.title("Hacker News Community change over time") <NEW_LINE> plt.show()
Pass a list of strings, each a filepath to a kenlm model
625990614a966d76dd5f05a8
class SmoothedValue(object): <NEW_LINE> <INDENT> def __init__(self, window_size): <NEW_LINE> <INDENT> self.deque = deque(maxlen=window_size) <NEW_LINE> <DEDENT> def add_value(self, value): <NEW_LINE> <INDENT> self.deque.append(value) <NEW_LINE> <DEDENT> def get_median_value(self): <NEW_LINE> <INDENT> return np.median(self.deque)
Track a series of values and provide access to smoothed values over a window or the global series average.
625990615166f23b2e244a87
class UserProfile(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length=255, unique=True) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> objects = UserProfileManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = ['name'] <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name
Database model for users in the system
62599061ac7a0e7691f73b99
class UnicastDnsSdClientProtocol(asyncio.Protocol): <NEW_LINE> <INDENT> def __init__(self, services: typing.List[str], host: str, timeout: int): <NEW_LINE> <INDENT> self.queries = create_service_queries(services, QueryType.PTR) <NEW_LINE> self.host = host <NEW_LINE> self.timeout = timeout <NEW_LINE> self.transport = None <NEW_LINE> self.parser: ServiceParser = ServiceParser() <NEW_LINE> self.semaphore: asyncio.Semaphore = asyncio.Semaphore(value=0) <NEW_LINE> self.received_responses: int = 0 <NEW_LINE> self._task: typing.Optional[asyncio.Future] = None <NEW_LINE> <DEDENT> async def get_response(self) -> Response: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> await asyncio.wait_for( self.semaphore.acquire(), timeout=self.timeout, ) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._finished() <NEW_LINE> <DEDENT> if self._task: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> await self._task <NEW_LINE> <DEDENT> except asyncio.CancelledError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> services = self.parser.parse() <NEW_LINE> return Response( services=services, deep_sleep=False, model=_get_model(services), ) <NEW_LINE> <DEDENT> def connection_made(self, transport) -> None: <NEW_LINE> <INDENT> self.transport = transport <NEW_LINE> self._task = asyncio.ensure_future(self._resend_loop()) <NEW_LINE> <DEDENT> async def _resend_loop(self): <NEW_LINE> <INDENT> for _ in range(math.ceil(self.timeout)): <NEW_LINE> <INDENT> for query in self.queries: <NEW_LINE> <INDENT> log_binary( _LOGGER, "Sending DNS request to " + self.host, level=TRAFFIC_LEVEL, Data=query, ) <NEW_LINE> self.transport.sendto(query) <NEW_LINE> <DEDENT> await asyncio.sleep(1) <NEW_LINE> <DEDENT> <DEDENT> def datagram_received(self, data: bytes, _) -> None: <NEW_LINE> <INDENT> log_binary( _LOGGER, "Received DNS response from " + self.host, level=TRAFFIC_LEVEL, Data=data, Index=self.received_responses + 1, Total=len(self.queries), ) <NEW_LINE> self.parser.add_message(DnsMessage().unpack(data)) <NEW_LINE> self.received_responses += 1 <NEW_LINE> if self.received_responses == len(self.queries): <NEW_LINE> <INDENT> self._finished() <NEW_LINE> if self.transport: <NEW_LINE> <INDENT> self.transport.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def error_received(self, exc) -> None: <NEW_LINE> <INDENT> _LOGGER.debug("Error during DNS lookup for %s: %s", self.host, exc) <NEW_LINE> self._finished() <NEW_LINE> <DEDENT> def connection_lost(self, exc) -> None: <NEW_LINE> <INDENT> self._finished() <NEW_LINE> <DEDENT> def _finished(self) -> None: <NEW_LINE> <INDENT> self.semaphore.release() <NEW_LINE> if self._task: <NEW_LINE> <INDENT> self._task.cancel()
Protocol to make unicast requests.
62599061adb09d7d5dc0bc20
class TextUnitProperty(TimeStampedModel): <NEW_LINE> <INDENT> created_date = models.DateTimeField(auto_now_add=True) <NEW_LINE> modified_date = models.DateTimeField(auto_now=True) <NEW_LINE> created_by = models.ForeignKey(User, related_name="created_%(class)s_set", null=True, blank=True, db_index=False, on_delete=SET_NULL) <NEW_LINE> modified_by = models.ForeignKey(User, related_name="modified_%(class)s_set", null=True, blank=True, db_index=False, on_delete=SET_NULL) <NEW_LINE> text_unit = models.ForeignKey(TextUnit, db_index=True, on_delete=CASCADE) <NEW_LINE> key = models.CharField(max_length=1024, db_index=True) <NEW_LINE> value = models.CharField(max_length=1024, db_index=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('text_unit', 'key', 'value') <NEW_LINE> verbose_name_plural = 'Text Unit Properties' <NEW_LINE> indexes = [Index(fields=['text_unit', 'key', 'value'])] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "TextUnitProperty (text_unit_pk={0}, key={1}, value={2})" .format(self.text_unit.pk, self.key, self.value) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "TextUnitProperty (id={0})".format(self.id)
TextUnitProperty object model TextUnitProperty is a flexible class for creating key-value properties for a :class:`TextUnit<apps.document.models.TextUnit>`. Each TextUnit can have zero or more TextUnitProperty records, which may be used either at document ingestion to store metadata, such as Track Changes or annotations, or subsequently to store relevant information.
6259906155399d3f05627bd5
class Doublet2D(object): <NEW_LINE> <INDENT> def __init__(self, location, strength): <NEW_LINE> <INDENT> self.flow_type = 'doublet' <NEW_LINE> self.location = location <NEW_LINE> self.strength = strength <NEW_LINE> <DEDENT> @property <NEW_LINE> def xs(self): <NEW_LINE> <INDENT> return self.location[0] <NEW_LINE> <DEDENT> @xs.setter <NEW_LINE> def xs(self, value): <NEW_LINE> <INDENT> self.location[0] = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def ys(self): <NEW_LINE> <INDENT> return self.location[1] <NEW_LINE> <DEDENT> @ys.setter <NEW_LINE> def ys(self, value): <NEW_LINE> <INDENT> self.location[1] = value <NEW_LINE> <DEDENT> def get_velocity(self, xVals, yVals): <NEW_LINE> <INDENT> m1 = self.strength/(2*np.pi) <NEW_LINE> m2 = 1./((xVals - self.xs)**2 + (yVals - self.ys)**2)**2 <NEW_LINE> Vx = m1*m2*((yVals - self.ys)**2 - (xVals - self.xs)**2) <NEW_LINE> Vy = m1*m2*-2*(xVals - self.xs)*(yVals - self.ys) <NEW_LINE> return Vx,Vy <NEW_LINE> <DEDENT> def get_stream_function(self, xVals, yVals): <NEW_LINE> <INDENT> m1 = self.strength/(2*np.pi) <NEW_LINE> psi = m1*-1*(yVals - self.ys)/((xVals - self.xs)**2 + (yVals - self.ys)**2) <NEW_LINE> return psi <NEW_LINE> <DEDENT> def get_velocity_potential(self, xVals, yVals): <NEW_LINE> <INDENT> m1 = self.strength/(2*np.pi) <NEW_LINE> phi = m1*(xVals - self.xs)/((xVals - self.xs)**2 + (yVals - self.ys)**2) <NEW_LINE> return phi
Class method for modeling 2D doublet potential flow singularities.
625990614428ac0f6e659be8
class CosReduce(GATReduce): <NEW_LINE> <INDENT> def __init__(self, attn_drop, aggregator=None): <NEW_LINE> <INDENT> super(CosReduce, self).__init__(attn_drop, aggregator) <NEW_LINE> <DEDENT> def forward(self, nodes): <NEW_LINE> <INDENT> a1 = torch.unsqueeze(nodes.data['a1'], 1) <NEW_LINE> a2 = nodes.mailbox['a2'] <NEW_LINE> ft = nodes.mailbox['ft'] <NEW_LINE> a = a1 * a2 <NEW_LINE> a = a.sum(-1, keepdim=True) <NEW_LINE> e = F.softmax(F.leaky_relu(a), dim=1) <NEW_LINE> if self.attn_drop: <NEW_LINE> <INDENT> e = self.attn_drop(e) <NEW_LINE> <DEDENT> return {'accum': self.apply_agg(e * ft)}
used in Gaan
62599061cb5e8a47e493cce0
class Fitting(Boolean): <NEW_LINE> <INDENT> def Delete(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Insert(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Modify(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Select(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Plane = property(lambda self: object(), lambda self, v: None, lambda self: None)
Fitting()
62599061d6c5a102081e37da
class IThemeSpecific(IDefaultPloneLayer): <NEW_LINE> <INDENT> pass
Marker interface that defines a Zope 3 browser layer.
6259906163d6d428bbee3de3
class Boolean(_Type): <NEW_LINE> <INDENT> def __init__(self, **kw): <NEW_LINE> <INDENT> super(Boolean, self).__init__(type_="boolean", **kw)
Json-schema integer type
625990616e29344779b01d05
class NachosTime(TimeMeasurement): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> TimeMeasurement.__init__(self, 'tsc', value, 'Nachos', 0, 0)
NachosTime is a specific case of the Data Streams Post Processing TimeMeasurement class. The specificity to Nachos is NachosTime is always measured in Ticks, it is generated by Nachos, and because of the nature of Nachos, there is not any error associated with it.
625990614e4d562566373abd
class RawMem: <NEW_LINE> <INDENT> encoding = "" <NEW_LINE> cont = [] <NEW_LINE> hash = None <NEW_LINE> """ Abstract class RawMem """ <NEW_LINE> def __init__(self, buf=None, rawASCII=False): <NEW_LINE> <INDENT> this_buf = [] if buf is None else buf <NEW_LINE> self.msgs = this_buf <NEW_LINE> self.hash = dict() <NEW_LINE> if rawASCII: <NEW_LINE> <INDENT> self.decoding = "ascii" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.decoding = "iso-8859-1" <NEW_LINE> <DEDENT> self.encoding = self.decoding <NEW_LINE> self._init_buf(this_buf) <NEW_LINE> self.leg = [] <NEW_LINE> <DEDENT> def _init_buf(self, buf): <NEW_LINE> <INDENT> if isinstance(buf, str): <NEW_LINE> <INDENT> self.cont = buf.split("\n") <NEW_LINE> <DEDENT> elif isinstance(buf, list): <NEW_LINE> <INDENT> self.cont = buf <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert False <NEW_LINE> <DEDENT> <DEDENT> def simpler_str(self, s): <NEW_LINE> <INDENT> if isinstance(s, str): <NEW_LINE> <INDENT> a = simpler_ascii( s ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a = "?" <NEW_LINE> <DEDENT> return a <NEW_LINE> <DEDENT> def from_file(self, inName=None): <NEW_LINE> <INDENT> fIn = open(inName, "rb") <NEW_LINE> buf = fIn.read().decode( self.decoding ) <NEW_LINE> fIn.close() <NEW_LINE> self.cont = buf.split("\n") <NEW_LINE> return True <NEW_LINE> <DEDENT> def out_str(self, s, isTextStream=True): <NEW_LINE> <INDENT> if isTextStream: <NEW_LINE> <INDENT> a = s <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a = s.encode(self.encoding) <NEW_LINE> <DEDENT> return a <NEW_LINE> <DEDENT> def to_stream(self, aStream, a): <NEW_LINE> <INDENT> code = -1 <NEW_LINE> try: <NEW_LINE> <INDENT> aStream.write( a ) <NEW_LINE> code = 0 <NEW_LINE> <DEDENT> except UnicodeEncodeError: <NEW_LINE> <INDENT> s = self.simpler_str( a ) <NEW_LINE> aStream.write( s ) <NEW_LINE> <DEDENT> return code
Raw Memory class
62599061435de62698e9d4bd
class FileHandler(object): <NEW_LINE> <INDENT> def __init__(self, mode): <NEW_LINE> <INDENT> self.file_name = "ProblemAndAnswer.txt" <NEW_LINE> self.mode = mode <NEW_LINE> self.file_object = open(self.file_name, self.mode) <NEW_LINE> <DEDENT> def mod_string(self): <NEW_LINE> <INDENT> defined_string = self.file_object.read() <NEW_LINE> defined_string = defined_string.split(" ") <NEW_LINE> del defined_string[-1] <NEW_LINE> return defined_string <NEW_LINE> <DEDENT> def write_answer(self, answer): <NEW_LINE> <INDENT> self.file_object.write(str(answer)) <NEW_LINE> <DEDENT> def close_file(self): <NEW_LINE> <INDENT> self.file_object.close()
Class that handles reading and writing to file
625990613d592f4c4edbc593
class bmcRouter(DirectRouter): <NEW_LINE> <INDENT> def _getFacade(self): <NEW_LINE> <INDENT> return Zuul.getFacade('BMCAdapter', self.context) <NEW_LINE> <DEDENT> def routerbs(self, deviceip, bootsequence, cfgboottype): <NEW_LINE> <INDENT> facade = self._getFacade() <NEW_LINE> devobject = self.context <NEW_LINE> success, message = facade.bootsequence( devobject, deviceip, bootsequence, cfgboottype) <NEW_LINE> if success: <NEW_LINE> <INDENT> return DirectResponse.succeed(message) <NEW_LINE> <DEDENT> return DirectResponse.fail(message) <NEW_LINE> <DEDENT> def routerfpc(self, deviceip, frupowercontrol): <NEW_LINE> <INDENT> facade = self._getFacade() <NEW_LINE> devobject = self.context <NEW_LINE> frunum = 1 <NEW_LINE> success, message = facade.frupowerctrl(devobject, deviceip, frunum, frupowercontrol) <NEW_LINE> if success: <NEW_LINE> <INDENT> return DirectResponse.succeed(message) <NEW_LINE> <DEDENT> return DirectResponse.fail(message)
BMC Router
625990617cff6e4e811b70fc
class StoneEncoderInterface(object): <NEW_LINE> <INDENT> def encode(self, validator, value): <NEW_LINE> <INDENT> raise NotImplementedError
Interface defining a stone object encoder.
62599061cc0a2c111447c62a
class TestFillNan(unittest.TestCase): <NEW_LINE> <INDENT> def test_fill_nan(self): <NEW_LINE> <INDENT> a = np.array([0.1, 0.2, np.nan, 0.4, 0.5]) <NEW_LINE> np.testing.assert_almost_equal( fill_nan(a), np.array([0.1, 0.2, 0.3, 0.4, 0.5]), decimal=7 ) <NEW_LINE> np.testing.assert_almost_equal( fill_nan(a, method="Constant", default=8.0), np.array([0.1, 0.2, 8.0, 0.4, 0.5]), decimal=7, )
Define :func:`colour.utilities.array.fill_nan` definition unit tests methods.
6259906191af0d3eaad3b4de
class Rq(): <NEW_LINE> <INDENT> def __init__(self,inid,name,pid,pname): <NEW_LINE> <INDENT> self.inid=0 <NEW_LINE> self.name=u'' <NEW_LINE> self.pid=0 <NEW_LINE> self.pname=u'' <NEW_LINE> self.cgid=0 <NEW_LINE> self.cgname=u'' <NEW_LINE> self.sb={} <NEW_LINE> <DEDENT> def addSb(self,tid,tname): <NEW_LINE> <INDENT> self.sb[tid]=tname <NEW_LINE> <DEDENT> def getSb(self): <NEW_LINE> <INDENT> return self.sb <NEW_LINE> <DEDENT> def addCg(self,cid,cname): <NEW_LINE> <INDENT> self.cgid=cid <NEW_LINE> self.cgname=cname <NEW_LINE> <DEDENT> def getCg(self): <NEW_LINE> <INDENT> return [self.cgid,self.cgname]
殖民入侵记录表
625990613eb6a72ae038bd16