code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class UnknownError(QCEngineException): <NEW_LINE> <INDENT> error_type = "unknown_error" <NEW_LINE> header = "QCEngine Unknown Error" | Unknown QCEngine error, the type was not able to be specified. | 6259906101c39578d7f14290 |
class PercolatorQuery(Query): <NEW_LINE> <INDENT> def __init__(self, doc, query=None, **kwargs): <NEW_LINE> <INDENT> super(PercolatorQuery, self).__init__(**kwargs) <NEW_LINE> self.doc = doc <NEW_LINE> self.query = query <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> data = {'doc': self.doc} <NEW_LINE> if isinstance(self.query, Query): <NEW_LINE> <INDENT> data['query'] = self.query.serialize() <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def search(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() | A percolator query is used to determine which registered
PercolatorDoc's match the document supplied. | 6259906197e22403b383c5c3 |
class ProjectBug(models.Model): <NEW_LINE> <INDENT> STATES = ( ('draft', u'草稿'), ('confirm', u"已确认"), ('appointed', u"已指派"), ('processing', u"处理中"), ('refuse', u"已拒绝"), ('hold', u"挂起"), ('solved', u"已解决"), ('done', u"完成"), ('close', u"关闭") ) <NEW_LINE> LEVELS = ( (1, u"致命"), (2, u"重大"), (3, u"次要"), (4, u"一般"), (5, u"建议") ) <NEW_LINE> project = models.ForeignKey("project.Project", verbose_name=u"项目名称") <NEW_LINE> task = models.ForeignKey('project.ProjectTask', verbose_name=u"项目任务", null=True, blank=True) <NEW_LINE> name = models.CharField(max_length=50, verbose_name=u"Bug名称") <NEW_LINE> description = models.TextField(verbose_name=u"Bug描述") <NEW_LINE> state = models.CharField(max_length=10, verbose_name=u"状态", choices=STATES, default='draft') <NEW_LINE> level = models.IntegerField(verbose_name=u"级别", choices=LEVELS, default=4) <NEW_LINE> tester = models.ForeignKey("tcis_base.User", related_name="tester", verbose_name=u"测试员", null=True, blank=True) <NEW_LINE> handler = models.ForeignKey("tcis_base.User", related_name="handler", verbose_name=u"处理员", null=True, blank=True) <NEW_LINE> checker = models.ForeignKey('tcis_base.User', related_name="checker", verbose_name=u"验证员", null=True, blank=True) <NEW_LINE> open_times = models.IntegerField(verbose_name=u"打开次数", default=1) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "project_bug" <NEW_LINE> verbose_name = u'项目Bug' <NEW_LINE> verbose_name_plural = u"项目Bug管理" | 项目bug管理 | 62599061d486a94d0ba2d67f |
class GeneratorWrapper(Sequence): <NEW_LINE> <INDENT> def __init__(self, inputs, outputs, sample_weights, batch_size, shuffle): <NEW_LINE> <INDENT> self._inputs = inputs <NEW_LINE> self._outputs = outputs <NEW_LINE> self._sample_weights = sample_weights <NEW_LINE> self._size = inputs[0].shape[0] <NEW_LINE> self._batch_size = batch_size <NEW_LINE> self._num_batches = int((self._size-1)/batch_size) + 1 <NEW_LINE> self._shuffle = shuffle <NEW_LINE> self._ids = np.arange(0, self._size) <NEW_LINE> self._reshuffle() <NEW_LINE> print("\nTotal samples: {} ".format(self._size)) <NEW_LINE> print("Batch size: {} ".format(min(self._batch_size, self._size))) <NEW_LINE> print("Total batches: {} \n".format(self._num_batches)) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self._num_batches <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> start = index * self._batch_size <NEW_LINE> end = min(start + self._batch_size, self._size) <NEW_LINE> ids = self._ids[start: end] <NEW_LINE> inputs = [v[ids, :] for v in self._inputs] <NEW_LINE> outputs = [v[ids, :] for v in self._outputs] <NEW_LINE> sample_weights = [v[ids] for v in self._sample_weights] <NEW_LINE> return inputs, outputs, sample_weights <NEW_LINE> <DEDENT> def on_epoch_end(self): <NEW_LINE> <INDENT> self._reshuffle() <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> return self._inputs, self._outputs, self._sample_weights <NEW_LINE> <DEDENT> def _reshuffle(self): <NEW_LINE> <INDENT> if self._num_batches > 1 and self._shuffle: <NEW_LINE> <INDENT> self._ids = np.random.choice(self._size, self._size, replace=False) <NEW_LINE> <DEDENT> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = super(GeneratorWrapper, self).get_config() <NEW_LINE> return config | Converts fit() into fit_generator() interface. | 62599061379a373c97d9a6db |
class Walker(object): <NEW_LINE> <INDENT> def __init__(self, proxy, baseoid): <NEW_LINE> <INDENT> self.baseoid = baseoid <NEW_LINE> self.lastoid = baseoid <NEW_LINE> self.proxy = proxy <NEW_LINE> self.results = {} <NEW_LINE> self.defer = defer.Deferred() <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> d = self.proxy.getbulk(self.baseoid) <NEW_LINE> d.addErrback(lambda x: x.trap(snmp.SNMPEndOfMibView, snmp.SNMPNoSuchName) and {}) <NEW_LINE> d.addCallback(self.getMore) <NEW_LINE> d.addErrback(self.fireError) <NEW_LINE> return self.defer <NEW_LINE> <DEDENT> def getMore(self, x): <NEW_LINE> <INDENT> stop = False <NEW_LINE> for o in x: <NEW_LINE> <INDENT> if o in self.results: <NEW_LINE> <INDENT> stop = True <NEW_LINE> continue <NEW_LINE> <DEDENT> if translateOid(o)[:len(translateOid(self.baseoid))] != translateOid(self.baseoid): <NEW_LINE> <INDENT> stop = True <NEW_LINE> continue <NEW_LINE> <DEDENT> self.results[o] = x[o] <NEW_LINE> if translateOid(self.lastoid) < translateOid(o): <NEW_LINE> <INDENT> self.lastoid = o <NEW_LINE> <DEDENT> <DEDENT> if stop or not x: <NEW_LINE> <INDENT> self.defer.callback(self.results) <NEW_LINE> self.defer = None <NEW_LINE> return <NEW_LINE> <DEDENT> d = self.proxy.getbulk(self.lastoid) <NEW_LINE> d.addErrback(lambda x: x.trap(snmp.SNMPEndOfMibView, snmp.SNMPNoSuchName) and {}) <NEW_LINE> d.addCallback(self.getMore) <NEW_LINE> d.addErrback(self.fireError) <NEW_LINE> return None <NEW_LINE> <DEDENT> def fireError(self, error): <NEW_LINE> <INDENT> self.defer.errback(error) <NEW_LINE> self.defer = None | SNMP walker class | 6259906116aa5153ce401b94 |
class FernetSetup(BasePermissionsSetup): <NEW_LINE> <INDENT> name = 'fernet_setup' <NEW_LINE> @classmethod <NEW_LINE> def main(cls): <NEW_LINE> <INDENT> tutils = token_utils.TokenUtils( CONF.fernet_tokens.key_repository, CONF.fernet_tokens.max_active_keys, 'fernet_tokens' ) <NEW_LINE> keystone_user_id, keystone_group_id = cls.get_user_group() <NEW_LINE> tutils.create_key_directory(keystone_user_id, keystone_group_id) <NEW_LINE> if tutils.validate_key_repository(requires_write=True): <NEW_LINE> <INDENT> tutils.initialize_key_repository( keystone_user_id, keystone_group_id) | Setup a key repository for Fernet tokens.
This also creates a primary key used for both creating and validating
Fernet tokens. To improve security, you should rotate your keys (using
keystone-manage fernet_rotate, for example). | 625990615166f23b2e244a89 |
class LazyFile(object): <NEW_LINE> <INDENT> def __init__(self, filename, mode='r', encoding=None, errors='strict', atomic=False): <NEW_LINE> <INDENT> self.name = filename <NEW_LINE> self.mode = mode <NEW_LINE> self.encoding = encoding <NEW_LINE> self.errors = errors <NEW_LINE> self.atomic = atomic <NEW_LINE> if filename == '-': <NEW_LINE> <INDENT> self._f, self.should_close = open_stream(filename, mode, encoding, errors) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if 'r' in mode: <NEW_LINE> <INDENT> open(filename, mode).close() <NEW_LINE> <DEDENT> self._f = None <NEW_LINE> self.should_close = True <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self.open(), name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self._f is not None: <NEW_LINE> <INDENT> return repr(self._f) <NEW_LINE> <DEDENT> return '<unopened file %r %s>' % (self.name, self.mode) <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> if self._f is not None: <NEW_LINE> <INDENT> return self._f <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> rv, self.should_close = open_stream(self.name, self.mode, self.encoding, self.errors, atomic=self.atomic) <NEW_LINE> <DEDENT> except (IOError, OSError) as e: <NEW_LINE> <INDENT> from .exceptions import FileError <NEW_LINE> raise FileError(self.name, hint=get_streerror(e)) <NEW_LINE> <DEDENT> self._f = rv <NEW_LINE> return rv <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self._f is not None: <NEW_LINE> <INDENT> self._f.close() <NEW_LINE> <DEDENT> <DEDENT> def close_intelligently(self): <NEW_LINE> <INDENT> if self.should_close: <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, tb): <NEW_LINE> <INDENT> self.close_intelligently() | A lazy file works like a regular file but it does not fully open
the file but it does perform some basic checks early to see if the
filename parameter does make sense. This is useful for safely opening
files for writing. | 625990618a43f66fc4bf3846 |
class BoatdHTTPServer(ThreadingMixIn, HTTPServer): <NEW_LINE> <INDENT> def __init__(self, boat, server_address, RequestHandlerClass, bind_and_activate=True): <NEW_LINE> <INDENT> HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate) <NEW_LINE> log.info('boatd api listening on %s:%s', *server_address) <NEW_LINE> self.boat = boat <NEW_LINE> self.running = True <NEW_LINE> self.handles = { '/': self.boatd_info, '/boat': self.boat_attr, '/wind': self.wind, '/active': self.boat_active } <NEW_LINE> self.post_handles = { '/': self.boatd_post, } <NEW_LINE> <DEDENT> def wind(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> speed = self.boat.wind_speed() <NEW_LINE> <DEDENT> except (AttributeError, TypeError): <NEW_LINE> <INDENT> speed = -1 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return {'direction': self.boat.wind_direction(), 'speed': speed} <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> log.exception('Error when attempting to read wind direction') <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> def boat_active(self): <NEW_LINE> <INDENT> return {'value': self.boat.active} <NEW_LINE> <DEDENT> def boatd_info(self): <NEW_LINE> <INDENT> return {'boatd': {'version': VERSION}} <NEW_LINE> <DEDENT> def boat_attr(self): <NEW_LINE> <INDENT> return { 'heading': self.boat.heading(), 'wind': self.wind(), 'position': self.boat.position(), 'active': self.boat.active } <NEW_LINE> <DEDENT> def boatd_post(self, content): <NEW_LINE> <INDENT> response = {} <NEW_LINE> if 'quit' in content: <NEW_LINE> <INDENT> if content.get('quit'): <NEW_LINE> <INDENT> self.running = False <NEW_LINE> response['quit'] = True <NEW_LINE> <DEDENT> <DEDENT> return response <NEW_LINE> <DEDENT> def boat_post_function(self, name, content): <NEW_LINE> <INDENT> f = self.post_handles.get(name) <NEW_LINE> if f is not None: <NEW_LINE> <INDENT> return f(content) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.driver_function(name, args=[content['value']]) <NEW_LINE> <DEDENT> <DEDENT> def boat_function(self, function_string): <NEW_LINE> <INDENT> json_content = self.handles.get(function_string)() <NEW_LINE> return json_content <NEW_LINE> <DEDENT> def driver_function(self, function_string, args=None): <NEW_LINE> <INDENT> if args is None: <NEW_LINE> <INDENT> args = [] <NEW_LINE> <DEDENT> obj_path = [p for p in function_string.split('/') if p] <NEW_LINE> attr = get_deep_attr(self.boat, obj_path) <NEW_LINE> if callable(attr): <NEW_LINE> <INDENT> json_content = {"result": attr(*args)} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> return json_content | The main REST server for boatd. Listens for requests on port server_address
and handles each request with RequestHandlerClass. | 62599061e5267d203ee6cf1b |
class Restaurant(): <NEW_LINE> <INDENT> def __init__(self, restaurant_name, cuisine_type): <NEW_LINE> <INDENT> self.restaurant_name = restaurant_name <NEW_LINE> self.cuisine_type = cuisine_type <NEW_LINE> self.number_served = 0 <NEW_LINE> <DEDENT> def describe_restaurant(self): <NEW_LINE> <INDENT> print(self.restaurant_name) <NEW_LINE> print(self.cuisine_type) <NEW_LINE> <DEDENT> def open_restaurant(self): <NEW_LINE> <INDENT> print(self.cuisine_type + " restaurant " + self.restaurant_name + " is open!") <NEW_LINE> <DEDENT> def set_number_served(self, number_served): <NEW_LINE> <INDENT> self.number_served = number_served <NEW_LINE> <DEDENT> def increment_number_served(self, additional_served): <NEW_LINE> <INDENT> self.number_served += additional_served | A class representing a restaurant | 62599061ac7a0e7691f73b9b |
class EvaluationError(Exception): <NEW_LINE> <INDENT> pass | For evaluation errors | 62599061e64d504609df9f2a |
class Model(nn.Module): <NEW_LINE> <INDENT> def reset(self): <NEW_LINE> <INDENT> self.h = [Variable(Tensor(ModelManager.batch_size, ModelManager.hidden_size).zero_()) for i in range(ModelManager.num_hidden_layers)] <NEW_LINE> self.c = self.h <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> super(ModelManager.Model, self).__init__() <NEW_LINE> self.hidden_layers = [nn.LSTMCell((ModelManager.input_size if not i else ModelManager.hidden_size), ModelManager.hidden_size) for i in range(ModelManager.num_hidden_layers)] <NEW_LINE> self.output_layer = nn.Linear(ModelManager.hidden_size, ModelManager.output_size) <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> for i in range(ModelManager.num_hidden_layers): <NEW_LINE> <INDENT> self.h[i], self.c[i] = self.hidden_layers[i]((x if not i else self.h[i - 1]), (self.h[i], self.c[i])) <NEW_LINE> <DEDENT> model_output = self.output_layer(self.h[-1]) <NEW_LINE> return model_output | This model contains an LSTM created using PyTorch.
This model will accept a batch of inputs, and will output a batch of predictions. | 62599061097d151d1a2c2728 |
class ParallelNpArray(object): <NEW_LINE> <INDENT> def __init__(self, mp=None): <NEW_LINE> <INDENT> self._mp = mp <NEW_LINE> <DEDENT> def __call__(self, func): <NEW_LINE> <INDENT> def _parall(*args, **kwargs): <NEW_LINE> <INDENT> if self._mp.switch: <NEW_LINE> <INDENT> slices = self.prepare_slices(args[0], self._mp) <NEW_LINE> result_queue = [] <NEW_LINE> processes = [] <NEW_LINE> for i in range(self._mp.num_procs): <NEW_LINE> <INDENT> q = Queue() <NEW_LINE> p = Process(target=self.array_worker, args=(func, args, slices[i], q,)) <NEW_LINE> processes.append(p) <NEW_LINE> result_queue.append(q) <NEW_LINE> <DEDENT> for p in processes: <NEW_LINE> <INDENT> p.run() <NEW_LINE> <DEDENT> results = [] <NEW_LINE> for i, p in enumerate(processes): <NEW_LINE> <INDENT> res = result_queue[i].get() <NEW_LINE> if res: <NEW_LINE> <INDENT> results += res <NEW_LINE> <DEDENT> <DEDENT> return results <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return func(*args) <NEW_LINE> <DEDENT> <DEDENT> return _parall <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def array_worker(func, fargs, x_slice, result_queue): <NEW_LINE> <INDENT> args = [arg[x_slice] for arg in fargs] <NEW_LINE> result = func(*args) <NEW_LINE> result_queue.put(result) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def prepare_slices(x_list, mp): <NEW_LINE> <INDENT> l_shape = np.shape(x_list) <NEW_LINE> if mp.num_procs > 1: <NEW_LINE> <INDENT> len_slice = l_shape[0] // (mp.num_procs - 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> len_slice = l_shape[0] <NEW_LINE> <DEDENT> len_slice = max(len_slice, 1) <NEW_LINE> slices = [] <NEW_LINE> for proc in range(mp.num_procs): <NEW_LINE> <INDENT> slices.append(slice(proc * len_slice, (proc + 1) * len_slice)) <NEW_LINE> <DEDENT> return slices | do parallelisation using shared memory | 62599061d6c5a102081e37dc |
class SpaceToDepth(nn.Module): <NEW_LINE> <INDENT> def __init__(self, block_size=4): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> assert block_size in {2, 4}, "Space2Depth only supports blocks size = 4 or 2" <NEW_LINE> self.block_size = block_size <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> N, C, H, W = x.size() <NEW_LINE> S = self.block_size <NEW_LINE> x = x.view(N, C, H // S, S, W // S, S) <NEW_LINE> x = x.permute(0, 3, 5, 1, 2, 4).contiguous() <NEW_LINE> x = x.view(N, C * S * S, H // S, W // S) <NEW_LINE> return x <NEW_LINE> <DEDENT> def extra_repr(self): <NEW_LINE> <INDENT> return f"block_size={self.block_size}" | Pixel Unshuffle | 625990614428ac0f6e659beb |
class Line2D(Line): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Line2D(%s, %s)' % (self.P0,self.vL) <NEW_LINE> <DEDENT> def calculate_t_from_point(self,point): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.calculate_t_from_x(point.x) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return self.calculate_t_from_y(point.y) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def dimension(self): <NEW_LINE> <INDENT> return '2D' <NEW_LINE> <DEDENT> def distance_to_line(self,line): <NEW_LINE> <INDENT> if self.is_parallel(line): <NEW_LINE> <INDENT> return self.distance_to_point(line.P0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> def _intersect_line_skew(self,skew_line): <NEW_LINE> <INDENT> u=self.vL <NEW_LINE> v=skew_line.vL <NEW_LINE> w=self.P0-skew_line.P0 <NEW_LINE> t=-v.perp_product(w) / v.perp_product(u) <NEW_LINE> return self.calculate_point(t) | A two dimensional line, situated on an x, y plane.
Equation of the line is P(t) = P0 + vL*t where:
- P(t) is a point on the line;
- P0 is the start point of the line;
- vL is the line vector;
- t is any real number.
:param P0: The start point of the line.
:type P0: Point2D
:param vL: The line vector.
:type vL: Vector2D
:Example:
.. code-block:: python
>>> l = Line2D(Point2D(0,0), Vector2D(1,0))
>>> print(l)
Line2D(Point2D(0,0), Vector2D(1,0))
.. seealso:: `<https://geomalgorithms.com/a02-_lines.html>`_ | 625990616e29344779b01d07 |
class MultipleMeasureData(AbstractData): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> abstract = True | Abstract model for DSD with measure dimension but no time dimension
Each domain specific application with measure dimension but no time
dimension should subclass this class and use it to store the data
dim_key must be defined as a ForeignKey to the domain specific Dimensions
class
For each measure defined in the measure dimension concept scheme a django
field should be defined with measure id its name and an appropriate type
that depends on the measure representation.
For each attribute attached to the measure, appropriate django fields must
be defined for each measure with name *__** where * is the measure id and
** is the attribute id | 625990613d592f4c4edbc595 |
class FixedValueParamDef(PositionParamDef): <NEW_LINE> <INDENT> def __init__(self, values): <NEW_LINE> <INDENT> positions = [] <NEW_LINE> for v in values: <NEW_LINE> <INDENT> pos = v <NEW_LINE> positions.append(pos) <NEW_LINE> <DEDENT> super(FixedValueParamDef, self).__init__(values, positions) <NEW_LINE> self._logger.debug("Initialized FixedValue with %s", values) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> param_dict = {"values": self.values, "type": self.__class__.__name__} <NEW_LINE> self._logger.debug("Converting to dict: %s", param_dict) <NEW_LINE> return param_dict | Extension of PositionParamDef, in which the position is equal to the value
of each entry from values. | 6259906129b78933be26ac20 |
class FCEUXServer: <NEW_LINE> <INDENT> def __init__(self, frame_func, quit_func=None, ip='localhost', port=1234): <NEW_LINE> <INDENT> self._serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> self._serversocket.bind((ip, port)) <NEW_LINE> self._serversocket.listen(5) <NEW_LINE> self._clientsocket, self._address = self._serversocket.accept() <NEW_LINE> self._on_frame_func = frame_func <NEW_LINE> self._on_quit_func = quit_func <NEW_LINE> self._server_info = self.recv() + ' ' + str(self._address) <NEW_LINE> self.send('ACK') <NEW_LINE> <DEDENT> @property <NEW_LINE> def info(self): <NEW_LINE> <INDENT> return self._server_info <NEW_LINE> <DEDENT> def send(self, msg): <NEW_LINE> <INDENT> if not isinstance(msg, str): <NEW_LINE> <INDENT> self.quit() <NEW_LINE> raise TypeError('Arguments have to be string') <NEW_LINE> <DEDENT> self._clientsocket.send(bytes(msg+'\n', 'utf-8')) <NEW_LINE> <DEDENT> def recv(self): <NEW_LINE> <INDENT> return self._clientsocket.recv(4096).decode('utf-8') <NEW_LINE> <DEDENT> def init_frame(self): <NEW_LINE> <INDENT> frame_str = self.recv() <NEW_LINE> if len(frame_str) == 0: <NEW_LINE> <INDENT> self.quit('Client had quit') <NEW_LINE> <DEDENT> frame = int(frame_str) <NEW_LINE> return frame <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> frame = self.init_frame() <NEW_LINE> self._on_frame_func(self, frame) <NEW_LINE> <DEDENT> <DEDENT> except BrokenPipeError: <NEW_LINE> <INDENT> self.quit('Client has quit.') <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> self.quit() <NEW_LINE> <DEDENT> <DEDENT> def frame_advance(self): <NEW_LINE> <INDENT> self.send('CONT') <NEW_LINE> <DEDENT> def get_joypad(self): <NEW_LINE> <INDENT> self.send('JOYPAD') <NEW_LINE> return self.recv() <NEW_LINE> <DEDENT> def set_joypad(self, up=False, down=False, left=False, right=False, A=False, B=False, start=False, select=False): <NEW_LINE> <INDENT> self.send('SETJOYPAD') <NEW_LINE> joypad = str(up)+' '+str(down)+' '+str(left)+' '+str(right) + ' '+str(A)+' '+str(B)+' '+str(start)+' '+str(select) <NEW_LINE> self.send(joypad) <NEW_LINE> <DEDENT> def read_mem(self, addr, signed=False): <NEW_LINE> <INDENT> self.send('MEM') <NEW_LINE> self.send(str(addr)) <NEW_LINE> unsigned = int(self.recv()) <NEW_LINE> if signed: <NEW_LINE> <INDENT> return unsigned-256 if unsigned > 127 else unsigned <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return unsigned <NEW_LINE> <DEDENT> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.send('RES') <NEW_LINE> <DEDENT> def quit(self, reason=''): <NEW_LINE> <INDENT> if self._on_quit_func is not None: <NEW_LINE> <INDENT> self._on_quit_func() <NEW_LINE> <DEDENT> self._serversocket.close() <NEW_LINE> self._clientsocket.close() <NEW_LINE> print(reason) <NEW_LINE> print('Server has quit.') <NEW_LINE> exit() | Server class for making NES bots. Uses FCEUX emulator.
Visit https://www.fceux.com for info. You will also need to
load client lua script in the emulator. | 6259906132920d7e50bc76ff |
class Range: <NEW_LINE> <INDENT> start: Decimal <NEW_LINE> end: Decimal <NEW_LINE> def __init__(self, start, end): <NEW_LINE> <INDENT> self.start = Decimal(start) <NEW_LINE> self.end = Decimal(end) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return '(%0f, %0f)' % (self.start, self.end) <NEW_LINE> <DEDENT> def length(self) -> Decimal: <NEW_LINE> <INDENT> return self.end - self.start <NEW_LINE> <DEDENT> def average(self) -> Decimal: <NEW_LINE> <INDENT> return (self.start + self.end) / 2 <NEW_LINE> <DEDENT> def __contains__(self, num) -> bool: <NEW_LINE> <INDENT> return self.start <= num and self.end > num | Represents a range of Decimals | 6259906191af0d3eaad3b4e0 |
class Task(object): <NEW_LINE> <INDENT> def __init__(self, max_iter=None, proba_curriculum=0.2, batch_size=10, width=4): <NEW_LINE> <INDENT> self.max_iter = max_iter <NEW_LINE> self.num_iter = 0 <NEW_LINE> self.proba_curriculum = proba_curriculum <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.width = width <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> return self.next() <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if (self.max_iter is None) or (self.num_iter < self.max_iter): <NEW_LINE> <INDENT> u = np.random.rand() <NEW_LINE> if u < self.proba_curriculum: <NEW_LINE> <INDENT> length = np.random.randint(1, 21) <NEW_LINE> params = self.sample_params(length=length) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> params = self.sample_params() <NEW_LINE> <DEDENT> self.num_iter += 1 <NEW_LINE> return (self.num_iter - 1), params, self.sample(**params) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise StopIteration() | docstring for Task | 6259906101c39578d7f14291 |
class Blockchain(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._chain = [self.get_genesis_block()] <NEW_LINE> self.timestamp = int(datetime.now().timestamp()) <NEW_LINE> self.difficulty_bits = 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def chain(self): <NEW_LINE> <INDENT> return self.dict(self._chain) <NEW_LINE> <DEDENT> def dict(self, chain): <NEW_LINE> <INDENT> return json.loads(json.dumps(chain, default=lambda o: o.__dict__)) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._chain = [self._chain[0]] <NEW_LINE> <DEDENT> def get_genesis_block(self): <NEW_LINE> <INDENT> return Block(0, "0", 1465154705, "my genesis block!!", 0, 0, "f6b3fd6d417048423692c275deeaa010d4174bd680635d3e3cb0050aa46401cb") <NEW_LINE> <DEDENT> def add_block(self, data): <NEW_LINE> <INDENT> self._chain.append(self.create_block(data)) <NEW_LINE> <DEDENT> def create_block(self, block_data): <NEW_LINE> <INDENT> previous_block = self.get_latest_block() <NEW_LINE> next_index = previous_block.index + 1 <NEW_LINE> next_timestamp = self.timestamp <NEW_LINE> next_hash, next_nonce = self.calculate_hash(next_index, previous_block.hash, next_timestamp, block_data) <NEW_LINE> return Block(next_index, previous_block.hash, next_timestamp, block_data, self.difficulty_bits, next_nonce, next_hash) <NEW_LINE> <DEDENT> def get_latest_block(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._chain[-1] <NEW_LINE> <DEDENT> except IndexError as e: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def calculate_hash(self, index, previous_hash, timestamp, data): <NEW_LINE> <INDENT> header = str(index) + previous_hash + str(timestamp) + data + str(self.difficulty_bits) <NEW_LINE> hash_value, nonce = self.proof_of_work(header) <NEW_LINE> return hash_value, nonce <NEW_LINE> <DEDENT> def proof_of_work(self, header): <NEW_LINE> <INDENT> target = 2 ** (256 - difficulty_bits) <NEW_LINE> for nonce in range(max_nonce): <NEW_LINE> <INDENT> hash_result = SHA256.new(data=(str(header) + str(nonce)).encode()).hexdigest() <NEW_LINE> if int(hash_result, 16) < target: <NEW_LINE> <INDENT> print("Success with nonce %d" % nonce) <NEW_LINE> print("Hash is %s" % hash_result) <NEW_LINE> return (hash_result, nonce) <NEW_LINE> <DEDENT> <DEDENT> print("Failed after %d (max_nonce) tries" % nonce) <NEW_LINE> return nonce | A class representing list of blocks | 6259906107f4c71912bb0af6 |
class gbSeq(Seq): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(gbSeq, self).__init__(*args, **kwargs) <NEW_LINE> self.locus = self.data.get('LOCUS',(None,))[0] <NEW_LINE> try: <NEW_LINE> <INDENT> self.taxid = self.data['FEATURES'][1]['source'][1]['db_xref'][0].split(':')[1] <NEW_LINE> <DEDENT> except (KeyError,IndexError): <NEW_LINE> <INDENT> self.taxid = None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.organism = self.data['FEATURES'][1]['source'][1]['organism'][0] <NEW_LINE> <DEDENT> except (KeyError,IndexError): <NEW_LINE> <INDENT> self.organism = None | Provides some convenience attributes for accessing data in
Seq.data | 625990614f88993c371f107b |
class DevConfig(Config): <NEW_LINE> <INDENT> DEBUG = True <NEW_LINE> host = "ec2-54-235-244-185.compute-1.amazonaws.com" <NEW_LINE> user = "xvnedalyoohnpo" <NEW_LINE> password = "5db0f5db98186e38cd15f8d46396141a152d3795a26bb3931e9b1026a6a8e38b" <NEW_LINE> database = "d4pn014537djvi" <NEW_LINE> SQLALCHEMY_DATABASE_URI='postgresql://xvnedalyoohnpo:5db0f5db98186e38cd15f8d46396141a152d3795a26bb3931e9b1026a6a8e38b@ec2-54-235-244-185.compute-1.amazonaws.com/d4pn014537djvi' | Dev config | 625990617d847024c075da8d |
class ActionReverted(Event): <NEW_LINE> <INDENT> type_name = "undo" <NEW_LINE> def __hash__(self) -> int: <NEW_LINE> <INDENT> return hash(32143124318) <NEW_LINE> <DEDENT> def __eq__(self, other) -> bool: <NEW_LINE> <INDENT> return isinstance(other, ActionReverted) <NEW_LINE> <DEDENT> def __str__(self) -> Text: <NEW_LINE> <INDENT> return "ActionReverted()" <NEW_LINE> <DEDENT> def as_story_string(self) -> Text: <NEW_LINE> <INDENT> return self.type_name <NEW_LINE> <DEDENT> def apply_to(self, tracker: "DialogueStateTracker") -> None: <NEW_LINE> <INDENT> tracker._reset() <NEW_LINE> tracker.replay_events() | Bot undoes its last action.
The bot reverts everything until before the most recent action.
This includes the action itself, as well as any events that
action created, like set slot events - the bot will now
predict a new action using the state before the most recent
action. | 625990617b25080760ed883d |
@enum.unique <NEW_LINE> class WireMode(enum.IntEnum): <NEW_LINE> <INDENT> rs485_4 = VI_ASRL_WIRE_485_4 <NEW_LINE> rs485_2_dtr_echo = VI_ASRL_WIRE_485_2_DTR_ECHO <NEW_LINE> rs485_2_dtr_ctrl = VI_ASRL_WIRE_485_2_DTR_CTRL <NEW_LINE> rs485_2_auto = VI_ASRL_WIRE_485_2_AUTO <NEW_LINE> rs232_dte = VI_ASRL_WIRE_232_DTE <NEW_LINE> rs232_dce = VI_ASRL_WIRE_232_DCE <NEW_LINE> rs232_auto = VI_ASRL_WIRE_232_AUTO <NEW_LINE> unknown = VI_STATE_UNKNOWN | Valid modes for National Instruments hardware supporting it. | 62599061a79ad1619776b619 |
class Flavour(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def flavour(cls) -> str: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def delims(cls) -> Tuple[str, str]: <NEW_LINE> <INDENT> return "[", "]" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def current_schema_expr(cls) -> str: <NEW_LINE> <INDENT> return "NULL" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def column_type_expr(cls) -> str: <NEW_LINE> <INDENT> return "NULL" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def jdbc_error_help(cls) -> str: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_all_table_names(cls, db: DATABASE_SUPPORTER_FWD_REF) -> List[str]: <NEW_LINE> <INDENT> raise RuntimeError(_MSG_NO_FLAVOUR) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_all_table_details(cls, db: DATABASE_SUPPORTER_FWD_REF) -> List[List[Any]]: <NEW_LINE> <INDENT> raise RuntimeError(_MSG_NO_FLAVOUR) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def describe_table(cls, db: DATABASE_SUPPORTER_FWD_REF, table: str) -> List[List[Any]]: <NEW_LINE> <INDENT> raise RuntimeError(_MSG_NO_FLAVOUR) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fetch_column_names(cls, db: DATABASE_SUPPORTER_FWD_REF, table: str) -> List[str]: <NEW_LINE> <INDENT> raise RuntimeError(_MSG_NO_FLAVOUR) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_datatype(cls, db: DATABASE_SUPPORTER_FWD_REF, table: str, column: str) -> str: <NEW_LINE> <INDENT> raise RuntimeError(_MSG_NO_FLAVOUR) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_column_type(cls, db: DATABASE_SUPPORTER_FWD_REF, table: str, column: str) -> str: <NEW_LINE> <INDENT> raise RuntimeError(_MSG_NO_FLAVOUR) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_comment(cls, db: DATABASE_SUPPORTER_FWD_REF, table: str, column: str) -> str: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_system_variable(cls, db: DATABASE_SUPPORTER_FWD_REF, varname: str) -> Any: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def mysql_using_file_per_table(cls, db: DATABASE_SUPPORTER_FWD_REF) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def mysql_using_innodb_barracuda(cls, db: DATABASE_SUPPORTER_FWD_REF) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def mysql_table_using_barracuda(cls, db: DATABASE_SUPPORTER_FWD_REF, tablename: str) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def mysql_convert_table_to_barracuda(cls, db: DATABASE_SUPPORTER_FWD_REF, tablename: str, logger: logging.Logger = None, compressed: bool = False) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def mysql_using_innodb_strict_mode(cls, db: DATABASE_SUPPORTER_FWD_REF) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def mysql_get_max_allowed_packet(cls, db: DATABASE_SUPPORTER_FWD_REF) -> Optional[int]: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def is_read_only(cls, db: DATABASE_SUPPORTER_FWD_REF, logger: logging.Logger = None) -> bool: <NEW_LINE> <INDENT> return False | Describes a database "flavour" (dialect). | 62599061442bda511e95d8b6 |
class FairseqNATModel(TransformerModel): <NEW_LINE> <INDENT> def __init__(self, args, encoder, decoder): <NEW_LINE> <INDENT> super().__init__(args, encoder, decoder) <NEW_LINE> self.tgt_dict = decoder.dictionary <NEW_LINE> self.bos = decoder.dictionary.bos() <NEW_LINE> self.eos = decoder.dictionary.eos() <NEW_LINE> self.pad = decoder.dictionary.pad() <NEW_LINE> self.unk = decoder.dictionary.unk() <NEW_LINE> self.en_tag = decoder.dictionary.index("<en>") <NEW_LINE> self.ch_tag = decoder.dictionary.index("<ch>") <NEW_LINE> self.ensemble_models = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def allow_length_beam(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def allow_ensemble(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def enable_ensemble(self, models): <NEW_LINE> <INDENT> self.encoder.ensemble_models = [m.encoder for m in models] <NEW_LINE> self.decoder.ensemble_models = [m.decoder for m in models] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def add_args(parser): <NEW_LINE> <INDENT> TransformerModel.add_args(parser) <NEW_LINE> parser.add_argument( "--apply-bert-init", action="store_true", help="use custom param initialization for BERT", ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def build_decoder(cls, args, tgt_dict, embed_tokens): <NEW_LINE> <INDENT> decoder = FairseqNATDecoder(args, tgt_dict, embed_tokens) <NEW_LINE> if getattr(args, "apply_bert_init", False): <NEW_LINE> <INDENT> decoder.apply(init_bert_params) <NEW_LINE> <DEDENT> return decoder <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def build_encoder(cls, args, src_dict, embed_tokens): <NEW_LINE> <INDENT> encoder = FairseqNATEncoder(args, src_dict, embed_tokens) <NEW_LINE> if getattr(args, "apply_bert_init", False): <NEW_LINE> <INDENT> encoder.apply(init_bert_params) <NEW_LINE> <DEDENT> return encoder <NEW_LINE> <DEDENT> def forward_encoder(self, encoder_inputs): <NEW_LINE> <INDENT> return self.encoder(*encoder_inputs) <NEW_LINE> <DEDENT> def forward_decoder(self, *args, **kwargs): <NEW_LINE> <INDENT> return NotImplementedError <NEW_LINE> <DEDENT> def initialize_output_tokens(self, *args, **kwargs): <NEW_LINE> <INDENT> return NotImplementedError <NEW_LINE> <DEDENT> def forward(self, *args, **kwargs): <NEW_LINE> <INDENT> return NotImplementedError | Abstract class for all nonautoregressive-based models | 6259906144b2445a339b74bd |
class FlowStatsMixIn(LBMixIn): <NEW_LINE> <INDENT> pass | When mixed with an LBFluidSim-descendant class, provides easy access
to various flow statistics | 625990612ae34c7f260ac7a0 |
class Error(RuntimeError): <NEW_LINE> <INDENT> pass | Generic exception class. | 62599061b7558d5895464a8a |
class ClientMonitor(metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self, config: dict): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.listeners = dict() <NEW_LINE> self.connections = self.get_current_connections() <NEW_LINE> <DEDENT> def add_listener(self, name: str, action): <NEW_LINE> <INDENT> self.listeners[name] = action <NEW_LINE> <DEDENT> def run(self) -> List[Event]: <NEW_LINE> <INDENT> prior = self.connections <NEW_LINE> current = self.get_current_connections() <NEW_LINE> self.connections = current <NEW_LINE> new, dropped = compare_connections(prior, current) <NEW_LINE> events = [] <NEW_LINE> if new: <NEW_LINE> <INDENT> message = "found {} new connection(s):\n".format(len(new)) <NEW_LINE> for client, client_connections in new.items(): <NEW_LINE> <INDENT> for real_address, details in client_connections.items(): <NEW_LINE> <INDENT> message += "user {} from address {}".format(details['Common Name'], details['Real Address']) <NEW_LINE> <DEDENT> <DEDENT> events.append( Event(message, dict(new=new)) ) <NEW_LINE> <DEDENT> return events <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def get_current_connections(self) -> dict: <NEW_LINE> <INDENT> pass | Monitor client connections | 6259906155399d3f05627bd9 |
class ListIssuesForRepoInputSet(InputSet): <NEW_LINE> <INDENT> def set_AccessToken(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AccessToken', value) <NEW_LINE> <DEDENT> def set_Assignee(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Assignee', value) <NEW_LINE> <DEDENT> def set_Direction(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Direction', value) <NEW_LINE> <DEDENT> def set_Labels(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Labels', value) <NEW_LINE> <DEDENT> def set_Mentioned(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Mentioned', value) <NEW_LINE> <DEDENT> def set_Milestone(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Milestone', value) <NEW_LINE> <DEDENT> def set_Page(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Page', value) <NEW_LINE> <DEDENT> def set_Repo(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Repo', value) <NEW_LINE> <DEDENT> def set_Since(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Since', value) <NEW_LINE> <DEDENT> def set_Sort(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Sort', value) <NEW_LINE> <DEDENT> def set_State(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'State', value) <NEW_LINE> <DEDENT> def set_User(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'User', value) | An InputSet with methods appropriate for specifying the inputs to the ListIssuesForRepo
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 6259906166673b3332c31ab6 |
class CorporatePaymentForm(forms.Form): <NEW_LINE> <INDENT> full_name = forms.CharField(max_length=127, label=_(u'Имя, Фамилия')) <NEW_LINE> org = forms.CharField(max_length=255, label=_(u'Название компании')) <NEW_LINE> position = forms.CharField(max_length=127, label=_(u'Должность')) <NEW_LINE> email = forms.EmailField(label='Email') <NEW_LINE> telephone = forms.CharField(label=_(u'Телефон')) <NEW_LINE> students = forms.CharField(label=_(u'Сколько людей планируете обучать?'), widget=forms.NumberInput) <NEW_LINE> info = forms.CharField(label=_(u'Комментарий'), widget=forms.Textarea, required=False, max_length=10000) <NEW_LINE> def clean_students(self): <NEW_LINE> <INDENT> val = self.cleaned_data.get('students') <NEW_LINE> if val is not None and not (val.isdigit() and 1 <= int(val) <= 1000000000): <NEW_LINE> <INDENT> raise forms.ValidationError(_(u'Пожалуйста, укажите планируемое число слушателей курсов')) <NEW_LINE> <DEDENT> return val | форма приема оплаты для юр.лиц | 62599061d6c5a102081e37de |
class Quart_UK( Unit ): <NEW_LINE> <INDENT> name= "qt.(UK)" <NEW_LINE> factor= 0.879877 | quart (imperial) | 6259906124f1403a9268642b |
class IBlogstarLastEntries(IPortletDataProvider): <NEW_LINE> <INDENT> portletTitle = schema.TextLine(title=_(u"Title of the portlet"), description = _(u"Insert the title of the portlet."), default=_(u"Blog entries"), required = True) <NEW_LINE> blogFolder = schema.Choice(title=_(u"Blog folder"), description=_(u"Insert the folder that is used for the blog. Leave empty to search in all the site."), required=False, source=SearchableTextSourceBinder({'object_provides' : IATFolder.__identifier__}, default_query='path:')) <NEW_LINE> entries = schema.Int(title=_(u"Entries"), description=_(u"The number of entries to show."), default=5, required=True) <NEW_LINE> entriesState = schema.List(title=_(u'Entries state'), description=_(u'Select the review state of the entries. Leave empty to show all the entries.'), value_type=schema.Choice(vocabulary="collective.portlet.blogstarlastentries.BlogEntryStatesVocabulary", required=False,) ) | A portlet
It inherits from IPortletDataProvider because for this portlet, the
data that is being rendered and the portlet assignment itself are the
same. | 62599061cc0a2c111447c62c |
class TestLicenseLicenseTier(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 testLicenseLicenseTier(self): <NEW_LINE> <INDENT> pass | LicenseLicenseTier unit test stubs | 62599061a219f33f346c7ec1 |
class HelloViewSet(viewsets.ViewSet): <NEW_LINE> <INDENT> serializer_class=serializers.HelloSerializer <NEW_LINE> def list(self, request): <NEW_LINE> <INDENT> a_viewset = [ 'Uses action (list, create, retrieve, update, partial_update)', 'Automatically maps to URLs using routers', 'Prvides more functionality with less code' ] <NEW_LINE> return Response({'message':'Hello!','a_viewset':a_viewset}) <NEW_LINE> <DEDENT> def create(self, request): <NEW_LINE> <INDENT> serializer = serializers.HelloSerializer(data = request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> name = serializer.data.get('name') <NEW_LINE> message = "Hello {0}".format(name) <NEW_LINE> return Response({'message':message}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response( serializer.errors, status = status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> <DEDENT> def retrieve(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method': 'GET'}) <NEW_LINE> <DEDENT> def update(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method': 'PUT'}) <NEW_LINE> <DEDENT> def partial_update(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method': 'PATCH'}) <NEW_LINE> <DEDENT> def destroy(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method': 'DESTROY'}) | Test API ViewSet | 6259906191f36d47f22319ec |
class dataflow_fmri_with_confound(dataflow.DataFlow): <NEW_LINE> <INDENT> def __init__(self, fmri_files, confound_files): <NEW_LINE> <INDENT> assert (len(fmri_files) == len(confound_files)) <NEW_LINE> self.fmri_files = fmri_files <NEW_LINE> self.confound_files = confound_files <NEW_LINE> self._size = len(fmri_files) <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return self._size <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> for a, b in zip(self.fmri_files, self.confound_files): <NEW_LINE> <INDENT> yield a, b | Iterate through fmri filenames and confound filenames
| 625990613539df3088ecd957 |
class PagedResult(Result): <NEW_LINE> <INDENT> def __init__(self, access_token, path, page_num, params, data, endpoint=None): <NEW_LINE> <INDENT> super(PagedResult, self).__init__(access_token, path, params, data) <NEW_LINE> self.page = page_num <NEW_LINE> self.endpoint = endpoint <NEW_LINE> <DEDENT> def next_page(self): <NEW_LINE> <INDENT> params = copy.copy(self.params) <NEW_LINE> params['page'] = self.page + 1 <NEW_LINE> return _get_api(self.path, endpoint=self.endpoint, **params) <NEW_LINE> <DEDENT> def prev_page(self): <NEW_LINE> <INDENT> if self.page <= 1: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> params = copy.copy(self.params) <NEW_LINE> params['page'] = self.page - 1 <NEW_LINE> return _get_api(self.path, endpoint=self.endpoint, **params) | This class wraps the response from an API call that responded with
a page of results.
Usage:
result = search_items(title='foo', fields=['id'])
print 'First page: %d, data: %s' % (result.page, result.data)
result = result.next_page()
print 'Second page: %d, data: %s' % (result.page, result.data) | 6259906107f4c71912bb0af7 |
class TestCleanXMLFile(test.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpTestData(cls): <NEW_LINE> <INDENT> cls.user = UserFactory(username='xml user', email='[email protected]') <NEW_LINE> cls.priority = Priority.objects.get(value='P1') <NEW_LINE> cls.status_confirmed = TestCaseStatus.objects.get(name='CONFIRMED') <NEW_LINE> cls.original_xml_version = None <NEW_LINE> if hasattr(settings, 'TESTOPIA_XML_VERSION'): <NEW_LINE> <INDENT> cls.original_xml_version = settings.TESTOPIA_XML_VERSION <NEW_LINE> <DEDENT> settings.TESTOPIA_XML_VERSION = 1.1 <NEW_LINE> <DEDENT> def test_clean_xml_file(self): <NEW_LINE> <INDENT> result = clean_xml_file(xml_file_without_error) <NEW_LINE> self.assertEqual(2, len(result)) <NEW_LINE> result = clean_xml_file(xml_file_single_case_without_error) <NEW_LINE> self.assertEqual(1, len(result)) <NEW_LINE> self.assertRaises(User.DoesNotExist, clean_xml_file, xml_file_with_error) <NEW_LINE> self.assertRaises(ValueError, clean_xml_file, xml_file_in_malformat) <NEW_LINE> self.assertRaises(ValueError, clean_xml_file, xml_file_with_wrong_version) | Test for testplan.clean_xml_file | 6259906145492302aabfdb95 |
class SelectBySuffix(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.select_by_suffix" <NEW_LINE> bl_label = "Select by Suffix" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> global converted <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return ((len(context.selected_objects) > 0) and (context.mode == 'OBJECT')) <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> sname = context.object.name <NEW_LINE> if not '_' in sname: <NEW_LINE> <INDENT> ssuffix = [sname, None] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ssuffix = sname.split('_') <NEW_LINE> <DEDENT> for ob in context.scene.objects: <NEW_LINE> <INDENT> if not '_' in ob.name: <NEW_LINE> <INDENT> suffixes = ob.name, None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> suffixes = ob.name.split('_') <NEW_LINE> <DEDENT> if ssuffix[-1]==suffixes[-1]: <NEW_LINE> <INDENT> ob.select = True <NEW_LINE> <DEDENT> <DEDENT> return {'FINISHED'} | Select all objects with the same suffix | 625990614a966d76dd5f05ae |
class UserModelTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.new_user = User(password = 'banana') <NEW_LINE> <DEDENT> def test_password_setter(self): <NEW_LINE> <INDENT> self.assertTrue(self.new_user.password_hash is not None) <NEW_LINE> <DEDENT> def test_no_access_password(self): <NEW_LINE> <INDENT> with self.assertRaises(AttributeError): <NEW_LINE> <INDENT> self.new_user.password <NEW_LINE> <DEDENT> <DEDENT> def test_password_verification(self): <NEW_LINE> <INDENT> self.assertTrue(self.new_user.verify_password('banana')) | Test class to test behaviours of the [Class] class
Args:
unittest.TestCase : Test case class that helps create test cases | 62599061004d5f362081fb4d |
class Connection: <NEW_LINE> <INDENT> def __init__(self, dbname): <NEW_LINE> <INDENT> self.dbname = dbname <NEW_LINE> self.conn = self.connect() <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> return psycopg2.connect("dbname=%s" % self.dbname) <NEW_LINE> <DEDENT> def execute(self, query, args=None, update=False): <NEW_LINE> <INDENT> cur = self.conn.cursor() <NEW_LINE> if args: <NEW_LINE> <INDENT> cur.execute(query, args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur.execute(query) <NEW_LINE> <DEDENT> if update: <NEW_LINE> <INDENT> self.conn.commit() <NEW_LINE> <DEDENT> return cur <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.conn.close() | Provides handful operations and destroys DB connection automatically | 625990617d847024c075da90 |
class Zip(Package): <NEW_LINE> <INDENT> def extract_zip(self, zip_path, extract_path, password, recursion_depth): <NEW_LINE> <INDENT> if self.is_overwritten(zip_path): <NEW_LINE> <INDENT> log.debug("ZIP file contains a file with the same name, original is going to be overwrite") <NEW_LINE> new_zip_path = zip_path + ".old" <NEW_LINE> shutil.move(zip_path, new_zip_path) <NEW_LINE> zip_path = new_zip_path <NEW_LINE> <DEDENT> with ZipFile(zip_path, "r") as archive: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> archive.extractall(path=extract_path, pwd=password) <NEW_LINE> <DEDENT> except BadZipfile: <NEW_LINE> <INDENT> raise CuckooPackageError("Invalid Zip file") <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> archive.extractall(path=extract_path, pwd="infected") <NEW_LINE> <DEDENT> except RuntimeError as e: <NEW_LINE> <INDENT> raise CuckooPackageError("Unable to extract Zip file: " "{0}".format(e)) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> if recursion_depth < 4: <NEW_LINE> <INDENT> for name in archive.namelist(): <NEW_LINE> <INDENT> if name.endswith(".zip"): <NEW_LINE> <INDENT> self.extract_zip(os.path.join(extract_path, name), extract_path, password, recursion_depth + 1) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def is_overwritten(self, zip_path): <NEW_LINE> <INDENT> with ZipFile(zip_path, "r") as archive: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for name in archive.namelist(): <NEW_LINE> <INDENT> if name == os.path.basename(zip_path): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> except BadZipfile: <NEW_LINE> <INDENT> raise CuckooPackageError("Invalid Zip file") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_infos(self, zip_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with ZipFile(zip_path, "r") as archive: <NEW_LINE> <INDENT> return archive.infolist() <NEW_LINE> <DEDENT> <DEDENT> except BadZipfile: <NEW_LINE> <INDENT> raise CuckooPackageError("Invalid Zip file") <NEW_LINE> <DEDENT> <DEDENT> def start(self, path): <NEW_LINE> <INDENT> root = os.environ["TEMP"] <NEW_LINE> password = self.options.get("password") <NEW_LINE> exe_regex = re.compile('(\.exe|\.scr|\.msi|\.bat|\.lnk)$',flags=re.IGNORECASE) <NEW_LINE> zipinfos = self.get_infos(path) <NEW_LINE> self.extract_zip(path, root, password, 0) <NEW_LINE> file_name = self.options.get("file") <NEW_LINE> if not file_name: <NEW_LINE> <INDENT> if len(zipinfos): <NEW_LINE> <INDENT> for f in zipinfos: <NEW_LINE> <INDENT> if exe_regex.search(f.filename): <NEW_LINE> <INDENT> file_name = f.filename <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> file_name = file_name if file_name else zipinfos[0].filename <NEW_LINE> log.debug("Missing file option, auto executing: {0}".format(file_name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise CuckooPackageError("Empty ZIP archive") <NEW_LINE> <DEDENT> <DEDENT> file_path = os.path.join(root, file_name) <NEW_LINE> return self.execute(file_path, self.options.get("arguments"), file_path) | Zip analysis package. | 62599061435de62698e9d4c2 |
class RedisOrderOperation(BaseRedis): <NEW_LINE> <INDENT> def __init__(self, db, redis): <NEW_LINE> <INDENT> super().__init__(db, redis) <NEW_LINE> <DEDENT> def set_order_expiration(self, pk): <NEW_LINE> <INDENT> with manage_redis(self.db) as redis: <NEW_LINE> <INDENT> key = OrderCreateSerializer.generate_orderid(pk) <NEW_LINE> redis.setex(key, 3000, 1) | the operation of Shopper about redis | 6259906116aa5153ce401b98 |
class Rule(_messages.Message): <NEW_LINE> <INDENT> class ActionValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> NO_ACTION = 0 <NEW_LINE> ALLOW = 1 <NEW_LINE> ALLOW_WITH_LOG = 2 <NEW_LINE> DENY = 3 <NEW_LINE> DENY_WITH_LOG = 4 <NEW_LINE> LOG = 5 <NEW_LINE> <DEDENT> action = _messages.EnumField('ActionValueValuesEnum', 1) <NEW_LINE> conditions = _messages.MessageField('Condition', 2, repeated=True) <NEW_LINE> description = _messages.StringField(3) <NEW_LINE> in_ = _messages.StringField(4, repeated=True) <NEW_LINE> logConfig = _messages.MessageField('LogConfig', 5, repeated=True) <NEW_LINE> notIn = _messages.StringField(6, repeated=True) <NEW_LINE> permissions = _messages.StringField(7, repeated=True) | A rule to be applied in a Policy.
Enums:
ActionValueValuesEnum: Required
Fields:
action: Required
conditions: Additional restrictions that must be met
description: Human-readable description of the rule.
in_: The rule matches if the PRINCIPAL/AUTHORITY_SELECTOR is in this set
of entries.
logConfig: The config returned to callers of tech.iam.IAM.CheckPolicy for
any entries that match the LOG action.
notIn: The rule matches if the PRINCIPAL/AUTHORITY_SELECTOR is not in this
set of entries. The format for in and not_in entries is the same as for
members in a Binding (see google/iam/v1/policy.proto).
permissions: A permission is a string of form '<service>.<resource
type>.<verb>' (e.g., 'storage.buckets.list'). A value of '*' matches all
permissions, and a verb part of '*' (e.g., 'storage.buckets.*') matches
all verbs. | 625990618a43f66fc4bf384a |
class WFIRSTObservatoryL2(ObservatoryL2Halo): <NEW_LINE> <INDENT> def __init__(self, **specs): <NEW_LINE> <INDENT> ObservatoryL2Halo.__init__(self,**specs) | WFIRST Observatory at L2 implementation.
Contains methods and parameters unique to the WFIRST mission. | 62599061627d3e7fe0e08546 |
class RemoveFixedIP(command.Command): <NEW_LINE> <INDENT> deprecated = True <NEW_LINE> log = logging.getLogger('deprecated') <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(RemoveFixedIP, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( "ip_address", metavar="<ip-address>", help=_("IP address to remove from server (name only)"), ) <NEW_LINE> parser.add_argument( "server", metavar="<server>", help=_("Server to remove the IP address from (name or ID)"), ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> self.log.warning(_('This command has been deprecated. ' 'Please use "server remove fixed ip" instead.')) <NEW_LINE> compute_client = self.app.client_manager.compute <NEW_LINE> server = utils.find_resource( compute_client.servers, parsed_args.server) <NEW_LINE> server.remove_fixed_ip(parsed_args.ip_address) | Remove fixed IP address from server | 6259906199cbb53fe683259d |
class IdentifyDevice(_StandardCommand): <NEW_LINE> <INDENT> _cmdval = 0x25 <NEW_LINE> _sendtwice = True | Identify Device
Start or restart a 10s timer. While the timer is running the
device will run a procedure to enable an observer to distinguish
the device from other devices in which it is not running. This
procedure is manufacturer-dependent.
Identification will be stopped immediately upon reception of any
command other than Initialise, RecallMinLevel, RecallMaxLevel or
IdentifyDevice. | 625990618e7ae83300eea749 |
class StartJobUpdateResult(object): <NEW_LINE> <INDENT> __slots__ = [ 'key', 'updateSummary', ] <NEW_LINE> thrift_spec = ( None, (1, TType.STRUCT, 'key', (JobUpdateKey, JobUpdateKey.thrift_spec), None, ), (2, TType.STRUCT, 'updateSummary', (JobUpdateSummary, JobUpdateSummary.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, key=None, updateSummary=None,): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.updateSummary = updateSummary <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.key = JobUpdateKey() <NEW_LINE> self.key.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.updateSummary = JobUpdateSummary() <NEW_LINE> self.updateSummary.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('StartJobUpdateResult') <NEW_LINE> if self.key is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('key', TType.STRUCT, 1) <NEW_LINE> self.key.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.updateSummary is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('updateSummary', TType.STRUCT, 2) <NEW_LINE> self.updateSummary.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, getattr(self, key)) for key in self.__slots__] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for attr in self.__slots__: <NEW_LINE> <INDENT> my_val = getattr(self, attr) <NEW_LINE> other_val = getattr(other, attr) <NEW_LINE> if my_val != other_val: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Result of the startUpdate call.
Attributes:
- key: Unique identifier for the job update.
- updateSummary: Summary of the update that is in progress for the given JobKey. | 62599061462c4b4f79dbd0c1 |
class LISTAConvDictADMM(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_input_channels=3, num_output_channels=3, kc=64, ks=7, ista_iters=3, iter_weight_share=True, pad='reflection', norm_weights=True): <NEW_LINE> <INDENT> super(LISTAConvDictADMM, self).__init__() <NEW_LINE> if iter_weight_share == False: <NEW_LINE> <INDENT> raise NotImplementedError('untied weights is not implemented yet...') <NEW_LINE> <DEDENT> self._ista_iters = ista_iters <NEW_LINE> self.softthrsh = SoftshrinkTrainable(Parameter(0.1 * torch.ones(1, kc), requires_grad=True)) <NEW_LINE> self.encode_conv = dp_conv( num_input_channels, kc, ks, stride=1, bias=False, pad=pad ) <NEW_LINE> self.decode_conv0 = dp_conv( kc, num_input_channels, ks, stride=1, bias=False, pad=pad ) <NEW_LINE> self.decode_conv1 = dp_conv( kc, num_input_channels, ks, stride=1, bias=False, pad=pad ) <NEW_LINE> self.mu = Parameter(0.6 * torch.ones(1), requires_grad=True) <NEW_LINE> <DEDENT> def _init_vars(self): <NEW_LINE> <INDENT> wd = self.decode_conv[1].weight.data <NEW_LINE> wd = F.normalize(F.normalize(wd, p=2, dim=2), p=2, dim=3) <NEW_LINE> self.decode_conv[1].weight.data = wd <NEW_LINE> self.encode_conv[1].weight.data = we <NEW_LINE> <DEDENT> def forward_enc(self, inputs): <NEW_LINE> <INDENT> sc = self.softthrsh(self.encode_conv(inputs)) <NEW_LINE> for step in range(self._ista_iters): <NEW_LINE> <INDENT> _inputs = self.mu * inputs + (1 - self.mu) * self.decode_conv0(sc) <NEW_LINE> sc_residual = self.encode_conv( _inputs - self.decode_conv1(sc) ) <NEW_LINE> sc = self.softthrsh(sc + sc_residual) <NEW_LINE> <DEDENT> return sc <NEW_LINE> <DEDENT> def forward_dec(self, sc): <NEW_LINE> <INDENT> return self.decode_conv0(sc) <NEW_LINE> <DEDENT> def forward(self, inputs): <NEW_LINE> <INDENT> sc = self.forward_enc(inputs) <NEW_LINE> outputs = self.forward_dec(sc) <NEW_LINE> return outputs, sc | LISTA ConvDict encoder based on paper:
https://arxiv.org/pdf/1711.00328.pdf | 625990616e29344779b01d0b |
class CardItem(object): <NEW_LINE> <INDENT> def __init__(self, title, url, pic_url=None): <NEW_LINE> <INDENT> super(CardItem, self).__init__() <NEW_LINE> self.title = title <NEW_LINE> self.url = url <NEW_LINE> self.pic_url = pic_url <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> if is_not_null_and_blank_str(self.pic_url) and is_not_null_and_blank_str( self.title) and is_not_null_and_blank_str(self.url): <NEW_LINE> <INDENT> data = { "title": self.title, "messageURL": self.url, "picURL": self.pic_url } <NEW_LINE> return data <NEW_LINE> <DEDENT> elif is_not_null_and_blank_str(self.title) and is_not_null_and_blank_str(self.url): <NEW_LINE> <INDENT> data = { "title": self.title, "actionURL": self.url } <NEW_LINE> return data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.error("CardItem是ActionCard的子控件时,title、url不能为空;是FeedCard的子控件时,title、url、pic_url不能为空!") <NEW_LINE> raise ValueError("CardItem是ActionCard的子控件时,title、url不能为空;是FeedCard的子控件时,title、url、pic_url不能为空!") | ActionCard和FeedCard消息类型中的子控件 | 6259906176e4537e8c3f0c49 |
class CompanyForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Company <NEW_LINE> fields = ('name',) <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._caffe = kwargs.pop('caffe') <NEW_LINE> kwargs.setdefault('label_suffix', '') <NEW_LINE> super(CompanyForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['name'].label = 'Nazwa' <NEW_LINE> <DEDENT> def clean_name(self): <NEW_LINE> <INDENT> name = self.cleaned_data['name'] <NEW_LINE> query = Company.objects.filter(name=name, caffe=self._caffe) <NEW_LINE> if query.exists(): <NEW_LINE> <INDENT> raise ValidationError(_('Nazwa nie jest unikalna.')) <NEW_LINE> <DEDENT> return name <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> company = super(CompanyForm, self).save(commit=False) <NEW_LINE> company.caffe = self._caffe <NEW_LINE> if commit: <NEW_LINE> <INDENT> company.save() <NEW_LINE> <DEDENT> return company | Responsible for creating a Company. | 62599061435de62698e9d4c3 |
class ScalarFactor(AbstractFactor): <NEW_LINE> <INDENT> __slots__ = ["dimension", "exponent"] <NEW_LINE> def __init__(self, factor_dimension, factor_exponent): <NEW_LINE> <INDENT> self.dimension = factor_dimension <NEW_LINE> self.exponent = factor_exponent <NEW_LINE> self.value_idx = None <NEW_LINE> <DEDENT> def __str__(self, factor_fmt_str="x_{dim}^{exp}", *args, **kwargs): <NEW_LINE> <INDENT> return factor_fmt_str.format(**{"dim": self.dimension + 1, "exp": self.exponent}) <NEW_LINE> <DEDENT> def __repr__(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.__str__(*args, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_ops(self) -> int: <NEW_LINE> <INDENT> if self.exponent > 1: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> <DEDENT> def compute(self, x, value_array): <NEW_LINE> <INDENT> value_array[self.value_idx] = x[self.dimension] ** self.exponent <NEW_LINE> <DEDENT> def get_recipe(self): <NEW_LINE> <INDENT> if self.exponent == 1: <NEW_LINE> <INDENT> return [(self.value_idx, self.dimension)], [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [], [(self.value_idx, self.dimension, self.exponent)] <NEW_LINE> <DEDENT> <DEDENT> def get_instructions(self, array_name: str) -> str: <NEW_LINE> <INDENT> dim = self.dimension <NEW_LINE> exp = self.exponent <NEW_LINE> idx = self.value_idx <NEW_LINE> instr = f"x[{dim}]" <NEW_LINE> if exp > 1: <NEW_LINE> <INDENT> instr = f"pow({instr},{exp})" <NEW_LINE> <DEDENT> instr = f"{array_name}[{idx}] = {instr};\n" <NEW_LINE> return instr | a factor depending on just one variable: :math:`f(x) = x_d^e` | 62599061cc0a2c111447c62d |
class CSVContinueDataset(CSVDatasetBase, ContinueDatasetBase): <NEW_LINE> <INDENT> source_file: Optional[str] = None <NEW_LINE> _base_directory: Optional[str] = None <NEW_LINE> def __init__( self, *, authorized: Optional[bool] = None, remove_unneeded_fields: Optional[bool] = None, base_directory: Optional[str] = None, ) -> None: <NEW_LINE> <INDENT> if base_directory is not None: <NEW_LINE> <INDENT> self.set_base_directory(base_directory) <NEW_LINE> <DEDENT> super().__init__( authorized=authorized, remove_unneeded_fields=remove_unneeded_fields ) <NEW_LINE> <DEDENT> def __contains__(self, value: str) -> bool: <NEW_LINE> <INDENT> for row in self.get_content(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if value == row["idna_subject"]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def __getattr__(self, value: Any) -> Any: <NEW_LINE> <INDENT> raise AttributeError(value) <NEW_LINE> <DEDENT> def __getitem__(self, value: Any) -> Any: <NEW_LINE> <INDENT> raise KeyError(value) <NEW_LINE> <DEDENT> def update_source_file_afterwards(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> result = func(self, *args, **kwargs) <NEW_LINE> self.source_file = os.path.join( self.base_directory, PyFunceble.cli.storage.AUTOCONTINUE_FILE ) <NEW_LINE> return result <NEW_LINE> <DEDENT> return wrapper <NEW_LINE> <DEDENT> @property <NEW_LINE> def base_directory(self) -> Optional[str]: <NEW_LINE> <INDENT> return self._base_directory <NEW_LINE> <DEDENT> @base_directory.setter <NEW_LINE> @update_source_file_afterwards <NEW_LINE> def base_directory(self, value: str) -> None: <NEW_LINE> <INDENT> if not isinstance(value, str): <NEW_LINE> <INDENT> raise TypeError(f"<value> should be {str}, {type(value)} given.") <NEW_LINE> <DEDENT> if not value: <NEW_LINE> <INDENT> raise ValueError("<value> should not be empty.") <NEW_LINE> <DEDENT> self._base_directory = value <NEW_LINE> <DEDENT> def set_base_directory(self, value: str) -> "CSVContinueDataset": <NEW_LINE> <INDENT> self.base_directory = value <NEW_LINE> return self <NEW_LINE> <DEDENT> @CSVDatasetBase.execute_if_authorized(None) <NEW_LINE> def cleanup(self) -> "CSVContinueDataset": <NEW_LINE> <INDENT> if self.source_file: <NEW_LINE> <INDENT> FileHelper(self.source_file).delete() <NEW_LINE> PyFunceble.facility.Logger.debug("Deleted: %r", self.source_file) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> @CSVDatasetBase.execute_if_authorized(None) <NEW_LINE> def get_to_test(self, session_id: str) -> Generator[Tuple[str], str, None]: <NEW_LINE> <INDENT> min_days = 365.25 * 20 <NEW_LINE> for data in self.get_filtered_content({"session_id": session_id}): <NEW_LINE> <INDENT> if (datetime.utcnow() - data["tested_at"]).days < min_days: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not data["idna_subject"]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> yield data["idna_subject"] | Provides the interface for the management of the continue
CSV file. | 6259906132920d7e50bc7703 |
class Vector3(Vector): <NEW_LINE> <INDENT> def __new__(cls, data, type = None): <NEW_LINE> <INDENT> data = np.array(data) <NEW_LINE> if type == None: <NEW_LINE> <INDENT> type = data.dtype <NEW_LINE> <DEDENT> return Vector.__new__(cls, shape = (3,), data = data, type = type) <NEW_LINE> <DEDENT> @property <NEW_LINE> def x (self): <NEW_LINE> <INDENT> return self[0] <NEW_LINE> <DEDENT> @x.setter <NEW_LINE> def x (self, value): <NEW_LINE> <INDENT> self[0] = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def y (self): <NEW_LINE> <INDENT> return self[1] <NEW_LINE> <DEDENT> @y.setter <NEW_LINE> def y (self, value): <NEW_LINE> <INDENT> self[1] = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def z (self): <NEW_LINE> <INDENT> return self[2] <NEW_LINE> <DEDENT> @z.setter <NEW_LINE> def z (self, value): <NEW_LINE> <INDENT> self[2] = value <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def zeros(type=None): <NEW_LINE> <INDENT> return Vector3([0.0,0.0,0.0], type) | 3D-s vektor
Az általános C{Vector} specializálása, mely csak három elemű vektort képes
csak elfogadni.
Az adattagok névvel és indexxel is elérhetők | 625990611f037a2d8b9e53c9 |
class _LoremFlickr(RemoteImage): <NEW_LINE> <INDENT> LOREM_FLICKR_URL = 'https://loremflickr.com' <NEW_LINE> WIDTH = 1280 <NEW_LINE> HEIGHT = 768 <NEW_LINE> def __init__(self, keyword: str) -> None: <NEW_LINE> <INDENT> super().__init__(self._build_url(_LoremFlickr.LOREM_FLICKR_URL, _LoremFlickr.WIDTH, _LoremFlickr.HEIGHT, keyword)) <NEW_LINE> <DEDENT> def _build_url(self, url: str, width: int, height: int, keyword: str) -> str: <NEW_LINE> <INDENT> return ( f'{url}/{width}/{height}/{keyword}' ) | キーワードをもとにネットから画像を取得する。
Args:
keyword (str): キーワード | 625990610c0af96317c578bd |
class OutputFormatTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def testOutputFormatConstructor(self): <NEW_LINE> <INDENT> new_format = mapscript.outputFormatObj('GDAL/GTiff', 'gtiff') <NEW_LINE> assert new_format.name == 'gtiff' <NEW_LINE> assert new_format.mimetype == 'image/tiff' | http://mapserver.gis.umn.edu/bugs/show_bug.cgi?id=511 | 625990613617ad0b5ee0780b |
class SupportedBuildpackResource(ProxyResource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'system_data': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'system_data': {'key': 'systemData', 'type': 'SystemData'}, 'properties': {'key': 'properties', 'type': 'SupportedBuildpackResourceProperties'}, } <NEW_LINE> def __init__( self, *, properties: Optional["SupportedBuildpackResourceProperties"] = None, **kwargs ): <NEW_LINE> <INDENT> super(SupportedBuildpackResource, self).__init__(**kwargs) <NEW_LINE> self.properties = properties | Supported buildpack resource payload.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource Id for the resource.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource.
:vartype type: str
:ivar system_data: Metadata pertaining to creation and last modification of the resource.
:vartype system_data: ~azure.mgmt.appplatform.v2022_01_01_preview.models.SystemData
:ivar properties: Supported buildpack resource properties.
:vartype properties:
~azure.mgmt.appplatform.v2022_01_01_preview.models.SupportedBuildpackResourceProperties | 625990614f88993c371f107d |
class InvalidFormatException(Exception): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> Exception.__init__(self, *args, **kwargs) | InvalidFormatException: raised when file format is unrecognized | 625990618e71fb1e983bd188 |
class ResultModel(dict): <NEW_LINE> <INDENT> def __init__(self, **kw): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> for k, v in kw.items(): <NEW_LINE> <INDENT> self.__setattr__(k, v) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> self[str.replace(name, '-', '_')] = value <NEW_LINE> <DEDENT> def __getattr__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError(r"'%s' object has no attribute '%s'" % (self.__class__.__name__, key)) | The base class of the response data. | 6259906156b00c62f0fb3f88 |
class TransitiveIdealGraded(RecursivelyEnumeratedSet_generic): <NEW_LINE> <INDENT> def __init__(self, succ, generators, max_depth=float("inf")): <NEW_LINE> <INDENT> RecursivelyEnumeratedSet_generic.__init__(self, seeds=generators, successors=succ, enumeration='breadth', max_depth=max_depth) <NEW_LINE> self._generators = self._seeds <NEW_LINE> self._succ = self.successors <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self.breadth_first_search_iterator() | Generic tool for constructing ideals of a relation.
INPUT:
- ``relation`` -- a function (or callable) returning a list (or iterable)
- ``generators`` -- a list (or iterable)
- ``max_depth`` -- (Default: infinity) Specifies the maximal depth to
which elements are computed
Return the set `S` of elements that can be obtained by repeated
application of ``relation`` on the elements of ``generators``.
Consider ``relation`` as modeling a directed graph (possibly with
loops, cycles, or circuits). Then `S` is the ideal generated by
``generators`` under this relation.
Enumerating the elements of `S` is achieved by breadth first search
through the graph; hence elements are enumerated by increasing
distance from the generators. The time complexity is `O(n+m)`
where `n` is the size of the ideal, and `m` the number of edges in
the relation. The memory complexity is the depth, that is the
maximal distance between a generator and an element of `S`.
See also :class:`SearchForest` and :class:`TransitiveIdeal`.
EXAMPLES::
sage: [i for i in TransitiveIdealGraded(lambda i: [i+1] if i<10 else [], [0])]
doctest:...: DeprecationWarning: This class soon will not be
available in that way anymore. Use RecursivelyEnumeratedSet
instead. See http://trac.sagemath.org/6637 for details.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
We now illustrate that the enumeration is done lazily, by breadth first search::
sage: C = TransitiveIdealGraded(lambda x: [x-1, x+1], (-10, 0, 10))
sage: f = C.__iter__()
The elements at distance 0 from the generators::
sage: sorted([ next(f) for i in range(3) ])
[-10, 0, 10]
The elements at distance 1 from the generators::
sage: sorted([ next(f) for i in range(6) ])
[-11, -9, -1, 1, 9, 11]
The elements at distance 2 from the generators::
sage: sorted([ next(f) for i in range(6) ])
[-12, -8, -2, 2, 8, 12]
The enumeration order between elements at the same distance is not specified.
We compute all the permutations which are larger than [3,1,2,4] or
[2,1,3,4] in the permutohedron::
sage: [p for p in TransitiveIdealGraded(attrcall("permutohedron_succ"), [Permutation([3,1,2,4]), Permutation([2,1,3,4])])]
[[3, 1, 2, 4], [2, 1, 3, 4], [2, 1, 4, 3], [3, 2, 1, 4], [2, 3, 1, 4], [3, 1, 4, 2], [2, 3, 4, 1], [3, 4, 1, 2], [3, 2, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1], [4, 3, 1, 2], [4, 2, 1, 3], [3, 4, 2, 1], [4, 2, 3, 1], [4, 3, 2, 1]] | 6259906156ac1b37e6303845 |
class GaussBandit(Bandit): <NEW_LINE> <INDENT> def __init__(self, mu, seed=None): <NEW_LINE> <INDENT> super().__init__(mu, seed) <NEW_LINE> <DEDENT> def randomize(self): <NEW_LINE> <INDENT> self.rt = (np.minimum(np.maximum(self.random.normal(self.mu, 0.1), 0), 1)).astype(float) <NEW_LINE> <DEDENT> def print(self): <NEW_LINE> <INDENT> return "Gaussian bandit with arms (%s)" % ", ".join("%.3f" % s for s in self.mu) | Bernoulli bandit. | 62599061435de62698e9d4c4 |
class GraphQLScalarType(GraphQLNamedType): <NEW_LINE> <INDENT> __slots__ = "name", "description", "serialize", "parse_value", "parse_literal" <NEW_LINE> def __init__( self, name, description=None, serialize=None, parse_value=None, parse_literal=None, ): <NEW_LINE> <INDENT> assert name, "Type must be named." <NEW_LINE> assert_valid_name(name) <NEW_LINE> self.name = name <NEW_LINE> self.description = description <NEW_LINE> assert callable(serialize), ( '{} must provide "serialize" function. If this custom Scalar is ' 'also used as an input type, ensure "parse_value" and "parse_literal" ' "functions are also provided." ).format(self) <NEW_LINE> if parse_value is not None or parse_literal is not None: <NEW_LINE> <INDENT> assert callable(parse_value) and callable( parse_literal ), '{} must provide both "parse_value" and "parse_literal" functions.'.format( self ) <NEW_LINE> <DEDENT> self.serialize = serialize <NEW_LINE> self.parse_value = parse_value or none_func <NEW_LINE> self.parse_literal = parse_literal or none_func <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name | Scalar Type Definition
The leaf values of any request and input values to arguments are
Scalars (or Enums) and are defined with a name and a series of coercion
functions used to ensure validity.
Example:
def coerce_odd(value):
if value % 2 == 1:
return value
return None
OddType = GraphQLScalarType(name='Odd', serialize=coerce_odd) | 625990611f5feb6acb1642a8 |
class advFileManager(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.current_directory = False <NEW_LINE> <DEDENT> def open_stage_file(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> full_name = filename <NEW_LINE> stage_content = open(full_name, "r", encoding="utf-8").read() <NEW_LINE> <DEDENT> except FileNotFoundError as error: <NEW_LINE> <INDENT> dprint(f"[!]Stage file not found:", filename) <NEW_LINE> print(filename, " is not found") <NEW_LINE> return False <NEW_LINE> <DEDENT> code_block = re.compile(r'([#\!\¡])([áéíóúa-zA-Z0-9_-\|-\s-]*)\{(.*?)\}', re.MULTILINE | re.DOTALL) <NEW_LINE> blocks = code_block.findall(stage_content) <NEW_LINE> if blocks: <NEW_LINE> <INDENT> return blocks <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def load_stage_file(self, stage_file, adv_dir=''): <NEW_LINE> <INDENT> if adv_dir: <NEW_LINE> <INDENT> dprint(f"[+]Setting current directory in {adv_dir}") <NEW_LINE> self.current_directory = adv_dir <NEW_LINE> <DEDENT> if not self.current_directory: <NEW_LINE> <INDENT> self.current_directory = '' <NEW_LINE> <DEDENT> full_name = f"{self.current_directory}\\{stage_file}.adventure" <NEW_LINE> dprint(f"[+]Loading {full_name[-10:]}...") <NEW_LINE> parser_content = self.open_stage_file(full_name) <NEW_LINE> if not parser_content: <NEW_LINE> <INDENT> dprint( "[!]Error to load stage, invalid content or empty file") <NEW_LINE> return False <NEW_LINE> <DEDENT> return parser_content | open_stage_file : open file, check integrity and extract blocks
load_stage_file : dump stage content | 625990619c8ee82313040ce8 |
class TestBangdiwalaB(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.tests = [(array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), 0.1467764060356653), (array([[3600, 2595], [65, 3740]]), 0.575688404132935), (array([[9901, 64], [2, 33]]), 0.9933537203915539), (array([[9900, 86], [1, 13]]), 0.9912756264181609), (array([[21, 5], [3, 21]]), 0.7067307692307693), (array([[40, 5], [3, 2]]), 0.8142131979695432), (array([[40, 2], [3, 5]]), 0.8727175080558539), (array([[51, 4, 0, 1, 1], [3, 78, 1, 0, 0], [0, 0, 13, 4, 0], [0, 1, 1, 16, 7], [0, 0, 0, 0, 5]]), 0.851430701836145), (array([[136, 3], [1, 46]]), 0.965614166588588), ] <NEW_LINE> self.errors = [(array([[1, 2], [4, 5], [7, 8]]), ValueError), (array([[1, 2], [3, -4]]), ValueError), (array([[0, 0], [0, 0]]), ValueError) ] <NEW_LINE> <DEDENT> def test_bangdiwala_b(self): <NEW_LINE> <INDENT> for matrix, res in self.tests: <NEW_LINE> <INDENT> self.assertAlmostEqual(bangdiwala_b(matrix), res, places=7) <NEW_LINE> <DEDENT> <DEDENT> def test_bangdiwala_b_domain(self): <NEW_LINE> <INDENT> for matrix, err_type in self.errors: <NEW_LINE> <INDENT> with self.assertRaises(err_type): <NEW_LINE> <INDENT> bangdiwala_b(matrix) | This class implements the tests for Bangdiwala's B
| 625990618a43f66fc4bf384c |
class BTable( NonTerminal ) : <NEW_LINE> <INDENT> def __init__( self, parser, btableblocks ): <NEW_LINE> <INDENT> NonTerminal.__init__( self, parser, btableblocks ) <NEW_LINE> self._nonterms = (self.btableblocks,) = (btableblocks,) <NEW_LINE> self.setparent( self, self.children() ) <NEW_LINE> <DEDENT> def children( self ) : <NEW_LINE> <INDENT> return self._nonterms <NEW_LINE> <DEDENT> def show(self, buf=sys.stdout, offset=0, attrnames=False, showcoord=False): <NEW_LINE> <INDENT> lead = u' ' * offset <NEW_LINE> buf.write( lead + u'btable: ' ) <NEW_LINE> if showcoord : <NEW_LINE> <INDENT> buf.write( u' (at %s)' % self.coord ) <NEW_LINE> <DEDENT> buf.write(u'\n') <NEW_LINE> [ x.show(buf, offset+2, attrnames, showcoord) for x in self.children() ] | class to handle `btable` grammar. | 625990613c8af77a43b68aa0 |
class Player: <NEW_LINE> <INDENT> def __init__(self, checker): <NEW_LINE> <INDENT> assert(checker == 'X' or checker == 'O') <NEW_LINE> self.checker = checker <NEW_LINE> self.num_moves = 0 <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> s = 'Player ' + self.checker <NEW_LINE> return s <NEW_LINE> <DEDENT> def opponent_checker(self): <NEW_LINE> <INDENT> if self.checker == 'X': <NEW_LINE> <INDENT> return 'O' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'X' <NEW_LINE> <DEDENT> <DEDENT> def next_move(self, board): <NEW_LINE> <INDENT> x = int(input('Enter a column: ')) <NEW_LINE> while not board.can_add_to(x): <NEW_LINE> <INDENT> print('Try again!') <NEW_LINE> x = int(input('Enter a column: ')) <NEW_LINE> <DEDENT> self.num_moves += 1 <NEW_LINE> return x | a data type for a Connect Four player object
| 62599061e5267d203ee6cf1e |
class MultipleChoice(QuestionBase): <NEW_LINE> <INDENT> _question_answer_locator = (By.CSS_SELECTOR, '.openstax-answer') <NEW_LINE> _nudge_message_locator = ( By.XPATH, '//textarea/following-sibling::div[div[h5]]') <NEW_LINE> @property <NEW_LINE> def answers(self) -> List[MultipleChoice.Answer]: <NEW_LINE> <INDENT> return [self.Answer(self, option) for option in self.find_elements(*self._question_answer_locator)] <NEW_LINE> <DEDENT> def random_answer(self) -> None: <NEW_LINE> <INDENT> sleep(0.25) <NEW_LINE> answers = self.answers <NEW_LINE> if not answers: <NEW_LINE> <INDENT> raise TutorException('No answers found') <NEW_LINE> <DEDENT> answers[Utility.random(0, len(answers) - 1)].select() <NEW_LINE> sleep(0.25) <NEW_LINE> <DEDENT> class Answer(Region): <NEW_LINE> <INDENT> _answer_button_locator = (By.CSS_SELECTOR, '.answer-input-box') <NEW_LINE> _answer_letter_locator = (By.CSS_SELECTOR, '.answer-letter') <NEW_LINE> _answer_content_locator = (By.CSS_SELECTOR, '.answer-content') <NEW_LINE> @property <NEW_LINE> def answer_id(self) -> str: <NEW_LINE> <INDENT> return (self.find_element(*self._answer_button_locator) .get_attribute('id')) <NEW_LINE> <DEDENT> @property <NEW_LINE> def letter(self) -> str: <NEW_LINE> <INDENT> return self.find_element(*self._answer_letter_locator).text <NEW_LINE> <DEDENT> @property <NEW_LINE> def answer(self) -> str: <NEW_LINE> <INDENT> return (self.find_element(*self._answer_content_locator) .get_attribute('textContent')) <NEW_LINE> <DEDENT> def select(self) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> button = WebDriverWait(self.driver, 5).until( expect.presence_of_element_located( self._answer_button_locator)) <NEW_LINE> <DEDENT> except TimeoutException: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> Utility.click_option(self.driver, element=button) <NEW_LINE> sleep(0.75) | A mutiple choice response step for an assessment. | 625990618e7ae83300eea74b |
class SIM900_stick(VisaInstrument): <NEW_LINE> <INDENT> def __init__(self, name: str, address: str, reset: bool=False, **kwargs): <NEW_LINE> <INDENT> super().__init__(name, address, terminator='\n', **kwargs) <NEW_LINE> self.add_parameter('volt_p1', label='Port 1 Voltage', unit='V', set_cmd=partial(self.setvolt, 1, 'VOLT'), get_cmd=partial(self.get_from_port, 1, 'VOLT?'), get_parser=float, vals=vals.Numbers(-20, 20)) <NEW_LINE> self.add_parameter('volt_p2', label='Port 2 Voltage', unit='V', set_cmd=partial(self.setvolt, 2, 'VOLT'), get_cmd=partial(self.get_from_port, 2, 'VOLT?'), get_parser=float, vals=vals.Numbers(-20, 20)) <NEW_LINE> self.add_parameter('output_p1', set_cmd=partial(self.write_to_port, 1, 'EXON'), get_cmd=partial(self.get_from_port, 1, 'EXON?'), set_parser=parse_bool, get_parser=int, vals=vals.Enum(*boolcheck)) <NEW_LINE> self.add_parameter('output_p2', set_cmd=partial(self.write_to_port, 2, 'EXON'), get_cmd=partial(self.get_from_port, 2, 'EXON?'), set_parser=parse_bool, get_parser=int, vals=vals.Enum(*boolcheck)) <NEW_LINE> self.write('FLSH 1') <NEW_LINE> time.sleep(0.05) <NEW_LINE> self.write('FLSH 2') <NEW_LINE> time.sleep(0.05) <NEW_LINE> self.write_to_port(1, 'TERM', 2) <NEW_LINE> time.sleep(0.05) <NEW_LINE> self.write_to_port(5, 'TERM', 2) <NEW_LINE> time.sleep(0.05) <NEW_LINE> if reset: <NEW_LINE> <INDENT> self.reset() <NEW_LINE> <DEDENT> time.sleep(0.25) <NEW_LINE> self.connect_message() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.write_to_port(1, '*RST', '') <NEW_LINE> time.sleep(0.05) <NEW_LINE> self.write_to_port(2, '*RST', '') <NEW_LINE> time.sleep(0.05) <NEW_LINE> self.write('*RST') <NEW_LINE> time.sleep(0.05) <NEW_LINE> <DEDENT> def write_to_port(self, port, message, val): <NEW_LINE> <INDENT> sendmess = message + ' {}'.format(val) <NEW_LINE> s = 'SNDT {},'.format(int(port)) + '"{}"'.format(sendmess) <NEW_LINE> self.write(s) <NEW_LINE> time.sleep(0.05) <NEW_LINE> <DEDENT> def get_from_port(self, port, message): <NEW_LINE> <INDENT> self.write('FLOQ') <NEW_LINE> time.sleep(0.05) <NEW_LINE> s = 'SNDT {},'.format(int(port)) + '"{}"'.format(message) <NEW_LINE> self.write(s) <NEW_LINE> time.sleep(0.1) <NEW_LINE> ans = self.ask('GETN? {},20'.format(int(port)))[5:] <NEW_LINE> time.sleep(0.05) <NEW_LINE> return ans <NEW_LINE> <DEDENT> def setvolt(self, port, message, val): <NEW_LINE> <INDENT> self.write_to_port(port, message, np.round(val, 3)) | Instrument Driver for the SRS Frame SIM900. Configure this class if you
change the instruments and their port orders in the rack. Note that you
must reset or write the escape string if you connect to any single port
(using "CONN p,'escapestring'") | 62599061e76e3b2f99fda0be |
class TestAnomalyLogColouring(tests.GraphicsTest): <NEW_LINE> <INDENT> def test_plot_anomaly_log_colouring(self): <NEW_LINE> <INDENT> with fail_any_deprecation_warnings(): <NEW_LINE> <INDENT> with add_gallery_to_path(): <NEW_LINE> <INDENT> import plot_anomaly_log_colouring <NEW_LINE> <DEDENT> with show_replaced_by_check_graphic(self): <NEW_LINE> <INDENT> plot_anomaly_log_colouring.main() | Test the anomaly colouring gallery code. | 62599061cc0a2c111447c62e |
class DescribeLoginWhiteCombinedListResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TotalCount = None <NEW_LINE> self.LoginWhiteCombinedInfos = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TotalCount = params.get("TotalCount") <NEW_LINE> if params.get("LoginWhiteCombinedInfos") is not None: <NEW_LINE> <INDENT> self.LoginWhiteCombinedInfos = [] <NEW_LINE> for item in params.get("LoginWhiteCombinedInfos"): <NEW_LINE> <INDENT> obj = LoginWhiteCombinedInfo() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.LoginWhiteCombinedInfos.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RequestId = params.get("RequestId") | DescribeLoginWhiteCombinedList返回参数结构体
| 62599061379a373c97d9a6e2 |
class CharacterArrayCoder(VariableCoder): <NEW_LINE> <INDENT> def encode(self, variable, name=None): <NEW_LINE> <INDENT> variable = ensure_fixed_length_bytes(variable) <NEW_LINE> dims, data, attrs, encoding = unpack_for_encoding(variable) <NEW_LINE> if data.dtype.kind == "S" and encoding.get("dtype") is not str: <NEW_LINE> <INDENT> data = bytes_to_char(data) <NEW_LINE> if "char_dim_name" in encoding.keys(): <NEW_LINE> <INDENT> char_dim_name = encoding.pop("char_dim_name") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> char_dim_name = f"string{data.shape[-1]}" <NEW_LINE> <DEDENT> dims = dims + (char_dim_name,) <NEW_LINE> <DEDENT> return Variable(dims, data, attrs, encoding) <NEW_LINE> <DEDENT> def decode(self, variable, name=None): <NEW_LINE> <INDENT> dims, data, attrs, encoding = unpack_for_decoding(variable) <NEW_LINE> if data.dtype == "S1" and dims: <NEW_LINE> <INDENT> encoding["char_dim_name"] = dims[-1] <NEW_LINE> dims = dims[:-1] <NEW_LINE> data = char_to_bytes(data) <NEW_LINE> <DEDENT> return Variable(dims, data, attrs, encoding) | Transforms between arrays containing bytes and character arrays. | 6259906129b78933be26ac23 |
class CountryResource(object): <NEW_LINE> <INDENT> swagger_types = { 'iso2': 'str', 'iso3': 'str', 'name': 'str' } <NEW_LINE> attribute_map = { 'iso2': 'iso2', 'iso3': 'iso3', 'name': 'name' } <NEW_LINE> def __init__(self, iso2=None, iso3=None, name=None): <NEW_LINE> <INDENT> self._iso2 = None <NEW_LINE> self._iso3 = None <NEW_LINE> self._name = None <NEW_LINE> self.discriminator = None <NEW_LINE> if iso2 is not None: <NEW_LINE> <INDENT> self.iso2 = iso2 <NEW_LINE> <DEDENT> if iso3 is not None: <NEW_LINE> <INDENT> self.iso3 = iso3 <NEW_LINE> <DEDENT> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def iso2(self): <NEW_LINE> <INDENT> return self._iso2 <NEW_LINE> <DEDENT> @iso2.setter <NEW_LINE> def iso2(self, iso2): <NEW_LINE> <INDENT> self._iso2 = iso2 <NEW_LINE> <DEDENT> @property <NEW_LINE> def iso3(self): <NEW_LINE> <INDENT> return self._iso3 <NEW_LINE> <DEDENT> @iso3.setter <NEW_LINE> def iso3(self, iso3): <NEW_LINE> <INDENT> self._iso3 = iso3 <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, CountryResource): <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. | 625990618e71fb1e983bd189 |
class FunctionHintSource: <NEW_LINE> <INDENT> EH_FRAME = 0 <NEW_LINE> EXTERNAL_EH_FRAME = 1 | Enums that describe the source of function hints. | 6259906124f1403a9268642d |
class LineMustNotContainWord(LineRule): <NEW_LINE> <INDENT> name = "line-must-not-contain" <NEW_LINE> id = "R5" <NEW_LINE> options_spec = [ListOption('words', [], "Comma separated list of words that should not be found")] <NEW_LINE> violation_message = "Line contains {0}" <NEW_LINE> def validate(self, line, _commit): <NEW_LINE> <INDENT> strings = self.options['words'].value <NEW_LINE> violations = [] <NEW_LINE> for string in strings: <NEW_LINE> <INDENT> regex = re.compile(rf"\b{string.lower()}\b", re.IGNORECASE | re.UNICODE) <NEW_LINE> match = regex.search(line.lower()) <NEW_LINE> if match: <NEW_LINE> <INDENT> violations.append(RuleViolation(self.id, self.violation_message.format(string), line)) <NEW_LINE> <DEDENT> <DEDENT> return violations if violations else None | Violation if a line contains one of a list of words (NOTE: using a word in the list inside another word is not
a violation, e.g: WIPING is not a violation if 'WIP' is a word that is not allowed.) | 6259906191af0d3eaad3b4e6 |
@dataclass <NEW_LINE> class CommandTweak(TweakBase): <NEW_LINE> <INDENT> apply_command: str = '' <NEW_LINE> detach_command: str = '' <NEW_LINE> icon: str = '' <NEW_LINE> def _apply(self, command): <NEW_LINE> <INDENT> Logger.info(f'CmdTweak: calling {command}') <NEW_LINE> ret = os.system(command) <NEW_LINE> Logger.info(f'CmdTweak: System returned {ret}') <NEW_LINE> return ret <NEW_LINE> <DEDENT> def apply(self): <NEW_LINE> <INDENT> ret = self._apply(self.apply_command) <NEW_LINE> self.notify_apply(not ret) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def detach(self): <NEW_LINE> <INDENT> ret = self._apply(self.detach_command) <NEW_LINE> self.notify_detach(not ret) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return self.apply() <NEW_LINE> <DEDENT> @property <NEW_LINE> def valid(self) -> bool: <NEW_LINE> <INDENT> return super().valid and self.apply_command | Used for tweaks requiring passing a command into the command line.
Json can be extended as follows.
```
{
"apply_command": "@echo applying",
"detach_command": "@echo disabling"
}
```
Attributes:
`apply_command` - The command that is passed into the cmd when
when the `apply` method is called.
`detach_command` - Similar to `apply_command` except it does not
have to be specified if the tweak is one-off.
`icon` - The icon from `segmdl2.ttf` that will be used for button
if available. | 625990613617ad0b5ee0780d |
class DescribleL4RulesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Business = None <NEW_LINE> self.Id = None <NEW_LINE> self.RuleIdList = None <NEW_LINE> self.Limit = None <NEW_LINE> self.Offset = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Business = params.get("Business") <NEW_LINE> self.Id = params.get("Id") <NEW_LINE> self.RuleIdList = params.get("RuleIdList") <NEW_LINE> self.Limit = params.get("Limit") <NEW_LINE> self.Offset = params.get("Offset") | DescribleL4Rules request structure.
| 625990614a966d76dd5f05b2 |
class BrandingIO(BaseModel): <NEW_LINE> <INDENT> logo: Optional[str] <NEW_LINE> font: Optional[FontIO] | Represent an instance of a corporate branding. | 625990614f88993c371f107e |
class Pbs(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def submitPbs(code2run,pbsfolder,pbsfilename,queue): <NEW_LINE> <INDENT> pbsfilepath = "{0}/{1}.pbs".format(pbsfolder,pbsfilename) <NEW_LINE> errorpath = "{0}/{1}.err".format(pbsfolder,pbsfilename) <NEW_LINE> outpath = "{0}/{1}.out".format(pbsfolder,pbsfilename) <NEW_LINE> file = open(pbsfilepath,"w") <NEW_LINE> file.write("#!/bin/sh\n") <NEW_LINE> file.write("#PBS -l nodes=1:ppn=2\n") <NEW_LINE> file.write("#PBS -l walltime=16:00:00\n") <NEW_LINE> file.write("#PBS -q {0}\n".format(queue)) <NEW_LINE> file.write("#PBS -r n\n") <NEW_LINE> file.write("#PBS -V\n") <NEW_LINE> file.write("#PBS -o {0}\n".format(outpath)) <NEW_LINE> file.write("#PBS -e {0}\n".format(errorpath)) <NEW_LINE> file.write("cd $PBS_O_WORKDIR\n") <NEW_LINE> file.write(code2run+"\n") <NEW_LINE> file.close() <NEW_LINE> code = "qsub {0}".format(pbsfilepath) <NEW_LINE> os.system(code) | methods related to pbs
| 62599061009cb60464d02bf6 |
class MainView(generic.TemplateView): <NEW_LINE> <INDENT> template_name = 'green/main.html' | Loads the main page. | 62599061d486a94d0ba2d687 |
class TestBgpLocalAsn(BaseActionTestCase): <NEW_LINE> <INDENT> action_cls = bgp_local_asn <NEW_LINE> def test_action(self): <NEW_LINE> <INDENT> action = self.get_action_instance() <NEW_LINE> mock_callback = MockCallback() <NEW_LINE> kwargs = { 'username': '', 'rbridge_id': '224', 'get': False, 'ip': '', 'local_as': '44322', 'vrf': 'test', 'password': '', 'port': '22', 'test': True, 'callback': mock_callback.callback } <NEW_LINE> action.run(**kwargs) <NEW_LINE> expected_xml = ( '<config><rbridge-id xmlns="urn:brocade.com:mgmt:brocade-rbridge">' '<rbridge-id>224</rbridge-id><router><bgp xmlns="urn:brocade.com:m' 'gmt:brocade-bgp"><vrf-name>test</vrf-name><router-bgp-cmds-holder' '><router-bgp-attributes><local-as>44322</local-as></router-bgp-at' 'tributes></router-bgp-cmds-holder></bgp></router></rbridge-id></c' 'onfig>' ) <NEW_LINE> self.assertTrue(expected_xml, mock_callback.returned_data) | Test holder class
| 62599061a79ad1619776b61c |
class NewStockReport(object): <NEW_LINE> <INDENT> def __init__(self, form, timestamp, tag, transactions): <NEW_LINE> <INDENT> self._form = form <NEW_LINE> self.form_id = form._id <NEW_LINE> self.timestamp = timestamp <NEW_LINE> self.tag = tag <NEW_LINE> self.transactions = transactions <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_xml(cls, form, config, elem): <NEW_LINE> <INDENT> tag = elem.tag <NEW_LINE> tag = tag[tag.find('}')+1:] <NEW_LINE> timestamp = force_to_datetime(elem.attrib.get('date') or form.received_on).replace(tzinfo=None) <NEW_LINE> products = elem.findall('./{%s}entry' % stockconst.COMMTRACK_REPORT_XMLNS) <NEW_LINE> transactions = [t for prod_entry in products for t in StockTransaction.from_xml(config, timestamp, tag, elem, prod_entry)] <NEW_LINE> return cls(form, timestamp, tag, transactions) <NEW_LINE> <DEDENT> @transaction.commit_on_success <NEW_LINE> def create_models(self, domain=None): <NEW_LINE> <INDENT> if self.tag not in stockconst.VALID_REPORT_TYPES: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> report = DbStockReport.objects.create( form_id=self.form_id, date=self.timestamp, type=self.tag, domain=self._form.domain, ) <NEW_LINE> for txn in self.transactions: <NEW_LINE> <INDENT> db_txn = DbStockTransaction( report=report, case_id=txn.case_id, section_id=txn.section_id, product_id=txn.product_id, ) <NEW_LINE> if domain: <NEW_LINE> <INDENT> db_txn.domain = domain <NEW_LINE> <DEDENT> db_txn.type = txn.action <NEW_LINE> db_txn.subtype = txn.subaction <NEW_LINE> if self.tag == stockconst.REPORT_TYPE_BALANCE: <NEW_LINE> <INDENT> db_txn.stock_on_hand = txn.quantity <NEW_LINE> db_txn.quantity = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert self.tag == stockconst.REPORT_TYPE_TRANSFER <NEW_LINE> previous_transaction = db_txn.get_previous_transaction() <NEW_LINE> db_txn.quantity = txn.relative_quantity <NEW_LINE> db_txn.stock_on_hand = (previous_transaction.stock_on_hand if previous_transaction else 0) + db_txn.quantity <NEW_LINE> <DEDENT> db_txn.save() | Intermediate class for dealing with stock XML | 62599061379a373c97d9a6e3 |
class VotesRoot(BoxLayout): <NEW_LINE> <INDENT> votes_container = ObjectProperty(None) <NEW_LINE> votes = {} <NEW_LINE> def add_vote_widget(self, name): <NEW_LINE> <INDENT> vote_widget = Factory.VoteWidget() <NEW_LINE> vote_widget.name = name <NEW_LINE> self.votes_container.add_widget(vote_widget) <NEW_LINE> self.votes[name] = self.votes_container.children[0] <NEW_LINE> <DEDENT> @inlineCallbacks <NEW_LINE> def on_session(self, session): <NEW_LINE> <INDENT> self.session = session <NEW_LINE> votes_results = yield self.session.call(u'io.crossbar.demo.vote.get') <NEW_LINE> for vote in votes_results: <NEW_LINE> <INDENT> self.votes[vote[u'subject']].amount = vote[u'votes'] <NEW_LINE> <DEDENT> <DEDENT> def send_vote(self, name): <NEW_LINE> <INDENT> if self.session: <NEW_LINE> <INDENT> self.session.call(u'io.crossbar.demo.vote.vote', name) <NEW_LINE> <DEDENT> <DEDENT> def send_reset(self): <NEW_LINE> <INDENT> if self.session: <NEW_LINE> <INDENT> self.session.call(u'io.crossbar.demo.vote.reset') <NEW_LINE> <DEDENT> <DEDENT> def on_vote_message(self, vote_result): <NEW_LINE> <INDENT> self.votes[vote_result[u'subject']].amount = vote_result[u'votes'] <NEW_LINE> <DEDENT> def on_reset_message(self): <NEW_LINE> <INDENT> for vote_widget in self.votes_container.children: <NEW_LINE> <INDENT> vote_widget.amount = 0 | The Root widget, defined in conjunction with the rule in votes.kv. | 62599061627d3e7fe0e0854a |
class LastFmAuthBlueprint(auth.oauth.OAuthBlueprint): <NEW_LINE> <INDENT> def generate_oauth_finished(self): <NEW_LINE> <INDENT> def oauth_finished(): <NEW_LINE> <INDENT> if 'token' not in flask.request.args: <NEW_LINE> <INDENT> return flask.redirect(self.oauth_refused_url) <NEW_LINE> <DEDENT> token = flask.request.args['token'] <NEW_LINE> http_resp = self.api.get( '%s&token=%s' % (self.api.access_token_url, token)) <NEW_LINE> resp = type('obj', (object,), {'content' : json.loads(http_resp.content)}) <NEW_LINE> auth.signals.oauth_completed.send(self, response = resp, access_token = resp.content['session']['key']) <NEW_LINE> token_key = flask.session.pop(u"original_token", None) <NEW_LINE> if token_key: <NEW_LINE> <INDENT> del resp.content['session']['key'] <NEW_LINE> resp.content.update({u'oauth_token': token_key}) <NEW_LINE> return flask.redirect( oauthlib.common.add_params_to_uri( flask.url_for('oauth_provider.authorize'), resp.content.items()) + "&done") <NEW_LINE> <DEDENT> return flask.redirect(flask.url_for(self.oauth_completed_view)) <NEW_LINE> <DEDENT> return oauth_finished | Provides a custom oauth_finished function for Last.fm. | 6259906199cbb53fe68325a1 |
class Kocka: <NEW_LINE> <INDENT> def __init__(self, pocet_stien = 6): <NEW_LINE> <INDENT> self.__pocet_stien = pocet_stien <NEW_LINE> <DEDENT> def vrat_pocet_stien(self): <NEW_LINE> <INDENT> return self.__pocet_stien <NEW_LINE> <DEDENT> def hod(self): <NEW_LINE> <INDENT> import random as _random <NEW_LINE> return _random.randint(1, self.__pocet_stien) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str("Kocka s {0} stenami".format(self.__pocet_stien)) | Trieda reprezentuje hraciu kocku. | 625990617d43ff2487427f6f |
class RoDict(Mapping): <NEW_LINE> <INDENT> def __init__(self, data: Dict[Text, Any], forgive_type=False): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> self._forgive_type = forgive_type <NEW_LINE> <DEDENT> def __getitem__(self, key: Text) -> Any: <NEW_LINE> <INDENT> return make_ro(self._data[key], self._forgive_type) <NEW_LINE> <DEDENT> def __len__(self) -> int: <NEW_LINE> <INDENT> return len(self._data) <NEW_LINE> <DEDENT> def __iter__(self) -> Iterator[Any]: <NEW_LINE> <INDENT> return iter(self._data) | Wrapper around a dict to make it read-only. | 625990618e7ae83300eea74d |
class Node4C(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> def __init__( self): <NEW_LINE> <INDENT> self.__node_next = None <NEW_LINE> self.__is_on = False <NEW_LINE> self.__is_running = False <NEW_LINE> return <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def configure( self, p_Ts: pandora.Box): <NEW_LINE> <INDENT> if self.__node_next: <NEW_LINE> <INDENT> self.__node_next.configure( p_Ts) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def execute( self): <NEW_LINE> <INDENT> if self.__node_next: <NEW_LINE> <INDENT> self.__node_next.execute() <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def is_on( self): <NEW_LINE> <INDENT> return self.__is_on <NEW_LINE> <DEDENT> def is_ready( self): <NEW_LINE> <INDENT> return self.__is_on and not self.__is_running <NEW_LINE> <DEDENT> def is_running( self): <NEW_LINE> <INDENT> return self.__is_running <NEW_LINE> <DEDENT> def node_last( self): <NEW_LINE> <INDENT> node = self <NEW_LINE> while node: <NEW_LINE> <INDENT> if not node.node_next(): <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> node = node.node_next() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def node_next( self, node=None): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return self.__node_next <NEW_LINE> <DEDENT> self.__node_next = node <NEW_LINE> return self <NEW_LINE> <DEDENT> def to_off( self): <NEW_LINE> <INDENT> self.__is_on = False <NEW_LINE> if self.__node_next: <NEW_LINE> <INDENT> self.__node_next.to_off() <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def to_on( self): <NEW_LINE> <INDENT> self.__is_on = True <NEW_LINE> if self.__node_next: <NEW_LINE> <INDENT> self.__node_next.to_on() <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def to_ready( self): <NEW_LINE> <INDENT> self.__is_running = False <NEW_LINE> if self.__node_next: <NEW_LINE> <INDENT> self.__node_next.to_ready() <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def to_running( self): <NEW_LINE> <INDENT> if self.is_on(): <NEW_LINE> <INDENT> self.__is_running = True <NEW_LINE> <DEDENT> if self.__node_next: <NEW_LINE> <INDENT> self.__node_next.to_running() <NEW_LINE> <DEDENT> return | Node for controller.
A controller consists of nodes.
.. note::
Es ist die Frage, ob ein _Node einen Eingang und einen Ausgang braucht,
denn das kann mit den Variablen erledigt werden, von denen gelesen und
auf die geschrieben wird und die ja dem Ctor übergeben werden.
Schließlich sind alle Subclasses von _Node appspez. und damit weiß die
App, wie die Nodes über welche Variablen zusammenhängen müssen. | 62599061462c4b4f79dbd0c5 |
class Catch(object): <NEW_LINE> <INDENT> def __call__(self, func, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __dict__ = None <NEW_LINE> __weakref__ = None <NEW_LINE> result = None <NEW_LINE> success = None | Reproduces the behavior of the mel command of the same name. if writing pymel scripts from scratch, you should
use the try/except structure. This command is provided for python scripts generated by py2mel. stores the
result of the function in catch.result.
>>> if not catch( lambda: myFunc( "somearg" ) ):
... result = catch.result
... print "succeeded:", result | 62599061097d151d1a2c272f |
class ImagesReader(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def open_file(file_name, gray=False): <NEW_LINE> <INDENT> img = cv.imread(file_name) <NEW_LINE> if gray: <NEW_LINE> <INDENT> return cv.cvtColor(img, cv.COLOR_BGR2GRAY) <NEW_LINE> <DEDENT> return img <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read_images_dictionary(file_path, extension, gray=False): <NEW_LINE> <INDENT> imgs_dic = [] <NEW_LINE> for file in sorted(glob.glob(os.path.join(file_path, "*."+extension))): <NEW_LINE> <INDENT> imgs_dic.append(ImagesReader.open_file(file, gray)) <NEW_LINE> <DEDENT> return imgs_dic <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def merge_image_list(images, others): <NEW_LINE> <INDENT> for image in others: <NEW_LINE> <INDENT> images.append(image) <NEW_LINE> <DEDENT> return images | A class to read image | 62599061adb09d7d5dc0bc2a |
@Message.register(Byte(SSH_MSG_USERAUTH_FAILURE)) <NEW_LINE> class AuthFailure(Message): <NEW_LINE> <INDENT> SPEC = [('auth_continue', NameList), ('partial', Boolean)] <NEW_LINE> def __init__(self, auth_continue, partial): <NEW_LINE> <INDENT> super(AuthFailure, self).__init__(self.HEADER) <NEW_LINE> self.auth_continue = auth_continue <NEW_LINE> self.partial = partial | AuthFailure: Section 5.1 | 625990614428ac0f6e659bf2 |
class RegularMultiTriangleTiling( MultiTriangleTiling ): <NEW_LINE> <INDENT> def __init__( self, A, m ): <NEW_LINE> <INDENT> self.n = 1 <NEW_LINE> self.m = int( m ) <NEW_LINE> self.A = np.deg2rad( A ) <NEW_LINE> self.C = np.pi - 2 * np.pi / self.m <NEW_LINE> self.B = np.pi - ( self.A + self.C ) <NEW_LINE> self.a = np.sin( self.A ) / np.sin( self.C ) <NEW_LINE> self.b = np.sin( self.B ) / np.sin( self.C ) <NEW_LINE> self.c = 1 <NEW_LINE> self.get_s( ) | Class to generate a triangle tiling with the specified parameters, for the
special case of ``n`` equal to 1
Parameters
----------
A : float
Angle of lower-right corner of triangle (in degrees)
m : int
Number of arms in the tiling | 62599061e64d504609df9f2e |
class SolutionTagResource(CommonResource): <NEW_LINE> <INDENT> class Meta(CommonMeta): <NEW_LINE> <INDENT> queryset = models.SolutionTag.objects.all() <NEW_LINE> filtering = {'name': ALL, 'colour': ('exact'), 'show': ('exact'), } <NEW_LINE> detail_uri_name = 'name' | API Resource for 'SolutionTag' model. | 625990614e4d562566373ac7 |
class QuotaTcp(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.b_key = "quota-tcp" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.tcp_quota = "" <NEW_LINE> self.tcp_reserve = "" <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value) | This class does not support CRUD Operations please use parent.
:param tcp_quota: {"description": "NAT port quota per user (default: not configured)", "minimum": 1, "type": "number", "maximum": 64000, "format": "number"}
:param tcp_reserve: {"description": "Number of ports to reserve per user (default: same as user-quota value) (Reserved quota per user (default: same as user-quota value))", "minimum": 0, "type": "number", "maximum": 64000, "format": "number"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` | 6259906199cbb53fe68325a2 |
class Singleton(type): <NEW_LINE> <INDENT> instance = {} <NEW_LINE> def __call__(cls, *args, **kw): <NEW_LINE> <INDENT> if cls not in cls.instance: <NEW_LINE> <INDENT> cls.instance[cls] = super(Singleton, cls).__call__(*args, **kw) <NEW_LINE> <DEDENT> return cls.instance[cls] | The **singleton pattern** is a design pattern that restricts the
instantiation of a class to one object. This is useful when exactly one
object is needed to coordinate actions across the system.
As a metaclass, the pattern is applied to derived classes such as
::
from pynion import Singleton
class Foo(object):
__metaclass__ = Singleton
def __init__(self, bar):
self.bar = bar
Derived classes can become parents of other classes. Classes inherited from
a ``__metaclass__ = Singleton`` are also Singleton. | 6259906191f36d47f22319ef |
class Message(object): <NEW_LINE> <INDENT> def __init__(self, vars): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__sender = vars["from"] <NEW_LINE> self.__to = vars["to"] <NEW_LINE> self.__body = vars["body"] <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> raise InvalidMessageError(e[0]) <NEW_LINE> <DEDENT> self.__command = None <NEW_LINE> self.__arg = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def sender(self): <NEW_LINE> <INDENT> return self.__sender <NEW_LINE> <DEDENT> @property <NEW_LINE> def to(self): <NEW_LINE> <INDENT> return self.__to <NEW_LINE> <DEDENT> @property <NEW_LINE> def body(self): <NEW_LINE> <INDENT> return self.__body <NEW_LINE> <DEDENT> def __parse_command(self): <NEW_LINE> <INDENT> if self.__arg != None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> body = self.__body <NEW_LINE> if body.startswith('\\'): <NEW_LINE> <INDENT> body = '/' + body[1:] <NEW_LINE> <DEDENT> self.__arg = '' <NEW_LINE> if body.startswith('/'): <NEW_LINE> <INDENT> parts = body.split(' ', 1) <NEW_LINE> self.__command = parts[0][1:] <NEW_LINE> if len(parts) > 1: <NEW_LINE> <INDENT> self.__arg = parts[1].strip() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.__arg = self.__body.strip() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def command(self): <NEW_LINE> <INDENT> self.__parse_command() <NEW_LINE> return self.__command <NEW_LINE> <DEDENT> @property <NEW_LINE> def arg(self): <NEW_LINE> <INDENT> self.__parse_command() <NEW_LINE> return self.__arg <NEW_LINE> <DEDENT> def reply(self, body, message_type=MESSAGE_TYPE_CHAT, raw_xml=False, send_message=send_message): <NEW_LINE> <INDENT> return send_message([self.sender], body, from_jid=self.to, message_type=message_type, raw_xml=raw_xml) | Encapsulates an XMPP message received by the application. | 6259906166673b3332c31abd |
class MediaDir: <NEW_LINE> <INDENT> NULL = 0 <NEW_LINE> ENCODING = 1 <NEW_LINE> DECODING = 2 <NEW_LINE> ENCODING_DECODING = 3 | Media direction constants.
Member documentation:
NULL -- media is not active
ENCODING -- media is active in transmit/encoding direction only.
DECODING -- media is active in receive/decoding direction only
ENCODING_DECODING -- media is active in both directions. | 6259906145492302aabfdb9b |
class CLBOrNodeDeleted(Exception): <NEW_LINE> <INDENT> def __init__(self, error, clb_id, node_id=None): <NEW_LINE> <INDENT> super(CLBOrNodeDeleted, self).__init__( 'CLB {} or node {} deleted due to {}'.format(clb_id, node_id, error)) <NEW_LINE> self.error = error <NEW_LINE> self.clb_id = clb_id <NEW_LINE> self.node_id = node_id | CLB or Node is deleted or in process of getting deleted
:param :class:`RequestError` error: Error that caused this exception
:param str clb_id: ID of deleted load balancer
:param str node_id: ID of deleted node in above load balancer | 62599061009cb60464d02bf8 |
class View(ViewDecorator, ResponseSetter): <NEW_LINE> <INDENT> same_exception_content = True <NEW_LINE> urls = {} <NEW_LINE> @classmethod <NEW_LINE> def get_urls(cls): <NEW_LINE> <INDENT> return cls.urls.get(cls, []) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def add_url(cls, url, name): <NEW_LINE> <INDENT> cls.urls.setdefault(cls, []).append((url, name)) <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(View, self).__init__(*args, **kwargs) <NEW_LINE> for http_method in HTTP_METHODS: <NEW_LINE> <INDENT> method_name = http_method.lower() <NEW_LINE> try: <NEW_LINE> <INDENT> setattr( self, 'on_%s' % method_name, self._wrap_response( getattr(self, method_name) ) ) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _wrap_response(self, method): <NEW_LINE> <INDENT> @wraps(method) <NEW_LINE> def wrapper(request, response, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.content = method(request, *args, **kwargs) <NEW_LINE> <DEDENT> except HttpException as e: <NEW_LINE> <INDENT> if self.same_exception_content: <NEW_LINE> <INDENT> e.content_type = self.content_type <NEW_LINE> e.content_wrapper = self.content_wrapper <NEW_LINE> <DEDENT> e.set_response(response) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.set_response(response) <NEW_LINE> <DEDENT> <DEDENT> return wrapper | Wrapper around falcon view api | 62599061435de62698e9d4c8 |
class UserViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> authentication_classes = (authentication.SessionAuthentication,) <NEW_LINE> permission_classes = (ApiKeyHeaderPermission,) <NEW_LINE> queryset = User.objects.all().prefetch_related("preferences").select_related("profile") <NEW_LINE> serializer_class = UserSerializer <NEW_LINE> paginate_by = 10 <NEW_LINE> paginate_by_param = "page_size" | DRF class for interacting with the User ORM object | 625990615166f23b2e244a93 |
class DataReader: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.cur_path = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> self.file_path = os.path.join(self.cur_path, r"../TestData/TestData.xlsx") <NEW_LINE> <DEDENT> def load_excel_data(self): <NEW_LINE> <INDENT> records = None <NEW_LINE> try: <NEW_LINE> <INDENT> if self.file_path is not None: <NEW_LINE> <INDENT> records = exc.iget_records(file_name=self.file_path) <NEW_LINE> <DEDENT> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> traceback.print_exc(ex) <NEW_LINE> <DEDENT> return records <NEW_LINE> <DEDENT> def get_data(self, tc_name, column_name): <NEW_LINE> <INDENT> value = None <NEW_LINE> excel_records = self.load_excel_data() <NEW_LINE> try: <NEW_LINE> <INDENT> if excel_records is not None: <NEW_LINE> <INDENT> for record in excel_records: <NEW_LINE> <INDENT> if record['TC_Name'] == tc_name: <NEW_LINE> <INDENT> value = record[column_name] <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> traceback.print_exc(ex) <NEW_LINE> <DEDENT> return value | This class includes basic reusable data helpers. | 625990617047854f46340a7f |
class TOS(commands.Cog): <NEW_LINE> <INDENT> def __init__(self, bot: Bot): <NEW_LINE> <INDENT> self.bot = bot <NEW_LINE> toscfg = ConfigUtil("./static/tos.json") <NEW_LINE> tos = toscfg.read()['tos'] <NEW_LINE> dgl = toscfg.read()['dgl'] <NEW_LINE> print(tos, dgl) <NEW_LINE> tmp = [] <NEW_LINE> for item in tos: <NEW_LINE> <INDENT> for name in item['names']: <NEW_LINE> <INDENT> tmp.append((name, f"You may not use Discord to {item['content']}")) <NEW_LINE> <DEDENT> <DEDENT> for item in dgl: <NEW_LINE> <INDENT> for name in item['names']: <NEW_LINE> <INDENT> tmp.append((name, item['content'])) <NEW_LINE> <DEDENT> <DEDENT> self.entries = dict(tmp) <NEW_LINE> <DEDENT> @commands.command(name="tos", aliases=["dgl", "terms", "guidelines"]) <NEW_LINE> @commands.cooldown(1, 10, BucketType.channel) <NEW_LINE> async def tos(self, ctx, entry): <NEW_LINE> <INDENT> if not entry in self.entries: <NEW_LINE> <INDENT> await ctx.send("That item wasn't a valid entry.", delete_after=10) <NEW_LINE> return <NEW_LINE> <DEDENT> content = self.entries[entry] <NEW_LINE> await ctx.send(f"> {content}") | A cog for showing the terms and guidelines | 62599061e5267d203ee6cf20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.