code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class DHOpTimerService(UInt8Service): <NEW_LINE> <INDENT> unit = 'Hr' <NEW_LINE> def to_cmd_help(self) -> SACmdHelp: <NEW_LINE> <INDENT> _help = super(DHOpTimerService, self).to_cmd_help() <NEW_LINE> _help.update_kwargs_params({ 0: '關閉設定時間功能', '非0': '代表運轉時間' }) <NEW_LINE> _help.update_kwargs_unit('Hr') <NEW_LINE> return _help
運轉時間設定功能
62598fb05fc7496912d48299
@dataclasses.dataclass <NEW_LINE> class TensorboardConfig(base_config.Config): <NEW_LINE> <INDENT> track_lr: bool = True <NEW_LINE> write_model_weights: bool = False
Configuration for Tensorboard. Attributes: track_lr: Whether or not to track the learning rate in Tensorboard. Defaults to True. write_model_weights: Whether or not to write the model weights as images in Tensorboard. Defaults to False.
62598fb07b25080760ed74e0
class SteveESWrapper(object): <NEW_LINE> <INDENT> def __init__(self, ES): <NEW_LINE> <INDENT> self.ES = ES <NEW_LINE> <DEDENT> def get(self, index, doc_type, id): <NEW_LINE> <INDENT> return self.ES.get(index = index+'_'+doc_type, doc_type = '_doc', id = id) <NEW_LINE> <DEDENT> def exists(self, index, doc_type, id): <NEW_LINE> <INDENT> return self.ES.exists(index = index+'_'+doc_type, doc_type = '_doc', id = id) <NEW_LINE> <DEDENT> def delete(self, index, doc_type, id): <NEW_LINE> <INDENT> return self.ES.delete(index = index+'_'+doc_type, doc_type = '_doc', id = id) <NEW_LINE> <DEDENT> def index(self, index, doc_type, id = None, body = None): <NEW_LINE> <INDENT> return self.ES.index(index = index+'_'+doc_type, doc_type = '_doc', id = id, body = body) <NEW_LINE> <DEDENT> def update(self, index, doc_type, id, body): <NEW_LINE> <INDENT> return self.ES.update(index = index+'_'+doc_type, doc_type = '_doc', id = id, body = body) <NEW_LINE> <DEDENT> def scroll(self, scroll_id, scroll): <NEW_LINE> <INDENT> return self.ES.scroll(scroll_id = scroll_id, scroll = scroll) <NEW_LINE> <DEDENT> def delete_by_query(self, **kwargs): <NEW_LINE> <INDENT> return self.ES.delete_by_query(**kwargs) <NEW_LINE> <DEDENT> def search(self, index, doc_type, size = 100, scroll = None, _source_include = None, body = None, q = None, sort = None): <NEW_LINE> <INDENT> if q: <NEW_LINE> <INDENT> body = { "query": { "query_string": { "query": q } } } <NEW_LINE> <DEDENT> if sort and body: <NEW_LINE> <INDENT> if '.keyword' not in sort: <NEW_LINE> <INDENT> sort = sort + ".keyword" <NEW_LINE> <DEDENT> body['sort'] = [ { sort: 'asc'} ] <NEW_LINE> <DEDENT> return self.ES.search( index = index+'_'+doc_type, doc_type = '_doc', size = size, scroll = scroll, _source_include = _source_include, body = body ) <NEW_LINE> <DEDENT> def count(self, index, doc_type = '*', body = None): <NEW_LINE> <INDENT> return self.ES.count( index = index+'_'+doc_type, doc_type = '_doc', body = body )
Class for rewriting old-style queries to the new ones, where doc_type is an integral part of the DB name
62598fb063b5f9789fe85199
class TestGamePlayPlayers(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 testGamePlayPlayers(self): <NEW_LINE> <INDENT> pass
GamePlayPlayers unit test stubs
62598fb0cc0a2c111447b043
class BERTLoaderTransform: <NEW_LINE> <INDENT> def __init__(self, use_avg_len, batch_size, shuffle, num_ctxes, num_buckets, vocab): <NEW_LINE> <INDENT> self._sampler_fn = BERTSamplerFn(use_avg_len, batch_size, shuffle, num_ctxes, num_buckets) <NEW_LINE> self._data_fn = BERTDataLoaderFn(use_avg_len, num_ctxes, vocab) <NEW_LINE> <DEDENT> def __call__(self, dataset): <NEW_LINE> <INDENT> sampler = self._sampler_fn(dataset) <NEW_LINE> dataloader = self._data_fn(dataset, sampler) <NEW_LINE> return dataloader
Create dataloader for a BERT dataset.
62598fb03d592f4c4edbaef2
class LiveJournalOpenId(OpenIdAuth): <NEW_LINE> <INDENT> name = 'livejournal' <NEW_LINE> def get_user_details(self, response): <NEW_LINE> <INDENT> values = super().get_user_details(response) <NEW_LINE> values['username'] = values.get('username') or urlsplit(response.identity_url).netloc.split('.', 1)[0] <NEW_LINE> return values <NEW_LINE> <DEDENT> def openid_url(self): <NEW_LINE> <INDENT> if not self.data.get('openid_lj_user'): <NEW_LINE> <INDENT> raise AuthMissingParameter(self, 'openid_lj_user') <NEW_LINE> <DEDENT> return 'http://{}.livejournal.com'.format(self.data['openid_lj_user'])
LiveJournal OpenID authentication backend
62598fb0a8370b77170f040d
class JSONEventHandler(EventHandler): <NEW_LINE> <INDENT> name = 'json' <NEW_LINE> encoding = 'utf-8' <NEW_LINE> def start(self): <NEW_LINE> <INDENT> self.data = {} <NEW_LINE> <DEDENT> def jsonFn(self, comic): <NEW_LINE> <INDENT> fn = os.path.join(self.basepath, comic, 'dosage.json') <NEW_LINE> fn = os.path.abspath(fn) <NEW_LINE> return fn <NEW_LINE> <DEDENT> def getComicData(self, comic): <NEW_LINE> <INDENT> if comic not in self.data: <NEW_LINE> <INDENT> if os.path.exists(self.jsonFn(comic)): <NEW_LINE> <INDENT> with codecs.open(self.jsonFn(comic), 'r', self.encoding) as f: <NEW_LINE> <INDENT> self.data[comic] = json.load(f) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.data[comic] = {'pages':{}} <NEW_LINE> <DEDENT> <DEDENT> return self.data[comic] <NEW_LINE> <DEDENT> def getPageInfo(self, comic, url): <NEW_LINE> <INDENT> comicData = self.getComicData(comic) <NEW_LINE> if url not in comicData['pages']: <NEW_LINE> <INDENT> comicData['pages'][url] = {'images':{}} <NEW_LINE> <DEDENT> return comicData['pages'][url] <NEW_LINE> <DEDENT> def comicDownloaded(self, comic, filename, text=None): <NEW_LINE> <INDENT> pageInfo = self.getPageInfo(comic.name, comic.referrer) <NEW_LINE> pageInfo['images'][comic.url] = os.path.basename(filename) <NEW_LINE> <DEDENT> def comicPageLink(self, comic, url, prevUrl): <NEW_LINE> <INDENT> pageInfo = self.getPageInfo(comic, url) <NEW_LINE> pageInfo['prev'] = prevUrl <NEW_LINE> <DEDENT> def end(self): <NEW_LINE> <INDENT> for comic in self.data: <NEW_LINE> <INDENT> with codecs.open(self.jsonFn(comic), 'w', self.encoding) as f: <NEW_LINE> <INDENT> json.dump(self.data[comic], f, indent=2, separators=(',', ': '), sort_keys=True)
Output metadata for comics in JSON format.
62598fb099fddb7c1ca62e02
class MixedSizePartitionMeasurer(PartitionMeasurer): <NEW_LINE> <INDENT> def get_weight(self, _): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> def get_size(self, partition_name): <NEW_LINE> <INDENT> if partition_name[1] == 0: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> return 1
An implementation of PartitionMeasurer that provides 2-size for partition 0 and 1-size for partition 1
62598fb056ac1b37e630221e
class ArgPos: <NEW_LINE> <INDENT> BODY = "body" <NEW_LINE> PATH = "path" <NEW_LINE> PARAM = "param"
Argument positions
62598fb0a05bb46b3848a89d
class JsonWriterPipeline(object): <NEW_LINE> <INDENT> def __init__(self, items): <NEW_LINE> <INDENT> self.items_ = items <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_settings(cls, settings): <NEW_LINE> <INDENT> return cls(settings['PIPELINE_OUTPUT']) <NEW_LINE> <DEDENT> def process_item(self, item, scraper): <NEW_LINE> <INDENT> if 'events' in item: <NEW_LINE> <INDENT> for individual_item in item['events']: <NEW_LINE> <INDENT> self._process_item(individual_item) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._process_item(item) <NEW_LINE> <DEDENT> return item <NEW_LINE> <DEDENT> def _process_item(self, item): <NEW_LINE> <INDENT> if item['venue_name'] not in self.items_: <NEW_LINE> <INDENT> self.items_[item['venue_name']] = [] <NEW_LINE> <DEDENT> self.items_[item['venue_name']].append(dict(item)) <NEW_LINE> return item
JSON extracting spider pipeline
62598fb07d847024c075c3f4
class InvalidScoreLengthForFrame(ScoringException): <NEW_LINE> <INDENT> def __init__(self, score_type, score, frame): <NEW_LINE> <INDENT> super(InvalidScoreLengthForFrame, self).__init__( ('{type} {score} has incorrect number of tries for ' 'frame: {frame}.'.format(type=score_type, score=score, frame=frame)))
Every frame should have 1. in case of a strike, a minimum of 1 attemptfor all frames except the last frame in which case it will have 3 attempts. 2. in case of a spare, a minimum of 2 attemptfor all frames except the last frame in which case it will have 3 attempts. 3. exactly 2 attempts for all frames in case of an open frame.
62598fb0442bda511e95c48a
class StatusLocacao(models.Model): <NEW_LINE> <INDENT> status_locacao = models.CharField(max_length=100) <NEW_LINE> icone = models.CharField(max_length=100) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.status_locacao <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Status da Locação' <NEW_LINE> verbose_name_plural = 'Status das Locações'
Define o `estado da locação`: 'Realizada', 'Com Pendências', 'Cancelada' e 'Finalizada'
62598fb0e5267d203ee6b93b
class Algorithm: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.algorithm_name = "ILP" <NEW_LINE> self.ilp_time_limit = 60 <NEW_LINE> self.ilp_tune = False <NEW_LINE> self.ch_alpha = 1.0 <NEW_LINE> self.ch_seed = None <NEW_LINE> <DEDENT> def use_ilp(self, time_limit = 60, tune = False): <NEW_LINE> <INDENT> self.algorithm_name = "ILP" <NEW_LINE> self.ilp_time_limit = time_limit <NEW_LINE> self.ilp_tune = tune <NEW_LINE> <DEDENT> def use_ch(self, alpha = 1.0, seed = None): <NEW_LINE> <INDENT> self.algorithm_name = "CH" <NEW_LINE> self.ch_alpha = alpha <NEW_LINE> self.ch_seed = seed <NEW_LINE> <DEDENT> def run(self, weights, subgraph): <NEW_LINE> <INDENT> if self.algorithm_name == "ILP": <NEW_LINE> <INDENT> return ilp.run(weights, subgraph, self.ilp_time_limit, self.ilp_tune) <NEW_LINE> <DEDENT> elif self.algorithm_name == "CH": <NEW_LINE> <INDENT> return ch.run(weights, subgraph, self.ch_alpha, self.ch_seed) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Invalid algorithm name \"" + self.algorithm_name + "\". Options: \"ILP\", \"CH\".")
Class to select algorithm for solving the subproblems. Attributes: algorithm_name (string): Name of selected algorithm. Options: "ILP", "CH". Default: "ILP". ilp_time_limit (float): Time limit for algorithm "ILP" in seconds. If <= 0, no time limit is enforced. Default: 60. ilp_tune (bool): If True, the model generated by "ILP" is tuned before being optimized. Default: False. ch_alpha (float): Between 0 and 1. If smaller than 1, the algorithm behaves non-deterministically. Default: 1.0. ch_seed (None or int): Seed for random generation. Default: None.
62598fb023849d37ff8510e6
class Dashboard: <NEW_LINE> <INDENT> pass
The robot side to store and send updates of Dashboard values
62598fb0aad79263cf42e806
class CommitStripFr(GenericCommitStrip): <NEW_LINE> <INDENT> name = "commit_fr" <NEW_LINE> long_name = "Commit Strip (Fr)" <NEW_LINE> url = "http://www.commitstrip.com/fr" <NEW_LINE> _categories = ("FRANCAIS",) <NEW_LINE> first_url = "http://www.commitstrip.com/fr/2012/02/22/interview/"
Class to retrieve Commit Strips in French.
62598fb04428ac0f6e658558
class DaskSLURMBackend(BaseDaskJobQueueBackend): <NEW_LINE> <INDENT> def __init__( self, minimum_number_of_workers=1, maximum_number_of_workers=1, resources_per_worker=QueueWorkerResources(), queue_name="default", setup_script_commands=None, extra_script_options=None, adaptive_interval="10000ms", disable_nanny_process=False, adaptive_class=None, ): <NEW_LINE> <INDENT> super().__init__( minimum_number_of_workers, maximum_number_of_workers, resources_per_worker, queue_name, setup_script_commands, extra_script_options, adaptive_interval, disable_nanny_process, cluster_type="slurm", adaptive_class=adaptive_class, ) <NEW_LINE> <DEDENT> def _get_cluster_class(self): <NEW_LINE> <INDENT> from dask_jobqueue import SLURMCluster <NEW_LINE> return SLURMCluster
An openff-evaluator backend which uses a `dask_jobqueue.SLURMCluster` object to run calculations within an existing SLURM queue. See Also -------- dask_jobqueue.SLURMCluster DaskSLURMBackend
62598fb02c8b7c6e89bd37f8
class AllDistComp(om.ExplicitComponent): <NEW_LINE> <INDENT> def initialize(self): <NEW_LINE> <INDENT> self.options.declare('num_nodes', types=int) <NEW_LINE> self.options.declare('limit', types=float, default=1.0) <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> nn = self.options['num_nodes'] <NEW_LINE> self.add_input('x1', val=np.zeros(nn)) <NEW_LINE> self.add_input('y1', val=np.zeros(nn)) <NEW_LINE> self.add_input('x2', val=np.zeros(nn)) <NEW_LINE> self.add_input('y2', val=np.zeros(nn)) <NEW_LINE> self.add_output('dist', val=np.zeros(nn)) <NEW_LINE> arange1 = np.arange(nn, dtype=int) <NEW_LINE> self.declare_partials('dist', ['x1', 'y1', 'x2', 'y2'], rows=arange1, cols=arange1) <NEW_LINE> <DEDENT> def compute(self, inputs, outputs): <NEW_LINE> <INDENT> nn = self.options['num_nodes'] <NEW_LINE> limit = self.options['limit'] <NEW_LINE> x1 = inputs['x1'] <NEW_LINE> y1 = inputs['y1'] <NEW_LINE> x2 = inputs['x2'] <NEW_LINE> y2 = inputs['y2'] <NEW_LINE> diff_x = x1 - x2 <NEW_LINE> diff_y = y1 - y2 <NEW_LINE> dist = np.sqrt(diff_x**2 + diff_y**2) <NEW_LINE> dist[np.where(dist < 1e-10)] = 1e-10 <NEW_LINE> self.dx = diff_x/dist/limit <NEW_LINE> self.dy = diff_y/dist/limit <NEW_LINE> outputs['dist'] = (limit - dist)/limit <NEW_LINE> <DEDENT> def compute_partials(self, params, jacobian): <NEW_LINE> <INDENT> jacobian['dist', 'x1'] = -self.dx <NEW_LINE> jacobian['dist', 'x2'] = self.dx <NEW_LINE> jacobian['dist', 'y1'] = -self.dy <NEW_LINE> jacobian['dist', 'y2'] = self.dy
For computing complete pairwise distance constraints.
62598fb07047854f4633f40d
class CarouselPluginItem(BaseLink, LinkMethodsMixin): <NEW_LINE> <INDENT> plugin = models.ForeignKey(CarouselPlugin, related_name="carousel_item") <NEW_LINE> image = FilerImageField() <NEW_LINE> link_title = models.CharField(max_length=35)
The item in a carousel - basically a Link, with an image
62598fb0091ae35668704c52
class DecodeFailureMode(enum.Enum): <NEW_LINE> <INDENT> ABORT = 1 <NEW_LINE> SKIP = 2
This enum is used to identify the two possible modes to handle any error that can occur while decoding the payload received from the server table monitors. In both the cases (``SKIP`` and ``ABORT``) it will try to recover once by default.
62598fb05fdd1c0f98e5dfbe
class event_dispatcher(dispatcher): <NEW_LINE> <INDENT> def __init__(self, cleanup, processors=None): <NEW_LINE> <INDENT> dispatcher.__init__(self, cleanup, processors) <NEW_LINE> self.__starttime = time.time() <NEW_LINE> <DEDENT> def post_event(self, event): <NEW_LINE> <INDENT> self._events.append(event) <NEW_LINE> return True <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while self.running: <NEW_LINE> <INDENT> self.__starttime = time.time() <NEW_LINE> while (len(self) > 0): <NEW_LINE> <INDENT> self._dispatch_event(self._events.pop(0)) <NEW_LINE> <DEDENT> sleeptime = self.sleep-(time.time()-self.__starttime) <NEW_LINE> if (sleeptime > 0): <NEW_LINE> <INDENT> time.sleep(sleeptime)
Class to dispatch non-timed event @author ykk @date Feb 2011
62598fb0627d3e7fe0e06ee1
class TargetDiscretizer(BaseEstimator): <NEW_LINE> <INDENT> def __init__(self, discretizer: Callable) -> None: <NEW_LINE> <INDENT> if callable(discretizer): <NEW_LINE> <INDENT> self.discretizer = discretizer <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError(f"{self.__class__.__name__} constructor expect a callable") <NEW_LINE> <DEDENT> <DEDENT> def fit_resample( self, X: pd.DataFrame, y: pd.Series ) -> Tuple[pd.DataFrame, pd.Series]: <NEW_LINE> <INDENT> X, y = check_xy(X, y) <NEW_LINE> y = y.apply(self.discretizer) <NEW_LINE> return X, y
Discretize numerical target variable. The `TargetDiscretizer` transformer maps target variable values to discrete values using a user defined function. Parameters: discretizer: user defined function.
62598fb0460517430c432077
@dataclass <NEW_LINE> class ExtendedInfo: <NEW_LINE> <INDENT> other_element: Optional[object] = field( default=None, metadata={ "type": "Wildcard", "namespace": "##other", "required": True, } ) <NEW_LINE> id: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, } ) <NEW_LINE> other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } )
:ivar other_element: :ivar id: An internal ID to identify this object. :ivar other_attributes: A placeholder so that content creators can add attributes as desired.
62598fb099cbb53fe6830f0c
class BanditArm(object): <NEW_LINE> <INDENT> def __init__(self, true_params=None, prior_params=None): <NEW_LINE> <INDENT> if true_params: <NEW_LINE> <INDENT> self.true_distribution = true_params.get('distribution', 'bernoulli') <NEW_LINE> self.p = true_params.get('p', 0.5) <NEW_LINE> self.n = true_params.get('n', 1) <NEW_LINE> self.mu = true_params.get('mu', 0.5) <NEW_LINE> self.lamb = true_params.get('lamb', 0.5) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('CANNOT PROCEED, Need known arm distributions to proceed') <NEW_LINE> <DEDENT> self.trials = 0 <NEW_LINE> self.sample_mean = 0 <NEW_LINE> if prior_params: <NEW_LINE> <INDENT> self.prior_distribution = prior_params.get('distribution', 'beta') <NEW_LINE> self.prior_alpha = prior_params.get('alpha', 1) <NEW_LINE> self.prior_beta = prior_params.get('beta', 1) <NEW_LINE> self.prior_mu = prior_params.get('mu', 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.prior_alpha, self.prior_beta, self.prior_mu, self.prior_distribution = 1, 1, 1, 'beta' <NEW_LINE> <DEDENT> <DEDENT> def update_trial_count_for_arm(self): <NEW_LINE> <INDENT> self.trials += 1 <NEW_LINE> <DEDENT> def observe_reward_for_trial(self): <NEW_LINE> <INDENT> self.update_trial_count_for_arm() <NEW_LINE> if self.true_distribution == 'bernoulli': <NEW_LINE> <INDENT> return np.random.binomial(n=1, p=self.p) <NEW_LINE> <DEDENT> <DEDENT> def update_sample_reward_mean_mle(self, reward): <NEW_LINE> <INDENT> new_value = (((self.trials - 1) / self.trials) * self.sample_mean) + ((1 / self.trials) * reward) <NEW_LINE> self.sample_mean = new_value <NEW_LINE> return <NEW_LINE> <DEDENT> def update_upper_confidence_bound(self, total_trials): <NEW_LINE> <INDENT> if self.true_distribution == 'bernoulli' or self.true_distribution == 'binomial': <NEW_LINE> <INDENT> return self.sample_mean + math.sqrt((2 * math.log(total_trials)) / self.trials) if self.trials > 0 else 0 <NEW_LINE> <DEDENT> <DEDENT> def update_sample_reward_mean_map(self, reward): <NEW_LINE> <INDENT> if reward > 0: <NEW_LINE> <INDENT> self.prior_alpha += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.prior_beta += 1 <NEW_LINE> <DEDENT> self.sample_mean = self.prior_alpha / (self.prior_alpha + self.prior_beta) <NEW_LINE> return <NEW_LINE> <DEDENT> def sample_from_posterior_distribution(self): <NEW_LINE> <INDENT> if self.true_distribution == 'bernoulli' or self.true_distribution == 'binomial': <NEW_LINE> <INDENT> return np.random.beta(self.prior_alpha, self.prior_beta)
Arm is just one possible control or decision configuration available to us (which arm to pick / which action to take) This can be a: - bernoulli arm (just 1/0 reward like a click or conversion) - binomial or poisson arm (prob of click or arrival rate) - normal or lognormal (value per click or value per conversion) - contextual arm (where arm is actually combination of features)
62598fb05166f23b2e24340d
class Bool(BooleanLogics.Bool, AtomicProposition): <NEW_LINE> <INDENT> pass
The class of Boolean atomic propositions.
62598fb0f548e778e596b5d8
class RpcCallBacks(object): <NEW_LINE> <INDENT> def __init__(self, vdpd, ipt_drvr): <NEW_LINE> <INDENT> self._vdpd = vdpd <NEW_LINE> self._iptd = ipt_drvr <NEW_LINE> <DEDENT> def _enqueue_event(self, vm): <NEW_LINE> <INDENT> oui = vm.get('oui') <NEW_LINE> if oui and oui.get('ip_addr') != '0.0.0.0' and self._iptd: <NEW_LINE> <INDENT> rule_info = dict(mac=vm.get('vm_mac'), ip=oui.get('ip_addr'), port=vm.get('port_uuid'), status=vm.get('status')) <NEW_LINE> self._iptd.enqueue_event(rule_info) <NEW_LINE> <DEDENT> <DEDENT> def send_vm_info(self, context, msg): <NEW_LINE> <INDENT> vm_info = eval(msg) <NEW_LINE> LOG.debug('Received vm_info: %(vm_info)s', {'vm_info': vm_info}) <NEW_LINE> self._vdpd.vdp_vm_event(vm_info) <NEW_LINE> if isinstance(vm_info, list): <NEW_LINE> <INDENT> for vm in vm_info: <NEW_LINE> <INDENT> self._enqueue_event(vm) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._enqueue_event(vm_info) <NEW_LINE> <DEDENT> <DEDENT> def update_ip_rule(self, context, msg): <NEW_LINE> <INDENT> rule_info = eval(msg) <NEW_LINE> LOG.debug('RX Info : %s', rule_info) <NEW_LINE> if self._iptd: <NEW_LINE> <INDENT> self._iptd.enqueue_event(rule_info) <NEW_LINE> <DEDENT> <DEDENT> def send_msg_to_agent(self, context, msg): <NEW_LINE> <INDENT> msg_type = context.get('type') <NEW_LINE> uplink = json.loads(msg) <NEW_LINE> LOG.debug("Received %(context)s and %(msg)s", ( {'context': context, 'msg': uplink})) <NEW_LINE> if msg_type == constants.UPLINK_NAME: <NEW_LINE> <INDENT> LOG.debug("uplink is %(uplink)s", uplink) <NEW_LINE> self._vdpd.dfa_uplink_restart(uplink)
RPC call back methods.
62598fb0851cf427c66b82ef
class Events(ItemIterator): <NEW_LINE> <INDENT> nickname = 'events' <NEW_LINE> requires_path = False <NEW_LINE> def __init__(self, *args, **kargs): <NEW_LINE> <INDENT> super(Events, self).__init__(*args, **kargs) <NEW_LINE> self.md5er = self.subagent(Md5er) <NEW_LINE> self.collisions = dict(md5=[], fname=[]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def events_db(self): <NEW_LINE> <INDENT> return self.conf.events_db <NEW_LINE> <DEDENT> def write_dupe(self, item1, item2): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def find_matches(self, item, field): <NEW_LINE> <INDENT> results = self.database._matching_values( field=field, value=getattr(item,field)) <NEW_LINE> return [x for x in results if x.id !=item.id] <NEW_LINE> <DEDENT> def seek_fname_collision(self, item): <NEW_LINE> <INDENT> if not len(os.path.splitext(item.fname)[0]) > 4: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> results = self.find_matches(item, 'fname') <NEW_LINE> if not len(results): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> item_ids = [row.value['_id'] for row in results] <NEW_LINE> if len(item_ids)>1: <NEW_LINE> <INDENT> reason = 'fname' <NEW_LINE> self.record_collision(reason, item_ids, item) <NEW_LINE> <DEDENT> <DEDENT> def seek_md5_collision(self, item): <NEW_LINE> <INDENT> if not item.md5: <NEW_LINE> <INDENT> report(' - md5 not set, calling subagent'); <NEW_LINE> self.md5er.callback(item) <NEW_LINE> <DEDENT> reason = 'md5' <NEW_LINE> results = self.find_matches(item, 'md5') <NEW_LINE> if not len(results): return <NEW_LINE> item_ids = [row.value['_id'] for row in results] + [item._id] <NEW_LINE> self.record_collision(reason, item_ids, item) <NEW_LINE> <DEDENT> def record_collision(self, reason, item_ids, item=None): <NEW_LINE> <INDENT> self.collisions[reason] += item_ids <NEW_LINE> item_ids = sorted(item_ids) <NEW_LINE> event = Event(reason=reason, item_ids=item_ids, details=dict(md5=item.md5)) <NEW_LINE> event.store(self.events_db) <NEW_LINE> report(' - by {0}: found {1} events'.format( reason, len(item_ids))) <NEW_LINE> <DEDENT> def callback(self, item=None, **kargs): <NEW_LINE> <INDENT> report(item._id) <NEW_LINE> if item._id not in self.collisions['fname']: <NEW_LINE> <INDENT> self.seek_fname_collision(item) <NEW_LINE> <DEDENT> if item._id not in self.collisions['md5']: <NEW_LINE> <INDENT> self.seek_md5_collision(item)
saves size info
62598fb0796e427e5384e7c8
class MigratePrivateIpAddressRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.SourceNetworkInterfaceId = None <NEW_LINE> self.DestinationNetworkInterfaceId = None <NEW_LINE> self.PrivateIpAddress = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.SourceNetworkInterfaceId = params.get("SourceNetworkInterfaceId") <NEW_LINE> self.DestinationNetworkInterfaceId = params.get("DestinationNetworkInterfaceId") <NEW_LINE> self.PrivateIpAddress = params.get("PrivateIpAddress")
MigratePrivateIpAddress请求参数结构体
62598fb0be8e80087fbbf098
class BINARY_MULTIPLY(BINARY): <NEW_LINE> <INDENT> def touch_value(self, stack, frame): <NEW_LINE> <INDENT> (TOS1, TOS) = stack[-2:] <NEW_LINE> stack[-2:] = [TOS1 * TOS]
Implements TOS = TOS1 * TOS.
62598fb085dfad0860cbfa8d
class IncomingFriendshipsResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None) <NEW_LINE> <DEDENT> def get_Limit(self): <NEW_LINE> <INDENT> return self._output.get('Limit', None) <NEW_LINE> <DEDENT> def get_Remaining(self): <NEW_LINE> <INDENT> return self._output.get('Remaining', None) <NEW_LINE> <DEDENT> def get_Reset(self): <NEW_LINE> <INDENT> return self._output.get('Reset', None)
A ResultSet with methods tailored to the values returned by the IncomingFriendships Choreo. The ResultSet object is used to retrieve the results of a Choreo execution.
62598fb0a8370b77170f0410
class LambdaExpression(VariableBinderExpression): <NEW_LINE> <INDENT> PREFIX = '\\' <NEW_LINE> def _skolemise(self, bound_vars, counter): <NEW_LINE> <INDENT> bv = bound_vars.copy() <NEW_LINE> bv.add(self.variable) <NEW_LINE> return self.__class__(self.variable, self.term._skolemise(bv, counter)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "LambdaExpression('%s', '%s')" % (self.variable, self.term)
A lambda expression: \x.M.
62598fb0a05bb46b3848a89f
class M3_10(models.Model): <NEW_LINE> <INDENT> name = models.CharField(_("name"), max_length=500) <NEW_LINE> name_fr = models.CharField(_("name fr"), max_length=500) <NEW_LINE> name_es = models.CharField(_("name es"), max_length=500) <NEW_LINE> name_ar = models.CharField(_("name ar"), max_length=500) <NEW_LINE> name_ru = models.CharField(_("name ru"), max_length=500) <NEW_LINE> name_zh = models.CharField(_("name zh"), max_length=500) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = _("Name") <NEW_LINE> <DEDENT> pass
M3_10
62598fb0e76e3b2f99fd8a6a
class StudioApiFixture(object): <NEW_LINE> <INDENT> @lazy <NEW_LINE> def session(self): <NEW_LINE> <INDENT> session = requests.Session() <NEW_LINE> response = session.get(STUDIO_BASE_URL + "/auto_auth?staff=true") <NEW_LINE> if response.ok: <NEW_LINE> <INDENT> return session <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = "Could not log in to use Studio restful API. Status code: {0}".format(response.status_code) <NEW_LINE> raise StudioApiLoginError(msg) <NEW_LINE> <DEDENT> <DEDENT> @lazy <NEW_LINE> def session_cookies(self): <NEW_LINE> <INDENT> return {key: val for key, val in self.session.cookies.items()} <NEW_LINE> <DEDENT> @lazy <NEW_LINE> def headers(self): <NEW_LINE> <INDENT> return { 'Content-type': 'application/json', 'Accept': 'application/json', 'X-CSRFToken': self.session_cookies.get('csrftoken', '') }
Base class for fixtures that use the Studio restful API.
62598fb0cb5e8a47e493c193
@xs.process <NEW_LINE> class MarineSedimentTransport: <NEW_LINE> <INDENT> ss_ratio_land = xs.variable( description='sand/silt ratio of continental sediment source' ) <NEW_LINE> ss_ratio_sea = xs.variable( dims=('y', 'x'), intent='out', description='sand/silt ratio of marine sediment layer' ) <NEW_LINE> porosity_sand = xs.variable( description='surface (reference) porosity of sand' ) <NEW_LINE> porosity_silt = xs.variable( description='surface (reference) porosity of silt' ) <NEW_LINE> e_depth_sand = xs.variable( description='e-folding depth of exp. porosity curve for sand' ) <NEW_LINE> e_depth_silt = xs.variable( description='e-folding depth of exp. porosity curve for silt' ) <NEW_LINE> diffusivity_sand = xs.variable( description='diffusivity (transport coefficient) for sand' ) <NEW_LINE> diffusivity_silt = xs.variable( description='diffusivity (transport coefficient) for silt' ) <NEW_LINE> layer_depth = xs.variable( description='mean depth (thickness) of marine active layer' ) <NEW_LINE> shape = xs.foreign(UniformRectilinearGrid2D, 'shape') <NEW_LINE> fs_context = xs.foreign(FastscapelibContext, 'context') <NEW_LINE> elevation = xs.foreign(SurfaceToErode, 'elevation') <NEW_LINE> sediment_source = xs.foreign(ChannelErosion, 'erosion') <NEW_LINE> sea_level = xs.foreign(Sea, 'level') <NEW_LINE> erosion = xs.variable( dims=('y', 'x'), intent='out', groups='erosion', description='marine erosion or deposition of sand/silt' ) <NEW_LINE> def initialize(self): <NEW_LINE> <INDENT> self.fs_context["runmarine"] = True <NEW_LINE> <DEDENT> def run_step(self): <NEW_LINE> <INDENT> self.fs_context["ratio"] = self.ss_ratio_land <NEW_LINE> self.fs_context["poro1"] = self.porosity_sand <NEW_LINE> self.fs_context["poro2"] = self.porosity_silt <NEW_LINE> self.fs_context["zporo1"] = self.e_depth_sand <NEW_LINE> self.fs_context["zporo2"] = self.e_depth_silt <NEW_LINE> self.fs_context["kdsea1"] = self.diffusivity_sand <NEW_LINE> self.fs_context["kdsea2"] = self.diffusivity_silt <NEW_LINE> self.fs_context["layer"] = self.layer_depth <NEW_LINE> self.fs_context["sealevel"] = self.sea_level <NEW_LINE> self.fs_context["Sedflux"] = self.sediment_source.ravel() <NEW_LINE> self.fs_context["h"] = self.elevation.flatten() <NEW_LINE> fs.marine() <NEW_LINE> erosion_flat = self.elevation.ravel() - self.fs_context["h"] <NEW_LINE> self.erosion = erosion_flat.reshape(self.shape) <NEW_LINE> self.ss_ratio_sea = self.fs_context["fmix"].copy().reshape(self.shape)
Marine sediment transport, deposition and compaction. The source of sediment used for marine transport originates from channel erosion and/or transport, which, integrated over the whole continental area, provides a volume of sediment yielded through the shoreline. A uniform, user-defined ratio of sand/silt is considered for this sediment yield. Each of these grain size category has its own properties like porosity, the exponential decreasing of porosity with depth and the transport coefficient (diffusivity).
62598fb071ff763f4b5e77a5
class PKTestCase(ModelsBaseTestCase): <NEW_LINE> <INDENT> def test_behaviour(self): <NEW_LINE> <INDENT> from django.db import models <NEW_LINE> class Publication(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=30) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ('title',) <NEW_LINE> <DEDENT> <DEDENT> class Article2(models.Model): <NEW_LINE> <INDENT> headline = models.CharField(max_length=100) <NEW_LINE> publications = models.ManyToManyField(Publication) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.headline <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ('headline',) <NEW_LINE> <DEDENT> <DEDENT> self.resetDB() <NEW_LINE> p = Publication(id=None, title='The Python Journal') <NEW_LINE> a = Article2(id=None, headline='Django lets you build Web apps easily') <NEW_LINE> self.assertRaises(ValueError, lambda a, p: a.publications.add(p), a, p) <NEW_LINE> p.save() <NEW_LINE> a.save() <NEW_LINE> self.assertEquals(a.id, 2) <NEW_LINE> article_alias = self.adapter.DjangoClassAlias(Article2, None) <NEW_LINE> x = Article2() <NEW_LINE> article_alias.applyAttributes(x, { 'headline': 'Foo bar!', 'id': 2, 'publications': [p] }) <NEW_LINE> <DEDENT> def test_none(self): <NEW_LINE> <INDENT> from django.db import models <NEW_LINE> class Foo(models.Model): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.resetDB() <NEW_LINE> alias = self.adapter.DjangoClassAlias(Foo, None) <NEW_LINE> x = Foo() <NEW_LINE> self.assertEquals(x.id, None) <NEW_LINE> alias.applyAttributes(x, { 'id': 0 }) <NEW_LINE> self.assertEquals(x.id, None) <NEW_LINE> <DEDENT> def test_no_pk(self): <NEW_LINE> <INDENT> from django.db import models <NEW_LINE> class NotSaved(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> <DEDENT> instances = [NotSaved(name="a"), NotSaved(name="b")] <NEW_LINE> encoded = pyamf.encode(instances, encoding=pyamf.AMF3).getvalue() <NEW_LINE> decoded = pyamf.get_decoder(pyamf.AMF3, encoded).readElement() <NEW_LINE> self.assertEquals(decoded[0]['name'], 'a') <NEW_LINE> self.assertEquals(decoded[1]['name'], 'b')
See ticket #599 for this. Check to make sure that django pk fields are set first
62598fb066656f66f7d5a424
class EncoderWrapper(ModelPart, Attentive): <NEW_LINE> <INDENT> def __init__(self, name: str, encoders: List[Any], attention_type: Type, attention_state_size: int, use_sentinels=False, share_attn_projections=False) -> None: <NEW_LINE> <INDENT> ModelPart.__init__(self, name, None, None) <NEW_LINE> Attentive.__init__(self, attention_type) <NEW_LINE> self.encoders = encoders <NEW_LINE> self._attention_type = attention_type <NEW_LINE> self._attention_state_size = attention_state_size <NEW_LINE> self._use_sentinels = use_sentinels <NEW_LINE> self._share_attn_projections = share_attn_projections <NEW_LINE> self.encoded = tf.concat([e.encoded for e in encoders], 1) <NEW_LINE> <DEDENT> def create_attention_object(self): <NEW_LINE> <INDENT> return self._attention_type( self.encoders, self._attention_state_size, "attention_{}".format(self.name), use_sentinels=self._use_sentinels, share_projections=self._share_attn_projections) <NEW_LINE> <DEDENT> def feed_dict(self, dataset: Dataset, train: bool) -> FeedDict: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> @property <NEW_LINE> def _attention_tensor(self): <NEW_LINE> <INDENT> raise NotImplementedError("Encoder wrapper does not contain the" " attention tensor") <NEW_LINE> <DEDENT> @property <NEW_LINE> def _attention_mask(self): <NEW_LINE> <INDENT> raise NotImplementedError("Encoder wrapper does not contain the" " attention mask")
Wrapper doing attention combination behaving as a single encoder. This class wraps encoders and performs the attention combination in such a way that for the decoder, it looks like a single encoder capable to generate a single context vector.
62598fb0379a373c97d99048
class Example11App(pygubu.TkApplication): <NEW_LINE> <INDENT> def _create_ui(self): <NEW_LINE> <INDENT> self.builder = builder = pygubu.Builder() <NEW_LINE> builder.add_from_file("exampleB.ui") <NEW_LINE> builder.add_resource_path(".") <NEW_LINE> self.mainwindow = builder.get_object("MainWindow", self.master) <NEW_LINE> builder.connect_callbacks(self) <NEW_LINE> vars = self.builder.tkvariables <NEW_LINE> vars["input_text"].set("") <NEW_LINE> root.bind("<Control-q>", lambda event: self.on_quit_button_click()) <NEW_LINE> <DEDENT> def on_quit_button_click(self): <NEW_LINE> <INDENT> root.destroy() <NEW_LINE> <DEDENT> def on_button_display_text_click(self): <NEW_LINE> <INDENT> vars = self.builder.tkvariables <NEW_LINE> text = vars["input_text"].get() <NEW_LINE> messagebox.askokcancel("Text entered by user:", text) <NEW_LINE> <DEDENT> def validate_input_text(self, value): <NEW_LINE> <INDENT> if value.isdigit(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif value is "": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Class representing a Tkinter based application.
62598fb00c0af96317c563b0
class PropertyCreateListView(generics.ListCreateAPIView): <NEW_LINE> <INDENT> queryset = Property.objects.all() <NEW_LINE> serializer_class = PropertyListSerializer <NEW_LINE> filter_fields = ( 'area_unit', 'bathrooms', 'bedrooms', 'home_size', 'home_type', 'price', 'area_unit', 'bathrooms', 'bedrooms', 'price_last_sold', 'date_last_sold', 'rent', 'property_size', 'tax_value', 'tax_year', 'year_built', 'address', 'zillow') <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save()
This class allows creation and query of Property objects.
62598fb023849d37ff8510e8
class PlayerDeleteView(DeleteView): <NEW_LINE> <INDENT> model = Player <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if not request.user.is_authenticated: <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> return super().get(request, args, kwargs) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if not request.user.is_authenticated: <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> return super().post(request, args, kwargs) <NEW_LINE> <DEDENT> def get_success_url(self, **kwargs): <NEW_LINE> <INDENT> messages.success(self.request, "Player '{}' deleted successfully".format(self.object.name)) <NEW_LINE> return reverse('sports-manager:player-list')
View that deletes a new category.
62598fb05fcc89381b266166
class SelectorBIC(ModelSelector): <NEW_LINE> <INDENT> def select(self): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", category=DeprecationWarning) <NEW_LINE> bestScore = np.inf <NEW_LINE> bestModel = None <NEW_LINE> for n_components in range(self.min_n_components,self.max_n_components+1 ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hmm_model = self.base_model(n_components) <NEW_LINE> bicScore = -2*hmm_model.score(self.X, self.lengths) + 2*n_components <NEW_LINE> if(bicScore<bestScore): <NEW_LINE> <INDENT> bestScore = bicScore <NEW_LINE> bestModel = hmm_model <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return bestModel
select the model with the lowest Bayesian Information Criterion(BIC) score http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf Bayesian information criteria: BIC = -2 * logL + p * logN
62598fb099cbb53fe6830f0d
class _PosixLock(_InterProcessLock): <NEW_LINE> <INDENT> def trylock(self): <NEW_LINE> <INDENT> fcntl.fcntl(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) <NEW_LINE> <DEDENT> def unlock(self): <NEW_LINE> <INDENT> fcntl.fcntl(self.lockfile, fcntl.LOCK_UN)
LOCK_UN - unlock LOCK_SH - acquire a shared lock LOCK_EX -acquire an exclusive lock When operation is LOCK_SH or LOCK_EX, it can also be bitwise ORed with LOCK_NB to avoid blocking on lock acquisition. If LOCK_NB is used and the lock cannot be acquired, an IOError will be raised and the exception will have an errno attribute set to EACCES or EAGAIN (depending on the operating system; for portability, check for both values). On at least some systems, LOCK_EX can only be used if the file descriptor refers to a file opened for writing
62598fb032920d7e50bc6089
class OTPAuthentication(Form): <NEW_LINE> <INDENT> secret = OTPSecretKeyField(qrcode_url="/qrcode", render_kw={ "data-ng-model": "model.secret", "module": "OTPApp" }) <NEW_LINE> check = fld.IntegerField(validators=[ vld.NumberRange(min=0, max=999999), OTPCheck( secret=lambda form, field: form.secret.data, method="TOTP" ) ], render_kw={"data-ng-model": "model.check"})
OTP Authentication form.
62598fb03317a56b869be565
class Recipe(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255) <NEW_LINE> price = models.DecimalField(max_digits=10, decimal_places=2, null=True) <NEW_LINE> cost = models.DecimalField(max_digits=10, decimal_places=2, null=True) <NEW_LINE> shelf_life = models.PositiveSmallIntegerField(default=0)
Example: Guacamole
62598fb026068e7796d4c98a
class RetryableError(db_module.Error): <NEW_LINE> <INDENT> pass
Indicates that a transaction can be retried.
62598fb05fdd1c0f98e5dfc0
class HACSSensor(Entity): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._state = None <NEW_LINE> <DEDENT> async def async_update(self): <NEW_LINE> <INDENT> if hacs.store.task_running: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> updates = 0 <NEW_LINE> for repository in hacs.store.repositories: <NEW_LINE> <INDENT> repository = hacs.store.repositories[repository] <NEW_LINE> if repository.pending_update: <NEW_LINE> <INDENT> updates += 1 <NEW_LINE> <DEDENT> <DEDENT> self._state = updates <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return "hacs" <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return "mdi:package" <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return "pending update(s)"
HACS Sensor class.
62598fb0a17c0f6771d5c26a
class RateBasedRule(pulumi.CustomResource): <NEW_LINE> <INDENT> def __init__(__self__, __name__, __opts__=None, metric_name=None, name=None, predicates=None, rate_key=None, rate_limit=None): <NEW_LINE> <INDENT> if not __name__: <NEW_LINE> <INDENT> raise TypeError('Missing resource name argument (for URN creation)') <NEW_LINE> <DEDENT> if not isinstance(__name__, basestring): <NEW_LINE> <INDENT> raise TypeError('Expected resource name to be a string') <NEW_LINE> <DEDENT> if __opts__ and not isinstance(__opts__, pulumi.ResourceOptions): <NEW_LINE> <INDENT> raise TypeError('Expected resource options to be a ResourceOptions instance') <NEW_LINE> <DEDENT> __props__ = dict() <NEW_LINE> if not metric_name: <NEW_LINE> <INDENT> raise TypeError('Missing required property metric_name') <NEW_LINE> <DEDENT> elif not isinstance(metric_name, basestring): <NEW_LINE> <INDENT> raise TypeError('Expected property metric_name to be a basestring') <NEW_LINE> <DEDENT> __self__.metric_name = metric_name <NEW_LINE> __props__['metricName'] = metric_name <NEW_LINE> if name and not isinstance(name, basestring): <NEW_LINE> <INDENT> raise TypeError('Expected property name to be a basestring') <NEW_LINE> <DEDENT> __self__.name = name <NEW_LINE> __props__['name'] = name <NEW_LINE> if predicates and not isinstance(predicates, list): <NEW_LINE> <INDENT> raise TypeError('Expected property predicates to be a list') <NEW_LINE> <DEDENT> __self__.predicates = predicates <NEW_LINE> __props__['predicates'] = predicates <NEW_LINE> if not rate_key: <NEW_LINE> <INDENT> raise TypeError('Missing required property rate_key') <NEW_LINE> <DEDENT> elif not isinstance(rate_key, basestring): <NEW_LINE> <INDENT> raise TypeError('Expected property rate_key to be a basestring') <NEW_LINE> <DEDENT> __self__.rate_key = rate_key <NEW_LINE> __props__['rateKey'] = rate_key <NEW_LINE> if not rate_limit: <NEW_LINE> <INDENT> raise TypeError('Missing required property rate_limit') <NEW_LINE> <DEDENT> elif not isinstance(rate_limit, int): <NEW_LINE> <INDENT> raise TypeError('Expected property rate_limit to be a int') <NEW_LINE> <DEDENT> __self__.rate_limit = rate_limit <NEW_LINE> __props__['rateLimit'] = rate_limit <NEW_LINE> super(RateBasedRule, __self__).__init__( 'aws:wafregional/rateBasedRule:RateBasedRule', __name__, __props__, __opts__) <NEW_LINE> <DEDENT> def set_outputs(self, outs): <NEW_LINE> <INDENT> if 'metricName' in outs: <NEW_LINE> <INDENT> self.metric_name = outs['metricName'] <NEW_LINE> <DEDENT> if 'name' in outs: <NEW_LINE> <INDENT> self.name = outs['name'] <NEW_LINE> <DEDENT> if 'predicates' in outs: <NEW_LINE> <INDENT> self.predicates = outs['predicates'] <NEW_LINE> <DEDENT> if 'rateKey' in outs: <NEW_LINE> <INDENT> self.rate_key = outs['rateKey'] <NEW_LINE> <DEDENT> if 'rateLimit' in outs: <NEW_LINE> <INDENT> self.rate_limit = outs['rateLimit']
Provides a WAF Rate Based Rule Resource
62598fb0097d151d1a2c1060
class SparkJob(_messages.Message): <NEW_LINE> <INDENT> @encoding.MapUnrecognizedFields('additionalProperties') <NEW_LINE> class PropertiesValue(_messages.Message): <NEW_LINE> <INDENT> class AdditionalProperty(_messages.Message): <NEW_LINE> <INDENT> key = _messages.StringField(1) <NEW_LINE> value = _messages.StringField(2) <NEW_LINE> <DEDENT> additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) <NEW_LINE> <DEDENT> archiveUris = _messages.StringField(1, repeated=True) <NEW_LINE> args = _messages.StringField(2, repeated=True) <NEW_LINE> fileUris = _messages.StringField(3, repeated=True) <NEW_LINE> jarFileUris = _messages.StringField(4, repeated=True) <NEW_LINE> loggingConfig = _messages.MessageField('LoggingConfig', 5) <NEW_LINE> mainClass = _messages.StringField(6) <NEW_LINE> mainJarFileUri = _messages.StringField(7) <NEW_LINE> properties = _messages.MessageField('PropertiesValue', 8)
A Cloud Dataproc job for running Apache Spark (http://spark.apache.org/) applications on YARN. Messages: PropertiesValue: Optional. A mapping of property names to values, used to configure Spark. Properties that conflict with values set by the Cloud Dataproc API may be overwritten. Can include properties set in /etc/spark/conf/spark-defaults.conf and classes in user code. Fields: archiveUris: Optional. HCFS URIs of archives to be extracted in the working directory of Spark drivers and tasks. Supported file types: .jar, .tar, .tar.gz, .tgz, and .zip. args: Optional. The arguments to pass to the driver. Do not include arguments, such as --conf, that can be set as job properties, since a collision may occur that causes an incorrect job submission. fileUris: Optional. HCFS URIs of files to be copied to the working directory of Spark drivers and distributed tasks. Useful for naively parallel tasks. jarFileUris: Optional. HCFS URIs of jar files to add to the CLASSPATHs of the Spark driver and tasks. loggingConfig: Optional. The runtime log config for job execution. mainClass: The name of the driver's main class. The jar file that contains the class must be in the default CLASSPATH or specified in jar_file_uris. mainJarFileUri: The HCFS URI of the jar file that contains the main class. properties: Optional. A mapping of property names to values, used to configure Spark. Properties that conflict with values set by the Cloud Dataproc API may be overwritten. Can include properties set in /etc/spark/conf/spark-defaults.conf and classes in user code.
62598fb099cbb53fe6830f0e
class Container(Instance): <NEW_LINE> <INDENT> klass = None <NEW_LINE> _cast_types = () <NEW_LINE> _valid_defaults = SequenceTypes <NEW_LINE> _trait = None <NEW_LINE> def __init__(self, trait=None, default_value=None, **metadata): <NEW_LINE> <INDENT> if default_value is None and not is_trait(trait): <NEW_LINE> <INDENT> default_value = trait <NEW_LINE> trait = None <NEW_LINE> <DEDENT> if default_value is None: <NEW_LINE> <INDENT> args = () <NEW_LINE> <DEDENT> elif isinstance(default_value, self._valid_defaults): <NEW_LINE> <INDENT> args = (default_value,) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value)) <NEW_LINE> <DEDENT> if is_trait(trait): <NEW_LINE> <INDENT> if isinstance(trait, type): <NEW_LINE> <INDENT> warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)", DeprecationWarning, stacklevel=3) <NEW_LINE> <DEDENT> self._trait = trait() if isinstance(trait, type) else trait <NEW_LINE> <DEDENT> elif trait is not None: <NEW_LINE> <INDENT> raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait)) <NEW_LINE> <DEDENT> super(Container,self).__init__(klass=self.klass, args=args, **metadata) <NEW_LINE> <DEDENT> def element_error(self, obj, element, validator): <NEW_LINE> <INDENT> e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." % (self.name, class_of(obj), validator.info(), repr_type(element)) <NEW_LINE> raise TraitError(e) <NEW_LINE> <DEDENT> def validate(self, obj, value): <NEW_LINE> <INDENT> if isinstance(value, self._cast_types): <NEW_LINE> <INDENT> value = self.klass(value) <NEW_LINE> <DEDENT> value = super(Container, self).validate(obj, value) <NEW_LINE> if value is None: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> value = self.validate_elements(obj, value) <NEW_LINE> return value <NEW_LINE> <DEDENT> def validate_elements(self, obj, value): <NEW_LINE> <INDENT> validated = [] <NEW_LINE> if self._trait is None or isinstance(self._trait, Any): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> for v in value: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> v = self._trait._validate(obj, v) <NEW_LINE> <DEDENT> except TraitError: <NEW_LINE> <INDENT> self.element_error(obj, v, self._trait) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> validated.append(v) <NEW_LINE> <DEDENT> <DEDENT> return self.klass(validated) <NEW_LINE> <DEDENT> def instance_init(self, obj): <NEW_LINE> <INDENT> if isinstance(self._trait, TraitType): <NEW_LINE> <INDENT> self._trait.this_class = self.this_class <NEW_LINE> self._trait.instance_init(obj) <NEW_LINE> <DEDENT> super(Container, self).instance_init(obj) <NEW_LINE> <DEDENT> def default_value_repr(self): <NEW_LINE> <INDENT> return repr(self.make_dynamic_default())
An instance of a container (list, set, etc.) To be subclassed by overriding klass.
62598fb05166f23b2e24340f
class DummySocket(HasTraits): <NEW_LINE> <INDENT> queue = Instance(Queue, ()) <NEW_LINE> message_sent = Int(0) <NEW_LINE> context = Instance(zmq.Context) <NEW_LINE> def _context_default(self): <NEW_LINE> <INDENT> return zmq.Context.instance() <NEW_LINE> <DEDENT> def recv_multipart(self, flags=0, copy=True, track=False): <NEW_LINE> <INDENT> return self.queue.get_nowait() <NEW_LINE> <DEDENT> def send_multipart(self, msg_parts, flags=0, copy=True, track=False): <NEW_LINE> <INDENT> msg_parts = list(map(zmq.Message, msg_parts)) <NEW_LINE> self.queue.put_nowait(msg_parts) <NEW_LINE> self.message_sent += 1
A dummy socket implementing (part of) the zmq.Socket interface.
62598fb067a9b606de546003
class Decide(callbacks.Plugin): <NEW_LINE> <INDENT> def __init__(self, irc): <NEW_LINE> <INDENT> self.__parent = super(Decide, self) <NEW_LINE> self.__parent.__init__(irc) <NEW_LINE> <DEDENT> def decide(self, irc, msg, args, timestamp, text): <NEW_LINE> <INDENT> time_quotient = timestamp / conf.supybot.plugins.Decide.interval() <NEW_LINE> rg = random.Random(str(time_quotient)+text.replace(' ', '')) <NEW_LINE> choices = text.split(conf.supybot.plugins.Decide.separator()) <NEW_LINE> choices = [s.strip() for s in choices] <NEW_LINE> if len(choices) == 1: <NEW_LINE> <INDENT> choices = ['Yes', 'No'] <NEW_LINE> <DEDENT> irc.reply(rg.choice(choices)) <NEW_LINE> <DEDENT> decide = wrap(decide, ['now', 'text'])
This plugin has only one command, 'decide'.
62598fb03346ee7daa337662
class EllipticEnvelop(OutlierDetectionMixin, MinCovDet): <NEW_LINE> <INDENT> def __init__(self, store_precision=True, assume_centered=False, support_fraction=None, contamination=0.1): <NEW_LINE> <INDENT> MinCovDet.__init__(self, store_precision=store_precision, assume_centered=assume_centered, support_fraction=support_fraction) <NEW_LINE> OutlierDetectionMixin.__init__(self, contamination=contamination) <NEW_LINE> <DEDENT> def fit(self, X): <NEW_LINE> <INDENT> MinCovDet.fit(self, X) <NEW_LINE> X_centered = X - self.location_ <NEW_LINE> values = self.mahalanobis(X_centered) <NEW_LINE> self.threshold = sp.stats.scoreatpercentile( values, 100. * (1. - self.contamination)) <NEW_LINE> return self
An object for detecting outliers in a Gaussian distributed dataset. Attributes ---------- `contamination`: float, 0. < contamination < 0.5 The amount of contamination of the data set, i.e. the proportion of outliers in the data set. `location_`: array-like, shape (n_features,) Estimated robust location `covariance_`: array-like, shape (n_features, n_features) Estimated robust covariance matrix `precision_`: array-like, shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) `support_`: array-like, shape (n_samples,) A mask of the observations that have been used to compute the robust estimates of location and shape. Parameters ---------- store_precision: bool Specify if the estimated precision is stored assume_centered: Boolean If True, the support of robust location and covariance estimates is computed, and a covariance estimate is recomputed from it, without centering the data. Useful to work with data whose mean is significantly equal to zero but is not exactly zero. If False, the robust location and covariance are directly computed with the FastMCD algorithm without additional treatment. support_fraction: float, 0 < support_fraction < 1 The proportion of points to be included in the support of the raw MCD estimate. Default is None, which implies that the minimum value of support_fraction will be used within the algorithm: [n_sample + n_features + 1] / 2 contamination: float, 0. < contamination < 0.5 The amount of contamination of the data set, i.e. the proportion of outliers in the data set. See Also -------- EmpiricalCovariance, MinCovDet Notes ----- Outlier detection from covariance estimation may break or not perform well in high-dimensional settings. In particular, one will always take care to work with n_samples > n_features ** 2.
62598fb0e1aae11d1e7ce83e
class DummyTime: <NEW_LINE> <INDENT> def __init__(self, curr_time, increment): <NEW_LINE> <INDENT> self.curr_time = curr_time <NEW_LINE> self.increment = increment <NEW_LINE> self.started = False <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.started = True <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.started: <NEW_LINE> <INDENT> self.curr_time += self.increment <NEW_LINE> <DEDENT> return self.curr_time
Mock replacement for time.time. Increases returned time on access.
62598fb085dfad0860cbfa8e
class Parrot: <NEW_LINE> <INDENT> species = "bird" <NEW_LINE> def __init__(self, name, age): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> def sing(self, song): <NEW_LINE> <INDENT> return "{} sings {}".format(self.name, song) <NEW_LINE> <DEDENT> def dance(self): <NEW_LINE> <INDENT> return "{} is now dancing".format(self.name)
This is a docstring for the parrot class
62598fb076e4537e8c3ef5dd
class gpgTool(RunEnvTool): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def envNames(self): <NEW_LINE> <INDENT> return ['gpgBin', 'gpgKeyServer'] <NEW_LINE> <DEDENT> def _installTool(self, env): <NEW_LINE> <INDENT> self._install.debrpm('gnupg') <NEW_LINE> self._install.debrpm('gnupg2') <NEW_LINE> self._install.debrpm('dirmngr') <NEW_LINE> self._install.emerge(['app-crypt/gnupg']) <NEW_LINE> self._install.pacman(['gnupg']) <NEW_LINE> self._install.apk(['gnupg']) <NEW_LINE> self._install.brew('gnupg') <NEW_LINE> <DEDENT> def initEnv(self, env): <NEW_LINE> <INDENT> super(gpgTool, self).initEnv(env) <NEW_LINE> env.setdefault('gpgKeyServer', 'hkp://keyserver.ubuntu.com:80') <NEW_LINE> if self._have_tool and self._detect.isDeb(): <NEW_LINE> <INDENT> self._have_tool = self._pathutil.which('dirmngr')
The GNU Privacy Guard. Home: https://www.gnupg.org/ gpgKeyServer is hkp://keyserver.ubuntu.com:80 by default
62598fb0e76e3b2f99fd8a6c
class account_invoice(models.Model): <NEW_LINE> <INDENT> _inherit = "account.invoice" <NEW_LINE> bvr_reference = fields.Char( "BVR REF.", size=32, track_visibility='onchange') <NEW_LINE> @api.constrains('bvr_reference') <NEW_LINE> def _check_bvr_ref(self): <NEW_LINE> <INDENT> for data in self: <NEW_LINE> <INDENT> if not data.bvr_reference: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> clean_ref = data.bvr_reference.replace(' ', '') <NEW_LINE> if not clean_ref.isdigit() or len(clean_ref) > 27: <NEW_LINE> <INDENT> raise exceptions.ValidationError('Error: BVR ref should only' + 'contain number (max. 27) ' + 'and spaces.') <NEW_LINE> <DEDENT> clean_ref = clean_ref.rjust(27, '0') <NEW_LINE> if not clean_ref == mod10r(clean_ref[0:26]): <NEW_LINE> <INDENT> raise exceptions.ValidationError('Invalid BVR ref number. ' + 'Please check the number.') <NEW_LINE> <DEDENT> <DEDENT> return True
Inherit account.invoice in order to change BVR ref field type
62598fb0442bda511e95c48e
class GenericBloomFilter(object): <NEW_LINE> <INDENT> def __init__(self, capacity, error_rate=0.01): <NEW_LINE> <INDENT> self.capacity = capacity <NEW_LINE> self.error_rate = error_rate <NEW_LINE> self.bf = None <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self.bf <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.bf) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(self.bf) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.bf) <NEW_LINE> <DEDENT> def add(self, key): <NEW_LINE> <INDENT> return self.bf.add(key) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_temp_file(): <NEW_LINE> <INDENT> tempdir = get_temp_dir() <NEW_LINE> if not os.path.exists(tempdir): <NEW_LINE> <INDENT> os.makedirs(tempdir) <NEW_LINE> <DEDENT> filename = ''.join([choice(string.letters) for _ in range(12)]) <NEW_LINE> temp_file = os.path.join(tempdir, filename + '-w3af.bloom') <NEW_LINE> return temp_file
A simple "interface like" class to define how a bloom filter should look like, methods, attributes, etc. The idea is to give a consistent API to all the other sections of the code and allow the use of different bloom filter implementations.
62598fb0fff4ab517ebcd81b
class CustomScreen(UssdHandlerAbstract): <NEW_LINE> <INDENT> screen_type = "custom_screen" <NEW_LINE> serializer = CustomScreenSchema <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CustomScreen, self).__init__(*args, **kwargs) <NEW_LINE> self.custom_screen_instance = str_to_class( self.screen_content['screen_obj'] )( self.ussd_request, self.handler, self.screen_content, initial_screen={}, ) <NEW_LINE> <DEDENT> def handle(self): <NEW_LINE> <INDENT> return self.custom_screen_instance.handle() <NEW_LINE> <DEDENT> def show_ussd_content(self, **kwargs): <NEW_LINE> <INDENT> if self.custom_screen_instance.__class__.__dict__.get('show_ussd_content'): <NEW_LINE> <INDENT> return self.custom_screen_instance.show_ussd_content() <NEW_LINE> <DEDENT> return "custom_screen\n{}".format(self.screen_content['screen_obj']) <NEW_LINE> <DEDENT> def get_next_screens(self) -> typing.List[Link]: <NEW_LINE> <INDENT> if self.custom_screen_instance.__class__.__dict__.get('get_next_screens'): <NEW_LINE> <INDENT> return self.custom_screen_instance.get_next_screens() <NEW_LINE> <DEDENT> return [ Link(Vertex(self.handler), Vertex(self.screen_content['next_screen']), self.screen_content['input_identifier'])]
If you have a particular user case that's not yet covered by our existing screens, this is the screen to use. This screen allows us to define our own ussd screen. To create it you need the following fields. 1. screen_object This is the path to be used to import the class 2. serializer (optional) This if you want to be validating your screen with specific fields 3. You can define any field that you feel your custom screen might need. EXAMPLE: examples of custom screen .. code-block:: python class SampleCustomHandler1(UssdHandlerAbstract): abstract = True # don't register custom classes @staticmethod def show_ussd_content(): # This method doesn't have to be static # Do anything custom here. return UssdResponse("This is a custom Handler1") def handle_ussd_input(self, ussd_input): # Do anything custom here print(ussd_input) # pep 8 for the sake of using it. return self.ussd_request.forward('custom_screen_2') class SampleSerializer(UssdBaseSerializer, NextUssdScreenSerializer): input_identifier = serializers.CharField(max_length=100) class SampleCustomHandlerWithSerializer(UssdHandlerAbstract): abstract = True # don't register custom classes serializer = SampleSerializer @staticmethod def show_ussd_content(): # This method doesn't have to be static return "Enter a digit and it will be doubled on your behalf" def handle_ussd_input(self, ussd_input): self.ussd_request.session[ self.screen_content['input_identifier'] ] = int(ussd_input) * 2 return self.ussd_request.forward( self.screen_content['next_screen'] ) example of defining a yaml .. literalinclude:: .././ussd/tests/sample_screen_definition/valid_menu_screen_conf.yml
62598fb01b99ca400228f54b
class Encoder(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_shape, n_blocks=4, nz_feat=100, batch_norm=True, input_coord=False, pretrained=True): <NEW_LINE> <INDENT> super(Encoder, self).__init__() <NEW_LINE> if input_coord: <NEW_LINE> <INDENT> self.resnet_conv = ResNetCoord(n_blocks=4) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.resnet_conv = ResNetConv(n_blocks=4, pretrained=pretrained) <NEW_LINE> <DEDENT> self.enc_conv1 = nb.conv2d(batch_norm, 512, 256, stride=2, kernel_size=4) <NEW_LINE> nc_input = 256 * (input_shape[0] // 64) * (input_shape[1] // 64) <NEW_LINE> self.enc_fc = nb.fc_stack(nc_input, nz_feat, 2) <NEW_LINE> nb.net_init(self.enc_conv1) <NEW_LINE> <DEDENT> def forward(self, img): <NEW_LINE> <INDENT> resnet_feat = self.resnet_conv(img) <NEW_LINE> out_enc_conv1 = self.enc_conv1(resnet_feat) <NEW_LINE> out_enc_conv1 = out_enc_conv1.view(img.size(0), -1) <NEW_LINE> feat = self.enc_fc(out_enc_conv1) <NEW_LINE> return feat
Current: Resnet with 4 blocks (x32 spatial dim reduction) Another conv with stride 2 (x64) This is sent to 2 fc layers with final output nz_feat.
62598fb0ac7a0e7691f7253f
class BtihResolver(NameResolverDir): <NEW_LINE> <INDENT> namespace="btih" <NEW_LINE> def __init__(self, namespace, hash, **kwargs): <NEW_LINE> <INDENT> verbose=kwargs.get("verbose") <NEW_LINE> if verbose: <NEW_LINE> <INDENT> logging.debug("{0}.__init__({1}, {2}, {3})".format(self.__class__.__name__, namespace, hash, kwargs)) <NEW_LINE> <DEDENT> if namespace != self.namespace: <NEW_LINE> <INDENT> raise CodingException(message="namespace != "+self.namespace) <NEW_LINE> <DEDENT> super(BtihResolver, self).__init__(self, namespace, hash, **kwargs) <NEW_LINE> self.btih = hash <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def new(cls, namespace, hash, *args, **kwargs): <NEW_LINE> <INDENT> verbose=kwargs.get("verbose") <NEW_LINE> ch = super(BtihResolver, cls).new(namespace, hash, *args, **kwargs) <NEW_LINE> return ch <NEW_LINE> <DEDENT> def itemid(self, verbose=False, **kwargs): <NEW_LINE> <INDENT> searchurl = config["archive"]["url_btihsearch"] + self.btih <NEW_LINE> searchres = loads(httpget(searchurl)) <NEW_LINE> if not searchres["response"]["numFound"]: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return searchres["response"]["docs"][0]["identifier"] <NEW_LINE> <DEDENT> def retrieve(self, verbose=False, **kwargs): <NEW_LINE> <INDENT> raise ToBeImplementedException("btih retrieve") <NEW_LINE> <DEDENT> def content(self, verbose=False, **kwargs): <NEW_LINE> <INDENT> data = self.retrieve() <NEW_LINE> if verbose: logging.debug("Retrieved doc size={}".format(len(data))) <NEW_LINE> return {'Content-type': self.mimetype, 'data': data, } <NEW_LINE> <DEDENT> def metadata(self, headers=True, verbose=False, **kwargs): <NEW_LINE> <INDENT> raise ToBeImplementedException(name="btih.metadata()") <NEW_LINE> <DEDENT> def magnetlink(self, verbose=False, headers=False, **kwargs): <NEW_LINE> <INDENT> magnetlink = MagnetLinkService.btihget(self.btih) <NEW_LINE> data = magnetlink or "" <NEW_LINE> return {"Content-type": "text/plain", "data": data} if headers else data <NEW_LINE> <DEDENT> def torrenturl(self, verbose=False): <NEW_LINE> <INDENT> itemid = self.itemid(verbose=verbose) <NEW_LINE> if not itemid: <NEW_LINE> <INDENT> raise NoContentException() <NEW_LINE> <DEDENT> return "https://archive.org/download/{}/{}_archive.torrent".format(itemid, itemid) <NEW_LINE> <DEDENT> def torrent(self, verbose=False, headers=False, **kwargs): <NEW_LINE> <INDENT> torrenturl = self.torrenturl(verbose=verbose) <NEW_LINE> data = bencode.bencode(ArchiveItem.modifiedtorrent(self.itemid(), wantmodified=True, verbose=verbose)) <NEW_LINE> mimetype = "application/x-bittorrent" <NEW_LINE> return {"Content-type": mimetype, "data": data} if headers else data
Resolve BitTorrent Hashes Fields: btih # BitTorrent hash - in ascii B32 format This could also easily be extended to Support "magnetlink" as the thing being looked for (and return btih and other outputs) Support outputs of itemid, metadata (of item)
62598fb0e5267d203ee6b93f
class Index(PynamoDBIndex): <NEW_LINE> <INDENT> Meta = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> if self.Meta is None: <NEW_LINE> <INDENT> raise ValueError("Indexes require a Meta class for settings") <NEW_LINE> <DEDENT> if not hasattr(self.Meta, "projection"): <NEW_LINE> <INDENT> raise ValueError("No projection defined, define a projection for this class") <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> async def count(cls, hash_key, range_key_condition=None, filter_condition=None, consistent_read=False, **filters): <NEW_LINE> <INDENT> return await cls.Meta.model.count( hash_key, range_key_condition=range_key_condition, filter_condition=filter_condition, index_name=cls.Meta.index_name, consistent_read=consistent_read, **filters ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def query(self, hash_key, range_key_condition=None, filter_condition=None, scan_index_forward=None, consistent_read=False, limit=None, last_evaluated_key=None, attributes_to_get=None, **filters): <NEW_LINE> <INDENT> return await self.Meta.model.query( hash_key, range_key_condition=range_key_condition, filter_condition=filter_condition, index_name=self.Meta.index_name, scan_index_forward=scan_index_forward, consistent_read=consistent_read, limit=limit, last_evaluated_key=last_evaluated_key, attributes_to_get=attributes_to_get, **filters ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def scan(cls, filter_condition=None, segment=None, total_segments=None, limit=None, last_evaluated_key=None, page_size=None, consistent_read=None, **filters): <NEW_LINE> <INDENT> return await cls.Meta.model.scan( filter_condition=filter_condition, segment=segment, total_segments=total_segments, limit=limit, last_evaluated_key=last_evaluated_key, page_size=page_size, consistent_read=consistent_read, index_name=cls.Meta.index_name, **filters )
Base class for secondary indexes
62598fb023849d37ff8510ea
class Reflect3D(Reflect2D): <NEW_LINE> <INDENT> def __init__(self, xl, xr, yl, yr, zl, zr): <NEW_LINE> <INDENT> self.dim = 3 <NEW_LINE> self.boundaries = [ [xl, xr], [yl, yr], [zl, zr] ] <NEW_LINE> <DEDENT> def reverse_velocities(self, particles, primitive, particles_index): <NEW_LINE> <INDENT> ghost_indices = particles_index["ghost"] <NEW_LINE> xl = self.boundaries[0][0] <NEW_LINE> xr = self.boundaries[0][1] <NEW_LINE> x = particles[0,ghost_indices] <NEW_LINE> i = np.where((x < xl) | (xr < x))[0] <NEW_LINE> primitive[1, ghost_indices[i]] *= -1.0 <NEW_LINE> yl = self.boundaries[1][0] <NEW_LINE> yr = self.boundaries[1][1] <NEW_LINE> y = particles[1,ghost_indices] <NEW_LINE> i = np.where((y < yl) | (yr < y))[0] <NEW_LINE> primitive[2, ghost_indices[i]] *= -1.0 <NEW_LINE> zl = self.boundaries[2][0] <NEW_LINE> zr = self.boundaries[2][1] <NEW_LINE> z = particles[2,ghost_indices] <NEW_LINE> i = np.where((z < zl) | (zr < z))[0] <NEW_LINE> primitive[3, ghost_indices[i]] *= -1.0 <NEW_LINE> <DEDENT> def primitive_to_ghost(self, particles, primitive, particles_index): <NEW_LINE> <INDENT> primitive = super(Reflect3D, self).primitive_to_ghost(particles, primitive, particles_index) <NEW_LINE> self.reverse_velocities(particles, primitive, particles_index) <NEW_LINE> return primitive <NEW_LINE> <DEDENT> def gradient_to_ghost(self, particles, grad, particles_index): <NEW_LINE> <INDENT> new_grad = super(Reflect3D, self).gradient_to_ghost(particles, grad, particles_index) <NEW_LINE> ghost_indices = particles_index["ghost"] <NEW_LINE> return new_grad
3d refect boundary class
62598fb04e4d56256637245d
@api.route("/<int:service_id>") <NEW_LINE> @api.response(404, "service_id not found") <NEW_LINE> @api.param("service_id", "The service identifier") <NEW_LINE> class Service(Resource): <NEW_LINE> <INDENT> @api.marshal_with(service_model) <NEW_LINE> def get(self, service_id): <NEW_LINE> <INDENT> service = get_service(service_id) <NEW_LINE> if service is None: <NEW_LINE> <INDENT> api.abort(404) <NEW_LINE> <DEDENT> return service <NEW_LINE> <DEDENT> @api.response(204, "Service deleted") <NEW_LINE> def delete(self, service_id): <NEW_LINE> <INDENT> result = delete_service(service_id) <NEW_LINE> if not result: <NEW_LINE> <INDENT> api.abort(404) <NEW_LINE> <DEDENT> return "", 204
Show a single service item and lets you delete it.
62598fb0e5267d203ee6b940
class FindProductsInputSet(InputSet): <NEW_LINE> <INDENT> def set_AppID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AppID', value) <NEW_LINE> <DEDENT> def set_AvailableItemsOnly(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AvailableItemsOnly', value) <NEW_LINE> <DEDENT> def set_CategoryID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'CategoryID', value) <NEW_LINE> <DEDENT> def set_DomainName(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'DomainName', value) <NEW_LINE> <DEDENT> def set_HideDuplicateItems(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'HideDuplicateItems', value) <NEW_LINE> <DEDENT> def set_IncludeSelector(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'IncludeSelector', value) <NEW_LINE> <DEDENT> def set_MaxEntries(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'MaxEntries', value) <NEW_LINE> <DEDENT> def set_PageNumber(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'PageNumber', value) <NEW_LINE> <DEDENT> def set_ProductID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ProductID', value) <NEW_LINE> <DEDENT> def set_ProductSort(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ProductSort', value) <NEW_LINE> <DEDENT> def set_QueryKeywords(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'QueryKeywords', value) <NEW_LINE> <DEDENT> def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ResponseFormat', value) <NEW_LINE> <DEDENT> def set_SandboxMode(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'SandboxMode', value) <NEW_LINE> <DEDENT> def set_SiteID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'SiteID', value) <NEW_LINE> <DEDENT> def set_SortOrder(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'SortOrder', value)
An InputSet with methods appropriate for specifying the inputs to the FindProducts Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62598fb07047854f4633f411
class JsonWebKeyOperation(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> ENCRYPT = "encrypt" <NEW_LINE> DECRYPT = "decrypt" <NEW_LINE> SIGN = "sign" <NEW_LINE> VERIFY = "verify" <NEW_LINE> WRAP_KEY = "wrapKey" <NEW_LINE> UNWRAP_KEY = "unwrapKey" <NEW_LINE> IMPORT_ENUM = "import" <NEW_LINE> RELEASE = "release"
The permitted JSON web key operations of the key. For more information, see JsonWebKeyOperation.
62598fb05fc7496912d4829c
class Grid2LSTMCell(GridRNNCell): <NEW_LINE> <INDENT> def __init__(self, num_units, tied=False, non_recurrent_fn=None, use_peepholes=False, forget_bias=1.0): <NEW_LINE> <INDENT> super(Grid2LSTMCell, self).__init__( num_units=num_units, num_dims=2, input_dims=0, output_dims=0, priority_dims=0, tied=tied, non_recurrent_dims=None if non_recurrent_fn is None else 0, cell_fn=lambda n, i: rnn.LSTMCell( num_units=n, input_size=i, forget_bias=forget_bias, use_peepholes=use_peepholes, state_is_tuple=False), non_recurrent_fn=non_recurrent_fn)
2D LSTM cell This creates a 2D cell which receives input and gives output in the first dimension. The first dimension can optionally be non-recurrent if `non_recurrent_fn` is specified.
62598fb03539df3088ecc2e9
class IdentifierEndpoint(IsThereAnyDealErrorResponse): <NEW_LINE> <INDENT> def __init__(self, response_dict): <NEW_LINE> <INDENT> super().__init__(response_dict) <NEW_LINE> self.plain = None <NEW_LINE> if 'data' in response_dict and response_dict['data']: <NEW_LINE> <INDENT> self.plain = response_dict['data'].get('plain')
IsThereAnyDeal API Identifier endpoint parser All properties can be None if the value can't be retrieved from the IsThereAnyDeal API Attributes ---------- plain : str or None IsThereAnyDeal API game identifier
62598fb08e7ae83300ee90d9
class LdapError(Exception): <NEW_LINE> <INDENT> def __init__(self, msg): <NEW_LINE> <INDENT> self.msg = msg <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.msg
exception about ldap update.
62598fb0f7d966606f74801c
class PUTAttachmentType(object): <NEW_LINE> <INDENT> swagger_types = { 'description': 'str', 'file_name': 'str' } <NEW_LINE> attribute_map = { 'description': 'description', 'file_name': 'fileName' } <NEW_LINE> def __init__(self, description=None, file_name=None): <NEW_LINE> <INDENT> self._description = None <NEW_LINE> self._file_name = None <NEW_LINE> self.discriminator = None <NEW_LINE> if description is not None: <NEW_LINE> <INDENT> self.description = description <NEW_LINE> <DEDENT> if file_name is not None: <NEW_LINE> <INDENT> self.file_name = file_name <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self._description <NEW_LINE> <DEDENT> @description.setter <NEW_LINE> def description(self, description): <NEW_LINE> <INDENT> self._description = description <NEW_LINE> <DEDENT> @property <NEW_LINE> def file_name(self): <NEW_LINE> <INDENT> return self._file_name <NEW_LINE> <DEDENT> @file_name.setter <NEW_LINE> def file_name(self, file_name): <NEW_LINE> <INDENT> self._file_name = file_name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.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 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, PUTAttachmentType): <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.
62598fb04a966d76dd5eef0e
class JSONEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> if isinstance(o, datetime): <NEW_LINE> <INDENT> return o.isoformat() <NEW_LINE> <DEDENT> elif isinstance(o, set): <NEW_LINE> <INDENT> return list(o) <NEW_LINE> <DEDENT> elif hasattr(o, 'as_dict'): <NEW_LINE> <INDENT> return o.as_dict() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return json.JSONEncoder.default(self, o) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return [self.default(child_obj) for child_obj in o] <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return json.JSONEncoder.default(self, o)
JSONEncoder that supports Home Assistant objects.
62598fb08da39b475be0321d
class RefExpr(object): <NEW_LINE> <INDENT> def __init__(self, expr_or_var): <NEW_LINE> <INDENT> self.expr = expr_or_var <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_var(self): <NEW_LINE> <INDENT> return type(self.expr) is str <NEW_LINE> <DEDENT> def printables(self): <NEW_LINE> <INDENT> yield 0, "Ref:" <NEW_LINE> yield 1, self.expr.printables() <NEW_LINE> <DEDENT> def __eq__(self, another): <NEW_LINE> <INDENT> return self.expr == another.expr
This expression both captures a reference to a cell as well as a reference to a variable.
62598fb067a9b606de546004
class register: <NEW_LINE> <INDENT> url="" <NEW_LINE> phone = "" <NEW_LINE> password = "" <NEW_LINE> authCode = "" <NEW_LINE> inviteCode = "" <NEW_LINE> X_Type= "" <NEW_LINE> code = ""
request
62598fb05166f23b2e243411
@dataclass <NEW_LINE> class EventDetails: <NEW_LINE> <INDENT> sports_mode: SportsMode <NEW_LINE> track: str <NEW_LINE> laps: int <NEW_LINE> maximum_players: int <NEW_LINE> start_type: str <NEW_LINE> car_category: list <NEW_LINE> leaderboard_id: str <NEW_LINE> raw_data: dict = None <NEW_LINE> @classmethod <NEW_LINE> def from_json(cls, json_data): <NEW_LINE> <INDENT> event_infos = json_data["event"][0]["value"][0]["GameParameter"]["events"][0] <NEW_LINE> track_infos = json_data["event"][0]["value"][0]["GameParameter"]["tracks"][0] <NEW_LINE> instance = cls( sports_mode=SportsMode.from_one_line_title(event_infos["information"]["one_line_title"]["US"]), track=localization.get_track_name_by_course_code(track_infos["course_code"]), laps=event_infos["race"]["race_limit_laps"], maximum_players=event_infos["race"]["entry_max"], start_type=event_infos["race"]["start_type"], car_category=event_infos["regulation"]["car_category_types"], leaderboard_id=event_infos["ranking"]["board_id"] ) <NEW_LINE> instance.raw_data = json_data <NEW_LINE> return instance <NEW_LINE> <DEDENT> def dump_json(self, filename): <NEW_LINE> <INDENT> if self.raw_data is None: <NEW_LINE> <INDENT> raise ValueError("No raw data stored (probably not created from json), cannot dump") <NEW_LINE> <DEDENT> with open(filename, "w") as outfile: <NEW_LINE> <INDENT> json.dump(self.raw_data, outfile)
Detailed information of a single race event.
62598fb0dd821e528d6d8f6c
class AggregratedTopPlayers: <NEW_LINE> <INDENT> _endpoint = 'topscorers' <NEW_LINE> _include = ['aggregratedGoalscorers.player', 'aggregratedGoalscorers.team', 'aggregratedCardscorers.player', 'aggregratedCardscorers.team', 'aggregratedAssistscorers.player', 'aggregratedAssistscorers.team'] <NEW_LINE> def __init__(self, season_id, api_key, **kwargs): <NEW_LINE> <INDENT> endpoint = _form_endpoint([self._endpoint, 'season', season_id]) <NEW_LINE> self.json = _get_json(endpoint = endpoint, api_key=api_key, include={'include': self._include}) <NEW_LINE> <DEDENT> def info(self): <NEW_LINE> <INDENT> return _api_scrape(self.json, key=['data'], exclude=['aggregratedGoalscorers', 'aggregratedCardscorers', 'aggregratedAssistantscorers']) <NEW_LINE> <DEDENT> def goalscorers(self): <NEW_LINE> <INDENT> return _api_scrape(self.json, key=['data', 'aggregratedGoalscorers'], exclude=None) <NEW_LINE> <DEDENT> def cardscorers(self): <NEW_LINE> <INDENT> return _api_scrape(self.json, key=['data', 'aggregratedCardscorers'], exclude=None) <NEW_LINE> <DEDENT> def assistscorers(self): <NEW_LINE> <INDENT> return _api_scrape(self.json, key=['data', 'aggregratedAssistantscorers'], exclude=None)
Overview: Gets a list of top players for each country from the initial players list Input: Output: Notes: Add stage_id parameter
62598fb04428ac0f6e65855d
class IESDRTFile(form.Schema, IImageScaleTraversable): <NEW_LINE> <INDENT> title = schema.TextLine( title=_(u'Title'), required=False, ) <NEW_LINE> form.primary('file') <NEW_LINE> file = NamedBlobFile( title=_(u'File'), required=True, )
Files with special needs
62598fb067a9b606de546005
class LayerAttributesMangler(DefaultMangler): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> return json.JSONEncoder.default(self, obj) <NEW_LINE> <DEDENT> def decode(self, json_string): <NEW_LINE> <INDENT> default_obj = super(LayerAttributesMangler, self).decode(json_string) <NEW_LINE> for obj in default_obj: <NEW_LINE> <INDENT> obj['pk'] = obj['pk'] + self.basepk <NEW_LINE> obj['fields']['layer'] = obj['fields']['layer'] + self.basepk <NEW_LINE> <DEDENT> return default_obj
TODO
62598fb0a8370b77170f0413
class PurchasableState(Enum): <NEW_LINE> <INDENT> PURCHASABLE = "PURCHASABLE" <NEW_LINE> NOT_PURCHASABLE = "NOT_PURCHASABLE" <NEW_LINE> def to_dict(self): <NEW_LINE> <INDENT> result = {self.name: self.value} <NEW_LINE> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.value) <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, PurchasableState): <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
State determining if the product is purchasable by the user. Note - Any new values introduced later should be treated as &#39;NOT_PURCHASABLE&#39;. * &#39;PURCHASABLE&#39; - The product is purchasable by the user. * &#39;NOT_PURCHASABLE&#39; - The product is not purchasable by the user. Allowed enum values: [PURCHASABLE, NOT_PURCHASABLE]
62598fb03346ee7daa337663
class Base: <NEW_LINE> <INDENT> def __init__(self, test_mode=False): <NEW_LINE> <INDENT> self.resources_path = 'resources' <NEW_LINE> self.plugins_path = 'plugins' <NEW_LINE> self.init_multiplatform_python_paths() <NEW_LINE> if test_mode: <NEW_LINE> <INDENT> self.run_mode = 'test' <NEW_LINE> self.default_userspace_path = tempfile.gettempdir() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parent = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) <NEW_LINE> if parent.endswith('Kataja') and os.path.isfile(os.path.join(parent, 'VERSION')): <NEW_LINE> <INDENT> self.run_mode = 'source' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.run_mode = 'dist' <NEW_LINE> <DEDENT> self.default_userspace_path = '.' <NEW_LINE> <DEDENT> self.fonts = linux_fonts <NEW_LINE> self.cmd_or_ctrl = 'Ctrl' <NEW_LINE> <DEDENT> def switch_to_test_mode(self): <NEW_LINE> <INDENT> self.run_mode = 'test' <NEW_LINE> self.default_userspace_path = tempfile.gettempdir() <NEW_LINE> <DEDENT> def init_multiplatform_python_paths(self): <NEW_LINE> <INDENT> full_path_to_this_file = os.path.realpath(__file__) <NEW_LINE> filename = os.path.basename(__file__) <NEW_LINE> package_cut = os.path.join('environments', filename) <NEW_LINE> package_root = full_path_to_this_file[:-len(package_cut)] <NEW_LINE> source_cut = os.path.join('kataja', 'environments', filename) <NEW_LINE> source_root = full_path_to_this_file[:-len(source_cut)] <NEW_LINE> self.resources_path = os.path.join(package_root, 'resources') <NEW_LINE> self.plugins_path = os.path.join(source_root, 'plugins') <NEW_LINE> print('resources_path: ', self.resources_path) <NEW_LINE> print('plugins_path: ', self.plugins_path)
Default fonts and resource paths. These are used when running in Linux and as a base for Mac/Win
62598fb0009cb60464d01558
class connectBoxClass: <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> self.builder = hf.load_interface(__file__, 'glade/connectBox.glade') <NEW_LINE> self.save_objects() <NEW_LINE> self.builder.connect_signals(self.setup_signals()) <NEW_LINE> hf.center(self.window, self.parent.window) <NEW_LINE> self.window.show_all() <NEW_LINE> self.entry.grab_focus() <NEW_LINE> <DEDENT> def setup_signals(self): <NEW_LINE> <INDENT> sig = { 'on_mainwindow_destroy': self.close , 'on_entry_activate' : self.connect , 'on_spinbutton_activate': self.connect , 'on_connect_clicked' : self.connect , 'on_cancel_clicked' : self.close } <NEW_LINE> return sig <NEW_LINE> <DEDENT> def save_objects(self): <NEW_LINE> <INDENT> self.window = self.builder.get_object('mainwindow') <NEW_LINE> self.entry = self.builder.get_object('entry') <NEW_LINE> self.spinbutton = self.builder.get_object('spinbutton') <NEW_LINE> self.check = self.builder.get_object('checkbutton') <NEW_LINE> <DEDENT> def connect(self, button): <NEW_LINE> <INDENT> entry = self.entry <NEW_LINE> buf = entry.get_buffer() <NEW_LINE> host = buf.get_text() <NEW_LINE> if not host or not hf.validate_host(host): <NEW_LINE> <INDENT> entry.grab_focus() <NEW_LINE> return <NEW_LINE> <DEDENT> spin = self.spinbutton <NEW_LINE> buf_spin = spin.get_buffer() <NEW_LINE> port = buf_spin.get_text() <NEW_LINE> if not port: <NEW_LINE> <INDENT> spin.grab_focus() <NEW_LINE> return <NEW_LINE> <DEDENT> port = int(port) <NEW_LINE> obj = self.parent.get_clientobj() <NEW_LINE> result, factory = True, None <NEW_LINE> if self.check.get_active(): <NEW_LINE> <INDENT> result, lisport, factory = startserver.listen(host, port) <NEW_LINE> <DEDENT> if result: <NEW_LINE> <INDENT> if factory: <NEW_LINE> <INDENT> obj.set_factory(lisport, factory) <NEW_LINE> <DEDENT> self.parent.connect(host, port, obj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obj.updateView('server', __servfail__) <NEW_LINE> <DEDENT> self.close() <NEW_LINE> <DEDENT> def close(self, *args): <NEW_LINE> <INDENT> self.window.destroy()
Sets up Connect Box
62598fb0d486a94d0ba2c007
class rule_500(Rule): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Rule.__init__(self, 'case_generate_statement', '500', lTokens) <NEW_LINE> self.groups.append('case::keyword')
This rule checks the *case* keyword has proper case. |configuring_uppercase_and_lowercase_rules_link| **Violation** .. code-block:: vhdl CASE expression generate **Fix** .. code-block:: vhdl case expression generate
62598fb056ac1b37e6302223
class UTCtoUT1Warning(MJDWarning): <NEW_LINE> <INDENT> pass
A sub-class of MJDWarning meant for use when astropy.Time cannot interpolate UT1-UTC as a function of UTC because UTC is out of bounds of the data. This class exists so that users can filter these warnings out by creating a simple filter targeted at category=UTCtoUT1Warning.
62598fb0be7bc26dc9251e79
class Command(BaseCommand): <NEW_LINE> <INDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> if not settings.API_SCHEMA_FILE: <NEW_LINE> <INDENT> logger.error( 'API_SCHEMA_FILE is not defined in settings. Aborting.' ) <NEW_LINE> return <NEW_LINE> <DEDENT> if not os.path.exists(settings.API_SCHEMA_FILE): <NEW_LINE> <INDENT> logger.error( 'YAML API schema file "{}" does not exist. Aborting.' .format(settings.API_SCHEMA_FILE) ) <NEW_LINE> return <NEW_LINE> <DEDENT> with open(settings.API_SCHEMA_FILE, 'r') as f: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> schema = yaml.load(f) <NEW_LINE> <DEDENT> except yaml.YAMLError as e: <NEW_LINE> <INDENT> logger.error( "There's a problem with your YAML schema file: {}. " "Aborting.".format(e) ) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> if settings.SCROOGE_HOST: <NEW_LINE> <INDENT> schema['host'] = settings.SCROOGE_HOST <NEW_LINE> <DEDENT> elif not schema['host']: <NEW_LINE> <INDENT> logger.error( "You don't have 'SCROOGE_HOST' defined in your settings and " "'host' field in your API schema is empty as well. Aborting." ) <NEW_LINE> return <NEW_LINE> <DEDENT> json_schema_filename = os.path.splitext( os.path.basename(settings.API_SCHEMA_FILE) )[0] + '.json' <NEW_LINE> json_schema_file = os.path.join( os.path.dirname(settings.API_SCHEMA_FILE), json_schema_filename ) <NEW_LINE> with open(json_schema_file, 'w') as f: <NEW_LINE> <INDENT> json.dump(schema, f, separators=(',', ':'), ensure_ascii=False) <NEW_LINE> <DEDENT> logger.info( 'JSON API schema saved successfully as: {}' .format(json_schema_file) )
Generates JSON schema file from it's YAML counterpart identified by `API_SCHEMA_FILE`, which is expected to be present in settings. Previous version of such JSON schema will be overwritten. This command should be executed at every change of schema, as well as when Scrooge is installed.
62598fb085dfad0860cbfa8f
class TestLinks(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 testLinks(self): <NEW_LINE> <INDENT> model = picketer.models.links.Links()
Links unit test stubs
62598fb0a8370b77170f0414
class StratNcaggVersion(Strat): <NEW_LINE> <INDENT> def process(self, attr, nc_obj=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def finalize(self, nc_out): <NEW_LINE> <INDENT> return pkg_resources.require("ncagg")[0].version
Include an attribute indicating what version of ncagg was used.
62598fb063d6d428bbee27e4
class ArchiveError(Exception): <NEW_LINE> <INDENT> pass
Internal error handling of this script
62598fb0379a373c97d9904c
class VoiceLogConfig(SectionView): <NEW_LINE> <INDENT> voice_text_channel_map: Dict[str, str] <NEW_LINE> role_voice: str
:ivar voice_text_channel_map: Map of channel IDs, from voice channel to text channel. :ivar role_voice: The voice channel role to set for voice users.
62598fb0adb09d7d5dc0a5c3
class CommandRunner(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.commands = {} <NEW_LINE> self.command('help', self.cmd_help) <NEW_LINE> <DEDENT> def command(self, name, fn): <NEW_LINE> <INDENT> self.commands[name] = fn <NEW_LINE> <DEDENT> def cmd_help(self, *args): <NEW_LINE> <INDENT> return '\n'.join( [ '{}\t-\t{}'.format(nm, fn.__doc__) for nm, fn in self.commands.items() ] ) <NEW_LINE> <DEDENT> def run(self, line): <NEW_LINE> <INDENT> tokens = shlex.split(line, comments=True) <NEW_LINE> try: <NEW_LINE> <INDENT> command, args = tokens[0], tokens[1:] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if command not in self.commands: <NEW_LINE> <INDENT> print('{}: no such command'.format(command), file=stderr) <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result = self.commands[command](*args) <NEW_LINE> if result is not None: <NEW_LINE> <INDENT> puts(colored.magenta(result)) <NEW_LINE> <DEDENT> <DEDENT> except TypeError as e: <NEW_LINE> <INDENT> raise <NEW_LINE> puts(colored.red(str(e)))
Simple demo.
62598fb0fff4ab517ebcd81d
class NotificationResponse(SuccessResponse): <NEW_LINE> <INDENT> ok = True <NEW_LINE> def __init__(self) -> None: <NEW_LINE> <INDENT> super().__init__(jsonrpc="2.0", result=None, id=NOID) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "<NotificationResponse()>" <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return ""
Represents a JSON-RPC notification response object.
62598fb001c39578d7f12db7
class User(BaseModel): <NEW_LINE> <INDENT> email = "" <NEW_LINE> password = "" <NEW_LINE> first_name = "" <NEW_LINE> last_name = "" <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs)
User Attributes
62598fb02ae34c7f260ab11a
class TestPlaceholderShownQuirks(TestPlaceholderShown): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.purge() <NEW_LINE> self.quirks = True
Test placeholder shown selectors with quirks.
62598fb0fff4ab517ebcd81e
class LoginView(View, MonthCalendarMixin): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> form = LoginForm() <NEW_LINE> return render(request, 'accounts/login.html', {'form':form}) <NEW_LINE> <DEDENT> """create method for post request""" <NEW_LINE> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> form = LoginForm(request.POST) <NEW_LINE> if not form.is_valid(): <NEW_LINE> <INDENT> return render(request, 'accounts/login.html', {'form': form}) <NEW_LINE> <DEDENT> login_user = form.get_login_user() <NEW_LINE> auth_login(request, login_user) <NEW_LINE> now = datetime.today() <NEW_LINE> kwargs['month'] = now.month <NEW_LINE> kwargs['year'] = now.year <NEW_LINE> kwargs['day'] = now.day <NEW_LINE> return redirect(reverse('shifts:index', kwargs={'year': kwargs['year'], 'month': kwargs['month'], 'day': kwargs['day']}))
create method for get request
62598fb07b180e01f3e4906c
class Pattern (object): <NEW_LINE> <INDENT> def __init__(self): pass <NEW_LINE> def match(self, point): return False
Abstract base for data pattern matching routines.
62598fb03539df3088ecc2eb
class Person(XmlObj): <NEW_LINE> <INDENT> type = Attribute() <NEW_LINE> source = Attribute()
A person.
62598fb026068e7796d4c98e
@functools.total_ordering <NEW_LINE> class User(object): <NEW_LINE> <INDENT> def __init__(self, nick, user, host): <NEW_LINE> <INDENT> assert isinstance(nick, Identifier) <NEW_LINE> self.nick = nick <NEW_LINE> self.user = user <NEW_LINE> self.host = host <NEW_LINE> self.channels = {} <NEW_LINE> self.account = None <NEW_LINE> self.away = None <NEW_LINE> <DEDENT> hostmask = property(lambda self: '{}!{}@{}'.format(self.nick, self.user, self.host)) <NEW_LINE> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, User): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return self.nick == other.nick <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, User): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return self.nick < other.nick
A representation of a user Sopel is aware of. :param nick: the user's nickname :type nick: :class:`~.tools.Identifier` :param str user: the user's local username ("user" in `user@host.name`) :param str host: the user's hostname ("host.name" in `user@host.name`)
62598fb05fc7496912d4829d
class DebugListener(RegionProfilerListener): <NEW_LINE> <INDENT> def finalize(self): <NEW_LINE> <INDENT> print('RegionProfiler: Finalizing profiler', file=sys.stderr) <NEW_LINE> <DEDENT> def region_entered(self, profiler, region): <NEW_LINE> <INDENT> ts = region.timer.last_event_time - profiler.root.timer.begin_ts() <NEW_LINE> print('RegionProfiler: Entered {} at {}'. format(region.name, pretty_print_time(ts)), file=sys.stderr) <NEW_LINE> <DEDENT> def region_exited(self, profiler, region): <NEW_LINE> <INDENT> ts = region.timer.last_event_time - profiler.root.timer.begin_ts() <NEW_LINE> elapsed = region.timer.last_event_time - region.timer.begin_ts() <NEW_LINE> print('RegionProfiler: Exited {} at {} after {}'. format(region.name, pretty_print_time(ts), pretty_print_time(elapsed)), file=sys.stderr) <NEW_LINE> <DEDENT> def region_canceled(self, profiler, region): <NEW_LINE> <INDENT> ts = region.timer.last_event_time - profiler.root.timer.begin_ts() <NEW_LINE> print('RegionProfiler: Canceled {} at {}'.format(region.name, pretty_print_time(ts)), file=sys.stderr)
Log profiler events to console. This listener log enter/exit events in real time. Sample output:: RegionProfiler: Entered <main> at 0 ns RegionProfiler: Entered fetch_mnist() at 641 us RegionProfiler: Exited fetch_mnist() at 643 ms after 642 ms RegionProfiler: Entered train at 743 ms RegionProfiler: Entered fetch_next at 743 ms RegionProfiler: Exited fetch_next at 744 ms after 1.183 ms RegionProfiler: Entered forward at 744 ms RegionProfiler: Entered loss_fn() at 744 ms RegionProfiler: Entered NN at 745 ms RegionProfiler: Exited NN at 764 ms after 19.40 ms RegionProfiler: Exited loss_fn() at 765 ms after 20.55 ms RegionProfiler: Exited <main> at 1.066 s after 1.066 s RegionProfiler: Finalizing profiler
62598fb0627d3e7fe0e06ee7
class SshTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_parse_ssh_version(self): <NEW_LINE> <INDENT> ver = ssh._parse_ssh_version('Unknown\n') <NEW_LINE> self.assertEqual(ver, ()) <NEW_LINE> ver = ssh._parse_ssh_version('OpenSSH_1.0\n') <NEW_LINE> self.assertEqual(ver, (1, 0)) <NEW_LINE> ver = ssh._parse_ssh_version('OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.13, OpenSSL 1.0.1f 6 Jan 2014\n') <NEW_LINE> self.assertEqual(ver, (6, 6, 1)) <NEW_LINE> ver = ssh._parse_ssh_version('OpenSSH_7.6p1 Ubuntu-4ubuntu0.3, OpenSSL 1.0.2n 7 Dec 2017\n') <NEW_LINE> self.assertEqual(ver, (7, 6)) <NEW_LINE> <DEDENT> def test_version(self): <NEW_LINE> <INDENT> with mock.patch('ssh._run_ssh_version', return_value='OpenSSH_1.2\n'): <NEW_LINE> <INDENT> self.assertEqual(ssh.version(), (1, 2)) <NEW_LINE> <DEDENT> <DEDENT> def test_context_manager_empty(self): <NEW_LINE> <INDENT> with multiprocessing.Manager() as manager: <NEW_LINE> <INDENT> with ssh.ProxyManager(manager): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_context_manager_child_cleanup(self): <NEW_LINE> <INDENT> with multiprocessing.Manager() as manager: <NEW_LINE> <INDENT> with ssh.ProxyManager(manager) as ssh_proxy: <NEW_LINE> <INDENT> client = subprocess.Popen(['sleep', '964853320']) <NEW_LINE> ssh_proxy.add_client(client) <NEW_LINE> master = subprocess.Popen(['sleep', '964853321']) <NEW_LINE> ssh_proxy.add_master(master) <NEW_LINE> <DEDENT> <DEDENT> client.wait(0) <NEW_LINE> master.wait(0) <NEW_LINE> <DEDENT> def test_ssh_sock(self): <NEW_LINE> <INDENT> manager = multiprocessing.Manager() <NEW_LINE> proxy = ssh.ProxyManager(manager) <NEW_LINE> with mock.patch('tempfile.mkdtemp', return_value='/tmp/foo'): <NEW_LINE> <INDENT> with mock.patch('ssh.version', return_value=(6, 6)): <NEW_LINE> <INDENT> self.assertTrue(proxy.sock().endswith('%p')) <NEW_LINE> <DEDENT> proxy._sock_path = None <NEW_LINE> with mock.patch('ssh.version', return_value=(6, 7)): <NEW_LINE> <INDENT> self.assertTrue(proxy.sock().endswith('%C'))
Tests the ssh functions.
62598fb0d58c6744b42dc2f4
class OpenAPIClientException(Exception): <NEW_LINE> <INDENT> def __init__(self, message, code=500): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> self.code = code
Raised when there is an error executing requests
62598fb0a79ad1619776a0a1
class EPS_AUTHENTICATION_REJECT(Layer3NASEMM): <NEW_LINE> <INDENT> constructorList = [ie for ie in EMMHeader(Type=84)]
Net -> UE Dual
62598fb04f88993c371f0527
@patch('doorstop.server.utilities.json_response', Mock(return_value=True)) <NEW_LINE> class TestRoutesJSON(BaseTestCase): <NEW_LINE> <INDENT> def test_get_documents(self): <NEW_LINE> <INDENT> data = self.server.get_documents() <NEW_LINE> self.assertEqual({'prefixes': ['PREFIX', 'PREFIX2']}, data) <NEW_LINE> <DEDENT> def test_get_document(self): <NEW_LINE> <INDENT> data = server.get_document('prefix') <NEW_LINE> self.assertEqual({'UID': {'links': ['UID3', 'UID4'], 'text': 'TEXT'}, 'UID2': {}}, data) <NEW_LINE> <DEDENT> def test_get_items(self): <NEW_LINE> <INDENT> data = server.get_items('prefix') <NEW_LINE> self.assertEqual({'uids': ['UID', 'UID2']}, data) <NEW_LINE> <DEDENT> def test_get_item(self): <NEW_LINE> <INDENT> data = server.get_item('prefix', 'uid') <NEW_LINE> self.assertEqual({'data': {'links': ['UID3', 'UID4'], 'text': 'TEXT'}}, data) <NEW_LINE> <DEDENT> def test_get_attrs(self): <NEW_LINE> <INDENT> data = server.get_attrs('prefix', 'uid') <NEW_LINE> self.assertEqual({'attrs': ['links', 'text']}, data) <NEW_LINE> <DEDENT> def test_get_attr(self): <NEW_LINE> <INDENT> data = server.get_attr('prefix', 'uid', 'name') <NEW_LINE> self.assertEqual({'value': None}, data) <NEW_LINE> <DEDENT> def test_get_attr_str(self): <NEW_LINE> <INDENT> data = server.get_attr('prefix', 'uid', 'text') <NEW_LINE> self.assertEqual({'value': 'TEXT'}, data) <NEW_LINE> <DEDENT> def test_get_attr_list(self): <NEW_LINE> <INDENT> data = server.get_attr('prefix', 'uid', 'links') <NEW_LINE> self.assertEqual({'value': ['UID3', 'UID4']}, data) <NEW_LINE> <DEDENT> @patch('doorstop.server.main.numbers', {'prefix': 123}) <NEW_LINE> def test_post_numbers(self): <NEW_LINE> <INDENT> data = server.post_numbers('prefix') <NEW_LINE> self.assertEqual({'next': 123}, data)
Unit tests for the doorstop.web.server module JSON responses.
62598fb02ae34c7f260ab11b
class TimestampValidator: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self._last_dts: dict[av.stream.Stream, int | float] = defaultdict( lambda: float("-inf") ) <NEW_LINE> self._missing_dts = 0 <NEW_LINE> <DEDENT> def is_valid(self, packet: av.Packet) -> bool: <NEW_LINE> <INDENT> if packet.dts is None: <NEW_LINE> <INDENT> if self._missing_dts >= MAX_MISSING_DTS: <NEW_LINE> <INDENT> raise StopIteration( f"No dts in {MAX_MISSING_DTS+1} consecutive packets" ) <NEW_LINE> <DEDENT> self._missing_dts += 1 <NEW_LINE> return False <NEW_LINE> <DEDENT> self._missing_dts = 0 <NEW_LINE> prev_dts = self._last_dts[packet.stream] <NEW_LINE> if packet.dts <= prev_dts: <NEW_LINE> <INDENT> gap = packet.time_base * (prev_dts - packet.dts) <NEW_LINE> if gap > MAX_TIMESTAMP_GAP: <NEW_LINE> <INDENT> raise StopIteration( f"Timestamp overflow detected: last dts = {prev_dts}, dts = {packet.dts}" ) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> self._last_dts[packet.stream] = packet.dts <NEW_LINE> return True
Validate ordering of timestamps for packets in a stream.
62598fb010dbd63aa1c70bed
class Company(db.Model): <NEW_LINE> <INDENT> __tablename__ = "companies" <NEW_LINE> company_id = db.Column(db.Integer, autoincrement=True, primary_key=True) <NEW_LINE> key = db.Column(db.String(64), nullable=True, unique=True) <NEW_LINE> company = db.Column(db.String(64), nullable=True) <NEW_LINE> team = db.Column(db.String(64), nullable=True) <NEW_LINE> num_female_eng = db.Column(db.Integer) <NEW_LINE> num_eng = db.Column(db.Integer) <NEW_LINE> percent_female_eng = db.Column(db.Float) <NEW_LINE> last_updated = db.Column(db.DateTime) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<Company num_female_eng=%d num_eng=%d company=%s>" % (self.num_female_eng, self.num_eng, self.company)
Company contributing data on gender diversity.
62598fb0283ffb24f3cf38c6
class ImageResource ( MImageResource ): <NEW_LINE> <INDENT> _ref = Any <NEW_LINE> def _get_width ( self ): <NEW_LINE> <INDENT> return self.bitmap.width() <NEW_LINE> <DEDENT> def _get_height ( self ): <NEW_LINE> <INDENT> return self.bitmap.height() <NEW_LINE> <DEDENT> def _get_graphics ( self ): <NEW_LINE> <INDENT> return QtGraphics( painter_for( self.bitmap ) ) <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def _get_pixels ( self ): <NEW_LINE> <INDENT> image = self.bitmap.toImage() <NEW_LINE> return reshape( fromstring( image.bits(), uint8 ), ( self.height, self.width, 4 ) ) <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def _get_mono_bitmap ( self ): <NEW_LINE> <INDENT> return self.bitmap <NEW_LINE> <DEDENT> create_bitmap = MImageResource.create_image <NEW_LINE> create_bitmap_from_pixels = MImageResource.create_image_from_pixels <NEW_LINE> def create_icon ( self, size = None ): <NEW_LINE> <INDENT> ref = self._get_ref( size ) <NEW_LINE> if ref is not None: <NEW_LINE> <INDENT> image = ref.load() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> image = self._get_image_not_found_image() <NEW_LINE> <DEDENT> return QIcon( image ) <NEW_LINE> <DEDENT> def create_icon_from_pixels ( self ): <NEW_LINE> <INDENT> return QIcon( self.create_image_from_pixels() ) <NEW_LINE> <DEDENT> def save ( self, file_name ): <NEW_LINE> <INDENT> self.bitmap.save( file_name ) <NEW_LINE> <DEDENT> def _get_absolute_path ( self ): <NEW_LINE> <INDENT> ref = self._get_ref() <NEW_LINE> if ref is not None: <NEW_LINE> <INDENT> return abspath( self._ref.filename ) <NEW_LINE> <DEDENT> return self._get_image_not_found().absolute_path
The Qt4 toolkit specific implementation of an ImageResource. See the i_image_resource module for the API documentation.
62598fb0cb5e8a47e493c196