code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class PaginationException(SendbeeException): <NEW_LINE> <INDENT> pass
Handle Pagination Exceptions
6259905330dc7b76659a0d04
class SessionDetails: <NEW_LINE> <INDENT> __slots__ = ( 'realm', 'session', 'authid', 'authrole', 'authmethod', 'authprovider', 'authextra', ) <NEW_LINE> def __init__(self, realm, session, authid=None, authrole=None, authmethod=None, authprovider=None, authextra=None): <NEW_LINE> <INDENT> assert(isinstance(realm, string_types)) <NEW_LINE> assert(type(session) is int) <NEW_LINE> assert(authid is None or isinstance(authid, string_types)) <NEW_LINE> assert(authrole is None or isinstance(authrole, string_types)) <NEW_LINE> assert(authmethod is None or isinstance(authmethod, string_types)) <NEW_LINE> assert(authprovider is None or isinstance(authprovider, string_types)) <NEW_LINE> assert(authextra is None or type(authextra) == dict) <NEW_LINE> self.realm = realm <NEW_LINE> self.session = session <NEW_LINE> self.authid = authid <NEW_LINE> self.authrole = authrole <NEW_LINE> self.authmethod = authmethod <NEW_LINE> self.authprovider = authprovider <NEW_LINE> self.authextra = authextra <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "SessionDetails(realm=<{0}>, session={1}, authid=<{2}>, authrole=<{3}>, authmethod={4}, authprovider={5}, authextra={6})".format(self.realm, self.session, self.authid, self.authrole, self.authmethod, self.authprovider, self.authextra)
Provides details for a WAMP session upon open. .. seealso:: :func:`autobahn.wamp.interfaces.ISession.onJoin`
625990534e4d562566373911
class LabPairIdx: <NEW_LINE> <INDENT> def __init__(self, master, deflist, name, **kw): <NEW_LINE> <INDENT> self.default = kw.get('default') <NEW_LINE> self.hide = kw.get('hide') <NEW_LINE> label = kw.get('label', string.upper(name[:1]) + name[1:]) <NEW_LINE> self.coord = ["", ""] <NEW_LINE> self.label = Tkinter.Label(master, name="label", text=label, width=7, anchor='ne') <NEW_LINE> self.value = Tkinter.Label(master, name="value", width=4, anchor='ne') <NEW_LINE> self.label.pack(side='top', expand=1, fill='both') <NEW_LINE> self.value.pack(side='top', expand=1, fill='both') <NEW_LINE> if kw.get('command') is not None: <NEW_LINE> <INDENT> self.value.bind('<Button-1>', (lambda e, c=kw['command'], n=name: c(n))) <NEW_LINE> bindLabel(self.value) <NEW_LINE> <DEDENT> self.value.bind('<3>', self.goSect) <NEW_LINE> deflist[name+"x"] = (lambda val, db, self=self: self.update(0, val, db)) <NEW_LINE> deflist[name+"y"] = (lambda val, db, self=self: self.update(1, val, db)) <NEW_LINE> <DEDENT> def update(self, pos, val, db): <NEW_LINE> <INDENT> self.coord[pos] = val <NEW_LINE> val = "%s,%s" % (self.coord[0], self.coord[1]) <NEW_LINE> if callable(self.default): <NEW_LINE> <INDENT> val = self.default(val, db) <NEW_LINE> <DEDENT> elif val == self.default or val == ",": <NEW_LINE> <INDENT> val = "" <NEW_LINE> <DEDENT> if ((callable(self.hide) and self.hide(val, db)) or val == self.hide): <NEW_LINE> <INDENT> self.label.pack_forget() <NEW_LINE> self.value.pack_forget() <NEW_LINE> <DEDENT> elif ((callable(self.hide) and self.hide(self.value['text'])) or self.value['text'] == str(self.hide)): <NEW_LINE> <INDENT> self.label.pack(expand=1, fill='both') <NEW_LINE> self.value.pack(expand=1, fill='both') <NEW_LINE> <DEDENT> self.value['text'] = val <NEW_LINE> <DEDENT> def goSect(self, event): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> x, y = self.coord <NEW_LINE> viewer.cen.SetSect((x, x, y, y)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass
Same as LabPair, but take two values and create an x/y index.
625990538da39b475be046f6
class FilterNotes(Filter): <NEW_LINE> <INDENT> def artifact_id(self, operator, artifact_id): <NEW_LINE> <INDENT> self._tql.add_filter('artifactId', operator, artifact_id, TQL.Type.INTEGER) <NEW_LINE> <DEDENT> def author(self, operator, author): <NEW_LINE> <INDENT> self._tql.add_filter('author', operator, author, TQL.Type.STRING) <NEW_LINE> <DEDENT> def case_id(self, operator, case_id): <NEW_LINE> <INDENT> self._tql.add_filter('caseId', operator, case_id, TQL.Type.INTEGER) <NEW_LINE> <DEDENT> def date_added(self, operator, date_added): <NEW_LINE> <INDENT> self._tql.add_filter('dateAdded', operator, date_added, TQL.Type.STRING) <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_artifact(self): <NEW_LINE> <INDENT> from .artifact import FilterArtifacts <NEW_LINE> artifacts = FilterArtifacts(ApiEndpoints.ARTIFACTS, self._tcex, TQL()) <NEW_LINE> self._tql.add_filter('hasArtifact', TQL.Operator.EQ, artifacts, TQL.Type.SUB_QUERY) <NEW_LINE> return artifacts <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_case(self): <NEW_LINE> <INDENT> from .case import FilterCases <NEW_LINE> cases = FilterCases(ApiEndpoints.CASES, self._tcex, TQL()) <NEW_LINE> self._tql.add_filter('hasCase', TQL.Operator.EQ, cases, TQL.Type.SUB_QUERY) <NEW_LINE> return cases <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_task(self): <NEW_LINE> <INDENT> from .task import FilterTasks <NEW_LINE> tasks = FilterTasks(ApiEndpoints.TASKS, self._tcex, TQL()) <NEW_LINE> self._tql.add_filter('hasTask', TQL.Operator.EQ, tasks, TQL.Type.SUB_QUERY) <NEW_LINE> return tasks <NEW_LINE> <DEDENT> def id(self, operator, id): <NEW_LINE> <INDENT> self._tql.add_filter('id', operator, id, TQL.Type.INTEGER) <NEW_LINE> <DEDENT> def last_modified(self, operator, last_modified): <NEW_LINE> <INDENT> self._tql.add_filter('lastModified', operator, last_modified, TQL.Type.STRING) <NEW_LINE> <DEDENT> def summary(self, operator, summary): <NEW_LINE> <INDENT> self._tql.add_filter('summary', operator, summary, TQL.Type.STRING) <NEW_LINE> <DEDENT> def task_id(self, operator, task_id): <NEW_LINE> <INDENT> self._tql.add_filter('taskId', operator, task_id, TQL.Type.INTEGER) <NEW_LINE> <DEDENT> def workflow_event_id(self, operator, workflow_event_id): <NEW_LINE> <INDENT> self._tql.add_filter('workflowEventId', operator, workflow_event_id, TQL.Type.INTEGER)
Filter Object for Notes
625990548e71fb1e983bcfd4
@unique <NEW_LINE> class ControllerState(IntEnum): <NEW_LINE> <INDENT> INSTALL_WAIT = 0 <NEW_LINE> PLACEMENT = 1 <NEW_LINE> SERVICES = 2
Names for current screen state
62599054b57a9660fecd2f86
class RasaFileImporter(TrainingDataImporter): <NEW_LINE> <INDENT> def __init__( self, config_file: Optional[Text] = None, domain_path: Optional[Text] = None, training_data_paths: Optional[Union[List[Text], Text]] = None, ): <NEW_LINE> <INDENT> if config_file and os.path.exists(config_file): <NEW_LINE> <INDENT> self.config = io_utils.read_config_file(config_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.config = {} <NEW_LINE> <DEDENT> self._domain_path = domain_path <NEW_LINE> self._story_files, self._nlu_files = data.get_core_nlu_files( training_data_paths ) <NEW_LINE> <DEDENT> async def get_config(self) -> Dict: <NEW_LINE> <INDENT> return self.config <NEW_LINE> <DEDENT> async def get_stories( self, interpreter: "NaturalLanguageInterpreter" = RegexInterpreter(), template_variables: Optional[Dict] = None, use_e2e: bool = False, exclusion_percentage: Optional[int] = None, ) -> StoryGraph: <NEW_LINE> <INDENT> story_steps = await StoryFileReader.read_from_files( self._story_files, await self.get_domain(), interpreter, template_variables, use_e2e, exclusion_percentage, ) <NEW_LINE> return StoryGraph(story_steps) <NEW_LINE> <DEDENT> async def get_nlu_data(self, language: Optional[Text] = "en") -> TrainingData: <NEW_LINE> <INDENT> return utils.training_data_from_paths(self._nlu_files, language) <NEW_LINE> <DEDENT> async def get_domain(self) -> Domain: <NEW_LINE> <INDENT> domain = Domain.empty() <NEW_LINE> try: <NEW_LINE> <INDENT> domain = Domain.load(self._domain_path) <NEW_LINE> domain.check_missing_templates() <NEW_LINE> <DEDENT> except InvalidDomain: <NEW_LINE> <INDENT> logger.debug( "Loading domain from '{}' failed. Using empty domain.".format( self._domain_path ) ) <NEW_LINE> <DEDENT> return domain
Default `TrainingFileImporter` implementation.
62599054a79ad1619776b543
class BackendHTTPRequestHandler(BaseHTTPRequestHandler): <NEW_LINE> <INDENT> def _handle_req_with_cb(self): <NEW_LINE> <INDENT> headers = self.headers <NEW_LINE> body_len = int(headers['Content-Length'] or 0) <NEW_LINE> body = self.rfile.read(body_len) <NEW_LINE> cb = self.server.backend_callback <NEW_LINE> resp_tuple = cb(self.command, self.path, headers, body) <NEW_LINE> assert len(resp_tuple) == 3 <NEW_LINE> code, headers, body = resp_tuple <NEW_LINE> body = bytes(body, 'UTF-8') <NEW_LINE> self.send_response(code) <NEW_LINE> for name, val in headers.items(): <NEW_LINE> <INDENT> self.send_header(name, val) <NEW_LINE> <DEDENT> self.end_headers() <NEW_LINE> self.wfile.write(body) <NEW_LINE> print(body) <NEW_LINE> <DEDENT> protocol_version = 'HTTP/1.1' <NEW_LINE> do_GET = _handle_req_with_cb <NEW_LINE> do_POST = _handle_req_with_cb <NEW_LINE> def log_message(self, format, *args): <NEW_LINE> <INDENT> return
A wrapper for BackendHTTPServer.backend_callback. The class simply pushes HTTP requests to the callback, and then builds responses from data returned by the callback. That is done for simplicity. It is easier to code a single callback function than a whole handler class. We have to code one in every test, and we don't need much power in tests code, so we prefer a function over a class.
6259905463d6d428bbee3cde
class IndexDetail(generics.RetrieveUpdateDestroyAPIView): <NEW_LINE> <INDENT> queryset = Index.objects.all() <NEW_LINE> serializer_class = IndexSerializer <NEW_LINE> permission_classes = [permissions.IsAuthenticatedOrReadOnly,IsUserOrReadOnly] <NEW_LINE> def perform_destroy(self, instance): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> instance.delete() <NEW_LINE> <DEDENT> except ProtectedError as err: <NEW_LINE> <INDENT> raise APIException( code=502, detail="Protected error: {0}".format(err) )
Ce viewset fournit les actions `retrieve`,`update` et `destroy` pour les indices
6259905426068e7796d4de53
class Course(models.Model): <NEW_LINE> <INDENT> pass
课程表
62599054fff4ab517ebced2e
class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "sub categories"
Meta Class.
6259905494891a1f408ba17c
class RegisterModulePreparerPy(RegisterModulePreparerBase): <NEW_LINE> <INDENT> def prepare(self, py_b64, dest_filename=None): <NEW_LINE> <INDENT> mytempfile = self.modules["tempfile"] <NEW_LINE> myos = self.modules["os"] <NEW_LINE> mysubprocess = self.modules["subprocess"] <NEW_LINE> try: <NEW_LINE> <INDENT> contents = base64.decodestring(py_b64) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return None, ("%s: %s" % ("base64.decodestring error: ", e.message)) <NEW_LINE> <DEDENT> log.debug("creating tempfile with contents") <NEW_LINE> f_handle, tempfilename = mytempfile.mkstemp() <NEW_LINE> log.debug("writing contents to disk at '%s'", tempfilename) <NEW_LINE> myos.write(f_handle, contents) <NEW_LINE> log.info("syntax checking file") <NEW_LINE> py_proc = mysubprocess.Popen(["python", "-m", "py_compile", tempfilename], stdout=mysubprocess.PIPE, stderr=mysubprocess.PIPE) <NEW_LINE> py_out, py_err = py_proc.communicate() <NEW_LINE> log.debug("removing tempfile at '%s'", tempfilename) <NEW_LINE> if 0 != py_proc.returncode: <NEW_LINE> <INDENT> return None, ("Syntax check failed. (STDOUT: %s) (STDERR: %s)" % (py_out, py_err)) <NEW_LINE> <DEDENT> ret = self.uploader_object_factory(py_b64, dest_filename or tempfilename) <NEW_LINE> return ret, ""
class to register a python file by putting it in a web-accessible location
6259905423849d37ff8525d0
class survey_ExportResponses(S3Method): <NEW_LINE> <INDENT> def apply_method(self, r, **attr): <NEW_LINE> <INDENT> if r.representation != "xls": <NEW_LINE> <INDENT> r.error(415, current.error.BAD_FORMAT) <NEW_LINE> <DEDENT> series_id = self.record_id <NEW_LINE> if series_id is None: <NEW_LINE> <INDENT> r.error(405, current.error.BAD_METHOD) <NEW_LINE> <DEDENT> s3db = current.s3db <NEW_LINE> T = current.T <NEW_LINE> try: <NEW_LINE> <INDENT> import xlwt <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> r.error(501, T("xlwt not installed, so cannot export as a Spreadsheet")) <NEW_LINE> <DEDENT> section_break = False <NEW_LINE> try: <NEW_LINE> <INDENT> filename = "%s_All_responses.xls" % r.record.name <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> r.error(404, T("Series not found!")) <NEW_LINE> <DEDENT> output = BytesIO() <NEW_LINE> book = xlwt.Workbook(encoding="utf-8") <NEW_LINE> col = 0 <NEW_LINE> complete_row = {} <NEW_LINE> next_row = 2 <NEW_LINE> question_list = s3db.survey_getAllQuestionsForSeries(series_id) <NEW_LINE> if len(question_list) > 256: <NEW_LINE> <INDENT> section_list = s3db.survey_getAllSectionsForSeries(series_id) <NEW_LINE> section_break = True <NEW_LINE> <DEDENT> if section_break: <NEW_LINE> <INDENT> sheets = {} <NEW_LINE> cols = {} <NEW_LINE> for section in section_list: <NEW_LINE> <INDENT> sheet_name = section["name"].split(" ")[0] <NEW_LINE> if sheet_name not in sheets: <NEW_LINE> <INDENT> sheets[sheet_name] = book.add_sheet(sheet_name) <NEW_LINE> cols[sheet_name] = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> sheet = book.add_sheet(s3_str(T("Responses"))) <NEW_LINE> <DEDENT> for qstn in question_list: <NEW_LINE> <INDENT> if section_break: <NEW_LINE> <INDENT> sheet_name = qstn["section"].split(" ")[0] <NEW_LINE> sheet = sheets[sheet_name] <NEW_LINE> col = cols[sheet_name] <NEW_LINE> <DEDENT> row = 0 <NEW_LINE> sheet.write(row, col, s3_str(qstn["code"])) <NEW_LINE> row += 1 <NEW_LINE> widget_obj = s3db.survey_getWidgetFromQuestion(qstn["qstn_id"]) <NEW_LINE> sheet.write(row, col, s3_str(widget_obj.fullName())) <NEW_LINE> all_responses = s3db.survey_getAllAnswersForQuestionInSeries(qstn["qstn_id"], series_id) <NEW_LINE> for answer in all_responses: <NEW_LINE> <INDENT> value = answer["value"] <NEW_LINE> complete_id = answer["complete_id"] <NEW_LINE> if complete_id in complete_row: <NEW_LINE> <INDENT> row = complete_row[complete_id] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> complete_row[complete_id] = next_row <NEW_LINE> row = next_row <NEW_LINE> next_row += 1 <NEW_LINE> <DEDENT> sheet.write(row, col, s3_str(value)) <NEW_LINE> <DEDENT> col += 1 <NEW_LINE> if section_break: <NEW_LINE> <INDENT> cols[sheet_name] += 1 <NEW_LINE> <DEDENT> <DEDENT> sheet.panes_frozen = True <NEW_LINE> sheet.horz_split_pos = 2 <NEW_LINE> book.save(output) <NEW_LINE> from gluon.contenttype import contenttype <NEW_LINE> headers = current.response.headers <NEW_LINE> headers["Content-Type"] = contenttype(".xls") <NEW_LINE> headers["Content-disposition"] = "attachment; filename=\"%s\"" % filename <NEW_LINE> output.seek(0) <NEW_LINE> return output.read()
Download all responses in a Spreadsheet
625990547d847024c075d8e7
class AbstractField(models.Model): <NEW_LINE> <INDENT> label = models.CharField(_("Label"), max_length=settings.LABEL_MAX_LENGTH) <NEW_LINE> slug = models.SlugField(_('Slug'), max_length=2000, blank=True, default="") <NEW_LINE> field_type = models.IntegerField(_("Type"), choices=fields.NAMES) <NEW_LINE> required = models.BooleanField(_("Required"), default=True) <NEW_LINE> visible = models.BooleanField(_("Visible"), default=True) <NEW_LINE> choices = models.CharField(_("Choices"), max_length=settings.CHOICES_MAX_LENGTH, blank=True, help_text="Comma separated options where applicable. If an option " "itself contains commas, surround the option starting with the %s" "character and ending with the %s character." % (settings.CHOICES_QUOTE, settings.CHOICES_UNQUOTE)) <NEW_LINE> default = models.CharField(_("Default value"), blank=True, max_length=settings.FIELD_MAX_LENGTH) <NEW_LINE> placeholder_text = models.CharField(_("Placeholder Text"), null=True, blank=True, max_length=100, editable=settings.USE_HTML5) <NEW_LINE> help_text = models.CharField(_("Help text"), blank=True, max_length=settings.HELPTEXT_MAX_LENGTH) <NEW_LINE> objects = FieldManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _("Field") <NEW_LINE> verbose_name_plural = _("Fields") <NEW_LINE> abstract = True <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.label) <NEW_LINE> <DEDENT> def get_choices(self): <NEW_LINE> <INDENT> choice = "" <NEW_LINE> quoted = False <NEW_LINE> for char in self.choices: <NEW_LINE> <INDENT> if not quoted and char == settings.CHOICES_QUOTE: <NEW_LINE> <INDENT> quoted = True <NEW_LINE> <DEDENT> elif quoted and char == settings.CHOICES_UNQUOTE: <NEW_LINE> <INDENT> quoted = False <NEW_LINE> <DEDENT> elif char == "," and not quoted: <NEW_LINE> <INDENT> choice = choice.strip() <NEW_LINE> if choice: <NEW_LINE> <INDENT> yield choice, choice <NEW_LINE> <DEDENT> choice = "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> choice += char <NEW_LINE> <DEDENT> <DEDENT> choice = choice.strip() <NEW_LINE> if choice: <NEW_LINE> <INDENT> yield choice, choice <NEW_LINE> <DEDENT> <DEDENT> def is_a(self, *args): <NEW_LINE> <INDENT> return self.field_type in args
A field for a user-built form.
6259905438b623060ffaa2d5
class BatchProvider(): <NEW_LINE> <INDENT> def __init__(self, X, y, indices): <NEW_LINE> <INDENT> self.X = X <NEW_LINE> self.y = y <NEW_LINE> self.indices = indices <NEW_LINE> self.unused_indices = indices.copy() <NEW_LINE> <DEDENT> def next_batch(self, batch_size, add_dummy_dimension=True): <NEW_LINE> <INDENT> if len(self.unused_indices) < batch_size: <NEW_LINE> <INDENT> self.unused_indices = self.indices <NEW_LINE> <DEDENT> batch_indices = np.random.choice(self.unused_indices, batch_size, replace=False) <NEW_LINE> self.unused_indices = np.setdiff1d(self.unused_indices, batch_indices) <NEW_LINE> batch_indices = np.sort(batch_indices) <NEW_LINE> X_batch = self.X[batch_indices, ...] <NEW_LINE> y_batch = self.y[batch_indices, ...] <NEW_LINE> if add_dummy_dimension: <NEW_LINE> <INDENT> X_batch = np.expand_dims(X_batch, axis=-1) <NEW_LINE> <DEDENT> return X_batch, y_batch <NEW_LINE> <DEDENT> def iterate_batches(self, batch_size, add_dummy_dimension=True): <NEW_LINE> <INDENT> np.random.shuffle(self.indices) <NEW_LINE> N = self.indices.shape[0] <NEW_LINE> for b_i in range(0, N, batch_size): <NEW_LINE> <INDENT> batch_indices = np.sort(self.indices[b_i:b_i + batch_size]) <NEW_LINE> X_batch = self.X[batch_indices, ...] <NEW_LINE> y_batch = self.y[batch_indices, ...] <NEW_LINE> if add_dummy_dimension: <NEW_LINE> <INDENT> X_batch = np.expand_dims(X_batch, axis=-1) <NEW_LINE> <DEDENT> yield X_batch, y_batch
This is a helper class to conveniently access mini batches of training, testing and validation data
6259905471ff763f4b5e8cbb
class ConvModelAvgPool(Baseline): <NEW_LINE> <INDENT> def block(self, input_data, scope, pool_size=2, pool_strides=1, filters=16, conv_strides=1, kernel_size=3, padding='valid'): <NEW_LINE> <INDENT> with tf.variable_scope(scope): <NEW_LINE> <INDENT> h = tf.layers.conv2d(input_data, filters=filters, kernel_size=3, strides=conv_strides, padding='valid', name='conv') <NEW_LINE> a = tf.layers.average_pooling2d(h, pool_size=pool_size, strides=pool_strides, padding='same') <NEW_LINE> <DEDENT> var_name = scope + '_h' <NEW_LINE> self.feature_maps[var_name] = h <NEW_LINE> return a
Sum_pool layer is an aggregation layer which returns the sum of per-channel neighborhood values 7 layer convolutional neural network (conv - max)*6 - conv - softmax Inputs: - img: Input image of size (N, 32, 32, 3) - label: label associated with each input (N, C) N: dataset size C: number of classes
62599054d99f1b3c44d06bac
class ExperimentalPlugins(BasePluginManager): <NEW_LINE> <INDENT> def get_queryset(self): <NEW_LINE> <INDENT> return super(ExperimentalPlugins, self).get_queryset().filter(pluginversion__approved=True, pluginversion__experimental=True).distinct()
Shows only public plugins: i.e. those with "approved" flag set and with one "experimental" version
62599054d53ae8145f91996f
class ItemsPlugin(BasePluginUI): <NEW_LINE> <INDENT> tool_name = 'Item Types' <NEW_LINE> description = 'Helps handle data that is of a certain type.' <NEW_LINE> category = Category.Core <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> super(ItemsPlugin, self).__init__(*args) <NEW_LINE> self.item_types_object = ItemTypesObject() <NEW_LINE> self.itemTypesChanged = self.item_types_object.itemTypesChanged <NEW_LINE> self.augment('item_types', None, callback=self.on_item_types_augmented) <NEW_LINE> self.augment('item_actions', None, callback=self.on_item_actions_augmented) <NEW_LINE> <DEDENT> def on_item_types_augmented(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for i in data: <NEW_LINE> <INDENT> if issubclass(i, Item): <NEW_LINE> <INDENT> item_types.append(i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> if issubclass(data, Item): <NEW_LINE> <INDENT> item_types.append(data) <NEW_LINE> <DEDENT> <DEDENT> self.itemTypesChanged.emit(item_types) <NEW_LINE> <DEDENT> def on_item_actions_augmented(self, data): <NEW_LINE> <INDENT> if isinstance(data, ItemAction): <NEW_LINE> <INDENT> item_actions.append(data) <NEW_LINE> return <NEW_LINE> <DEDENT> for i in data: <NEW_LINE> <INDENT> if isinstance(i, ItemAction): <NEW_LINE> <INDENT> item_actions.append(i)
For augmentation purposes, we use a plugin to help with item types.
62599054f7d966606f74933e
class StalledEvent(Event): <NEW_LINE> <INDENT> pass
An stalled event is dispatched from the session manager when an FSM has stuck to a non-terminal state for longer than expected time.
62599054b5575c28eb713752
class RpcServiceMock(object): <NEW_LINE> <INDENT> def __init__(self, worker_instance): <NEW_LINE> <INDENT> self.worker = worker_instance <NEW_LINE> self._request = _RequestMock(worker_instance) <NEW_LINE> <DEDENT> def get_worker_info(self): <NEW_LINE> <INDENT> return worker.get_worker_info(self._request) <NEW_LINE> <DEDENT> def get_worker_id(self): <NEW_LINE> <INDENT> return worker.get_worker_id(self._request) <NEW_LINE> <DEDENT> def get_worker_tasks(self): <NEW_LINE> <INDENT> return worker.get_worker_tasks(self._request) <NEW_LINE> <DEDENT> def get_task(self, task_id): <NEW_LINE> <INDENT> return worker.get_task(self._request, task_id) <NEW_LINE> <DEDENT> def get_task_no_verify(self, task_id): <NEW_LINE> <INDENT> return worker.get_task_no_verify(self._request, task_id) <NEW_LINE> <DEDENT> def interrupt_tasks(self, task_list): <NEW_LINE> <INDENT> return worker.interrupt_tasks(self._request, task_list) <NEW_LINE> <DEDENT> def timeout_tasks(self, task_list): <NEW_LINE> <INDENT> return worker.timeout_tasks(self._request, task_list) <NEW_LINE> <DEDENT> def assign_task(self, task_id): <NEW_LINE> <INDENT> return worker.assign_task(self._request, task_id) <NEW_LINE> <DEDENT> def open_task(self, task_id): <NEW_LINE> <INDENT> return worker.open_task(self._request, task_id) <NEW_LINE> <DEDENT> def close_task(self, task_id, task_result): <NEW_LINE> <INDENT> return worker.close_task(self._request, task_id, task_result) <NEW_LINE> <DEDENT> def cancel_task(self, task_id): <NEW_LINE> <INDENT> return worker.cancel_task(self._request, task_id) <NEW_LINE> <DEDENT> def fail_task(self, task_id, task_result): <NEW_LINE> <INDENT> return worker.fail_task(self._request, task_id, task_result) <NEW_LINE> <DEDENT> def set_task_weight(self, task_id, weight): <NEW_LINE> <INDENT> return worker.set_task_weight(self._request, task_id, weight) <NEW_LINE> <DEDENT> def update_worker(self, enabled, ready, task_count): <NEW_LINE> <INDENT> return worker.update_worker(self._request, enabled, ready, task_count) <NEW_LINE> <DEDENT> def get_tasks_to_assign(self): <NEW_LINE> <INDENT> return worker.get_tasks_to_assign(self._request, ) <NEW_LINE> <DEDENT> def get_awaited_tasks(self, awaited_task_list): <NEW_LINE> <INDENT> return worker.get_awaited_tasks(self._request, awaited_task_list) <NEW_LINE> <DEDENT> def create_subtask(self, label, method, args, parent_id): <NEW_LINE> <INDENT> return worker.create_subtask(self._request, label, method, args, parent_id) <NEW_LINE> <DEDENT> def wait(self, task_id, child_list=None): <NEW_LINE> <INDENT> return worker.wait(self._request, task_id, child_list) <NEW_LINE> <DEDENT> def check_wait(self, task_id, child_list=None): <NEW_LINE> <INDENT> return worker.check_wait(self._request, task_id, child_list) <NEW_LINE> <DEDENT> def upload_task_log(self, task_id, relative_path, mode, chunk_start, chunk_len, chunk_checksum, encoded_chunk): <NEW_LINE> <INDENT> return worker.upload_task_log(self._request, task_id, relative_path, mode, chunk_start, chunk_len, chunk_checksum, encoded_chunk)
RpcServiceMock implements all XML-RPC methods.
62599054d486a94d0ba2d4d5
class Slug(PolymorphicModel): <NEW_LINE> <INDENT> slug = models.SlugField(max_length=200, unique=True, db_index=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s %s' % (self.__class__.__name__, self.slug.replace('-',' ').title())
Core namespace of assets and contents. A kludge to avoid content types.
6259905463d6d428bbee3ce0
class TestSceneNodeBasic_Box_and_Sphere(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.scale_factor = 4 <NEW_LINE> self.scale = np.ones((1, 3)).flatten() * self.scale_factor <NEW_LINE> self.center = [0, 0, -5] <NEW_LINE> self.radius = 0.5 <NEW_LINE> self.scaled_radius = self.radius * self.scale_factor <NEW_LINE> self.min= [-1,-1,-1] <NEW_LINE> self.max= [1,1,1] <NEW_LINE> self.scene_node = SceneNode(params = {'scale': self.scale}) <NEW_LINE> self.scene_node.children.append(Box({'min': self.min, 'max': self.max})) <NEW_LINE> self.scene_node.children.append(Sphere({'center': self.center, 'radius': self.radius})) <NEW_LINE> <DEDENT> def test_scene_node_creation(self): <NEW_LINE> <INDENT> M = np.eye(4) <NEW_LINE> M[:3,:3] = np.diag(self.scale) <NEW_LINE> nptest.assert_array_equal(self.scene_node.M, M) <NEW_LINE> nptest.assert_array_equal(self.scene_node.Minv, np.linalg.inv(M)) <NEW_LINE> self.assertEqual(len(self.scene_node.children), 2) <NEW_LINE> self.assertEqual(self.scene_node.children[0].__class__.__name__, 'Box') <NEW_LINE> self.assertEqual(self.scene_node.children[1].__class__.__name__, 'Sphere') <NEW_LINE> <DEDENT> def test_basic_ray_intersection_on_zaxis(self): <NEW_LINE> <INDENT> test_intersection_with_result(self.scene_node, origin=[0, 0, 10], direction=[0, 0, -1], isect_pt = [0, 0, 4], isect_normal=[0, 0, 1], isect_dist = 6.0) <NEW_LINE> <DEDENT> def test_basic_ray_intersection_parallel_to_zaxis(self): <NEW_LINE> <INDENT> expected_pt = [2.0, 0.0, 4.0] <NEW_LINE> expected_normal = [0.0,0.0,1.0] <NEW_LINE> test_intersection_with_result(self.scene_node, origin=[2, 0, 10], direction=[0, 0, -1], isect_pt = expected_pt, isect_normal= expected_normal, isect_dist = 10 - expected_pt[2])
Add an ellipse by scaling a sphere of radius 1 along y by a factor of 10 and check if the ellipse intersection for radius 2 holds on y axis.
6259905423e79379d538da09
class MoneyField(models.DecimalField): <NEW_LINE> <INDENT> def __init__(self, verbose_name=None, name=None, max_digits=28, decimal_places=18, **kwargs): <NEW_LINE> <INDENT> super(MoneyField, self).__init__(verbose_name, name, max_digits, decimal_places, **kwargs)
Decimal Field with hardcoded precision of 28 and a scale of 18. Usage: from decimal import Decimal field_name = MoneyField(default=Decimal(0))
6259905482261d6c52730950
class ReportCriteriaForm(forms.Form): <NEW_LINE> <INDENT> error_css_class = 'text-error' <NEW_LINE> endtime = forms.SplitDateTimeField(label='Report End Time', input_time_formats=['%I:%M %p'], input_date_formats=['%m/%d/%Y'], widget=ReportSplitDateTimeWidget) <NEW_LINE> duration = forms.ChoiceField(choices=zip(DURATIONS, DURATIONS), widget=forms.Select(attrs={'class': 'duration'})) <NEW_LINE> filterexpr = forms.CharField(label='Filter Expression', required=False, max_length=100, widget=forms.TextInput(attrs={'class': 'filterexpr'})) <NEW_LINE> ignore_cache = forms.BooleanField(required=False, widget=forms.HiddenInput) <NEW_LINE> debug = forms.BooleanField(required=False, widget=forms.HiddenInput) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> extra = kwargs.pop('extra') <NEW_LINE> super(ReportCriteriaForm, self).__init__(*args, **kwargs) <NEW_LINE> if extra: <NEW_LINE> <INDENT> logging.debug('creating ReportCriteriaForm, with extra fields: %s' % extra) <NEW_LINE> for field in extra: <NEW_LINE> <INDENT> field_id = 'criteria_%s' % field.id <NEW_LINE> eval_field = '%s(label="%s")' % (field.field_type, field.label) <NEW_LINE> self.fields[field_id] = eval(eval_field) <NEW_LINE> self.initial[field_id] = field.initial <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def criteria(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for k, v in self.cleaned_data.iteritems(): <NEW_LINE> <INDENT> if k == 'endtime': <NEW_LINE> <INDENT> result[k] = datetime_to_seconds(v) <NEW_LINE> <DEDENT> elif hasattr(v, 'temporary_file_path'): <NEW_LINE> <INDENT> newtemp = tempfile.NamedTemporaryFile(delete=False) <NEW_LINE> v.seek(0) <NEW_LINE> shutil.copyfileobj(v, newtemp) <NEW_LINE> v.close() <NEW_LINE> newtemp.close() <NEW_LINE> result[k] = newtemp.name <NEW_LINE> <DEDENT> elif k != 'debug': <NEW_LINE> <INDENT> result[k] = v <NEW_LINE> <DEDENT> <DEDENT> return result
Base Form for Report Criteria
6259905494891a1f408ba17d
class PersistentExternalizableDictionary(PersistentMapping, ExternalizableDictionaryMixin): <NEW_LINE> <INDENT> def toExternalDictionary(self, *args, **kwargs): <NEW_LINE> <INDENT> result = super(PersistentExternalizableDictionary, self).toExternalDictionary(self, *args, **kwargs) <NEW_LINE> for key, value in iteritems(self): <NEW_LINE> <INDENT> result[key] = toExternalObject(value, *args, **kwargs) <NEW_LINE> <DEDENT> return result
Dictionary mixin that provides :meth:`toExternalDictionary` to return a new dictionary with each value in the dict having been externalized with :func:`~.toExternalObject`. .. versionchanged:: 1.0 No longer extends :class:`nti.zodb.persistentproperty.PersistentPropertyHolder`. If you have subclasses that use writable properties and which should bypass the normal attribute setter implementation, please mixin this superclass (first) yourself.
625990546e29344779b01b57
class Field(Resource): <NEW_LINE> <INDENT> pass
A simple field to retrieve from a value by using its filters.
6259905415baa723494634a0
class GuestUser(object): <NEW_LINE> <INDENT> preferences = dict() <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.id = 0 <NEW_LINE> self.username = "guest" <NEW_LINE> self.display_name = "guest" <NEW_LINE> self.role = Role.get_by_name('Guest') <NEW_LINE> self.is_guest = True <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def can(self, permission): <NEW_LINE> <INDENT> perm_q = Session.query(Permission) .with_parent(self.role) .filter_by(name=permission) <NEW_LINE> return perm_q.count() > 0 <NEW_LINE> <DEDENT> def preference(self, pref): <NEW_LINE> <INDENT> return self.preferences[pref]
Dummy object for not-logged-in users
62599054435de62698e9d311
class TextPosition(Position): <NEW_LINE> <INDENT> def __init__(self, text): <NEW_LINE> <INDENT> Position.__init__(self) <NEW_LINE> self.pos = 0 <NEW_LINE> self.text = text <NEW_LINE> self.checkbytemark() <NEW_LINE> <DEDENT> def skip(self, string): <NEW_LINE> <INDENT> self.pos += len(string) <NEW_LINE> <DEDENT> def identifier(self): <NEW_LINE> <INDENT> length = 30 <NEW_LINE> if self.pos + length > len(self.text): <NEW_LINE> <INDENT> length = len(self.text) - self.pos <NEW_LINE> <DEDENT> return '*' + self.text[self.pos:self.pos + length] + '*' <NEW_LINE> <DEDENT> def isout(self): <NEW_LINE> <INDENT> return self.pos >= len(self.text) <NEW_LINE> <DEDENT> def current(self): <NEW_LINE> <INDENT> return self.text[self.pos] <NEW_LINE> <DEDENT> def extract(self, length): <NEW_LINE> <INDENT> if self.pos + length > len(self.text): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.text[self.pos : self.pos + length]
A parse position based on a raw text.
625990547b25080760ed8766
class EventFileLoggingApplication(EventStoringApplication): <NEW_LINE> <INDENT> def __init__(self, broker, output_file=None, **kwargs): <NEW_LINE> <INDENT> super(EventFileLoggingApplication, self).__init__(broker, **kwargs) <NEW_LINE> if output_file: <NEW_LINE> <INDENT> self.output_file = output_file <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.output_file = "events_%s.json" % self.name <NEW_LINE> <DEDENT> <DEDENT> def on_stop(self): <NEW_LINE> <INDENT> with open(self.output_file, "w") as f: <NEW_LINE> <INDENT> log.debug("outputting sunk events to file %s" % self.output_file) <NEW_LINE> f.write(json.dumps([e.to_map() for e in self.events], indent=2)) <NEW_LINE> <DEDENT> super(EventFileLoggingApplication, self).on_stop()
This Application outputs all of its received events that it subscribed to into a JSON file when it stops. Mainly intended for testing. WARNING: if you let this Application run for a very long time, you'll end up with a huge list of sunk events that may cause memory problems
625990544e4d562566373916
class ValidNode(n.LiteralNode): <NEW_LINE> <INDENT> validators = dict(a=float, b=int)
ValidNode test implementation.
625990542ae34c7f260ac5f5
class FavouriteDeleteAPIView(APIView): <NEW_LINE> <INDENT> def get_object(self, pk): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Favourite.objects.get(pk=pk) <NEW_LINE> <DEDENT> except Favourite.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> <DEDENT> def get(self, request, pk, format=None): <NEW_LINE> <INDENT> favourite_obj = self.get_object(pk) <NEW_LINE> serializer = FavouriteSerializer(favourite_obj) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def delete(self, request, pk, format=None): <NEW_LINE> <INDENT> favourite_obj = self.get_object(pk) <NEW_LINE> favourite_obj.delete() <NEW_LINE> return Response(status=status.HTTP_204_NO_CONTENT)
Retrieve, update or delete a favourite instance.
6259905407f4c71912bb0948
class ElementRemovalError(UserActionError): <NEW_LINE> <INDENT> message = "error removing element"
Element removal failed.
6259905407f4c71912bb0949
class ReadonlyAdmin(EtcAdmin): <NEW_LINE> <INDENT> view_on_site: bool = False <NEW_LINE> actions = None <NEW_LINE> def has_add_permission(self, request: HttpRequest) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def has_delete_permission(self, request: HttpRequest, obj: models.Model = None) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def changeform_view( self, request: HttpRequest, object_id: int = None, form_url: str = '', extra_context: dict = None ) -> HttpResponse: <NEW_LINE> <INDENT> extra_context = extra_context or {} <NEW_LINE> extra_context.update({ 'show_save_and_continue': False, 'show_save': False, }) <NEW_LINE> return super().changeform_view(request, object_id, extra_context=extra_context)
Read-only etc admin base class.
62599054b57a9660fecd2f8a
class Graph(): <NEW_LINE> <INDENT> def __init__(self, alist): <NEW_LINE> <INDENT> self.adj_lists = {} <NEW_LINE> for l in alist: <NEW_LINE> <INDENT> nid = l[NID] <NEW_LINE> if nid not in self.adj_lists: <NEW_LINE> <INDENT> self.adj_lists[nid] = [] <NEW_LINE> <DEDENT> self.adj_lists[nid].append(Node(nid)) <NEW_LINE> for neighbor in l[ALIST]: <NEW_LINE> <INDENT> self.adj_lists[nid].append(neighbor) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_node(self, nid): <NEW_LINE> <INDENT> if nid in self.adj_lists: <NEW_LINE> <INDENT> return self.adj_lists[nid][0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def get_alist(self, nid): <NEW_LINE> <INDENT> if nid in self.adj_lists: <NEW_LINE> <INDENT> return self.adj_lists[nid][1:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
The graph structure, here an adjacency list.
625990548e71fb1e983bcfd9
class DescribeRiskSyscallEventsExportResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.DownloadUrl = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.DownloadUrl = params.get("DownloadUrl") <NEW_LINE> self.RequestId = params.get("RequestId")
DescribeRiskSyscallEventsExport返回参数结构体
625990540c0af96317c577e7
class MonitoringManager(ResourceDetector): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(MonitoringManager, self).__init__("monitoring") <NEW_LINE> self.config = ConfParser("ro.conf") <NEW_LINE> self.monitoring_section = self.config.get("monitoring") <NEW_LINE> self.protocol = self.monitoring_section.get("protocol") <NEW_LINE> self.address = self.monitoring_section.get("address") <NEW_LINE> self.port = self.monitoring_section.get("port") <NEW_LINE> self.endpoint = self.monitoring_section.get("endpoint") <NEW_LINE> self.monitoring_server = {"protocol": self.protocol, "address": self.address, "port": self.port, "endpoint": self.endpoint, } <NEW_LINE> <DEDENT> def physical_topology(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return PhysicalMonitoring().send_topology(self.monitoring_server) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error("Physical topology - Could not send topology. Details: %s" % e) <NEW_LINE> logger.error(traceback.format_exc()) <NEW_LINE> <DEDENT> <DEDENT> def slice_topology(self): <NEW_LINE> <INDENT> return SliceMonitoring().send_topology(self.monitoring_server)
Periodically communicates both physical and slice data to the MS.
62599054379a373c97d9a534
class CpuIowaitPercent(ComputeMetricsNotificationBase): <NEW_LINE> <INDENT> metric = 'cpu.iowait.percent' <NEW_LINE> unit = '%' <NEW_LINE> sample_type = sample.TYPE_GAUGE,
Handle CPU I/O wait percentage message.
6259905463d6d428bbee3ce2
class JSONAPIResourceIdentifierSerializer(JSONAPIPrimaryDataSerializer): <NEW_LINE> <INDENT> primary = False <NEW_LINE> exclude_parameterized = True <NEW_LINE> def to_internal_value(self, data): <NEW_LINE> <INDENT> value = super( JSONAPIResourceIdentifierSerializer, self).to_internal_value(data) <NEW_LINE> id_field = list(value.serializer.fields.values())[0] <NEW_LINE> return id_field.get_attribute(value)
Common serializer support for JSON API objects with resource identifiers.
62599054596a897236129037
class PositionalEncoding(nn.Module): <NEW_LINE> <INDENT> def __init__(self, d_model, dropout=0, max_len=5000): <NEW_LINE> <INDENT> super(PositionalEncoding, self).__init__() <NEW_LINE> self.dropout = nn.Dropout(p=dropout) <NEW_LINE> pe = torch.zeros(max_len, d_model) <NEW_LINE> position = torch.arange(0, max_len).unsqueeze(1) <NEW_LINE> div_term = torch.exp(torch.arange(0, d_model, 2) * -(math.log(10000.0) / d_model)) <NEW_LINE> pe[:, 0::2] = torch.sin(position * div_term) <NEW_LINE> pe[:, 1::2] = torch.cos(position * div_term) <NEW_LINE> pe = pe.unsqueeze(0) <NEW_LINE> self.register_buffer('pe', pe) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = x + Variable(self.pe[:, :x.size(1)], requires_grad=False) <NEW_LINE> return self.dropout(x)
Add position information to input tensor. :Examples: >>> m = PositionalEncoding(d_model=6, max_len=10, dropout=0) >>> input = torch.randn(3, 10, 6) >>> output = m(input)
625990547cff6e4e811b6f50
class open_app_from_settings(parent_ui_steps.open_app_from_settings): <NEW_LINE> <INDENT> pass
description: opens an app/activity ideintified by <view_to_find> from settings page if <view_to_check> given it will check that the object identified by <view_to_check>: - appeared if <view_presence> is True - disappeared if <view_presence> is False usage: ui_steps.open_app_from_settings(view_to_find = {"text": "Apps"}, view_to_check = {"text": "Donwloaded"})() tags: ui, android, press, click, app, application, settings
62599054a17c0f6771d5d629
class PulseCounter(object): <NEW_LINE> <INDENT> def __init__(self, rcpod): <NEW_LINE> <INDENT> self.rcpod = rcpod <NEW_LINE> self.numSamples = 0 <NEW_LINE> <DEDENT> def sample(self, duration, prescale=0): <NEW_LINE> <INDENT> timer_off = 0x06 | (prescale << 4) <NEW_LINE> timer_on = timer_off | 0x01 <NEW_LINE> self.rcpod.poke('t1con', timer_off) <NEW_LINE> self.rcpod.poke('tmr1l', 0) <NEW_LINE> self.rcpod.poke('tmr1h', 0) <NEW_LINE> self.rcpod.poke('pir1', 0) <NEW_LINE> t1 = time.clock() <NEW_LINE> self.rcpod.poke('t1con', timer_on) <NEW_LINE> t2 = time.clock() <NEW_LINE> while 1: <NEW_LINE> <INDENT> while gtk.events_pending(): <NEW_LINE> <INDENT> gtk.main_iteration() <NEW_LINE> <DEDENT> t3 = time.clock() <NEW_LINE> if t3 > t1 + duration: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> self.rcpod.poke('t1con', timer_off) <NEW_LINE> t4 = time.clock() <NEW_LINE> self.counts = self.rcpod.peek('tmr1l') | (self.rcpod.peek('tmr1h') << 8) <NEW_LINE> self.overflow = bool(self.rcpod.peek('pir1') & 0x01) <NEW_LINE> self.minDuration = t3 - t2 <NEW_LINE> self.maxDuration = t4 - t1 <NEW_LINE> self.iTimeCenter = (self.minDuration + self.maxDuration) / 2.0 <NEW_LINE> self.iTimeError = (self.maxDuration - self.minDuration) / 2.0 <NEW_LINE> self.numSamples += 1 <NEW_LINE> <DEDENT> def sampleFrequency(self, duration): <NEW_LINE> <INDENT> self.sample(duration) <NEW_LINE> minFrequency = self.counts / (self.iTimeCenter + self.iTimeError) <NEW_LINE> maxFrequency = self.counts / (self.iTimeCenter - self.iTimeError) <NEW_LINE> self.frequency = (minFrequency + maxFrequency) / 2.0 <NEW_LINE> self.frequencyError = (maxFrequency - minFrequency) / 2.0
A counter for pulses arriving on RC0 / T1CKI
62599054435de62698e9d313
class RunCases: <NEW_LINE> <INDENT> def __init__(self, device, port): <NEW_LINE> <INDENT> self.test_report_root = '.\\TestReport' <NEW_LINE> self.device = device <NEW_LINE> self.port = port <NEW_LINE> if not os.path.exists(self.test_report_root): <NEW_LINE> <INDENT> os.mkdir(self.test_report_root) <NEW_LINE> <DEDENT> date_time = time.strftime('%Y-%m-%d_%H_%M_%S', time.localtime(time.time())) <NEW_LINE> self.test_report_path = self.test_report_root + '\\' + date_time <NEW_LINE> if not os.path.exists(self.test_report_path): <NEW_LINE> <INDENT> os.mkdir(self.test_report_path) <NEW_LINE> <DEDENT> self.file_name = self.test_report_path + '\\' + 'TestReport.html' <NEW_LINE> <DEDENT> def get_path(self): <NEW_LINE> <INDENT> return self.test_report_path <NEW_LINE> <DEDENT> def get_device(self): <NEW_LINE> <INDENT> return self.device <NEW_LINE> <DEDENT> def get_port(self): <NEW_LINE> <INDENT> return self.port <NEW_LINE> <DEDENT> def run(self, cases): <NEW_LINE> <INDENT> with open(self.file_name, 'wb') as file: <NEW_LINE> <INDENT> runner = HTMLTestRunner(stream=file, title='自动化测试报告', description='用例执行情况:') <NEW_LINE> runner.run(cases)
设置了每个设备UI自动化时设备信息、macaca server端口、存放测试报告/日志/截图的路径
625990547b25080760ed8767
class DB_step(models.Model): <NEW_LINE> <INDENT> Case_id = models.CharField(max_length=10, null=True) <NEW_LINE> name = models.CharField(max_length=50, null=True) <NEW_LINE> index = models.IntegerField(null=True) <NEW_LINE> api_method = models.CharField(max_length=10, null=True) <NEW_LINE> api_url = models.CharField(max_length=1000, null=True) <NEW_LINE> api_host = models.CharField(max_length=100, null=True) <NEW_LINE> api_header = models.CharField(max_length=1000, null=True) <NEW_LINE> api_body_method = models.CharField(max_length=10, null=True) <NEW_LINE> api_body = models.CharField(max_length=10, null=True) <NEW_LINE> get_path = models.CharField(max_length=500, null=True) <NEW_LINE> get_zz = models.CharField(max_length=500, null=True) <NEW_LINE> assert_zz = models.CharField(max_length=500, null=True) <NEW_LINE> assert_qz = models.CharField(max_length=500, null=True) <NEW_LINE> assert_path = models.CharField(max_length=500, null=True) <NEW_LINE> mock_res = models.CharField(max_length=1000, null=True) <NEW_LINE> public_header = models.CharField(max_length=1000, null=True) <NEW_LINE> api_login = models.CharField(max_length=10, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
小用例表
6259905430dc7b76659a0d07
class WordsCollection(Iterable): <NEW_LINE> <INDENT> def __init__(self, collection: List[Any] = []) -> None: <NEW_LINE> <INDENT> self._collection = collection <NEW_LINE> <DEDENT> def __iter__(self) -> AlphabeticalOrderIterator: <NEW_LINE> <INDENT> return AlphabeticalOrderIterator(self._collection) <NEW_LINE> <DEDENT> def get_reverse_iterator(self) -> AlphabeticalOrderIterator: <NEW_LINE> <INDENT> return AlphabeticalOrderIterator(self._collection, True) <NEW_LINE> <DEDENT> def add_item(self, item: Any): <NEW_LINE> <INDENT> self._collection.append(item)
EN: Concrete Collections provide one or several methods for retrieving fresh iterator instances, compatible with the collection class. RU: Конкретные Коллекции предоставляют один или несколько методов для получения новых экземпляров итератора, совместимых с классом коллекции.
625990548e71fb1e983bcfda
class Rack: <NEW_LINE> <INDENT> def __init__(self, bagtiles): <NEW_LINE> <INDENT> self.racktiles = rand.sample(bagtiles, 7) <NEW_LINE> self.solution = self.__findsolution__() <NEW_LINE> <DEDENT> def __findsubsets__(self, tiles): <NEW_LINE> <INDENT> sortrack = "".join(sorted(tiles)) <NEW_LINE> alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] <NEW_LINE> if "**" in sortrack: <NEW_LINE> <INDENT> alphabet_twos = ["".join(pair) for pair in itt.combinations_with_replacement(alphabet, 2)] <NEW_LINE> possible_racks = [sortrack.replace("**", pair) for pair in alphabet_twos] <NEW_LINE> subs = [self.__findsubsets__(list(rack)) for rack in possible_racks] <NEW_LINE> subs = [combo for templist in subs for combo in templist] <NEW_LINE> subs = list(set(subs)) <NEW_LINE> <DEDENT> elif "*" in sortrack: <NEW_LINE> <INDENT> possible_racks = [sortrack.replace("*", letter) for letter in alphabet] <NEW_LINE> subs = [self.__findsubsets__(list(rack)) for rack in possible_racks] <NEW_LINE> subs = [combo for templist in subs for combo in templist] <NEW_LINE> subs = list(set(subs)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subs = list() <NEW_LINE> for length in range(2, 8, 1): <NEW_LINE> <INDENT> templist = [sorted(combo) for combo in itt.combinations(tiles, length)] <NEW_LINE> templist = ["".join(combo).upper() for combo in templist] <NEW_LINE> subs.append(templist) <NEW_LINE> <DEDENT> subs = [combo for templist in subs for combo in templist] <NEW_LINE> subs = list(set(subs)) <NEW_LINE> <DEDENT> return subs <NEW_LINE> <DEDENT> def __findsolution__(self): <NEW_LINE> <INDENT> subsets = self.__findsubsets__(self.racktiles) <NEW_LINE> solution = [] <NEW_LINE> for stanagram in subsets: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> solution.append(maps.stanmap[stanagram]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> solution = [word for templist in solution for word in templist] <NEW_LINE> solution = [word for word in solution if len(word) > 2] <NEW_LINE> return solution <NEW_LINE> <DEDENT> def printrack(self): <NEW_LINE> <INDENT> print("---------------------------------------------------------") <NEW_LINE> print("This rack has the following tiles:") <NEW_LINE> print("".join(self.racktiles)) <NEW_LINE> <DEDENT> def printsolution(self): <NEW_LINE> <INDENT> print("This rack can make the following words (length three or more):") <NEW_LINE> for length in range(3,8,1): <NEW_LINE> <INDENT> wordsbylength = [word for word in self.solution if len(word) == length] <NEW_LINE> if len(wordsbylength) > 0: <NEW_LINE> <INDENT> print(wordsbylength)
Constitutes one seven-letter draw from scrabble tiles and has all the corresponding anagram solutions.
62599054b57a9660fecd2f8c
class QQAuthUserView(APIView): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> code = request.query_params.get('code') <NEW_LINE> if not code: <NEW_LINE> <INDENT> return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> oauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI) <NEW_LINE> try: <NEW_LINE> <INDENT> access_token = oauthqq.get_access_token(code) <NEW_LINE> openid = oauthqq.get_open_id(access_token) <NEW_LINE> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> logger.info(error) <NEW_LINE> return Response({'message': 'QQ服务器异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> qqauth_model = QQAuthUser.objects.get(openid=openid) <NEW_LINE> <DEDENT> except QQAuthUser.DoesNotExist: <NEW_LINE> <INDENT> openid_sin = generate_save_user_token(openid) <NEW_LINE> return Response({'access_token': openid_sin}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER <NEW_LINE> jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER <NEW_LINE> user = qqauth_model.user <NEW_LINE> payload = jwt_payload_handler(user) <NEW_LINE> token = jwt_encode_handler(payload) <NEW_LINE> response = Response({ 'token': token, 'username': user.username, 'user_id': user.id }) <NEW_LINE> merge_cart_cookie_to_redis(request, user, response) <NEW_LINE> return response <NEW_LINE> <DEDENT> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> serializer = QQAuthUserSerializer(data=request.data) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> user = serializer.save() <NEW_LINE> jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER <NEW_LINE> jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER <NEW_LINE> payload = jwt_payload_handler(user) <NEW_LINE> token = jwt_encode_handler(payload) <NEW_LINE> response = Response({ 'token': token, 'username': user.username, 'user_id': user.id }) <NEW_LINE> merge_cart_cookie_to_redis(request, user, response) <NEW_LINE> return response
扫码成功后回调处理
62599054e76e3b2f99fd9f0f
class While(AST): <NEW_LINE> <INDENT> def __init__(self, condition, token, block): <NEW_LINE> <INDENT> self.block = block <NEW_LINE> self.token = token <NEW_LINE> self.condition = condition
The while statement.
62599054cad5886f8bdc5b09
class AS2Error(Exception): <NEW_LINE> <INDENT> def __init__(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> self.msg = safe_unicode(msg) <NEW_LINE> if args: <NEW_LINE> <INDENT> if isinstance(args[0], dict): <NEW_LINE> <INDENT> xxx = args[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xxx = {} <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> xxx = kwargs <NEW_LINE> <DEDENT> self.xxx = collections.defaultdict(unicode) <NEW_LINE> for key, value in xxx.iteritems(): <NEW_LINE> <INDENT> self.xxx[safe_unicode(key)] = safe_unicode(value) <NEW_LINE> <DEDENT> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.msg % self.xxx <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return u'Error while displaying error' <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__unicode__()
formats the error messages. Under all circumstances: give (reasonable) output, no errors. input (msg,*args,**kwargs) can be anything: strings (any charset), unicode, objects. Note that these are errors, so input can be 'not valid'! to avoid the risk of 'errors during errors' catch-all solutions are used. 2 ways to raise Exceptions: - AS2Error('tekst %(var1)s %(var2)s',{'var1':'value1','var2':'value2'}) ###this one is preferred!! - AS2Error('tekst %(var1)s %(var2)s',var1='value1',var2='value2')
62599054fff4ab517ebced34
class RefreshApiToken(LoginRequiredMixin, View): <NEW_LINE> <INDENT> def post(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> token = Token.objects.get(user=request.user) <NEW_LINE> token.delete() <NEW_LINE> Token.objects.get_or_create(user=request.user) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> messages.add_message(request, messages.ERROR, f'Could not complete requested action: {err}', extra_tags='alert-danger') <NEW_LINE> <DEDENT> return redirect(self.request.META.get('HTTP_REFERER'))
delete current user API (auth) token and create a new one
62599054be383301e0254d15
class UserViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = User.objects.all() <NEW_LINE> serializer_class = UserSerializer
此viewset默认提供list和detail方法
62599054e64d504609df9e59
class DegreeRegistrationForm(models.Model): <NEW_LINE> <INDENT> enrolled_degree = models.OneToOneField("EnrolledDegreeCourse") <NEW_LINE> current_company = models.CharField(max_length=64, ) <NEW_LINE> current_position = models.CharField(max_length=64, ) <NEW_LINE> current_salary = models.IntegerField() <NEW_LINE> work_experience_choices = ( (0, "应届生"), (1, "1年"), (2, "2年"), (3, "3年"), (4, "4年"), (5, "5年"), (6, "6年"), (7, "7年"), (8, "8年"), (9, "9年"), (10, "10年"), (11, "超过10年"), ) <NEW_LINE> work_experience = models.IntegerField() <NEW_LINE> open_module = models.BooleanField("是否开通第1模块", default=True) <NEW_LINE> stu_specified_mentor = models.CharField("学员自行指定的导师名", max_length=32, blank=True, null=True) <NEW_LINE> study_plan_choices = ((0, "1-2小时/天"), (1, "2-3小时/天"), (2, "3-5小时/天"), (3, "5小时+/天"), ) <NEW_LINE> study_plan = models.SmallIntegerField(choices=study_plan_choices, default=1) <NEW_LINE> why_take_this_course = models.TextField("报此课程原因", max_length=1024) <NEW_LINE> why_choose_us = models.TextField("为何选路飞", max_length=1024) <NEW_LINE> your_expectation = models.TextField("你的期待", max_length=1024) <NEW_LINE> memo = models.CharField(max_length=255, blank=True, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "%s" % self.enrolled_degree <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = '学位课报名表' <NEW_LINE> verbose_name = verbose_name_plural
学位课程报名表
62599054507cdc57c63a62b7
class FileModel: <NEW_LINE> <INDENT> def __init__(self, path, name): <NEW_LINE> <INDENT> self.path = path_helpers.ensure_trailing_slash(path) <NEW_LINE> self.name = name <NEW_LINE> full_path = path_helpers.join_paths([path, name]) <NEW_LINE> base_path = conf.BaseConfig.FILES_BASE_PATH <NEW_LINE> if conf.BaseConfig.VIRTUAL_PATH == '': <NEW_LINE> <INDENT> self.href = full_path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.href = path_helpers.join_paths([conf.BaseConfig.VIRTUAL_PATH, full_path]) <NEW_LINE> <DEDENT> self.isdir = os.path.isdir(path_helpers.join_paths([base_path, full_path])) <NEW_LINE> if self.isdir: <NEW_LINE> <INDENT> self.size = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.size = os.path.getsize(path_helpers.join_paths([base_path, full_path])) <NEW_LINE> <DEDENT> self.icon = self.get_file_icon() <NEW_LINE> <DEDENT> def get_file_icon(self): <NEW_LINE> <INDENT> if self.isdir: <NEW_LINE> <INDENT> return icon_registry.directory_icon <NEW_LINE> <DEDENT> extension = self.name.split('.')[-1] <NEW_LINE> if extension in icon_registry.registry: <NEW_LINE> <INDENT> return icon_registry.registry[extension] <NEW_LINE> <DEDENT> return icon_registry.base_file_icon
Represents a file, will track size, file type ect
62599054adb09d7d5dc0ba7d
class Operator(object): <NEW_LINE> <INDENT> def __init__(self, name, version, cmd_cmpl, cmd_run, extensions): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.version = version <NEW_LINE> self.cmd_cmpl = cmd_cmpl <NEW_LINE> self.cmd_run = cmd_run <NEW_LINE> self.extensions = frozenset(extensions) <NEW_LINE> <DEDENT> def replace(self, filename): <NEW_LINE> <INDENT> name, ext = os.path.splitext(filename) <NEW_LINE> self.cmd_cmpl = self.cmd_cmpl.replace('FILENAME', name) <NEW_LINE> self.cmd_cmpl = self.cmd_cmpl.replace('FILE', filename) <NEW_LINE> self.cmd_cmpl = self.cmd_cmpl.replace('EXT', ext) <NEW_LINE> self.cmd_run = self.cmd_run.replace('FILENAME', name) <NEW_LINE> self.cmd_run = self.cmd_run.replace('FILE', filename) <NEW_LINE> self.cmd_run = self.cmd_run.replace('EXT', ext) <NEW_LINE> <DEDENT> def revert(self, filename): <NEW_LINE> <INDENT> name, ext = os.path.splitext(filename) <NEW_LINE> self.cmd_cmpl = self.cmd_cmpl.replace(name, 'FILENAME') <NEW_LINE> self.cmd_cmpl = self.cmd_cmpl.replace(filename, 'FILE') <NEW_LINE> self.cmd_cmpl = self.cmd_cmpl.replace(ext, 'EXT') <NEW_LINE> self.cmd_run = self.cmd_run.replace(name, 'FILENAME') <NEW_LINE> self.cmd_run = self.cmd_run.replace(filename, 'FILE') <NEW_LINE> self.cmd_run = self.cmd_run.replace(ext, 'EXT') <NEW_LINE> <DEDENT> def run(self, filename, specified_input): <NEW_LINE> <INDENT> _, ext = os.path.splitext(filename) <NEW_LINE> if ext: <NEW_LINE> <INDENT> if ext in self.extensions: <NEW_LINE> <INDENT> if self.cmd_cmpl: <NEW_LINE> <INDENT> self.replace(filename) <NEW_LINE> logging.debug('Compilation command:', self.cmd_cmpl) <NEW_LINE> Popen(self.cmd_cmpl, shell=True).wait() <NEW_LINE> self.revert(filename) <NEW_LINE> <DEDENT> self.replace(filename) <NEW_LINE> build = '' <NEW_LINE> build += self.cmd_run <NEW_LINE> logging.debug('Build command: {}'.format(build)) <NEW_LINE> process = Popen(build, shell=True, stdout=PIPE, stdin=PIPE, stderr=sys.stderr) <NEW_LINE> program_out = process. communicate(input=specified_input.encode())[0].decode() <NEW_LINE> program_out = program_out.strip() <NEW_LINE> return program_out <NEW_LINE> process.wait() <NEW_LINE> self.revert(filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.error('Extension not supported') <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logging.error('No specified file extension') <NEW_LINE> return None <NEW_LINE> <DEDENT> return None
Represents an operator which can be used to compile and run programs. Note: When passing file extensions to this class, they must have a leading `.` character (no backticks). Note: When passing compiler/interpreter commands to this class, make sure that they will be able to execute on your system! Args: name: The name of the compiler/interpreter we will interface with. version: The version of the aforementioned compiler/interpreter. cmd_cmpl: The command to compile a given program (if applicable). cmd_run: The command to run a given program. extensions: File extensions of the specific program we are targeting.
62599054d7e4931a7ef3d590
class Server: <NEW_LINE> <INDENT> def __init__(self, lean_exec_path, lean_path): <NEW_LINE> <INDENT> self.proc = subprocess.Popen([lean_exec_path, "-j0", "--server"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, bufsize=1, env={'LEAN_PATH': lean_path}) <NEW_LINE> self.seq_num = 0 <NEW_LINE> <DEDENT> def sync(self, filename): <NEW_LINE> <INDENT> self.seq_num += 1 <NEW_LINE> s = f'{{"seq_num": {self.seq_num}, "command": "sync", "file_name": "{filename}"}}\n' <NEW_LINE> self.proc.stdin.write(s) <NEW_LINE> self.proc.stdout.readline() <NEW_LINE> <DEDENT> def info(self, filename, line, col): <NEW_LINE> <INDENT> self.seq_num += 1 <NEW_LINE> s = f'{{"seq_num": {self.seq_num}, "command":"info", ' f'"file_name": "{filename}", ' f'"line": {line},"column":{col}}}\n' <NEW_LINE> self.proc.stdin.write(s) <NEW_LINE> ret = json.loads(self.proc.stdout.readline().rstrip()) <NEW_LINE> if 'record' in ret: <NEW_LINE> <INDENT> return ret['record']['state'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise LeanError(ret)
Very rough interface around the Lean server. Will work only if nothing bad happens/
6259905499cbb53fe68323fd
class StateValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> UNKNOWN = 0 <NEW_LINE> CREATING = 1 <NEW_LINE> RUNNING = 2 <NEW_LINE> ERROR = 3 <NEW_LINE> DELETING = 4 <NEW_LINE> UPDATING = 5
Output only. The cluster's state. Values: UNKNOWN: The cluster state is unknown. CREATING: The cluster is being created and set up. It is not ready for use. RUNNING: The cluster is currently running and healthy. It is ready for use. ERROR: The cluster encountered an error. It is not ready for use. DELETING: The cluster is being deleted. It cannot be used. UPDATING: The cluster is being updated. It continues to accept and process jobs.
6259905407f4c71912bb094d
class Arguments: <NEW_LINE> <INDENT> linkID = graphene.Int()
Corpo da requisição
62599054be8e80087fbc0594
class RemoveUserFromCohortTestCase(CohortViewsTestCase): <NEW_LINE> <INDENT> def request_remove_user_from_cohort(self, username, cohort): <NEW_LINE> <INDENT> if username is not None: <NEW_LINE> <INDENT> request = RequestFactory().post("dummy_url", {"username": username}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request = RequestFactory().post("dummy_url") <NEW_LINE> <DEDENT> request.user = self.staff_user <NEW_LINE> response = remove_user_from_cohort(request, six.text_type(self.course.id), cohort.id) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> return json.loads(response.content.decode('utf-8')) <NEW_LINE> <DEDENT> def verify_removed_user_from_cohort(self, username, response_dict, cohort, expected_error_msg=None): <NEW_LINE> <INDENT> if expected_error_msg is None: <NEW_LINE> <INDENT> self.assertTrue(response_dict.get("success")) <NEW_LINE> self.assertIsNone(response_dict.get("msg")) <NEW_LINE> self.assertFalse(self._user_in_cohort(username, cohort)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertFalse(response_dict.get("success")) <NEW_LINE> self.assertEqual(response_dict.get("msg"), expected_error_msg) <NEW_LINE> <DEDENT> <DEDENT> def test_non_staff(self): <NEW_LINE> <INDENT> cohort = CohortFactory(course_id=self.course.id, users=[]) <NEW_LINE> self._verify_non_staff_cannot_access( remove_user_from_cohort, "POST", [six.text_type(self.course.id), cohort.id] ) <NEW_LINE> <DEDENT> def test_no_username_given(self): <NEW_LINE> <INDENT> cohort = CohortFactory(course_id=self.course.id, users=[]) <NEW_LINE> response_dict = self.request_remove_user_from_cohort(None, cohort) <NEW_LINE> self.verify_removed_user_from_cohort( None, response_dict, cohort, expected_error_msg='No username specified' ) <NEW_LINE> <DEDENT> def test_user_does_not_exist(self): <NEW_LINE> <INDENT> username = "bogus" <NEW_LINE> cohort = CohortFactory(course_id=self.course.id, users=[]) <NEW_LINE> response_dict = self.request_remove_user_from_cohort( username, cohort ) <NEW_LINE> self.verify_removed_user_from_cohort( username, response_dict, cohort, expected_error_msg=u'No user \'{0}\''.format(username) ) <NEW_LINE> <DEDENT> def test_can_remove_user_not_in_cohort(self): <NEW_LINE> <INDENT> user = UserFactory() <NEW_LINE> cohort = CohortFactory(course_id=self.course.id, users=[]) <NEW_LINE> response_dict = self.request_remove_user_from_cohort(user.username, cohort) <NEW_LINE> self.verify_removed_user_from_cohort(user.username, response_dict, cohort) <NEW_LINE> <DEDENT> def test_can_remove_user_from_cohort(self): <NEW_LINE> <INDENT> user = UserFactory() <NEW_LINE> cohort = CohortFactory(course_id=self.course.id, users=[user]) <NEW_LINE> response_dict = self.request_remove_user_from_cohort(user.username, cohort) <NEW_LINE> self.verify_removed_user_from_cohort(user.username, response_dict, cohort)
Tests the `remove_user_from_cohort` view.
62599054e76e3b2f99fd9f11
class SaveError(Error): <NEW_LINE> <INDENT> pass
An attempt to save a page with changed interwiki has failed.
625990543c8af77a43b689c9
class DahuaEventThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive, events: list, channel: int): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.hass = hass <NEW_LINE> self.stopped = threading.Event() <NEW_LINE> self.on_receive = on_receive <NEW_LINE> self.client = client <NEW_LINE> self.events = events <NEW_LINE> self.started = False <NEW_LINE> self.channel = channel <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.started = True <NEW_LINE> _LOGGER.info("Starting DahuaEventThread") <NEW_LINE> while True: <NEW_LINE> <INDENT> if not self.started: <NEW_LINE> <INDENT> _LOGGER.debug("Exiting DahuaEventThread") <NEW_LINE> return <NEW_LINE> <DEDENT> coro = self.client.stream_events(self.on_receive, self.events, self.channel) <NEW_LINE> future = asyncio.run_coroutine_threadsafe(coro, self.hass.loop) <NEW_LINE> start_time = int(time.time()) <NEW_LINE> try: <NEW_LINE> <INDENT> future.result() <NEW_LINE> <DEDENT> except asyncio.TimeoutError as ex: <NEW_LINE> <INDENT> _LOGGER.warning("TimeoutError connecting to camera") <NEW_LINE> future.cancel() <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> _LOGGER.debug("%s", ex) <NEW_LINE> <DEDENT> if not self.started: <NEW_LINE> <INDENT> _LOGGER.debug("Exiting DahuaEventThread") <NEW_LINE> return <NEW_LINE> <DEDENT> end_time = int(time.time()) <NEW_LINE> if (end_time - start_time) < 10: <NEW_LINE> <INDENT> time.sleep(60) <NEW_LINE> <DEDENT> _LOGGER.debug("reconnecting to camera's event stream...") <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self.started: <NEW_LINE> <INDENT> _LOGGER.info("Stopping DahuaEventThread") <NEW_LINE> self.stopped.set() <NEW_LINE> self.started = False
Connects to device and subscribes to events. Mainly to capture motion detection events.
625990540c0af96317c577e9
class _CommandFemElementFluid1D(CommandManager): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(_CommandFemElementFluid1D, self).__init__() <NEW_LINE> self.resources = {'Pixmap': 'fem-fluid-section', 'MenuText': QtCore.QT_TRANSLATE_NOOP("FEM_ElementFluid1D", "Fluid section for 1D flow"), 'Accel': "C, B", 'ToolTip': QtCore.QT_TRANSLATE_NOOP("FEM_ElementFluid1D", "Creates a FEM fluid section for 1D flow")} <NEW_LINE> self.is_active = 'with_analysis' <NEW_LINE> <DEDENT> def Activated(self): <NEW_LINE> <INDENT> FreeCAD.ActiveDocument.openTransaction("Create FemElementFluid1D") <NEW_LINE> FreeCADGui.addModule("ObjectsFem") <NEW_LINE> FreeCADGui.doCommand("FemGui.getActiveAnalysis().addObject(ObjectsFem.makeElementFluid1D(FreeCAD.ActiveDocument))") <NEW_LINE> FreeCADGui.doCommand("FreeCADGui.ActiveDocument.setEdit(FreeCAD.ActiveDocument.ActiveObject.Name)") <NEW_LINE> FreeCADGui.Selection.clearSelection() <NEW_LINE> FreeCAD.ActiveDocument.recompute()
The FEM_ElementFluid1D command definition
62599054379a373c97d9a537
class IMappingZone(components.Interface): <NEW_LINE> <INDENT> pass
A zone which consists of a map of domain names to record information. @type records: mapping @ivar records: An object mapping lower-cased domain names to lists of L{twisted.protocols.dns.IRecord} objects.
62599054379a373c97d9a538
class Contact(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> name = models.CharField(max_length=30) <NEW_LINE> phone_regex = RegexValidator( regex=r'\+?1?\d{9,15}$', message="Phone number must be entered in the format: +999999999. Up to 15 digits allowed." ) <NEW_LINE> phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) <NEW_LINE> email = models.EmailField(unique=False) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '{} contact of {}'.format(self.name, self.user.username)
Contact model.
62599054baa26c4b54d507b6
class LinkRsData(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'LinkRsData' <NEW_LINE> id = db.Column(db.Integer, primary_key=True, autoincrement=True) <NEW_LINE> resource_set_id = db.Column(db.Integer, db.ForeignKey('ResourceSet.id'), nullable=False) <NEW_LINE> categories_id = db.Column(db.Integer, db.ForeignKey('Categories.id'), nullable=False) <NEW_LINE> resource_set = db.relationship('ResourceSet') <NEW_LINE> categories = db.relationship('Categories') <NEW_LINE> def __init__(self, internal_rs_id, category_id): <NEW_LINE> <INDENT> self.resource_set_id = internal_rs_id <NEW_LINE> self.categories_id = category_id
Link resource set with categories
62599054fff4ab517ebced36
class PreviewFile(db.Model, BaseMixin, SerializerMixin): <NEW_LINE> <INDENT> name = db.Column(db.String(250)) <NEW_LINE> original_name = db.Column(db.String(250)) <NEW_LINE> revision = db.Column(db.Integer(), default=1) <NEW_LINE> position = db.Column(db.Integer(), default=1) <NEW_LINE> extension = db.Column(db.String(6)) <NEW_LINE> description = db.Column(db.Text()) <NEW_LINE> path = db.Column(db.String(400)) <NEW_LINE> source = db.Column(db.String(40)) <NEW_LINE> file_size = db.Column(db.Integer(), default=0) <NEW_LINE> status = db.Column(ChoiceType(STATUSES), default="processing") <NEW_LINE> validation_status = db.Column( ChoiceType(VALIDATION_STATUSES), default="neutral" ) <NEW_LINE> annotations = db.Column(JSONB) <NEW_LINE> task_id = db.Column( UUIDType(binary=False), db.ForeignKey("task.id"), index=True ) <NEW_LINE> person_id = db.Column(UUIDType(binary=False), db.ForeignKey("person.id")) <NEW_LINE> source_file_id = db.Column( UUIDType(binary=False), db.ForeignKey("output_file.id") ) <NEW_LINE> __table_args__ = ( db.UniqueConstraint("name", "task_id", "revision", name="preview_uc"), ) <NEW_LINE> shotgun_id = db.Column(db.Integer, unique=True) <NEW_LINE> is_movie = db.Column(db.Boolean, default=False) <NEW_LINE> url = db.Column(db.String(600)) <NEW_LINE> uploaded_movie_url = db.Column(db.String(600)) <NEW_LINE> uploaded_movie_name = db.Column(db.String(150)) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<PreviewFile %s>" % self.id <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_from_import(cls, data): <NEW_LINE> <INDENT> del data["type"] <NEW_LINE> if "comments" in data: <NEW_LINE> <INDENT> del data["comments"] <NEW_LINE> <DEDENT> previous_data = cls.get(data["id"]) <NEW_LINE> if "status" not in data or data["status"] == None: <NEW_LINE> <INDENT> data["status"] = "ready" <NEW_LINE> <DEDENT> if previous_data is None: <NEW_LINE> <INDENT> return (cls.create(**data), False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> previous_data.update(data) <NEW_LINE> return (previous_data, True)
Describes a file which is aimed at being reviewed. It is not a publication neither a working file.
625990543eb6a72ae038bb73
class sshConnecter(sshBaseConnecter): <NEW_LINE> <INDENT> def __init__(self,ip,userName,passWord): <NEW_LINE> <INDENT> super().__init__(ip,userName,passWord) <NEW_LINE> self.sh=paramiko.SSHClient() <NEW_LINE> <DEDENT> def ssh_get_connect(self,retryList): <NEW_LINE> <INDENT> self.sh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) <NEW_LINE> try: <NEW_LINE> <INDENT> self.sh.connect(self.ip, self.port, self.userName, self.passWord,timeout=3) <NEW_LINE> self.conStatus=True <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> err=str(e) <NEW_LINE> if 'Authentication failed' in err: <NEW_LINE> <INDENT> print('身份验证失败,重试密码中......') <NEW_LINE> <DEDENT> elif err: <NEW_LINE> <INDENT> loggerForSsh.error("%s连接超时,目标主机未开或网络出现问题"%self.ip) <NEW_LINE> return 0 <NEW_LINE> <DEDENT> <DEDENT> if self.conStatus is False: <NEW_LINE> <INDENT> for rePass in retryList: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.sh.connect(self.ip, self.port, self.userName, rePass) <NEW_LINE> self.conStatus=True <NEW_LINE> self.passWord = rePass <NEW_LINE> wd = reader() <NEW_LINE> wd.alterIp(self.ip,rePass) <NEW_LINE> break <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> err2=str(e) <NEW_LINE> if err2 != '': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if self.conStatus is False: <NEW_LINE> <INDENT> loggerForSsh.error('%s试完所有密码未能连接成功'%self.ip) <NEW_LINE> <DEDENT> <DEDENT> def ssh_do(self,cmds): <NEW_LINE> <INDENT> finalResult=[] <NEW_LINE> for m in cmds: <NEW_LINE> <INDENT> eachResult='' <NEW_LINE> stdin, stdout, stderr = self.sh.exec_command(m) <NEW_LINE> out = stdout.readlines() <NEW_LINE> for o in out: <NEW_LINE> <INDENT> eachResult = eachResult+o <NEW_LINE> <DEDENT> finalResult.append(eachResult) <NEW_LINE> <DEDENT> return finalResult
建立连接,并完成一系列操作
6259905494891a1f408ba180
class Vault(Backend): <NEW_LINE> <INDENT> _client = None <NEW_LINE> config_defaults = { 'vault_url': 'http://localhost:8200', } <NEW_LINE> def __init__(self, name: str, backend_config: dict, *args, **kwargs): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> config = {**self.config_defaults, **backend_config} <NEW_LINE> self.url = config['vault_url'] <NEW_LINE> self.token = config['vault_token'] <NEW_LINE> self.path = config['vault_path'] <NEW_LINE> <DEDENT> def _get_client(self): <NEW_LINE> <INDENT> if self._client is None: <NEW_LINE> <INDENT> self._client = hvac.Client(url=self.url, token=self.token) <NEW_LINE> <DEDENT> return self._client <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> client = self._get_client() <NEW_LINE> secret = client.secrets.kv.read_secret_version(path=self.path) <NEW_LINE> return secret['data']['data'][key]
Only KV2 is currently supported, token auth only.
62599054adb09d7d5dc0ba7f
class COORD(Structure): <NEW_LINE> <INDENT> _fields_ = [ ("x", short), ("y", short) ]
XY coordinate structure from "wincon.h"
6259905410dbd63aa1c720f6
class KeyboardConstants(Constants): <NEW_LINE> <INDENT> _virtualKeyCodes=VirtualKeyCodes() <NEW_LINE> if sys.platform == 'win32': <NEW_LINE> <INDENT> _asciiKeyCodes=AsciiConstants() <NEW_LINE> <DEDENT> if sys.platform == 'darwin': <NEW_LINE> <INDENT> _unicodeChars=UnicodeChars() <NEW_LINE> _ansiKeyCodes=AnsiKeyCodes() <NEW_LINE> <DEDENT> _modifierCodes=ModifierKeyCodes() <NEW_LINE> @classmethod <NEW_LINE> def getName(cls,id): <NEW_LINE> <INDENT> return cls._names.get(id,None) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _getKeyName(cls,keyEvent): <NEW_LINE> <INDENT> vcode_name = KeyboardConstants._virtualKeyCodes.getName(keyEvent.KeyID) <NEW_LINE> if vcode_name: <NEW_LINE> <INDENT> if vcode_name.startswith('VK_NUMPAD'): <NEW_LINE> <INDENT> return 'num_%s'%(vcode_name[9:].lower()) <NEW_LINE> <DEDENT> return vcode_name[3:].lower() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> phkey = keyEvent.Key.lower() <NEW_LINE> if phkey.startswith('numpad'): <NEW_LINE> <INDENT> phkey = 'num_%s'%(phkey.Key[6:]) <NEW_LINE> <DEDENT> return phkey <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def _getKeyNameAndModsForEvent(cls,keyEvent): <NEW_LINE> <INDENT> return cls._getKeyName(keyEvent), cls.getModifiersForEvent(keyEvent) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def getModifiersForEvent(cls,event): <NEW_LINE> <INDENT> return cls._modifierCodes2Labels(event.Modifiers) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _modifierCodes2Labels(cls,mods): <NEW_LINE> <INDENT> if mods == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> modconstants=cls._modifierCodes <NEW_LINE> modNameList=[] <NEW_LINE> for k in modconstants._keys: <NEW_LINE> <INDENT> mc=modconstants._names[k] <NEW_LINE> if mods&k == k: <NEW_LINE> <INDENT> modNameList.append(mc) <NEW_LINE> mods=mods-k <NEW_LINE> if mods==0: <NEW_LINE> <INDENT> return modNameList <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return modNameList
Stores internal windows hook constants including hook types, mappings from virtual keycode name to value and value to name, and event type value to name.
6259905471ff763f4b5e8cc3
class SearchLanguageSetting(EnumStringSetting): <NEW_LINE> <INDENT> def parse(self, data): <NEW_LINE> <INDENT> if data not in self.choices and data != self.value: <NEW_LINE> <INDENT> data = str(data).replace('_', '-') <NEW_LINE> lang = data.split('-')[0] <NEW_LINE> if data in self.choices: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif lang in self.choices: <NEW_LINE> <INDENT> data = lang <NEW_LINE> <DEDENT> elif data == 'nb-NO': <NEW_LINE> <INDENT> data = 'no-NO' <NEW_LINE> <DEDENT> elif data == 'ar-XA': <NEW_LINE> <INDENT> data = 'ar-SA' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = self.value <NEW_LINE> <DEDENT> <DEDENT> self.value = data
Available choices may change, so user's value may not be in choices anymore
625990548da39b475be04700
class HuffmanNode(object): <NEW_LINE> <INDENT> __slots__ = ['l', 'r'] <NEW_LINE> def __init__(self, l, r): <NEW_LINE> <INDENT> self.l = l <NEW_LINE> self.r = r <NEW_LINE> <DEDENT> def __getitem__(self, b): <NEW_LINE> <INDENT> return self.r if b else self.l <NEW_LINE> <DEDENT> def __setitem__(self, b, val): <NEW_LINE> <INDENT> if b: <NEW_LINE> <INDENT> self.r = val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.l = val <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '({}, {})'.format(self.l, self.r)
HuffmanNode is an entry of the binary tree used for encoding/decoding HPack compressed HTTP/2 headers
62599054f7d966606f749342
class EisensteinExtensionFieldCappedRelative(EisensteinExtensionGeneric, pAdicCappedRelativeFieldGeneric): <NEW_LINE> <INDENT> def __init__(self, prepoly, poly, prec, halt, print_mode, shift_seed, names, implementation='NTL'): <NEW_LINE> <INDENT> unram_prec = (prec + poly.degree() - 1) // poly.degree() <NEW_LINE> ntl_poly = ntl_ZZ_pX([a.lift() for a in poly.list()], poly.base_ring().prime()**unram_prec) <NEW_LINE> shift_poly = ntl_ZZ_pX([a.lift() for a in shift_seed.list()], shift_seed.base_ring().prime()**unram_prec) <NEW_LINE> if unram_prec <= 30: <NEW_LINE> <INDENT> self.prime_pow = PowComputer_ext_maker(poly.base_ring().prime(), unram_prec, unram_prec, prec, True, ntl_poly, "small", "e", shift_poly) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.prime_pow = PowComputer_ext_maker(poly.base_ring().prime(), 30, unram_prec, prec, True, ntl_poly, "big", "e", shift_poly) <NEW_LINE> <DEDENT> self._shift_seed = shift_seed <NEW_LINE> self._pre_poly = prepoly <NEW_LINE> self._implementation = implementation <NEW_LINE> EisensteinExtensionGeneric.__init__(self, poly, prec, print_mode, names, pAdicZZpXCRElement)
TESTS:: sage: R = Qp(3, 10000, print_pos=False); S.<x> = ZZ[]; f = x^3 + 9*x - 3 sage: W.<w> = R.ext(f); W == loads(dumps(W)) True
625990542ae34c7f260ac5fb
class AddClass(View): <NEW_LINE> <INDENT> def get(self, request, pk): <NEW_LINE> <INDENT> _class = Class.objects.get(pk=pk) <NEW_LINE> new_student = Student(user=request.user, name_of_class=_class.name) <NEW_LINE> new_student.save() <NEW_LINE> _class.students.add(new_student) <NEW_LINE> schedule = Schedule.objects.get(user=request.user) <NEW_LINE> schedule.classes.add(_class) <NEW_LINE> _class.taken += 1 <NEW_LINE> _class.save() <NEW_LINE> return redirect('dashboard')
Allow a student to enroll in a class
625990544e4d56256637391c
class _SystemHealthStorySet(story.StorySet): <NEW_LINE> <INDENT> PLATFORM = NotImplemented <NEW_LINE> def __init__(self, take_memory_measurement=True): <NEW_LINE> <INDENT> super(_SystemHealthStorySet, self).__init__( archive_data_file=('../data/memory_system_health_%s.json' % self.PLATFORM), cloud_storage_bucket=story.PARTNER_BUCKET) <NEW_LINE> for story_class in single_page_stories.IterAllStoryClasses(): <NEW_LINE> <INDENT> if self.PLATFORM not in story_class.SUPPORTED_PLATFORMS: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.AddStory(story_class(self, take_memory_measurement))
User stories for the System Health Plan. See https://goo.gl/Jek2NL.
62599054097d151d1a2c2587
class Version(Model): <NEW_LINE> <INDENT> def __init__(self, api=None, insite=None): <NEW_LINE> <INDENT> self.openapi_types = { 'api': str, 'insite': str } <NEW_LINE> self.attribute_map = { 'api': 'api', 'insite': 'insite' } <NEW_LINE> self._api = api <NEW_LINE> self._insite = insite <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt) -> 'Version': <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def api(self): <NEW_LINE> <INDENT> return self._api <NEW_LINE> <DEDENT> @api.setter <NEW_LINE> def api(self, api): <NEW_LINE> <INDENT> if api is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `api`, must not be `None`") <NEW_LINE> <DEDENT> self._api = api <NEW_LINE> <DEDENT> @property <NEW_LINE> def insite(self): <NEW_LINE> <INDENT> return self._insite <NEW_LINE> <DEDENT> @insite.setter <NEW_LINE> def insite(self, insite): <NEW_LINE> <INDENT> if insite is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `insite`, must not be `None`") <NEW_LINE> <DEDENT> self._insite = insite
NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually.
62599054b5575c28eb713756
@command(project_cmds) <NEW_LINE> class project_terminate(_ProjectAction): <NEW_LINE> <INDENT> action = 'terminate'
Terminate a project (special privileges needed)
6259905476e4537e8c3f0aa0
class LearningRateScheduler(TrainingCallback): <NEW_LINE> <INDENT> def __init__(self, learning_rates): <NEW_LINE> <INDENT> assert callable(learning_rates) or isinstance(learning_rates, collections.abc.Sequence) <NEW_LINE> if callable(learning_rates): <NEW_LINE> <INDENT> self.learning_rates = learning_rates <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.learning_rates = lambda epoch: learning_rates[epoch] <NEW_LINE> <DEDENT> super().__init__() <NEW_LINE> <DEDENT> def after_iteration(self, model, epoch, evals_log): <NEW_LINE> <INDENT> model.set_param('learning_rate', self.learning_rates(epoch))
Callback function for scheduling learning rate. .. versionadded:: 1.3.0 Parameters ---------- learning_rates : callable/collections.Sequence If it's a callable object, then it should accept an integer parameter `epoch` and returns the corresponding learning rate. Otherwise it should be a sequence like list or tuple with the same size of boosting rounds.
625990540a50d4780f706849
class ContinuedFraction_real(ContinuedFraction_base): <NEW_LINE> <INDENT> def __init__(self, x): <NEW_LINE> <INDENT> ContinuedFraction_base.__init__(self) <NEW_LINE> self._x0 = x <NEW_LINE> from .real_mpfi import RealIntervalField <NEW_LINE> self._xa = RealIntervalField(53)(self._x0) <NEW_LINE> self._quotients = [] <NEW_LINE> <DEDENT> def length(self): <NEW_LINE> <INDENT> return Infinity <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> raise ValueError("the length is infinite!") <NEW_LINE> <DEDENT> def __richcmp__(self, other, op): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.value() == other.value(): <NEW_LINE> <INDENT> return rich_to_bool(op, 0) <NEW_LINE> <DEDENT> if self.value() - other.value() > 0: <NEW_LINE> <INDENT> return rich_to_bool(op, 1) <NEW_LINE> <DEDENT> return rich_to_bool(op, -1) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return ContinuedFraction_base.__richcmp__(self, other, op) <NEW_LINE> <DEDENT> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return '[%d; ' % self.quotient(0) + ', '.join(str(self.quotient(i)) for i in range(1,20)) + ", ...]" <NEW_LINE> <DEDENT> def quotient(self, n): <NEW_LINE> <INDENT> x = self._xa <NEW_LINE> if len(self._quotients) > 1 and n >= len(self._quotients) and self._quotients[-1] == 0: <NEW_LINE> <INDENT> return ZZ_0 <NEW_LINE> <DEDENT> for k in range(len(self._quotients), n+1): <NEW_LINE> <INDENT> if x.lower().is_infinity() or x.upper().is_infinity() or x.lower().floor() != x.upper().floor(): <NEW_LINE> <INDENT> orbit = lambda z: -(self.denominator(k-2)*z-self.numerator(k-2))/(self.denominator(k-1)*z-self.numerator(k-1)) <NEW_LINE> x = x.parent()(orbit(self._x0)) <NEW_LINE> while x.lower().is_infinity() or x.upper().is_infinity() or x.lower().floor() != x.upper().floor(): <NEW_LINE> <INDENT> from .real_mpfi import RealIntervalField <NEW_LINE> self._prec = x.parent().prec() + 100 <NEW_LINE> x = RealIntervalField(self._prec)(orbit(self._x0)) <NEW_LINE> <DEDENT> <DEDENT> self._quotients.append(x.unique_floor()) <NEW_LINE> x = (x-x.unique_floor()) <NEW_LINE> if not x: <NEW_LINE> <INDENT> self._quotients.append(ZZ_0) <NEW_LINE> return ZZ_0 <NEW_LINE> <DEDENT> x = ~x <NEW_LINE> <DEDENT> self._xa = x <NEW_LINE> return self._quotients[n] <NEW_LINE> <DEDENT> def value(self): <NEW_LINE> <INDENT> return self._x0
Continued fraction of a real (exact) number. This class simply wraps a real number into an attribute (that can be accessed through the method :meth:`value`). The number is assumed to be irrational. EXAMPLES:: sage: cf = continued_fraction(pi) sage: cf [3; 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, 1, 1, 2, 2, 2, 2, ...] sage: cf.value() pi sage: cf = continued_fraction(e) sage: cf [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, 1, 1, ...] sage: cf.value() e
62599054596a89723612903a
class UserProfile(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length=255, unique=True) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> objects = UserProfileManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = ['name'] <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email
Database model for users in the system
62599054e5267d203ee6ce04
class DataService(): <NEW_LINE> <INDENT> def __init__(self, conf_path): <NEW_LINE> <INDENT> self.__client = MongoClient(HOST, PORT) <NEW_LINE> self.conf = Configuration() <NEW_LINE> self.base_conf = self.conf.read_configuration(conf_path) <NEW_LINE> <DEDENT> def getConfigJson(self): <NEW_LINE> <INDENT> return self.base_conf <NEW_LINE> <DEDENT> def getAllResult(self, cityId): <NEW_LINE> <INDENT> attrs = ['green', 'sky', 'road', 'building'] <NEW_LINE> client = MongoClient(HOST, PORT) <NEW_LINE> db = client[DBNAME] <NEW_LINE> collection_name = None <NEW_LINE> confs = self.base_conf['conf'] <NEW_LINE> for item in confs: <NEW_LINE> <INDENT> if item['id'] == cityId: <NEW_LINE> <INDENT> collection_name = item['result_c'] <NEW_LINE> <DEDENT> <DEDENT> collection = db[collection_name] <NEW_LINE> resut_arr = [] <NEW_LINE> start_time = time.time() <NEW_LINE> for record in collection.find(): <NEW_LINE> <INDENT> lo = record['location'][0] <NEW_LINE> la = record['location'][1] <NEW_LINE> max_num = -1 <NEW_LINE> max_attr = None <NEW_LINE> for attr in attrs: <NEW_LINE> <INDENT> if max_num < record[attr]: <NEW_LINE> <INDENT> max_num = record[attr] <NEW_LINE> max_attr = attr <NEW_LINE> <DEDENT> <DEDENT> resut_arr.append([la, lo, max_attr]) <NEW_LINE> <DEDENT> print(time.time() - start_time) <NEW_LINE> return resut_arr <NEW_LINE> <DEDENT> def getAllResultImprove(self, cityId): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> client = MongoClient(HOST, PORT) <NEW_LINE> db = client[DBNAME] <NEW_LINE> collection_name = None <NEW_LINE> confs = self.base_conf['conf'] <NEW_LINE> for item in confs: <NEW_LINE> <INDENT> if item['id'] == cityId: <NEW_LINE> <INDENT> collection_name = item['overall_result'] <NEW_LINE> <DEDENT> <DEDENT> collection = db[collection_name] <NEW_LINE> split_result = [] <NEW_LINE> for record in collection.find(): <NEW_LINE> <INDENT> del record['_id'] <NEW_LINE> split_result += record['seg'] <NEW_LINE> <DEDENT> print(time.time() - start_time) <NEW_LINE> return split_result <NEW_LINE> <DEDENT> def queryRegion(self, cityId, positions): <NEW_LINE> <INDENT> if len(positions) <= 2: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> region_boundaries = [[position['lng'], position['lat']] for position in positions] <NEW_LINE> client = MongoClient(HOST, PORT) <NEW_LINE> db = client[DBNAME] <NEW_LINE> collection_name = None <NEW_LINE> confs = self.base_conf['conf'] <NEW_LINE> for item in confs: <NEW_LINE> <INDENT> if item['id'] == cityId: <NEW_LINE> <INDENT> collection_name = item['result_c'] <NEW_LINE> <DEDENT> <DEDENT> collection = db[collection_name] <NEW_LINE> resut_arr = [] <NEW_LINE> start_time = time.time() <NEW_LINE> for record in collection.find({ 'location': { '$geoWithin': { '$polygon': region_boundaries } } }): <NEW_LINE> <INDENT> del record['_id'] <NEW_LINE> resut_arr.append(record) <NEW_LINE> <DEDENT> print(time.time() - start_time) <NEW_LINE> return { 'records': resut_arr, 'region': positions, 'cityId': cityId }
The function collection to query data from the Database
625990548e7ae83300eea5ad
class Account(rlp.Serializable): <NEW_LINE> <INDENT> fields = [ ('nonce', big_endian_int), ('balance', big_endian_int), ('storage_root', trie_root), ('code_hash', hash32) ] <NEW_LINE> def __init__(self, nonce: int=0, balance: int=0, storage_root: bytes=BLANK_ROOT_HASH, code_hash: bytes=EMPTY_SHA3, **kwargs: Any) -> None: <NEW_LINE> <INDENT> super().__init__(nonce, balance, storage_root, code_hash, **kwargs) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return ( f"Account(nonce={self.nonce}, balance={self.balance}, " f"storage_root=0x{self.storage_root.hex()}, " f"code_hash=0x{self.code_hash.hex()})" )
RLP object for accounts.
6259905482261d6c52730954
class _DatabaseFixtures(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.prescribing = [ { "month": str(p.processing_date), "practice": p.practice_id, "bnf_code": p.presentation_code, "items": p.total_items, "quantity": p.quantity, "net_cost": p.net_cost or 0, "actual_cost": p.actual_cost, "bnf_name": None, "sha": None, "pcn": None, "pct": None, "stp": None, "regional_team": None, } for p in Prescription.objects.all() ] <NEW_LINE> self.presentations = [ { "bnf_code": p.bnf_code, "name": p.name, "is_generic": p.is_generic, "adq_per_quantity": p.adq_per_quantity, } for p in Presentation.objects.all() ] <NEW_LINE> self.practices = [ { "code": p.code, "status_code": p.status_code, "name": p.name, "address1": None, "address2": None, "address3": None, "address4": None, "address5": None, "postcode": None, "location": None, "ccg_id": None, "setting": None, "close_date": None, "join_provider_date": None, "leave_provider_date": None, "open_date": None, } for p in Practice.objects.all() ] <NEW_LINE> self.practice_statistics = [ { "month": str(ps.date), "practice": ps.practice_id, "pct_id": None, "astro_pu_items": ps.astro_pu_items, "astro_pu_cost": ps.astro_pu_cost, "star_pu": json.dumps(ps.star_pu), "total_list_size": ps.total_list_size, "male_0_4": ps.male_0_4, "female_0_4": ps.female_0_4, "male_5_14": ps.male_5_14, "female_5_14": ps.female_5_14, "male_15_24": ps.male_15_24, "female_15_24": ps.female_15_24, "male_25_34": ps.male_25_34, "female_25_34": ps.female_25_34, "male_35_44": ps.male_35_44, "female_35_44": ps.female_35_44, "male_45_54": ps.male_45_54, "female_45_54": ps.female_45_54, "male_55_64": ps.male_55_64, "female_55_64": ps.female_55_64, "male_65_74": ps.male_65_74, "female_65_74": ps.female_65_74, "male_75_plus": ps.male_75_plus, "female_75_plus": ps.female_75_plus, } for ps in PracticeStatistics.objects.all() ] <NEW_LINE> self.bnf_map = []
Presents the same attributes as a DataFactory instance but with data read from the database (where it was presumably loaded from test fixtures), rather than randomly generated.
625990544e696a045264e8ad
class AlertPage(BasePage): <NEW_LINE> <INDENT> top_logo_frame_locator = (By.NAME, "TopLogo") <NEW_LINE> exit_button_locator = (By.ID, "mtLogout") <NEW_LINE> header_frame_locator = (By.NAME, "Header") <NEW_LINE> def switch_to_alert(self): <NEW_LINE> <INDENT> self.switch_to_window() <NEW_LINE> self.accept_ssl_certificate() <NEW_LINE> <DEDENT> def get_alert_page_title(self): <NEW_LINE> <INDENT> self.wait().until(EC.presence_of_element_located(self.top_logo_frame_locator), 'top logo frame not found before specified time') <NEW_LINE> return self.page_title() <NEW_LINE> <DEDENT> def close_alert_page(self): <NEW_LINE> <INDENT> self.close_browser() <NEW_LINE> self.switch_to_default_window() <NEW_LINE> <DEDENT> def click_exit_button(self): <NEW_LINE> <INDENT> self.switch_to_frame(self.header_frame_locator) <NEW_LINE> self.click_element(self.exit_button_locator) <NEW_LINE> self.switch_to_default_window()
Contains Alert UI page locators Switch to alert function Get alert page title function Close alert page function Click exit button function
62599054d7e4931a7ef3d594
class DefaultInsertionMarker(QGraphicsItem): <NEW_LINE> <INDENT> COLOR = QColor(70, 70, 70) <NEW_LINE> def boundingRect(self): <NEW_LINE> <INDENT> return QRectF(0, 0, 400, 15) <NEW_LINE> <DEDENT> def paint(self, painter, option, widget=None): <NEW_LINE> <INDENT> painter.fillRect(self.boundingRect(), self.COLOR)
Simple rectangle to act like a maker on the insertion effect.
62599054cb5e8a47e493cc12
class Label(object): <NEW_LINE> <INDENT> def __init__(self, pos=-1, lx=-1, ly=-1, text=""): <NEW_LINE> <INDENT> self.pos = pos <NEW_LINE> self.lx = lx <NEW_LINE> self.ly = ly <NEW_LINE> self.text = text
Auxiliary class. Just holds information about a label in :class:`RulerCtrl`.
62599054a17c0f6771d5d62c
class Learner(IRC.Bot): <NEW_LINE> <INDENT> def __init__(self, parent, target, username, server): <NEW_LINE> <INDENT> IRC.Bot.__init__(self, parent, target, username, server) <NEW_LINE> <DEDENT> def user_pubmsg(self, message): <NEW_LINE> <INDENT> if message.content != "!stop_learning": <NEW_LINE> <INDENT> if not message.content[-1:] == "?": <NEW_LINE> <INDENT> for user in self.parent.users: <NEW_LINE> <INDENT> message.content=message.content.replace(str(user), "") <NEW_LINE> <DEDENT> self.parent.kb.append(message.content) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ret = "OK learning ended" <NEW_LINE> if message.msg_type == "PRIVMSG": <NEW_LINE> <INDENT> self.reply(content=ret, msg_type=message.msg_type, target=message.pseudo) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.reply(content=ret, msg_type=message.msg_type, target=message.target) <NEW_LINE> <DEDENT> self.stop() <NEW_LINE> <DEDENT> <DEDENT> def user_privmsg(self, message): <NEW_LINE> <INDENT> self.user_pubmsg(message)
learning class for bot (mostly troll)
62599054b7558d58954649b5
class ResnetGenerator(nn.Module): <NEW_LINE> <INDENT> def __init__( self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm3d, use_dropout=False, n_blocks=6, padding_type="reflect", ): <NEW_LINE> <INDENT> assert n_blocks >= 0 <NEW_LINE> super(ResnetGenerator, self).__init__() <NEW_LINE> if type(norm_layer) == functools.partial: <NEW_LINE> <INDENT> use_bias = norm_layer.func == nn.InstanceNorm3d <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> use_bias = norm_layer == nn.InstanceNorm3d <NEW_LINE> <DEDENT> model = [ nn.ReplicationPad3d(3), nn.Conv3d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias), norm_layer(ngf), nn.ReLU(True), ] <NEW_LINE> n_downsampling = 2 <NEW_LINE> for i in range(n_downsampling): <NEW_LINE> <INDENT> mult = 2 ** i <NEW_LINE> model += [ nn.Conv3d( ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias, ), norm_layer(ngf * mult * 2), nn.ReLU(True), ] <NEW_LINE> <DEDENT> mult = 2 ** n_downsampling <NEW_LINE> for i in range(n_blocks): <NEW_LINE> <INDENT> model += [ ResnetBlock( ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias, ) ] <NEW_LINE> <DEDENT> for i in range(n_downsampling): <NEW_LINE> <INDENT> mult = 2 ** (n_downsampling - i) <NEW_LINE> model += [ nn.ConvTranspose3d( ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=use_bias, ), norm_layer(int(ngf * mult / 2)), nn.ReLU(True), ] <NEW_LINE> <DEDENT> model += [nn.ReplicationPad3d(3)] <NEW_LINE> model += [nn.Conv3d(ngf, output_nc, kernel_size=7, padding=0)] <NEW_LINE> model += [nn.Tanh()] <NEW_LINE> self.model = nn.Sequential(*model) <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> return self.model(input)
Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)
625990547d847024c075d8f1
class ArticleList(models.Model): <NEW_LINE> <INDENT> article_id = models.CharField('ID', primary_key=True, max_length=100) <NEW_LINE> article_title = models.CharField('文章标题', max_length=100) <NEW_LINE> article_url = models.URLField('文章URL') <NEW_LINE> article_user = models.CharField('作者', max_length=100) <NEW_LINE> article_user_url = models.URLField('作者URL') <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['-created', ] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.article_title <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.article_title
文章概要信息
62599054dc8b845886d54ada
class Heroes(AbstractResponse): <NEW_LINE> <INDENT> def parse_response(self): <NEW_LINE> <INDENT> self.assign_subkey('result') <NEW_LINE> self['heroes'] = [LocalizedHero(h) for h in self.get('heroes', [])]
:any:`get_heroes` response object Attributes ---------- heroes : list(LocalizedHero) List of localized hero information count : int Number of heroes returned
6259905476d4e153a661dd06
class LogFormatter(object): <NEW_LINE> <INDENT> def crawled(self, request, response, spider): <NEW_LINE> <INDENT> flags = ' %s' % str(response.flags) if response.flags else '' <NEW_LINE> return { 'format': CRAWLEDFMT, 'status': response.status, 'request': request, 'referer': request.headers.get('Referer'), 'flags': flags, } <NEW_LINE> <DEDENT> def scraped(self, item, response, spider): <NEW_LINE> <INDENT> src = response.getErrorMessage() if isinstance(response, Failure) else response <NEW_LINE> return { 'format': SCRAPEDFMT, 'src': src, 'item': item, } <NEW_LINE> <DEDENT> def dropped(self, item, exception, response, spider): <NEW_LINE> <INDENT> return { 'format': DROPPEDFMT, 'exception': exception, 'item': item, }
Class for generating log messages for different actions. All methods must return a plain string which doesn't include the log level or the timestamp
625990543539df3088ecd7bc
class MovieReview: <NEW_LINE> <INDENT> def __init__(self, title=None, year=None, text=None, publication_date=None): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.year = year <NEW_LINE> self.text = text <NEW_LINE> self.publication_date=publication_date <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_review_by_title_and_year(cls, title, year): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_movie_review(cls, movie): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"'{self.title}' ({self.year}): {self.text}"
Class representing a movie review. Attributes: title: String representing the title of movie reviewed. year: Integer representing the release year of the movie. text: String containing summary of movie review. publication_date: String representing date review was published.
6259905499cbb53fe6832401
class MongoDebugPanel(DebugPanel): <NEW_LINE> <INDENT> name = 'MongoDB' <NEW_LINE> has_content = True <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(MongoDebugPanel, self).__init__(*args, **kwargs) <NEW_LINE> self.jinja_env.loader = ChoiceLoader([self.jinja_env.loader, PackageLoader('flask.ext.mongoengine', 'templates')]) <NEW_LINE> operation_tracker.install_tracker() <NEW_LINE> <DEDENT> def process_request(self, request): <NEW_LINE> <INDENT> operation_tracker.reset() <NEW_LINE> <DEDENT> def nav_title(self): <NEW_LINE> <INDENT> return 'MongoDB' <NEW_LINE> <DEDENT> def nav_subtitle(self): <NEW_LINE> <INDENT> attrs = ['queries', 'inserts', 'updates', 'removes'] <NEW_LINE> ops = sum(sum((1 for o in getattr(operation_tracker, a) if not o['internal'])) for a in attrs) <NEW_LINE> total_time = sum(sum(o['time'] for o in getattr(operation_tracker, a)) for a in attrs) <NEW_LINE> return '{0} operations in {1:.2f}ms'.format(ops, total_time) <NEW_LINE> <DEDENT> def title(self): <NEW_LINE> <INDENT> return 'MongoDB Operations' <NEW_LINE> <DEDENT> def url(self): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> def content(self): <NEW_LINE> <INDENT> context = self.context.copy() <NEW_LINE> context['queries'] = operation_tracker.queries <NEW_LINE> context['inserts'] = operation_tracker.inserts <NEW_LINE> context['updates'] = operation_tracker.updates <NEW_LINE> context['removes'] = operation_tracker.removes <NEW_LINE> context['slow_query_limit'] = current_app.config.get('MONGO_DEBUG_PANEL_SLOW_QUERY_LIMIT', 100) <NEW_LINE> return self.render('panels/mongo-panel.html', context)
Panel that shows information about MongoDB operations (including stack) Adapted from https://github.com/hmarr/django-debug-toolbar-mongo
62599054adb09d7d5dc0ba81
class Database: <NEW_LINE> <INDENT> @contextmanager <NEW_LINE> def cursor(self) -> Generator[Cursor, None, None]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def result(self, cursor: Cursor) -> Result: <NEW_LINE> <INDENT> raise NotImplementedError
Common facade for get DB services.
625990544e4d56256637391d
class Widget(QWidget): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> QWidget.__init__(self, parent) <NEW_LINE> l=QVBoxLayout(self) <NEW_LINE> self._tm=TableModel(self) <NEW_LINE> self._tv=TableView(self) <NEW_LINE> self._tv.setShowGrid(False) <NEW_LINE> self._tv.setAlternatingRowColors(True) <NEW_LINE> self._tv.setModel(self._tm) <NEW_LINE> for row in range(0, self._tm.rowCount()): <NEW_LINE> <INDENT> self._tv.openPersistentEditor(self._tm.index(row, 0)) <NEW_LINE> self._tv.openPersistentEditor(self._tm.index(row, 1)) <NEW_LINE> <DEDENT> l.addWidget(self._tv)
A simple test widget to contain and own the model and table.
62599054d99f1b3c44d06bb6
class ExcerptTranslationInlineForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = ExcerptTranslation <NEW_LINE> exclude = []
Formulaire inline des extraits
625990548a43f66fc4bf36a3
class Dictionary: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._root = {} <NEW_LINE> self._end = "_end" <NEW_LINE> <DEDENT> def _getLastNode(self, prefix): <NEW_LINE> <INDENT> prefix = prefix.lower() <NEW_LINE> cur_dict = self._root <NEW_LINE> for letter in prefix: <NEW_LINE> <INDENT> if letter in cur_dict: <NEW_LINE> <INDENT> cur_dict = cur_dict[letter] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> return cur_dict <NEW_LINE> <DEDENT> def addWords(self, words): <NEW_LINE> <INDENT> for word in words: <NEW_LINE> <INDENT> word = word.lower() <NEW_LINE> cur_dict = self._root <NEW_LINE> for letter in word: <NEW_LINE> <INDENT> cur_dict = cur_dict.setdefault(letter, {}) <NEW_LINE> <DEDENT> cur_dict[self._end] = self._end <NEW_LINE> <DEDENT> <DEDENT> def isWord(self, word): <NEW_LINE> <INDENT> last_node = self._getLastNode(word) <NEW_LINE> return (last_node is not None and self._end in last_node) <NEW_LINE> <DEDENT> def isPrefix(self, prefix): <NEW_LINE> <INDENT> last_node = self._getLastNode(prefix) <NEW_LINE> return (last_node is not None)
Implementation of a Dictionary using trie. Not case-sensitive.
625990544e4d56256637391e
class OwnerContextAdapter: <NEW_LINE> <INDENT> def __init__(self, owner): <NEW_LINE> <INDENT> self._owner = owner <NEW_LINE> self._owned_name = getattr(owner, "_owned_name", repr(owner)) <NEW_LINE> display_name = getattr(self, "_owned_name", type(self).__name__) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hold = [o for o in self._owner._ownables.values() if isinstance(o, RackMethod)] <NEW_LINE> notify.hold_owner_notifications(*hold) <NEW_LINE> cls = type(self._owner) <NEW_LINE> for opener in core.trace_methods(cls, "open", Owner)[::-1]: <NEW_LINE> <INDENT> opener(self._owner) <NEW_LINE> <DEDENT> getattr(self._owner, "_logger", util.logger).debug("opened") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> notify.allow_owner_notifications(*hold) <NEW_LINE> <DEDENT> <DEDENT> def __exit__(self, *exc_info): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> holds = [o for o in self._owner._ownables.values() if isinstance(o, RackMethod)] <NEW_LINE> notify.hold_owner_notifications(*holds) <NEW_LINE> cls = type(self._owner) <NEW_LINE> methods = core.trace_methods(cls, "close", Owner) <NEW_LINE> all_ex = [] <NEW_LINE> for closer in methods: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> closer(self._owner) <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> all_ex.append(sys.exc_info()) <NEW_LINE> <DEDENT> <DEDENT> for ex in all_ex[::-1]: <NEW_LINE> <INDENT> if ex[0] is not util.ThreadEndedByMaster: <NEW_LINE> <INDENT> depth = len(tuple(traceback.walk_tb(ex[2]))) <NEW_LINE> traceback.print_exception(*ex, limit=-(depth - 1)) <NEW_LINE> <DEDENT> <DEDENT> getattr(self._owner, "_logger", util.logger).debug("closed") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> notify.allow_owner_notifications(*holds) <NEW_LINE> if len(all_ex) > 0: <NEW_LINE> <INDENT> ex = util.ConcurrentException(f"multiple exceptions while closing {self}") <NEW_LINE> ex.thread_exceptions = all_ex <NEW_LINE> raise ex <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(self._owner) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return getattr(self._owner, "_owned_name", None) or repr(self)
transform calls to __enter__ -> open and __exit__ -> close. each will be called
62599054009cb60464d02a56
class BgColorTool (ColorTool): <NEW_LINE> <INDENT> def __init__(self, width, height, default): <NEW_LINE> <INDENT> self.icon = ColorTextImage(width, height, False, True) <NEW_LINE> self.icon.set_bg_color(default) <NEW_LINE> ColorTool.__init__(self, self.icon, default) <NEW_LINE> <DEDENT> def on_set_color(self, menu, color): <NEW_LINE> <INDENT> if color is None: <NEW_LINE> <INDENT> self.default_set = True <NEW_LINE> self.icon.set_bg_color(self.default) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.default_set = False <NEW_LINE> self.icon.set_bg_color(color) <NEW_LINE> <DEDENT> self.color = color <NEW_LINE> self.emit("set-color", color)
ToolItem for choosing the backgroundground color
62599054cad5886f8bdc5b0c
class ExampleGroupWithPromotes(Group): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ExampleGroupWithPromotes, self).__init__() <NEW_LINE> self.G2 = self.add('G2', Group()) <NEW_LINE> self.C1 = self.G2.add('C1', IndepVarComp('x', 5.), promotes=['x']) <NEW_LINE> self.G1 = self.G2.add('G1', Group(), promotes=['x']) <NEW_LINE> self.C2 = self.G1.add('C2', ExecComp('y=x*2.0',x=3.,y=5.5), promotes=['x']) <NEW_LINE> self.G3 = self.add('G3', Group(), promotes=['x']) <NEW_LINE> self.C3 = self.G3.add('C3', ExecComp('y=x*2.0',x=3.,y=5.5)) <NEW_LINE> self.C4 = self.G3.add('C4', ExecComp('y=x*2.0',x=3.,y=5.5), promotes=['x']) <NEW_LINE> self.connect('G2.G1.C2.y', 'G3.C3.x') <NEW_LINE> self.G3.connect('C3.y', 'x')
A nested `Group` with implicit connections for testing
62599054dd821e528d6da3f6
class CreditCard: <NEW_LINE> <INDENT> def __init__(self, customer, bank, acnt, limit): <NEW_LINE> <INDENT> self._customer = customer <NEW_LINE> self._bank = bank <NEW_LINE> self._account = acnt <NEW_LINE> self._limit = limit <NEW_LINE> self._balance = 0 <NEW_LINE> <DEDENT> def get_customer(self): <NEW_LINE> <INDENT> return self._customer <NEW_LINE> <DEDENT> def get_bank(self): <NEW_LINE> <INDENT> return self._bank <NEW_LINE> <DEDENT> def get_account(self): <NEW_LINE> <INDENT> return self._account <NEW_LINE> <DEDENT> def get_limit(self): <NEW_LINE> <INDENT> return self._limit <NEW_LINE> <DEDENT> def get_balance(self): <NEW_LINE> <INDENT> return self._balance <NEW_LINE> <DEDENT> def charge(self, price): <NEW_LINE> <INDENT> if price + self._balance > self._limit: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._balance += price <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> def make_payment(self, amount): <NEW_LINE> <INDENT> self._balance -= amount
A consumer credit card
62599054a8ecb0332587272e
class Scheduler(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def matches_share_opponents(match1, match2): <NEW_LINE> <INDENT> (match1_1, match1_2) = match1 <NEW_LINE> return (match1_1 in match2 or match1_2 in match2) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def find_unique_match(matches, rest): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> possibility = rest.pop(0) <NEW_LINE> for match in matches: <NEW_LINE> <INDENT> if Scheduler.matches_share_opponents(match, possibility): <NEW_LINE> <INDENT> possibility = None <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if possibility: <NEW_LINE> <INDENT> return possibility <NEW_LINE> <DEDENT> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise NoMatchFound <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def generate_schedule(self, try_once=False): <NEW_LINE> <INDENT> raise NotImplementedError
Base class for schedulers. This class includes general-purpose scheduler functionality.
6259905426068e7796d4de5f
@dataclasses.dataclass(frozen=True) <NEW_LINE> class Frame: <NEW_LINE> <INDENT> priority: pyuavcan.transport.Priority <NEW_LINE> transfer_id: int <NEW_LINE> index: int <NEW_LINE> end_of_transfer: bool <NEW_LINE> payload: memoryview <NEW_LINE> def __post_init__(self) -> None: <NEW_LINE> <INDENT> if not isinstance(self.priority, pyuavcan.transport.Priority): <NEW_LINE> <INDENT> raise TypeError(f"Invalid priority: {self.priority}") <NEW_LINE> <DEDENT> if self.transfer_id < 0: <NEW_LINE> <INDENT> raise ValueError(f"Invalid transfer-ID: {self.transfer_id}") <NEW_LINE> <DEDENT> if self.index < 0: <NEW_LINE> <INDENT> raise ValueError(f"Invalid frame index: {self.index}") <NEW_LINE> <DEDENT> if not isinstance(self.end_of_transfer, bool): <NEW_LINE> <INDENT> raise TypeError(f"Bad end of transfer flag: {type(self.end_of_transfer).__name__}") <NEW_LINE> <DEDENT> if not isinstance(self.payload, memoryview): <NEW_LINE> <INDENT> raise TypeError(f"Bad payload type: {type(self.payload).__name__}") <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def single_frame_transfer(self) -> bool: <NEW_LINE> <INDENT> return self.index == 0 and self.end_of_transfer <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> payload_length_limit = 100 <NEW_LINE> if len(self.payload) > payload_length_limit: <NEW_LINE> <INDENT> payload = bytes(self.payload[:payload_length_limit]).hex() + "..." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> payload = bytes(self.payload).hex() <NEW_LINE> <DEDENT> kwargs = {f.name: getattr(self, f.name) for f in dataclasses.fields(self)} <NEW_LINE> kwargs["priority"] = self.priority.name <NEW_LINE> kwargs["payload"] = payload <NEW_LINE> return pyuavcan.util.repr_attributes(self, **kwargs)
The base class of a high-overhead-transport frame. It is used with the common transport algorithms defined in this module. Concrete transport implementations should make their transport-specific frame dataclasses inherit from this class. Derived types are recommended to not override ``__repr__()``.
62599054be383301e0254d18