code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class gre(packet_base.PacketBase): <NEW_LINE> <INDENT> _PACK_STR = "!BBH" <NEW_LINE> _CHECKSUM_PACK_STR = "!H2x" <NEW_LINE> _KEY_PACK_STR = "!I" <NEW_LINE> _SEQNUM_PACK_STR = "!I" <NEW_LINE> _MIN_LEN = struct.calcsize(_PACK_STR) <NEW_LINE> _CHECKSUM_LEN = struct.calcsize(_CHECKSUM_PACK_STR) <NEW_LINE> _KEY_LEN = struct.calcsize(_KEY_PACK_STR) <NEW_LINE> def __init__(self, protocol=ether.ETH_TYPE_IP, checksum=None, key=None, seq_number=None): <NEW_LINE> <INDENT> super(gre, self).__init__() <NEW_LINE> self.protocol = protocol <NEW_LINE> self.checksum = checksum <NEW_LINE> self.key = key <NEW_LINE> self.seq_number = seq_number <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parser(cls, buf): <NEW_LINE> <INDENT> present, version, protocol = struct.unpack_from(cls._PACK_STR, buf) <NEW_LINE> gre_offset = gre._MIN_LEN <NEW_LINE> checksum = None <NEW_LINE> key = None <NEW_LINE> seq_number = None <NEW_LINE> if present & GRE_CHECKSUM_FLG: <NEW_LINE> <INDENT> checksum, = struct.unpack_from(cls._CHECKSUM_PACK_STR, buf, gre_offset) <NEW_LINE> gre_offset += cls._CHECKSUM_LEN <NEW_LINE> <DEDENT> if present & GRE_KEY_FLG: <NEW_LINE> <INDENT> key, = struct.unpack_from(cls._KEY_PACK_STR, buf, gre_offset) <NEW_LINE> gre_offset += cls._KEY_LEN <NEW_LINE> <DEDENT> if present & GRE_SEQUENCE_NUM_FLG: <NEW_LINE> <INDENT> seq_number, = struct.unpack_from(cls._SEQNUM_PACK_STR, buf, gre_offset) <NEW_LINE> <DEDENT> msg = cls(protocol, checksum, key, seq_number) <NEW_LINE> from . import ethernet <NEW_LINE> gre._TYPES = ethernet.ethernet._TYPES <NEW_LINE> return msg, gre.get_packet_type(protocol), buf[gre_offset:] <NEW_LINE> <DEDENT> def serialize(self, payload=None, prev=None): <NEW_LINE> <INDENT> present = 0 <NEW_LINE> version = 0 <NEW_LINE> hdr = bytearray() <NEW_LINE> optional = bytearray() <NEW_LINE> if self.checksum: <NEW_LINE> <INDENT> present += GRE_CHECKSUM_FLG <NEW_LINE> optional += b'\x00' * self._CHECKSUM_LEN <NEW_LINE> <DEDENT> if self.key: <NEW_LINE> <INDENT> present += GRE_KEY_FLG <NEW_LINE> optional += struct.pack(self._KEY_PACK_STR, self.key) <NEW_LINE> <DEDENT> if self.seq_number: <NEW_LINE> <INDENT> present += GRE_SEQUENCE_NUM_FLG <NEW_LINE> optional += struct.pack(self._SEQNUM_PACK_STR, self.seq_number) <NEW_LINE> <DEDENT> msg_pack_into(self._PACK_STR, hdr, 0, present, version, self.protocol) <NEW_LINE> hdr += optional <NEW_LINE> if self.checksum: <NEW_LINE> <INDENT> self.checksum = packet_utils.checksum(hdr) <NEW_LINE> struct.pack_into(self._CHECKSUM_PACK_STR, hdr, self._MIN_LEN, self.checksum) <NEW_LINE> <DEDENT> return hdr | GRE (RFC2784,RFC2890) header encoder/decoder class.
An instance has the following attributes at least.
Most of them are same to the on-wire counterparts but in host byte order.
__init__ takes the corresponding args in this order.
============== ========================================================
Attribute Description
============== ========================================================
protocol Protocol Type field.
The Protocol Type is defined as "ETHER TYPES".
checksum Checksum field(optional).
When you set a value other than None,
this field will be automatically calculated.
key Key field(optional)
This field is intended to be used for identifying
an individual traffic flow within a tunnel.
seq_number Sequence Number field(optional)
============== ======================================================== | 62598fa8ac7a0e7691f72448 |
class MapValueError(ValueError): <NEW_LINE> <INDENT> pass | Illegal value for Map. | 62598fa85166f23b2e243315 |
class CandidateLocation(models.Model): <NEW_LINE> <INDENT> candidate = models.ForeignKey( 'Candidate', on_delete=models.CASCADE ) <NEW_LINE> location = models.ForeignKey( commons.Location, on_delete=models.PROTECT ) <NEW_LINE> current = models.BooleanField() | Describe the relation between Users and models, multiple users can have multiple locations and visa versa | 62598fa860cbc95b0636428a |
class EntityMap(models.Model): <NEW_LINE> <INDENT> appName = models.CharField(max_length=200, blank=False, null=False) <NEW_LINE> modelName = models.CharField(max_length=200, blank=False, null=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ("appName", "modelName") | DGT: Capa adicional para manejar
parametros de workflow
autonumericos y secuencias
permisos a nivel de campo ( fieldLevelSecurity ),
documentacion
acciones
replicar conttenttype
etc
Para manejar las vstas, se maneja directamente la protoOpcion, (se prodria crear un conttenttype )
?Exluyente - Incluyente
El nvel de acceso al ser excluyente, no podria sumar los permisos de los grupos,
seria necesario asignar un unico grupo ( Django group ) q defina los accesos a nivel de campos,
de tal forma q los grupos de Django seran de dos tipos,
** Debe ser incluyente para poder sumar,
** No todas las tablas manejaran esta restriccion
* Procedimiento
Por defecto se tienen todos los permisos; Las tablas;
La forma de registrarlos es de todas maneras sumando permisos; entonces
- se definen explicitamente las tablas q manejen fieldLevel securty ( EntityMap )
- se definen permisos por grupos
se manejan referecias debiles por nombre para poder importar/exportar la info,
de otra forma seria por contenttype
| 62598fa8d6c5a102081e2085 |
class PaymentFromSaleImportCSVStart(ModelView): <NEW_LINE> <INDENT> __name__ = 'import.csv.payment.from.sale.start' <NEW_LINE> profile_domain = fields.Function(fields.One2Many('profile.csv', None, 'Profile Domain', states={ 'invisible': True }), 'on_change_with_profile_domain') <NEW_LINE> profile = fields.Many2One('profile.csv', 'Profile CSV', required=True, domain=[ ('id', 'in', Eval('profile_domain')), ], depends=['profile_domain'] ) <NEW_LINE> import_file = fields.Binary('Import File', required=True) <NEW_LINE> attach = fields.Boolean('Attach File', help='Attach CSV file after import.') <NEW_LINE> @fields.depends('attach') <NEW_LINE> def on_change_with_profile_domain(self, name=None): <NEW_LINE> <INDENT> pool = Pool() <NEW_LINE> Model = pool.get('ir.model') <NEW_LINE> Profile = pool.get('profile.csv') <NEW_LINE> model, = Model.search([ ('model', '=', 'account.statement.line') ]) <NEW_LINE> profiles = Profile.search([ ('model', '=', model.id), ]) <NEW_LINE> return [p.id for p in profiles] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def default_profile(cls): <NEW_LINE> <INDENT> profiles = cls().on_change_with_profile_domain() <NEW_LINE> if len(profiles) == 1: <NEW_LINE> <INDENT> return profiles[0] <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def default_attach(cls): <NEW_LINE> <INDENT> return True | Payment From Sale Import CSV Start | 62598fa88da39b475be03121 |
class RangedDictVertexSlice(object): <NEW_LINE> <INDENT> __slots__ = [ "__ranged_dict", "__vertex_slice"] <NEW_LINE> def __init__(self, ranged_dict, vertex_slice): <NEW_LINE> <INDENT> self.__ranged_dict = ranged_dict <NEW_LINE> self.__vertex_slice = vertex_slice <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if not isinstance(key, str): <NEW_LINE> <INDENT> raise KeyError("Key must be a string") <NEW_LINE> <DEDENT> return _RangedListVertexSlice( self.__ranged_dict[key], self.__vertex_slice) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> ranged_list_vertex_slice = _RangedListVertexSlice( self.__ranged_dict[key], self.__vertex_slice) <NEW_LINE> ranged_list_vertex_slice.set_item(value) | A slice of a ranged dict to be used to update values
| 62598fa89c8ee8231304010f |
class StripePositiveIntegerField(StripeFieldMixin, models.PositiveIntegerField): <NEW_LINE> <INDENT> pass | A field used to define a PositiveIntegerField value according to djstripe logic. | 62598fa87d847024c075c301 |
class Mpl2dGraphicsView(QtGui.QWidget): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> QtGui.QWidget.__init__(self, parent) <NEW_LINE> self._myCanvas = Qt4Mpl2dCanvas(self) <NEW_LINE> self._myToolBar = MyNavigationToolbar(self, self._myCanvas) <NEW_LINE> self._vBox = QtGui.QVBoxLayout(self) <NEW_LINE> self._vBox.addWidget(self._myCanvas) <NEW_LINE> self._vBox.addWidget(self._myToolBar) <NEW_LINE> self._myImageIndex = 0 <NEW_LINE> self._myImageDict = dict() <NEW_LINE> self._2dPlot = None <NEW_LINE> return <NEW_LINE> <DEDENT> @property <NEW_LINE> def array2d(self): <NEW_LINE> <INDENT> return self._myCanvas.array2d <NEW_LINE> <DEDENT> def add_plot_2d(self, array2d, x_min, x_max, y_min, y_max, hold_prev_image=True, y_tick_label=None): <NEW_LINE> <INDENT> self._2dPlot = self._myCanvas.add_2d_plot(array2d, x_min, x_max, y_min, y_max, hold_prev_image, y_tick_label) <NEW_LINE> return self._2dPlot <NEW_LINE> <DEDENT> def add_image(self, imagefilename): <NEW_LINE> <INDENT> if os.path.exists(imagefilename) is False: <NEW_LINE> <INDENT> raise NotImplementedError("Image file %s does not exist." % (imagefilename)) <NEW_LINE> <DEDENT> self._myCanvas.addImage(imagefilename) <NEW_LINE> return <NEW_LINE> <DEDENT> @property <NEW_LINE> def canvas(self): <NEW_LINE> <INDENT> return self._myCanvas <NEW_LINE> <DEDENT> def clear_canvas(self): <NEW_LINE> <INDENT> return self._myCanvas.clear_canvas() <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> return self._myCanvas.draw() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def evt_view_updated(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def remove_last_plot(self): <NEW_LINE> <INDENT> if self._2dPlot is not None: <NEW_LINE> <INDENT> self._2dPlot.remove() <NEW_LINE> self._2dPlot = None <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> @property <NEW_LINE> def x_min(self): <NEW_LINE> <INDENT> return self._myCanvas.x_min <NEW_LINE> <DEDENT> @property <NEW_LINE> def x_max(self): <NEW_LINE> <INDENT> return self._myCanvas.x_max <NEW_LINE> <DEDENT> @property <NEW_LINE> def y_min(self): <NEW_LINE> <INDENT> return self._myCanvas.y_min <NEW_LINE> <DEDENT> @property <NEW_LINE> def y_max(self): <NEW_LINE> <INDENT> return self._myCanvas.y_max | A combined graphics view including matplotlib canvas and
a navigation tool bar for 2D image specifically | 62598fa816aa5153ce400440 |
class TEST11(PMEM2_MAP_DEVDAX): <NEW_LINE> <INDENT> test_case = "test_map_invalid_alignment" | DevDax map using invalid alignment in the offset | 62598fa83d592f4c4edbae0b |
@attr.s(cmp=False) <NEW_LINE> class Plan(object): <NEW_LINE> <INDENT> uid = attr.ib(None, init=False) <NEW_LINE> time = attr.ib(converter=int) <NEW_LINE> title = attr.ib() <NEW_LINE> location = attr.ib(None, converter=lambda x: x or "") <NEW_LINE> location_id = attr.ib(None, converter=lambda x: x or "") <NEW_LINE> author_id = attr.ib(None, init=False) <NEW_LINE> guests = attr.ib(None, init=False) <NEW_LINE> @property <NEW_LINE> def going(self): <NEW_LINE> <INDENT> return [ id_ for id_, status in (self.guests or {}).items() if status is GuestStatus.GOING ] <NEW_LINE> <DEDENT> @property <NEW_LINE> def declined(self): <NEW_LINE> <INDENT> return [ id_ for id_, status in (self.guests or {}).items() if status is GuestStatus.DECLINED ] <NEW_LINE> <DEDENT> @property <NEW_LINE> def invited(self): <NEW_LINE> <INDENT> return [ id_ for id_, status in (self.guests or {}).items() if status is GuestStatus.INVITED ] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_pull(cls, data): <NEW_LINE> <INDENT> rtn = cls( time=data.get("event_time"), title=data.get("event_title"), location=data.get("event_location_name"), location_id=data.get("event_location_id"), ) <NEW_LINE> rtn.uid = data.get("event_id") <NEW_LINE> rtn.author_id = data.get("event_creator_id") <NEW_LINE> rtn.guests = { x["node"]["id"]: GuestStatus[x["guest_list_state"]] for x in json.loads(data["guest_state_list"]) } <NEW_LINE> return rtn <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_fetch(cls, data): <NEW_LINE> <INDENT> rtn = cls( time=data.get("event_time"), title=data.get("title"), location=data.get("location_name"), location_id=str(data["location_id"]) if data.get("location_id") else None, ) <NEW_LINE> rtn.uid = data.get("oid") <NEW_LINE> rtn.author_id = data.get("creator_id") <NEW_LINE> rtn.guests = {id_: GuestStatus[s] for id_, s in data["event_members"].items()} <NEW_LINE> return rtn <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_graphql(cls, data): <NEW_LINE> <INDENT> rtn = cls( time=data.get("time"), title=data.get("event_title"), location=data.get("location_name"), ) <NEW_LINE> rtn.uid = data.get("id") <NEW_LINE> rtn.author_id = data["lightweight_event_creator"].get("id") <NEW_LINE> rtn.guests = { x["node"]["id"]: GuestStatus[x["guest_list_state"]] for x in data["event_reminder_members"]["edges"] } <NEW_LINE> return rtn | Represents a plan. | 62598fa8442bda511e95c393 |
class StockTaskQueueList: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.queues = {} <NEW_LINE> tmp='123456' <NEW_LINE> for i in range(0,5,1): <NEW_LINE> <INDENT> self.queues[tmp[i:i+2]]=TaskQueue(Queue()) <NEW_LINE> <DEDENT> self.doneMaps = {} <NEW_LINE> for m in range(0,5,1): <NEW_LINE> <INDENT> self.doneMaps[tmp[m:m+2]]={} <NEW_LINE> <DEDENT> <DEDENT> def clearOldData(self): <NEW_LINE> <INDENT> for list in self.queues.values(): <NEW_LINE> <INDENT> list.queue.queue.clear() <NEW_LINE> <DEDENT> <DEDENT> def toString(self): <NEW_LINE> <INDENT> rlt = '' <NEW_LINE> tmp='123456' <NEW_LINE> tmp1 = ['上市时间获取','股价URL待生成','季度股价待下载','季度股价待解析','数据待入库'] <NEW_LINE> for i in range(0,5,1): <NEW_LINE> <INDENT> rlt += tmp1[i]+':' + str(self.queues[tmp[i:i+2]].size())+' ' <NEW_LINE> <DEDENT> return rlt | job1 获取最新全量股票信息
1、从东方财富页面获取最新所有股票 code,name
2、逐个股票获取上市时间(用于后面生成季度股价url) 后续可以扩展为存储上市公司信息
job2 下载缺失的股价信息 数据库单只股票最大时间至当前日期的数据
3、生成需要下载的URL(新浪股票数据一个季度一个页面)
4、下载页面
5、解析页面
6、数据入库 | 62598fa87047854f4633f317 |
class APPend(SCPINode, SCPIQuery, SCPISet): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _cmd = "APPend" <NEW_LINE> args = ["<string>,<block_data>"] | MEMory:DATA:APPend
Arguments: <string>,<block_data> | 62598fa84e4d562566372363 |
class TestStaffPhoneReportingByElection(TestCase): <NEW_LINE> <INDENT> def test(self): <NEW_LINE> <INDENT> center = RegistrationCenterFactory() <NEW_LINE> elections = [ {'polling_start_time': now() - datetime.timedelta(days=60)}, {'polling_start_time': now() - datetime.timedelta(days=40)}, {'polling_start_time': now() - datetime.timedelta(days=20)}, ] <NEW_LINE> for election in elections: <NEW_LINE> <INDENT> election['polling_end_time'] = election['polling_start_time'] + datetime.timedelta(hours=6) <NEW_LINE> election['object'] = ElectionFactory( polling_start_time=election['polling_start_time'], polling_end_time=election['polling_end_time'], ) <NEW_LINE> election['staff_phone_1'] = StaffPhoneFactory( registration_center=center, creation_date=election['object'].work_start_time ) <NEW_LINE> election['staff_phone_2'] = StaffPhoneFactory( registration_center=center, creation_date=election['object'].work_end_time ) <NEW_LINE> <DEDENT> for i, election in enumerate(elections, start=1): <NEW_LINE> <INDENT> messages_for_center = message_log(election['object'])[center.center_id] <NEW_LINE> self.assertEqual(len(messages_for_center), i * 2) <NEW_LINE> for message in messages_for_center: <NEW_LINE> <INDENT> self.assertEqual(message['type'], 'phonelink') | StaffPhone objects aren't tied explicitly to an election, but
a StaffPhone object created after the end of an election shouldn't
be reported for that election.
Create two StaffPhone objects per election, one at the very start
and one at the very end. Verify that, for each election, the reported
messages are all StaffPhone objects up until the very end of that
election. | 62598fa863b5f9789fe850a3 |
class HuntApproval(HuntApprovalBase): <NEW_LINE> <INDENT> def __init__( self, data: user_pb2.ApiHuntApproval, username: str, context: context_lib.GrrApiContext, ): <NEW_LINE> <INDENT> super().__init__( hunt_id=utils.UrnStringToHuntId(data.subject.urn), approval_id=data.id, username=username, context=context) <NEW_LINE> self.data = data | Hunt approval object with fetched data. | 62598fa82ae34c7f260ab020 |
class SystemTestSuite(NoseTestSuite): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(SystemTestSuite, self).__init__(*args, **kwargs) <NEW_LINE> self.test_id = kwargs.get('test_id', self._default_test_id) <NEW_LINE> self.fasttest = kwargs.get('fasttest', False) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> super(SystemTestSuite, self).__enter__() <NEW_LINE> args = [self.root, '--settings=test'] <NEW_LINE> if self.fasttest: <NEW_LINE> <INDENT> args.append('--skip-collect') <NEW_LINE> <DEDENT> call_task('pavelib.assets.update_assets', args=args) <NEW_LINE> <DEDENT> @property <NEW_LINE> def cmd(self): <NEW_LINE> <INDENT> cmd = ( './manage.py {system} test --verbosity={verbosity} ' '{test_id} {test_opts} --traceback --settings=test'.format( system=self.root, verbosity=self.verbosity, test_id=self.test_id, test_opts=self.test_options_flags, ) ) <NEW_LINE> return self._under_coverage_cmd(cmd) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _default_test_id(self): <NEW_LINE> <INDENT> default_test_id = "{system}/djangoapps/* common/djangoapps/*".format( system=self.root ) <NEW_LINE> if self.root in ('lms', 'cms'): <NEW_LINE> <INDENT> default_test_id += " {system}/lib/*".format(system=self.root) <NEW_LINE> <DEDENT> if self.root == 'lms': <NEW_LINE> <INDENT> default_test_id += " {system}/tests.py".format(system=self.root) <NEW_LINE> <DEDENT> return default_test_id | TestSuite for lms and cms nosetests | 62598fa82c8b7c6e89bd3704 |
class DescribePersonSamplesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Type = None <NEW_LINE> self.PersonIds = None <NEW_LINE> self.Names = None <NEW_LINE> self.Tags = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Type = params.get("Type") <NEW_LINE> self.PersonIds = params.get("PersonIds") <NEW_LINE> self.Names = params.get("Names") <NEW_LINE> self.Tags = params.get("Tags") <NEW_LINE> self.Offset = params.get("Offset") <NEW_LINE> self.Limit = params.get("Limit") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | DescribePersonSamples请求参数结构体
| 62598fa8167d2b6e312b6eaf |
class AvroDouble(AvroNumber): <NEW_LINE> <INDENT> _schema = avro.schema.PrimitiveSchema("double") <NEW_LINE> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return "double" | Avro "double" type for 64-bit IEEE floating-point numbers. | 62598fa899cbb53fe6830e15 |
class Set_object_union(Set_object_binary): <NEW_LINE> <INDENT> def __init__(self, X, Y): <NEW_LINE> <INDENT> Set_object_binary.__init__(self, X, Y, "union", "\\cup") <NEW_LINE> <DEDENT> def is_finite(self): <NEW_LINE> <INDENT> return self._X.is_finite() and self._Y.is_finite() <NEW_LINE> <DEDENT> def __cmp__(self, right): <NEW_LINE> <INDENT> if not is_Set(right): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if not isinstance(right, Set_object_union): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if self._X == right._X and self._Y == right._Y or self._X == right._Y and self._Y == right._X: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return -1 <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for x in self._X: <NEW_LINE> <INDENT> yield x <NEW_LINE> <DEDENT> for y in self._Y: <NEW_LINE> <INDENT> yield y <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, x): <NEW_LINE> <INDENT> return x in self._X or x in self._Y <NEW_LINE> <DEDENT> def cardinality(self): <NEW_LINE> <INDENT> return self._X.cardinality() + self._Y.cardinality() | A formal union of two sets. | 62598fa8cc0a2c111447af4f |
class SystemParameter(_messages.Message): <NEW_LINE> <INDENT> httpHeader = _messages.StringField(1) <NEW_LINE> name = _messages.StringField(2) <NEW_LINE> urlQueryParameter = _messages.StringField(3) | Define a parameter's name and location. The parameter may be passed as
either an HTTP header or a URL query parameter, and if both are passed the
behavior is implementation-dependent.
Fields:
httpHeader: Define the HTTP header name to use for the parameter. It is
case insensitive.
name: Define the name of the parameter, such as "api_key", "alt",
"callback", and etc. It is case sensitive.
urlQueryParameter: Define the URL query parameter name to use for the
parameter. It is case sensitive. | 62598fa81f037a2d8b9e402b |
class MyMazeRobot(MazeRobot): <NEW_LINE> <INDENT> def autoRun(self): <NEW_LINE> <INDENT> raise NotImplementedError("autoRun:Not Implemented") <NEW_LINE> <DEDENT> def doAfterStop(self,runDirection,runDistance,stopReason): <NEW_LINE> <INDENT> raise NotImplementedError("doAfterStop:Not Implemented") | 要实现迷宫探索的机器人子类 | 62598fa88e71fb1e983bb9f1 |
class ProductReleaseVocabulary(SQLObjectVocabularyBase): <NEW_LINE> <INDENT> implements(IHugeVocabulary) <NEW_LINE> displayname = 'Select a Product Release' <NEW_LINE> step_title = 'Search' <NEW_LINE> _table = ProductRelease <NEW_LINE> _orderBy = [Product.q.name, ProductSeries.q.name, Milestone.q.name] <NEW_LINE> _clauseTables = ['Product', 'ProductSeries'] <NEW_LINE> def toTerm(self, obj): <NEW_LINE> <INDENT> productrelease = obj <NEW_LINE> productseries = productrelease.milestone.productseries <NEW_LINE> product = productseries.product <NEW_LINE> token = '%s/%s/%s' % ( product.name, productseries.name, productrelease.version) <NEW_LINE> return SimpleTerm( obj.id, token, '%s %s %s' % ( product.name, productseries.name, productrelease.version)) <NEW_LINE> <DEDENT> def getTermByToken(self, token): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> productname, productseriesname, dummy = token.split('/', 2) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise LookupError(token) <NEW_LINE> <DEDENT> obj = ProductRelease.selectOne( AND(ProductRelease.q.milestoneID == Milestone.q.id, Milestone.q.productseriesID == ProductSeries.q.id, ProductSeries.q.productID == Product.q.id, Product.q.name == productname, ProductSeries.q.name == productseriesname)) <NEW_LINE> try: <NEW_LINE> <INDENT> return self.toTerm(obj) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise LookupError(token) <NEW_LINE> <DEDENT> <DEDENT> def search(self, query, vocab_filter=None): <NEW_LINE> <INDENT> if not query: <NEW_LINE> <INDENT> return self.emptySelectResults() <NEW_LINE> <DEDENT> query = ensure_unicode(query).lower() <NEW_LINE> objs = self._table.select( AND( Milestone.q.id == ProductRelease.q.milestoneID, ProductSeries.q.id == Milestone.q.productseriesID, Product.q.id == ProductSeries.q.productID, OR( CONTAINSSTRING(Product.q.name, query), CONTAINSSTRING(ProductSeries.q.name, query), ) ), orderBy=self._orderBy ) <NEW_LINE> return objs | All `IProductRelease` objects vocabulary. | 62598fa83539df3088ecc1f3 |
class TestLinterPages(DefaultSiteTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> if not self.site.has_extension('Linter'): <NEW_LINE> <INDENT> self.skipTest( 'The site {} does not use Linter extension'.format(self.site)) <NEW_LINE> <DEDENT> <DEDENT> def test_linter_pages(self): <NEW_LINE> <INDENT> le = list(self.site.linter_pages( lint_categories='obsolete-tag|missing-end-tag', total=5)) <NEW_LINE> self.assertLessEqual(len(le), 5) <NEW_LINE> for entry in le: <NEW_LINE> <INDENT> self.assertIsInstance(entry, pywikibot.Page) <NEW_LINE> self.assertIn(entry._lintinfo['category'], ['obsolete-tag', 'missing-end-tag']) | Test linter_pages methods. | 62598fa857b8e32f525080ba |
class PDF_Renderer(threading.Thread, GObject.GObject): <NEW_LINE> <INDENT> def __init__(self, model, pdfqueue): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> GObject.GObject.__init__(self) <NEW_LINE> self.model = model <NEW_LINE> self.pdfqueue = pdfqueue <NEW_LINE> self.quit = False <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> for idx, row in enumerate(self.model): <NEW_LINE> <INDENT> if self.quit: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not row[1]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> nfile = row[2] <NEW_LINE> npage = row[3] <NEW_LINE> pdfdoc = self.pdfqueue[nfile - 1] <NEW_LINE> page = pdfdoc.document.get_page(npage-1) <NEW_LINE> w, h = page.get_size() <NEW_LINE> thumbnail = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(w/2.0), int(h/2.0)) <NEW_LINE> cr = cairo.Context(thumbnail) <NEW_LINE> cr.scale(1.0/2.0, 1.0/2.0) <NEW_LINE> page.render(cr) <NEW_LINE> time.sleep(0.003) <NEW_LINE> GObject.idle_add(self.emit,'update_thumbnail', idx, thumbnail, priority=GObject.PRIORITY_LOW) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) | Class for rendering thumbnails of pages. | 62598fa8adb09d7d5dc0a4ca |
class PerceptualLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, mode=1, weights=[1.0, 1.0, 1.0, 1.0, 1.0]): <NEW_LINE> <INDENT> super(PerceptualLoss, self).__init__() <NEW_LINE> self.add_module('vgg', VGG19()) <NEW_LINE> if mode == 1: <NEW_LINE> <INDENT> self.criterion = torch.nn.L1Loss() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.criterion = torch.nn.MSELoss() <NEW_LINE> <DEDENT> self.weights = weights <NEW_LINE> <DEDENT> def __call__(self, x, y): <NEW_LINE> <INDENT> x_vgg, y_vgg = self.vgg(x), self.vgg(y) <NEW_LINE> content_loss = 0.0 <NEW_LINE> content_loss += self.weights[0] * self.criterion(x_vgg['relu1_1'], y_vgg['relu1_1']) <NEW_LINE> content_loss += self.weights[1] * self.criterion(x_vgg['relu2_1'], y_vgg['relu2_1']) <NEW_LINE> content_loss += self.weights[2] * self.criterion(x_vgg['relu3_1'], y_vgg['relu3_1']) <NEW_LINE> content_loss += self.weights[3] * self.criterion(x_vgg['relu4_1'], y_vgg['relu4_1']) <NEW_LINE> content_loss += self.weights[4] * self.criterion(x_vgg['relu5_1'], y_vgg['relu5_1']) <NEW_LINE> return content_loss | Perceptual loss, VGG-based
https://arxiv.org/abs/1603.08155
https://github.com/dxyang/StyleTransfer/blob/master/utils.py | 62598fa856ac1b37e630212b |
class CareerDetail(LoginRequiredMixin, DetailView): <NEW_LINE> <INDENT> model = Career <NEW_LINE> context_object_name = 'career' <NEW_LINE> http_method_names = ['get'] <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(CareerDetail, self).get_context_data(**kwargs) <NEW_LINE> return context | Detail Career | 62598fa8f9cc0f698b1c5268 |
class Latch(object): <NEW_LINE> <INDENT> def __init__(self, count): <NEW_LINE> <INDENT> count = int(count) <NEW_LINE> if count <= 0: <NEW_LINE> <INDENT> raise ValueError("Count must be greater than zero") <NEW_LINE> <DEDENT> self._count = count <NEW_LINE> self._cond = threading.Condition() <NEW_LINE> <DEDENT> @property <NEW_LINE> def needed(self): <NEW_LINE> <INDENT> return max(0, self._count) <NEW_LINE> <DEDENT> def countdown(self): <NEW_LINE> <INDENT> with self._cond: <NEW_LINE> <INDENT> self._count -= 1 <NEW_LINE> if self._count <= 0: <NEW_LINE> <INDENT> self._cond.notify_all() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def wait(self, timeout=None): <NEW_LINE> <INDENT> watch = tt.StopWatch(duration=timeout) <NEW_LINE> watch.start() <NEW_LINE> with self._cond: <NEW_LINE> <INDENT> while self._count > 0: <NEW_LINE> <INDENT> if watch.expired(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._cond.wait(watch.leftover(return_none=True)) <NEW_LINE> <DEDENT> <DEDENT> return True | A class that ensures N-arrivals occur before unblocking.
TODO(harlowja): replace with http://bugs.python.org/issue8777 when we no
longer have to support python 2.6 or 2.7 and we can only support 3.2 or
later. | 62598fa844b2445a339b690f |
@method_decorator(check_validity_of_license, name='dispatch') <NEW_LINE> class CreateUserView(LoginRequiredMixin, SuccessMessageMixin, CreateView): <NEW_LINE> <INDENT> model = User <NEW_LINE> form_class = UserForm <NEW_LINE> template_name = 'user_form.html' <NEW_LINE> success_message = "%(username)s was created successfully" <NEW_LINE> success_url = reverse_lazy('list_users') <NEW_LINE> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> form = self.get_form() <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> user = form.save() <NEW_LINE> user.set_password(request.POST['password']) <NEW_LINE> user.save() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error(form.errors) <NEW_LINE> messages.error(request, form.errors) <NEW_LINE> return redirect('add_user') <NEW_LINE> <DEDENT> return HttpResponseRedirect(reverse('list_users')) | Create new user | 62598fa83d592f4c4edbae0d |
class TestOptions3(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testOptions3(self): <NEW_LINE> <INDENT> pass | Options3 unit test stubs | 62598fa8460517430c431ffc |
class CraneliftDomain(Domain): <NEW_LINE> <INDENT> name = 'clif' <NEW_LINE> label = 'Cranelift' <NEW_LINE> object_types = { 'type': ObjType(l_('type'), 'type'), 'inst': ObjType(l_('instruction'), 'inst') } <NEW_LINE> directives = { 'type': ClifType, 'inst': ClifInst, 'instgroup': ClifInstGroup, } <NEW_LINE> roles = { 'type': XRefRole(), 'inst': XRefRole(), 'instgroup': XRefRole(), } <NEW_LINE> initial_data = { 'objects': {}, } <NEW_LINE> def clear_doc(self, docname): <NEW_LINE> <INDENT> for fullname, (fn, _l) in list(self.data['objects'].items()): <NEW_LINE> <INDENT> if fn == docname: <NEW_LINE> <INDENT> del self.data['objects'][fullname] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def merge_domaindata(self, docnames, otherdata): <NEW_LINE> <INDENT> for fullname, (fn, objtype) in otherdata['objects'].items(): <NEW_LINE> <INDENT> if fn in docnames: <NEW_LINE> <INDENT> self.data['objects'][fullname] = (fn, objtype) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode): <NEW_LINE> <INDENT> objects = self.data['objects'] <NEW_LINE> if target not in objects: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> obj = objects[target] <NEW_LINE> return make_refnode(builder, fromdocname, obj[0], obj[1] + '-' + target, contnode, target) <NEW_LINE> <DEDENT> def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): <NEW_LINE> <INDENT> objects = self.data['objects'] <NEW_LINE> if target not in objects: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> obj = objects[target] <NEW_LINE> return [('clif:' + self.role_for_objtype(obj[1]), make_refnode(builder, fromdocname, obj[0], obj[1] + '-' + target, contnode, target))] | Cranelift domain for IR objects. | 62598fa8851cf427c66b8208 |
class SendMessageInputSet(InputSet): <NEW_LINE> <INDENT> def set_AWSAccessKeyId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AWSAccessKeyId', value) <NEW_LINE> <DEDENT> def set_AWSAccountId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AWSAccountId', value) <NEW_LINE> <DEDENT> def set_AWSSecretKeyId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AWSSecretKeyId', value) <NEW_LINE> <DEDENT> def set_MessageBody(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'MessageBody', value) <NEW_LINE> <DEDENT> def set_QueueName(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'QueueName', value) <NEW_LINE> <DEDENT> def set_UserRegion(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'UserRegion', value) | An InputSet with methods appropriate for specifying the inputs to the SendMessage
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 62598fa8d7e4931a7ef3bfdb |
class KojiScratchPkgSpec(object): <NEW_LINE> <INDENT> SEP = ':' <NEW_LINE> def __init__(self, text='', user=None, task=None, subpackages=[]): <NEW_LINE> <INDENT> self.user = None <NEW_LINE> self.task = None <NEW_LINE> self.subpackages = [] <NEW_LINE> if text: <NEW_LINE> <INDENT> self.parse(text) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.user = user <NEW_LINE> self.task = task <NEW_LINE> self.subpackages = subpackages <NEW_LINE> <DEDENT> <DEDENT> def parse(self, text): <NEW_LINE> <INDENT> parts = text.count(self.SEP) + 1 <NEW_LINE> if parts == 1: <NEW_LINE> <INDENT> raise ValueError('KojiScratchPkgSpec requires a user and task id') <NEW_LINE> <DEDENT> elif parts == 2: <NEW_LINE> <INDENT> self.user, self.task = text.split(self.SEP) <NEW_LINE> <DEDENT> elif parts >= 3: <NEW_LINE> <INDENT> part1, part2, part3 = text.split(self.SEP)[0:3] <NEW_LINE> self.user = part1 <NEW_LINE> self.task = part2 <NEW_LINE> self.subpackages = part3.split(',') <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ("<KojiScratchPkgSpec user=%s task=%s subpkgs=%s>" % (self.user, self.task, ", ".join(self.subpackages))) | A package specification syntax parser for Koji scratch builds
This holds information on user, task and subpackages to be fetched
from koji and possibly installed (features external do this class).
New objects can be created either by providing information in the textual
format or by using the actual parameters for user, task and subpackages.
The textual format is useful for command line interfaces and configuration
files, while using parameters is better for using this in a programatic
fashion.
This package definition has a special behaviour: if no subpackages are
specified, all packages of the chosen architecture (plus noarch packages)
will match.
The following sets of examples are interchangeable. Specifying all packages
from a scratch build (whose task id is 1000) sent by user jdoe:
>>> from kvm_utils import KojiScratchPkgSpec
>>> pkg = KojiScratchPkgSpec('jdoe:1000')
>>> pkg = KojiScratchPkgSpec(user=jdoe, task=1000)
Specifying some packages from a scratch build whose task id is 1000, sent
by user jdoe:
>>> pkg = KojiScratchPkgSpec('jdoe:1000:kernel,kernel-devel')
>>> pkg = KojiScratchPkgSpec(user=jdoe, task=1000,
subpackages=['kernel', 'kernel-devel']) | 62598fa83539df3088ecc1f4 |
class WorkoutPdfTableExportTestCase(WgerTestCase): <NEW_LINE> <INDENT> def export_pdf_token(self): <NEW_LINE> <INDENT> user = User.objects.get(username='test') <NEW_LINE> uid, token = make_token(user) <NEW_LINE> response = self.client.get( reverse('manager:workout:pdf-table', kwargs={ 'id': 3, 'uidb64': uid, 'token': token }) ) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(response['Content-Type'], 'application/pdf') <NEW_LINE> self.assertEqual( response['Content-Disposition'], 'attachment; filename=Workout-3-table.pdf', ) <NEW_LINE> self.assertGreater(int(response['Content-Length']), 38000) <NEW_LINE> self.assertLess(int(response['Content-Length']), 42000) <NEW_LINE> <DEDENT> def export_pdf_token_wrong(self): <NEW_LINE> <INDENT> uid = 'AB' <NEW_LINE> token = 'abc-11223344556677889900' <NEW_LINE> response = self.client.get( reverse('manager:workout:pdf-table', kwargs={ 'id': 3, 'uidb64': uid, 'token': token }) ) <NEW_LINE> self.assertEqual(response.status_code, 403) <NEW_LINE> <DEDENT> def export_pdf(self, fail=False): <NEW_LINE> <INDENT> response = self.client.get(reverse('manager:workout:pdf-table', kwargs={'id': 3})) <NEW_LINE> if fail: <NEW_LINE> <INDENT> self.assertIn(response.status_code, (403, 404, 302)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(response['Content-Type'], 'application/pdf') <NEW_LINE> self.assertEqual( response['Content-Disposition'], 'attachment; filename=Workout-3-table.pdf', ) <NEW_LINE> self.assertGreater(int(response['Content-Length']), 38000) <NEW_LINE> self.assertLess(int(response['Content-Length']), 42000) <NEW_LINE> <DEDENT> <DEDENT> def test_export_pdf_anonymous(self): <NEW_LINE> <INDENT> self.export_pdf(fail=True) <NEW_LINE> self.export_pdf_token() <NEW_LINE> self.export_pdf_token_wrong() <NEW_LINE> <DEDENT> def test_export_pdf_owner(self): <NEW_LINE> <INDENT> self.user_login('test') <NEW_LINE> self.export_pdf(fail=False) <NEW_LINE> self.export_pdf_token() <NEW_LINE> self.export_pdf_token_wrong() <NEW_LINE> <DEDENT> def test_export_pdf_other(self): <NEW_LINE> <INDENT> self.user_login('admin') <NEW_LINE> self.export_pdf(fail=True) <NEW_LINE> self.export_pdf_token() <NEW_LINE> self.export_pdf_token_wrong() | Tests exporting a workout as a pdf | 62598fa855399d3f05626464 |
class InlineAdminForm(AdminForm): <NEW_LINE> <INDENT> def __init__(self, formset, form, fieldsets, prepopulated_fields, original, readonly_fields=None, model_admin=None): <NEW_LINE> <INDENT> self.formset = formset <NEW_LINE> self.model_admin = model_admin <NEW_LINE> self.original = original <NEW_LINE> if original is not None: <NEW_LINE> <INDENT> self.original_content_type_id = ContentType.objects.get_for_model(original).pk <NEW_LINE> <DEDENT> self.show_url = original and hasattr(original, 'get_absolute_url') <NEW_LINE> super(InlineAdminForm, self).__init__(form, fieldsets, prepopulated_fields, readonly_fields, model_admin) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for name, options in self.fieldsets: <NEW_LINE> <INDENT> yield InlineFieldset(self.formset, self.form, name, self.readonly_fields, model_admin=self.model_admin, **options) <NEW_LINE> <DEDENT> <DEDENT> def needs_explicit_pk_field(self): <NEW_LINE> <INDENT> if self.form._meta.model._meta.has_auto_field or not self.form._meta.model._meta.pk.editable: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> for parent in self.form._meta.model._meta.get_parent_list(): <NEW_LINE> <INDENT> if parent._meta.has_auto_field: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def field_count(self): <NEW_LINE> <INDENT> num_of_fields = 0 <NEW_LINE> if self.has_auto_field(): <NEW_LINE> <INDENT> num_of_fields += 1 <NEW_LINE> <DEDENT> num_of_fields += len(self.fieldsets[0][1]["fields"]) <NEW_LINE> if self.formset.can_order: <NEW_LINE> <INDENT> num_of_fields += 1 <NEW_LINE> <DEDENT> if self.formset.can_delete: <NEW_LINE> <INDENT> num_of_fields += 1 <NEW_LINE> <DEDENT> return num_of_fields <NEW_LINE> <DEDENT> def pk_field(self): <NEW_LINE> <INDENT> return AdminField(self.form, self.formset._pk_field.name, False) <NEW_LINE> <DEDENT> def fk_field(self): <NEW_LINE> <INDENT> fk = getattr(self.formset, "fk", None) <NEW_LINE> if fk: <NEW_LINE> <INDENT> return AdminField(self.form, fk.name, False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> <DEDENT> def deletion_field(self): <NEW_LINE> <INDENT> from django.forms.formsets import DELETION_FIELD_NAME <NEW_LINE> return AdminField(self.form, DELETION_FIELD_NAME, False) <NEW_LINE> <DEDENT> def ordering_field(self): <NEW_LINE> <INDENT> from django.forms.formsets import ORDERING_FIELD_NAME <NEW_LINE> return AdminField(self.form, ORDERING_FIELD_NAME, False) | A wrapper around an inline form for use in the admin system. | 62598fa899cbb53fe6830e16 |
class TimestepObjectCache(object): <NEW_LINE> <INDENT> def __init__(self, timestep): <NEW_LINE> <INDENT> self.session = core.Session.object_session(timestep) <NEW_LINE> self._timestep_id = timestep.id <NEW_LINE> <DEDENT> def _initialise_cache(self): <NEW_LINE> <INDENT> all_objects = self.session.query(core.SimulationObjectBase).filter_by(timestep_id=self._timestep_id).all() <NEW_LINE> self._map_finder_offset = {} <NEW_LINE> self._map_finder_id = {} <NEW_LINE> for obj in all_objects: <NEW_LINE> <INDENT> typetag = obj.object_typetag_from_code(obj.object_typecode) <NEW_LINE> if typetag not in self._map_finder_offset: <NEW_LINE> <INDENT> self._map_finder_offset[typetag] = {} <NEW_LINE> <DEDENT> if typetag not in self._map_finder_id: <NEW_LINE> <INDENT> self._map_finder_id[typetag] = {} <NEW_LINE> <DEDENT> self._map_finder_offset[typetag][obj.finder_offset] = obj <NEW_LINE> self._map_finder_id[typetag][obj.finder_id] = obj <NEW_LINE> <DEDENT> <DEDENT> def _ensure_cache(self): <NEW_LINE> <INDENT> if not hasattr(self, "_map_finder_id") or not hasattr(self, "_map_finder_offset"): <NEW_LINE> <INDENT> self._initialise_cache() <NEW_LINE> <DEDENT> <DEDENT> def resolve_from_finder_offset(self, finder_offset, typetag): <NEW_LINE> <INDENT> self._ensure_cache() <NEW_LINE> try: <NEW_LINE> <INDENT> return self._map_finder_offset[typetag][finder_offset] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def resolve_from_finder_id(self, finder_id, typetag): <NEW_LINE> <INDENT> self._ensure_cache() <NEW_LINE> try: <NEW_LINE> <INDENT> return self._map_finder_id[typetag][finder_id] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None | A temporary store for all objects in a timestep, allowing objects to be resolved without a further database query | 62598fa82c8b7c6e89bd3705 |
class XMLReceiver(SerializeReceiver): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.format = 'xml' | Data format class for form submission in XML,
e.g. for software clients. | 62598fa8cc0a2c111447af50 |
class TestDeleteDocxTableRowRangeResponse(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testDeleteDocxTableRowRangeResponse(self): <NEW_LINE> <INDENT> pass | DeleteDocxTableRowRangeResponse unit test stubs | 62598fa8dd821e528d6d8e75 |
class AceJumpWithinLineCommand(AceJumpCommand): <NEW_LINE> <INDENT> def prompt(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def init_value(self): <NEW_LINE> <INDENT> return " " <NEW_LINE> <DEDENT> def regex(self): <NEW_LINE> <INDENT> return r'\b\w|\w\b|(?<=_)\w|\w(?=_)' <NEW_LINE> <DEDENT> def after_jump(self, view): <NEW_LINE> <INDENT> global mode <NEW_LINE> if mode == 3: <NEW_LINE> <INDENT> view.run_command("move", {"by": "word_ends", "forward": True}) <NEW_LINE> mode = 0 <NEW_LINE> <DEDENT> <DEDENT> def get_region_type(self): <NEW_LINE> <INDENT> return "current_line" | Specialized command for within-line-mode | 62598fa8be8e80087fbbefa3 |
class Stat(object): <NEW_LINE> <INDENT> def __init__(self, mean = [],variance =[],pi=[]): <NEW_LINE> <INDENT> self.mean = mean <NEW_LINE> self.variance=variance <NEW_LINE> self.pi=pi <NEW_LINE> <DEDENT> def SetInitialValues(self,cluster,data): <NEW_LINE> <INDENT> spltdData = list(self.split(np.sort(data),cluster)) <NEW_LINE> self.pi = [] <NEW_LINE> self.mean = [] <NEW_LINE> self.variance = [] <NEW_LINE> for x in range(cluster): <NEW_LINE> <INDENT> self.pi.append(1/cluster) <NEW_LINE> self.mean.append(np.mean(spltdData[x])) <NEW_LINE> self.variance.append(np.var(spltdData[x])) <NEW_LINE> <DEDENT> <DEDENT> def split(self, a, n): <NEW_LINE> <INDENT> k, m = divmod(len(a), n) <NEW_LINE> return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)) | Statistic Object for data transfer
| 62598fa81f5feb6acb162b61 |
class VCSView(BrowserView): <NEW_LINE> <INDENT> def getVCal(self): <NEW_LINE> <INDENT> context = self.context <NEW_LINE> out = BytesIO() <NEW_LINE> map = { 'dtstamp': rfc2445dt(DateTime()), 'created': rfc2445dt(DateTime(context.CreationDate())), 'uid': IUUID(context), 'modified': rfc2445dt(DateTime(context.ModificationDate())), 'summary': vformat(context.Title()), 'startdate': rfc2445dt(context.start_date), 'enddate': rfc2445dt(context.end_date), } <NEW_LINE> out.write(VCS_EVENT_START % map) <NEW_LINE> description = context.Description() <NEW_LINE> if description: <NEW_LINE> <INDENT> out.write(foldLine('DESCRIPTION:%s\n' % vformat(description))) <NEW_LINE> <DEDENT> location = context.location <NEW_LINE> if location: <NEW_LINE> <INDENT> location = location.encode('utf-8') <NEW_LINE> out.write('LOCATION:%s\n' % vformat(location)) <NEW_LINE> <DEDENT> out.write(VCS_EVENT_END) <NEW_LINE> return out.getvalue() <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> response = self.request.response <NEW_LINE> response.setHeader('Content-Type', 'text/x-vCalendar') <NEW_LINE> response.setHeader('Content-Disposition', 'attachment; filename="%s.vcs"' % self.context.getId()) <NEW_LINE> out = BytesIO() <NEW_LINE> out.write(VCS_HEADER % {'prodid': PROJECTNAME}) <NEW_LINE> out.write(self.getVCal()) <NEW_LINE> out.write(VCS_FOOTER) <NEW_LINE> return n2rn(out.getvalue()) | VCS view. | 62598fa832920d7e50bc5f95 |
class Base(Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> created = DateTimeField(editable=False) <NEW_LINE> updated = DateTimeField(editable=False) <NEW_LINE> is_active = BooleanField(default=True) <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.created = timezone.now() <NEW_LINE> self.updated = timezone.now() <NEW_LINE> super(Base, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> if hasattr(self, "name") and self.name: <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "%s" % (type(self)) | Base model for all of the models in the application. | 62598fa8cb5e8a47e493c118 |
class DynamicSplit(base.NextNodeMixin, base.UndoViewMixin, base.CancelViewMixin, base.PerformViewMixin, base.DetailsViewMixin, base.Gateway): <NEW_LINE> <INDENT> task_type = 'SPLIT' <NEW_LINE> activation_cls = DynamicSplitActivation <NEW_LINE> def __init__(self, callback): <NEW_LINE> <INDENT> super(DynamicSplit, self).__init__() <NEW_LINE> self._task_count_callback = callback | Activates several outgoing task instances depends on callback value
Example::
spit_on_decision = flow.DynamicSplit(lambda p: 4) \
.Next(this.make_decision)
make_decision = flow.View(MyView) \
.Next(this.join_on_decision)
join_on_decision = flow.Join() \
.Next(this.end) | 62598fa8d486a94d0ba2bf0e |
class TLEParserError(Exception): <NEW_LINE> <INDENT> def __init__(self, expr, msg): <NEW_LINE> <INDENT> self.expr = expr <NEW_LINE> self.msg = msg | Exception class to raise on an TLE parse error | 62598fa84428ac0f6e658463 |
class CA(Ordination): <NEW_LINE> <INDENT> short_method_name = 'CA' <NEW_LINE> long_method_name = 'Canonical Analysis' <NEW_LINE> def __init__(self, X, row_ids, column_ids): <NEW_LINE> <INDENT> self.X = np.asarray(X, dtype=np.float64) <NEW_LINE> self._ca() <NEW_LINE> self.row_ids = row_ids <NEW_LINE> self.column_ids = column_ids <NEW_LINE> <DEDENT> def _ca(self): <NEW_LINE> <INDENT> X = self.X <NEW_LINE> r, c = X.shape <NEW_LINE> if X.min() < 0: <NEW_LINE> <INDENT> raise ValueError("Input matrix elements must be non-negative.") <NEW_LINE> <DEDENT> grand_total = X.sum() <NEW_LINE> Q = X / grand_total <NEW_LINE> column_marginals = Q.sum(axis=0) <NEW_LINE> row_marginals = Q.sum(axis=1) <NEW_LINE> self.column_marginals = column_marginals <NEW_LINE> self.row_marginals = row_marginals <NEW_LINE> expected = np.outer(row_marginals, column_marginals) <NEW_LINE> Q_bar = (Q - expected) / np.sqrt(expected) <NEW_LINE> U_hat, W, Ut = np.linalg.svd(Q_bar, full_matrices=False) <NEW_LINE> rank = svd_rank(Q_bar.shape, W) <NEW_LINE> assert rank <= min(r, c) - 1 <NEW_LINE> self.U_hat = U_hat[:, :rank] <NEW_LINE> self.W = W[:rank] <NEW_LINE> self.U = Ut[:rank].T <NEW_LINE> <DEDENT> def scores(self, scaling): <NEW_LINE> <INDENT> if scaling not in {1, 2}: <NEW_LINE> <INDENT> raise NotImplementedError( "Scaling {0} not implemented.".format(scaling)) <NEW_LINE> <DEDENT> V = self.column_marginals[:, None]**-0.5 * self.U <NEW_LINE> V_hat = self.row_marginals[:, None]**-0.5 * self.U_hat <NEW_LINE> F = V_hat * self.W <NEW_LINE> F_hat = V * self.W <NEW_LINE> eigvals = self.W**2 <NEW_LINE> species_scores = [V, F_hat][scaling - 1] <NEW_LINE> site_scores = [F, V_hat][scaling - 1] <NEW_LINE> return OrdinationResults(eigvals=eigvals, species=species_scores, site=site_scores, site_ids=self.row_ids, species_ids=self.column_ids) | Compute correspondence analysis, a multivariate statistical
technique for ordination.
In general, rows in the data table will correspond to sites and
columns to species, but the method is symmetric. In order to
measure the correspondence between rows and columns, the
:math:`\chi^2` distance is used, and those distances are preserved
in the transformed space. The :math:`\chi^2` distance doesn't take
double zeros into account, and so it is expected to produce better
ordination that PCA when the data has lots of zero values.
It is related to Principal Component Analysis (PCA) but it should
be preferred in the case of steep or long gradients, that is, when
there are many zeros in the input data matrix.
Parameters
----------
X : array_like
Contingency table. It can be applied to different kinds of
data tables but data must be non-negative and dimensionally
homogeneous (quantitative or binary).
Notes
-----
The algorithm is based on [1]_, \S 9.4.1., and is expected to give
the same results as ``cca(X)`` in R's package vegan.
See Also
--------
CCA
References
----------
.. [1] Legendre P. and Legendre L. 1998. Numerical
Ecology. Elsevier, Amsterdam. | 62598fa8009cb60464d0145f |
class ListNode: <NEW_LINE> <INDENT> def __init__(self, x): <NEW_LINE> <INDENT> self.val = x <NEW_LINE> self.next = None | Comment out while running in LeetCode
Keep while running locally | 62598fa80c0af96317c562c3 |
class CCMapHintField(CCField): <NEW_LINE> <INDENT> TYPE = 7 <NEW_LINE> def __init__(self, hint): <NEW_LINE> <INDENT> if __debug__: <NEW_LINE> <INDENT> if len(hint) > 127 or len(hint) < 0: <NEW_LINE> <INDENT> raise AssertionError("Hint must be from 0 to 127 characters in length. Hint passed is '"+hint+"'") <NEW_LINE> <DEDENT> <DEDENT> self.type_val = CCMapHintField.TYPE <NEW_LINE> self.hint = hint <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return_str = " Map Hint Field (type=7)\n" <NEW_LINE> return_str += " hint = '"+str(self.hint)+"'" <NEW_LINE> return return_str <NEW_LINE> <DEDENT> @property <NEW_LINE> def json_data(self): <NEW_LINE> <INDENT> json_field = {} <NEW_LINE> json_field["type"] = self.type_val <NEW_LINE> json_field["hint"] = self.hint <NEW_LINE> return json_field <NEW_LINE> <DEDENT> @property <NEW_LINE> def byte_data(self): <NEW_LINE> <INDENT> hint_bytes = b"" <NEW_LINE> hint_bytes += self.hint.encode("ascii") <NEW_LINE> hint_bytes += b'\x00' <NEW_LINE> return hint_bytes | A class defining a hint
Member vars:
type_val (int): the type identifier of this class (set to 7)
hint (string): the hint for the level max length 127 characters | 62598fa86aa9bd52df0d4e09 |
class CmdNeige(Commande): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Commande.__init__(self, "neige", "snow") <NEW_LINE> self.aide_courte = "gère la construction dans la neige" <NEW_LINE> self.aide_longue = "Cette commande permet la construction de bonhommes " "de neige et de boule de neige. Voir plus en détail " "la commande %neige:fabriquer%." <NEW_LINE> <DEDENT> def ajouter_parametres(self): <NEW_LINE> <INDENT> self.ajouter_parametre(PrmBoule()) <NEW_LINE> self.ajouter_parametre(PrmCreer()) <NEW_LINE> self.ajouter_parametre(PrmDetruire()) <NEW_LINE> self.ajouter_parametre(PrmEdit()) <NEW_LINE> self.ajouter_parametre(PrmFabriquer()) <NEW_LINE> self.ajouter_parametre(PrmInstaller()) <NEW_LINE> self.ajouter_parametre(PrmPoursuivre()) <NEW_LINE> self.ajouter_parametre(PrmRetirer()) | Commande 'neige'.
| 62598fa8b7558d5895463570 |
class StatsTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> scales.reset() <NEW_LINE> <DEDENT> def testJsonCollapse(self): <NEW_LINE> <INDENT> r = Root() <NEW_LINE> r.getChild('here', False).countStat += 1 <NEW_LINE> r.getChild('not', True).countStat += 100 <NEW_LINE> out = StringIO() <NEW_LINE> formats.jsonFormat(out) <NEW_LINE> self.assertEquals('{"here": {"count": 1}}\n', out.getvalue()) | Test cases for stats classes. | 62598fa81b99ca400228f4d0 |
class CartListSerializer(serializers.ListSerializer): <NEW_LINE> <INDENT> def get_attribute(self, instance): <NEW_LINE> <INDENT> manager = super(CartListSerializer, self).get_attribute(instance) <NEW_LINE> assert isinstance(manager, models.Manager) and issubclass(manager.model, BaseCartItem) <NEW_LINE> return manager.filter_cart_items(instance, self.context['request']) | This serializes a list of cart items, whose quantity is non-zero. | 62598fa8fff4ab517ebcd725 |
class DBCancerType(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'color': 'str', 'id': 'str', 'name': 'str' } <NEW_LINE> self.attribute_map = { 'color': 'color', 'id': 'id', 'name': 'name' } <NEW_LINE> self._color = None <NEW_LINE> self._id = None <NEW_LINE> self._name = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def color(self): <NEW_LINE> <INDENT> return self._color <NEW_LINE> <DEDENT> @color.setter <NEW_LINE> def color(self, color): <NEW_LINE> <INDENT> self._color = color <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa88e71fb1e983bb9f3 |
class Subscription(object): <NEW_LINE> <INDENT> def __init__(self, recipient, token): <NEW_LINE> <INDENT> self.recipient = recipient <NEW_LINE> self.token = token <NEW_LINE> <DEDENT> @property <NEW_LINE> def recipient_id(self): <NEW_LINE> <INDENT> return self.recipient.id <NEW_LINE> <DEDENT> def confirm(self): <NEW_LINE> <INDENT> if self.recipient.token != self.token: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.recipient.confirmed = True <NEW_LINE> return True <NEW_LINE> <DEDENT> def unsubscribe(self): <NEW_LINE> <INDENT> if self.recipient.token != self.token: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> session = object_session(self.recipient) <NEW_LINE> session.delete(self.recipient) <NEW_LINE> session.flush() <NEW_LINE> return True | Adds subscription management to a recipient. | 62598fa8e5267d203ee6b84c |
class InvalidContext(InvalidOperation): <NEW_LINE> <INDENT> def handle(self, context, *args): <NEW_LINE> <INDENT> return _NaN | Invalid context. Unknown rounding, for example.
This occurs and signals invalid-operation if an invalid context was
detected during an operation. This can occur if contexts are not checked
on creation and either the precision exceeds the capability of the
underlying concrete representation or an unknown or unsupported rounding
was specified. These aspects of the context need only be checked when
the values are required to be used. The result is [0,qNaN]. | 62598fa8fff4ab517ebcd726 |
class KeyboardController: <NEW_LINE> <INDENT> def __init__(self, evManager): <NEW_LINE> <INDENT> self.evManager = evManager <NEW_LINE> self.evManager.RegisterListener(self) <NEW_LINE> <DEDENT> def Notify(self, event): <NEW_LINE> <INDENT> if isinstance(event, events.TickEvent): <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> ev = None <NEW_LINE> if event.type == QUIT: <NEW_LINE> <INDENT> ev = events.QuitEvent() <NEW_LINE> <DEDENT> elif event.type == KEYDOWN: <NEW_LINE> <INDENT> if event.key == K_ESCAPE: <NEW_LINE> <INDENT> ev = events.QuitEvent() <NEW_LINE> <DEDENT> elif event.key == K_UP: <NEW_LINE> <INDENT> direction = DIRECTION_UP <NEW_LINE> ev = events.CharactorMoveRequestEvent(direction) <NEW_LINE> <DEDENT> elif event.key == K_DOWN: <NEW_LINE> <INDENT> direction = DIRECTION_DOWN <NEW_LINE> ev = events.CharactorMoveRequestEvent(direction) <NEW_LINE> <DEDENT> elif event.key == K_LEFT: <NEW_LINE> <INDENT> direction = DIRECTION_LEFT <NEW_LINE> ev = events.CharactorMoveRequestEvent(direction) <NEW_LINE> <DEDENT> elif event.key == K_RIGHT: <NEW_LINE> <INDENT> direction = DIRECTION_RIGHT <NEW_LINE> ev = events.CharactorMoveRequestEvent(direction) <NEW_LINE> <DEDENT> <DEDENT> if ev: <NEW_LINE> <INDENT> self.evManager.Post(ev) | KeyboardController takes Pygame events generated by the
keyboard and uses them to control the model, by sending Requests
or to control the Pygame display directly, as with the QuitEvent | 62598fa860cbc95b0636428e |
class Users(models.Model): <NEW_LINE> <INDENT> uname = models.CharField(max_length=30, verbose_name='用户名') <NEW_LINE> uphone = models.CharField(max_length=11, verbose_name='电话号码') <NEW_LINE> upwd = models.CharField(max_length=20) <NEW_LINE> uemail = models.EmailField(verbose_name='邮箱') <NEW_LINE> isActive = models.BooleanField(default=True) <NEW_LINE> hasbuy = models.ManyToManyField(Goods, null=True, verbose_name='已买过') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.uname <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'users' <NEW_LINE> verbose_name = '用户信息' <NEW_LINE> verbose_name_plural = verbose_name | docstring for ClassName | 62598fa8d6c5a102081e2089 |
class School(object): <NEW_LINE> <INDENT> def __init__(self,school_name,school_addr): <NEW_LINE> <INDENT> self.school_name = school_name <NEW_LINE> self.school_addr = school_addr <NEW_LINE> self.school_course = {} <NEW_LINE> self.school_class = {} <NEW_LINE> self.school_teacher = {} <NEW_LINE> <DEDENT> def create_course(self,course_name,course_price,course_time): <NEW_LINE> <INDENT> course_obj = Course(course_name,course_price,course_time) <NEW_LINE> self.school_course[course_name] = course_obj <NEW_LINE> <DEDENT> def create_class(self,class_name,courese_obj): <NEW_LINE> <INDENT> class_obj=Class(class_name,courese_obj) <NEW_LINE> self.school_class[class_name]=class_obj <NEW_LINE> <DEDENT> def create_teacher(self,teacher_name, teacher_salary,class_name,class_obj): <NEW_LINE> <INDENT> teacher_obj = Teacher(teacher_name, teacher_salary) <NEW_LINE> teacher_obj.teacher_add_class(class_name,class_obj) <NEW_LINE> self.school_teacher[teacher_name] = teacher_obj <NEW_LINE> <DEDENT> def create_student(self, student_name, student_age, class_choice): <NEW_LINE> <INDENT> student_obj = Student(student_name, student_age) <NEW_LINE> class_obj = self.school_class[class_choice] <NEW_LINE> class_obj.class_student[student_name] = student_obj <NEW_LINE> self.school_class[class_choice] = class_obj | 学校类,包含名称,地址,课程,班级,教师 | 62598fa87cff6e4e811b596b |
class Count(Fold): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(Count, self).__init__( subspec=T, init=int, op=lambda cur, val: cur + 1) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s()' % self.__class__.__name__ | takes a count of how many values occurred
>>> glom([1, 2, 3], Count())
3 | 62598fa830dc7b766599f78f |
class TerritoryCode (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): <NEW_LINE> <INDENT> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'TerritoryCode') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('http://ddex.net/xml/20120719/iso3166a2.xsd', 10, 3) <NEW_LINE> _Documentation = 'An ISO 3166-1 two-letter code representing a ddex:Territory.' | An ISO 3166-1 two-letter code representing a ddex:Territory. | 62598fa8442bda511e95c397 |
@_assemble(_acq480, 4) <NEW_LINE> class acq2106_acq480x4(_acq2106): <NEW_LINE> <INDENT> pass | ACQ2106 carrier with four ACQ480 modules. | 62598fa8bd1bec0571e15064 |
class ProcessManager(MonitoredProcess): <NEW_LINE> <INDENT> def __init__(self, conf, uuid, namespace=None, service=None, pids_path=None, default_cmd_callback=None, cmd_addl_env=None, pid_file=None, run_as_root=False): <NEW_LINE> <INDENT> self.conf = conf <NEW_LINE> self.uuid = uuid <NEW_LINE> self.namespace = namespace <NEW_LINE> self.default_cmd_callback = default_cmd_callback <NEW_LINE> self.cmd_addl_env = cmd_addl_env <NEW_LINE> self.pids_path = pids_path or self.conf.external_pids <NEW_LINE> self.pid_file = pid_file <NEW_LINE> self.run_as_root = run_as_root <NEW_LINE> if service: <NEW_LINE> <INDENT> self.service_pid_fname = 'pid.' + service <NEW_LINE> self.service = service <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.service_pid_fname = 'pid' <NEW_LINE> self.service = 'default-service' <NEW_LINE> <DEDENT> common_utils.ensure_dir(os.path.dirname(self.get_pid_file_name())) <NEW_LINE> <DEDENT> def enable(self, cmd_callback=None, reload_cfg=False): <NEW_LINE> <INDENT> if not self.active: <NEW_LINE> <INDENT> if not cmd_callback: <NEW_LINE> <INDENT> cmd_callback = self.default_cmd_callback <NEW_LINE> <DEDENT> cmd = cmd_callback(self.get_pid_file_name()) <NEW_LINE> ip_wrapper = ip_lib.IPWrapper(namespace=self.namespace) <NEW_LINE> ip_wrapper.netns.execute(cmd, addl_env=self.cmd_addl_env, run_as_root=self.run_as_root) <NEW_LINE> <DEDENT> elif reload_cfg: <NEW_LINE> <INDENT> self.reload_cfg() <NEW_LINE> <DEDENT> <DEDENT> def reload_cfg(self): <NEW_LINE> <INDENT> self.disable('HUP') <NEW_LINE> <DEDENT> def disable(self, sig='9', get_stop_command=None): <NEW_LINE> <INDENT> pid = self.pid <NEW_LINE> if self.active: <NEW_LINE> <INDENT> if get_stop_command: <NEW_LINE> <INDENT> cmd = get_stop_command(self.get_pid_file_name()) <NEW_LINE> ip_wrapper = ip_lib.IPWrapper(namespace=self.namespace) <NEW_LINE> ip_wrapper.netns.execute(cmd, addl_env=self.cmd_addl_env) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = ['kill', '-%s' % (sig), pid] <NEW_LINE> utils.execute(cmd, run_as_root=True) <NEW_LINE> if sig == '9': <NEW_LINE> <INDENT> fileutils.delete_if_exists(self.get_pid_file_name()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif pid: <NEW_LINE> <INDENT> LOG.debug('Process for %(uuid)s pid %(pid)d is stale, ignoring ' 'signal %(signal)s', {'uuid': self.uuid, 'pid': pid, 'signal': sig}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOG.debug('No process started for %s', self.uuid) <NEW_LINE> <DEDENT> <DEDENT> def get_pid_file_name(self): <NEW_LINE> <INDENT> if self.pid_file: <NEW_LINE> <INDENT> return self.pid_file <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return utils.get_conf_file_name(self.pids_path, self.uuid, self.service_pid_fname) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def pid(self): <NEW_LINE> <INDENT> return utils.get_value_from_file(self.get_pid_file_name(), int) <NEW_LINE> <DEDENT> @property <NEW_LINE> def active(self): <NEW_LINE> <INDENT> pid = self.pid <NEW_LINE> if pid is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> cmdline = '/proc/%s/cmdline' % pid <NEW_LINE> try: <NEW_LINE> <INDENT> with open(cmdline, "r") as f: <NEW_LINE> <INDENT> return self.uuid in f.readline() <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> return False | An external process manager for Neutron spawned processes.
Note: The manager expects uuid to be in cmdline. | 62598fa88a43f66fc4bf20be |
class Profile(object): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> host = config.get('PROFILE_ELASTICSEARCH_HOST') <NEW_LINE> user = config.get('PROFILE_ELASTICSEARCH_USER') <NEW_LINE> password = config.get('PROFILE_ELASTICSEARCH_PASS') <NEW_LINE> self.es = database.initEs(host, user, password) <NEW_LINE> logger.debug('Connecting on %s for %s' % (host, index)) <NEW_LINE> <DEDENT> def find_all(self): <NEW_LINE> <INDENT> query = '{"query": {"match_all": {}}}' <NEW_LINE> return self.es.search(index=index, doc_type=doc_type, body=query, size=10000) <NEW_LINE> <DEDENT> def find_ativos(self): <NEW_LINE> <INDENT> query = '{"query": {"match": {"status": "A"}}}' <NEW_LINE> return self.es.search(index=index, doc_type=doc_type, body=query, size=10000) <NEW_LINE> <DEDENT> def save(self, doc, refresh=False): <NEW_LINE> <INDENT> logger.debug(doc) <NEW_LINE> res = self.es.index( index=index, doc_type=doc_type, body=doc, id=doc['login'], refresh=refresh) <NEW_LINE> logger.debug("Created documento ID %s" % res['_id']) <NEW_LINE> return res <NEW_LINE> <DEDENT> def update(self, id, doc, refresh=False): <NEW_LINE> <INDENT> res = self.es.update( index=index, doc_type=doc_type, body=doc, id=id, refresh=refresh) <NEW_LINE> logger.debug("Document %s updated" % res['_id']) <NEW_LINE> <DEDENT> def delete(self, id): <NEW_LINE> <INDENT> self.es.delete(index=index, doc_type=doc_type, id=id) | Profile operations. | 62598fa8e5267d203ee6b84d |
class ICC_026: <NEW_LINE> <INDENT> pass | Grim Necromancer | 62598fa863b5f9789fe850a7 |
class BaseStore(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.data_path = settings.DATA_PATH <NEW_LINE> <DEDENT> def save(self, obj, id_code): <NEW_LINE> <INDENT> filestream = open('{0}/{1}'.format(self.data_path, id_code), 'w+') <NEW_LINE> pickle.dump(obj, filestream) <NEW_LINE> filestream.close() <NEW_LINE> <DEDENT> def load(self, id_code): <NEW_LINE> <INDENT> filestream = open('{0}/{1}'.format(self.data_path, id_code), 'rb') <NEW_LINE> workflow = pickle.load(filestream) <NEW_LINE> return workflow | Basic datastore | 62598fa892d797404e388b06 |
class BlueMarbleExamples(GaLabExamples): <NEW_LINE> <INDENT> def startup(self): <NEW_LINE> <INDENT> self.file = self.DataDir + '/model.ctl' <NEW_LINE> <DEDENT> def ex_proj_stereo(self): <NEW_LINE> <INDENT> ga.basemap('nps', opts=(-90.,40.)) <NEW_LINE> ga.blue_marble(Show=True) <NEW_LINE> title("Northern Stereographic Projection") <NEW_LINE> <DEDENT> def ex_proj_polar_orthographic(self): <NEW_LINE> <INDENT> ga.basemap('npo', opts=(-90.,90.)) <NEW_LINE> ga.blue_marble(Show=True) <NEW_LINE> title("Orthographic Projection (North Pole)") | Examples based on the Blue Marble image. | 62598fa8be8e80087fbbefa5 |
class PubsubProjectsTopicsSubscriptionsListRequest(_messages.Message): <NEW_LINE> <INDENT> pageSize = _messages.IntegerField(1, variant=_messages.Variant.INT32) <NEW_LINE> pageToken = _messages.StringField(2) <NEW_LINE> topic = _messages.StringField(3, required=True) | A PubsubProjectsTopicsSubscriptionsListRequest object.
Fields:
pageSize: Maximum number of subscription names to return.
pageToken: The value returned by the last ListTopicSubscriptionsResponse;
indicates that this is a continuation of a prior ListTopicSubscriptions
call, and that the system should return the next page of data.
topic: The name of the topic that subscriptions are attached to. | 62598fa8a8ecb03325871152 |
class BlogHome(TemplateView): <NEW_LINE> <INDENT> template_name = 'blogs/index.html' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> entries = BlogEntry.objects.order_by('-pub_date')[:6] <NEW_LINE> latest_entry = None <NEW_LINE> other_entries = [] <NEW_LINE> if entries: <NEW_LINE> <INDENT> latest_entry = entries[0] <NEW_LINE> other_entries = entries[1:] <NEW_LINE> <DEDENT> context.update({ 'latest_entry': latest_entry, 'entries': other_entries, }) <NEW_LINE> return context | Main blog view | 62598fa830bbd72246469919 |
class Head(Protein): <NEW_LINE> <INDENT> def __init__(self, parent, side): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> self.side = side <NEW_LINE> self.bs = binding_site.BindingSite(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def other_head(self): <NEW_LINE> <INDENT> return self.parent.heads[self.side ^ 1] | Generic head located on a parent protein | 62598fa85fcc89381b2660ee |
class NinjaAnt(Ant): <NEW_LINE> <INDENT> name = 'Ninja' <NEW_LINE> damage = 1 <NEW_LINE> implemented = True <NEW_LINE> food_cost = 5 <NEW_LINE> blocks_path =False <NEW_LINE> def action(self, colony): <NEW_LINE> <INDENT> for bee in list(self.place.bees): <NEW_LINE> <INDENT> bee.reduce_armor(self.damage) | NinjaAnt does not block the path and damages all bees in its place. | 62598fa80c0af96317c562c5 |
class LoggingModem(models.Model): <NEW_LINE> <INDENT> probe = models.ForeignKey(Probe, verbose_name=_(u'Modem APN')) <NEW_LINE> modem = models.ForeignKey(Modem, verbose_name=_(u'Modem APN')) <NEW_LINE> created = models.DateTimeField(default=django.utils.timezone.now, verbose_name=_(u'Date created')) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('Logging Modem') <NEW_LINE> verbose_name_plural = _('Logging Modems') | Logging at which time the modem was attached to a particular Probe | 62598fa8dd821e528d6d8e78 |
class Accuracy(Metric): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swig_metric = singa.Accuracy() | Compute the top one accuracy for singel label prediction tasks.
It calls the C++ functions to do the calculation. | 62598fa88e71fb1e983bb9f5 |
class AuthMiddleware: <NEW_LINE> <INDENT> def __init__(self, inner): <NEW_LINE> <INDENT> self.inner = inner <NEW_LINE> <DEDENT> def __call__(self, scope): <NEW_LINE> <INDENT> close_old_connections() <NEW_LINE> query_string = scope['query_string'].decode('utf-8') <NEW_LINE> if not query_string: <NEW_LINE> <INDENT> return self.inner(scope) <NEW_LINE> <DEDENT> query_dict = None <NEW_LINE> if query_string: <NEW_LINE> <INDENT> query_dict = parse.parse_qs(query_string) <NEW_LINE> <DEDENT> if not query_dict: <NEW_LINE> <INDENT> return self.inner(scope) <NEW_LINE> <DEDENT> token = query_dict.get('token')[0] <NEW_LINE> try: <NEW_LINE> <INDENT> data = jwt_decode_handler(token) <NEW_LINE> <DEDENT> except jwt.ExpiredSignatureError: <NEW_LINE> <INDENT> logger.error(f"Expired token: {token}") <NEW_LINE> return self.inner(dict(scope)) <NEW_LINE> <DEDENT> except jwt.InvalidSignatureError: <NEW_LINE> <INDENT> logger.error(f'Invalid token: {token}') <NEW_LINE> return self.inner(dict(scope)) <NEW_LINE> <DEDENT> except jwt.DecodeError: <NEW_LINE> <INDENT> logger.error(f"JWT decode error: {token}") <NEW_LINE> return self.inner(dict(scope)) <NEW_LINE> <DEDENT> scope['user_id'] = data['user_id'] <NEW_LINE> scope['username'] = data['username'] <NEW_LINE> scope['role'] = data['role'] <NEW_LINE> return self.inner(dict(scope)) | Middleware which populates scope["user"] from a Django session.
Requires SessionMiddleware to function. | 62598fa87c178a314d78d3e0 |
class TestStringEnum(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testStringEnum(self): <NEW_LINE> <INDENT> """Test OuterEnum""" <NEW_LINE> assert StringEnum.allowed_values[('value',)] == { 'PLACED': "placed", 'APPROVED': "approved", 'DELIVERED': "delivered" } <NEW_LINE> with self.assertRaises(petstore_api.ApiValueError): <NEW_LINE> <INDENT> StringEnum('bad_value') <NEW_LINE> <DEDENT> valid_value = StringEnum.allowed_values[('value',)]['PLACED'] <NEW_LINE> assert valid_value == StringEnum(valid_value).value | StringEnum unit test stubs | 62598fa832920d7e50bc5f98 |
class CharacterTrigramEmbedding(Embedding): <NEW_LINE> <INDENT> def __init__(self, language='en', maxlen=1024): <NEW_LINE> <INDENT> vectors_path = download_path('fasttext', language) <NEW_LINE> final_path = vectors_path.with_suffix('.numpy') <NEW_LINE> url = FAST_TEXT_URL_TEMPLATE.format(language) <NEW_LINE> self.maxlen = maxlen <NEW_LINE> self.sequencer = sequencer = Sequencers.CharacterTrigramSequencer( maxlen=maxlen) <NEW_LINE> download_if_needed(url, vectors_path) <NEW_LINE> if not final_path.exists(): <NEW_LINE> <INDENT> with open(vectors_path, mode='r', encoding='utf8') as f: <NEW_LINE> <INDENT> first_line = f.readline() <NEW_LINE> words, dimensions = map(int, first_line.split()) <NEW_LINE> embeddings = np.memmap(final_path.with_suffix( '.tmp'), dtype='float32', mode='w+', shape=(sequencer.features, dimensions)) <NEW_LINE> <DEDENT> for line in tqdm(iterable=open(str(vectors_path), mode='r', encoding='utf8'), total=words, desc='Parsing', unit='vector'): <NEW_LINE> <INDENT> segments = line.split() <NEW_LINE> if len(segments) > dimensions and len(segments[0]) == 3: <NEW_LINE> <INDENT> word = sequencer.transform([segments[0]])[0][0] <NEW_LINE> try: <NEW_LINE> <INDENT> numbers = np.array(list(map(np.float32, segments[1:]))) <NEW_LINE> embeddings[word] = numbers <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> embeddings[0] = np.zeros(dimensions) <NEW_LINE> embeddings.flush() <NEW_LINE> del embeddings <NEW_LINE> final_path.with_suffix('.tmp').rename(final_path) <NEW_LINE> <DEDENT> with open(vectors_path, mode='r', encoding='utf8') as f: <NEW_LINE> <INDENT> first_line = f.readline() <NEW_LINE> words, dimensions = map(int, first_line.split()) <NEW_LINE> self.embeddings = np.memmap( final_path, dtype='float32', mode='r', shape=(sequencer.features, dimensions)) | Language model base that will download and compile pretrained FastText vectors
for a given language.
Attributes
----------
embeddings
A two dimensional numpy array [term id, vector dimension] storing floating points.
This is a memory mapped array to save some I/O.
>>> from vectoria import Embeddings
>>> chargram = Embeddings.CharacterTrigramEmbedding(language='en', maxlen=6)
>>> chargram.embed('hello')
array([[[ -4.47659999e-01, -3.63579988e-01, -3.11529994e-01, ...,
-5.76590002e-01, 2.53699988e-01, -3.65200005e-02],
[ -4.00400013e-01, 3.42779997e-04, -1.96740001e-01, ...,
-2.23260000e-01, -2.42109999e-01, 1.57110006e-01],
[ -1.79299995e-01, -1.67520002e-01, -3.27329993e-01, ...,
6.78020000e-01, 4.57850009e-01, -9.05459970e-02],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00]]], dtype=float32) | 62598fa899fddb7c1ca62d8a |
class KLpq(VariationalInference): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> VariationalInference.__init__(self, *args, **kwargs) <NEW_LINE> <DEDENT> def initialize(self, n_minibatch=1, *args, **kwargs): <NEW_LINE> <INDENT> self.n_minibatch = n_minibatch <NEW_LINE> self.samples = tf.placeholder(shape=(self.n_minibatch, self.variational.num_vars), dtype=tf.float32, name='samples') <NEW_LINE> return VariationalInference.initialize(self, *args, **kwargs) <NEW_LINE> <DEDENT> def update(self, sess): <NEW_LINE> <INDENT> samples = self.variational.sample(self.samples.get_shape(), sess) <NEW_LINE> _, loss = sess.run([self.train, self.losses], {self.samples: samples}) <NEW_LINE> return loss <NEW_LINE> <DEDENT> def build_loss(self): <NEW_LINE> <INDENT> x = self.data.sample(self.n_data) <NEW_LINE> self.variational.set_params(self.variational.mapping(x)) <NEW_LINE> q_log_prob = tf.zeros([self.n_minibatch], dtype=tf.float32) <NEW_LINE> for i in range(self.variational.num_vars): <NEW_LINE> <INDENT> q_log_prob += self.variational.log_prob_zi(i, self.samples) <NEW_LINE> <DEDENT> log_w = self.model.log_prob(x, self.samples) - q_log_prob <NEW_LINE> log_w_norm = log_w - log_sum_exp(log_w) <NEW_LINE> w_norm = tf.exp(log_w_norm) <NEW_LINE> self.losses = w_norm * log_w <NEW_LINE> return -tf.reduce_mean(q_log_prob * tf.stop_gradient(w_norm)) | Kullback-Leibler divergence from posterior to variational model,
KL( p(z |x) || q(z) ).
(Cappe et al., 2008) | 62598fa83617ad0b5ee06097 |
class AssemblyInput(tls.Unicode, TypeMeta): <NEW_LINE> <INDENT> info_text = "KBaseAssembly.AssemblyInput" <NEW_LINE> class v1_0(tls.Unicode, TypeMeta): <NEW_LINE> <INDENT> info_text = "KBaseAssembly.AssemblyInput-1.0" | AssemblyInput type | 62598fa84e4d562566372368 |
class FitbitOAuth1(BaseOAuth1): <NEW_LINE> <INDENT> name = 'fitbit' <NEW_LINE> AUTHORIZATION_URL = 'https://www.fitbit.com/oauth/authorize' <NEW_LINE> REQUEST_TOKEN_URL = 'https://api.fitbit.com/oauth/request_token' <NEW_LINE> ACCESS_TOKEN_URL = 'https://api.fitbit.com/oauth/access_token' <NEW_LINE> ID_KEY = 'encodedId' <NEW_LINE> EXTRA_DATA = [('encodedId', 'id'), ('displayName', 'username')] <NEW_LINE> def get_user_details(self, response): <NEW_LINE> <INDENT> return {'username': response.get('displayName'), 'email': ''} <NEW_LINE> <DEDENT> def user_data(self, access_token, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_json( 'https://api.fitbit.com/1/user/-/profile.json', auth=self.oauth_auth(access_token) )['user'] | Fitbit OAuth1 authentication backend | 62598fa8379a373c97d98f55 |
class VIEW_3D_PT_mypanel(bpy.types.Panel): <NEW_LINE> <INDENT> bl_label = 'My Panel' <NEW_LINE> bl_space_type = 'VIEW_3D' <NEW_LINE> bl_region_type = 'UI' <NEW_LINE> bl_category = 'My Addon' <NEW_LINE> def draw(self, context): <NEW_LINE> <INDENT> layout = self.layout <NEW_LINE> col = layout.column(align = True) <NEW_LINE> col.operator('script.myoperator', text='Say Hello!') <NEW_LINE> col.prop(context.scene, 'my_prop_slider', slider=True) <NEW_LINE> col.prop(context.scene, 'my_prop_value') <NEW_LINE> col.prop(context.scene, 'my_prop_toggle') <NEW_LINE> col.prop(context.scene, 'my_prop_enum') | Tooltip | 62598fa8e76e3b2f99fd8979 |
class RandomWalk(Initializer): <NEW_LINE> <INDENT> __default_values__ = {'scale': None} <NEW_LINE> def __init__(self, act_func='linear', scale=None): <NEW_LINE> <INDENT> super(RandomWalk, self).__init__() <NEW_LINE> self.act_func = act_func <NEW_LINE> self.scale = scale <NEW_LINE> <DEDENT> def __call__(self, shape): <NEW_LINE> <INDENT> if len(shape) != 2: <NEW_LINE> <INDENT> raise InitializationError("Works only with 2D matrices but shape " "was: {}".format(shape)) <NEW_LINE> <DEDENT> if shape[0] != shape[1]: <NEW_LINE> <INDENT> raise InitializationError("Matrix needs to be square, but was {}" "".format(shape)) <NEW_LINE> <DEDENT> N = shape[1] <NEW_LINE> if self.scale is None: <NEW_LINE> <INDENT> scale = { 'linear': np.exp(1 / (2 * N)), 'rel': np.sqrt(2) * np.exp(1.2 / (max(N, 6) - 2.4)) }[self.act_func] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> scale = self.scale <NEW_LINE> <DEDENT> return scale * self.rnd.randn(*shape) / N | Initializes a (square) weight matrix with the random walk scheme proposed
by:
Sussillo, David, and L. F. Abbott.
"Random Walk Initialization for Training Very Deep Feedforward Networks."
arXiv:1412.6558 [cs, Stat], December 19, 2014.
http://arxiv.org/abs/1412.6558. | 62598fa8f9cc0f698b1c526a |
class TGetTablesResp: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRUCT, 'status', (TStatus, TStatus.thrift_spec), None, ), (2, TType.STRUCT, 'operationHandle', (TOperationHandle, TOperationHandle.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, status=None, operationHandle=None,): <NEW_LINE> <INDENT> self.status = status <NEW_LINE> self.operationHandle = operationHandle <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.status = TStatus() <NEW_LINE> self.status.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.operationHandle = TOperationHandle() <NEW_LINE> self.operationHandle.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('TGetTablesResp') <NEW_LINE> if self.status is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('status', TType.STRUCT, 1) <NEW_LINE> self.status.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.operationHandle is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('operationHandle', TType.STRUCT, 2) <NEW_LINE> self.operationHandle.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if self.status is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field status is unset!') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- status
- operationHandle | 62598fa838b623060ffa8fdb |
class Processor(AwardProcessor): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> AwardProcessor.__init__(self, 'Defender', 'Most Flag Defends', [PLAYER_COL, Column('Defends', Column.NUMBER, Column.DESC)]) <NEW_LINE> <DEDENT> def on_flag_action(self, e): <NEW_LINE> <INDENT> if e.action_type == FlagActionEvent.DEFEND: <NEW_LINE> <INDENT> self.results[e.player] += 1 | Overview
This processor is awarded to the player with the most flag defends.
Implementation
Count the flag action events of the appropriate type.
Notes
None. | 62598fa8f7d966606f747f28 |
class Square: <NEW_LINE> <INDENT> def __init__(self, size=0): <NEW_LINE> <INDENT> if not isinstance(size, int): <NEW_LINE> <INDENT> raise TypeError("size must be an integer") <NEW_LINE> <DEDENT> if size < 0: <NEW_LINE> <INDENT> raise ValueError("size must be >= 0") <NEW_LINE> <DEDENT> self.__size = size | The Square class | 62598fa80c0af96317c562c6 |
class InvincibleEnemy(SimpleEnemy): <NEW_LINE> <INDENT> name = "Invincible Enemy" <NEW_LINE> colour = 'green' <NEW_LINE> points = 10 <NEW_LINE> def __init__(self, grid_size=(.3, .3), grid_speed=5/50, health=400): <NEW_LINE> <INDENT> super().__init__(grid_size, grid_speed, health) <NEW_LINE> <DEDENT> def damage(self, damage, type_): <NEW_LINE> <INDENT> self.health -= damage <NEW_LINE> if self.health < 0: <NEW_LINE> <INDENT> self.health = 0 <NEW_LINE> <DEDENT> <DEDENT> def step(self, data): <NEW_LINE> <INDENT> grid = data.grid <NEW_LINE> path = data.path <NEW_LINE> movement = self.grid_speed <NEW_LINE> while movement > 0: <NEW_LINE> <INDENT> cell_offset = grid.pixel_to_cell_offset(self.position) <NEW_LINE> offset_length = abs(cell_offset[0] + cell_offset[1]) <NEW_LINE> if offset_length == 0: <NEW_LINE> <INDENT> partial_movement = movement <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> partial_movement = min(offset_length, movement) <NEW_LINE> <DEDENT> cell_position = grid.pixel_to_cell(self.position) <NEW_LINE> delta = path.get_best_delta(cell_position) <NEW_LINE> dx, dy = get_delta_through_centre(cell_offset, delta) <NEW_LINE> speed = partial_movement * self.cell_size <NEW_LINE> self.move_by((speed * dx, speed * dy)) <NEW_LINE> self.position = tuple(int(i) for i in self.position) <NEW_LINE> movement -= partial_movement <NEW_LINE> <DEDENT> intersects = rectangles_intersect(*self.get_bounding_box(), (0, 0), grid.pixels) <NEW_LINE> return intersects or grid.pixel_to_cell(self.position) in path.deltas | An enemy that can only by killed by EnergyTower. | 62598fa821bff66bcd722baa |
class ZhiPinSpider(BaseSpider, metaclass=SpiderMeta): <NEW_LINE> <INDENT> request_sleep = 15 <NEW_LINE> def crawl(self): <NEW_LINE> <INDENT> city_code = self._parse_city() <NEW_LINE> if not city_code: <NEW_LINE> <INDENT> self.logger.error('%s 不支持目标城市' % __class__.__name__) <NEW_LINE> return <NEW_LINE> <DEDENT> search_url = 'https://www.zhipin.com/c' + city_code <NEW_LINE> page = 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> params = {'query': self.job, 'page': page, 'ka': 'page-%s' % page} <NEW_LINE> resp = self.request('get', search_url, params=params) <NEW_LINE> html = etree.HTML(resp.text) <NEW_LINE> detail_urls = html.xpath('//div[@class="info-primary"]/h3/a/@href') <NEW_LINE> if not detail_urls: <NEW_LINE> <INDENT> if page == 1: <NEW_LINE> <INDENT> self.logger.error('%s 可能已被BAN' % __class__.__name__) <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> for each in detail_urls: <NEW_LINE> <INDENT> yield self._parse_detail('https://www.zhipin.com' + each) <NEW_LINE> <DEDENT> page += 1 <NEW_LINE> <DEDENT> <DEDENT> def _parse_city(self): <NEW_LINE> <INDENT> index_url = 'https://www.zhipin.com/common/data/city.json' <NEW_LINE> resp = self.request('get', index_url) <NEW_LINE> city_code = re.findall(r'"code":(\d+),"name":"%s"' % self.city, resp.text) <NEW_LINE> if city_code: <NEW_LINE> <INDENT> return city_code[0] <NEW_LINE> <DEDENT> <DEDENT> def _parse_detail(self, detail_url): <NEW_LINE> <INDENT> resp = self.request('get', detail_url) <NEW_LINE> html = etree.HTML(resp.text) <NEW_LINE> title = html.xpath('//div[@class="info-primary"]/div[@class="name"]/h1/text()') <NEW_LINE> if not title: <NEW_LINE> <INDENT> if re.search(r'您暂时无法继续访问~', resp.text): <NEW_LINE> <INDENT> self.logger.error('%s 可能已被BAN' % __class__.__name__) <NEW_LINE> return <NEW_LINE> <DEDENT> self.logger.warning('%s 解析出错' % detail_url) <NEW_LINE> return self._parse_detail(detail_url) <NEW_LINE> <DEDENT> result = { 'title': title[0], 'company': html.xpath('//div[@class="info-company"]/h3/a/text()')[0], 'salary': html.xpath('//div[@class="info-primary"]/div[@class="name"]/span/text()')[0], 'experience': html.xpath('//div[@class="info-primary"]/p/text()')[1].replace('经验:', ''), 'education': html.xpath('//div[@class="info-primary"]/p/text()')[2].replace('学历:', ''), 'url': detail_url, 'description': html.xpath('string(//div[@class="job-sec"][1]/div)') } <NEW_LINE> return result | BOSS直聘 | 62598fa8be383301e025373d |
class ArnoldWinther(CiarletElement): <NEW_LINE> <INDENT> def __init__(self, cell, degree): <NEW_LINE> <INDENT> assert degree == 3, "Only defined for degree 3" <NEW_LINE> Ps = ONSymTensorPolynomialSet(cell, degree) <NEW_LINE> Ls = ArnoldWintherDual(cell, degree) <NEW_LINE> mapping = "double contravariant piola" <NEW_LINE> super(ArnoldWinther, self).__init__(Ps, Ls, degree, mapping=mapping) | The definition of the conforming Arnold-Winther element.
| 62598fa885dfad0860cbfa16 |
class CPOutlineArtist(matplotlib.collections.LineCollection): <NEW_LINE> <INDENT> def set_paths(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, name, labels, *args, **kwargs): <NEW_LINE> <INDENT> lines = [] <NEW_LINE> for l in labels: <NEW_LINE> <INDENT> new_labels, counts = scipy.ndimage.label(l != 0, numpy.ones((3, 3), bool)) <NEW_LINE> if counts == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> l = l.astype(numpy.uint64) * counts + new_labels <NEW_LINE> unique, idx = numpy.unique(l.flatten(), return_inverse=True) <NEW_LINE> if unique[0] == 0: <NEW_LINE> <INDENT> my_range = numpy.arange(len(unique)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> my_range = numpy.arange(1, len(unique)) <NEW_LINE> <DEDENT> idx.shape = l.shape <NEW_LINE> pts, offs, counts = centrosome.cpmorphology.get_outline_pts(idx, my_range) <NEW_LINE> pts = pts + 0.5 <NEW_LINE> pts = pts[:, ::-1] <NEW_LINE> for off, count in zip(offs, counts): <NEW_LINE> <INDENT> lines.append(numpy.vstack((pts[off : off + count], pts[off : off + 1]))) <NEW_LINE> <DEDENT> <DEDENT> matplotlib.collections.LineCollection.__init__(self, lines, *args, **kwargs) <NEW_LINE> <DEDENT> def get_outline_name(self): <NEW_LINE> <INDENT> return self.__outline_name | An artist that is a plot of the outline around an object
This class is here so that we can add and remove artists for certain
outlines. | 62598fa863b5f9789fe850a9 |
class SupportedFieldChoices(BaseResource): <NEW_LINE> <INDENT> def __init__(self, dataFinder: DataFinder): <NEW_LINE> <INDENT> super().__init__(dataFinder) <NEW_LINE> <DEDENT> def get(self) -> List[str]: <NEW_LINE> <INDENT> return DataFinder.SUPPORTED_FIELD_CHOICES | List of supported field choices. | 62598fa82c8b7c6e89bd370a |
class ThreadedServer(object): <NEW_LINE> <INDENT> def __init__(self, host, port): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> self.sock.bind((self.host, self.port)) <NEW_LINE> <DEDENT> def listen(self): <NEW_LINE> <INDENT> self.sock.listen(5) <NEW_LINE> while True: <NEW_LINE> <INDENT> client, address = self.sock.accept() <NEW_LINE> print("Client connected from {0}:{1}".format(address[0],address[1])) <NEW_LINE> client.settimeout(60) <NEW_LINE> threading.Thread(target = self.listenToClient,args = (client,address)).start() <NEW_LINE> <DEDENT> <DEDENT> def listenToClient(self, client, address): <NEW_LINE> <INDENT> size = 1024 <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> data = client.recv(size) <NEW_LINE> if data: <NEW_LINE> <INDENT> response = data <NEW_LINE> client.send(response) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Client disconnected from {0}:{1}".format(address[0],address[1])) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> client.close() <NEW_LINE> return False | Socket server where many client CLI can connect to use the OPC UA Client | 62598fa8be8e80087fbbefa7 |
class VoiceprinttopnVerifyResponse(object): <NEW_LINE> <INDENT> openapi_types = { 'scores': 'list[UnionIDScore]' } <NEW_LINE> attribute_map = { 'scores': 'scores' } <NEW_LINE> def __init__(self, scores=None): <NEW_LINE> <INDENT> self._scores = None <NEW_LINE> self.discriminator = None <NEW_LINE> if scores is not None: <NEW_LINE> <INDENT> self.scores = scores <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def scores(self): <NEW_LINE> <INDENT> return self._scores <NEW_LINE> <DEDENT> @scores.setter <NEW_LINE> def scores(self, scores): <NEW_LINE> <INDENT> self._scores = scores <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, VoiceprinttopnVerifyResponse): <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. | 62598fa87d43ff24874273a4 |
class WebcomicName(GenericTumblrV1): <NEW_LINE> <INDENT> name = "webcomicname" <NEW_LINE> long_name = "Webcomic Name" <NEW_LINE> url = "https://webcomicname.com" | Class to retrieve Webcomic Name comics. | 62598fa867a9b606de545f10 |
class DeliveryViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = DeliveryHead.objects.all() <NEW_LINE> serializer_class = DeliverySerializer | API endpoint that allows users to be viewed or edited. | 62598fa8d486a94d0ba2bf12 |
class FakeContext: <NEW_LINE> <INDENT> def __init__(self, db={}): <NEW_LINE> <INDENT> self.db = db <NEW_LINE> self.queries = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def db(self): <NEW_LINE> <INDENT> return self.__db <NEW_LINE> <DEDENT> @db.setter <NEW_LINE> def db(self, db): <NEW_LINE> <INDENT> self.__db=db <NEW_LINE> <DEDENT> @property <NEW_LINE> def queries(self): <NEW_LINE> <INDENT> return self.__queries <NEW_LINE> <DEDENT> @queries.setter <NEW_LINE> def queries(self, queries): <NEW_LINE> <INDENT> self.__queries = queries | A fake session, just used to query the database | 62598fa891f36d47f2230e47 |
@zope.interface.implementer(IObjectConfigurationLoadedEvent) <NEW_LINE> class ObjectConfigurationLoadedEvent(ObjectModifiedEvent): <NEW_LINE> <INDENT> pass | Object configuration loaded | 62598fa899fddb7c1ca62d8b |
class Meta: <NEW_LINE> <INDENT> verbose_name = 'UserRole' <NEW_LINE> verbose_name_plural = 'UserRoles' | Meta definition for UserRole. | 62598fa88da39b475be03129 |
class DivisionDict(typing.TypedDict, total=False): <NEW_LINE> <INDENT> id: typing.Optional[int] <NEW_LINE> name: typing.Optional[str] <NEW_LINE> employees: typing.Sequence["EmployeeDict"] | TypedDict for properties that are not required. | 62598fa8f7d966606f747f2a |
class MongoNHMStratigraphyTask(MongoTask): <NEW_LINE> <INDENT> module = 'enhmstratigraphy' | Import NHM Stratigraphy Export file into MongoDB | 62598fa8851cf427c66b820e |
class DNC_Model_V3(DNC_Model): <NEW_LINE> <INDENT> def __init__(self, num_dnc_layers=3, num_fcn_layers=3, *args, **kwargs): <NEW_LINE> <INDENT> super(DNC_Model_V3, self).__init__(*args, **kwargs) <NEW_LINE> self._num_dnc_layers = num_dnc_layers <NEW_LINE> self._num_fcn_layers = num_fcn_layers <NEW_LINE> <DEDENT> def getModel(self): <NEW_LINE> <INDENT> if self.model is not None: <NEW_LINE> <INDENT> return self.model <NEW_LINE> <DEDENT> print('{} constructing model {}'.format(strftime("%H:%M:%S"), self.getName())) <NEW_LINE> feat = keras.Input( shape=(self._time_step, self._feat_size), name='features', dtype=tf.float32) <NEW_LINE> layer = feat <NEW_LINE> for i in range(self._num_dnc_layers): <NEW_LINE> <INDENT> rnn = keras.layers.RNN( cell = dnc.DNC( name='DNC_{}'.format(i), output_size=self.output_size, controller_units=self.controller_units, memory_size=self.memory_size, word_size=self.word_size, num_read_heads=self.num_read_heads ), return_sequences=True if i+1 < self._num_dnc_layers else False ) <NEW_LINE> layer = keras.layers.Bidirectional(rnn)(layer) <NEW_LINE> <DEDENT> layer = keras.layers.AlphaDropout(self._dropout_rate)(layer) <NEW_LINE> units = self.output_size <NEW_LINE> for i in range(self._num_fcn_layers): <NEW_LINE> <INDENT> layer = keras.layers.Dense( units=units, bias_initializer=tf.constant_initializer(0.1), activation='selu' )(layer) <NEW_LINE> units = units // 2 <NEW_LINE> <DEDENT> outputs = keras.layers.Dense( units=1, bias_initializer=tf.constant_initializer(0.1), )(layer) <NEW_LINE> self.model = keras.Model(inputs=feat, outputs=outputs) <NEW_LINE> self.model._name = self.getName() <NEW_LINE> return self.model | Multiple Bidirectional DNC layers, AlphaDropout, Multiple FCN layers | 62598fa87047854f4633f31f |
class Headers(CaseInsensitiveDict): <NEW_LINE> <INDENT> def elements(self, key): <NEW_LINE> <INDENT> return header_elements(key, self.get(key)) <NEW_LINE> <DEDENT> def get_all(self, name): <NEW_LINE> <INDENT> value = self.get(name, '') <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return [val.strip() for val in value.split(',')] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Headers(%s)" % repr(list(self.items())) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> headers = ["%s: %s\r\n" % (k, v) for k, v in self.items()] <NEW_LINE> return "".join(headers) + '\r\n' <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> for k, v in super(Headers, self).items(): <NEW_LINE> <INDENT> if isinstance(v, list): <NEW_LINE> <INDENT> for vv in v: <NEW_LINE> <INDENT> yield (str(k), str(vv)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> yield (str(k), str(v)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __bytes__(self): <NEW_LINE> <INDENT> return str(self).encode("latin1") <NEW_LINE> <DEDENT> def append(self, key, value): <NEW_LINE> <INDENT> if key not in self: <NEW_LINE> <INDENT> if key.lower() == "set-cookie": <NEW_LINE> <INDENT> self[key] = [value] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self[key] = value <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(self[key], list): <NEW_LINE> <INDENT> self[key].append(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self[key] = ", ".join([self[key], value]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_header(self, _name, _value, **_params): <NEW_LINE> <INDENT> parts = [] <NEW_LINE> if _value is not None: <NEW_LINE> <INDENT> parts.append(_value) <NEW_LINE> <DEDENT> for k, v in list(_params.items()): <NEW_LINE> <INDENT> k = k.replace('_', '-') <NEW_LINE> if v is None: <NEW_LINE> <INDENT> parts.append(k) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parts.append(_formatparam(k, v)) <NEW_LINE> <DEDENT> <DEDENT> self.append(_name, "; ".join(parts)) | This class implements a storage for headers as key value pairs.
The underlying model of a case insensitive dict matches the requirements
for headers quite well, because usually header keys are unique. If
several values may be associated with a header key, most HTTP headers
represent the values as an enumeration using a comma as item separator.
There is, however one exception (currently) to this rule. In order to
set several cookies, there should be multiple headers with the same
key, each setting one cookie ("Set-Cookie: some_cookie").
This is modeled by having either a string (common case) or a list
(cookie case) as value in the underlying dict. In order to allow
easy iteration over all headers as they appear in the HTTP request,
the items() method expands associated lists of values. So if you have
{ "Set-Cookie": [ "cookie1", "cookie2" ] }, the items() method returns
the two pairs ("Set-Cookie", "cookie1") and ("Set-Cookie", "cookie2").
This is convenient for most use cases. The only drawback is that
len(keys()) is not equal to len(items()) for this specialized dict. | 62598fa87b25080760ed73f2 |
class TimeTrackingMixin(object): <NEW_LINE> <INDENT> created = Column(DateTime) <NEW_LINE> modified = Column(DateTime) | A model mix-in with created and modified datetime columns. | 62598fa83d592f4c4edbae13 |
class MapObjectAPIViewSet(viewsets.ViewSet): <NEW_LINE> <INDENT> queryset = MapPointer.objects.all() <NEW_LINE> def list(self, request): <NEW_LINE> <INDENT> ct = request.QUERY_PARAMS.get('ct') <NEW_LINE> pk = request.QUERY_PARAMS.get('pk') <NEW_LINE> if ct and pk: <NEW_LINE> <INDENT> pointers = MapPointer.objects.filter(content_type_id=ct) .filter(object_pk=pk) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pointers = MapPointer.objects.all() <NEW_LINE> <DEDENT> serializer = MapObjectSerializer(pointers, many=True, context={'request': request}) <NEW_LINE> return Response(serializer.data) | This viewset is made only for GET requests. It presents entire
list of all map objects created by users in proper format. They
are then used to populate main map view with map pointers.
It is possible to search through certain objects by ID and object type
to which the marker referes to. To do so, in the GET parameter of the
content type and the ID of the object, e.g.
```/api-maps/objects/?ct=23&pk=1``` | 62598fa88a43f66fc4bf20c2 |
class ImportResourceType(enum.Enum): <NEW_LINE> <INDENT> CATEGORY = "category" <NEW_LINE> ORDER = "order" <NEW_LINE> ORDER_PATCH = "order-patch" <NEW_LINE> PRICE = "price" <NEW_LINE> PRODUCT = "product" <NEW_LINE> PRODUCT_DRAFT = "product-draft" <NEW_LINE> PRODUCT_TYPE = "product-type" <NEW_LINE> PRODUCT_VARIANT = "product-variant" <NEW_LINE> PRODUCT_VARIANT_PATCH = "product-variant-patch" <NEW_LINE> CUSTOMER = "customer" | The type of the import resource. | 62598fa84e4d56256637236b |
class Host(object): <NEW_LINE> <INDENT> __slots__ = [ 'name', 'vars', 'groups' ] <NEW_LINE> def __init__(self, name=None, port=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.vars = {} <NEW_LINE> self.groups = [] <NEW_LINE> if port and port != C.DEFAULT_REMOTE_PORT: <NEW_LINE> <INDENT> self.set_variable('ansible_ssh_port', int(port)) <NEW_LINE> <DEDENT> if self.name is None: <NEW_LINE> <INDENT> raise Exception("host name is required") <NEW_LINE> <DEDENT> <DEDENT> def add_group(self, group): <NEW_LINE> <INDENT> self.groups.append(group) <NEW_LINE> <DEDENT> def set_variable(self, key, value): <NEW_LINE> <INDENT> self.vars[key]=value <NEW_LINE> <DEDENT> def get_groups(self): <NEW_LINE> <INDENT> groups = {} <NEW_LINE> for g in self.groups: <NEW_LINE> <INDENT> groups[g.name] = g <NEW_LINE> ancestors = g.get_ancestors() <NEW_LINE> for a in ancestors: <NEW_LINE> <INDENT> groups[a.name] = a <NEW_LINE> <DEDENT> <DEDENT> return groups.values() <NEW_LINE> <DEDENT> def get_variables(self): <NEW_LINE> <INDENT> results = {} <NEW_LINE> for group in self.groups: <NEW_LINE> <INDENT> results.update(group.get_variables()) <NEW_LINE> <DEDENT> results.update(self.vars) <NEW_LINE> results['inventory_hostname'] = self.name <NEW_LINE> groups = self.get_groups() <NEW_LINE> results['group_names'] = sorted([ g.name for g in groups if g.name != 'all']) <NEW_LINE> return results | a single ansible host | 62598fa8be383301e025373f |
class SpeechRecognitionCanceledEventArgs(SpeechRecognitionEventArgs): <NEW_LINE> <INDENT> def __init__(self, evt_args): <NEW_LINE> <INDENT> super().__init__(evt_args) <NEW_LINE> self._cancellation_details = evt_args.cancellation_details <NEW_LINE> <DEDENT> @property <NEW_LINE> def cancellation_details(self) -> "CancellationDetails": <NEW_LINE> <INDENT> return self._cancellation_details | Class for speech recognition canceled event arguments. | 62598fa82ae34c7f260ab028 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.