code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class TestAnnotationSet(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 testAnnotationSet(self): <NEW_LINE> <INDENT> pass
AnnotationSet unit test stubs
62598fcfa05bb46b3848ac87
class ReverseHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> def get(self, input): <NEW_LINE> <INDENT> self.write(input[::-1])
docstring for ReverseHandler
62598fcf656771135c489a8c
class TipWxCallbackHandler(BaseHandler): <NEW_LINE> <INDENT> async def post(self): <NEW_LINE> <INDENT> jsonObj = parseWeixin(self.request.body.decode('utf-8'),['result_code','return_code','time_end','out_trade_no']) <NEW_LINE> print(jsonObj) <NEW_LINE> print('wxpay/wx_callback') <NEW_LINE> if jsonObj['return_code']=='SUCCESS' and jsonObj['result_code'] =='SUCCESS': <NEW_LINE> <INDENT> order_number = jsonObj['out_trade_no'] <NEW_LINE> time_end = jsonObj['time_end'] <NEW_LINE> tip = await self.db.tip.get_by_orderNumber(order_number) <NEW_LINE> print('find order') <NEW_LINE> if tip is None: <NEW_LINE> <INDENT> self.finish_wx() <NEW_LINE> return <NEW_LINE> <DEDENT> await self.db.tip.update(tip["_id"],{'state':'accpaid','payTime':self.get_timestamp()}) <NEW_LINE> await self.db.master.add_money_by_user_id('tip_money',tip['to_user'],int(tip['price'])) <NEW_LINE> notice = produce_notice_system_tip('tip_finish',tip['to_user'],{'tipId':tip['_id']}) <NEW_LINE> notice_id = await self.db.notice.insert(notice) <NEW_LINE> print('order update') <NEW_LINE> self.finish_wx() <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('order fail') <NEW_LINE> self.finish_wx(result=prepay_id) <NEW_LINE> <DEDENT> <DEDENT> def finish_wx(self): <NEW_LINE> <INDENT> self.finish('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>')
@api {post} /v1.0/tip/wxpay/wx_callback 微信支付腾讯回调 @apiGroup order @apiVersion 1.0.0 @apiDescription 微信支付回调 @apiPermission user
62598fcf3617ad0b5ee06564
class AsyncSerial(serial.Serial): <NEW_LINE> <INDENT> async def read(self, n=None) -> bytes: <NEW_LINE> <INDENT> take_all = n is None <NEW_LINE> if take_all: n = 1 <NEW_LINE> while self.in_waiting < n: <NEW_LINE> <INDENT> await asyncio.sleep(0.05) <NEW_LINE> <DEDENT> if take_all: n = self.in_waiting <NEW_LINE> return super().read(n)
Simple wrapper of Serial, that provides an async api
62598fcfad47b63b2c5a7c77
class Variable(): <NEW_LINE> <INDENT> def __init__(self, name="", value=0, type="numeric"): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._value = value <NEW_LINE> self._type = type <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, value): <NEW_LINE> <INDENT> self._name = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @type.setter <NEW_LINE> def type(self, value): <NEW_LINE> <INDENT> self._type = value
Clase base para los diferentes tipos de variables que puede soportar un Objeto
62598fcfd8ef3951e32c806a
class Sge(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.template_path = os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> self.template_environment = Environment( autoescape=False, loader=FileSystemLoader(os.path.join(self.template_path, 'templates')), trim_blocks=False) <NEW_LINE> <DEDENT> def render_template(self, template_filename, context): <NEW_LINE> <INDENT> return self.template_environment.get_template(template_filename).render(context) <NEW_LINE> <DEDENT> def create_cluster_shell_script(self, output, template_filename, context): <NEW_LINE> <INDENT> with open(output, 'w') as output_filehandle: <NEW_LINE> <INDENT> shell_script = self.render_template(template_filename, context) <NEW_LINE> output_filehandle.write(shell_script) <NEW_LINE> <DEDENT> if context['submit']: <NEW_LINE> <INDENT> self.submit_job(script=output) <NEW_LINE> <DEDENT> return {"output":output} <NEW_LINE> <DEDENT> def submit_job(self, script): <NEW_LINE> <INDENT> command = " ".join(["qsub", script]) <NEW_LINE> print("Command is: ", command) <NEW_LINE> try: <NEW_LINE> <INDENT> return_code = call(command, shell=True) <NEW_LINE> if return_code != 0: <NEW_LINE> <INDENT> print("Job submission terminated by signal", -return_code, file=sys.stderr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Job submission returned", return_code, file=sys.stderr) <NEW_LINE> <DEDENT> <DEDENT> except OSError as job_error: <NEW_LINE> <INDENT> print("Execution failed:", job_error, file=sys.stderr) <NEW_LINE> <DEDENT> <DEDENT> def create_hold_job_string(self, jobs): <NEW_LINE> <INDENT> return ",".join(jobs) <NEW_LINE> <DEDENT> def get_jobid_from_submission(self, sge_output, sge_output_jobid_index=2): <NEW_LINE> <INDENT> return sge_output.split()[sge_output_jobid_index]
NAME Sge -- A SGE class for parallel job submission SYNOPSIS hpc = Sge() DESCRIPTION The Sun Grid Engine (SGE) can be used to run parallel jobs across numerous nodes and cores across a network. The Sge module provides APIs and wrappers for handling routine tasks that are typically performed on the command line.
62598fcfa05bb46b3848ac89
class ShootSearch(object): <NEW_LINE> <INDENT> MAX_STEP = 120 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.strat = ShootExpe() <NEW_LINE> team1 = SoccerTeam("test") <NEW_LINE> team1.add("Expe",RandomStrategy()) <NEW_LINE> team2 = SoccerTeam("test2") <NEW_LINE> team2.add("Nothing",GardienStrategy()) <NEW_LINE> team2.add("cible",CampeurStrategy_1()) <NEW_LINE> self.simu = Simulation(team1,team2,max_steps=1000000) <NEW_LINE> self.simu.listeners+=self <NEW_LINE> self.discr_step = 10 <NEW_LINE> self.nb_essais = 10 <NEW_LINE> <DEDENT> def start(self,visu=True): <NEW_LINE> <INDENT> if visu : <NEW_LINE> <INDENT> show_simu(self.simu) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.simu.start() <NEW_LINE> <DEDENT> <DEDENT> def begin_match(self,team1,team2,state): <NEW_LINE> <INDENT> self.res = dict() <NEW_LINE> self.last = 0 <NEW_LINE> self.but = 0 <NEW_LINE> self.cpt = 0 <NEW_LINE> self.params = [x for x in np.linspace(1,settings.maxPlayerShoot,self.discr_step)] <NEW_LINE> self.idx=0 <NEW_LINE> <DEDENT> def begin_round(self,team1,team2,state): <NEW_LINE> <INDENT> position = Vector2D(np.random.random()*settings.GAME_WIDTH/2.+settings.GAME_WIDTH/2.,np.random.random()*settings.GAME_HEIGHT) <NEW_LINE> self.simu.state.states[(1,0)].position = position.copy() <NEW_LINE> self.simu.state.states[(2,0)].position = Vector2D(145,45) <NEW_LINE> self.simu.state.states[(2,1)].position = Vector2D(70,65) <NEW_LINE> self.simu.state.states[(1,0)].vitesse = Vector2D() <NEW_LINE> self.simu.state.ball.position = Vector2D(120,45) <NEW_LINE> self.strat.norm = self.params[self.idx] if self.idx < len(self.params) else 1 <NEW_LINE> self.last = self.simu.step <NEW_LINE> <DEDENT> def update_round(self,team1,team2,state): <NEW_LINE> <INDENT> if state.step>self.last+self.MAX_STEP: <NEW_LINE> <INDENT> self.simu.end_round() <NEW_LINE> <DEDENT> <DEDENT> def end_round(self,team1,team2,state): <NEW_LINE> <INDENT> if state.goal>0: <NEW_LINE> <INDENT> self.but+=1 <NEW_LINE> <DEDENT> self.cpt+=1 <NEW_LINE> if self.cpt>=self.nb_essais: <NEW_LINE> <INDENT> self.res[self.params[self.idx]] = self.but*1./self.cpt <NEW_LINE> logger.debug("parametre %s : %f" %((str(self.params[self.idx]),self.res[self.params[self.idx]]))) <NEW_LINE> self.idx+=1 <NEW_LINE> self.but=0 <NEW_LINE> self.cpt=0 <NEW_LINE> <DEDENT> """ si plus de parametre, fin du match""" <NEW_LINE> if self.idx>=len(self.params): <NEW_LINE> <INDENT> self.simu.end_match()
nombre d'iterations maximales jusqu'a l'arret d'un round discr_step : pas de discretisation du parametre nb_essais : nombre d'essais par parametre
62598fcfa219f33f346c6c23
class ShellyBlock(RestoreEntity): <NEW_LINE> <INDENT> def __init__(self, block, instance, prefix=""): <NEW_LINE> <INDENT> conf = instance.conf <NEW_LINE> id_prefix = conf.get(CONF_OBJECT_ID_PREFIX) <NEW_LINE> self._unique_id = slugify(id_prefix + "_" + block.type + "_" + block.id + prefix) <NEW_LINE> self.entity_id = "." + self._unique_id <NEW_LINE> entity_id = instance._get_specific_config(CONF_ENTITY_ID, None, block.id) <NEW_LINE> if entity_id is not None: <NEW_LINE> <INDENT> self.entity_id = "." + slugify(id_prefix + "_" + entity_id + prefix) <NEW_LINE> self._unique_id += "_" + slugify(entity_id) <NEW_LINE> <DEDENT> self._show_id_in_name = conf.get(CONF_SHOW_ID_IN_NAME) <NEW_LINE> self._block = block <NEW_LINE> self.hass = instance.hass <NEW_LINE> self.instance = instance <NEW_LINE> self._block.cb_updated.append(self._updated) <NEW_LINE> block.shelly_device = self <NEW_LINE> self._name = instance._get_specific_config(CONF_NAME, None, block.id) <NEW_LINE> self._name_ext = None <NEW_LINE> self._is_removed = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> if self._name is None: <NEW_LINE> <INDENT> name = self._block.friendly_name() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = self._name <NEW_LINE> <DEDENT> if self._name_ext: <NEW_LINE> <INDENT> name += ' - ' + self._name_ext <NEW_LINE> <DEDENT> if self._show_id_in_name: <NEW_LINE> <INDENT> name += " [" + self._block.id + "]" <NEW_LINE> <DEDENT> return name <NEW_LINE> <DEDENT> def _updated(self, _block): <NEW_LINE> <INDENT> if self.entity_id is not None and not self._is_removed: <NEW_LINE> <INDENT> self.schedule_update_ha_state(True) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> attrs = {'ip_address': self._block.ip_addr, 'shelly_type': self._block.type_name(), 'shelly_id': self._block.id, 'discovery': self._block.discovery_src } <NEW_LINE> room = self._block.room_name() <NEW_LINE> if room: <NEW_LINE> <INDENT> attrs['room'] = room <NEW_LINE> <DEDENT> if self._block.info_values is not None: <NEW_LINE> <INDENT> for key, value in self._block.info_values.items(): <NEW_LINE> <INDENT> if self.instance.conf_attribute(key): <NEW_LINE> <INDENT> attrs[key] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return attrs <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_info(self): <NEW_LINE> <INDENT> return { 'identifiers': { (DOMAIN, self._block.unit_id) }, 'name': self._block.friendly_name(), 'manufacturer': 'Allterco', 'model': self._block.type_name(), 'sw_version': self._block.fw_version() } <NEW_LINE> return self.instance.build_device_info(self._block) <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return self._unique_id <NEW_LINE> <DEDENT> def remove(self): <NEW_LINE> <INDENT> self._is_removed = True <NEW_LINE> self.hass.add_job(self.async_remove)
Base class for Shelly entities
62598fcf5fdd1c0f98e5e3aa
class CTD_ANON_14 (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = None <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('/tmp/tmpHOdumhxsds/PacBioBaseDataModel.xsd', 594, 6) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __BinCount = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'BinCount'), 'BinCount', '__httppacificbiosciences_comPacBioBaseDataModel_xsd_CTD_ANON_14_httppacificbiosciences_comPacBioBaseDataModel_xsdBinCount', True, pyxb.utils.utility.Location('/tmp/tmpHOdumhxsds/PacBioBaseDataModel.xsd', 596, 8), ) <NEW_LINE> BinCount = property(__BinCount.value, __BinCount.set, None, None) <NEW_LINE> _ElementMap.update({ __BinCount.name() : __BinCount }) <NEW_LINE> _AttributeMap.update({ })
Complex type [anonymous] with content type ELEMENT_ONLY
62598fcf4527f215b58ea2ec
class sitetree_childrenNode(template.Node): <NEW_LINE> <INDENT> def __init__(self, tree_item, navigation_type, use_template): <NEW_LINE> <INDENT> self.use_template = use_template <NEW_LINE> self.tree_item = tree_item <NEW_LINE> self.navigation_type = navigation_type <NEW_LINE> <DEDENT> def render(self, context): <NEW_LINE> <INDENT> return get_sitetree().children(self.tree_item, self.navigation_type, self.use_template.resolve(context), context)
Renders tree items under specified parent site tree item.
62598fcf091ae35668705049
class Position(models.Model): <NEW_LINE> <INDENT> name: 'models.CharField[str, str]' = models.CharField( 'Должность', max_length=50, ) <NEW_LINE> department: 'models.ForeignKey[Department, str]' = models.ForeignKey( to=Department, verbose_name='Отдел', on_delete=models.DO_NOTHING, blank=True, null=True, ) <NEW_LINE> def __str__(self) -> str: <NEW_LINE> <INDENT> return f'{self.name} Отдел: {self.department or "Отсутствует"}' <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name: str = 'Должность' <NEW_LINE> verbose_name_plural: str = 'Должности'
`Должность` сотрудника.
62598fcf71ff763f4b5e7ba0
class RelLink(object): <NEW_LINE> <INDENT> def __init__(self, rel=None, href=None): <NEW_LINE> <INDENT> self.swagger_types = { 'rel': 'str', 'href': 'str' } <NEW_LINE> self.attribute_map = { 'rel': 'rel', 'href': 'href' } <NEW_LINE> self._rel = rel <NEW_LINE> self._href = href <NEW_LINE> <DEDENT> @property <NEW_LINE> def rel(self): <NEW_LINE> <INDENT> return self._rel <NEW_LINE> <DEDENT> @rel.setter <NEW_LINE> def rel(self, rel): <NEW_LINE> <INDENT> self._rel = rel <NEW_LINE> <DEDENT> @property <NEW_LINE> def href(self): <NEW_LINE> <INDENT> return self._href <NEW_LINE> <DEDENT> @href.setter <NEW_LINE> def href(self, href): <NEW_LINE> <INDENT> self._href = href <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> if not isinstance(other, RelLink): <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 the swagger code generator program. Do not edit the class manually.
62598fcf97e22403b383b327
class ExtendedReadWritableBag(Bag, _ExtendedReadWritableMixin): <NEW_LINE> <INDENT> def __init__(self, bagpath): <NEW_LINE> <INDENT> super(ExtendedReadWritableBag, self).__init__(bagpath) <NEW_LINE> self._extend(bagpath) <NEW_LINE> <DEDENT> def _extend(self, bagdir): <NEW_LINE> <INDENT> _ExtendedReadWritableMixin.__init__(self, bagdir)
A Bag with an extended interface.
62598fcf4527f215b58ea2ee
class MRI10yr06mo01da_normal(ChrisApp): <NEW_LINE> <INDENT> AUTHORS = 'FNNDSC (dev@babyMRI.org)' <NEW_LINE> SELFPATH = os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> SELFEXEC = os.path.basename(__file__) <NEW_LINE> EXECSHELL = 'python3' <NEW_LINE> TITLE = 'Anonymized reference MRI' <NEW_LINE> CATEGORY = 'Raw Data' <NEW_LINE> TYPE = 'fs' <NEW_LINE> DESCRIPTION = 'This application simply copies from embedded data a reference normal anonymized MRI of a subject aged 10 years, 06 months, 01 days.' <NEW_LINE> DOCUMENTATION = 'http://wiki' <NEW_LINE> VERSION = '1.1.4' <NEW_LINE> ICON = '' <NEW_LINE> LICENSE = 'Opensource (MIT)' <NEW_LINE> MAX_NUMBER_OF_WORKERS = 1 <NEW_LINE> MIN_NUMBER_OF_WORKERS = 1 <NEW_LINE> MAX_CPU_LIMIT = '' <NEW_LINE> MIN_CPU_LIMIT = '' <NEW_LINE> MAX_MEMORY_LIMIT = '' <NEW_LINE> MIN_MEMORY_LIMIT = '' <NEW_LINE> MIN_GPU_LIMIT = 0 <NEW_LINE> MAX_GPU_LIMIT = 0 <NEW_LINE> OUTPUT_META_DICT = {} <NEW_LINE> def define_parameters(self): <NEW_LINE> <INDENT> self.add_argument('--splash', help = 'a splash message to print', type = str, dest = 'splash', optional = True, default = '') <NEW_LINE> self.add_argument('--dir', dest ='dir', type = str, default = '', optional = True, help = 'directory override') <NEW_LINE> <DEDENT> def run(self, options): <NEW_LINE> <INDENT> print(Gstr_title) <NEW_LINE> print('Version: %s' % MRI10yr06mo01da_normal.VERSION) <NEW_LINE> if len(options.splash): <NEW_LINE> <INDENT> print(options.splash) <NEW_LINE> <DEDENT> if len(options.dir): <NEW_LINE> <INDENT> copy_tree(options.dir, options.outputdir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> str_srcDir = '../data' <NEW_LINE> l_files = os.listdir(str_srcDir) <NEW_LINE> for str_file in l_files: <NEW_LINE> <INDENT> str_filename = os.path.join(str_srcDir, str_file) <NEW_LINE> if (os.path.isfile(str_filename)): <NEW_LINE> <INDENT> print('Copying %s...' % str_filename) <NEW_LINE> shutil.copy(str_filename, options.outputdir) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def show_man_page(self): <NEW_LINE> <INDENT> print(Gstr_synopsis)
This application simply copies from embedded data a reference normal anonymized MRI of a subject aged 10 years, 06 months, 01 days..
62598fcfbe7bc26dc9252069
class AlphaDivDisplayModule(SampleToolDisplayModule): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def required_tool_results(): <NEW_LINE> <INDENT> return [AlphaDiversityResultModule] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def name(cls): <NEW_LINE> <INDENT> return MODULE_NAME <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_result_model(cls): <NEW_LINE> <INDENT> return AlphaDiversityResult <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_wrangler(cls): <NEW_LINE> <INDENT> return AlphaDivWrangler
Alpha Diversity display module.
62598fcf9f28863672818a8d
class PathMapping(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Path = None <NEW_LINE> self.Environment = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Path = params.get("Path") <NEW_LINE> self.Environment = params.get("Environment")
Custom domain name path mapping.
62598fcf60cbc95b0636475e
class DcvValidator(Validator): <NEW_LINE> <INDENT> def _validate(self, instance_type, dcv_enabled, allowed_ips, port, os, architecture: str): <NEW_LINE> <INDENT> if dcv_enabled: <NEW_LINE> <INDENT> allowed_oses = get_supported_dcv_os(architecture) <NEW_LINE> if os not in allowed_oses: <NEW_LINE> <INDENT> self._add_failure( f"NICE DCV can be used with one of the following operating systems " f"when using {architecture} architecture: {allowed_oses}. " "Please double check the os configuration.", FailureLevel.ERROR, ) <NEW_LINE> <DEDENT> if re.search(r"(micro)|(nano)", instance_type): <NEW_LINE> <INDENT> self._add_failure( "The packages required for desktop virtualization in the selected instance type '{0}' " "may cause instability of the instance. If you want to use NICE DCV it is recommended " "to use an instance type with at least 1.7 GB of memory.".format(instance_type), FailureLevel.WARNING, ) <NEW_LINE> <DEDENT> if allowed_ips == CIDR_ALL_IPS: <NEW_LINE> <INDENT> self._add_failure( f"With this configuration you are opening DCV port {port} to the world (0.0.0.0/0). " "It is recommended to restrict access.", FailureLevel.WARNING, )
DCV parameters validators. Validate instance type, architecture and os when DCV is enabled.
62598fcf71ff763f4b5e7ba4
class Hermes(object): <NEW_LINE> <INDENT> backend = None <NEW_LINE> mangler = None <NEW_LINE> cachedClass = None <NEW_LINE> ttl = 3600 <NEW_LINE> def __init__(self, backendClass = AbstractBackend, manglerClass = Mangler, cachedClass = Cached, **kwargs): <NEW_LINE> <INDENT> self.ttl = kwargs.pop('ttl', self.ttl) <NEW_LINE> assert issubclass(manglerClass, Mangler) <NEW_LINE> self.mangler = manglerClass() <NEW_LINE> assert issubclass(cachedClass, Cached) <NEW_LINE> self.cachedClass = cachedClass <NEW_LINE> assert issubclass(backendClass, AbstractBackend) <NEW_LINE> self.backend = backendClass(self.mangler, **kwargs) <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> if callable(args[0]) or inspect.ismethoddescriptor(args[0]): <NEW_LINE> <INDENT> return self.cachedClass(self.backend, self.mangler, self.ttl, args[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('First positional argument must be callable or method descriptor') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return lambda fn: self.cachedClass( self.backend, self.mangler, kwargs.pop('ttl', self.ttl), fn, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> def clean(self, tags = None): <NEW_LINE> <INDENT> if tags: <NEW_LINE> <INDENT> self.backend.remove(map(self.mangler.nameTag, tags)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.backend.clean()
Cache facade. Usage: import hermes.backend.redis cache = hermes.Hermes(hermes.backend.redis.Backend, ttl = 600, host = 'localhost', db = 1) @cache def foo(a, b): return a * b class Example: @cache(tags = ('math', 'power'), ttl = 1200) def bar(self, a, b): return a ** b @cache(tags = ('math', 'avg'), key = lambda fn, *args, **kwargs: 'avg:{0}:{1}'.format(*args)) def baz(self, a, b): return (a + b) / 2.0 print(foo(2, 333)) example = Example() print(example.bar(2, 10)) print(example.baz(2, 10)) foo.invalidate(2, 333) example.bar.invalidate(2, 10) example.baz.invalidate(2, 10) cache.clean(['math']) # invalidate entries tagged 'math' cache.clean() # flush cache
62598fcfdc8b845886d539e0
class ServerCommand(_SimpleCommand): <NEW_LINE> <INDENT> NAME = "SERVER"
Sent by the server on new connection and includes the server_name. Format:: SERVER <server_name>
62598fcf97e22403b383b32b
class Extension(object): <NEW_LINE> <INDENT> dist_name = None <NEW_LINE> ext_name = None <NEW_LINE> version = None <NEW_LINE> def get_default_config(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'Add at least a config section with "enabled = true"') <NEW_LINE> <DEDENT> def get_config_schema(self): <NEW_LINE> <INDENT> schema = config_lib.ConfigSchema(self.ext_name) <NEW_LINE> schema['enabled'] = config_lib.Boolean() <NEW_LINE> return schema <NEW_LINE> <DEDENT> def validate_environment(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_frontend_classes(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def get_backend_classes(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def register_gstreamer_elements(self): <NEW_LINE> <INDENT> pass
Base class for Mopidy extensions
62598fcf5fdd1c0f98e5e3b0
class UndoLine: <NEW_LINE> <INDENT> def Activated(self): <NEW_LINE> <INDENT> if (FreeCAD.activeDraftCommand != None): <NEW_LINE> <INDENT> if (FreeCAD.activeDraftCommand.featureName == "Line"): <NEW_LINE> <INDENT> FreeCAD.activeDraftCommand.undolast() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def GetResources(self): <NEW_LINE> <INDENT> return {'Pixmap' : 'Draft_Rotate', 'MenuText': QtCore.QT_TRANSLATE_NOOP("Draft_UndoLine", "Undo last segment"), 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Draft_UndoLine", "Undoes the last drawn segment of the line being drawn")} <NEW_LINE> <DEDENT> def IsActive(self): <NEW_LINE> <INDENT> if FreeCADGui.ActiveDocument: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
a FreeCAD command to undo last drawn segment of a line
62598fcf5fcc89381b26635e
class Status(colander.SequenceSchema): <NEW_LINE> <INDENT> status = colander.SchemaNode(colander.String(), validator=colander.OneOf(list(UpdateStatus.values())))
A SequenceSchema to validate a list of Update status objects.
62598fcffbf16365ca7944e0
class GCMove(Move): <NEW_LINE> <INDENT> parse_mover = staticmethod(None) <NEW_LINE> print_mover = staticmethod(None) <NEW_LINE> def __init__(self, pfreq, rmin, movers): <NEW_LINE> <INDENT> self.pfreq = pfreq <NEW_LINE> self.rmin = rmin <NEW_LINE> self.movers = movers <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> strme = [] <NEW_LINE> move = "move {} {} {} {}".format(self.key, len(self.movers), self.pfreq, self.rmin) <NEW_LINE> strme.append(move) <NEW_LINE> for mover in self.movers: <NEW_LINE> <INDENT> strme.append(self.print_mover(mover)) <NEW_LINE> <DEDENT> return "\n".join(strme) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> repme = "pfreq= {!r}, rmin= {!r}, movers= {!r}" .format(self.pfreq, self.rmin, self.movers) <NEW_LINE> return "{}({})".format(type(self).__name__, repme) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, dlstr): <NEW_LINE> <INDENT> lines = dlstr.splitlines() <NEW_LINE> line = lines.pop(0) <NEW_LINE> pfreq, rmin = GCMove._parse_move_statement(line)[2:] <NEW_LINE> movers = [] <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> mover = cls.parse_mover(line) <NEW_LINE> movers.append(mover) <NEW_LINE> <DEDENT> return cls(pfreq, rmin, movers) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _parse_move_statement(dlstr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tokens = dlstr.lower().split() <NEW_LINE> if tokens[0] != "move": <NEW_LINE> <INDENT> raise ValueError("Expected 'move' statement") <NEW_LINE> <DEDENT> mtype, nmove, pfreq, rmin = tokens[1], int(tokens[2]), int(tokens[3]), float(tokens[4]) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise ValueError("Badly formed 'move' statement?") <NEW_LINE> <DEDENT> return mtype, nmove, pfreq, rmin
Grand Canonical insertions have an extra minimum insertion distance parameter cf standard MCMove types
62598fcf099cdd3c636755f1
class EnhancedProgressBar(ProgressBar): <NEW_LINE> <INDENT> def render_progress(self): <NEW_LINE> <INDENT> if not self.is_hidden: <NEW_LINE> <INDENT> return super(EnhancedProgressBar, self).render_progress()
Enhanced progressbar ensuring that nothing is displayed when the bar is hidden.
62598fcfbe7bc26dc925206b
class UKPostcodeField(RegexField): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(UKPostcodeField, self).__init__(r'^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW]) [0-9][ABD-HJLNP-UW-Z]{2})$', max_length=None, min_length=None, error_message=gettext(u'Enter a postcode. A space is required between the two postcode parts.'), *args, **kwargs)
A form field that validates its input is a UK postcode. The regular expression used is sourced from the schema for British Standard BS7666 address types: http://www.govtalk.gov.uk/gdsc/schemas/bs7666-v2-0.xsd
62598fcfadb09d7d5dc0a99f
class IamRoleInvalidArgumentsError(Exception): <NEW_LINE> <INDENT> pass
Invalid arguments were used to create a role or trust policy.
62598fcf0fa83653e46f530c
class ServiceOrchestrator(object): <NEW_LINE> <INDENT> def __init__(self, token, tenant): <NEW_LINE> <INDENT> self.provision_event = threading.Event() <NEW_LINE> self.destroy_event = threading.Event() <NEW_LINE> self.so_e = SOE(token=token, tenant=tenant, ready_event=self.provision_event, destroy_event=self.destroy_event) <NEW_LINE> self.so_d = SOD(so_e=self.so_e, tenant=tenant, token=token, ready_event=self.provision_event, destroy_event=self.destroy_event) <NEW_LINE> LOG.debug('Starting SOD thread...') <NEW_LINE> self.so_d.start()
Sample SO.
62598fcf97e22403b383b32d
class PositionwiseFeedForward(nn.Module): <NEW_LINE> <INDENT> def __init__(self, size, hidden_size, dropout=0.1): <NEW_LINE> <INDENT> super(PositionwiseFeedForward, self).__init__() <NEW_LINE> self.w_1 = onmt.modules.BottleLinear(size, hidden_size) <NEW_LINE> self.w_2 = onmt.modules.BottleLinear(hidden_size, size) <NEW_LINE> self.layer_norm = onmt.modules.BottleLayerNorm(size) <NEW_LINE> self.dropout_1 = nn.Dropout(dropout) <NEW_LINE> self.dropout_2 = nn.Dropout(dropout) <NEW_LINE> self.relu = nn.ReLU() <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> inter = self.dropout_1(self.relu(self.w_1(self.layer_norm(x)))) <NEW_LINE> output = self.dropout_2(self.w_2(inter)) <NEW_LINE> return output + x
A two-layer Feed-Forward-Network.
62598fcfcc40096d6161a3ea
class ResourceManager: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.fonts = {} <NEW_LINE> self.tiles = {} <NEW_LINE> self.init_tiles("res/imgs/tile_resources.png") <NEW_LINE> self.finishedLoading = True <NEW_LINE> <DEDENT> def init_tiles(self, fn): <NEW_LINE> <INDENT> self.tilesMap = pygame.image.load(fn) <NEW_LINE> self.init_fonts() <NEW_LINE> self.init_letter_tiles(ord('A')) <NEW_LINE> self.init_letter_tiles(ord('a')) <NEW_LINE> self.init_board_tiles() <NEW_LINE> <DEDENT> def init_letter_tiles(self, starting): <NEW_LINE> <INDENT> for letter in range(starting, starting + 26): <NEW_LINE> <INDENT> t = self.tilesMap.subsurface( [0, 0, Tile_Size[0], Tile_Size[0]]).copy() <NEW_LINE> letter_s = self.fonts[Scrabble_Tile_Font].render( chr(letter), True, colors.BLACK) <NEW_LINE> letter_sx = (Tile_Size[0] - letter_s.get_width()) / 2 <NEW_LINE> letter_sy = (Tile_Size[1] - letter_s.get_height()) / 2 <NEW_LINE> if starting == ord('a'): <NEW_LINE> <INDENT> num_s = self.fonts[Scrabble_Number_Font].render( '0', True, colors.BLACK) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> num_s = self.fonts[Scrabble_Number_Font].render( str(wh.POINTS[chr(letter)]), True, colors.BLACK) <NEW_LINE> <DEDENT> num_sx = Tile_Size[0] - num_s.get_width() - 2 <NEW_LINE> num_sy = Tile_Size[1] - num_s.get_height() - 2 <NEW_LINE> t.blit(letter_s, (letter_sx, letter_sy)) <NEW_LINE> t.blit(num_s, (num_sx, num_sy)) <NEW_LINE> self.tiles[chr(letter)] = t <NEW_LINE> <DEDENT> t = self.tilesMap.subsurface( [0, 0, Tile_Size[0], Tile_Size[1]]).copy() <NEW_LINE> self.tiles[' '] = t <NEW_LINE> <DEDENT> def init_fonts(self): <NEW_LINE> <INDENT> for key, fn, sizes in Fonts_Config: <NEW_LINE> <INDENT> for size in sizes: <NEW_LINE> <INDENT> self.fonts[key + str(size)] = pygame.font.Font('./res/fonts/' + fn, size) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def init_board_tiles(self): <NEW_LINE> <INDENT> for key, render, rect in Board_Tiles: <NEW_LINE> <INDENT> t = self.tilesMap.subsurface(*rect).copy() <NEW_LINE> if render: <NEW_LINE> <INDENT> letter_s = self.fonts[Scrabble_Board_Font].render( key, True, colors.BLACK) <NEW_LINE> letter_sx = (Tile_Size[0] - letter_s.get_width()) / 2 <NEW_LINE> letter_sy = (Tile_Size[1] - letter_s.get_height()) / 2 <NEW_LINE> t.blit(letter_s, (letter_sx, letter_sy)) <NEW_LINE> <DEDENT> self.tiles[key] = t
The resource man(ager). Tracks all the resources and provides references to them for all the other classes to use (and draw). Must be initialized and linked at the start of the program.
62598fcf4c3428357761a6e4
class cmd_domain_pwdsettings_pso_show(Command): <NEW_LINE> <INDENT> synopsis = "%prog <psoname> [options]" <NEW_LINE> takes_optiongroups = { "sambaopts": options.SambaOptions, "versionopts": options.VersionOptions, "credopts": options.CredentialsOptions, } <NEW_LINE> takes_options = [ Option("-H", "--URL", help="LDB URL for database or target server", metavar="URL", dest="H", type=str) ] <NEW_LINE> takes_args = ["psoname"] <NEW_LINE> def run(self, psoname, H=None, credopts=None, sambaopts=None, versionopts=None): <NEW_LINE> <INDENT> lp = sambaopts.get_loadparm() <NEW_LINE> creds = credopts.get_credentials(lp) <NEW_LINE> samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) <NEW_LINE> pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb)) <NEW_LINE> check_pso_valid(samdb, pso_dn, psoname) <NEW_LINE> show_pso_by_dn(self.outf, samdb, pso_dn)
Display a Password Settings Object's details.
62598fcf7cff6e4e811b5e4e
class StopCond(Protocol): <NEW_LINE> <INDENT> def __call__(self, *, iterations: int, objectives: th.Tensor) -> th.Tensor: ...
A callable protocol that determines whether to stop optimization or not.
62598fcf50812a4eaa620df7
class Field(ElemWise): <NEW_LINE> <INDENT> __slots__ = '_hash', '_child', '_name' <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> if re.match('^\w+$', self._name): <NEW_LINE> <INDENT> return '%s.%s' % (self._child, self._name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "%s['%s']" % (self._child, self._name) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def _expr(self): <NEW_LINE> <INDENT> return symbol(self._name, datashape.DataShape(self.dshape.measure)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def dshape(self): <NEW_LINE> <INDENT> shape = self._child.dshape.shape <NEW_LINE> schema = self._child.dshape.measure.dict[self._name] <NEW_LINE> shape = shape + schema.shape <NEW_LINE> schema = (schema.measure,) <NEW_LINE> return DataShape(*(shape + schema))
A single field from an expression Get a single field from an expression with record-type schema. Collapses that record. We store the name of the field in the ``_name`` attribute. SELECT a FROM table >>> points = symbol('points', '5 * 3 * {x: int32, y: int32}') >>> points.x.dshape dshape("5 * 3 * int32")
62598fcfbe7bc26dc925206c
@OFPInstruction.register_instruction_type([ofproto_v1_3.OFPIT_GOTO_TABLE]) <NEW_LINE> class OFPInstructionGotoTable(StringifyMixin): <NEW_LINE> <INDENT> def __init__(self, table_id, type_=None, len_=None): <NEW_LINE> <INDENT> super(OFPInstructionGotoTable, self).__init__() <NEW_LINE> self.type = ofproto_v1_3.OFPIT_GOTO_TABLE <NEW_LINE> self.len = ofproto_v1_3.OFP_INSTRUCTION_GOTO_TABLE_SIZE <NEW_LINE> self.table_id = table_id <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parser(cls, buf, offset): <NEW_LINE> <INDENT> (type_, len_, table_id) = struct.unpack_from( ofproto_v1_3.OFP_INSTRUCTION_GOTO_TABLE_PACK_STR, buf, offset) <NEW_LINE> return cls(table_id) <NEW_LINE> <DEDENT> def serialize(self, buf, offset): <NEW_LINE> <INDENT> msg_pack_into(ofproto_v1_3.OFP_INSTRUCTION_GOTO_TABLE_PACK_STR, buf, offset, self.type, self.len, self.table_id)
Goto table instruction This instruction indicates the next table in the processing pipeline. ================ ====================================================== Attribute Description ================ ====================================================== table_id Next table ================ ======================================================
62598fcf956e5f7376df5891
class Context: <NEW_LINE> <INDENT> def __init__(self, logger=logger, obj=None): <NEW_LINE> <INDENT> self.logger = logger <NEW_LINE> self.exceptions = [] <NEW_LINE> self.obj = obj
will be passed to all `coroutine`s in the pipeline `Context` object is a common object shared by all coroutines in the pipeline. attributes: + `exceptions` is a list which remains empty until an exception occurs within a `task` and is handled by the module. Then `exception` contains each exception caught by the module. Each exception is logged only one time with its traceback when it's caught by `Control` context manager. .. note:: if an exception is caught by the module it will be "re-raised" thus terminate the process but user code could still raise another exception(s) for example if a coroutine is not implemented using `task` or GeneratorExit is handled within the user loop... + `logger` will be used for every message logged by the module, and can be used by the user. The default is to use the module's `logger`. + `obj` attribute is an arbitrary object provided by the user when creating the pipeline. The default is `None`. .. seealso:: `create`
62598fcf3617ad0b5ee06570
class LcarsTabLeft(LcarsWidget): <NEW_LINE> <INDENT> def __init__(self, colour, pos, handler = None, rectSize = None): <NEW_LINE> <INDENT> if rectSize == None: <NEW_LINE> <INDENT> image = pygame.image.load("assets/tab.png").convert() <NEW_LINE> size = (image.get_rect().width, image.get_rect().height) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> size = rectSize <NEW_LINE> image = pygame.Surface(rectSize).convert() <NEW_LINE> image.fill(colour) <NEW_LINE> <DEDENT> self.image = image <NEW_LINE> LcarsWidget.__init__(self, colour, pos, handler, size) <NEW_LINE> self.applyColour(colour)
Left-hand Tab widget (like radio button) (21x16) - implemented in PiCorder v0.1
62598fcfcc40096d6161a3eb
class S3QuestionTypeOptionOtherWidget(S3QuestionTypeOptionWidget): <NEW_LINE> <INDENT> def __init__(self, question_id = None ): <NEW_LINE> <INDENT> T = current.T <NEW_LINE> S3QuestionTypeOptionWidget.__init__(self, question_id) <NEW_LINE> self.typeDescription = T("Option Other") <NEW_LINE> <DEDENT> def getList(self): <NEW_LINE> <INDENT> list = S3QuestionTypeOptionWidget.getList(self) <NEW_LINE> list.append("Other") <NEW_LINE> return list
Option Question Type widget with a final other option attached provides a widget for the survey module that will manage simple yes no questions. Available metadata for this class: Help message: A message to help with completing the question Length: The number of options #: A number one for each option Other: The question type the other option should be @author: Graeme Foster (graeme at acm dot org)
62598fcf7cff6e4e811b5e50
class BlogMigrationView(BrowserView): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> self.has_blog_entries = len(self.blog_entries()) > 0 <NEW_LINE> return self.render() <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> return self.index() <NEW_LINE> <DEDENT> def blog_entries(self): <NEW_LINE> <INDENT> items = api.content.find( context=api.portal.get(), object_provides=IBlogEntry, sort_on='effective', sort_order='reverse' ) <NEW_LINE> return items <NEW_LINE> <DEDENT> def blog_entries_count(self): <NEW_LINE> <INDENT> return len(self.blog_entries()) <NEW_LINE> <DEDENT> def used_image_assets(self, uuid): <NEW_LINE> <INDENT> item = api.content.get(UID=uuid) <NEW_LINE> html_body = item.text.raw <NEW_LINE> xhtml = lxml.html.document_fromstring(html_body) <NEW_LINE> images = xhtml.xpath('//img') <NEW_LINE> image_idx = len(images) <NEW_LINE> return image_idx
Migrate blog content Move blog entries to folderish blog posting content types and transfer the associated images to the folder content
62598fcf283ffb24f3cf3cae
class game_engine(): <NEW_LINE> <INDENT> def game_is_over(self): <NEW_LINE> <INDENT> return False
game_engine class will contain any game logic or attributes to drive the flow of the game and its rules
62598fcf377c676e912f6f8d
class RewriteIO(io.RawIOBase): <NEW_LINE> <INDENT> def __init__(self, src, dest, buf=None): <NEW_LINE> <INDENT> io.RawIOBase.__init__(self) <NEW_LINE> self._src = src <NEW_LINE> self._dest = dest <NEW_LINE> if not buf: <NEW_LINE> <INDENT> buf = [] <NEW_LINE> <DEDENT> self._buf = buf <NEW_LINE> <DEDENT> def readinto(self, b): <NEW_LINE> <INDENT> self._checkClosed() <NEW_LINE> self._checkReadable() <NEW_LINE> buf = bytes("".join(self._buf)) <NEW_LINE> if buf and buf is not None: <NEW_LINE> <INDENT> l = len(b) <NEW_LINE> if len(self._buf) > l: <NEW_LINE> <INDENT> del b[l:] <NEW_LINE> b[0:l], buf = buf[:l], buf[l:] <NEW_LINE> self._buf = [buf] <NEW_LINE> return len(b) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> length = len(buf) <NEW_LINE> del b[length:] <NEW_LINE> b[0:length] = buf <NEW_LINE> self._buf = [] <NEW_LINE> return len(b) <NEW_LINE> <DEDENT> <DEDENT> if _readinto is not None: <NEW_LINE> <INDENT> return _readinto(self._src, b) <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._src.recv_into(b) <NEW_LINE> <DEDENT> except socket.error as e: <NEW_LINE> <INDENT> n = e.args[0] <NEW_LINE> if n == EINTR: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if n in _blocking_errnos: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def write(self, b): <NEW_LINE> <INDENT> self._checkClosed() <NEW_LINE> self._checkWritable() <NEW_LINE> try: <NEW_LINE> <INDENT> return self._dest.send(bytes(b)) <NEW_LINE> <DEDENT> except socket.error as e: <NEW_LINE> <INDENT> if e.args[0] in _blocking_errnos: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> <DEDENT> def writeall(self, b): <NEW_LINE> <INDENT> sent = 0 <NEW_LINE> while sent < len(b): <NEW_LINE> <INDENT> sent += self._dest.send(_get_memory(b, sent)) <NEW_LINE> <DEDENT> <DEDENT> def readable(self): <NEW_LINE> <INDENT> return not self.closed <NEW_LINE> <DEDENT> def writable(self): <NEW_LINE> <INDENT> return not self.closed <NEW_LINE> <DEDENT> def recv(self, n=None): <NEW_LINE> <INDENT> return self.read(n) <NEW_LINE> <DEDENT> def send(self, b): <NEW_LINE> <INDENT> return self.write(b) <NEW_LINE> <DEDENT> def sendall(self, b): <NEW_LINE> <INDENT> return self.writeall(b)
Raw I/O implementation for stream sockets. It provides the raw I/O interface on top of a socket object. Backported from python 3.
62598fcfab23a570cc2d4f82
class ContentTypeGb2312Middleware(object): <NEW_LINE> <INDENT> def process_response(self, request, response, spider): <NEW_LINE> <INDENT> response.headers['Content-Type'] = 'text/html; charset=gb2312' <NEW_LINE> return response
处理不规范的页面(优先级降低至580之后才能生效) 原因: 默认配置的 DOWNLOADER_MIDDLEWARES 包含 MetaRefreshMiddleware 当请求页面存在如 Content-Location 类似的 header 时, 会触发重定向请求 指定 Content-Type 为 gb2312
62598fcfa219f33f346c6c2f
@instancedoc <NEW_LINE> class ExpectElement(InterfaceElement): <NEW_LINE> <INDENT> def __init__(self, parent, value, is_name=False, name=None): <NEW_LINE> <INDENT> RingElement.__init__(self, parent) <NEW_LINE> self._create = value <NEW_LINE> if parent is None: return <NEW_LINE> if isinstance(value, string_types) and parent._eval_using_file_cutoff and parent._eval_using_file_cutoff < len(value): <NEW_LINE> <INDENT> self._get_using_file = True <NEW_LINE> <DEDENT> if is_name: <NEW_LINE> <INDENT> self._name = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._name = parent._create(value, name=name) <NEW_LINE> <DEDENT> except (RuntimeError, ValueError) as x: <NEW_LINE> <INDENT> self._session_number = -1 <NEW_LINE> raise_(TypeError, TypeError(*x.args), sys.exc_info()[2]) <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> self._session_number = -1 <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> self._session_number = parent._session_number <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash('%s%s'%(self, self._session_number)) <NEW_LINE> <DEDENT> def _check_valid(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> P = self.parent() <NEW_LINE> if P is None or P._session_number == BAD_SESSION or self._session_number == -1 or P._session_number != self._session_number: <NEW_LINE> <INDENT> raise ValueError("The %s session in which this object was defined is no longer running."%P.name()) <NEW_LINE> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError("The session in which this object was defined is no longer running.") <NEW_LINE> <DEDENT> return P <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._check_valid() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if hasattr(self, '_name'): <NEW_LINE> <INDENT> P = self.parent() <NEW_LINE> if P is not None: <NEW_LINE> <INDENT> P.clear(self._name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except (RuntimeError, ExceptionPexpect): <NEW_LINE> <INDENT> pass
Expect element.
62598fcffbf16365ca7944e6
class VolumeGroupPost(object): <NEW_LINE> <INDENT> swagger_types = { 'id': 'str', 'name': 'str', 'destroyed': 'bool', 'qos': 'Qos', 'priority_adjustment': 'PriorityAdjustment', 'space': 'Space', 'time_remaining': 'int', 'volume_count': 'int' } <NEW_LINE> attribute_map = { 'id': 'id', 'name': 'name', 'destroyed': 'destroyed', 'qos': 'qos', 'priority_adjustment': 'priority_adjustment', 'space': 'space', 'time_remaining': 'time_remaining', 'volume_count': 'volume_count' } <NEW_LINE> required_args = { } <NEW_LINE> def __init__( self, id=None, name=None, destroyed=None, qos=None, priority_adjustment=None, space=None, time_remaining=None, volume_count=None, ): <NEW_LINE> <INDENT> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if destroyed is not None: <NEW_LINE> <INDENT> self.destroyed = destroyed <NEW_LINE> <DEDENT> if qos is not None: <NEW_LINE> <INDENT> self.qos = qos <NEW_LINE> <DEDENT> if priority_adjustment is not None: <NEW_LINE> <INDENT> self.priority_adjustment = priority_adjustment <NEW_LINE> <DEDENT> if space is not None: <NEW_LINE> <INDENT> self.space = space <NEW_LINE> <DEDENT> if time_remaining is not None: <NEW_LINE> <INDENT> self.time_remaining = time_remaining <NEW_LINE> <DEDENT> if volume_count is not None: <NEW_LINE> <INDENT> self.volume_count = volume_count <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, key, value): <NEW_LINE> <INDENT> if key not in self.attribute_map: <NEW_LINE> <INDENT> raise KeyError("Invalid key `{}` for `VolumeGroupPost`".format(key)) <NEW_LINE> <DEDENT> self.__dict__[key] = value <NEW_LINE> <DEDENT> def __getattribute__(self, item): <NEW_LINE> <INDENT> value = object.__getattribute__(self, item) <NEW_LINE> if isinstance(value, Property): <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> if hasattr(self, attr): <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> <DEDENT> if issubclass(VolumeGroupPost, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = 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, VolumeGroupPost): <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
Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition.
62598fcf71ff763f4b5e7bac
class POWER_SEQUENCER_OT_preview_to_selection(bpy.types.Operator): <NEW_LINE> <INDENT> doc = { "name": doc_name(__qualname__), "demo": "https://i.imgur.com/EV1sUrn.gif", "description": doc_description(__doc__), "shortcuts": [ ({"type": "P", "value": "PRESS", "ctrl": True, "alt": True}, {}, "Preview To Selection") ], "keymap": "Sequencer", } <NEW_LINE> bl_idname = doc_idname(__qualname__) <NEW_LINE> bl_label = doc["name"] <NEW_LINE> bl_description = doc_brief(doc["description"]) <NEW_LINE> bl_options = {"REGISTER", "UNDO"} <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return context.sequences <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> sequences = ( context.selected_sequences if len(context.selected_sequences) >= 1 else context.sequences ) <NEW_LINE> frame_start, frame_end = get_frame_range(sequences) <NEW_LINE> set_preview_range(context, frame_start, frame_end - 1) <NEW_LINE> return {"FINISHED"}
*brief* Sets the timeline preview range to match the selection Sets the scene frame start to the earliest frame start of selected sequences and the scene frame end to the last frame of selected sequences. Uses all sequences in the current context if no sequences are selected.
62598fcf7cff6e4e811b5e52
class MyYandex(Yandex): <NEW_LINE> <INDENT> params = { 'webvisor': True, 'clickmap': True, 'track_links': True, 'accurate_bounce': True, 'no_index': False, 'track_hash': False, 'xml': False, 'user_params': False, }
Модифицированный класс управления счётчиком. Подключаем некоторые плюшки из тех, что умеет счётчик.
62598fcf3d592f4c4edbb2df
class DatabaseLibrary(ConnectionManager, Query, Assertion): <NEW_LINE> <INDENT> ROBOT_LIBRARY_SCOPE = 'GLOBAL'
Database Library contains utilities meant for Robot Framework's usage. This can allow you to query your database after an action has been made to verify the results. This is `compatible*` with any Database API Specification 2.0 module. References: + Database API Specification 2.0 - http://www.python.org/dev/peps/pep-0249/ + Lists of DB API 2.0 - http://wiki.python.org/moin/DatabaseInterfaces + Python Database Programming - http://wiki.python.org/moin/DatabaseProgramming/ Notes: `compatible* - or at least theoretically it should be compatible. Currently tested only with postgresql (using psycopg2).` Example Usage: | # Setup | | Connect to Database | | # Guard assertion (verify that test started in expected state). | | Check if not exists in database | select id from person where first_name = 'Franz Allan' and last_name = 'See' | | # Drive UI to do some action | | Go To | http://localhost/person/form.html | | # From selenium library | | Input Text | name=first_name | Franz Allan | # From selenium library | | Input Text | name=last_name | See | # From selenium library | | Click Button | Save | | # From selenium library | | # Log results | | @{queryResults} | Query | select * from person | | Log Many | @{queryResults} | | # Verify if persisted in the database | | Check if exists in database | select id from person where first_name = 'Franz Allan' and last_name = 'See' | | # Teardown | | Disconnect from Database |
62598fcf50812a4eaa620df9
class Test_arrayexpress_files(unittest.TestCase): <NEW_LINE> <INDENT> def test_new_accessions_1(self): <NEW_LINE> <INDENT> ref_acc = ['E-GEOD-42314', 'E-GEOD-51468', 'E-GEOD-55234', 'E-GEOD-50778', 'E-GEOD-30583'] <NEW_LINE> test_acc = new_accessions() <NEW_LINE> self.assertEqual(ref_acc, test_acc) <NEW_LINE> <DEDENT> def test_new_accessions_2(self): <NEW_LINE> <INDENT> os.chdir('test_new_accessions_2') <NEW_LINE> ref_acc = ['E-GEOD-42314'] <NEW_LINE> test_acc = new_accessions() <NEW_LINE> os.chdir('..') <NEW_LINE> self.assertEqual(ref_acc, test_acc)
Test the functions from the arrayexpress_files script.
62598fcfbe7bc26dc925206e
class Meta: <NEW_LINE> <INDENT> model = Ticket <NEW_LINE> fields = ( "original", ) <NEW_LINE> widgets = { "original": Select(attrs={ "class": "form-control select2", }), }
TicketDuplicationForm Meta class
62598fcfec188e330fdf8cc1
class IntersectionVolume(VolumeCombination): <NEW_LINE> <INDENT> def __init__(self, volume1, volume2): <NEW_LINE> <INDENT> super(IntersectionVolume, self).__init__( volume1=volume1, volume2=volume2, fnc=lambda a, b: a and b, str_fnc='{0} and {1}' )
"And" combination (intersection) of two volumes.
62598fcfd8ef3951e32c8071
class SetQuota(command.Command): <NEW_LINE> <INDENT> log = logging.getLogger(__name__ + '.SetQuota') <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(SetQuota, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'project', metavar='<project/class>', help='Set quotas for this project or class (name/ID)', ) <NEW_LINE> parser.add_argument( '--class', dest='quota_class', action='store_true', default=False, help='Set quotas for <class>', ) <NEW_LINE> for k, v in itertools.chain( COMPUTE_QUOTAS.items(), VOLUME_QUOTAS.items()): <NEW_LINE> <INDENT> parser.add_argument( '--%s' % v, metavar='<%s>' % v, type=int, help='New value for the %s quota' % v, ) <NEW_LINE> <DEDENT> parser.add_argument( '--volume-type', metavar='<volume-type>', help='Set quotas for a specific <volume-type>', ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> self.log.debug('take_action(%s)', parsed_args) <NEW_LINE> compute_client = self.app.client_manager.compute <NEW_LINE> volume_client = self.app.client_manager.volume <NEW_LINE> compute_kwargs = {} <NEW_LINE> for k, v in COMPUTE_QUOTAS.items(): <NEW_LINE> <INDENT> value = getattr(parsed_args, v, None) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> compute_kwargs[k] = value <NEW_LINE> <DEDENT> <DEDENT> volume_kwargs = {} <NEW_LINE> for k, v in VOLUME_QUOTAS.items(): <NEW_LINE> <INDENT> value = getattr(parsed_args, v, None) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> if parsed_args.volume_type: <NEW_LINE> <INDENT> k = k + '_%s' % parsed_args.volume_type <NEW_LINE> <DEDENT> volume_kwargs[k] = value <NEW_LINE> <DEDENT> <DEDENT> if compute_kwargs == {} and volume_kwargs == {}: <NEW_LINE> <INDENT> sys.stderr.write("No quotas updated") <NEW_LINE> return <NEW_LINE> <DEDENT> if parsed_args.quota_class: <NEW_LINE> <INDENT> if compute_kwargs: <NEW_LINE> <INDENT> compute_client.quota_classes.update( parsed_args.project, **compute_kwargs) <NEW_LINE> <DEDENT> if volume_kwargs: <NEW_LINE> <INDENT> volume_client.quota_classes.update( parsed_args.project, **volume_kwargs) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if compute_kwargs: <NEW_LINE> <INDENT> compute_client.quotas.update( parsed_args.project, **compute_kwargs) <NEW_LINE> <DEDENT> if volume_kwargs: <NEW_LINE> <INDENT> volume_client.quotas.update( parsed_args.project, **volume_kwargs)
Set quotas for project or class
62598fcf5fcc89381b266362
class PageManager(PublisherManager): <NEW_LINE> <INDENT> def get_query_set(self): <NEW_LINE> <INDENT> return PageQuerySet(self.model) <NEW_LINE> <DEDENT> def on_site(self, site=None): <NEW_LINE> <INDENT> return self.get_query_set().on_site(site) <NEW_LINE> <DEDENT> def root(self): <NEW_LINE> <INDENT> return self.get_query_set().root() <NEW_LINE> <DEDENT> def all_root(self): <NEW_LINE> <INDENT> return self.get_query_set().all_root() <NEW_LINE> <DEDENT> def valid_targets(self, page_id, request, perms, page=None): <NEW_LINE> <INDENT> return self.get_query_set().valid_targets(page_id, request, perms, page) <NEW_LINE> <DEDENT> def published(self, site=None): <NEW_LINE> <INDENT> return self.get_query_set().published(site) <NEW_LINE> <DEDENT> def expired(self): <NEW_LINE> <INDENT> return self.drafts().expired() <NEW_LINE> <DEDENT> def get_all_pages_with_application(self): <NEW_LINE> <INDENT> return self.get_query_set().filter(title_set__application_urls__gt='').distinct() <NEW_LINE> <DEDENT> def get_home(self, site=None): <NEW_LINE> <INDENT> return self.get_query_set().get_home(site) <NEW_LINE> <DEDENT> def search(self, q, language=None, current_site_only=True): <NEW_LINE> <INDENT> from cms.plugin_pool import plugin_pool <NEW_LINE> qs = self.get_query_set() <NEW_LINE> if settings.CMS_MODERATOR: <NEW_LINE> <INDENT> qs = qs.public() <NEW_LINE> <DEDENT> if current_site_only: <NEW_LINE> <INDENT> site = Site.objects.get_current() <NEW_LINE> qs = qs.filter(site=site) <NEW_LINE> <DEDENT> qt = Q(title_set__title__icontains=q) <NEW_LINE> qp = Q() <NEW_LINE> plugins = plugin_pool.get_all_plugins() <NEW_LINE> for plugin in plugins: <NEW_LINE> <INDENT> c = plugin.model <NEW_LINE> if hasattr(c, 'search_fields'): <NEW_LINE> <INDENT> for field in c.search_fields: <NEW_LINE> <INDENT> qp |= Q(**{'cmsplugin__%s__%s__icontains' % (c.__name__.lower(), field):q}) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if language: <NEW_LINE> <INDENT> qt &= Q(title_set__language=language) <NEW_LINE> qp &= Q(cmsplugin__language=language) <NEW_LINE> <DEDENT> qs = qs.filter(qt | qp) <NEW_LINE> return qs.distinct()
Use draft() and public() methods for accessing the corresponding instances.
62598fcf4c3428357761a6ea
class Muscle(Element): <NEW_LINE> <INDENT> def __init__( self, ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._attribute_names = []
All muscle attributes are available here except: name, class, joint, jointinparent, site, tendon, slidersite, cranksite.
62598fcf091ae35668705057
class BaseCaptchaTextInput(MultiWidget): <NEW_LINE> <INDENT> def __init__(self, attrs=None): <NEW_LINE> <INDENT> widgets = ( HiddenInput(attrs), TextInput(attrs), ) <NEW_LINE> super(BaseCaptchaTextInput, self).__init__(widgets, attrs) <NEW_LINE> <DEDENT> def decompress(self, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> return value.split(',') <NEW_LINE> <DEDENT> return [None, None] <NEW_LINE> <DEDENT> def fetch_captcha_store(self, name, value, attrs=None, generator=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> reverse('captcha-image', args=('dummy',)) <NEW_LINE> <DEDENT> except NoReverseMatch: <NEW_LINE> <INDENT> raise ImproperlyConfigured('Make sure you\'ve included captcha.urls as explained in the INSTALLATION section on http://readthedocs.org/docs/django-simple-captcha/en/latest/usage.html#installation') <NEW_LINE> <DEDENT> if settings.CAPTCHA_GET_FROM_POOL: <NEW_LINE> <INDENT> key = CaptchaStore.pick() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> key = CaptchaStore.generate_key(generator) <NEW_LINE> <DEDENT> self._value = [key, u('')] <NEW_LINE> self._key = key <NEW_LINE> self.id_ = self.build_attrs(attrs).get('id', None) <NEW_LINE> <DEDENT> def id_for_label(self, id_): <NEW_LINE> <INDENT> if id_: <NEW_LINE> <INDENT> return id_ + '_1' <NEW_LINE> <DEDENT> return id_ <NEW_LINE> <DEDENT> def image_url(self): <NEW_LINE> <INDENT> return reverse('captcha-image', kwargs={'key': self._key}) <NEW_LINE> <DEDENT> def audio_url(self): <NEW_LINE> <INDENT> return reverse('captcha-audio', kwargs={'key': self._key}) if settings.CAPTCHA_FLITE_PATH else None <NEW_LINE> <DEDENT> def refresh_url(self): <NEW_LINE> <INDENT> return reverse('captcha-refresh')
Base class for Captcha widgets
62598fcfbf627c535bcb18d9
class Solution: <NEW_LINE> <INDENT> def middleNode(self, head): <NEW_LINE> <INDENT> fast, slow = head, head <NEW_LINE> while fast: <NEW_LINE> <INDENT> fast = fast.next <NEW_LINE> if not fast: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> fast = fast.next <NEW_LINE> if not fast: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> slow = slow.next <NEW_LINE> <DEDENT> return slow
@param head: the head of linked list. @return: a middle node of the linked list
62598fcfbe7bc26dc925206f
class DjangoTestCase(FreshenTestCase, TestCase): <NEW_LINE> <INDENT> def __init__(self, step_runner, step_registry, feature, scenario, feature_suite): <NEW_LINE> <INDENT> FreshenTestCase.__init__(self, step_runner, step_registry, feature, scenario, feature_suite) <NEW_LINE> TestCase.__init__(self, scenario.name) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> super(DjangoTestCase, self).setUp() <NEW_LINE> for hook_impl in self.step_registry.get_hooks('before', self.scenario.get_tags()): <NEW_LINE> <INDENT> hook_impl.run(self.scenario) <NEW_LINE> <DEDENT> if scc.fixtures: <NEW_LINE> <INDENT> self.fixtures = scc.fixtures <NEW_LINE> <DEDENT> if hasattr(self, '_pre_setup'): <NEW_LINE> <INDENT> self._pre_setup() <NEW_LINE> <DEDENT> <DEDENT> def runScenario(self): <NEW_LINE> <INDENT> for step in self.scenario.iter_steps(): <NEW_LINE> <INDENT> self.runStep(step, 3) <NEW_LINE> <DEDENT> self.last_step = None <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> for hook_impl in reversed(self.step_registry.get_hooks('after', self.scenario.get_tags())): <NEW_LINE> <INDENT> hook_impl.run(self.scenario)
Support Django tests.
62598fcfadb09d7d5dc0a9a7
class Command(BaseCommand): <NEW_LINE> <INDENT> help = 'Trains the database used by the chat bot' <NEW_LINE> can_import_settings = True <NEW_LINE> def handle(self, *args, **options): <NEW_LINE> <INDENT> from chatterbot import ChatBot <NEW_LINE> from chatterbot.ext.django_chatterbot import settings <NEW_LINE> from chatterbot.trainers import ChatterBotCorpusTrainer <NEW_LINE> chatterbot = ChatBot(**settings.CHATTERBOT) <NEW_LINE> trainer = ChatterBotCorpusTrainer(chatterbot) <NEW_LINE> trainer.train(*settings.CHATTERBOT['training_data']) <NEW_LINE> if hasattr(self.style, 'SUCCESS'): <NEW_LINE> <INDENT> style = self.style.SUCCESS <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> style = self.style.NOTICE <NEW_LINE> <DEDENT> self.stdout.write(style('Starting training...')) <NEW_LINE> training_class = trainer.__class__.__name__ <NEW_LINE> self.stdout.write(style('ChatterBot trained using "%s"' % training_class))
A Django management command for calling a chat bot's training method.
62598fcfec188e330fdf8cc3
class NewPost(BlogHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> if self.user: <NEW_LINE> <INDENT> self.render("newpost.html") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.redirect("/login") <NEW_LINE> <DEDENT> <DEDENT> def post(self): <NEW_LINE> <INDENT> if not self.user: <NEW_LINE> <INDENT> self.redirect('/blog') <NEW_LINE> <DEDENT> subject = self.request.get('subject') <NEW_LINE> content = self.request.get('content') <NEW_LINE> uid = self.read_secure_cookie('user_id') <NEW_LINE> curr_user = User.by_id(int(uid)) <NEW_LINE> if subject and content: <NEW_LINE> <INDENT> p = Post(parent = blog_key(), subject = subject, content = content, author = curr_user) <NEW_LINE> p.put() <NEW_LINE> self.redirect('/blog/%s' % str(p.key.id())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error = "subject and content, please!" <NEW_LINE> self.render("newpost.html", subject=subject, content=content, error=error)
renders the new post page
62598fcfa219f33f346c6c33
class Solution: <NEW_LINE> <INDENT> def lengthOfLongestSubstring(self, s: str) -> int: <NEW_LINE> <INDENT> res = 0 <NEW_LINE> pos = {} <NEW_LINE> pre = -1 <NEW_LINE> for i, v in enumerate(s): <NEW_LINE> <INDENT> pre = max(pre, pos[v] if v in pos else -1) <NEW_LINE> res = max(res, i - pre) <NEW_LINE> pos[v] = i <NEW_LINE> <DEDENT> return res
parameters ---------- res: (best) result (so far) pos: position where character appeared last pre: prehead (one step before head) of current substring
62598fcf091ae35668705059
class IsAdmin(MyBaseHandler): <NEW_LINE> <INDENT> @token_required() <NEW_LINE> @my_async_jsonp <NEW_LINE> async def get(self): <NEW_LINE> <INDENT> user = self.get_current_session_user() <NEW_LINE> grp_rel = await UserGrpRel.objects.get(user=user) <NEW_LINE> if grp_rel is None: <NEW_LINE> <INDENT> res = dict( result=False ) <NEW_LINE> return get_std_json_response(data=jsontool.dumps(res)) <NEW_LINE> <DEDENT> if grp_rel.g_name == 'admin': <NEW_LINE> <INDENT> res = dict( result=True ) <NEW_LINE> return get_std_json_response(data=jsontool.dumps(res)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = dict( result=False ) <NEW_LINE> return get_std_json_response(data=jsontool.dumps(res))
是否是管理员
62598fcfff9c53063f51aa7a
class DataScope(Serializable): <NEW_LINE> <INDENT> def __init__(self, query=None, **kwargs): <NEW_LINE> <INDENT> self._query = None <NEW_LINE> self.query = query <NEW_LINE> <DEDENT> @property <NEW_LINE> def query(self): <NEW_LINE> <INDENT> return self._query <NEW_LINE> <DEDENT> @query.setter <NEW_LINE> def query(self, query): <NEW_LINE> <INDENT> self._query = self._get_object(DataQuery, query) <NEW_LINE> <DEDENT> @query.deleter <NEW_LINE> def query(self): <NEW_LINE> <INDENT> self._query = None
Query to against data.
62598fcf283ffb24f3cf3cb4
class BaseClassProperties(type): <NEW_LINE> <INDENT> @wraps(type.__init__) <NEW_LINE> def __init__(cls, *args, **kwargs): <NEW_LINE> <INDENT> from weakref import WeakSet <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> cls._instances = WeakSet() <NEW_LINE> <DEDENT> @property <NEW_LINE> def instances(cls): <NEW_LINE> <INDENT> return list(cls._instances)
Create a metaclass which has an instances property
62598fcf60cbc95b0636476c
class SSHHandler: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def connect(self, remote): <NEW_LINE> <INDENT> result_successful, result_message = True, '' <NEW_LINE> for host, username, password in [conn for conn in CONNECTION_LIST]: <NEW_LINE> <INDENT> if host == remote: <NEW_LINE> <INDENT> break; <NEW_LINE> <DEDENT> <DEDENT> for idx in range(CONNECTION_ATTEMPT_MAX): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logger.info('Connecting to {} - attempt #{}'.format(host, idx+1)) <NEW_LINE> self.ssh = paramiko.SSHClient() <NEW_LINE> self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) <NEW_LINE> self.ssh.connect(host, username=username, password=password) <NEW_LINE> <DEDENT> except paramiko.AuthenticationException: <NEW_LINE> <INDENT> result_message = 'Error: Authentication failed when connecting to {}'.format(host) <NEW_LINE> logger.error(result_message) <NEW_LINE> result_successful = False <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> result_message = 'Error: Could not connect to {} - {}'.format(host, e) <NEW_LINE> logger.error(result_message) <NEW_LINE> result_successful = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result_message = 'Successfully connected to {}'.format(host) <NEW_LINE> logger.info(result_message) <NEW_LINE> result_successful = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return (result_successful, result_message) <NEW_LINE> <DEDENT> def execute_cmd(self, cmd): <NEW_LINE> <INDENT> logger.info('Executing command: {}'.format(cmd)) <NEW_LINE> result_successful, result_message = True, '' <NEW_LINE> try: <NEW_LINE> <INDENT> stdin, stdout, stderr = self.ssh.exec_command(cmd) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> result_successful = False <NEW_LINE> result_message = str(e) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> err = stderr.read() <NEW_LINE> if (err): <NEW_LINE> <INDENT> result_successful = False <NEW_LINE> result_message = err <NEW_LINE> logger.info('Failed.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result_successful = True <NEW_LINE> result_message = stdout.read() <NEW_LINE> logger.info('Successful.') <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> stdin.close() <NEW_LINE> stderr.close() <NEW_LINE> stdout.close() <NEW_LINE> <DEDENT> return (result_successful, result_message) <NEW_LINE> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> if hasattr(self, 'ssh'): <NEW_LINE> <INDENT> self.ssh.close() <NEW_LINE> <DEDENT> logger.info('Disconnected')
Handle SSH connections and remote command executions.
62598fcf9f28863672818a94
class RPC_Server(rpc_common.RPCShellCommon): <NEW_LINE> <INDENT> NAME = 'Generic RPC Service' <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> rpc_common.RPCShellCommon.__init__(self, *args, **kwargs) <NEW_LINE> self.get_credentials() <NEW_LINE> self.get_connection() <NEW_LINE> self.get_channel() <NEW_LINE> self.get_logchannel() <NEW_LINE> self.loginfo(self.get_idstr()) <NEW_LINE> exchange = self.get_rpc_exchange() <NEW_LINE> if exchange is not '': <NEW_LINE> <INDENT> self.logdebug("Declaring exchange %s" % exchange) <NEW_LINE> <DEDENT> self.logdebug("Declaring queue %s" % self.get_queue_name()) <NEW_LINE> self.channel.queue_declare(queue=self.get_queue_name(), auto_delete=False) <NEW_LINE> if exchange is not '': <NEW_LINE> <INDENT> self.logdebug("Binding queue %s to exchange %s" % (self.get_queue_name(), exchange)) <NEW_LINE> self.channel.queue_bind(queue=self.get_queue_name(), exchange=self.get_rpc_exchange(), routing_key=self.get_queue_name()) <NEW_LINE> <DEDENT> <DEDENT> def server_log_response(self, response): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> fname = "%s-lastresponse.txt" % self.program <NEW_LINE> self.logdebug("Logging response to %s" % fname) <NEW_LINE> lastresp = open(fname, "w") <NEW_LINE> lastresp.write(self.responseobj.prettyprint() + '\n') <NEW_LINE> lastresp.close() <NEW_LINE> <DEDENT> <DEDENT> def logdebug(self, message): <NEW_LINE> <INDENT> rpc_common.RPCShellCommon.logdebug(self, message) <NEW_LINE> if self.logchannel is not None and self.debug: <NEW_LINE> <INDENT> self.server_log_bcast(message) <NEW_LINE> <DEDENT> <DEDENT> def loginfo(self, message): <NEW_LINE> <INDENT> rpc_common.RPCShellCommon.loginfo(self, message) <NEW_LINE> if self.logchannel is not None: <NEW_LINE> <INDENT> self.server_log_bcast(message) <NEW_LINE> <DEDENT> <DEDENT> def server_log_bcast(self, message): <NEW_LINE> <INDENT> logline = "%s: %s" % (self.get_uuid(), message) <NEW_LINE> self.logchannel.basic_publish(exchange=self.logexchange, routing_key='', body=logline) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.logdebug("Setting basic_qos, prefetch_count=1") <NEW_LINE> self.channel.basic_qos(prefetch_count=1) <NEW_LINE> self.logdebug("Basic_consume, callback on_request(), queue %s" % self.get_queue_name()) <NEW_LINE> self.channel.basic_consume(self.on_request, queue=self.get_queue_name()) <NEW_LINE> self.logdebug("Server waiting for RPC calls.") <NEW_LINE> self.channel.start_consuming()
RPC Server object to be extended by RPC servers.
62598fcfab23a570cc2d4f85
class AccountViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> lookup_field = 'username' <NEW_LINE> queryset = Account.objects.all() <NEW_LINE> serializer_class = AccountSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> user = self.request.user <NEW_LINE> return Account.objects.filter(id=user.id) <NEW_LINE> <DEDENT> def get_permissions(self): <NEW_LINE> <INDENT> if self.request.method == 'POST': <NEW_LINE> <INDENT> return (permissions.AllowAny(),) <NEW_LINE> <DEDENT> return (permissions.IsAuthenticated(), IsAccountOwner(),) <NEW_LINE> <DEDENT> def create(self, request): <NEW_LINE> <INDENT> serializer = self.serializer_class(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> Account.objects.create_user(**serializer.validated_data) <NEW_LINE> return Response(serializer.validated_data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response({ 'status': 'Bad request', 'message': 'Account could not be created with received data.', 'errors': json.dumps(serializer.errors) }, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def update(self, request, *args, **kwargs): <NEW_LINE> <INDENT> username = kwargs.get("username", None) <NEW_LINE> if username: <NEW_LINE> <INDENT> instance = Account.objects.get(username=username) <NEW_LINE> self.check_object_permissions(self.request, instance) <NEW_LINE> serializer = self.serializer_class(instance, data=request.data, partial=True) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> instance = serializer.save() <NEW_LINE> self.update_password_if_changed(instance, request, serializer) <NEW_LINE> self.update_admin_status(instance, serializer) <NEW_LINE> return Response(serializer.data, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> <DEDENT> return Response({ 'status': 'Bad request', 'message': 'Account could not be updated with received data.' }, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def update_admin_status(instance, serializer): <NEW_LINE> <INDENT> admin_password = serializer.validated_data.get('admin_password', None) <NEW_LINE> if admin_password == "remove": <NEW_LINE> <INDENT> Account.objects.make_account_not_admin(instance) <NEW_LINE> <DEDENT> if Account.check_admin_password(admin_password): <NEW_LINE> <INDENT> Account.objects.make_account_admin(instance) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def update_password_if_changed(instance, request, serializer): <NEW_LINE> <INDENT> password = serializer.validated_data.get('password', None) <NEW_LINE> confirm_password = serializer.validated_data.get('confirm_password', None) <NEW_LINE> if password and confirm_password and password == confirm_password: <NEW_LINE> <INDENT> instance.set_password(password) <NEW_LINE> instance.save() <NEW_LINE> <DEDENT> update_session_auth_hash(request, instance)
Primary controller for all REST actions on our Account model (i.e. out primary user model) Automatically provides GET/POST/PUT/DELETE, though we override POST and PUT with custom behavior.
62598fcffbf16365ca7944ec
class ResetMixin(object): <NEW_LINE> <INDENT> def reset(self): <NEW_LINE> <INDENT> instdict = self.__dict__ <NEW_LINE> classdict = self.__class__.__dict__ <NEW_LINE> for mname, mval in classdict.items(): <NEW_LINE> <INDENT> if mname in instdict and isinstance(mval, OneTimeProperty): <NEW_LINE> <INDENT> delattr(self, mname)
A Mixin class to add a .reset() method to users of OneTimeProperty. By default, auto attributes once computed, become static. If they happen to depend on other parts of an object and those parts change, their values may now be invalid. This class offers a .reset() method that users can call *explicitly* when they know the state of their objects may have changed and they want to ensure that *all* their special attributes should be invalidated. Once reset() is called, all their auto attributes are reset to their OneTimeProperty descriptors, and their accessor functions will be triggered again. .. warning:: If a class has a set of attributes that are OneTimeProperty, but that can be initialized from any one of them, do NOT use this mixin! For instance, UniformTimeSeries can be initialized with only sampling_rate and t0, sampling_interval and time are auto-computed. But if you were to reset() a UniformTimeSeries, it would lose all 4, and there would be then no way to break the circular dependency chains. If this becomes a problem in practice (for our analyzer objects it isn't, as they don't have the above pattern), we can extend reset() to check for a _no_reset set of names in the instance which are meant to be kept protected. But for now this is NOT done, so caveat emptor. Examples -------- >>> class A(ResetMixin): ... def __init__(self,x=1.0): ... self.x = x ... ... @auto_attr ... def y(self): ... print('*** y computation executed ***') ... return self.x / 2.0 ... >>> a = A(10) About to access y twice, the second time no computation is done: >>> a.y *** y computation executed *** 5.0 >>> a.y 5.0 Changing x >>> a.x = 20 a.y doesn't change to 10, since it is a static attribute: >>> a.y 5.0 We now reset a, and this will then force all auto attributes to recompute the next time we access them: >>> a.reset() About to access y twice again after reset(): >>> a.y *** y computation executed *** 10.0 >>> a.y 10.0
62598fcf091ae3566870505b
class ThrottlingMiddleware(BaseMiddleware): <NEW_LINE> <INDENT> def __init__(self, limit=DEFAULT_RATE_LIMIT, key_prefix='antiflood_'): <NEW_LINE> <INDENT> self.rate_limit = limit <NEW_LINE> self.prefix = key_prefix <NEW_LINE> super(ThrottlingMiddleware, self).__init__() <NEW_LINE> <DEDENT> async def on_process_message(self, message: types.Message, data: dict): <NEW_LINE> <INDENT> handler = current_handler.get() <NEW_LINE> dispatcher = Dispatcher.get_current() <NEW_LINE> if handler: <NEW_LINE> <INDENT> limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) <NEW_LINE> key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> limit = self.rate_limit <NEW_LINE> key = f"{self.prefix}_message" <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> await dispatcher.throttle(key, rate=limit) <NEW_LINE> <DEDENT> except Throttled as t: <NEW_LINE> <INDENT> await self.message_throttled(message, t) <NEW_LINE> raise CancelHandler() <NEW_LINE> <DEDENT> <DEDENT> async def message_throttled(self, message: types.Message, throttled: Throttled): <NEW_LINE> <INDENT> handler = current_handler.get() <NEW_LINE> dispatcher = Dispatcher.get_current() <NEW_LINE> if handler: <NEW_LINE> <INDENT> key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> key = f"{self.prefix}_message" <NEW_LINE> <DEDENT> delta = throttled.rate - throttled.delta <NEW_LINE> if throttled.exceeded_count <= 2: <NEW_LINE> <INDENT> await message.reply('Вы не можете посылать больше одного запроса в секунду!') <NEW_LINE> <DEDENT> await asyncio.sleep(delta) <NEW_LINE> thr = await dispatcher.check_key(key) <NEW_LINE> if thr.exceeded_count == throttled.exceeded_count: <NEW_LINE> <INDENT> await message.reply('Unlocked.')
Simple middleware
62598fcfbf627c535bcb18dd
class Polynomial(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.terms = {} <NEW_LINE> <DEDENT> def add_term(self, term): <NEW_LINE> <INDENT> key = term.as_tuple() <NEW_LINE> if key in self.terms: <NEW_LINE> <INDENT> self.terms[key].koeff += term.koeff <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.terms[key] = term <NEW_LINE> <DEDENT> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> polynom = Polynomial() <NEW_LINE> polynom.terms = self.terms.copy() <NEW_LINE> for key in other.terms: <NEW_LINE> <INDENT> if key in polynom.terms: <NEW_LINE> <INDENT> polynom.terms[key].koeff += other.terms[key].koeff <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> polynom.terms[key] = other.terms[key] <NEW_LINE> <DEDENT> <DEDENT> polynom._canon() <NEW_LINE> return polynom <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> polynom = Polynomial() <NEW_LINE> polynom.terms = self.terms.copy() <NEW_LINE> for key in other.terms: <NEW_LINE> <INDENT> if key in polynom.terms: <NEW_LINE> <INDENT> polynom.terms[key].koeff -= other.terms[key].koeff <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> polynom.terms[key] = -other.terms[key] <NEW_LINE> <DEDENT> <DEDENT> polynom._canon() <NEW_LINE> return polynom <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> polynom = Polynomial() <NEW_LINE> for other_key in other.terms: <NEW_LINE> <INDENT> for self_key in self.terms: <NEW_LINE> <INDENT> term = self.terms[self_key] * other.terms[other_key] <NEW_LINE> polynom.add_term(term) <NEW_LINE> <DEDENT> <DEDENT> polynom._canon() <NEW_LINE> return polynom <NEW_LINE> <DEDENT> def __neg__(self): <NEW_LINE> <INDENT> polynom = Polynomial() <NEW_LINE> for key in self.terms: <NEW_LINE> <INDENT> term = -self.terms[key] <NEW_LINE> polynom.terms[term.as_tuple()] = term <NEW_LINE> <DEDENT> return polynom <NEW_LINE> <DEDENT> def _canon(self): <NEW_LINE> <INDENT> terms = {key: term for key, term in self.terms.items() if term.koeff != 0.0} <NEW_LINE> self.terms = terms <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> self._canon() <NEW_LINE> terms = [] <NEW_LINE> for key in sorted(self.terms): <NEW_LINE> <INDENT> terms.append(str(self.terms[key])) <NEW_LINE> <DEDENT> s = '' <NEW_LINE> for term in filter(None, terms): <NEW_LINE> <INDENT> if s: <NEW_LINE> <INDENT> if term[0] == '-': <NEW_LINE> <INDENT> s += term <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s += '+' + term <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> s += term <NEW_LINE> <DEDENT> <DEDENT> if s: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '0'
Реализует выражение вида 3x^2y+5zy^3
62598fcf8a349b6b43686671
class FileStorageSettings(Settings): <NEW_LINE> <INDENT> _IMPL_TYPE: ClassVar[str] = "implementation" <NEW_LINE> _KEY: ClassVar[str] = "file_storage" <NEW_LINE> @property <NEW_LINE> def impl_type(self) -> ImplementationType: <NEW_LINE> <INDENT> return self._impl_type <NEW_LINE> <DEDENT> @impl_type.setter <NEW_LINE> def impl_type(self, value: ImplementationType): <NEW_LINE> <INDENT> self._impl_type = value <NEW_LINE> <DEDENT> def _parse_data(self, data: Dict[str, Any]): <NEW_LINE> <INDENT> super()._parse_data(data) <NEW_LINE> self.impl_type = ImplementationType.parse(super().get_setting_from_key( setting_key=f"{FileStorageSettings._KEY}.{FileStorageSettings._IMPL_TYPE}", settings=data, default=ImplementationType.DEFAULT.value))
specialized file storage settings class
62598fcf50812a4eaa620dfc
class EditProfileAdminForm(FlaskForm): <NEW_LINE> <INDENT> email = StringField('Email', validators=[DataRequired(), Length(1, 64), Email()]) <NEW_LINE> username = StringField('Username', validators=[DataRequired(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, 'Usernames must have only letters, ' 'numbers, dots or underscores')]) <NEW_LINE> confirmed = BooleanField('Confirmed') <NEW_LINE> role = SelectField('Role', coerce=int) <NEW_LINE> name = StringField('Real name', validators=[Length(0, 64)]) <NEW_LINE> location = StringField('Location', validators=[Length(0, 64)]) <NEW_LINE> about_me = TextAreaField('About me') <NEW_LINE> submit = SubmitField('Submit') <NEW_LINE> def __init__(self, user, *args, **kwargs): <NEW_LINE> <INDENT> super(EditProfileAdminForm, self).__init__(*args, **kwargs) <NEW_LINE> self.role.choices = [(role.id, role.name) for role in Role.query.order_by(Role.name).all()] <NEW_LINE> self.user = user <NEW_LINE> <DEDENT> def validate_email(self, field): <NEW_LINE> <INDENT> if field.data != self.user.email and User.query.filter_by(email=field.data).first(): <NEW_LINE> <INDENT> raise ValidationError('Email already registered.') <NEW_LINE> <DEDENT> <DEDENT> def validate_username(self, field): <NEW_LINE> <INDENT> if field.data != self.user.username and User.query.filter_by(username=field.data).first(): <NEW_LINE> <INDENT> raise ValidationError('Username already in use.')
管理员编辑用户资料的表单
62598fcf7cff6e4e811b5e58
class ISEOFieldsMarker(Interface): <NEW_LINE> <INDENT> pass
Marker interface that will be provided by instances using the ISeoFields behavior.
62598fcf5fdd1c0f98e5e3be
class MinimaxAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> def MinMax(gameState , depth , AgentIndex ): <NEW_LINE> <INDENT> if gameState.isWin() or gameState.isLose() or depth==0: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> if AgentIndex == 0: <NEW_LINE> <INDENT> return max( [-float("inf")] + [MinMax(gameState.generateSuccessor(AgentIndex, action) ,depth ,AgentIndex + 1 ) for action in gameState.getLegalActions(AgentIndex)] ) <NEW_LINE> <DEDENT> elif AgentIndex == gameState.getNumAgents()-1: <NEW_LINE> <INDENT> return min( [float("inf")] + [MinMax(gameState.generateSuccessor(AgentIndex, action) ,depth - 1 , 0 ) for action in gameState.getLegalActions(AgentIndex)] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return min( [float("inf")] + [MinMax(gameState.generateSuccessor(AgentIndex, action) ,depth , AgentIndex + 1 ) for action in gameState.getLegalActions(AgentIndex)] ) <NEW_LINE> <DEDENT> <DEDENT> legalMoves = gameState.getLegalActions() <NEW_LINE> scores = [MinMax(gameState.generateSuccessor(0,action) , self.depth , 1) for action in legalMoves] <NEW_LINE> bestScore = max(scores) <NEW_LINE> bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] <NEW_LINE> if not bestIndices: return Directions.STOP <NEW_LINE> chosenIndex = random.choice(bestIndices) <NEW_LINE> return legalMoves[chosenIndex]
Your minimax agent (question 2)
62598fcf5fcc89381b266365
class allow_http(object): <NEW_LINE> <INDENT> def __init__(self, *methods): <NEW_LINE> <INDENT> self.methods = methods <NEW_LINE> <DEDENT> def __call__(self, func): <NEW_LINE> <INDENT> def inner(request, *args, **kwargs): <NEW_LINE> <INDENT> if request.method not in self.methods: <NEW_LINE> <INDENT> return HttpResponseNotAllowed(self.methods) <NEW_LINE> <DEDENT> return func(request, *args, **kwargs) <NEW_LINE> <DEDENT> inner.__name__ = func.__name__ <NEW_LINE> return inner
use like @allow_http("GET", "POST") def my_view_handler(request, ...): ...
62598fcf4c3428357761a6f0
class SQLType: <NEW_LINE> <INDENT> TYPE_MAP = { int: "INTEGER", float: "REAL", str: "TEXT", } <NEW_LINE> def __init__(self, type_constructor, *, sql_type=None, not_null=False): <NEW_LINE> <INDENT> self.type_constructor = type_constructor <NEW_LINE> self._sql_type = ( sql_type if sql_type is not None else SQLType.TYPE_MAP[type_constructor] ) <NEW_LINE> self.not_null = not_null <NEW_LINE> <DEDENT> def __call__(self, value): <NEW_LINE> <INDENT> return self.type_constructor(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def sql_type(self): <NEW_LINE> <INDENT> if self.not_null: <NEW_LINE> <INDENT> return f"{self._sql_type} NOT NULL".lstrip() <NEW_LINE> <DEDENT> return self._sql_type.lstrip()
Base class for custom sqlite schema types.
62598fcf3d592f4c4edbb2e7
class FTPService(IngestService): <NEW_LINE> <INDENT> DATE_FORMAT = '%Y%m%d%H%M%S' <NEW_LINE> FILE_SUFFIX = '.xml' <NEW_LINE> def config_from_url(self, url): <NEW_LINE> <INDENT> url_parts = urlparse(url) <NEW_LINE> return { 'username': url_parts.username, 'password': url_parts.password, 'host': url_parts.hostname, 'path': url_parts.path.lstrip('/'), } <NEW_LINE> <DEDENT> def _get_items(self, ftp): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return ftp.mlsd() <NEW_LINE> <DEDENT> except (ftplib.error_proto): <NEW_LINE> <INDENT> ftp.set_pasv(False) <NEW_LINE> return ftp.mlsd() <NEW_LINE> <DEDENT> <DEDENT> def _update(self, provider): <NEW_LINE> <INDENT> config = provider.get('config', {}) <NEW_LINE> last_updated = provider.get('last_updated') <NEW_LINE> if 'dest_path' not in config: <NEW_LINE> <INDENT> config['dest_path'] = tempfile.mkdtemp(prefix='superdesk_ingest_') <NEW_LINE> <DEDENT> items = [] <NEW_LINE> try: <NEW_LINE> <INDENT> with ftplib.FTP(config.get('host')) as ftp: <NEW_LINE> <INDENT> ftp.login(config.get('username'), config.get('password')) <NEW_LINE> ftp.cwd(config.get('path', '')) <NEW_LINE> items = self._get_items(ftp) <NEW_LINE> for filename, facts in items: <NEW_LINE> <INDENT> if facts.get('type', '') != 'file': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not filename.lower().endswith(self.FILE_SUFFIX): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if last_updated: <NEW_LINE> <INDENT> item_last_updated = datetime.strptime(facts['modify'], self.DATE_FORMAT).replace(tzinfo=utc) <NEW_LINE> if item_last_updated < last_updated: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> dest = os.path.join(config['dest_path'], filename) <NEW_LINE> try: <NEW_LINE> <INDENT> with open(dest, 'xb') as f: <NEW_LINE> <INDENT> ftp.retrbinary('RETR %s' % filename, f.write) <NEW_LINE> <DEDENT> <DEDENT> except FileExistsError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> xml = etree.parse(dest).getroot() <NEW_LINE> parser = get_xml_parser(xml) <NEW_LINE> if not parser: <NEW_LINE> <INDENT> raise IngestFtpError.ftpUnknownParserError(Exception('Parser not found'), provider, filename) <NEW_LINE> <DEDENT> items.append(parser.parse_message(xml, provider)) <NEW_LINE> <DEDENT> <DEDENT> return items <NEW_LINE> <DEDENT> except IngestFtpError: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> raise IngestFtpError.ftpError(ex, provider)
FTP Ingest Service.
62598fcf3346ee7daa337860
class Function(): <NEW_LINE> <INDENT> def __init__(self, ret_val, function, body, doxygen=None, static=False, explicit=False, virtual=False, split=True): <NEW_LINE> <INDENT> self.ret_val = ret_val <NEW_LINE> self.function = function <NEW_LINE> self.body = body <NEW_LINE> self.doxygen = doxygen <NEW_LINE> self.static = "static " if static else "" <NEW_LINE> self.explicit = "explicit " if explicit else "" <NEW_LINE> self.virtual = "virtual " if virtual else "" <NEW_LINE> self.split_implementation = split <NEW_LINE> <DEDENT> def declaration(self): <NEW_LINE> <INDENT> if self.ret_val: <NEW_LINE> <INDENT> return "{0}{1} {2} {{ {3} }}".format( self.static, self.ret_val, self.function, self.body ) <NEW_LINE> <DEDENT> return "{0}{1}{2} {3}".format( self.virtual, self.explicit, self.function, self.body ) <NEW_LINE> <DEDENT> def definition(self): <NEW_LINE> <INDENT> if self.ret_val: <NEW_LINE> <INDENT> return "{0}{1} {2};".format( self.static, self.ret_val, self.function, self.body ) <NEW_LINE> <DEDENT> return "{0}{1}{2};".format( self.virtual, self.explicit, self.function ) <NEW_LINE> <DEDENT> def write_declaration(self, file): <NEW_LINE> <INDENT> if self.doxygen: <NEW_LINE> <INDENT> next_line_indent(file) <NEW_LINE> file.write(self.doxygen.to_string()) <NEW_LINE> <DEDENT> if self.split_implementation: <NEW_LINE> <INDENT> next_line_indent(file) <NEW_LINE> file.write(self.definition()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> next_line_indent(file) <NEW_LINE> file.write(self.declaration()) <NEW_LINE> <DEDENT> <DEDENT> def write_implementation(self, file, classname=None, extra_op = ""): <NEW_LINE> <INDENT> if not self.split_implementation: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> has_final = re.compile(r" final$").match(self.function) <NEW_LINE> impl_function = re.sub(r" final$", "", self.function) <NEW_LINE> impl_function = re.sub(r" = [0-9\.f]+ ", " ", impl_function) <NEW_LINE> next_line(file) <NEW_LINE> if self.ret_val: <NEW_LINE> <INDENT> add_before_inline = "" <NEW_LINE> add_after_inline = "" <NEW_LINE> if inline_implementation: <NEW_LINE> <INDENT> add_before_inline = "inline " if not (self.ret_val.startswith("template<>") or has_final) else "" <NEW_LINE> add_after_inline = "inline " if self.ret_val.startswith("template<>") and not (has_final) else "" <NEW_LINE> <DEDENT> file.write('{0}{1} {2}{3}{4}\n{{'.format(add_before_inline, self.ret_val, add_after_inline, (classname + '::') if classname else '', impl_function)) <NEW_LINE> next_line_indent(file) <NEW_LINE> file.write(self.body) <NEW_LINE> if extra_op: <NEW_LINE> <INDENT> next_line_indent(file) <NEW_LINE> file.write(extra_op) <NEW_LINE> <DEDENT> next_line(file) <NEW_LINE> file.write('}') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> add_inline = "" <NEW_LINE> if inline_implementation: <NEW_LINE> <INDENT> add_inline = "inline " <NEW_LINE> <DEDENT> file.write('{0}{1}{2}'.format(add_inline, (classname + '::') if classname else '', impl_function)) <NEW_LINE> next_line_indent(file) <NEW_LINE> file.write(self.body) <NEW_LINE> <DEDENT> next_line(file)
A C++ Function
62598fcf656771135c489aa4
class NipapAuthError(NipapError): <NEW_LINE> <INDENT> pass
General NIPAP AAA error
62598fcfd8ef3951e32c8075
class tm_get_ppg_usage_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.STRUCT, 'success', (tm_ppg_usage_t, tm_ppg_usage_t.thrift_spec), None, ), (1, TType.STRUCT, 'ouch', (InvalidTmOperation, InvalidTmOperation.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, ouch=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.ouch = ouch <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 == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = tm_ppg_usage_t() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ouch = InvalidTmOperation() <NEW_LINE> self.ouch.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('tm_get_ppg_usage_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ouch is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ouch', TType.STRUCT, 1) <NEW_LINE> self.ouch.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.success) <NEW_LINE> value = (value * 31) ^ hash(self.ouch) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success - ouch
62598fcfad47b63b2c5a7c8e
class VirtualMachineIdentity(Model): <NEW_LINE> <INDENT> _validation = { 'principal_id': {'readonly': True}, 'tenant_id': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'principal_id': {'key': 'principalId', 'type': 'str'}, 'tenant_id': {'key': 'tenantId', 'type': 'str'}, 'type': {'key': 'type', 'type': 'ResourceIdentityType'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(VirtualMachineIdentity, self).__init__(**kwargs) <NEW_LINE> self.principal_id = None <NEW_LINE> self.tenant_id = None <NEW_LINE> self.type = kwargs.get('type', None)
Identity for the virtual machine. Variables are only populated by the server, and will be ignored when sending a request. :ivar principal_id: The principal id of virtual machine identity. :vartype principal_id: str :ivar tenant_id: The tenant id associated with the virtual machine. :vartype tenant_id: str :param type: The type of identity used for the virtual machine. Currently, the only supported type is 'SystemAssigned', which implicitly creates an identity. Possible values include: 'SystemAssigned' :type type: str or ~azure.mgmt.compute.v2017_03_30.models.ResourceIdentityType
62598fcf4c3428357761a6f2
class Reddit(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.posts = TTLOrderedDict(default_ttl=TTL) <NEW_LINE> self.notifications = [] <NEW_LINE> self.logger = Logger() <NEW_LINE> <DEDENT> def fetch_latest_posts(self): <NEW_LINE> <INDENT> self.notifications = [] <NEW_LINE> self.logger.log.info('Fetching nba front page') <NEW_LINE> nba_front_page = requests.get(URL, headers = {'User-agent' : 'irnba 0.0.1'}) <NEW_LINE> posts = [] <NEW_LINE> keys = ['title', 'id', 'ups', 'permalink'] <NEW_LINE> try: <NEW_LINE> <INDENT> posts = nba_front_page.json()['data']['children'] <NEW_LINE> <DEDENT> except KeyError as exception: <NEW_LINE> <INDENT> self.logger.log.error('Key error on {0}'.format(exception.message)) <NEW_LINE> <DEDENT> except Exception as general_exception: <NEW_LINE> <INDENT> self.logger.log.error('Exception on {0}'.format(general_exception.message)) <NEW_LINE> <DEDENT> for p in posts: <NEW_LINE> <INDENT> post = p.get('data', {}) <NEW_LINE> id = post.get('id', None) <NEW_LINE> if not id: <NEW_LINE> <INDENT> self.logger.log.info('Post with no id found: {0}'.format(json.dumps(post))) <NEW_LINE> continue <NEW_LINE> <DEDENT> if not id in self.posts: <NEW_LINE> <INDENT> self.posts[id] = {key: post.get(key, '') for key in keys} <NEW_LINE> <DEDENT> self.notifications.append( self.is_post_getting_hot(self.posts[id], id) ) <NEW_LINE> <DEDENT> <DEDENT> def is_post_getting_hot(self, post, id): <NEW_LINE> <INDENT> upvotes = post.get('ups', 0) <NEW_LINE> if upvotes > UPVOTE_THRESHOLD and not self.posts[id].get('marked', False): <NEW_LINE> <INDENT> title = post.get('title', '') <NEW_LINE> link = post.get('permalink', '') <NEW_LINE> self.posts[id]['marked'] = True <NEW_LINE> return {'title': title, 'link': BASE_URL + link} <NEW_LINE> <DEDENT> return None
Class to define reddit instance
62598fcf091ae3566870505f
class Day03Tests(unittest.TestCase): <NEW_LINE> <INDENT> def test_solve_part_one_solves_the_puzzle_correctly(self): <NEW_LINE> <INDENT> data = [ "#1 @ 1,3: 4x4", "#2 @ 3,1: 4x4", "#3 @ 5,5: 2x2", ] <NEW_LINE> day = Day03(data) <NEW_LINE> self.assertEqual(day.solve_part_one(), 4) <NEW_LINE> <DEDENT> def test_solve_part_two_solves_the_puzzle_correctly(self): <NEW_LINE> <INDENT> data = [ "#1 @ 1,3: 4x4", "#2 @ 3,1: 4x4", "#3 @ 5,5: 2x2", ] <NEW_LINE> day = Day03(data) <NEW_LINE> day.solve_part_one() <NEW_LINE> self.assertEqual(day.solve_part_two(), 3)
Tests for `Day03`.
62598fcf71ff763f4b5e7bb6
class itkImageCVF22(itkImageBase2): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> ImageDimension = _itkImagePython.itkImageCVF22_ImageDimension <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def SetRegions(self, *args): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_SetRegions(self, *args) <NEW_LINE> <DEDENT> def FillBuffer(self, *args): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_FillBuffer(self, *args) <NEW_LINE> <DEDENT> def SetPixel(self, *args): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_SetPixel(self, *args) <NEW_LINE> <DEDENT> def GetPixel(self, *args): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_GetPixel(self, *args) <NEW_LINE> <DEDENT> def GetBufferPointer(self, *args): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_GetBufferPointer(self, *args) <NEW_LINE> <DEDENT> def GetPixelContainer(self, *args): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_GetPixelContainer(self, *args) <NEW_LINE> <DEDENT> def SetPixelContainer(self, *args): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_SetPixelContainer(self, *args) <NEW_LINE> <DEDENT> def GetPixelAccessor(self, *args): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_GetPixelAccessor(self, *args) <NEW_LINE> <DEDENT> def GetNeighborhoodAccessor(self, *args): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_GetNeighborhoodAccessor(self, *args) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkImagePython.delete_itkImageCVF22 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkImagePython.itkImageCVF22_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkImageCVF22.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
Proxy of C++ itkImageCVF22 class
62598fcf3d592f4c4edbb2e9
class EvalMetric(object): <NEW_LINE> <INDENT> def __init__(self, name, output_names=None, label_names=None, **kwargs): <NEW_LINE> <INDENT> super(EvalMetric, self).__init__() <NEW_LINE> self.name = str(name) <NEW_LINE> self.output_names = output_names <NEW_LINE> self.label_names = label_names <NEW_LINE> self._has_global_stats = kwargs.pop("has_global_stats", False) <NEW_LINE> self._kwargs = kwargs <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "EvalMetric: {}".format(dict(self.get_name_value())) <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = self._kwargs.copy() <NEW_LINE> config.update({ "metric": self.__class__.__name__, "name": self.name, "output_names": self.output_names, "label_names": self.label_names}) <NEW_LINE> return config <NEW_LINE> <DEDENT> def update_dict(self, label, pred): <NEW_LINE> <INDENT> if self.output_names is not None: <NEW_LINE> <INDENT> pred = [pred[name] for name in self.output_names] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pred = list(pred.values()) <NEW_LINE> <DEDENT> if self.label_names is not None: <NEW_LINE> <INDENT> label = [label[name] for name in self.label_names] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> label = list(label.values()) <NEW_LINE> <DEDENT> self.update(label, pred) <NEW_LINE> <DEDENT> def update(self, labels, preds): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.num_inst = 0 <NEW_LINE> self.sum_metric = 0.0 <NEW_LINE> self.global_num_inst = 0 <NEW_LINE> self.global_sum_metric = 0.0 <NEW_LINE> <DEDENT> def reset_local(self): <NEW_LINE> <INDENT> self.num_inst = 0 <NEW_LINE> self.sum_metric = 0.0 <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> if self.num_inst == 0: <NEW_LINE> <INDENT> return self.name, float("nan") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.name, self.sum_metric / self.num_inst <NEW_LINE> <DEDENT> <DEDENT> def get_global(self): <NEW_LINE> <INDENT> if self._has_global_stats: <NEW_LINE> <INDENT> if self.global_num_inst == 0: <NEW_LINE> <INDENT> return self.name, float("nan") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.name, self.global_sum_metric / self.global_num_inst <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return self.get() <NEW_LINE> <DEDENT> <DEDENT> def get_name_value(self): <NEW_LINE> <INDENT> name, value = self.get() <NEW_LINE> if not isinstance(name, list): <NEW_LINE> <INDENT> name = [name] <NEW_LINE> <DEDENT> if not isinstance(value, list): <NEW_LINE> <INDENT> value = [value] <NEW_LINE> <DEDENT> return list(zip(name, value)) <NEW_LINE> <DEDENT> def get_global_name_value(self): <NEW_LINE> <INDENT> if self._has_global_stats: <NEW_LINE> <INDENT> name, value = self.get_global() <NEW_LINE> if not isinstance(name, list): <NEW_LINE> <INDENT> name = [name] <NEW_LINE> <DEDENT> if not isinstance(value, list): <NEW_LINE> <INDENT> value = [value] <NEW_LINE> <DEDENT> return list(zip(name, value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.get_name_value()
Base class for all evaluation metrics. Parameters: ---------- name : str Name of this metric instance for display. output_names : list of str, or None, default None Name of predictions that should be used when updating with update_dict. By default include all predictions. label_names : list of str, or None, default None Name of labels that should be used when updating with update_dict. By default include all labels.
62598fcfd8ef3951e32c8076
class ListAddable(ListArgs): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def add(self, list_or_not): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.extend(list_or_not) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self.append(list_or_not) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def radd(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self[:0] = other <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self.insert(0, other) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return self.__class__(self).add(other) <NEW_LINE> <DEDENT> def __radd__(self, other): <NEW_LINE> <INDENT> return self.__class__(self).radd(other) <NEW_LINE> <DEDENT> def __iadd__(self, other): <NEW_LINE> <INDENT> return self.add(other)
list addable (add(+) = extend or append)
62598fcffbf16365ca7944f2
class DynamicCollectionAdapter(object): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.data) <NEW_LINE> <DEDENT> def _reset_empty(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.data) <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> __nonzero__ = __bool__
simplified CollectionAdapter for internal API consistency
62598fcf4527f215b58ea304
class PrivateTagsApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = get_user_model().objects.create_user( 'test@londonappdev.com', 'password' ) <NEW_LINE> self.client = APIClient() <NEW_LINE> self.client.force_authenticate(self.user) <NEW_LINE> <DEDENT> def test_retrieve_tags(self): <NEW_LINE> <INDENT> Tag.objects.create(user=self.user, name='Vegan') <NEW_LINE> Tag.objects.create(user=self.user, name='Dessert') <NEW_LINE> res = self.client.get(TAGS_URL) <NEW_LINE> tags = Tag.objects.all().order_by('-name') <NEW_LINE> serializer = TagSerializer(tags, many=True) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, serializer.data) <NEW_LINE> <DEDENT> def test_tags_limited_to_user(self): <NEW_LINE> <INDENT> user2 = get_user_model().objects.create_user( 'other@londonappdev.com', 'testpass' ) <NEW_LINE> Tag.objects.create(user=user2, name='Fruity') <NEW_LINE> tag = Tag.objects.create(user=self.user, name='Comfort Food') <NEW_LINE> res = self.client.get(TAGS_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(len(res.data), 1) <NEW_LINE> self.assertEqual(res.data[0]['name'], tag.name) <NEW_LINE> <DEDENT> def test_create_tag_successful(self): <NEW_LINE> <INDENT> payload = {'name': 'Simple'} <NEW_LINE> self.client.post(TAGS_URL, payload) <NEW_LINE> exists = Tag.objects.filter( user=self.user, name=payload['name'] ).exists() <NEW_LINE> self.assertTrue(exists) <NEW_LINE> <DEDENT> def test_create_tag_invalid(self): <NEW_LINE> <INDENT> payload = {'name': ''} <NEW_LINE> res = self.client.post(TAGS_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
Test the authorized user tags API
62598fcf50812a4eaa620dff
class GetInputMock(mock.Mock): <NEW_LINE> <INDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> print(args[0], end='') <NEW_LINE> <DEDENT> return_value = super().__call__(*args, **kwargs) <NEW_LINE> print(return_value) <NEW_LINE> return return_value
A mock get_input object. This object is meant to mock the :func:`plugins.utils.get_input` function. On top of returning the value you want it to return, it also prints the first argument it was called with followed by the return value. As can be seen in the example below, this replicates the printing behavior of the :func:`plugins.utils.get_input` function instead of merely returning the assigned return value. The sole reason this behavior is desired is to make the automatic challenge execution tests print the same output as when executing the challenges normally (also see the example runs on the challenge documentation pages). Example:: >>> from plugins.utils import get_input >>> result = get_input("Input request > ") ## Here the user has to type the response himself. Input request > answer >>> print(result) answer >>> from mock import Mock >>> get_input = Mock(return_value='answer') >>> result = get_input("Input request > ") ## Nothing is printed when calling this mock object. >>> print(result) answer >>> from tests.test_challenge_execution import GetInputMock >>> get_input = GetInputMock(return_value='answer') >>> result = get_input("Input request > ") ## When calling this mock object, the printing behavior of 'get_input' is replicated. Input request > answer >>> print(result) answer
62598fcf60cbc95b06364774
class PublicRecipeApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> <DEDENT> def test_auth_required(self): <NEW_LINE> <INDENT> res = self.client.get(RECIPES_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
Test unauthotenticated recipe API access
62598fcfec188e330fdf8ccd
class JSONResponseError(BotoServerError): <NEW_LINE> <INDENT> def __init__(self, status, reason, body=None, *args): <NEW_LINE> <INDENT> self.status = status <NEW_LINE> self.reason = reason <NEW_LINE> self.body = body <NEW_LINE> if self.body: <NEW_LINE> <INDENT> self.error_message = self.body.get('message', None) <NEW_LINE> self.error_code = get_error_name(self.body.get('__type', None))
This exception expects the fully parsed and decoded JSON response body to be passed as the body parameter. :ivar status: The HTTP status code. :ivar reason: The HTTP reason message. :ivar body: The Python dict that represents the decoded JSON response body. :ivar error_message: The full description of the AWS error encountered. :ivar error_code: A short string that identifies the AWS error (e.g. ConditionalCheckFailedException)
62598fcfa219f33f346c6c3d
class CustomFeaturedEntry(FeaturedEntry): <NEW_LINE> <INDENT> featured_short_title = models.CharField( _('short name'), max_length=50, blank=True, null=True, help_text=_('short title for featured entry.')) <NEW_LINE> featured_short_comment = models.CharField( _('short comment'), max_length=150, blank=True, null=True, help_text=_('short comment for featured entry.')) <NEW_LINE> featured_date = models.DateTimeField( _('last update'), default=timezone.now) <NEW_LINE> featured_image = FileBrowseField("Image", max_length=200, directory='featured_image', extensions=['.jpg','.jpeg','.gif','.png'], blank=True, null=True, help_text=_('Used for illustration. image size : 300 x 200')) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True
Abstract model class to mark entries as featured.
62598fcf4527f215b58ea306
class ContactForm(ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Contact <NEW_LINE> widgets = { 'description': Textarea(attrs={'cols': 23, 'rows': 3}), } <NEW_LINE> <DEDENT> def __init__(self, user, *args, **kwargs): <NEW_LINE> <INDENT> super(ContactForm, self).__init__(*args, **kwargs) <NEW_LINE> self.helper = FormHelper() <NEW_LINE> if self.instance.id: <NEW_LINE> <INDENT> form_action = common_submit_buttons(default_action='update') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> form_action = common_submit_buttons(default_action='add') <NEW_LINE> <DEDENT> css_class = 'col-md-6' <NEW_LINE> self.helper.layout = Layout( TabHolder( Tab(_('general').capitalize(), Div( Div('phonebook', css_class=css_class), Div('contact', css_class=css_class), Div('last_name', css_class=css_class), Div('first_name', css_class=css_class), Div('status', css_class=css_class), Div('email', css_class=css_class), css_class='row' ), form_action, css_class='well' ), Tab(_('advanced data').capitalize(), Div( Div('unit_number', css_class=css_class), Div('address', css_class=css_class), Div('city', css_class=css_class), Div('state', css_class=css_class), Div('country', css_class=css_class), Div('description', css_class=css_class), Div('additional_vars', css_class=css_class), css_class='row' ), form_action, css_class='well' ), ), ) <NEW_LINE> if user: <NEW_LINE> <INDENT> self.fields['phonebook'].choices = phonebook_list(user)
Contact ModelForm
62598fcf099cdd3c636755fb
@internationalizeDocstring <NEW_LINE> class Sudo(callbacks.Plugin): <NEW_LINE> <INDENT> def __init__(self, irc): <NEW_LINE> <INDENT> callbacks.Plugin.__init__(self, irc) <NEW_LINE> self.db = SudoDB() <NEW_LINE> self._path = os.path.join(conf.supybot.directories.data(), 'sudo.db') <NEW_LINE> if not world.testing and os.path.isfile(self._path): <NEW_LINE> <INDENT> self.db.load(open(self._path, 'r')) <NEW_LINE> <DEDENT> <DEDENT> @internationalizeDocstring <NEW_LINE> def add(self, irc, msg, args, priority, name, mode, hostmask, regexp): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if mode == 'deny' and hostmask is not None: <NEW_LINE> <INDENT> irc.error(_('You don\'t have to give a hostmask when setting ' 'a "deny" rule.')) <NEW_LINE> return <NEW_LINE> <DEDENT> if hostmask is None: <NEW_LINE> <INDENT> hostmask = msg.prefix <NEW_LINE> <DEDENT> if priority is None: <NEW_LINE> <INDENT> priority = 0 <NEW_LINE> <DEDENT> self.db.add(name, SudoRule(priority, mode, hostmask, regexp)) <NEW_LINE> <DEDENT> except DuplicatedName: <NEW_LINE> <INDENT> irc.error(_('This name already exists')) <NEW_LINE> return <NEW_LINE> <DEDENT> irc.replySuccess() <NEW_LINE> <DEDENT> add = wrap(add, ['owner', optional('int'), 'something', ('literal', ('allow', 'deny')), optional('hostmask'), 'text']) <NEW_LINE> @internationalizeDocstring <NEW_LINE> def remove(self, irc, msg, args, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.db.remove(name) <NEW_LINE> <DEDENT> except NonExistantId: <NEW_LINE> <INDENT> irc.error(_('This name does not exist.')) <NEW_LINE> return <NEW_LINE> <DEDENT> irc.replySuccess() <NEW_LINE> <DEDENT> remove = wrap(remove, ['owner', 'something']) <NEW_LINE> @internationalizeDocstring <NEW_LINE> def sudo(self, irc, msg, args, command): <NEW_LINE> <INDENT> name, rule = self.db.getRuleMatching(command) <NEW_LINE> bannedChars = conf.supybot.commands.nested.brackets() <NEW_LINE> if name is None: <NEW_LINE> <INDENT> log.warning('Sudo for %r not granted to "%s"' % (command, msg.prefix)) <NEW_LINE> irc.error(_('Sudo not granted.')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert rule is not None <NEW_LINE> log.info('Sudo granted to "%s" with rule %s' % (msg.prefix, name)) <NEW_LINE> msg.prefix = rule.hostmask <NEW_LINE> tokens = callbacks.tokenize(command) <NEW_LINE> msg.nick = msg.prefix.split('!')[0] <NEW_LINE> self.Proxy(irc.irc, msg, tokens) <NEW_LINE> <DEDENT> <DEDENT> sudo = wrap(sudo, ['text']) <NEW_LINE> @internationalizeDocstring <NEW_LINE> def fakehostmask(self, irc, msg, args, hostmask, command): <NEW_LINE> <INDENT> log.info('fakehostmask used to run "%s" as %s' % (command, hostmask)) <NEW_LINE> msg.prefix = hostmask <NEW_LINE> (msg.nick, msg.user, msg.host)=ircutils.splitHostmask(hostmask) <NEW_LINE> tokens = callbacks.tokenize(command) <NEW_LINE> self.Proxy(irc.irc, msg, tokens) <NEW_LINE> <DEDENT> fakehostmask = wrap(fakehostmask, ['owner', 'hostmask', 'text']) <NEW_LINE> def die(self): <NEW_LINE> <INDENT> if not world.testing: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.unlink(self._path) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.db.save(open(self._path, 'a')) <NEW_LINE> <DEDENT> callbacks.Plugin.die(self)
Plugin that allows to run commands as someone else
62598fcf4a966d76dd5ef310
class MemberConfiguration(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "Description": (str, False), "MemberFrameworkConfiguration": (MemberFrameworkConfiguration, False), "Name": (str, True), }
`MemberConfiguration <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-managedblockchain-member-memberconfiguration.html>`__
62598fcfbe7bc26dc9252075
class InitiativeInChat(BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> chat = request.data['chat'] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return get_object_or_404(Chat, id=chat) in request.user.chats.all()
Может ли загружать документы в ту команду
62598fcf283ffb24f3cf3cbf
class UserProfileSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = models.UserProfile <NEW_LINE> fields = ('id', 'email', 'name', 'password') <NEW_LINE> extra_kwargs = {'password': {'write_only': True}} <NEW_LINE> <DEDENT> def create(self, validate_data): <NEW_LINE> <INDENT> user = models.UserProfile( email = validate_data['email'], name = validate_data['name'] ) <NEW_LINE> user.set_password(validate_data['password']) <NEW_LINE> user.save() <NEW_LINE> return user
A Serializer for our user profile objects
62598fcf60cbc95b06364776
class Square(): <NEW_LINE> <INDENT> def __init__(self, size=0, position=(0, 0)): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> self.position = position <NEW_LINE> <DEDENT> ''' Calculates the area ''' <NEW_LINE> def area(self): <NEW_LINE> <INDENT> return self.__size * self.__size <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self.__size <NEW_LINE> <DEDENT> @size.setter <NEW_LINE> def size(self, value): <NEW_LINE> <INDENT> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("size must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("size must be >= 0") <NEW_LINE> <DEDENT> self.__size = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def position(self): <NEW_LINE> <INDENT> return self.__position <NEW_LINE> <DEDENT> @position.setter <NEW_LINE> def position(self, value): <NEW_LINE> <INDENT> if isinstance(value, tuple) and len(value) == 2: <NEW_LINE> <INDENT> if isinstance(value[0], int) and isinstance(value[1], int): <NEW_LINE> <INDENT> if value[0] >= 0 and value[1] >= 0: <NEW_LINE> <INDENT> self.__position = value <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> raise TypeError("position must be a tuple of 2 positive integers") <NEW_LINE> <DEDENT> def my_print(self): <NEW_LINE> <INDENT> if self.__size == 0: <NEW_LINE> <INDENT> print() <NEW_LINE> return <NEW_LINE> <DEDENT> for line in range(self.__position[1]): <NEW_LINE> <INDENT> print() <NEW_LINE> <DEDENT> for col in range(self.__size): <NEW_LINE> <INDENT> print("{}{}".format(" " * self.__position[0], "#" * self.__size))
Square class
62598fcf9f28863672818a99
class ADPAPIConnection(object): <NEW_LINE> <INDENT> connection = {'status': 'availabe', 'type': 'unknown', 'token': '', 'expires': '', 'sessionState': ''} <NEW_LINE> connectionConfiguration = None <NEW_LINE> userAgent = 'adp-userinfo-python/' + __version__ <NEW_LINE> def isConnectedIndicator(self): <NEW_LINE> <INDENT> return self.connection['status'] == 'connected' <NEW_LINE> <DEDENT> def getAccessToken(self): <NEW_LINE> <INDENT> return self.connection['token'] <NEW_LINE> <DEDENT> def getExpiration(self): <NEW_LINE> <INDENT> return self.connection['expires'] <NEW_LINE> <DEDENT> def getSessionState(self): <NEW_LINE> <INDENT> return self.connection['sessionState'] <NEW_LINE> <DEDENT> def getConfig(self): <NEW_LINE> <INDENT> return self.connectionConfiguration <NEW_LINE> <DEDENT> def setSessionState(self, sessionState): <NEW_LINE> <INDENT> self.connection['sessionState'] = sessionState <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> if self.getConfig().initDone is False: <NEW_LINE> <INDENT> logging.debug('connecting without config init') <NEW_LINE> raise ConfigError(self.__class__.__name__, Error.errDict['initBad']['errCode'], Error.errDict['initBad']['errMsg']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> formData = {'grant_type': self.getConfig().getGrantType()} <NEW_LINE> headers = {'user-agent': self.userAgent} <NEW_LINE> r = requests.post(self.getConfig().getTokenServerURL(), headers=(headers), cert=(self.getConfig().getSSLCertPath(), self.getConfig().getSSLKeyPath()), auth=(self.getConfig().getClientID(), self.getConfig().getClientSecret()), data=(formData)) <NEW_LINE> logging.debug(r.status_code) <NEW_LINE> logging.debug(r.json()) <NEW_LINE> if (r.status_code == requests.codes.ok): <NEW_LINE> <INDENT> self.connection['status'] = 'connected' <NEW_LINE> self.connection['token'] = r.json()['access_token'] <NEW_LINE> self.connection['expires'] = datetime.datetime.now() + datetime.timedelta(0, r.json()['expires_in'], 0) <NEW_LINE> if self.getSessionState() == '': <NEW_LINE> <INDENT> self.setSessionState(str(uuid.uuid1())) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ConnectError(self.__class__.__name__, str(r.status_code), 'Unable to connect to ADP') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> if self.getAccessToken() != '': <NEW_LINE> <INDENT> headers = {'user-agent': self.userAgent} <NEW_LINE> r = requests.get(self.getConfig().getDisconnectURL() + '?id_token_hint=' + self.getAccessToken(), headers=(headers)) <NEW_LINE> logging.debug(r.status_code) <NEW_LINE> <DEDENT> self.connection = {'status': 'ready', 'type': 'unknown', 'token': '', 'expires': '', 'state': ''}
Base class for maintaining ADP connection status and information Instance Variables: connection: dictionary storing the connection status and access-token information connectionConfiguration: instance of the ConnectionConfiguration class that was used to instantiate the connection
62598fcf7b180e01f3e4926c
class EchoHandler(WebSocketHandler): <NEW_LINE> <INDENT> @gen.coroutine <NEW_LINE> def on_message(self, message): <NEW_LINE> <INDENT> message = json.loads(message) <NEW_LINE> delay = message.get('delay', 0) <NEW_LINE> if delay: <NEW_LINE> <INDENT> yield gen.sleep(delay) <NEW_LINE> <DEDENT> self.write_message(message)
EchoHandler is a WebSocketHandler
62598fcffbf16365ca7944f6
class RandomPhoneNumberProvider(PhoneNumberProvider): <NEW_LINE> <INDENT> def getValue(self): <NEW_LINE> <INDENT> return ''.join(str(random.randint(0, 9)) for _ in range(10))
Data provider that returns a random phone number.
62598fcf7cff6e4e811b5e62
class IndexView(HomeAssistantView): <NEW_LINE> <INDENT> url = '/' <NEW_LINE> name = 'frontend:index' <NEW_LINE> requires_auth = False <NEW_LINE> def __init__(self, repo_path, js_option): <NEW_LINE> <INDENT> self.repo_path = repo_path <NEW_LINE> self.js_option = js_option <NEW_LINE> self._template_cache = {} <NEW_LINE> <DEDENT> def get_template(self, latest): <NEW_LINE> <INDENT> if self.repo_path is not None: <NEW_LINE> <INDENT> root = os.path.join(self.repo_path, 'hass_frontend') <NEW_LINE> <DEDENT> elif latest: <NEW_LINE> <INDENT> import hass_frontend <NEW_LINE> root = hass_frontend.where() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> import hass_frontend_es5 <NEW_LINE> root = hass_frontend_es5.where() <NEW_LINE> <DEDENT> tpl = self._template_cache.get(root) <NEW_LINE> if tpl is None: <NEW_LINE> <INDENT> with open(os.path.join(root, 'index.html')) as file: <NEW_LINE> <INDENT> tpl = jinja2.Template(file.read()) <NEW_LINE> <DEDENT> if self.repo_path is None: <NEW_LINE> <INDENT> self._template_cache[root] = tpl <NEW_LINE> <DEDENT> <DEDENT> return tpl <NEW_LINE> <DEDENT> async def get(self, request, extra=None): <NEW_LINE> <INDENT> hass = request.app['hass'] <NEW_LINE> latest = self.repo_path is not None or _is_latest(self.js_option, request) <NEW_LINE> if not hass.components.onboarding.async_is_onboarded(): <NEW_LINE> <INDENT> if latest: <NEW_LINE> <INDENT> location = '/frontend_latest/onboarding.html' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> location = '/frontend_es5/onboarding.html' <NEW_LINE> <DEDENT> return web.Response(status=302, headers={ 'location': location }) <NEW_LINE> <DEDENT> no_auth = '1' <NEW_LINE> if not request[KEY_AUTHENTICATED]: <NEW_LINE> <INDENT> no_auth = '0' <NEW_LINE> <DEDENT> template = await hass.async_add_job(self.get_template, latest) <NEW_LINE> extra_key = DATA_EXTRA_HTML_URL if latest else DATA_EXTRA_HTML_URL_ES5 <NEW_LINE> template_params = dict( no_auth=no_auth, theme_color=MANIFEST_JSON['theme_color'], extra_urls=hass.data[extra_key], use_oauth='1' ) <NEW_LINE> return web.Response(text=template.render(**template_params), content_type='text/html')
Serve the frontend.
62598fcf099cdd3c636755fc
class Campaign(StatableModel): <NEW_LINE> <INDENT> title = StringField(required=True) <NEW_LINE> deliveries = ListField(ReferenceField(Delivery)) <NEW_LINE> templates = ListField(ReferenceField(Template)) <NEW_LINE> currency = StringField(default=Currency.USD[0], choices=Currency.choices) <NEW_LINE> payout = FloatField() <NEW_LINE> meta = { 'allow_inheritance' : False }
Mongo Engine Model for campaigns
62598fd09f28863672818a9a
class Message(object): <NEW_LINE> <INDENT> _regex = r':((?P<USERNAME>[^!]+)!)?(?P<HOSTNAME>\S+)\s+(?P<ACTION>\S+)\s+:?(?P<CHANNEL>\S+)\s*(?:(?::|[+-]+)(?P<MESSAGE>.*))?' <NEW_LINE> def __init__(self, username=None, hostname=None, action=None, channel=None, msg=None): <NEW_LINE> <INDENT> self.raw_msg = "" <NEW_LINE> self.username = username or "" <NEW_LINE> self.hostname = hostname or "" <NEW_LINE> self.action = action or "" <NEW_LINE> self.channel = channel or "" <NEW_LINE> self.msg = msg or "" <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Message(username=%r, hostname=%r, action=%r, channel=%r, msg=%r)" % ( self.username, self.hostname, self.action, self.channel, self.msg) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (self.username == other.username and self.hostname == other.hostname and self.action == other.action and self.channel == other.channel and self.msg == other.msg) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> hashables = (self.username, self.hostname, self.action, self.channel, self.msg) <NEW_LINE> result = 0 <NEW_LINE> for value in hashables: <NEW_LINE> <INDENT> result = 33*result + hash(value) <NEW_LINE> <DEDENT> return hash(result) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, raw_string): <NEW_LINE> <INDENT> msg = Message() <NEW_LINE> msg.raw_msg = raw_string <NEW_LINE> matches = re.match(Message._regex, msg.raw_msg) <NEW_LINE> if matches: <NEW_LINE> <INDENT> matches_dict = matches.groupdict() <NEW_LINE> msg.username = matches_dict['USERNAME'] or "" <NEW_LINE> msg.hostname = matches_dict['HOSTNAME'] or "" <NEW_LINE> msg.action = matches_dict['ACTION'] or "" <NEW_LINE> msg.channel = matches_dict['CHANNEL'] or "" <NEW_LINE> msg.msg = matches_dict['MESSAGE'] or "" <NEW_LINE> <DEDENT> return msg <NEW_LINE> <DEDENT> def to_raw(self, with_username=None): <NEW_LINE> <INDENT> string_list = [] <NEW_LINE> if with_username == True and len(self.hostname) > 0: <NEW_LINE> <INDENT> string_list.append(':') <NEW_LINE> if len(self.username) > 0: <NEW_LINE> <INDENT> string_list.append(self.username) <NEW_LINE> string_list.append('!') <NEW_LINE> <DEDENT> string_list.append(self.hostname) <NEW_LINE> string_list.append(' ') <NEW_LINE> <DEDENT> string_list.append(self.action) <NEW_LINE> string_list.append(' ') <NEW_LINE> string_list.append(self.channel) <NEW_LINE> string_list.append(' :') <NEW_LINE> string_list.append(self.msg) <NEW_LINE> self.raw_msg = ''.join(string_list) <NEW_LINE> return self.raw_msg
A standard IRC message object that will store the message details. Class attribute: `_regex`: keeps track of how to parse each message. Attributes: `raw_msg`: Given raw message `username`: Parsed out username `hostname`: Parsed out hostname `action`: Parsed out action `channel`: Parsed out channel `msg`: Parsed out message
62598fd0d8ef3951e32c8079