code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class LineEditCount(QObject): <NEW_LINE> <INDENT> def __init__(self, lineEdit): <NEW_LINE> <INDENT> QObject.__init__(self) <NEW_LINE> hbox = QHBoxLayout(lineEdit) <NEW_LINE> hbox.setContentsMargins(0, 0, 0, 0) <NEW_LINE> lineEdit.setLayout(hbox) <NEW_LINE> hbox.addStretch() <NEW_LINE> self.counter = QLabel(lineEdit) <NEW_LINE> hbox.addWidget(self.counter) <NEW_LINE> lineEdit.setStyleSheet("padding-right: 2px; padding-left: 2px;") <NEW_LINE> <DEDENT> def update_count(self, index, total, hasSearch=False): <NEW_LINE> <INDENT> message = "%s / %s" % (index, total) <NEW_LINE> self.counter.setText(message) <NEW_LINE> if total > 0: <NEW_LINE> <INDENT> self.counter.setStyleSheet("background: #73c990;") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.counter.setStyleSheet("background: #6a6ea9;") <NEW_LINE> <DEDENT> if index == 0 and total == 0 and hasSearch: <NEW_LINE> <INDENT> self.counter.setStyleSheet("background: #e73e3e;color: white;")
Show summary results inside the line edit, for counting some property.
62598fa0a8370b77170f0225
class DependencyNotFoundError(SetupError): <NEW_LINE> <INDENT> pass
Raised when a dependency cannot be found
62598fa04e4d562566372265
class BadTileID(Exception): <NEW_LINE> <INDENT> def __init__(self, bad_tile_id): <NEW_LINE> <INDENT> message = ('no tile by id #%d' % bad_tile_id) <NEW_LINE> super(BadTileID, self).__init__(message) <NEW_LINE> self.bad_tile_id = bad_tile_id
Tilesheet: tile was referenced by an ID which does not exist. Args: bad_tile_id (int): the tile id referenced which does not actually exist in a Tilesheet. Attributes: bad_tile_id (int): the tile ID referenced which does not exist.
62598fa085dfad0860cbf995
class VisualVertexBuilder(AttributeCollectorBase): <NEW_LINE> <INDENT> _kwds_prefix = "vertex_" <NEW_LINE> color = (str(self.vertex_defaults["color"]), color_conv) <NEW_LINE> label = None <NEW_LINE> shape = str(self.vertex_defaults["shape"]) <NEW_LINE> size = float(self.vertex_defaults["size"])
Collects some visual properties of a vertex for drawing
62598fa0e1aae11d1e7ce744
class Registered(Message): <NEW_LINE> <INDENT> MESSAGE_TYPE = 65 <NEW_LINE> def __init__(self, request, registration): <NEW_LINE> <INDENT> assert (type(request) is int) <NEW_LINE> assert (type(registration) is int) <NEW_LINE> Message.__init__(self) <NEW_LINE> self.request = request <NEW_LINE> self.registration = registration <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse(wmsg): <NEW_LINE> <INDENT> assert(len(wmsg) > 0 and wmsg[0] == Registered.MESSAGE_TYPE) <NEW_LINE> if len(wmsg) != 3: <NEW_LINE> <INDENT> raise ProtocolError("invalid message length {0} for REGISTERED".format(len(wmsg))) <NEW_LINE> <DEDENT> request = check_or_raise_id(wmsg[1], "'request' in REGISTERED") <NEW_LINE> registration = check_or_raise_id(wmsg[2], "'registration' in REGISTERED") <NEW_LINE> obj = Registered(request, registration) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def marshal(self): <NEW_LINE> <INDENT> return [Registered.MESSAGE_TYPE, self.request, self.registration] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Registered(request={0}, registration={1})".format(self.request, self.registration)
A WAMP ``REGISTERED`` message. Format: ``[REGISTERED, REGISTER.Request|id, Registration|id]``
62598fa007f4c71912baf285
class CPUMeasurer(object): <NEW_LINE> <INDENT> def __init__(self, pid=None): <NEW_LINE> <INDENT> self._ps = ProcStat(pid) <NEW_LINE> <DEDENT> def start(self, timestamp, statstring=None): <NEW_LINE> <INDENT> ps = self._ps <NEW_LINE> self._starttime = timestamp <NEW_LINE> if statstring: <NEW_LINE> <INDENT> ps.load(statstring) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ps.reread() <NEW_LINE> <DEDENT> self._start_tics = ps.tms_stime + ps.tms_utime <NEW_LINE> <DEDENT> def end(self, timestamp, statstring=None): <NEW_LINE> <INDENT> ps = self._ps <NEW_LINE> if statstring: <NEW_LINE> <INDENT> ps.load(statstring) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ps.reread() <NEW_LINE> <DEDENT> end_tics = ps.tms_stime + ps.tms_utime <NEW_LINE> return float(end_tics - self._start_tics) / (timestamp - self._starttime)
Helper to measure CPU utilization of a process.
62598fa099fddb7c1ca62d08
class Customer(object): <NEW_LINE> <INDENT> def __init__(self, name, email): <NEW_LINE> <INDENT> email_check = str(email).lower() <NEW_LINE> if '@' not in email_check: <NEW_LINE> <INDENT> print("This is not a valid email. Try again.") <NEW_LINE> <DEDENT> for cust_id in customers: <NEW_LINE> <INDENT> if customers[cust_id][1] == email_check: <NEW_LINE> <INDENT> print("That email is already in use.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.email = email <NEW_LINE> self.name = str(name) <NEW_LINE> new_id = random.randint(1,10000) <NEW_LINE> while new_id in customers: <NEW_LINE> <INDENT> new_id = random.randint(1,10000) <NEW_LINE> <DEDENT> self.cust_id = new_id <NEW_LINE> customers[self.cust_id] = [self.name, self.email] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_email(self): <NEW_LINE> <INDENT> return self.email <NEW_LINE> <DEDENT> def cust_id(self): <NEW_LINE> <INDENT> return self.cust_id <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Customer ' + str(self.cust_id) + ' is called ' + self.name + ' and has email ' + self.email
Customer class, gives a random unused ID
62598fa0462c4b4f79dbb84d
class vn41_t15(rose.upgrade.MacroUpgrade): <NEW_LINE> <INDENT> BEFORE_TAG = "vn4.1_t33" <NEW_LINE> AFTER_TAG = "vn4.1_t15" <NEW_LINE> def upgrade(self, config, meta_config=None): <NEW_LINE> <INDENT> self.add_setting(config, ["namelist:jules_rivers"]) <NEW_LINE> self.add_setting(config, ["file:jules_rivers.nml", "source"], "namelist:jules_rivers") <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "l_rivers"], ".false.") <NEW_LINE> ignored = ConfigNode.STATE_USER_IGNORED <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "rivers_type"], "'rfm'", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "rivers_timestep"], "-32768", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "cland"], "0.2", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "criver"], "0.62", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "cbland"], "0.1", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "cbriver"], "0.15", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "retl"], "0.0", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "retr"], "0.005", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "a_thresh"], "1", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "runoff_factor"], "1.0", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "rivers_speed"], "0.4", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers", "rivers_meander"], "1.4", state = ignored) <NEW_LINE> self.add_setting(config, ["namelist:jules_rivers_props"], state = ignored) <NEW_LINE> source = self.get_setting_value(config, ["file:ancillaries.nml","source"]) <NEW_LINE> if source: <NEW_LINE> <INDENT> self.change_setting_value(config, ["file:ancillaries.nml","source"], source.replace("namelist:jules_co2", "(namelist:jules_rivers_props) namelist:jules_co2")) <NEW_LINE> <DEDENT> return config, self.reports
Upgrade macro for JULES ticket #15 by Huw Lewis
62598fa01f037a2d8b9e3f29
class JDSeleniumMiddleware(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.driver = webdriver.Chrome() <NEW_LINE> self.driver.set_window_size(1232, 8392) <NEW_LINE> <DEDENT> @retry(stop_max_attempt_number=30, wait_fixed=200) <NEW_LINE> def retry_load_page(self, request, num, spider): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> xpath_pattern = "//div[@id='J_goodsList']/ul/li[%d]" % ((num - 1) * 4 + 1) <NEW_LINE> self.driver.find_element_by_xpath(xpath_pattern) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> spider.logger.debug('Retry<{}>(<{}>)'.format(request.url, self.cnt)) <NEW_LINE> self.cnt += 1 <NEW_LINE> raise Exception("<{}> page loading failed.".format(request.url)) <NEW_LINE> <DEDENT> <DEDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> if not request.url.startswith('https://www.jd.com'): <NEW_LINE> <INDENT> self.cnt = 1 <NEW_LINE> self.is_slide = False <NEW_LINE> self.driver.get(request.url) <NEW_LINE> num = 1 <NEW_LINE> while num < 16: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print('****' * 30) <NEW_LINE> self.retry_load_page(request, num, spider) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> spider.logger.error(e) <NEW_LINE> return request <NEW_LINE> <DEDENT> js = "window.scrollBy(0, %d);" % random.randint(450, 470) <NEW_LINE> time.sleep(0.5) <NEW_LINE> self.driver.execute_script(js) <NEW_LINE> num += 1 <NEW_LINE> <DEDENT> html = self.driver.page_source <NEW_LINE> spider.logger.info("Retry <{}> Successful".format(request.url)) <NEW_LINE> return HtmlResponse(url=request.url, body=html.encode('utf-8'), encoding='utf-8', request=request) <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.driver.quit()
模拟浏览器下载中间件
62598fa0097d151d1a2c0e6b
class Breach(Testssl_base): <NEW_LINE> <INDENT> stix = Bundled(mitigation_object=load_mitigation("BREACH")) <NEW_LINE> def _set_arguments(self): <NEW_LINE> <INDENT> self._arguments = ["-B"] <NEW_LINE> <DEDENT> def _worker(self, results): <NEW_LINE> <INDENT> return self._obtain_results(results, ["BREACH"])
Analysis of the breach testssl results
62598fa0f548e778e596b3ef
class TestSaveState(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.dojo = Dojo() <NEW_LINE> <DEDENT> def test_empty_session_not_persisted(self): <NEW_LINE> <INDENT> self.dojo.save_state() <NEW_LINE> result = sys.stdout.getvalue().strip() <NEW_LINE> self.assertEqual( result, 'Session has no data to persist to the database.') <NEW_LINE> <DEDENT> def test_session_with_data_saved_successfully(self): <NEW_LINE> <INDENT> self.dojo.create_room('office', ['Valala']) <NEW_LINE> self.dojo.add_person('ladi', 'adeniran', 'fellow') <NEW_LINE> self.dojo.add_person('pet', 'sampras', 'staff') <NEW_LINE> self.dojo.save_state('test_dojo.db') <NEW_LINE> result = sys.stdout.getvalue().strip() <NEW_LINE> self.assertTrue(result) <NEW_LINE> self.assertEqual( result[237:280], 'Your session has been saved to the database') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> del self.dojo
The test suite for the functionalities, save state and load state in the Dojo class
62598fa0460517430c431f7c
class self_seg(null_seg): <NEW_LINE> <INDENT> def __str__(self): return '.' <NEW_LINE> def next_self(self): <NEW_LINE> <INDENT> self.next = self.next_null <NEW_LINE> return self.cntx <NEW_LINE> <DEDENT> def bind(self,cntx): <NEW_LINE> <INDENT> null_seg.bind(self,cntx) <NEW_LINE> self.next = self.next_self
summary: > This path segment returns the context node exactly once.
62598fa0bd1bec0571e14fe4
class Element(object): <NEW_LINE> <INDENT> _idx = itertools.count(0) <NEW_LINE> def __init__(self, name=None): <NEW_LINE> <INDENT> self._my_id = self._idx.next() <NEW_LINE> if name is None: <NEW_LINE> <INDENT> self.name = 'element%d' % self._my_id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> super(Element, self).__init__()
A generic device.
62598fa0be8e80087fbbeea1
class TeamByMatchTimeFinder(object): <NEW_LINE> <INDENT> def __init__(self, category: Category): <NEW_LINE> <INDENT> self._category = category <NEW_LINE> <DEDENT> def find_possible_teams(self, taken: datetime) -> Iterable[Iterable[TeamInfo]]: <NEW_LINE> <INDENT> if taken > datetime.now(): <NEW_LINE> <INDENT> logging.warning('Future taken date: {}.'.format(taken)) <NEW_LINE> <DEDENT> matches = self._category.match_category.filter( match_term__start__time__range=( (taken - MatchTerm.STANDARD_LENGTH).time(), taken.time() ), match_term__day__day=taken.date(), ) <NEW_LINE> return tuple((match.home_team_info, match.away_team_info) for match in matches)
Tries find possible teams in category playing in given time.
62598fa06aa9bd52df0d4d0d
class ColoredFormatter(logging.Formatter): <NEW_LINE> <INDENT> _LOG_COLORS = { 'WARNING': 'y', 'INFO': 'g', 'DEBUG': 'b', 'CRITICAL': 'y', 'ERROR': 'r' } <NEW_LINE> def format(self, record): <NEW_LINE> <INDENT> levelname = record.levelname <NEW_LINE> if levelname in self._LOG_COLORS: <NEW_LINE> <INDENT> record.levelname = colored( record.levelname[0], self._LOG_COLORS[record.levelname], style='b' ) <NEW_LINE> <DEDENT> return logging.Formatter.format(self, record)
Formatter for colored log.
62598fa0baa26c4b54d4f0f2
class MatdynBaseWorkChain(BaseRestartWorkChain): <NEW_LINE> <INDENT> _process_class = MatdynCalculation <NEW_LINE> @classmethod <NEW_LINE> def define(cls, spec): <NEW_LINE> <INDENT> super().define(spec) <NEW_LINE> spec.expose_inputs(MatdynCalculation, namespace='matdyn') <NEW_LINE> spec.expose_outputs(MatdynCalculation) <NEW_LINE> spec.outline( cls.setup, while_(cls.should_run_process)( cls.run_process, cls.inspect_process, ), cls.results, ) <NEW_LINE> spec.exit_code(300, 'ERROR_UNRECOVERABLE_FAILURE', message='The calculation failed with an unrecoverable error.') <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> super().setup() <NEW_LINE> self.ctx.restart_calc = None <NEW_LINE> self.ctx.inputs = AttributeDict(self.exposed_inputs(MatdynCalculation, 'matdyn')) <NEW_LINE> <DEDENT> def report_error_handled(self, calculation, action): <NEW_LINE> <INDENT> arguments = [calculation.process_label, calculation.pk, calculation.exit_status, calculation.exit_message] <NEW_LINE> self.report('{}<{}> failed with exit status {}: {}'.format(*arguments)) <NEW_LINE> self.report(f'Action taken: {action}') <NEW_LINE> <DEDENT> @process_handler(priority=600) <NEW_LINE> def handle_unrecoverable_failure(self, node): <NEW_LINE> <INDENT> if node.is_failed and node.exit_status < 400: <NEW_LINE> <INDENT> self.report_error_handled(node, 'unrecoverable error, aborting...') <NEW_LINE> return ProcessHandlerReport(True, self.exit_codes.ERROR_UNRECOVERABLE_FAILURE)
Workchain to run a Quantum ESPRESSO matdyn.x calculation with automated error handling and restarts.
62598fa092d797404e388a87
class SensorsView(generics.ListCreateAPIView): <NEW_LINE> <INDENT> queryset = Sensors.objects.all() <NEW_LINE> serializer_class = SensorsSerializer <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> <DEDENT> def list(request, *args, **kwargs): <NEW_LINE> <INDENT> sensors = [] <NEW_LINE> for sensor in Sensors.objects.all(): <NEW_LINE> <INDENT> if env("DEBUG") == True: <NEW_LINE> <INDENT> data = {"Temperature": "21", "Humidity": "56"} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = requests.get('http://' + sensor.ip + '/data').json() <NEW_LINE> <DEDENT> sensors.append({'id':sensor.id, 'name': sensor.name, 'temperature':data['Temperature'], 'humidity':data['Humidity']}) <NEW_LINE> <DEDENT> return Response(sensors)
API endpoint that allows groups to be viewed or edited.
62598fa0379a373c97d98e59
class CommentForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Comment <NEW_LINE> fields = [ "comment" ] <NEW_LINE> <DEDENT> def __init__(self, obj, instance=None, **kwargs): <NEW_LINE> <INDENT> self.obj = obj <NEW_LINE> if instance is not None: <NEW_LINE> <INDENT> assert obj == instance.content_object <NEW_LINE> <DEDENT> return super(CommentForm, self).__init__(instance=instance, **kwargs) <NEW_LINE> <DEDENT> def save(self, request): <NEW_LINE> <INDENT> comment = self.instance <NEW_LINE> if comment.pk is None: <NEW_LINE> <INDENT> comment.content_object = self.obj <NEW_LINE> comment.user = request.user <NEW_LINE> comment.site = Site.objects.get_current() <NEW_LINE> comment.valid_rating = 0 <NEW_LINE> comment.is_public = True <NEW_LINE> comment.is_removed = False <NEW_LINE> <DEDENT> return super(CommentForm, self).save(self)
Comment form.
62598fa07cff6e4e811b5867
class Member(Person): <NEW_LINE> <INDENT> def __init__(self, schema, current_id): <NEW_LINE> <INDENT> super().__init__(1, db_schema=schema) <NEW_LINE> self.schema = None <NEW_LINE> self.id = current_id <NEW_LINE> <DEDENT> def add_to_member_table(self, login_email, hashed_password, company, schema=None): <NEW_LINE> <INDENT> accept_date = datetime.date.today() <NEW_LINE> accept_date = str(accept_date.year) + "-" + str(accept_date.month) + "-" + str(accept_date.day) <NEW_LINE> join_date = datetime.date.today() <NEW_LINE> join_date = str(join_date.year) + "-" + str(join_date.month) + "-" + str(join_date.day) <NEW_LINE> password_set = int(time.time()) <NEW_LINE> data = (login_email, hashed_password, accept_date, join_date, password_set, company) <NEW_LINE> if schema is None: <NEW_LINE> <INDENT> schema = self.schema <NEW_LINE> <DEDENT> db = database.Database(schema) <NEW_LINE> try: <NEW_LINE> <INDENT> db.execute(insert_member, data) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> db.conn_close() <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def create_member(cls, user_name, user_email, password, new_company_id, schema): <NEW_LINE> <INDENT> def add_to_member_table(login_email, hashed_password, company_id): <NEW_LINE> <INDENT> accept_date = datetime.date.today() <NEW_LINE> accept_date = str(accept_date.year) + "-" + str(accept_date.month) + "-" + str(accept_date.day) <NEW_LINE> join_date = datetime.date.today() <NEW_LINE> join_date = str(join_date.year) + "-" + str(join_date.month) + "-" + str(join_date.day) <NEW_LINE> password_set = int(time.time()) <NEW_LINE> data = (login_email, hashed_password, accept_date, join_date, password_set, company_id) <NEW_LINE> db = database.Database('test_login_master_files') <NEW_LINE> try: <NEW_LINE> <INDENT> db.execute(insert_member, data) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> db.conn_close() <NEW_LINE> <DEDENT> <DEDENT> def add_to_person_table(username, email, current_schema, master_id=None): <NEW_LINE> <INDENT> if master_id is not None: <NEW_LINE> <INDENT> Person.add_person(username, current_schema, master_id) <NEW_LINE> user_id = Person.get_id_by_username(username, current_schema) <NEW_LINE> return user_id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> add_to_member_table(user_email, password, new_company_id) <NEW_LINE> current_user = add_to_person_table(user_name, user_email, schema) <NEW_LINE> return cls(current_user, schema)
This class is used to hold the higher functions of the lower classes.
62598fa0a79ad16197769ea7
class ibmTextToSpeech: <NEW_LINE> <INDENT> IBM_SPEECH_API_URL = 'https://stream.watsonplatform.net' + '/text-to-speech/api/v1/synthesize' <NEW_LINE> def get_api_url(self): <NEW_LINE> <INDENT> return self.IBM_SPEECH_API_URL <NEW_LINE> <DEDENT> def get_text_to_speech(self, text, lang): <NEW_LINE> <INDENT> wav_file = '.cache/ibmTransAudio.wav' <NEW_LINE> AudioEndPoint = 'https://api.yone3.net/get/audio' <NEW_LINE> langParam = '?voice=' <NEW_LINE> if lang == 'ja': <NEW_LINE> <INDENT> langParam += 'ja-JP_EmiVoice' <NEW_LINE> <DEDENT> elif lang == 'en': <NEW_LINE> <INDENT> num = random.randint(1, 100) <NEW_LINE> if num % 2 == 1: <NEW_LINE> <INDENT> langParam += 'en-US_MichaelVoice' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> langParam += 'en-US_LisaVoice' <NEW_LINE> <DEDENT> <DEDENT> api_url = self.get_api_url() + langParam <NEW_LINE> req_body = json.dumps({ 'text': text }) <NEW_LINE> headers = { 'Content-Type': 'application/json', 'Accept': 'audio/wav' } <NEW_LINE> res = requests.post( api_url, data=req_body, auth=( settings.IBM_TtoS_USERNAME, settings.IBM_TtoS_PASSWORD ), headers=headers ) <NEW_LINE> res_dict = {} <NEW_LINE> if not res: <NEW_LINE> <INDENT> res_dict['text'] = 'no reponse' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> wf = wave.open(wav_file, 'wb') <NEW_LINE> wf.setnchannels(1) <NEW_LINE> wf.setsampwidth(2) <NEW_LINE> wf.setframerate(22050) <NEW_LINE> wf.writeframesraw(res.content) <NEW_LINE> wf.close() <NEW_LINE> res_dict['text'] = AudioEndPoint <NEW_LINE> <DEDENT> return res_dict
IBM Watsonのテキスト to 音声処理APIへアクセスするクラス
62598fa056b00c62f0fb26f3
class DummySingleton1(bouwer.util.Singleton): <NEW_LINE> <INDENT> def __init__(self, arg1, arg2): <NEW_LINE> <INDENT> self.arg1 = arg1 <NEW_LINE> self.arg2 = arg2
First Dummy Singleton class
62598fa07b25080760ed72eb
class SmtLibOptions(SolverOptions): <NEW_LINE> <INDENT> def __init__(self, **base_options): <NEW_LINE> <INDENT> SolverOptions.__init__(self, **base_options) <NEW_LINE> if self.unsat_cores_mode is not None: <NEW_LINE> <INDENT> raise PysmtValueError("'unsat_cores_mode' option not supported.") <NEW_LINE> <DEDENT> self.debug_interaction = False <NEW_LINE> if 'debug_interaction' in self.solver_options: <NEW_LINE> <INDENT> self.debug_interaction = self.solver_options['debug_interaction'] <NEW_LINE> del self.solver_options['debug_interaction'] <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, solver): <NEW_LINE> <INDENT> solver.set_option(":print-success", "true") <NEW_LINE> solver.set_option(":diagnostic-output-channel", '"stdout"') <NEW_LINE> if self.generate_models: <NEW_LINE> <INDENT> solver.set_option(":produce-models", "true") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> solver.set_option(":produce-models", "false") <NEW_LINE> <DEDENT> if self.random_seed is not None: <NEW_LINE> <INDENT> solver.set_option(":random-seed", str(self.random_seed)) <NEW_LINE> <DEDENT> for k,v in self.solver_options.items(): <NEW_LINE> <INDENT> if k in (':print-success', 'diagnostic-output-channel'): <NEW_LINE> <INDENT> raise PysmtValueError("Cannot override %s." % k) <NEW_LINE> <DEDENT> solver.set_option(k, str(v))
Options for the SmtLib Solver. * debug_interaction: True, False Print the communication between pySMT and the wrapped executable
62598fa03c8af77a43b67e61
class Options(object): <NEW_LINE> <INDENT> def __init__(self, namespace='', port=8000, address='', registry=CollectorRegistry()): <NEW_LINE> <INDENT> self._namespace = namespace <NEW_LINE> self._registry = registry <NEW_LINE> self._port = int(port) <NEW_LINE> self._address = address <NEW_LINE> <DEDENT> @property <NEW_LINE> def registry(self): <NEW_LINE> <INDENT> return self._registry <NEW_LINE> <DEDENT> @property <NEW_LINE> def namespace(self): <NEW_LINE> <INDENT> return self._namespace <NEW_LINE> <DEDENT> @property <NEW_LINE> def port(self): <NEW_LINE> <INDENT> return self._port <NEW_LINE> <DEDENT> @property <NEW_LINE> def address(self): <NEW_LINE> <INDENT> return self._address
Options contains options for configuring the exporter. The address can be empty as the prometheus client will assume it's localhost :type namespace: str :param namespace: The prometheus namespace to be used. Defaults to ''. :type port: int :param port: The Prometheus port to be used. Defaults to 8000. :type address: str :param address: The Prometheus address to be used. Defaults to ''. :type registry: registry :param registry: The Prometheus address to be used. Defaults to ''. :type registry: :class:`~prometheus_client.core.CollectorRegistry` :param registry: A Prometheus collector registry instance.
62598fa0adb09d7d5dc0a3cd
class YeelightScanner: <NEW_LINE> <INDENT> _scanner = None <NEW_LINE> @classmethod <NEW_LINE> @callback <NEW_LINE> def async_get(cls, hass: HomeAssistant): <NEW_LINE> <INDENT> if cls._scanner is None: <NEW_LINE> <INDENT> cls._scanner = cls(hass) <NEW_LINE> <DEDENT> return cls._scanner <NEW_LINE> <DEDENT> def __init__(self, hass: HomeAssistant) -> None: <NEW_LINE> <INDENT> self._hass = hass <NEW_LINE> self._seen = {} <NEW_LINE> self._callbacks = {} <NEW_LINE> self._scan_task = None <NEW_LINE> <DEDENT> async def _async_scan(self): <NEW_LINE> <INDENT> _LOGGER.debug("Yeelight scanning") <NEW_LINE> for _ in range(3): <NEW_LINE> <INDENT> devices = await self._hass.async_add_executor_job(discover_bulbs) <NEW_LINE> for device in devices: <NEW_LINE> <INDENT> unique_id = device["capabilities"]["id"] <NEW_LINE> if unique_id in self._seen: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> host = device["ip"] <NEW_LINE> self._seen[unique_id] = host <NEW_LINE> _LOGGER.debug("Yeelight discovered at %s", host) <NEW_LINE> if unique_id in self._callbacks: <NEW_LINE> <INDENT> self._hass.async_create_task(self._callbacks[unique_id](host)) <NEW_LINE> self._callbacks.pop(unique_id) <NEW_LINE> if len(self._callbacks) == 0: <NEW_LINE> <INDENT> self._async_stop_scan() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> await asyncio.sleep(SCAN_INTERVAL.total_seconds()) <NEW_LINE> self._scan_task = self._hass.loop.create_task(self._async_scan()) <NEW_LINE> <DEDENT> @callback <NEW_LINE> def _async_start_scan(self): <NEW_LINE> <INDENT> _LOGGER.debug("Start scanning") <NEW_LINE> self._scan_task = self._hass.loop.create_task(self._async_scan()) <NEW_LINE> <DEDENT> @callback <NEW_LINE> def _async_stop_scan(self): <NEW_LINE> <INDENT> _LOGGER.debug("Stop scanning") <NEW_LINE> if self._scan_task is not None: <NEW_LINE> <INDENT> self._scan_task.cancel() <NEW_LINE> self._scan_task = None <NEW_LINE> <DEDENT> <DEDENT> @callback <NEW_LINE> def async_register_callback(self, unique_id, callback_func): <NEW_LINE> <INDENT> host = self._seen.get(unique_id) <NEW_LINE> if host is not None: <NEW_LINE> <INDENT> self._hass.async_create_task(callback_func(host)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._callbacks[unique_id] = callback_func <NEW_LINE> if len(self._callbacks) == 1: <NEW_LINE> <INDENT> self._async_start_scan() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @callback <NEW_LINE> def async_unregister_callback(self, unique_id): <NEW_LINE> <INDENT> if unique_id not in self._callbacks: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._callbacks.pop(unique_id) <NEW_LINE> if len(self._callbacks) == 0: <NEW_LINE> <INDENT> self._async_stop_scan()
Scan for Yeelight devices.
62598fa0e5267d203ee6b750
class Help(object): <NEW_LINE> <INDENT> swagger_types = { 'text': 'str' } <NEW_LINE> attribute_map = { 'text': 'text' } <NEW_LINE> def __init__(self, text=None): <NEW_LINE> <INDENT> self._text = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.text = text <NEW_LINE> <DEDENT> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return self._text <NEW_LINE> <DEDENT> @text.setter <NEW_LINE> def text(self, text): <NEW_LINE> <INDENT> if text is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `text`, must not be `None`") <NEW_LINE> <DEDENT> self._text = text <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(Help, 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, Help): <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.
62598fa08e71fb1e983bb8f9
class Subscription(models.Model): <NEW_LINE> <INDENT> pack_name = models.CharField('Subscription Name', max_length=255) <NEW_LINE> price = models.PositiveIntegerField('Subscription Price',) <NEW_LINE> no_resume = models.IntegerField('No. of Resume User can Access') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.pack_name
Add Subscription Pack by Admin
62598fa0d7e4931a7ef3bedc
class HathiBaseAPI: <NEW_LINE> <INDENT> api_root = "" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.session = requests.Session() <NEW_LINE> headers = { "User-Agent": "ppa-django/%s (%s)" % (ppa_version, self.session.headers["User-Agent"]) } <NEW_LINE> tech_contact = getattr(settings, "TECHNICAL_CONTACT", None) <NEW_LINE> if tech_contact: <NEW_LINE> <INDENT> headers["From"] = tech_contact <NEW_LINE> <DEDENT> self.session.headers.update(headers) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.session.close() <NEW_LINE> <DEDENT> def _make_request(self, url, params=None): <NEW_LINE> <INDENT> url = "%s/%s" % (self.api_root, url) <NEW_LINE> rqst_opts = {} <NEW_LINE> if params: <NEW_LINE> <INDENT> rqst_opts["params"] = params <NEW_LINE> <DEDENT> start = time.time() <NEW_LINE> resp = self.session.get(url, **rqst_opts) <NEW_LINE> logger.debug("get %s %s: %f sec", url, resp.status_code, time.time() - start) <NEW_LINE> if resp.status_code == requests.codes.ok: <NEW_LINE> <INDENT> return resp <NEW_LINE> <DEDENT> if resp.status_code == requests.codes.not_found: <NEW_LINE> <INDENT> raise HathiItemNotFound <NEW_LINE> <DEDENT> if resp.status_code == requests.codes.forbidden: <NEW_LINE> <INDENT> raise HathiItemForbidden
Base client class for HathiTrust APIs
62598fa04428ac0f6e65836e
class MyList(list): <NEW_LINE> <INDENT> def print_sorted(self): <NEW_LINE> <INDENT> copy_list = self[:] <NEW_LINE> copy_list.sort() <NEW_LINE> print(copy_list)
Represent a list that inherits from a built-in list.
62598fa04f6381625f1993de
class Initiator(Resource): <NEW_LINE> <INDENT> def update(self, **kwargs): <NEW_LINE> <INDENT> raise NimOSAPIOperationUnsupported("update operation not supported")
Manage initiators in initiator groups. An initiator group has a set of initiators that can be configured as part of your ACL to access a specific volume through group membership. # Parameters id : Identifier for initiator. access_protocol : Access protocol used by the initiator. Valid values are 'iscsi' and 'fc'. initiator_group_id : Identifier of the initiator group that this initiator is assigned to. initiator_group_name : Name of the initiator group that this initiator is assigned to. label : Unique Identifier of the iSCSI initiator. Label is required when creating iSCSI initiator. iqn : IQN name of the iSCSI initiator. Each initiator IQN name must have an associated IP address specified using the 'ip_address' attribute. You can choose not to enter the IP address for an initiator if you prefer not to authenticate using both name and IP address, in this case the IP address will be returned as '*'. ip_address : IP address of the iSCSI initiator. Each initiator IP address must have an associated name specified using 'name' attribute. You can choose not to enter the name for an initiator if you prefer not to authenticate using both name and IP address, in this case the IQN name will be returned as '*'. alias : Alias of the Fibre Channel initiator. Maximum alias length is 32 characters. Each initiator alias must have an associated WWPN specified using the 'wwpn' attribute. You can choose not to enter the WWPN for an initiator when using previously saved initiator alias. chapuser_id : Identifier for the CHAP user. wwpn : WWPN (World Wide Port Name) of the Fibre Channel initiator. WWPN is required when creating a Fibre Channel initiator. Each initiator WWPN can have an associated alias specified using the 'alias' attribute. You can choose not to enter the alias for an initiator if you prefer not to assign an initiator alias. vp_override : Flag to allow modifying VP created initiator groups. When set to true, user can add this initiator to a VP created initiator group. creation_time : Time when this initiator group was created. last_modified : Time when this initiator group was last modified. override_existing_alias : Forcibly add Fibre Channel initiator to initiator group by updating or removing conflicting Fibre Channel initiator aliases.
62598fa0c432627299fa2e1d
class Service(Dict[str, Parameter]): <NEW_LINE> <INDENT> def __init__( self, name: str, parameters: Optional[Dict[str, Parameter]] = None, **extra: Parameter, ) -> None: <NEW_LINE> <INDENT> super(Service, self).__init__() <NEW_LINE> self.name = name <NEW_LINE> self.update(parameters or {}) <NEW_LINE> self.update(extra) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "<%s %s>" % (self.__class__.__name__, self.name) <NEW_LINE> <DEDENT> def __getattr__(self, name: str) -> Parameter: <NEW_LINE> <INDENT> return self[name] <NEW_LINE> <DEDENT> def __setattr__(self, name: str, value: Parameter) -> None: <NEW_LINE> <INDENT> self[name] = value
Service definition. The :class:`Service` class represents a single service definition in a Service file. It’s actually a dictionnary of its own parameters. The ``name`` attributes is mapped to the section name of the service in the Service file. Each parameters can be accessed either as a dictionnary entry or as an attributes. >>> myservice = Service('myservice', {'dbname': 'mydb'}, host='myhost') >>> myservice.name 'myservice' >>> myservice.dbname 'mydb' >>> myservice['dbname'] 'mydb' >>> myservice.user = 'myuser' >>> list(sorted(myservice.items())) [('dbname', 'mydb'), ('host', 'myhost'), ('name', 'myservice'), ('user', 'myuser')]
62598fa03539df3088ecc0f8
class QuoteViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = models.QuoteModel.objects.all() <NEW_LINE> serializer_class = serializers.QuoteSerializer
API endpoint that allows currency quotations to be viewed.
62598fa18e7ae83300ee8ee3
class NasHTTPServerHandler(BaseHTTPServer.BaseHTTPRequestHandler): <NEW_LINE> <INDENT> post_paths = { "/ac": handle_ac, "/pr": handle_pr, "/download": handle_download } <NEW_LINE> ac_actions = { "acctcreate": handle_ac_acctcreate, "login": handle_ac_login, "svcloc": handle_ac_svcloc, } <NEW_LINE> download_actions = { "count": handle_download_count, "list": handle_download_list, "contents": handle_download_contents, } <NEW_LINE> def version_string(self): <NEW_LINE> <INDENT> return "Nintendo Wii (http)" <NEW_LINE> <DEDENT> def do_GET(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.send_response(200) <NEW_LINE> self.send_header("Content-type", "text/html") <NEW_LINE> self.send_header("X-Organization", "Nintendo") <NEW_LINE> self.send_header("Server", "BigIP") <NEW_LINE> self.end_headers() <NEW_LINE> self.wfile.write("ok") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.log(logging.ERROR, "Exception occurred on GET request!") <NEW_LINE> logger.log(logging.ERROR, "%s", traceback.format_exc()) <NEW_LINE> <DEDENT> <DEDENT> def do_POST(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> length = int(self.headers['content-length']) <NEW_LINE> post = utils.qs_to_dict(self.rfile.read(length)) <NEW_LINE> client_address = ( self.headers.get('x-forwarded-for', self.client_address[0]), self.client_address[1] ) <NEW_LINE> post['ipaddr'] = client_address[0] <NEW_LINE> command = self.post_paths.get(self.path, handle_post) <NEW_LINE> ret = command(self, client_address, post) <NEW_LINE> if ret is not None: <NEW_LINE> <INDENT> self.send_header("Content-Length", str(len(ret))) <NEW_LINE> self.end_headers() <NEW_LINE> self.wfile.write(ret) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> logger.log(logging.ERROR, "Exception occurred on POST request!") <NEW_LINE> logger.log(logging.ERROR, "%s", traceback.format_exc())
Nintendo NAS server handler.
62598fa1d53ae8145f9182d1
class Settings(object): <NEW_LINE> <INDENT> NotDefined = object() <NEW_LINE> def __init__(self, **overrides): <NEW_LINE> <INDENT> self.overrides = overrides <NEW_LINE> self._orig = {} <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> for k, v in self.overrides.iteritems(): <NEW_LINE> <INDENT> self._orig[k] = getattr(settings, k, self.NotDefined) <NEW_LINE> setattr(settings, k, v) <NEW_LINE> <DEDENT> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> for k, v in self._orig.iteritems(): <NEW_LINE> <INDENT> if v is self.NotDefined: <NEW_LINE> <INDENT> delattr(settings, k) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(settings, k, v)
Allows you to define settings that are required for this function to work. >>> with Settings(SENTRY_LOGIN_URL='foo'): #doctest: +SKIP >>> print settings.SENTRY_LOGIN_URL #doctest: +SKIP
62598fa1442bda511e95c29e
class Column(): <NEW_LINE> <INDENT> Name = 0 <NEW_LINE> Location = 1 <NEW_LINE> InternalID = 2 <NEW_LINE> LabelsAllowed = 3 <NEW_LINE> NumColumns = 4
Enum for table column positions
62598fa1baa26c4b54d4f0f4
class PyBpython(PythonPackage): <NEW_LINE> <INDENT> homepage = "https://github.com/bpython/bpython" <NEW_LINE> url = "https://github.com/bpython/bpython/archive/0.17-release.tar.gz" <NEW_LINE> version('0.17', '0889bc44c89b82e78baf1fd929b50cdb') <NEW_LINE> depends_on('py-pygments') <NEW_LINE> depends_on('py-requests') <NEW_LINE> depends_on('py-curtsies@0.1.18:0.199999') <NEW_LINE> depends_on('py-greenlet') <NEW_LINE> depends_on('py-setuptools') <NEW_LINE> depends_on('py-six')
A fancy curses interface to the Python interactive interpreter. https://bpython-interpreter.org/
62598fa17d43ff2487427324
class TestExportGmap(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> logging.info('setup') <NEW_LINE> self.____never_used_variable = 1 <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> logging.info("teardown") <NEW_LINE> <DEDENT> def test_export_gmap_true(self): <NEW_LINE> <INDENT> assert True <NEW_LINE> <DEDENT> def test_bottle_tmp_never_used_variable_as_1(self): <NEW_LINE> <INDENT> logging.info("test_bottle_tmp: test_bottle_tmp_true") <NEW_LINE> assert self.____never_used_variable == 1
unit tests for export_gmap
62598fa166656f66f7d5a235
class cycle(object): <NEW_LINE> <INDENT> def next(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __getattribute__(self, name): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, iterable): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(S, *more): <NEW_LINE> <INDENT> pass
cycle(iterable) --> cycle object Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely.
62598fa1a8370b77170f0229
class Adc(Instruction): <NEW_LINE> <INDENT> sets_zero_bit = True <NEW_LINE> sets_negative_bit = True <NEW_LINE> @classmethod <NEW_LINE> def write(cls, cpu, memory_address, value): <NEW_LINE> <INDENT> result = cpu.a_reg + int(value) + int(cpu.status_reg.bits[Status.StatusTypes.carry]) <NEW_LINE> overflow = bool((cpu.a_reg ^ result) & (value ^ result) & 0x80) <NEW_LINE> cpu.status_reg.bits[Status.StatusTypes.overflow] = overflow <NEW_LINE> cpu.status_reg.bits[Status.StatusTypes.carry] = bool(result & 256) <NEW_LINE> cpu.a_reg = np.uint8(result) <NEW_LINE> return cpu.a_reg
A + M + C -> A, C N Z C I D V + + + - - +
62598fa14e4d562566372268
class CSVFilterForm(forms.Form): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.model = kwargs.pop('model') <NEW_LINE> super(CSVFilterForm, self).__init__(*args, **kwargs) <NEW_LINE> if not self.model: <NEW_LINE> <INDENT> raise ImproperlyConfigured('Seems like there is no model defined. check our urlpatterns (add model to kwargs).') <NEW_LINE> <DEDENT> self.csv_filter_definition = settings.CSV_EXPORTER_FILTER_DEFINITION[self.model._meta.module_name] <NEW_LINE> self.create_fields(filter_def=self.csv_filter_definition) <NEW_LINE> <DEDENT> def create_fields(self, filter_def={}, prefix=""): <NEW_LINE> <INDENT> for key in filter_def: <NEW_LINE> <INDENT> if type(filter_def[key]) == dict: <NEW_LINE> <INDENT> self.create_fields(filter_def=filter_def[key], prefix=prefix + key + "__") <NEW_LINE> <DEDENT> elif type(filter_def[key]) == list: <NEW_LINE> <INDENT> for filter_type in filter_def[key]: <NEW_LINE> <INDENT> self.fields[prefix + key + "__" + filter_type] = forms.CharField(required=False) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.fields[prefix + key + "__" + filter_def[key]] = forms.CharField(required=False) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def clean(self): <NEW_LINE> <INDENT> filters = {} <NEW_LINE> for item in self.cleaned_data: <NEW_LINE> <INDENT> if self.cleaned_data[item]: <NEW_LINE> <INDENT> filters[item] = self.cleaned_data[item] <NEW_LINE> <DEDENT> <DEDENT> if len(filters) == 0: <NEW_LINE> <INDENT> raise forms.ValidationError("no filters selected!") <NEW_LINE> <DEDENT> self.filters = filters <NEW_LINE> return super(CSVFilterForm, self).clean() <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> return self.model.objects.filter(**self.filters)
filter the data of a queryset.
62598fa1379a373c97d98e5b
class TestLive(TestAsServer): <NEW_LINE> <INDENT> def setUpPreSession(self): <NEW_LINE> <INDENT> TestAsServer.setUpPreSession(self) <NEW_LINE> self.destdir = '.' <NEW_LINE> f = open("liveinput.dat","wb") <NEW_LINE> self.nchunks = 1017 <NEW_LINE> for i in range(0,self.nchunks): <NEW_LINE> <INDENT> data = chr((ord('a')+i)%256) * 1024 <NEW_LINE> f.write(data) <NEW_LINE> <DEDENT> f.close() <NEW_LINE> self.livesourceinput = "liveinput.dat" <NEW_LINE> self.filename = "storage.dat" <NEW_LINE> <DEDENT> def setUpPostSession(self): <NEW_LINE> <INDENT> TestAsServer.setUpPostSession(self) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> TestAsServer.tearDown(self) <NEW_LINE> try: <NEW_LINE> <INDENT> os.remove(self.livesourceinput) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> os.remove(self.filename) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def test_live_source(self): <NEW_LINE> <INDENT> time.sleep(20) <NEW_LINE> print >>sys.stderr,"test: Comparing input to storage.dat" <NEW_LINE> f = open(self.livesourceinput,"rb") <NEW_LINE> g = open(self.filename,"rb") <NEW_LINE> for i in range(0,self.nchunks): <NEW_LINE> <INDENT> expdata = f.read(1024) <NEW_LINE> gotdata = g.read(1024) <NEW_LINE> self.assertEquals(expdata,gotdata) <NEW_LINE> <DEDENT> f.close() <NEW_LINE> g.close()
Basic test that starts a live source which generates ~1000 chunks.
62598fa1cb5e8a47e493c098
class AddLoginWhiteListRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Rules = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("Rules") is not None: <NEW_LINE> <INDENT> self.Rules = LoginWhiteListsRule() <NEW_LINE> self.Rules._deserialize(params.get("Rules"))
AddLoginWhiteList请求参数结构体
62598fa1a79ad16197769ea9
class BEPZero(Transform): <NEW_LINE> <INDENT> default_priority =760 <NEW_LINE> def apply(self): <NEW_LINE> <INDENT> visitor = BEPZeroSpecial(self.document) <NEW_LINE> self.document.walk(visitor) <NEW_LINE> self.startnode.parent.remove(self.startnode)
Special processing for BEP 0.
62598fa17b25080760ed72ed
class IndividualCourseSummary(models.Model): <NEW_LINE> <INDENT> _name='school.individual_course_summary' <NEW_LINE> _inherit = ['school.open.form.mixin'] <NEW_LINE> program_id = fields.Many2one('school.individual_program', string='Individual Program') <NEW_LINE> course_group_id = fields.Many2one('school.course_group', string='Course Group') <NEW_LINE> uid = fields.Char(string="UID",related="course_group_id.uid") <NEW_LINE> name = fields.Char(string="Name",related="course_group_id.name") <NEW_LINE> responsible_id = fields.Many2one('res.partner', string="Name",related="course_group_id.responsible_id") <NEW_LINE> total_hours = fields.Integer(string="Credits",related="course_group_id.total_hours") <NEW_LINE> total_credits = fields.Integer(string="Hours",related="course_group_id.total_credits") <NEW_LINE> sequence = fields.Integer(string="Sequence",related="course_group_id.sequence") <NEW_LINE> level = fields.Integer(string="Level",related="course_group_id.level") <NEW_LINE> ind_course_group_ids = fields.One2many('school.individual_course_group', string='Courses Groups', compute="_compute_ind_course_group_ids") <NEW_LINE> def _compute_ind_course_group_ids(self): <NEW_LINE> <INDENT> for rec in self: <NEW_LINE> <INDENT> rec.ind_course_group_ids = self.env['school.individual_course_group'].search([('bloc_id','in',self.program_id.bloc_ids.ids),('source_course_group_id','=',rec.course_group_id.id)])
IndividualCourse Summary
62598fa13c8af77a43b67e62
class IsOwnerOrReadOnly(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif obj.author == request.user: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
自定义权限类
62598fa166673b3332c3020b
class TestRunBenchmark(unittest.TestCase): <NEW_LINE> <INDENT> @patch('test_runners.tf_cnn_bench.run_benchmark.TestRunner.run_test_suite') <NEW_LINE> @patch('test_runners.tf_cnn_bench.run_benchmark.TestRunner._make_log_dir') <NEW_LINE> def test_run_tests(self, make_log_dir_mock, run_test_suite): <NEW_LINE> <INDENT> expected_file = ('test_runners/tf_cnn_bench/test_configs/' 'expected_full_config.yaml') <NEW_LINE> f = open(expected_file) <NEW_LINE> expected_full_config = yaml.safe_load(f) <NEW_LINE> config = 'test_runners/tf_cnn_bench/test_configs/basic_run_config.yaml' <NEW_LINE> test_runner = run_benchmark.TestRunner(config, '/workspace', 'bench_home') <NEW_LINE> test_runner.run_tests() <NEW_LINE> make_log_dir_mock.assert_called_with('/workspace/logs') <NEW_LINE> run_test_suite.assert_called_with(expected_full_config) <NEW_LINE> <DEDENT> @patch('test_runners.tf_cnn_bench.run_benchmark.TestRunner._make_log_dir') <NEW_LINE> @patch('test_runners.tf_cnn_bench.run_benchmark.reporting.process_folder') <NEW_LINE> @patch('test_runners.tf_cnn_bench.run_benchmark.TestRunner.run_benchmark') <NEW_LINE> def test_run_test_suite(self, run_benchmark_mock, reporting_mock, _): <NEW_LINE> <INDENT> config_file = ( 'test_runners/tf_cnn_bench/test_configs/expected_full_config.yaml') <NEW_LINE> f = open(config_file) <NEW_LINE> full_config = yaml.safe_load(f) <NEW_LINE> test_runner = run_benchmark.TestRunner(None, '/workspace', 'bench_home') <NEW_LINE> test_runner.run_test_suite(full_config) <NEW_LINE> self.assertEqual(run_benchmark_mock.call_count, 3) <NEW_LINE> self.assertEqual(reporting_mock.call_count, 1) <NEW_LINE> last_run_benchmark_arg0 = run_benchmark_mock.call_args[0][0] <NEW_LINE> last_run_benchmark_arg1 = run_benchmark_mock.call_args[0][1] <NEW_LINE> self.assertEqual(last_run_benchmark_arg0['copy'], 2) <NEW_LINE> self.assertIn('test_suite_start_time', last_run_benchmark_arg0) <NEW_LINE> self.assertTrue(last_run_benchmark_arg0['model'], 'resnet50') <NEW_LINE> self.assertTrue(last_run_benchmark_arg0['batch_size'], 64) <NEW_LINE> self.assertIsInstance(last_run_benchmark_arg1, run_benchmark.cluster_local.LocalInstance)
Tests for run_benchmark module.
62598fa167a9b606de545e0f
class GetUserFeedInputSet(InputSet): <NEW_LINE> <INDENT> def set_AccessToken(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AccessToken', value) <NEW_LINE> <DEDENT> def set_Count(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Count', value) <NEW_LINE> <DEDENT> def set_MaxID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'MaxID', value) <NEW_LINE> <DEDENT> def set_MinID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'MinID', value) <NEW_LINE> <DEDENT> def set_UserID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'UserID', value)
An InputSet with methods appropriate for specifying the inputs to the GetUserFeed Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62598fa1cc0a2c111447ae53
class getFilialById_args(object): <NEW_LINE> <INDENT> def __init__(self, id=None,): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.id = iprot.readI32() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getFilialById_args') <NEW_LINE> if self.id is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('id', TType.I32, 1) <NEW_LINE> oprot.writeI32(self.id) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - id
62598fa107f4c71912baf289
class Meta: <NEW_LINE> <INDENT> verbose_name = "Rol" <NEW_LINE> verbose_name_plural = "Roles"
Configuraciones
62598fa12c8b7c6e89bd360b
class ErrorTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_Raise(self): <NEW_LINE> <INDENT> nest.ResetKernel() <NEW_LINE> try: <NEW_LINE> <INDENT> raise nest.NESTError('test') <NEW_LINE> self.fail('an error should have risen!') <NEW_LINE> <DEDENT> except nest.NESTError: <NEW_LINE> <INDENT> info = sys.exc_info()[1] <NEW_LINE> if not "test" in info.__str__(): <NEW_LINE> <INDENT> self.fail('could not pass error message to NEST!') <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.fail('wrong error has been thrown') <NEW_LINE> <DEDENT> <DEDENT> def test_StackUnderFlow(self): <NEW_LINE> <INDENT> nest.ResetKernel() <NEW_LINE> try: <NEW_LINE> <INDENT> nest.sr('clear ;') <NEW_LINE> self.fail('an error should have risen!') <NEW_LINE> <DEDENT> except nest.NESTError: <NEW_LINE> <INDENT> info = sys.exc_info()[1] <NEW_LINE> if not "StackUnderflow" in info.__str__(): <NEW_LINE> <INDENT> self.fail('wrong error message') <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.fail('wrong error has been thrown') <NEW_LINE> <DEDENT> <DEDENT> def test_DivisionByZero(self): <NEW_LINE> <INDENT> nest.ResetKernel() <NEW_LINE> try: <NEW_LINE> <INDENT> nest.sr('1 0 div') <NEW_LINE> self.fail('an error should have risen!') <NEW_LINE> <DEDENT> except nest.NESTError: <NEW_LINE> <INDENT> info = sys.exc_info()[1] <NEW_LINE> if not "DivisionByZero" in info.__str__(): <NEW_LINE> <INDENT> self.fail('wrong error message') <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.fail('wrong error has been thrown') <NEW_LINE> <DEDENT> <DEDENT> def test_UnknownNode(self): <NEW_LINE> <INDENT> nest.ResetKernel() <NEW_LINE> try: <NEW_LINE> <INDENT> nest.Connect([99],[99]) <NEW_LINE> self.fail('an error should have risen!') <NEW_LINE> <DEDENT> except nest.NESTError: <NEW_LINE> <INDENT> info = sys.exc_info()[1] <NEW_LINE> if not "UnknownNode" in info.__str__(): <NEW_LINE> <INDENT> self.fail('wrong error message') <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.fail('wrong error has been thrown') <NEW_LINE> <DEDENT> <DEDENT> def test_UnknownModel(self): <NEW_LINE> <INDENT> nest.ResetKernel() <NEW_LINE> try: <NEW_LINE> <INDENT> nest.Create(-1) <NEW_LINE> self.fail('an error should have risen!') <NEW_LINE> <DEDENT> except nest.NESTError: <NEW_LINE> <INDENT> info = sys.exc_info()[1] <NEW_LINE> if not "UnknownModelName" in info.__str__(): <NEW_LINE> <INDENT> self.fail('wrong error message') <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.fail('wrong error has been thrown')
Tests if errors are handled correctly
62598fa16e29344779b004a1
class Beam(): <NEW_LINE> <INDENT> def __init__(self, elements, supports): <NEW_LINE> <INDENT> self.len_elements = [element.length for element in elements] <NEW_LINE> self.E_elements = [element.E for element in elements] <NEW_LINE> self.I_elements = [element.I for element in elements] <NEW_LINE> self.num_elements = len(elements) <NEW_LINE> self.num_nodes = self.num_elements + 1 <NEW_LINE> self.num_dof = self.num_nodes * 2 <NEW_LINE> self.supports = supports <NEW_LINE> self.stiffness = np.zeros((self.num_dof, self.num_dof)) <NEW_LINE> self.load = np.zeros((self.num_dof)) <NEW_LINE> for i, element in enumerate(elements): <NEW_LINE> <INDENT> a = i * 2 <NEW_LINE> b = a + 4 <NEW_LINE> stiffness_element = np.zeros_like(self.stiffness) <NEW_LINE> stiffness_element[a:b, a:b] = element.stiffness <NEW_LINE> self.stiffness = self.stiffness + stiffness_element <NEW_LINE> load_element = np.zeros_like(self.load) <NEW_LINE> load_element[a:b] = element.nodal_loads <NEW_LINE> self.load = self.load - load_element <NEW_LINE> <DEDENT> for i in range(self.num_dof): <NEW_LINE> <INDENT> if self.supports[i] < 0: <NEW_LINE> <INDENT> self.stiffness[i, :] = 0 <NEW_LINE> self.stiffness[:, i] = 0 <NEW_LINE> self.stiffness[i, i] = 1 <NEW_LINE> self.load[i] = 0 <NEW_LINE> <DEDENT> if self.supports[i] > 0: <NEW_LINE> <INDENT> self.stiffness[i, i] = self.stiffness[i, i] + self.supports[i] <NEW_LINE> <DEDENT> <DEDENT> self.displacement = np.linalg.solve(self.stiffness, self.load)
Class for an assembly of elements into a single beam.
62598fa1eab8aa0e5d30bbcc
class Perceptron(object): <NEW_LINE> <INDENT> def __init__(self, eta=0.01, n_iter=10): <NEW_LINE> <INDENT> self.eta = eta <NEW_LINE> self.n_iter = n_iter <NEW_LINE> self.w_ = [] <NEW_LINE> self.errors_ = [] <NEW_LINE> <DEDENT> def fit(self, X, y): <NEW_LINE> <INDENT> self.w_ = np.zeros(1 + X.shape[1]) <NEW_LINE> self.errors_ = [] <NEW_LINE> for _ in range(self.n_iter): <NEW_LINE> <INDENT> errors = 0 <NEW_LINE> for xi, target in zip(X, y): <NEW_LINE> <INDENT> update = self.eta * (target - self.predict(xi)) <NEW_LINE> self.w_[1:] += update * xi <NEW_LINE> self.w_[0] += update <NEW_LINE> errors += int(update != 0.0) <NEW_LINE> <DEDENT> self.errors_.append(errors) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def net_input(self, X): <NEW_LINE> <INDENT> return np.dot(X, self.w_[1:]) + self.w_[0] <NEW_LINE> <DEDENT> def predict(self, X): <NEW_LINE> <INDENT> return np.where(self.net_input(X) >= 0.0, 1, -1)
Perceptron classifier Parameters eta: float Learning rate (0.0 - 1.0) n_iter: int Passes over the training set Attributes w_: 1d-array Weights after filtering errors_: list Number of misclassification in every epoch
62598fa1460517430c431f7e
class SearchFinalMultipleNumQA(SearchMultipleNumQABase): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def is_match(value_list, num, data): <NEW_LINE> <INDENT> (matched, left_over_final_data) = SearchMultipleNumQABase.multiple_num_helper(value_list, num, data) <NEW_LINE> return matched
Aggregator for: P7_other_[12,13,14]
62598fa1e5267d203ee6b753
class RenderAutoShortcutLink(AutoLinkMixin, components.RenderComponent): <NEW_LINE> <INDENT> def createHTML(self, token, parent): <NEW_LINE> <INDENT> page, tag, href = self.createHTMLHelper(token, parent, 'key') <NEW_LINE> if token.bookmark is not None: <NEW_LINE> <INDENT> tok = self.findToken(page, token) <NEW_LINE> href += token.bookmark <NEW_LINE> if token.header: <NEW_LINE> <INDENT> h = self.findHeading(page) <NEW_LINE> if h: <NEW_LINE> <INDENT> for n in h.children: <NEW_LINE> <INDENT> self.translator.renderer.process(tag, n) <NEW_LINE> <DEDENT> html.String(tag, content=u':') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> tok = self.findHeading(page) <NEW_LINE> <DEDENT> tag['href'] = href <NEW_LINE> if tok is not None: <NEW_LINE> <INDENT> for n in tok.children: <NEW_LINE> <INDENT> self.translator.renderer.process(tag, n) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> msg = "Failed to locate a heading for '{}'." <NEW_LINE> raise exceptions.RenderException(token.info, msg, page.source) <NEW_LINE> <DEDENT> return tag
Render AutoShortcutLink token.
62598fa10a50d4780f705220
class Cello(Instrument): <NEW_LINE> <INDENT> name, short_name = 'Cello', 'Vcl.' <NEW_LINE> clef = 'bass' <NEW_LINE> max_gliss = NumberedInterval(12) <NEW_LINE> max_trill = NumberedInterval(5) <NEW_LINE> range = PitchRange.from_pitches( NamedPitch("c,"), NamedPitch("a'"), ) <NEW_LINE> quadruple_sort = 'start_offset' <NEW_LINE> strings = { 4: NamedPitch("c,"), 3: NamedPitch("g,"), 2: NamedPitch("d"), 1: NamedPitch("a"), } <NEW_LINE> string_ranges = { 4: PitchRange.from_pitches( NamedPitch("c,"), NamedPitch("c"), ), 3: PitchRange.from_pitches( NamedPitch("g,"), NamedPitch("g"), ), 2: PitchRange.from_pitches( NamedPitch("d"), NamedPitch("d'"), ), 1: PitchRange.from_pitches( NamedPitch("a"), NamedPitch("a'"), ), }
Model of the cello as an instrument. :: >>> import aurora >>> aurora.nouns.instruments.Cello() Cello()
62598fa1442bda511e95c2a0
class EbsCustomTagsRule(BaseRule): <NEW_LINE> <INDENT> def __init__(self, cfn_model=None, debug=None): <NEW_LINE> <INDENT> BaseRule.__init__(self, cfn_model, debug=debug) <NEW_LINE> <DEDENT> def rule_text(self): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print('rule_text' + lineno()) <NEW_LINE> <DEDENT> return 'Ebs volume does not have the required tags of Name, ResourceOwner, DeployedBy, Project' <NEW_LINE> <DEDENT> def rule_type(self): <NEW_LINE> <INDENT> self.type = 'VIOLATION::FAILING_VIOLATION' <NEW_LINE> return 'VIOLATION::FAILING_VIOLATION' <NEW_LINE> <DEDENT> def rule_id(self): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print('rule_id' + lineno()) <NEW_LINE> <DEDENT> self.id = 'F89' <NEW_LINE> return 'F89' <NEW_LINE> <DEDENT> def tags_to_dict(self, aws_tags): <NEW_LINE> <INDENT> return {str(tag['Key']): str(tag['Value']) for tag in self.ensure_list(aws_tags)} <NEW_LINE> <DEDENT> def ensure_list(self, value): <NEW_LINE> <INDENT> ret_value = value <NEW_LINE> if not value: <NEW_LINE> <INDENT> ret_value = [] <NEW_LINE> <DEDENT> elif not isinstance(value, Iterable) or isinstance(value, string_types): <NEW_LINE> <INDENT> ret_value = [value] <NEW_LINE> <DEDENT> return ret_value <NEW_LINE> <DEDENT> def audit_impl(self): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print('EbsHasTagsRule - audit_impl' + lineno()) <NEW_LINE> <DEDENT> violating_volumes = [] <NEW_LINE> resources = self.cfn_model.resources_by_type('AWS::EC2::Volume') <NEW_LINE> if len(resources) > 0: <NEW_LINE> <INDENT> for resource in resources: <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print('resource: ' + str(resource) + lineno()) <NEW_LINE> print('vars: ' + str(vars(resource))+lineno()) <NEW_LINE> <DEDENT> if hasattr(resource, 'tags') and resource.tags: <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print('has tags attribute' + lineno()) <NEW_LINE> <DEDENT> if type(resource.tags) == type(str()): <NEW_LINE> <INDENT> json_acceptable_string = resource.tags.replace("'", "\"") <NEW_LINE> resource.tags = json.loads(json_acceptable_string) <NEW_LINE> <DEDENT> if self.debug: <NEW_LINE> <INDENT> print('tags dict: '+str(resource.tags)+lineno()) <NEW_LINE> <DEDENT> tags_dict = list(resource.tags.keys()) <NEW_LINE> required_tags = ('Name', 'ResourceOwner', 'DeployedBy', 'Project') <NEW_LINE> if not set(required_tags).issubset(tags_dict): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print('missing required tags: '+lineno()) <NEW_LINE> <DEDENT> violating_volumes.append(str(resource.logical_resource_id)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print('does not tags property') <NEW_LINE> <DEDENT> violating_volumes.append(str(resource.logical_resource_id)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print('no violating_volumes' + lineno()) <NEW_LINE> <DEDENT> <DEDENT> return violating_volumes
Ebs custom tags rule
62598fa1d268445f26639aa6
class Task(object): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Container for an task. Runner objects run tasks (normally or in parallel). Intuitively, think of a Task as a box that Analysis creates and sends to a factory (Runner object) The base class is a dummy, meant to be extended
62598fa19c8ee82313040091
class palm_position(object): <NEW_LINE> <INDENT> x = 0 <NEW_LINE> y = 0 <NEW_LINE> z = 0
Fake palm position of hand to controller.
62598fa1a17c0f6771d5c080
class Cluster(Task): <NEW_LINE> <INDENT> def __init__(self, settings=None): <NEW_LINE> <INDENT> if settings is None: <NEW_LINE> <INDENT> settings = {} <NEW_LINE> <DEDENT> super(Cluster, self).__init__(settings) <NEW_LINE> self._kmeans_args = { 'max_iter': 50, 'tol': 1.0, } <NEW_LINE> <DEDENT> def get(self, img): <NEW_LINE> <INDENT> a = self._settings['algorithm'] <NEW_LINE> if a == 'kmeans': <NEW_LINE> <INDENT> return self._jump(img) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Unknown algorithm {}'.format(a)) <NEW_LINE> <DEDENT> <DEDENT> def _kmeans(self, img, k): <NEW_LINE> <INDENT> kmeans = KMeans(n_clusters=k, **self._kmeans_args) <NEW_LINE> try: <NEW_LINE> <INDENT> kmeans.fit(img) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise KMeansException() <NEW_LINE> <DEDENT> return kmeans.inertia_, kmeans.labels_, kmeans.cluster_centers_ <NEW_LINE> <DEDENT> def _jump(self, img): <NEW_LINE> <INDENT> npixels = img.size <NEW_LINE> best = None <NEW_LINE> prev_distorsion = 0 <NEW_LINE> largest_diff = float('-inf') <NEW_LINE> for k in range(self._settings['min_k'], self._settings['max_k']): <NEW_LINE> <INDENT> compact, labels, centers = self._kmeans(img, k) <NEW_LINE> distorsion = Cluster._square_distorsion(npixels, compact, 1.5) <NEW_LINE> diff = prev_distorsion - distorsion <NEW_LINE> prev_distorsion = distorsion <NEW_LINE> if diff > largest_diff: <NEW_LINE> <INDENT> largest_diff = diff <NEW_LINE> best = k, labels, centers <NEW_LINE> <DEDENT> <DEDENT> return best <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _default_settings(): <NEW_LINE> <INDENT> return { 'min_k': 2, 'max_k': 7, 'algorithm': 'kmeans', } <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _square_distorsion(npixels, compact, y): <NEW_LINE> <INDENT> return pow(compact / npixels, -y)
Use the K-Means algorithm to group pixels by clusters. The algorithm tries to determine the optimal number of clusters for the given pixels.
62598fa157b8e32f5250803f
class Test_keyImport(unittest.TestCase): <NEW_LINE> <INDENT> private_key = "L52XzL2cMkHxqxBXRyEpnPQZGUs3uKiL3R11XbAdHigRzDozKZeW" <NEW_LINE> public_key_hex = "0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2" <NEW_LINE> main_address = "15mKKb2eos1hWa6tisdPwwDC1a5J1y9nma" <NEW_LINE> def test_public_key_from_private_key(self): <NEW_LINE> <INDENT> result = public_key_from_private_key(self.private_key) <NEW_LINE> self.assertEqual(self.public_key_hex, result) <NEW_LINE> <DEDENT> def test_address_from_private_key(self): <NEW_LINE> <INDENT> result = address_from_private_key(self.private_key) <NEW_LINE> self.assertEqual(self.main_address, result) <NEW_LINE> <DEDENT> def test_is_valid_address(self): <NEW_LINE> <INDENT> self.assertTrue(is_address(self.main_address)) <NEW_LINE> self.assertFalse(is_address("not an address")) <NEW_LINE> <DEDENT> def test_is_private_key(self): <NEW_LINE> <INDENT> self.assertTrue(is_private_key(self.private_key)) <NEW_LINE> self.assertFalse(is_private_key(self.public_key_hex))
The keys used in this class are TEST keys from https://en.bitcoin.it/wiki/BIP_0032_TestVectors
62598fa191f36d47f2230dc4
class HoneywellConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> async def async_step_user(self, user_input=None): <NEW_LINE> <INDENT> errors = {} <NEW_LINE> if user_input is not None: <NEW_LINE> <INDENT> valid = await self.is_valid(**user_input) <NEW_LINE> if valid: <NEW_LINE> <INDENT> return self.async_create_entry( title=DOMAIN, data=user_input, ) <NEW_LINE> <DEDENT> errors["base"] = "invalid_auth" <NEW_LINE> <DEDENT> data_schema = { vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, } <NEW_LINE> return self.async_show_form( step_id="user", data_schema=vol.Schema(data_schema), errors=errors ) <NEW_LINE> <DEDENT> async def is_valid(self, **kwargs) -> bool: <NEW_LINE> <INDENT> client = await self.hass.async_add_executor_job( get_somecomfort_client, kwargs[CONF_USERNAME], kwargs[CONF_PASSWORD] ) <NEW_LINE> return client is not None
Handle a honeywell config flow.
62598fa1cb5e8a47e493c099
class SemDesconto(object): <NEW_LINE> <INDENT> def calcula(self, carrinho): <NEW_LINE> <INDENT> return 0
Não há descontos.
62598fa14e4d56256637226b
class BasicPostProcessor(Processor): <NEW_LINE> <INDENT> def get_board_topics_list(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_topic_all_reply(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_topic_page_reply(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def reply_topic(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def del_post(self): <NEW_LINE> <INDENT> raise NotImplementedError()
BasicPostProcessor, used to get/set posts' information
62598fa1e5267d203ee6b754
class DynamicUIRenderer(Enum): <NEW_LINE> <INDENT> indicatif_spinner = "indicatif-spinner" <NEW_LINE> experimental_prodash = "experimental-prodash"
Which renderer to use for dyanmic UI.
62598fa16fb2d068a7693d58
class Word(unicode): <NEW_LINE> <INDENT> def __new__(cls, string, pos_tag=None): <NEW_LINE> <INDENT> return super(Word, cls).__new__(cls, string) <NEW_LINE> <DEDENT> def __init__(self, string, pos_tag=None): <NEW_LINE> <INDENT> self.string = string <NEW_LINE> self.pos_tag = pos_tag <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Word('{0}')".format(self.string) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.string <NEW_LINE> <DEDENT> def singularize(self): <NEW_LINE> <INDENT> return _singularize(self.string) <NEW_LINE> <DEDENT> def pluralize(self): <NEW_LINE> <INDENT> return _pluralize(self.string)
A simple word representation.
62598fa1a79ad16197769eac
class LocaleURLMiddleware(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> if not settings.USE_I18N: <NEW_LINE> <INDENT> raise django.core.exceptions.MiddlewareNotUsed() <NEW_LINE> <DEDENT> <DEDENT> def process_request(self, request): <NEW_LINE> <INDENT> locale, path = utils.strip_path(request.path_info) <NEW_LINE> if localeurl_settings.USE_SESSION and not locale: <NEW_LINE> <INDENT> slocale = request.session.get('django_language') <NEW_LINE> if slocale and utils.supported_language(slocale): <NEW_LINE> <INDENT> locale = slocale <NEW_LINE> <DEDENT> <DEDENT> if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale: <NEW_LINE> <INDENT> accept_lang_header = request.META.get('HTTP_ACCEPT_LANGUAGE', '') <NEW_LINE> header_langs = parse_accept_lang_header(accept_lang_header) <NEW_LINE> accept_langs = [ l for l in (utils.supported_language(lang[0]) for lang in header_langs) if l ] <NEW_LINE> if accept_langs: <NEW_LINE> <INDENT> locale = accept_langs[0] <NEW_LINE> <DEDENT> <DEDENT> locale_path = utils.locale_path(path, locale) <NEW_LINE> if locale_path.lower() != request.path_info.lower(): <NEW_LINE> <INDENT> locale_url = utils.add_script_prefix(locale_path) <NEW_LINE> qs = request.META.get("QUERY_STRING", "") <NEW_LINE> if qs: <NEW_LINE> <INDENT> locale_url = "%s?%s" % (locale_path.encode("utf-8"), qs) <NEW_LINE> <DEDENT> redirect_class = HttpResponsePermanentRedirect <NEW_LINE> if not localeurl_settings.LOCALE_REDIRECT_PERMANENT: <NEW_LINE> <INDENT> redirect_class = HttpResponseRedirect <NEW_LINE> <DEDENT> return redirect_class(iri_to_uri(locale_url)) <NEW_LINE> <DEDENT> request.path_info = path <NEW_LINE> if not locale: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> locale = request.LANGUAGE_CODE <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> locale = settings.LANGUAGE_CODE <NEW_LINE> <DEDENT> <DEDENT> translation.activate(locale) <NEW_LINE> request.LANGUAGE_CODE = translation.get_language() <NEW_LINE> <DEDENT> def process_response(self, request, response): <NEW_LINE> <INDENT> if 'Content-Language' not in response: <NEW_LINE> <INDENT> response['Content-Language'] = translation.get_language() <NEW_LINE> <DEDENT> translation.deactivate() <NEW_LINE> return response
Middleware that sets the language based on the request path prefix and strips that prefix from the path. It will also automatically redirect any path without a prefix, unless PREFIX_DEFAULT_LOCALE is set to True. Exceptions are paths beginning with MEDIA_URL and/or STATIC_URL (if settings.LOCALE_INDEPENDENT_MEDIA_URL and/or settings.LOCALE_INDEPENDENT_STATIC_URL are set) or matching any regular expression from LOCALE_INDEPENDENT_PATHS from the project settings. For example, the path '/en/admin/' will set request.LANGUAGE_CODE to 'en' and request.path to '/admin/'. Alternatively, the language is set by the first component of the domain name. For example, a request on 'fr.example.com' would set the language to French. If you use this middleware the django.core.urlresolvers.reverse function is be patched to return paths with locale prefix (see models.py).
62598fa1cc0a2c111447ae54
class eICUSubsampleUnobs(eICUSubsampleObs): <NEW_LINE> <INDENT> def __init__(self, hparams, args): <NEW_LINE> <INDENT> eicuConstants.static_cat_features.remove('gender') <NEW_LINE> super().__init__(hparams, args)
Hyperparameters: subsample_g1_mean subsample_g2_mean subsample_g1_dist subsample_g2_dist
62598fa1cc0a2c111447ae55
class SumField(AggregateField): <NEW_LINE> <INDENT> function_name = 'Sum'
Summation aggregation
62598fa1e76e3b2f99fd887e
class ClearAllTransforms(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "pose.clearall" <NEW_LINE> bl_label = "Clear Transforms" <NEW_LINE> def execute(self,context): <NEW_LINE> <INDENT> for object in bpy.data.objects: <NEW_LINE> <INDENT> if object.type == 'ARMATURE': <NEW_LINE> <INDENT> bpy.ops.pose.rot_clear() <NEW_LINE> bpy.ops.pose.loc_clear() <NEW_LINE> bpy.ops.pose.scale_clear() <NEW_LINE> <DEDENT> <DEDENT> return{'FINISHED'}
Clears all transforms on the bone I hope
62598fa11f037a2d8b9e3f2f
class TestGetBoolEnv: <NEW_LINE> <INDENT> envar_name = "TEST_VAR" <NEW_LINE> @pytest.mark.parametrize( "environment_value", [ "1", "TRUE", "true", "YES", "yes", ], ) <NEW_LINE> def test_trythy_bools(self, monkeypatch, environment_value): <NEW_LINE> <INDENT> monkeypatch.setenv(self.envar_name, environment_value) <NEW_LINE> assert get_bool_env(self.envar_name, False) is True <NEW_LINE> <DEDENT> @pytest.mark.parametrize( "environment_value", [ "0", "FALSE", "false", "NO", "no", ], ) <NEW_LINE> def test_falsy_bools(self, monkeypatch, environment_value): <NEW_LINE> <INDENT> monkeypatch.setenv(self.envar_name, environment_value) <NEW_LINE> assert get_bool_env(self.envar_name, False) is False <NEW_LINE> <DEDENT> @pytest.mark.parametrize( "environment_value", [ "11", "junk", ], ) <NEW_LINE> def test_invalid(self, monkeypatch, environment_value): <NEW_LINE> <INDENT> monkeypatch.setenv(self.envar_name, environment_value) <NEW_LINE> with pytest.raises(ValueError): <NEW_LINE> <INDENT> get_bool_env(self.envar_name) <NEW_LINE> <DEDENT> <DEDENT> def test_defaults( self, ): <NEW_LINE> <INDENT> assert get_bool_env("NOT_EXISTING", True) is True, "Tried setting default to True" <NEW_LINE> assert ( get_bool_env("NOT_EXISTING", False) is False ), "Tried setting default to False" <NEW_LINE> assert ( get_bool_env("NOT_EXISTING") is False ), "Using default default, which should be False"
Test get_bool_env
62598fa107f4c71912baf28b
class test_lp_1282584(TransactionCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(test_lp_1282584, self).setUp() <NEW_LINE> self.wizardmakepicking = self.env['claim_make_picking.wizard'] <NEW_LINE> claimline_obj = self.env['claim.line'] <NEW_LINE> claim_obj = self.env['crm.claim'] <NEW_LINE> self.product_id = self.env.ref('product.product_product_4') <NEW_LINE> self.partner_id = self.env.ref('base.res_partner_12') <NEW_LINE> self.claim_id = claim_obj.create( { 'name': 'TEST CLAIM', 'number': 'TEST CLAIM', 'claim_type': self.env.ref('crm_claim_rma_config.' 'crm_claim_type_customer').id, 'delivery_address_id': self.partner_id.id, }) <NEW_LINE> self.warehouse_id = self.claim_id.warehouse_id <NEW_LINE> self.claim_line_id = claimline_obj.create( { 'name': 'TEST CLAIM LINE', 'claim_origine': 'none', 'product_id': self.product_id.id, 'claim_id': self.claim_id.id, 'location_dest_id': self.warehouse_id.lot_stock_id.id }) <NEW_LINE> <DEDENT> def test_00(self): <NEW_LINE> <INDENT> wiz_context = { 'active_id': self.claim_id.id, 'partner_id': self.partner_id.id, 'warehouse_id': self.warehouse_id.id, 'picking_type': self.warehouse_id.rma_in_type_id.id, } <NEW_LINE> wizard_id = self.wizardmakepicking.with_context(wiz_context).create({}) <NEW_LINE> res = wizard_id.action_create_picking() <NEW_LINE> self.assertEquals(res.get('res_model'), 'stock.picking', "Wrong model defined") <NEW_LINE> <DEDENT> def test_01(self): <NEW_LINE> <INDENT> wizardchangeproductqty = self.env['stock.change.product.qty'] <NEW_LINE> wiz_context = {'active_id': self.product_id} <NEW_LINE> wizard_chg_qty_id = wizardchangeproductqty.create({ 'product_id': self.product_id.id, 'new_quantity': 12}) <NEW_LINE> wizard_chg_qty_id.with_context(wiz_context).change_product_qty() <NEW_LINE> wiz_context = { 'active_id': self.claim_id.id, 'partner_id': self.partner_id.id, 'warehouse_id': self.warehouse_id.id, 'picking_type': self.warehouse_id.rma_out_type_id.id, } <NEW_LINE> wizard_id = self.wizardmakepicking.with_context(wiz_context).create({}) <NEW_LINE> res = wizard_id.action_create_picking() <NEW_LINE> self.assertEquals(res.get('res_model'), 'stock.picking', "Wrong model defined")
Test wizard open the right type of view The wizard can generate picking.in and picking.out Let's ensure it open the right view for each picking type
62598fa17047854f4633f21e
class VeranstaltungBasisdatenForm(forms.ModelForm): <NEW_LINE> <INDENT> required_css_class = 'required' <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> veranstalter_queryset = kwargs.pop('all_veranstalter', None) <NEW_LINE> super(VeranstaltungBasisdatenForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['verantwortlich'].queryset = veranstalter_queryset <NEW_LINE> self.fields['ergebnis_empfaenger'].queryset = veranstalter_queryset <NEW_LINE> self.fields['anzahl'] = forms.IntegerField(min_value=1) <NEW_LINE> years_tuple = kwargs['instance'].semester.auswertungstermin_years() <NEW_LINE> self.fields['auswertungstermin'].widget = extras.SelectDateWidget(years=years_tuple) <NEW_LINE> if kwargs['instance'].typ not in ['se', 'pr']: <NEW_LINE> <INDENT> del self.fields['auswertungstermin'] <NEW_LINE> <DEDENT> vltypes = ['vu', 'v'] <NEW_LINE> if kwargs['instance'].typ not in vltypes: <NEW_LINE> <INDENT> del self.fields['typ'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> choices = [] <NEW_LINE> for cur in self.fields['typ'].choices: <NEW_LINE> <INDENT> if cur[0] in vltypes: <NEW_LINE> <INDENT> choices.append(cur) <NEW_LINE> <DEDENT> <DEDENT> self.fields['typ'].choices = choices <NEW_LINE> <DEDENT> for k, field in self.fields.items(): <NEW_LINE> <INDENT> field.required = True <NEW_LINE> <DEDENT> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Veranstaltung <NEW_LINE> fields = ('typ', 'anzahl', 'sprache', 'verantwortlich', 'ergebnis_empfaenger', 'auswertungstermin') <NEW_LINE> widgets = {'ergebnis_empfaenger': forms.CheckboxSelectMultiple, 'auswertungstermin': forms.SelectDateWidget}
Definiert die Form für den 2. Schritt des Wizards.
62598fa1462c4b4f79dbb853
class ModifyApplicationVisualizationRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ApplicationId = None <NEW_LINE> self.BasicConfig = None <NEW_LINE> self.Volumes = None <NEW_LINE> self.InitContainers = None <NEW_LINE> self.Containers = None <NEW_LINE> self.Service = None <NEW_LINE> self.Job = None <NEW_LINE> self.CronJob = None <NEW_LINE> self.RestartPolicy = None <NEW_LINE> self.ImagePullSecrets = None <NEW_LINE> self.HorizontalPodAutoscaler = None <NEW_LINE> self.InitContainer = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ApplicationId = params.get("ApplicationId") <NEW_LINE> if params.get("BasicConfig") is not None: <NEW_LINE> <INDENT> self.BasicConfig = ApplicationBasicConfig() <NEW_LINE> self.BasicConfig._deserialize(params.get("BasicConfig")) <NEW_LINE> <DEDENT> if params.get("Volumes") is not None: <NEW_LINE> <INDENT> self.Volumes = [] <NEW_LINE> for item in params.get("Volumes"): <NEW_LINE> <INDENT> obj = Volume() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Volumes.append(obj) <NEW_LINE> <DEDENT> <DEDENT> if params.get("InitContainers") is not None: <NEW_LINE> <INDENT> self.InitContainers = [] <NEW_LINE> for item in params.get("InitContainers"): <NEW_LINE> <INDENT> obj = Container() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.InitContainers.append(obj) <NEW_LINE> <DEDENT> <DEDENT> if params.get("Containers") is not None: <NEW_LINE> <INDENT> self.Containers = [] <NEW_LINE> for item in params.get("Containers"): <NEW_LINE> <INDENT> obj = Container() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Containers.append(obj) <NEW_LINE> <DEDENT> <DEDENT> if params.get("Service") is not None: <NEW_LINE> <INDENT> self.Service = Service() <NEW_LINE> self.Service._deserialize(params.get("Service")) <NEW_LINE> <DEDENT> if params.get("Job") is not None: <NEW_LINE> <INDENT> self.Job = Job() <NEW_LINE> self.Job._deserialize(params.get("Job")) <NEW_LINE> <DEDENT> if params.get("CronJob") is not None: <NEW_LINE> <INDENT> self.CronJob = CronJob() <NEW_LINE> self.CronJob._deserialize(params.get("CronJob")) <NEW_LINE> <DEDENT> self.RestartPolicy = params.get("RestartPolicy") <NEW_LINE> self.ImagePullSecrets = params.get("ImagePullSecrets") <NEW_LINE> if params.get("HorizontalPodAutoscaler") is not None: <NEW_LINE> <INDENT> self.HorizontalPodAutoscaler = HorizontalPodAutoscaler() <NEW_LINE> self.HorizontalPodAutoscaler._deserialize(params.get("HorizontalPodAutoscaler")) <NEW_LINE> <DEDENT> if params.get("InitContainer") is not None: <NEW_LINE> <INDENT> self.InitContainer = Container() <NEW_LINE> self.InitContainer._deserialize(params.get("InitContainer")) <NEW_LINE> <DEDENT> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
ModifyApplicationVisualization请求参数结构体
62598fa124f1403a926857d6
class WebinarComponent(base.BaseComponent): <NEW_LINE> <INDENT> def list(self, **kwargs): <NEW_LINE> <INDENT> util.require_keys(kwargs, 'host_id') <NEW_LINE> if kwargs.get('start_time'): <NEW_LINE> <INDENT> kwargs['start_time'] = util.date_to_str(kwargs['start_time']) <NEW_LINE> <DEDENT> return self.post_request("/webinar/list", params=kwargs) <NEW_LINE> <DEDENT> def upcoming(self, **kwargs): <NEW_LINE> <INDENT> util.require_keys(kwargs, 'host_id') <NEW_LINE> if kwargs.get('start_time'): <NEW_LINE> <INDENT> kwargs['start_time'] = util.date_to_str(kwargs['start_time']) <NEW_LINE> <DEDENT> return self.post_request("/webinar/list/registration", params=kwargs) <NEW_LINE> <DEDENT> def create(self, **kwargs): <NEW_LINE> <INDENT> util.require_keys(kwargs, ['host_id', 'topic']) <NEW_LINE> if kwargs.get('start_time'): <NEW_LINE> <INDENT> kwargs['start_time'] = util.date_to_str(kwargs['start_time']) <NEW_LINE> <DEDENT> return self.post_request("/webinar/create", params=kwargs) <NEW_LINE> <DEDENT> def update(self, **kwargs): <NEW_LINE> <INDENT> util.require_keys(kwargs, ['id', 'host_id']) <NEW_LINE> if kwargs.get('start_time'): <NEW_LINE> <INDENT> kwargs['start_time'] = util.date_to_str(kwargs['start_time']) <NEW_LINE> <DEDENT> return self.post_request("/webinar/update", params=kwargs) <NEW_LINE> <DEDENT> def delete(self, **kwargs): <NEW_LINE> <INDENT> util.require_keys(kwargs, ['id', 'host_id']) <NEW_LINE> return self.post_request("/webinar/delete", params=kwargs) <NEW_LINE> <DEDENT> def end(self, **kwargs): <NEW_LINE> <INDENT> util.require_keys(kwargs, ['id', 'host_id']) <NEW_LINE> return self.post_request("/webinar/end", params=kwargs) <NEW_LINE> <DEDENT> def get(self, **kwargs): <NEW_LINE> <INDENT> util.require_keys(kwargs, ['id', 'host_id']) <NEW_LINE> return self.post_request("/webinar/get", params=kwargs) <NEW_LINE> <DEDENT> def register(self, **kwargs): <NEW_LINE> <INDENT> util.require_keys(kwargs, ['id', 'email', 'first_name', 'last_name']) <NEW_LINE> if kwargs.get('start_time'): <NEW_LINE> <INDENT> kwargs['start_time'] = util.date_to_str(kwargs['start_time']) <NEW_LINE> <DEDENT> return self.post_request("/webinar/register", params=kwargs)
Component dealing with all webinar related matters
62598fa1498bea3a75a57968
class SValueModel: <NEW_LINE> <INDENT> def compute_outlier_scores(self, frequencies): <NEW_LINE> <INDENT> if (len(frequencies.keys()) < 2): <NEW_LINE> <INDENT> raise Exception("There must be at least 2 aggregation units.") <NEW_LINE> <DEDENT> rng = frequencies[frequencies.keys()[0]].keys() <NEW_LINE> normalized_frequencies = {} <NEW_LINE> for j in frequencies.keys(): <NEW_LINE> <INDENT> normalized_frequencies[j] = _normalize_counts(frequencies[j]) <NEW_LINE> <DEDENT> medians = {} <NEW_LINE> for r in rng: <NEW_LINE> <INDENT> medians[r] = np.median([normalized_frequencies[j][r] for j in normalized_frequencies.keys()]) <NEW_LINE> <DEDENT> outlier_values = {} <NEW_LINE> for j in frequencies.keys(): <NEW_LINE> <INDENT> outlier_values[j] = 0 <NEW_LINE> for r in rng: <NEW_LINE> <INDENT> outlier_values[j] += abs(normalized_frequencies[j][r] - medians[r]) <NEW_LINE> <DEDENT> <DEDENT> return self._normalize(outlier_values) <NEW_LINE> <DEDENT> def _normalize(self, value_dict): <NEW_LINE> <INDENT> median = np.median([value_dict[i] for i in value_dict.keys()]) <NEW_LINE> n = len(value_dict.keys()) <NEW_LINE> if median < 1.0 / float(n): <NEW_LINE> <INDENT> divisor = 1.0 / float(n) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> divisor = median <NEW_LINE> <DEDENT> return_dict = {} <NEW_LINE> for i in value_dict.keys(): <NEW_LINE> <INDENT> return_dict[i] = float(value_dict[i]) / float(divisor) <NEW_LINE> <DEDENT> return return_dict
Model implementing SVA.
62598fa13539df3088ecc0fc
class Encounter(models.Model): <NEW_LINE> <INDENT> patient = models.ForeignKey(Patient) <NEW_LINE> start_date = models.DateTimeField() <NEW_LINE> end_date = models.DateTimeField(blank=True, null=True) <NEW_LINE> status = models.ForeignKey(EncounterStatus) <NEW_LINE> notes = models.TextField("Special Notes", blank=True, max_length=500) <NEW_LINE> date_created = models.DateTimeField(auto_now_add=True, null=True) <NEW_LINE> last_modified = models.DateTimeField(auto_now = True, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{} - {}: {}".format(self.patient, self.start_date, self.status)
The actual encounter, when a patient meets a practitioner or visits a service provider/point of care
62598fa12c8b7c6e89bd360e
class HDCASummary(HistoryItemCommon): <NEW_LINE> <INDENT> model_class: str = ModelClassField(HDCA_MODEL_CLASS_NAME) <NEW_LINE> type: str = Field( "collection", const=True, title="Type", description="This is always `collection` for dataset collections.", ) <NEW_LINE> collection_type: str = CollectionTypeField <NEW_LINE> populated_state: DatasetCollection.populated_states = PopulatedStateField <NEW_LINE> populated_state_message: Optional[str] = PopulatedStateMessageField <NEW_LINE> element_count: Optional[int] = ElementCountField <NEW_LINE> job_source_id: Optional[EncodedDatabaseIdField] = Field( None, title="Job Source ID", description="The encoded ID of the Job that produced this dataset collection. Used to track the state of the job.", ) <NEW_LINE> job_source_type: Optional[JobSourceType] = Field( None, title="Job Source Type", description="The type of job (model class) that produced this dataset collection. Used to track the state of the job.", ) <NEW_LINE> contents_url: AnyUrl = Field( ..., title="Contents URL", description="The relative URL to access the contents of this dataset collection.", )
History Dataset Collection Association summary information.
62598fa1bd1bec0571e14fe7
class Queue(): <NEW_LINE> <INDENT> def __init__(self,value=None,next_node=None): <NEW_LINE> <INDENT> if value == None and next_node == None: <NEW_LINE> <INDENT> self.tail = None <NEW_LINE> self.size = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.tail = Node(value,next_node) <NEW_LINE> self.size = 1 <NEW_LINE> <DEDENT> <DEDENT> def add(self,value): <NEW_LINE> <INDENT> n = Node(value) <NEW_LINE> n.next = self.tail <NEW_LINE> self.tail = n <NEW_LINE> self.size += 1 <NEW_LINE> <DEDENT> def remove(self, current=''): <NEW_LINE> <INDENT> if current == '': <NEW_LINE> <INDENT> current = self.tail <NEW_LINE> <DEDENT> if current.next: <NEW_LINE> <INDENT> if current.next.next: <NEW_LINE> <INDENT> current = current.next <NEW_LINE> return self.remove(current) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n = current.next.value <NEW_LINE> current.next = None <NEW_LINE> self.size -= 1 <NEW_LINE> return n <NEW_LINE> <DEDENT> <DEDENT> elif current == self.tail: <NEW_LINE> <INDENT> if current.value: <NEW_LINE> <INDENT> n = current.value <NEW_LINE> current = None <NEW_LINE> self.size -= 1 <NEW_LINE> return n <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Queue is already empty." <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("mind boggling coding error...") <NEW_LINE> <DEDENT> <DEDENT> def check_size(self): <NEW_LINE> <INDENT> return self.size <NEW_LINE> <DEDENT> def show_all(self, current=''): <NEW_LINE> <INDENT> if current == '': <NEW_LINE> <INDENT> current = self.tail <NEW_LINE> <DEDENT> if current: <NEW_LINE> <INDENT> if type(current) == int or type(current) == str: <NEW_LINE> <INDENT> print(current.value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(current.value.value) <NEW_LINE> <DEDENT> if current.next: <NEW_LINE> <INDENT> return self.show_all(current.next) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print("Empty queue.")
This is the best working version I can come up with so far that is both my style and 100% working. I would ideally like the remove() method to be recursive, and I would like to fully understand the issues with my earlier attempts at Stacks/Queues. Another interesting approach with Queues specifically is to have variables for both the front and back of the queue. Instead of having to traverse fom one end to the other when adding or removing, you can quickly start at that end by having two class variables or instance variables of a queue w/ node objects.
62598fa1442bda511e95c2a2
class RandomFlipTopBottom(HybridBlock): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(RandomFlipTopBottom, self).__init__() <NEW_LINE> <DEDENT> def hybrid_forward(self, F, x): <NEW_LINE> <INDENT> if is_np_array(): <NEW_LINE> <INDENT> F = F.npx <NEW_LINE> <DEDENT> return F.image.random_flip_top_bottom(x)
Randomly flip the input image top to bottom with a probability of 0.5. Inputs: - **data**: input tensor with (H x W x C) shape. Outputs: - **out**: output tensor with same shape as `data`.
62598fa1baa26c4b54d4f0f7
class FakePartnerFormProtectedFields(models.AbstractModel): <NEW_LINE> <INDENT> _name = 'cms.form.protected.fields' <NEW_LINE> _inherit = 'cms.form' <NEW_LINE> _form_fields_order = ['ihaveagroup', 'nogroup'] <NEW_LINE> nogroup = fields.Char() <NEW_LINE> ihaveagroup = fields.Char(groups='website.group_website_designer')
A test model form w/ `groups` protected fields.
62598fa17d43ff2487427326
class CConverter(Converter): <NEW_LINE> <INDENT> def __init__(self, code, *args): <NEW_LINE> <INDENT> super().__init__(code) <NEW_LINE> self.output = ["#include <stdio.h>\n", "int main(void) {", " int index = 0;", " static char array[30000];"] <NEW_LINE> self.op["add"] = "array[index] += {};" <NEW_LINE> self.op["sub"] = "array[index] -= {};" <NEW_LINE> self.op["left"] = "index -= {};" <NEW_LINE> self.op["right"] = "index += {};" <NEW_LINE> self.op["out"] = "putchar(array[index]);" <NEW_LINE> self.op["in"] = "array[index] = getchar();" <NEW_LINE> self.op["loop_begin"] = "while (array[index] != 0) {" <NEW_LINE> self.op["loop_end"] = "}" <NEW_LINE> self.op["zero"] = "array[index] = 0;" <NEW_LINE> self.op["final"] = "}\n" <NEW_LINE> self.extension = "c" <NEW_LINE> self.status["spaces"] = " " * 4
C code converter class
62598fa13cc13d1c6d4655b4
class Task(BaseItem, Tagged, Commented, TaskStateMixin, Owned, Meta, Base): <NEW_LINE> <INDENT> __tablename__ = 'tasks' <NEW_LINE> _modul_id = 1000 <NEW_LINE> id = sa.Column(sa.Integer, primary_key=True) <NEW_LINE> name = sa.Column('name', sa.Text, nullable=False, server_default="") <NEW_LINE> description = sa.Column('description', sa.Text, nullable=False, server_default="") <NEW_LINE> priority = sa.Column('priority', sa.Integer) <NEW_LINE> severity = sa.Column('severity', sa.Integer) <NEW_LINE> resolution = sa.Column('resolution', sa.Integer) <NEW_LINE> estimate = sa.Column('estimate', sa.Integer) <NEW_LINE> assignee_id = sa.Column('assignee_id', sa.Integer, sa.ForeignKey("users.id")) <NEW_LINE> assignee = sa.orm.relationship("User", primaryjoin="User.id==Task.assignee_id", backref="tasks") <NEW_LINE> nosy = sa.orm.relationship("User", secondary="nm_task_users") <NEW_LINE> sprints = sa.orm.relationship("Sprint", secondary="nm_task_sprints", backref="tasks") <NEW_LINE> @property <NEW_LINE> def weight(self): <NEW_LINE> <INDENT> if not self.priority or not self.severity: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> calc_p = {"6": 1000, "5": 100, "4": 75, "3": 50, "2": 25, "1": 1} <NEW_LINE> calc_s = {"6": 100, "5": 85, "4": 70, "3": 50, "2": 35, "1": 20} <NEW_LINE> p = float(calc_p[str(self.priority)]) <NEW_LINE> s = calc_s[str(self.severity)]/100.0 <NEW_LINE> return int(p*s)
A task is a general container for all kind of tasks, defects, feature requests or any other issue in your product.
62598fa199cbb53fe6830d1b
class KeyReferenceToPersistent(object): <NEW_LINE> <INDENT> zope.interface.implements(zope.app.keyreference.interfaces.IKeyReference) <NEW_LINE> key_type_id = 'zope.app.keyreference.persistent' <NEW_LINE> def __init__(self, object): <NEW_LINE> <INDENT> if not getattr(object, '_p_oid', None): <NEW_LINE> <INDENT> connection = IConnection(object, None) <NEW_LINE> if connection is None: <NEW_LINE> <INDENT> raise zope.app.keyreference.interfaces.NotYet(object) <NEW_LINE> <DEDENT> connection.add(object) <NEW_LINE> <DEDENT> self.object = object <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return self.object <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.object._p_jar.db().database_name, self.object._p_oid, )) <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> if self.key_type_id == other.key_type_id: <NEW_LINE> <INDENT> return cmp( (self.object._p_jar.db().database_name, self.object._p_oid), (other.object._p_jar.db().database_name, other.object._p_oid), ) <NEW_LINE> <DEDENT> return cmp(self.key_type_id, other.key_type_id)
An IReference for persistent object which is comparable. These references compare by _p_oids of the objects they reference.
62598fa1379a373c97d98e5e
class ModelTestListView(generics.ListAPIView): <NEW_LINE> <INDENT> queryset = Test.objects.all() <NEW_LINE> serializer_class = ModelTestSerializer
测试列表
62598fa18e7ae83300ee8ee8
class SAM_generators(th.nn.Module): <NEW_LINE> <INDENT> def __init__(self, data_shape, cat_embedding, zero_components, nh=None, batch_size=-1, **kwargs): <NEW_LINE> <INDENT> super(SAM_generators, self).__init__() <NEW_LINE> if batch_size == -1: <NEW_LINE> <INDENT> batch_size = data_shape[0] <NEW_LINE> <DEDENT> gpu = kwargs.get('gpu', False) <NEW_LINE> gpu_no = kwargs.get('gpu_no', 0) <NEW_LINE> rows, self.cols = data_shape <NEW_LINE> self.noise = [Variable(th.FloatTensor(batch_size, 1)) for i in range(self.cols)] <NEW_LINE> if gpu: <NEW_LINE> <INDENT> self.noise = [i.cuda(gpu_no) for i in self.noise] <NEW_LINE> <DEDENT> self.blocks = th.nn.ModuleList() <NEW_LINE> for i in range(self.cols): <NEW_LINE> <INDENT> self.blocks.append(SAM_block( [sum(cat_embedding) + 1, nh, cat_embedding[i]], cat_embedding, zero_components[i], **kwargs)) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> for i in self.noise: <NEW_LINE> <INDENT> i.data.normal_() <NEW_LINE> <DEDENT> self.generated_variables = [self.blocks[i]( th.cat([x, self.noise[i]], 1)) for i in range(self.cols)] <NEW_LINE> return self.generated_variables
Ensemble of all the generators.
62598fa197e22403b383ad55
class TomoReconsDialog(qt.QDialog): <NEW_LINE> <INDENT> class SinogramHasMultipleRoleInfoMessage(qt.QMessageBox): <NEW_LINE> <INDENT> def __init__(self, sinoName, roles): <NEW_LINE> <INDENT> qt.QMessageBox.__init__(self) <NEW_LINE> self.setIcon(qt.QMessageBox.Warning) <NEW_LINE> self.setText('Multiple role for a sinogram') <NEW_LINE> self.setInformativeText( 'The sinogram %s is used in multiple roles (%s).' 'This seems like an incorrect selection and might bring' 'incoherent reconstruction. Continue ?' %(str(sinoName), "; ".join(roles))) <NEW_LINE> self.yesButton = self.addButton(qt.QMessageBox.Ignore) <NEW_LINE> self.noButton = self.addButton(qt.QMessageBox.Cancel) <NEW_LINE> <DEDENT> <DEDENT> def __init__(self, parent=None, entries=None): <NEW_LINE> <INDENT> qt.QDialog.__init__(self, parent) <NEW_LINE> self.setWindowTitle('Sinogram selection for reconstruction') <NEW_LINE> self.mainWidget = TomoRecons(parent=self, entries=entries) <NEW_LINE> types = qt.QDialogButtonBox.Ok | qt.QDialogButtonBox.Cancel <NEW_LINE> _buttons = qt.QDialogButtonBox(parent=self) <NEW_LINE> _buttons.setStandardButtons(types) <NEW_LINE> _buttons.button(qt.QDialogButtonBox.Ok).clicked.connect( self._okTriggered) <NEW_LINE> _buttons.button(qt.QDialogButtonBox.Cancel).clicked.connect( self.reject) <NEW_LINE> self.setLayout(qt.QVBoxLayout()) <NEW_LINE> self.layout().addWidget(self.mainWidget) <NEW_LINE> self.layout().addWidget(_buttons) <NEW_LINE> <DEDENT> def getReconstructionType(self): <NEW_LINE> <INDENT> return self.mainWidget.getReconsType() <NEW_LINE> <DEDENT> def getSinogramsToRecons(self): <NEW_LINE> <INDENT> return self.mainWidget.getSinogramsToRecons() <NEW_LINE> <DEDENT> def getIt(self): <NEW_LINE> <INDENT> return self.mainWidget.getIt() <NEW_LINE> <DEDENT> def hasIt(self): <NEW_LINE> <INDENT> return self.getIt() is not None <NEW_LINE> <DEDENT> def getI0(self): <NEW_LINE> <INDENT> return self.mainWidget.getI0() <NEW_LINE> <DEDENT> def hasI0(self): <NEW_LINE> <INDENT> return self.mainWidget.getI0() is not None <NEW_LINE> <DEDENT> def _okTriggered(self): <NEW_LINE> <INDENT> if self.checkMultipleRole(): <NEW_LINE> <INDENT> self.accept() <NEW_LINE> <DEDENT> <DEDENT> def checkMultipleRole(self): <NEW_LINE> <INDENT> mSelections = self.mainWidget.getMultipleRole() <NEW_LINE> if mSelections is not None: <NEW_LINE> <INDENT> name = list(mSelections.keys())[0] <NEW_LINE> diag = self.SinogramHasMultipleRoleInfoMessage(sinoName=name, roles=mSelections[name]) <NEW_LINE> if diag.exec_(): <NEW_LINE> <INDENT> return diag.result() == qt.QDialogButtonBox.Ignore <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Dialog to validate the sinogram selection for tomogui reconstruction
62598fa116aa5153ce400348
class NoDifferenceError(Exception): <NEW_LINE> <INDENT> pass
This exception represents a case where schoology returns a String with the API and makes it easier to tell what went wrong.
62598fa13539df3088ecc0fd
class RKknn(RPackage): <NEW_LINE> <INDENT> homepage = "https://cloud.r-project.org/package=kknn" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/kknn_1.3.1.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/kknn" <NEW_LINE> version('1.3.1', sha256='22840e70ec2afa40371e274b583634c8f6d27149a87253ee411747d5db78f3db') <NEW_LINE> depends_on('r@2.10:', type=('build', 'run')) <NEW_LINE> depends_on('r-igraph@1.0:', type=('build', 'run')) <NEW_LINE> depends_on('r-matrix', type=('build', 'run'))
Weighted k-Nearest Neighbors for Classification, Regression and Clustering.
62598fa1adb09d7d5dc0a3d3
class InstrumentDriver(WorkhorseInstrumentDriver): <NEW_LINE> <INDENT> def __init__(self, evt_callback): <NEW_LINE> <INDENT> WorkhorseInstrumentDriver.__init__(self, evt_callback) <NEW_LINE> <DEDENT> def _build_protocol(self): <NEW_LINE> <INDENT> self._protocol = Protocol(Prompt, NEWLINE, self._driver_event) <NEW_LINE> log.debug("self._protocol = " + repr(self._protocol))
Specialization for this version of the workhorse ADCP driver
62598fa166673b3332c3020f
class Cinematics(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.scenes = [] <NEW_LINE> <DEDENT> def addScene(self, scene): <NEW_LINE> <INDENT> scenes.append(scence)
Cinématique : séquence de scènes
62598fa1e5267d203ee6b756
@unittest.skipUnless(hasattr(signal, "setitimer"), "requires setitimer()") <NEW_LINE> class SignalEINTRTest(EINTRBaseTest): <NEW_LINE> <INDENT> @unittest.skipUnless(hasattr(signal, 'sigtimedwait'), 'need signal.sigtimedwait()') <NEW_LINE> def test_sigtimedwait(self): <NEW_LINE> <INDENT> t0 = time.monotonic() <NEW_LINE> signal.sigtimedwait([signal.SIGUSR1], self.sleep_time) <NEW_LINE> dt = time.monotonic() - t0 <NEW_LINE> if sys.platform.startswith('aix'): <NEW_LINE> <INDENT> self.assertGreaterEqual(dt, self.sleep_time * 0.9) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertGreaterEqual(dt, self.sleep_time) <NEW_LINE> <DEDENT> <DEDENT> @unittest.skipUnless(hasattr(signal, 'sigwaitinfo'), 'need signal.sigwaitinfo()') <NEW_LINE> def test_sigwaitinfo(self): <NEW_LINE> <INDENT> self.sleep_time = 0.100 <NEW_LINE> signum = signal.SIGUSR1 <NEW_LINE> pid = os.getpid() <NEW_LINE> old_handler = signal.signal(signum, lambda *args: None) <NEW_LINE> self.addCleanup(signal.signal, signum, old_handler) <NEW_LINE> rpipe, wpipe = os.pipe() <NEW_LINE> code = '\n'.join(( 'import os, time', 'pid = %s' % os.getpid(), 'signum = %s' % int(signum), 'sleep_time = %r' % self.sleep_time, 'rpipe = %r' % rpipe, 'os.read(rpipe, 1)', 'os.close(rpipe)', 'time.sleep(sleep_time)', 'os.kill(pid, signum)', )) <NEW_LINE> t0 = time.monotonic() <NEW_LINE> proc = self.subprocess(code, pass_fds=(rpipe,)) <NEW_LINE> os.close(rpipe) <NEW_LINE> with kill_on_error(proc): <NEW_LINE> <INDENT> os.write(wpipe, b'x') <NEW_LINE> os.close(wpipe) <NEW_LINE> signal.sigwaitinfo([signum]) <NEW_LINE> dt = time.monotonic() - t0 <NEW_LINE> self.assertEqual(proc.wait(), 0) <NEW_LINE> <DEDENT> self.assertGreaterEqual(dt, self.sleep_time)
EINTR tests for the signal module.
62598fa10a50d4780f705223
class STUDIO_INIT_FLAGS(Flag): <NEW_LINE> <INDENT> NORMAL = 0x0 <NEW_LINE> LIVEUPDATE = 0x00000001 <NEW_LINE> ALLOW_MISSING_PLUGINS = 0x00000002 <NEW_LINE> SYNCHRONOUS_UPDATE = 0x00000004 <NEW_LINE> DEFERRED_CALLBACKS = 0x00000008 <NEW_LINE> LOAD_FROM_UPDATE = 0x00000010
Studio System initialization flags. The zero flag is called "NORMAL". :cvar int LIVEUPDATE: Enable live update. :cvar int ALLOW_MISSING_PLUGINS: Load banks even if they reference plugins that have not been loaded. :cvar int SYNCHRONOUS_UPDATE: Disable asynchronous processing and perform all processing on the calling thread instead. DEFERRED_CALLBACKS: Defer timeline callbacks until the main update. :cvar int LOAD_FROM_UPDATE: No additional threads are created for bank and resource loading.
62598fa1cc0a2c111447ae57
class PublicAPITests(TestCase): <NEW_LINE> <INDENT> def test_addDestination(self): <NEW_LINE> <INDENT> o = object() <NEW_LINE> eliot.addDestination(o) <NEW_LINE> self.addCleanup(eliot.removeDestination, o) <NEW_LINE> self.assertIn(o, Logger._destinations._destinations) <NEW_LINE> <DEDENT> def test_removeDestination(self): <NEW_LINE> <INDENT> self.assertEqual(eliot.removeDestination, Logger._destinations.remove) <NEW_LINE> <DEDENT> def test_addGlobalFields(self): <NEW_LINE> <INDENT> self.assertEqual(eliot.addGlobalFields, Logger._destinations.addGlobalFields)
Tests for the public API.
62598fa13eb6a72ae038a48c
class RedditShredderForm(forms.Form): <NEW_LINE> <INDENT> account = forms.ModelChoiceField(queryset=RedditAccounts.objects.none(), label=_('Select an Account'), required=False, widget=forms.Select({ 'class': 'form-control', })) <NEW_LINE> def __init__(self, user_id, *args, **kwargs): <NEW_LINE> <INDENT> super(RedditShredderForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['account'].queryset = RedditAccounts.objects.filter( user_id=user_id).values_list('reddit_user_name', flat=True) <NEW_LINE> <DEDENT> keep = forms.IntegerField(label=_('Time delay in hours'), initial=0, widget=forms.NumberInput({ 'class': 'form-control', 'placeholder': 'Time Delay in Hours' })) <NEW_LINE> karma_limit = forms.IntegerField(label=_('Karma Threshold'), initial=1, widget=forms.NumberInput({ 'class': 'form-control', 'placeholder': 'Karma Threshold', })) <NEW_LINE> delete_everything = forms.BooleanField(label=_('Delete Everything?'), required=False, widget=forms.CheckboxInput({ 'class': 'form-control' }))
Receives the user's preferences for the manual shredder.
62598fa18a43f66fc4bf1fc5
class ProductQuestionSamerel(Base): <NEW_LINE> <INDENT> __tablename__ = "em_product_question_same_rel" <NEW_LINE> id = Column(Integer, primary_key=True, autoincrement=True) <NEW_LINE> question = Column(VARCHAR(255), nullable=False, comment="问题内容") <NEW_LINE> qid = Column(Integer, ForeignKey("em_product_question.id"), comment="相同问答的记录编号") <NEW_LINE> create_tm = Column(DateTime, default=datetime.now(), comment="相似问题创建时间") <NEW_LINE> uid = Column(Integer, comment="创建者编号") <NEW_LINE> question_item = relationship("ProductQuestion", backref="samequestions") <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<<ProductQuestionSamerel>: {_q}".format(_q=self.question)
问答知识的相同问题
62598fa199cbb53fe6830d1c
class CnczPush(TCPSocketServer): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CnczPush, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def create_handler(self, con, addr, logger): <NEW_LINE> <INDENT> return CnczPushRHWrapper(con, addr, self, logger) <NEW_LINE> <DEDENT> def _push(self, occ, source): <NEW_LINE> <INDENT> self.state.push_occupation_changes(occ, source)
Listens for notification from C&CZ on port 1235
62598fa1925a0f43d25e7e86
class Session: <NEW_LINE> <INDENT> def __init__(self, user, token_payload, token): <NEW_LINE> <INDENT> self.user = user <NEW_LINE> self.token = token <NEW_LINE> if token_payload: <NEW_LINE> <INDENT> self.expires_at = token_payload["exp"] <NEW_LINE> self.issued_at = token_payload["iat"] <NEW_LINE> self.user_id = token_payload["sub"] <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def ttl(self): <NEW_LINE> <INDENT> if not self.expires_at: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return (self.expires_at - datetime.utcnow()).total_seconds() <NEW_LINE> <DEDENT> @property <NEW_LINE> def user(self): <NEW_LINE> <INDENT> if not self.user_id: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> db = DbSession() <NEW_LINE> user = db.Query(User).filter_by(self.user_id) <NEW_LINE> db.close() <NEW_LINE> return user
A api session
62598fa16e29344779b004a5
class AipImageProcess(AipBase): <NEW_LINE> <INDENT> __imageQualityEnhanceUrl = 'https://aip.baidubce.com/rest/2.0/image-process/v1/image_quality_enhance' <NEW_LINE> __dehazeUrl = 'https://aip.baidubce.com/rest/2.0/image-process/v1/dehaze' <NEW_LINE> __contrastEnhanceUrl = 'https://aip.baidubce.com/rest/2.0/image-process/v1/contrast_enhance' <NEW_LINE> def imageQualityEnhance(self, image, options=None): <NEW_LINE> <INDENT> options = options or {} <NEW_LINE> data = {} <NEW_LINE> data['image'] = base64.b64encode(image).decode() <NEW_LINE> data.update(options) <NEW_LINE> return self._request(self.__imageQualityEnhanceUrl, data) <NEW_LINE> <DEDENT> def dehaze(self, image, options=None): <NEW_LINE> <INDENT> options = options or {} <NEW_LINE> data = {} <NEW_LINE> data['image'] = base64.b64encode(image).decode() <NEW_LINE> data.update(options) <NEW_LINE> return self._request(self.__dehazeUrl, data) <NEW_LINE> <DEDENT> def contrastEnhance(self, image, options=None): <NEW_LINE> <INDENT> options = options or {} <NEW_LINE> data = {} <NEW_LINE> data['image'] = base64.b64encode(image).decode() <NEW_LINE> data.update(options) <NEW_LINE> return self._request(self.__contrastEnhanceUrl, data)
图像处理
62598fa1090684286d5935ff
class AttachmentData(Model): <NEW_LINE> <INDENT> _attribute_map = { "type": {"key": "type", "type": "str"}, "name": {"key": "name", "type": "str"}, "original_base64": {"key": "originalBase64", "type": "bytearray"}, "thumbnail_base64": {"key": "thumbnailBase64", "type": "bytearray"}, } <NEW_LINE> def __init__( self, *, type: str = None, name: str = None, original_base64: bytearray = None, thumbnail_base64: bytearray = None, **kwargs ) -> None: <NEW_LINE> <INDENT> super(AttachmentData, self).__init__(**kwargs) <NEW_LINE> self.type = type <NEW_LINE> self.name = name <NEW_LINE> self.original_base64 = original_base64 <NEW_LINE> self.thumbnail_base64 = thumbnail_base64
Attachment data. :param type: Content-Type of the attachment :type type: str :param name: Name of the attachment :type name: str :param original_base64: Attachment content :type original_base64: bytearray :param thumbnail_base64: Attachment thumbnail :type thumbnail_base64: bytearray
62598fa12c8b7c6e89bd3610
class ForEach(Statement, HasSymbolTable): <NEW_LINE> <INDENT> def __init__(self, pos: Tuple[int, int], name: Name, otype: ObjectType, atom_indices: Optional[Tuple[str, str]], constraints: Constraint, body: List[Statement]) -> None: <NEW_LINE> <INDENT> super().__init__(pos) <NEW_LINE> self.name: Name = name <NEW_LINE> self.type: ObjectType = otype <NEW_LINE> self.atom_indices: Optional[Tuple[str, str]] = atom_indices <NEW_LINE> self.constraints: Constraint = constraints <NEW_LINE> self.body: List[Statement] = body
For each loop
62598fa1e64d504609df92dd
class Model(Transformer, metaclass=ABCMeta): <NEW_LINE> <INDENT> pass
Abstract class for models that are fitted by estimators. A model is an ordinary Transformer except how it is created. While ordinary transformers are defined by specifying the parameters directly, a model is usually generated by an Estimator when Estimator.fit(table_env, table) is invoked. .. versionadded:: 1.11.0
62598fa1dd821e528d6d8d7e