code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class GeneratingCommand(SearchCommand): <NEW_LINE> <INDENT> def generate(self): <NEW_LINE> <INDENT> raise NotImplementedError('GeneratingCommand.generate(self, records)') <NEW_LINE> <DEDENT> def _prepare(self, argv, input_file): <NEW_LINE> <INDENT> ConfigurationSettings = type(self).ConfigurationSettings <NEW_LINE> argv = argv[2:] <NEW_LINE> return ConfigurationSettings, self.generate, argv, 'ANY' <NEW_LINE> <DEDENT> def _execute(self, operation, reader, writer): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for record in operation(): <NEW_LINE> <INDENT> writer.writerow(record) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.logger.error(e) <NEW_LINE> <DEDENT> <DEDENT> class ConfigurationSettings(SearchCommand.ConfigurationSettings): <NEW_LINE> <INDENT> @property <NEW_LINE> def generating(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def generates_timeorder(self): <NEW_LINE> <INDENT> return type(self)._generates_timeorder <NEW_LINE> <DEDENT> _generates_timeorder = False <NEW_LINE> @property <NEW_LINE> def local(self): <NEW_LINE> <INDENT> return type(self)._local <NEW_LINE> <DEDENT> _local = False <NEW_LINE> @property <NEW_LINE> def retainsevents(self): <NEW_LINE> <INDENT> return type(self)._retainsevents <NEW_LINE> <DEDENT> _retainsevents = True <NEW_LINE> @property <NEW_LINE> def streaming(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fix_up(cls, command): <NEW_LINE> <INDENT> if command.generate == GeneratingCommand.generate: <NEW_LINE> <INDENT> raise AttributeError('No GeneratingCommand.generate override') <NEW_LINE> <DEDENT> return | Generates events based on command arguments.
Generating commands receive no input and must be the first command on a
pipeline. By default Splunk will run your command locally on a search head:
:<source lang=python>@Configuration()</source>
You can change the default behavior by configuring your generating command
for event streaming:
:<source lang=python>@Configuration(streaming=True)</source>
Splunk will then run your command locally on a search head and/or remotely
on one or more indexers.
You can tell Splunk to run your streaming-enabled generating command locally
on a search head, never remotely on indexers:
:<source lang=python>@Configuration(local=True, streaming=True)</source>
If your generating command produces event records in time order, you must
tell Splunk to ensure correct behavior:
:<source lang=python>@Configuration(generates_timeorder=True)</source> | 6259907ddc8b845886d5501d |
class DocumentForm(forms.ModelForm): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> can_create_tags = kwargs.pop('can_create_tags', False) <NEW_LINE> can_archive = kwargs.pop('can_archive', False) <NEW_LINE> super(DocumentForm, self).__init__(*args, **kwargs) <NEW_LINE> tags_field = self.fields['tags'] <NEW_LINE> tags_field.widget.can_create_tags = can_create_tags <NEW_LINE> if not can_archive: <NEW_LINE> <INDENT> del self.fields['is_archived'] <NEW_LINE> <DEDENT> <DEDENT> title = StrippedCharField( min_length=5, max_length=255, widget=forms.TextInput(), label=_lazy(u'Title:'), help_text=_lazy(u'Title of article'), error_messages={'required': TITLE_REQUIRED, 'min_length': TITLE_SHORT, 'max_length': TITLE_LONG}) <NEW_LINE> slug = StrippedCharField( min_length=3, max_length=255, widget=forms.TextInput(), label=_lazy(u'Slug:'), help_text=_lazy(u'Article URL'), error_messages={'required': SLUG_REQUIRED, 'min_length': SLUG_SHORT, 'max_length': SLUG_LONG}) <NEW_LINE> products = forms.MultipleChoiceField( label=_lazy(u'Relevant to:'), choices=PRODUCTS, initial=[PRODUCTS[0][0]], required=False, widget=forms.CheckboxSelectMultiple()) <NEW_LINE> is_localizable = forms.BooleanField( initial=True, label=_lazy(u'Allow translations:'), required=False) <NEW_LINE> is_archived = forms.BooleanField( label=_lazy(u'Obsolete:'), required=False) <NEW_LINE> allow_discussion = forms.BooleanField( label=_lazy(u'Allow discussion on this article?'), initial=True, required=False) <NEW_LINE> category = forms.ChoiceField( choices=CATEGORIES, required=False, label=_lazy(u'Category:'), help_text=_lazy(u'Type of article')) <NEW_LINE> tags = tag_forms.TagField( required=False, label=_lazy(u'Topics:'), help_text=_lazy(u'Popular articles in each topic are displayed on the ' 'front page')) <NEW_LINE> locale = forms.CharField(widget=forms.HiddenInput()) <NEW_LINE> def clean_slug(self): <NEW_LINE> <INDENT> slug = self.cleaned_data['slug'] <NEW_LINE> if not re.compile(r'^[^/^\+^\?]+$').match(slug): <NEW_LINE> <INDENT> raise forms.ValidationError(SLUG_INVALID) <NEW_LINE> <DEDENT> return slug <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Document <NEW_LINE> fields = ('title', 'slug', 'category', 'is_localizable', 'products', 'tags', 'locale', 'is_archived', 'allow_discussion') <NEW_LINE> <DEDENT> def save(self, parent_doc, **kwargs): <NEW_LINE> <INDENT> doc = super(DocumentForm, self).save(commit=False, **kwargs) <NEW_LINE> doc.parent = parent_doc <NEW_LINE> doc.save() <NEW_LINE> self.save_m2m() <NEW_LINE> if not parent_doc: <NEW_LINE> <INDENT> prods = self.cleaned_data['products'] <NEW_LINE> doc.tags.add(*prods) <NEW_LINE> doc.tags.remove(*[p for p in PRODUCT_TAGS if p not in prods]) <NEW_LINE> <DEDENT> return doc | Form to create/edit a document. | 6259907da8370b77170f1e32 |
class gffObject(object): <NEW_LINE> <INDENT> def __init__(self, seqid, source, type, start, end, score, strand, phase, attributes): <NEW_LINE> <INDENT> self._seqid = seqid <NEW_LINE> self._source = source <NEW_LINE> self._type = type <NEW_LINE> self._start = start <NEW_LINE> self._end = end <NEW_LINE> self._score = score <NEW_LINE> self._strand = strand <NEW_LINE> self._phase = phase <NEW_LINE> self._attributes = attributes <NEW_LINE> self._attrib_dct = {} <NEW_LINE> pattern = re.compile(r"""(\w+)=([\w:.,]+)""") <NEW_LINE> tmp = pattern.findall(self._attributes) <NEW_LINE> for a in tmp: <NEW_LINE> <INDENT> key, val = (a) <NEW_LINE> self._attrib_dct[key]=val <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def seqid(self): <NEW_LINE> <INDENT> return self._seqid <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> return self._source <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @property <NEW_LINE> def start(self): <NEW_LINE> <INDENT> return self._start <NEW_LINE> <DEDENT> @property <NEW_LINE> def end(self): <NEW_LINE> <INDENT> return self._end <NEW_LINE> <DEDENT> @property <NEW_LINE> def score(self): <NEW_LINE> <INDENT> return self._score <NEW_LINE> <DEDENT> @property <NEW_LINE> def strand(self): <NEW_LINE> <INDENT> return self._strand <NEW_LINE> <DEDENT> @property <NEW_LINE> def phase(self): <NEW_LINE> <INDENT> return self._phase <NEW_LINE> <DEDENT> @property <NEW_LINE> def attributes(self): <NEW_LINE> <INDENT> return self._attributes <NEW_LINE> <DEDENT> @property <NEW_LINE> def attrib_dct(self): <NEW_LINE> <INDENT> return self._attrib_dct <NEW_LINE> <DEDENT> def toGFF3line(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getParents(self): <NEW_LINE> <INDENT> pass | "seqid" (gff column 1) landmark for coordinate system
"source" (gff column 2) source db/program etc
"type" (gff column 3) term from the Sequence Ontology
"start"(gff column 4) relative to the landmark seqid
"end" (gff column 5) 1-based integer coordinates
"score" (gff column 6) float
"strand" (gff column 7) +/i/./? for positive/negative/none/unknown strand (relative to the landmark)
"phase" (gff column 8) 0/1/2 for "CDS" features, start rel. to reading frame
"attributes" (gff column 9) list of feature attributes
in the format tag=value.
Multiple tag=value pairs are separated by semicolons.
ID, Name, Alias, Parent, Target, Gap, Derives_from, Note,
Dbxref, Ontology_term, Is_circular
Parent: groups exons into transcripts, transcripts into genes etc.
A feature may have multiple parents.
Target: Indicates the target of a nucleotide-to-nucleotide
or protein-to-nucleotide alignment.
The format of the value is "target_id start end [strand]",
where strand is optional and may be "+" or "-".
Gap: The alignment of the feature to the target if the two
are not collinear (e.g. contain gaps).
The alignment format is taken from the CIGAR format described
in the Exonerate documentation.
(http://cvsweb.sanger.ac.uk/cgi-bin/cvsweb.cgi/exonerate?cvsroot=Ensembl). ("THE GAP ATTRIBUTE")
Parent, the Alias, Note, DBxref and Ontology_term attributes can have multiple values. | 6259907d99fddb7c1ca63b09 |
class Config(dict): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> dict.__init__(self, *args, **kwargs) <NEW_LINE> <DEDENT> def load_file(self, file_name): <NEW_LINE> <INDENT> log.info("loading config singleton from file {n}".format(n=file_name)) <NEW_LINE> data = yaml.load(open(file_name, 'r')) <NEW_LINE> if not isinstance(data, dict): <NEW_LINE> <INDENT> raise Exception("config file not parsed correctly") <NEW_LINE> <DEDENT> log.info("objects in config {objs}".format(objs=data)) <NEW_LINE> deep_merge(self, data) | Configuration dictionary | 6259907e7d847024c075de40 |
class FieldInputMixin(FieldInput, Win): <NEW_LINE> <INDENT> def __init__(self, field): <NEW_LINE> <INDENT> FieldInput.__init__(self, field) <NEW_LINE> Win.__init__(self) <NEW_LINE> <DEDENT> def resize(self, height, width, y, x): <NEW_LINE> <INDENT> self._resize(height, width, y, x) <NEW_LINE> <DEDENT> def set_color(self, color): <NEW_LINE> <INDENT> self.color = color <NEW_LINE> self.refresh() | Mix both FieldInput and Win | 6259907ea8370b77170f1e33 |
class LegacySubContributionMapping(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'legacy_subcontribution_id_map' <NEW_LINE> __table_args__ = {'schema': 'events'} <NEW_LINE> event_id = db.Column( db.Integer, db.ForeignKey('events.events.id'), primary_key=True, autoincrement=False ) <NEW_LINE> legacy_contribution_id = db.Column( db.String, primary_key=True ) <NEW_LINE> legacy_subcontribution_id = db.Column( db.String, primary_key=True ) <NEW_LINE> subcontribution_id = db.Column( db.Integer, db.ForeignKey('events.subcontributions.id', name='fk_legacy_subcontribution_id_map_subcontribution'), nullable=False, index=True ) <NEW_LINE> event = db.relationship( 'Event', lazy=True, backref=db.backref( 'legacy_subcontribution_mappings', cascade='all, delete-orphan', lazy='dynamic' ) ) <NEW_LINE> subcontribution = db.relationship( 'SubContribution', lazy=False, backref=db.backref( 'legacy_mapping', cascade='all, delete-orphan', uselist=False, lazy=True ) ) <NEW_LINE> @return_ascii <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return format_repr(self, 'event_id', 'legacy_contribution_id', 'legacy_subcontribution_id', 'subcontribution_id') | Legacy subcontribution id mapping
Legacy subcontributions had ids unique only within their event
and contribution. This table maps those ids to the new globally
unique subcontribution id. | 6259907e7047854f46340e18 |
class Discriminator(nn.Module): <NEW_LINE> <INDENT> def __init__(self, image_size=256, down_size=64): <NEW_LINE> <INDENT> super(Discriminator, self).__init__() <NEW_LINE> self.image_size = image_size <NEW_LINE> self.down_size = down_size <NEW_LINE> self.num_down = int(math.log2(self.image_size // self.down_size)) <NEW_LINE> self.conv_in = nn.Sequential( spectral_norm(nn.Conv2d(3, 32, kernel_size=3, padding=1)), InstanceNorm(32), nn.LeakyReLU(negative_slope=0.1), ) <NEW_LINE> feat_dim = 32 <NEW_LINE> down_layers = [] <NEW_LINE> for i in range(self.num_down): <NEW_LINE> <INDENT> down_layers.append(nn.Sequential( spectral_norm(nn.Conv2d(feat_dim, feat_dim * 2, kernel_size=3, stride=2, padding=1)), InstanceNorm(feat_dim * 2), nn.LeakyReLU(negative_slope=0.1), spectral_norm(nn.Conv2d(feat_dim * 2, feat_dim * 4, kernel_size=3, stride=1, padding=1)), InstanceNorm(feat_dim * 4), nn.LeakyReLU(negative_slope=0.1) )) <NEW_LINE> feat_dim = feat_dim * 4 <NEW_LINE> <DEDENT> self.conv_down = nn.Sequential(*down_layers) <NEW_LINE> self.conv_out = nn.Sequential( spectral_norm(nn.Conv2d(feat_dim, feat_dim, kernel_size=3, padding=1)), InstanceNorm(feat_dim), nn.LeakyReLU(negative_slope=0.1), nn.Conv2d(feat_dim, 1, kernel_size=1, padding=0) ) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> out = self.conv_in(x) <NEW_LINE> out = self.conv_down(out) <NEW_LINE> out = self.conv_out(out) <NEW_LINE> return out | CartoonGAN Discriminator | 6259907e8a349b6b43687cc0 |
class NSNitroNserrMaxSvcEntityBindingOnSvcgroup(NSNitroBaseErrors): <NEW_LINE> <INDENT> pass | Nitro error code 435
Maximum services bound to service group exceeded | 6259907e56ac1b37e6303a14 |
class ClassDetailView(DetailView): <NEW_LINE> <INDENT> queryset = Class.objects.annotate(count_students=Count('students')) <NEW_LINE> template_name = "myschool/myclass_detail.html" <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(ClassDetailView, self).get_context_data(**kwargs) <NEW_LINE> c = context['class'] <NEW_LINE> context['num_students'] = c.students.count <NEW_LINE> context['studentlist'] = c.students.all() <NEW_LINE> return context | show details of a specific class | 6259907ebe7bc26dc9252b87 |
class Task101Test(unittest.TestCase): <NEW_LINE> <INDENT> def test_this_year(self): <NEW_LINE> <INDENT> self.assertEqual(days_in_year(2015), 365) <NEW_LINE> <DEDENT> def test_leap_year(self): <NEW_LINE> <INDENT> self.assertEqual(days_in_year(2012), 366) <NEW_LINE> <DEDENT> def test_century_turn_non_leap(self): <NEW_LINE> <INDENT> self.assertEqual(days_in_year(1900), 365) <NEW_LINE> <DEDENT> def test_century_turn_leap(self): <NEW_LINE> <INDENT> self.assertEqual(days_in_year(2400), 366) <NEW_LINE> <DEDENT> def test_century_2000(self): <NEW_LINE> <INDENT> self.assertEqual(days_in_year(2000), 366) <NEW_LINE> <DEDENT> def test_some_year(self): <NEW_LINE> <INDENT> self.assertEqual(days_in_year(1977), 365) <NEW_LINE> <DEDENT> def test_other_year(self): <NEW_LINE> <INDENT> self.assertEqual(days_in_year(2040), 366) | Testy do zadania 101 | 6259907e3617ad0b5ee07bb1 |
class DXTestDocument(Item): <NEW_LINE> <INDENT> exclude_from_nav = False | A Dexterity based test type containing a set of standard fields. | 6259907eaad79263cf43021d |
class Compare(VyperNode): <NEW_LINE> <INDENT> __slots__ = ("left", "op", "right") <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(kwargs["ops"]) > 1 or len(kwargs["comparators"]) > 1: <NEW_LINE> <INDENT> _raise_syntax_exc("Cannot have a comparison with more than two elements", kwargs) <NEW_LINE> <DEDENT> kwargs["op"] = kwargs.pop("ops")[0] <NEW_LINE> kwargs["right"] = kwargs.pop("comparators")[0] <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def evaluate(self) -> VyperNode: <NEW_LINE> <INDENT> left, right = self.left, self.right <NEW_LINE> if not isinstance(left, Constant): <NEW_LINE> <INDENT> raise UnfoldableNode("Node contains invalid field(s) for evaluation") <NEW_LINE> <DEDENT> if isinstance(self.op, In): <NEW_LINE> <INDENT> if not isinstance(right, List): <NEW_LINE> <INDENT> raise UnfoldableNode("Node contains invalid field(s) for evaluation") <NEW_LINE> <DEDENT> if next((i for i in right.elements if not isinstance(i, Constant)), None): <NEW_LINE> <INDENT> raise UnfoldableNode("Node contains invalid field(s) for evaluation") <NEW_LINE> <DEDENT> if len(set([type(i) for i in right.elements])) > 1: <NEW_LINE> <INDENT> raise UnfoldableNode("List contains multiple literal types") <NEW_LINE> <DEDENT> value = self.op._op(left.value, [i.value for i in right.elements]) <NEW_LINE> return NameConstant.from_node(self, value=value) <NEW_LINE> <DEDENT> if not isinstance(left, type(right)): <NEW_LINE> <INDENT> raise UnfoldableNode("Cannot compare different literal types") <NEW_LINE> <DEDENT> if not isinstance(self.op, (Eq, NotEq)) and not isinstance(left, (Int, Decimal)): <NEW_LINE> <INDENT> raise TypeMismatch(f"Invalid literal types for {self.op.description} comparison", self) <NEW_LINE> <DEDENT> value = self.op._op(left.value, right.value) <NEW_LINE> return NameConstant.from_node(self, value=value) | A comparison of two values.
Attributes
----------
left : VyperNode
The left-hand value in the comparison.
op : VyperNode
The comparison operator.
right : VyperNode
The right-hand value in the comparison. | 6259907e099cdd3c6367612b |
class FabberClException(FabberException): <NEW_LINE> <INDENT> def __init__(self, stdout="", returncode=-1, outdir=None, log=""): <NEW_LINE> <INDENT> grabnext = False <NEW_LINE> msg = "" <NEW_LINE> for line in stdout.splitlines(): <NEW_LINE> <INDENT> if line == "": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif grabnext: <NEW_LINE> <INDENT> msg = line.strip() <NEW_LINE> grabnext = False <NEW_LINE> <DEDENT> elif "exception" in line.lower(): <NEW_LINE> <INDENT> grabnext = True <NEW_LINE> <DEDENT> <DEDENT> log = log <NEW_LINE> if outdir: <NEW_LINE> <INDENT> logfile = os.path.join(outdir, "logfile") <NEW_LINE> if os.path.exists(logfile): <NEW_LINE> <INDENT> with open(logfile, "r") as logfile: <NEW_LINE> <INDENT> log = logfile.read() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> FabberException.__init__(self, msg, returncode, log) <NEW_LINE> self.args = (stdout, returncode, None, log) | Exception originating from the command line
We try to read the logfile and also attempt to
determine the message from the stdout | 6259907e97e22403b383c964 |
class Array_opt(): <NEW_LINE> <INDENT> def __init__(self, gamma_tilt_deg=[]): <NEW_LINE> <INDENT> self.gamma_n, self.gamma_tilt_deg = [], gamma_tilt_deg <NEW_LINE> self.gamma_tilt_deg_diff, self.psi_n = [], [] <NEW_LINE> self.Gamma_aud, self.thr_dist = [], [] <NEW_LINE> self.num_iter = [] <NEW_LINE> self.lin_eq_n_psi_1, self.lin_eq_n_psi_2 = [], [] <NEW_LINE> self.x_fin_unitn_psi_1, self.x_fin_unitn_psi_2 = [], [] <NEW_LINE> self.y_fin_unitn_psi_1, self.y_fin_unitn_psi_2 = [], [] <NEW_LINE> self.seg_pos, self.seg_pos_start, self.seg_pos_stop = [], [], [] <NEW_LINE> self.fixed_angle = [0,0,0] <NEW_LINE> if self.gamma_tilt_deg != [] : self.gamma_n = self.gamma_tilt_deg*np.pi/180 <NEW_LINE> <DEDENT> def update_opt_array(self, x_c_n=None, y_c_n=None, **new_input): <NEW_LINE> <INDENT> for key, val in new_input.items(): <NEW_LINE> <INDENT> if hasattr(self, key): <NEW_LINE> <INDENT> setattr(self, key, val) <NEW_LINE> <DEDENT> <DEDENT> if np.all(x_c_n != None) and 'psi_n' in new_input.keys(): <NEW_LINE> <INDENT> self.lin_eq_n_psi_1 = y_c_n - np.tan(-self.gamma_n + self.psi_n) * x_c_n <NEW_LINE> self.x_fin_unitn_psi_1 = new_input['x_a_t_n'][:,0] <NEW_LINE> self.y_fin_unitn_psi_1 = np.tan(-self.gamma_n + self.psi_n) * self.x_fin_unitn_psi_1 + self.lin_eq_n_psi_1 <NEW_LINE> self.lin_eq_n_psi_2 = y_c_n - np.tan(-self.gamma_n - self.psi_n) * x_c_n <NEW_LINE> self.x_fin_unitn_psi_2 = new_input['x_a_b_n'][:,0] <NEW_LINE> self.y_fin_unitn_psi_2 = np.tan(-self.gamma_n - self.psi_n) * self.x_fin_unitn_psi_2 + self.lin_eq_n_psi_2 <NEW_LINE> self.seg_pos = new_input['x_a_c_n'] <NEW_LINE> self.seg_pos_start = new_input['x_a_t_n'] <NEW_LINE> self.seg_pos_stop = new_input['x_a_b_n'] | Class to create an object with optimized array data. | 6259907e67a9b606de5477d8 |
class ResetAndRunTestcaseTest(helpers.ExtendedTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.setup_fake_filesystem() <NEW_LINE> os.makedirs(main.CHROMIUM_OUT) <NEW_LINE> os.makedirs(main.CLUSTERFUZZ_CACHE_DIR) <NEW_LINE> helpers.patch(self, [ 'daemon.stackdriver_logging.send_run', 'daemon.main.update_auth_header', 'daemon.main.run_testcase', 'daemon.main.prepare_binary_and_get_version', 'daemon.main.read_logs', 'daemon.main.clean', 'daemon.main.sleep', ]) <NEW_LINE> self.mock.prepare_binary_and_get_version.return_value = '0.2.2rc10' <NEW_LINE> self.mock.run_testcase.return_value = 'run_testcase' <NEW_LINE> self.mock.read_logs.return_value = 'some logs' <NEW_LINE> <DEDENT> def test_reset_run_testcase(self): <NEW_LINE> <INDENT> self.assertTrue(os.path.exists(main.CHROMIUM_OUT)) <NEW_LINE> self.assertTrue(os.path.exists(main.CLUSTERFUZZ_CACHE_DIR)) <NEW_LINE> main.reset_and_run_testcase(1234, 'sanity', 'master') <NEW_LINE> self.assertFalse(os.path.exists(main.CHROMIUM_OUT)) <NEW_LINE> self.assertFalse(os.path.exists(main.CLUSTERFUZZ_CACHE_DIR)) <NEW_LINE> self.assert_exact_calls( self.mock.update_auth_header, [mock.call()] * 2) <NEW_LINE> self.assert_exact_calls(self.mock.send_run, [ mock.call(1234, 'sanity', '0.2.2rc10', 'master', 'run_testcase', 'some logs', ''), mock.call(1234, 'sanity', '0.2.2rc10', 'master', 'run_testcase', 'some logs', '--current --skip-deps -i 20') ]) <NEW_LINE> self.assert_exact_calls( self.mock.prepare_binary_and_get_version, [mock.call('master')]) <NEW_LINE> self.mock.clean.assert_called_once_with() <NEW_LINE> self.assert_exact_calls(self.mock.sleep, [ mock.call('run_testcase'), mock.call('run_testcase')]) | Tests the reset_and_run_testcase method. | 6259907e656771135c48ad62 |
class PassivePlayer(Player): <NEW_LINE> <INDENT> def get_attack_areas(self, grid, match_state, *args, **kwargs): <NEW_LINE> <INDENT> return None | A lazy AI player that never attacks (for testing). | 6259907e7b180e01f3e49d97 |
class Host(object): <NEW_LINE> <INDENT> def __init__(self, authport=1812, acctport=1813, coaport=3799, dict=None): <NEW_LINE> <INDENT> self.dict = dict <NEW_LINE> self.authport = authport <NEW_LINE> self.acctport = acctport <NEW_LINE> self.coaport = coaport <NEW_LINE> <DEDENT> def CreatePacket(self, **args): <NEW_LINE> <INDENT> return packet.Packet(dict=self.dict, **args) <NEW_LINE> <DEDENT> def CreateAuthPacket(self, **args): <NEW_LINE> <INDENT> return packet.AuthPacket(dict=self.dict, **args) <NEW_LINE> <DEDENT> def CreateAcctPacket(self, **args): <NEW_LINE> <INDENT> return packet.AcctPacket(dict=self.dict, **args) <NEW_LINE> <DEDENT> def CreateCoAPacket(self, **args): <NEW_LINE> <INDENT> return packet.CoAPacket(dict=self.dict, **args) <NEW_LINE> <DEDENT> def SendPacket(self, fd, pkt): <NEW_LINE> <INDENT> fd.sendto(pkt.Packet(), pkt.source) <NEW_LINE> <DEDENT> def SendReplyPacket(self, fd, pkt): <NEW_LINE> <INDENT> fd.sendto(pkt.ReplyPacket(), pkt.source) | Generic RADIUS capable host.
:ivar dict: RADIUS dictionary
:type dict: pyrad.dictionary.Dictionary
:ivar authport: port to listen on for authentication packets
:type authport: integer
:ivar acctport: port to listen on for accounting packets
:type acctport: integer | 6259907e76e4537e8c3f0fe4 |
class CommandlineTest(VimivTestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.init_test(cls) <NEW_LINE> cls.search = cls.vimiv["commandline"].search <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.working_directory = os.getcwd() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> os.chdir(self.working_directory) <NEW_LINE> self.vimiv["library"].reload(os.getcwd()) | Command Line Tests. | 6259907e92d797404e38988e |
class QueryExternalContactListResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.PageData = None <NEW_LINE> self.NextCursor = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("PageData") is not None: <NEW_LINE> <INDENT> self.PageData = [] <NEW_LINE> for item in params.get("PageData"): <NEW_LINE> <INDENT> obj = ExternalContactSimpleInfo() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.PageData.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.NextCursor = params.get("NextCursor") <NEW_LINE> self.RequestId = params.get("RequestId") | QueryExternalContactList返回参数结构体
| 6259907edc8b845886d5501f |
class Client(Resource): <NEW_LINE> <INDENT> @jwt_required() <NEW_LINE> def get(self, name): <NEW_LINE> <INDENT> client = ClientModel.select(name) <NEW_LINE> if client: <NEW_LINE> <INDENT> return client.json(), 200 <NEW_LINE> <DEDENT> return {'message': 'Client not found'}, 404 <NEW_LINE> <DEDENT> @jwt_required() <NEW_LINE> def post(self, name): <NEW_LINE> <INDENT> if ClientModel.select(name): <NEW_LINE> <INDENT> return {'message': 'Client already exists'}, 400 <NEW_LINE> <DEDENT> client = ClientModel(name) <NEW_LINE> try: <NEW_LINE> <INDENT> client.save_to_db() <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> return {'message': 'Something went wrong'}, 500 <NEW_LINE> <DEDENT> return client.json(), 201 <NEW_LINE> <DEDENT> @jwt_required() <NEW_LINE> def delete(self, name): <NEW_LINE> <INDENT> client = ClientModel.select(name) <NEW_LINE> if client: <NEW_LINE> <INDENT> for request in client.requests: <NEW_LINE> <INDENT> request.delete_from_db() <NEW_LINE> <DEDENT> client.delete_from_db() <NEW_LINE> return {'message': 'Client deleted'}, 200 <NEW_LINE> <DEDENT> return {'message': 'Client not found'}, 404 | Client endpoint for url/client/<string:name> | 6259907e5fdd1c0f98e5f9e4 |
class MovingObject2D: <NEW_LINE> <INDENT> def __init__(self, initialPosition): <NEW_LINE> <INDENT> self.x = initialPosition[0] <NEW_LINE> self.y = initialPosition[1] <NEW_LINE> <DEDENT> def setPosition(self, newPosition): <NEW_LINE> <INDENT> self.x, self.y = newPosition <NEW_LINE> <DEDENT> def getPosition(self): <NEW_LINE> <INDENT> return self.x, self.y <NEW_LINE> <DEDENT> def getIntPosition(self): <NEW_LINE> <INDENT> return int(self.x), int(self.y) <NEW_LINE> <DEDENT> def move(self, speed): <NEW_LINE> <INDENT> self.x += speed[0] <NEW_LINE> self.y += speed[1] | I think pygame object do not support non integer positions so I made this
to make handle the positions. | 6259907e796e427e538501df |
class Movie(): <NEW_LINE> <INDENT> def __init__(self, movie_title, movie_year, movie_storyline, movie_thoughts, poster_image, trailer_youtube): <NEW_LINE> <INDENT> self.title = movie_title <NEW_LINE> self.year = movie_year <NEW_LINE> self.storyline = movie_storyline <NEW_LINE> self.thoughts = movie_thoughts <NEW_LINE> self.poster_image_url = poster_image <NEW_LINE> self.trailer_youtube_url = trailer_youtube <NEW_LINE> <DEDENT> def show_trailer(self): <NEW_LINE> <INDENT> webbrowser.open(self.trailer_youtube_url) | Create an instance of the class `Movie`.
Creates an instance of the class `Movie` which will be used in a
dynamically populated movie trailer website.
Args:
movie_title: A movie title
movie_year: The year the movie was made
movie_storyline: A short official summary of the movie from
IMDb
movie_thoughts: Some personal reflections on the movie
poster_image: A URL path to an image of the movie
trailer_youtube: A URL to the youtube trailer of the movie | 6259907e3d592f4c4edbc891 |
class CollisionMask(): <NEW_LINE> <INDENT> x = 0 <NEW_LINE> y = 0 <NEW_LINE> width = 0 <NEW_LINE> height = 0 <NEW_LINE> x_offset = 0 <NEW_LINE> y_offset = 0 <NEW_LINE> def __init__(self, width, height, x_offset, y_offset): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height <NEW_LINE> self.x_offset = x_offset <NEW_LINE> self.y_offset = y_offset <NEW_LINE> <DEDENT> def update(self, x, y): <NEW_LINE> <INDENT> self.x = x - self.x_offset <NEW_LINE> self.y = y - self.y_offset | This is a rectangle used for collision detection. | 6259907e4a966d76dd5f094b |
class PNGWidget(BaseWidget): <NEW_LINE> <INDENT> def __init__(self, run_dir_options, fig=None, output_widget=None, **kwargs): <NEW_LINE> <INDENT> BaseWidget.__init__(self, PNGMPL, run_dir_options, fig, output_widget, **kwargs) <NEW_LINE> <DEDENT> def _create_sim_dropdown(self, options): <NEW_LINE> <INDENT> sim_drop = widgets.Dropdown( description="Sims", options=options, value=None) <NEW_LINE> return sim_drop <NEW_LINE> <DEDENT> def _create_widgets_for_vis_args(self): <NEW_LINE> <INDENT> self.species = widgets.Dropdown(description="Species", options=["e"], value='e') <NEW_LINE> self.species_filter = widgets.Dropdown(description="Species_filter", options=['all'], value="all") <NEW_LINE> self.axis = widgets.Dropdown(description="Axis", options=["yx", "yz"], value="yx") <NEW_LINE> return {'species': self.species, 'species_filter': self.species_filter, 'axis': self.axis} | From within jupyter notebook this widget can be used in the following way:
%matplotlib widget
import matplotlib.pyplot as plt
plt.ioff() # deactivate instant plotting is necessary!
from picongpu.plugins.jupyter_widgets import PNGWidget
display(PNGWidget(run_dir_options="path/to/outputs")) | 6259907e5166f23b2e244e3d |
class CreditsPage(ScrollView): <NEW_LINE> <INDENT> pass | Credits ScrollView that autoscrolls through Credits.
Has a Back(Button) to reutrn you to MainMenu() when done. | 6259907e7cff6e4e811b74a5 |
@registries.ZIGBEE_CHANNEL_REGISTRY.register( measurement.CarbonMonoxideConcentration.cluster_id ) <NEW_LINE> class CarbonMonoxideConcentration(ZigbeeChannel): <NEW_LINE> <INDENT> REPORT_CONFIG = [ { "attr": "measured_value", "config": (REPORT_CONFIG_MIN_INT, REPORT_CONFIG_MAX_INT, 0.000001), } ] | Carbon Monoxide measurement channel. | 6259907eaad79263cf43021f |
class NIOVDE(NIO): <NEW_LINE> <INDENT> def __init__(self, hypervisor, control_file, local_file): <NEW_LINE> <INDENT> name = 'vde-{}'.format(uuid.uuid4()) <NEW_LINE> self._control_file = control_file <NEW_LINE> self._local_file = local_file <NEW_LINE> super().__init__(name, hypervisor) <NEW_LINE> <DEDENT> async def create(self): <NEW_LINE> <INDENT> await self._hypervisor.send("nio create_vde {name} {control} {local}".format(name=self._name, control=self._control_file, local=self._local_file)) <NEW_LINE> log.info("NIO VDE {name} created with control={control}, local={local}".format(name=self._name, control=self._control_file, local=self._local_file)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def control_file(self): <NEW_LINE> <INDENT> return self._control_file <NEW_LINE> <DEDENT> @property <NEW_LINE> def local_file(self): <NEW_LINE> <INDENT> return self._local_file <NEW_LINE> <DEDENT> def __json__(self): <NEW_LINE> <INDENT> return {"type": "nio_vde", "local_file": self._local_file, "control_file": self._control_file} | Dynamips VDE NIO.
:param hypervisor: Dynamips hypervisor instance
:param control_file: VDE control filename
:param local_file: VDE local filename | 6259907e71ff763f4b5e9212 |
class RecordCommandTestCase(BaseCommandTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(RecordCommandTestCase, self).setUp() <NEW_LINE> self.record_cmd = RecordCommand(poolbot=self.poolbot) <NEW_LINE> <DEDENT> def test_match_handler(self): <NEW_LINE> <INDENT> text = '{term} beat <@USERID>'.format(term=self.record_cmd.command_term) <NEW_LINE> self.assertTrue(self.record_cmd.match_request(text)) <NEW_LINE> text = ' {term} beat <@USERID>'.format(term=self.record_cmd.command_term) <NEW_LINE> self.assertTrue(self.record_cmd.match_request(text)) <NEW_LINE> <DEDENT> def test_victory_nouns_in_text(self): <NEW_LINE> <INDENT> self.record_cmd = RecordCommand(poolbot=self.poolbot) <NEW_LINE> for vic_noun in self.record_cmd.victory_nouns: <NEW_LINE> <INDENT> text = '{term} {noun} <@USERID>'.format( term=self.record_cmd.command_term, noun=vic_noun, ) <NEW_LINE> self.assertTrue(self.record_cmd._victory_noun_in_text(text)) <NEW_LINE> <DEDENT> text = '{term} {noun} <@USERID>'.format( term=self.record_cmd.command_term, noun='lost', ) <NEW_LINE> self.assertFalse(self.record_cmd._victory_noun_in_text(text)) <NEW_LINE> <DEDENT> def test_defeated_player_detection(self): <NEW_LINE> <INDENT> self.record_cmd = RecordCommand(poolbot=self.poolbot) <NEW_LINE> text = '{term} beat {user}'.format( term=self.record_cmd.command_term, user='<@USERID>' ) <NEW_LINE> value = self.record_cmd._find_defeated_player(text) <NEW_LINE> self.assertEqual(value, 'USERID') <NEW_LINE> text = '{term} beat toby'.format(term=self.record_cmd.command_term) <NEW_LINE> value = self.record_cmd._find_defeated_player(text) <NEW_LINE> self.assertIsNone(value) <NEW_LINE> text = '{term} beat'.format(term=self.record_cmd.command_term) <NEW_LINE> value = self.record_cmd._find_defeated_player(text) <NEW_LINE> self.assertIsNone(value) <NEW_LINE> <DEDENT> def test_post_data(self): <NEW_LINE> <INDENT> self.record_cmd = RecordCommand(poolbot=self.poolbot) <NEW_LINE> message = { "type": "message", "channel": "C2147483705", "user": player.PLAYER_1['slack_id'], "text": "{term} beat <@{user_id}>".format( term=self.record_cmd.command_term, user_id=player.PLAYER_2['slack_id'], ), "ts": "1355517523.000005" } <NEW_LINE> reply, callbacks = self.record_cmd.process_request(message) <NEW_LINE> self.assertEqual( reply, self.record_cmd.victory_message.format( winner=self.poolbot.get_username(player.PLAYER_1['slack_id']), loser=self.poolbot.get_username(player.PLAYER_2['slack_id']), delta_elo_winner=0, delta_elo_loser=0, winner_total=player.PLAYER_1['elo'], loser_total=player.PLAYER_2['elo'], emoji=self.record_cmd._get_emojis(), position_winner=1, position_loser=2, delta_position_winner=0, delta_position_loser=0, ), ) <NEW_LINE> self.assertItemsEqual(callbacks, ['spree']) | Tests for the RecordCommand class. | 6259907e67a9b606de5477d9 |
class SubmissionDelegate(DeclarativeMappedObject): <NEW_LINE> <INDENT> __tablename__ = 'submission_delegate' <NEW_LINE> __table_args__ = ( UniqueConstraint('user_id', 'delegate_id'), {'mysql_engine': 'InnoDB'}) <NEW_LINE> id = Column(Integer, nullable=False, primary_key=True) <NEW_LINE> user_id = Column(Integer, ForeignKey('tg_user.user_id', name='tg_user_id_fk1'), nullable=False) <NEW_LINE> delegate_id = Column(Integer, ForeignKey('tg_user.user_id', name='tg_user_id_fk2'), nullable=False) | A simple N:N mapping between users and their submission delegates | 6259907e4527f215b58eb6d3 |
class XenAPISRSelectionTestCase(stubs.XenAPITestBase): <NEW_LINE> <INDENT> def test_safe_find_sr_raise_exception(self): <NEW_LINE> <INDENT> self.flags(sr_matching_filter='yadayadayada') <NEW_LINE> stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) <NEW_LINE> session = xenapi_conn.XenAPISession('test_url', 'root', 'test_pass', fake.FakeVirtAPI()) <NEW_LINE> self.assertRaises(exception.StorageRepositoryNotFound, vm_utils.safe_find_sr, session) <NEW_LINE> <DEDENT> def test_safe_find_sr_local_storage(self): <NEW_LINE> <INDENT> self.flags(sr_matching_filter='other-config:i18n-key=local-storage') <NEW_LINE> stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) <NEW_LINE> session = xenapi_conn.XenAPISession('test_url', 'root', 'test_pass', fake.FakeVirtAPI()) <NEW_LINE> self.assertEqual(len(xenapi_fake.get_all('host')), 1) <NEW_LINE> host_ref = xenapi_fake.get_all('host')[0] <NEW_LINE> pbd_refs = xenapi_fake.get_all('PBD') <NEW_LINE> for pbd_ref in pbd_refs: <NEW_LINE> <INDENT> pbd_rec = xenapi_fake.get_record('PBD', pbd_ref) <NEW_LINE> if pbd_rec['host'] != host_ref: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> sr_rec = xenapi_fake.get_record('SR', pbd_rec['SR']) <NEW_LINE> if sr_rec['other_config']['i18n-key'] == 'local-storage': <NEW_LINE> <INDENT> local_sr = pbd_rec['SR'] <NEW_LINE> <DEDENT> <DEDENT> expected = vm_utils.safe_find_sr(session) <NEW_LINE> self.assertEqual(local_sr, expected) <NEW_LINE> <DEDENT> def test_safe_find_sr_by_other_criteria(self): <NEW_LINE> <INDENT> self.flags(sr_matching_filter='other-config:my_fake_sr=true') <NEW_LINE> stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) <NEW_LINE> session = xenapi_conn.XenAPISession('test_url', 'root', 'test_pass', fake.FakeVirtAPI()) <NEW_LINE> host_ref = xenapi_fake.get_all('host')[0] <NEW_LINE> local_sr = xenapi_fake.create_sr(name_label='Fake Storage', type='lvm', other_config={'my_fake_sr': 'true'}, host_ref=host_ref) <NEW_LINE> expected = vm_utils.safe_find_sr(session) <NEW_LINE> self.assertEqual(local_sr, expected) <NEW_LINE> <DEDENT> def test_safe_find_sr_default(self): <NEW_LINE> <INDENT> self.flags(sr_matching_filter='default-sr:true') <NEW_LINE> stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) <NEW_LINE> session = xenapi_conn.XenAPISession('test_url', 'root', 'test_pass', fake.FakeVirtAPI()) <NEW_LINE> pool_ref = session.call_xenapi('pool.get_all')[0] <NEW_LINE> expected = vm_utils.safe_find_sr(session) <NEW_LINE> self.assertEqual(session.call_xenapi('pool.get_default_SR', pool_ref), expected) | Unit tests for testing we find the right SR. | 6259907ed486a94d0ba2da1d |
class CorsRule(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "AllowedHeaders": ([str], False), "AllowedMethods": ([str], False), "AllowedOrigins": ([str], False), "ExposeHeaders": ([str], False), "MaxAgeSeconds": (integer, False), } | `CorsRule <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-mediastore-container-corsrule.html>`__ | 6259907e91f36d47f2231bc1 |
class Component: <NEW_LINE> <INDENT> version = "0.1" <NEW_LINE> def __init__(self, component_id: int, component_name: str) -> None: <NEW_LINE> <INDENT> self.__id: int = component_id <NEW_LINE> self.__name: str = component_name <NEW_LINE> self.__sensors: List[Sensor] = [] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.__sensors) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> output = ( f"ComponentId: {self.component_id}\n" f"ComponentName: {self.name}\nSensors:\n" ) <NEW_LINE> for sensor in self.sensors: <NEW_LINE> <INDENT> output += f"{sensor}\n" <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> @property <NEW_LINE> def component_id(self) -> int: <NEW_LINE> <INDENT> return self.__id <NEW_LINE> <DEDENT> @component_id.setter <NEW_LINE> def component_id(self, component_id: int) -> None: <NEW_LINE> <INDENT> self.__id = component_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self.__name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name: str): <NEW_LINE> <INDENT> self.__name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def sensors(self) -> List[Sensor]: <NEW_LINE> <INDENT> return self.__sensors <NEW_LINE> <DEDENT> @sensors.setter <NEW_LINE> def sensors(self, sensors: List[Sensor]): <NEW_LINE> <INDENT> self.__sensors = sensors | Class describing a sensor or actor component built into an instrument | 6259907e56b00c62f0fb433a |
class UtmMixin(models.AbstractModel): <NEW_LINE> <INDENT> _name = 'utm.mixin' <NEW_LINE> _description = 'UTM Mixin' <NEW_LINE> campaign_id = fields.Many2one('utm.campaign', 'Campaign', help="This is a name that helps you keep track of your different campaign efforts, e.g. Fall_Drive, Christmas_Special") <NEW_LINE> source_id = fields.Many2one('utm.source', 'Source', help="This is the source of the link, e.g. Search Engine, another domain, or name of email list") <NEW_LINE> medium_id = fields.Many2one('utm.medium', 'Medium', help="This is the method of delivery, e.g. Postcard, Email, or Banner Ad", oldname='channel_id') <NEW_LINE> def tracking_fields(self): <NEW_LINE> <INDENT> return [ ('utm_campaign', 'campaign_id', 'odoo_utm_campaign'), ('utm_source', 'source_id', 'odoo_utm_source'), ('utm_medium', 'medium_id', 'odoo_utm_medium'), ] <NEW_LINE> <DEDENT> @api.model <NEW_LINE> def default_get(self, fields): <NEW_LINE> <INDENT> values = super(UtmMixin, self).default_get(fields) <NEW_LINE> if self.env.uid != SUPERUSER_ID and self.env.user.has_group('sales_team.group_sale_salesman'): <NEW_LINE> <INDENT> return values <NEW_LINE> <DEDENT> for url_param, field_name, cookie_name in self.env['utm.mixin'].tracking_fields(): <NEW_LINE> <INDENT> if field_name in fields: <NEW_LINE> <INDENT> field = self._fields[field_name] <NEW_LINE> value = False <NEW_LINE> if request: <NEW_LINE> <INDENT> value = request.httprequest.cookies.get(cookie_name) <NEW_LINE> <DEDENT> if field.type == 'many2one' and isinstance(value, pycompat.string_types) and value: <NEW_LINE> <INDENT> Model = self.env[field.comodel_name] <NEW_LINE> records = Model.search([('name', '=', value)], limit=1) <NEW_LINE> if not records: <NEW_LINE> <INDENT> records = Model.create({'name': value}) <NEW_LINE> <DEDENT> value = records.id <NEW_LINE> <DEDENT> if value: <NEW_LINE> <INDENT> values[field_name] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return values | Mixin class for objects which can be tracked by marketing. | 6259907e5fdd1c0f98e5f9e6 |
class Sprite: <NEW_LINE> <INDENT> def __init__(self, item, x=0, y=0, theta=0, scale=1): <NEW_LINE> <INDENT> self.item = item <NEW_LINE> self.origPixmap = self.item.pixmap() <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.theta = theta <NEW_LINE> self.scale = scale <NEW_LINE> self.item.setTransformOriginPoint(QtCore.QPointF(self.origPixmap.width()/2, self.origPixmap.height()/2)) <NEW_LINE> <DEDENT> def resize(self, scale): <NEW_LINE> <INDENT> self.scale = scale <NEW_LINE> self.redraw() <NEW_LINE> <DEDENT> def redraw(self): <NEW_LINE> <INDENT> self.item.setScale(self.scale) <NEW_LINE> self.item.setX(-self.origPixmap.width()/2+self.scale*self.origPixmap.width()/2+self.x*self.scale) <NEW_LINE> self.item.setY(-self.origPixmap.height()/2+self.scale*self.origPixmap.height()/2+self.y*self.scale) <NEW_LINE> self.item.setRotation(self.theta) <NEW_LINE> <DEDENT> def moveRotate(self, x, y, theta): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.theta = theta <NEW_LINE> self.redraw() | Pour gérer tous les objets avec des images
Chaque objet a 2 positions :
- sa position sur le plateau (self.x, self.y)
- sa position dans la fenêtre (self.item.x(), self.item.Y()) | 6259907e442bda511e95da8a |
@dataclass <NEW_LINE> class AppSettings: <NEW_LINE> <INDENT> starting_credits: int <NEW_LINE> go_cost: int <NEW_LINE> image_scale: int <NEW_LINE> assets: dict | Holds the app settings | 6259907e7d847024c075de44 |
class ServicemanagementServicesConfigsGetRequest(_messages.Message): <NEW_LINE> <INDENT> configId = _messages.StringField(1, required=True) <NEW_LINE> serviceName = _messages.StringField(2, required=True) | A ServicemanagementServicesConfigsGetRequest object.
Fields:
configId: The id of the service config resource. Optional. If it is not
specified, the latest version of config will be returned.
serviceName: The name of the service. See the `ServiceManager` overview
for naming requirements. For example: `example.googleapis.com`. | 6259907e7c178a314d78e91e |
class Event: <NEW_LINE> <INDENT> def __init__(self, osuAPI, display_html, beatmap_id, beatmapset_id, date, epicfactor): <NEW_LINE> <INDENT> self.osuAPI = osuAPI <NEW_LINE> self.displayHTML = display_html <NEW_LINE> self.beatmapID = beatmap_id <NEW_LINE> self.beatmapsetID = beatmapset_id <NEW_LINE> self.beatmapSet = self.api.beatmapsetCls(self.api, beatmapset_id) <NEW_LINE> self.date = date <NEW_LINE> self.epicFactor = int(epicfactor) <NEW_LINE> self._beatmap = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def beatmap(self): <NEW_LINE> <INDENT> return self._beatmap <NEW_LINE> <DEDENT> async def getBeatmap(self): <NEW_LINE> <INDENT> if self._beatmap is None: <NEW_LINE> <INDENT> self._beatmap = (await self.osuAPI.getBeatmaps(beatmap_id=self.beatmapID))[0] <NEW_LINE> <DEDENT> return self._beatmap | Represents an "event". Meant to be subclassed | 6259907e796e427e538501e1 |
class StartParser(object): <NEW_LINE> <INDENT> def __init__(self, subparser, parent_parser): <NEW_LINE> <INDENT> self.parent_subparser = subparser <NEW_LINE> self.parent_parser = parent_parser <NEW_LINE> self.start_parser = self.parent_subparser.add_parser( 'start', help='Start VM', parents=[self.parent_parser]) <NEW_LINE> self.start_parser.set_defaults(func=self.handle_start) <NEW_LINE> self.start_parser.add_argument('--iso', metavar='ISO Name', type=str, help='Path of ISO to attach to VM', default=None) <NEW_LINE> self.start_parser.add_argument('vm_names', nargs='*', metavar='VM Names', type=str, help='Names of VMs') <NEW_LINE> <DEDENT> def handle_start(self, p_, args): <NEW_LINE> <INDENT> vm_factory = p_.rpc.get_connection('virtual_machine_factory') <NEW_LINE> for vm_name in args.vm_names: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> vm_object = vm_factory.get_virtual_machine_by_name(vm_name) <NEW_LINE> p_.rpc.annotate_object(vm_object) <NEW_LINE> vm_object.start(iso_name=args.iso) <NEW_LINE> p_.print_status('Successfully started VM %s' % vm_name) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> p_.print_status('Error while starting VM %s' % vm_name) <NEW_LINE> raise | Handle VM start parser. | 6259907eaad79263cf430221 |
class LoginView(GenericAPIView): <NEW_LINE> <INDENT> permission_classes = (AllowAny,) <NEW_LINE> serializer_class = LoginSerializer <NEW_LINE> token_model = TokenModel <NEW_LINE> @sensitive_post_parameters_m <NEW_LINE> def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(LoginView, self).dispatch(*args, **kwargs) <NEW_LINE> <DEDENT> def process_login(self): <NEW_LINE> <INDENT> django_login(self.request, self.user) <NEW_LINE> <DEDENT> def get_response_serializer(self): <NEW_LINE> <INDENT> response_serializer = TokenSerializer <NEW_LINE> return response_serializer <NEW_LINE> <DEDENT> def login(self): <NEW_LINE> <INDENT> self.user = self.serializer.validated_data['user'] <NEW_LINE> self.token = TokenModel.objects.get(user=self.user) <NEW_LINE> if getattr(settings, 'REST_SESSION_LOGIN', True): <NEW_LINE> <INDENT> self.process_login() <NEW_LINE> <DEDENT> <DEDENT> def get_response(self): <NEW_LINE> <INDENT> serializer_class = self.get_response_serializer() <NEW_LINE> serializer = serializer_class(instance=self.token, context={'request': self.request}) <NEW_LINE> return Response(serializer.data, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> self.serializer = self.get_serializer(data=self.request.data, context={'request': request}) <NEW_LINE> self.serializer.is_valid(raise_exception=True) <NEW_LINE> self.login() <NEW_LINE> return self.get_response() | Check the credentials and return the REST Token
if the credentials are valid and authenticated.
Calls Django Auth login method to register User ID
in Django session framework
Accept the following POST parameters: username, password
Return the REST Framework Token Object's key. | 6259907ea05bb46b3848be5c |
class ReactionSet(object): <NEW_LINE> <INDENT> def __init__(self, reactions): <NEW_LINE> <INDENT> self.reactions = reactions <NEW_LINE> self.trails = set() <NEW_LINE> self.supersets = set() <NEW_LINE> self.subsets = set() <NEW_LINE> self.organisms = set() <NEW_LINE> <DEDENT> def add_trail(self, trail): <NEW_LINE> <INDENT> self.trails.add(trail) <NEW_LINE> <DEDENT> def add_superset(self, superset): <NEW_LINE> <INDENT> self.supersets.add(superset) <NEW_LINE> <DEDENT> def add_subset(self, subset): <NEW_LINE> <INDENT> self.subsets.add(subset) <NEW_LINE> <DEDENT> def add_organisms(self): <NEW_LINE> <INDENT> for trail in self.trails: <NEW_LINE> <INDENT> for organism in trail.organisms: <NEW_LINE> <INDENT> self.organisms.add(organism.org) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def find(self, reactions): <NEW_LINE> <INDENT> return self if self.reactions == reactions else None | Represents a CoMetGeNe trail as a reaction set. | 6259907ebf627c535bcb2f39 |
class Post(BaseModel): <NEW_LINE> <INDENT> class StatusChoices(models.TextChoices): <NEW_LINE> <INDENT> PUBLIC = 'PU', _('Public') <NEW_LINE> PRIVATE = 'PR', _('Private') <NEW_LINE> TRASH = 'TR', _('Trash') <NEW_LINE> <DEDENT> title = models.CharField('title', max_length=140) <NEW_LINE> slug_name = models.SlugField(unique=True, max_length=140) <NEW_LINE> content = models.TextField('content', blank=True, null=True) <NEW_LINE> excerpt = models.TextField('excerpt', blank=True, null=True) <NEW_LINE> picture = models.ImageField(upload_to='posts/pictures', blank=True) <NEW_LINE> status = models.CharField( 'status', max_length=2, choices=StatusChoices.choices, default=StatusChoices.PRIVATE ) <NEW_LINE> category = models.ManyToManyField('posts.Category', blank=True) <NEW_LINE> tags = models.ForeignKey('posts.Tag', on_delete=models.CASCADE, blank=True, null=True) <NEW_LINE> author = models.ForeignKey('users.User', on_delete=models.CASCADE) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> class Meta(BaseModel.Meta): <NEW_LINE> <INDENT> ordering = ['-modified', '-created'] | Post model.
| 6259907e7b180e01f3e49d99 |
class NoPythonFiles(Exception): <NEW_LINE> <INDENT> pass | There is no python files to build | 6259907eaad79263cf430222 |
class NetworkNotifyEvent(wx.PyEvent): <NEW_LINE> <INDENT> def __init__(self, state): <NEW_LINE> <INDENT> wx.PyEvent.__init__(self) <NEW_LINE> self.SetEventType(EVT_NETWORK_NOTIFY_ID) <NEW_LINE> self.data = state | Simple event to tell the GUI to update the network notification icon. | 6259907e76e4537e8c3f0fe8 |
class TloInd: <NEW_LINE> <INDENT> def __init__(self, x): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self._cost = None <NEW_LINE> <DEDENT> def setCost(self, cost): <NEW_LINE> <INDENT> self._cost = cost <NEW_LINE> <DEDENT> def cost(self): <NEW_LINE> <INDENT> return self._cost | Merely an association of an opt point with a cost. | 6259907e5fc7496912d48f9f |
class Toluene(object): <NEW_LINE> <INDENT> mol_wt = 92.1 <NEW_LINE> density = 866.0 <NEW_LINE> k_ow = 1000.0 | The measured values of the known aromatic, toluene | 6259907e97e22403b383c969 |
class _StaticQuantizationUInt8Transformation(object): <NEW_LINE> <INDENT> def Prepare(self, emitter, registers, kernel_m, kernel_n, lhs, rhs): <NEW_LINE> <INDENT> emitter.EmitNewline() <NEW_LINE> emitter.EmitComment('StaticQuantization::Prepare') <NEW_LINE> lhs_offset = _ReadParams(emitter, registers, lhs, kernel_m, 4) <NEW_LINE> self.rhs_offsets = _ReadParams(emitter, registers, rhs, kernel_n, 4) <NEW_LINE> self.multiplicative_offset = _DuplicateGeneralRegister( emitter, registers, registers.MapParameter('multiplicative_offset', 'params.kernel.multiplicative_offset'), 4) <NEW_LINE> self.rounding_offset = _DuplicateGeneralRegister( emitter, registers, registers.MapParameter('rounding_offset', 'params.kernel.rounding_offset'), 4) <NEW_LINE> self.shift = _DuplicateGeneralRegister( emitter, registers, registers.MapParameter('shift', 'params.kernel.shift'), 4) <NEW_LINE> self.lhs_offsets = _Duplicate(emitter, registers, kernel_m, lhs_offset) <NEW_LINE> <DEDENT> def Transform(self, emitter, registers, data, unused_kernel_m, unused_kernel_n): <NEW_LINE> <INDENT> emitter.EmitNewline() <NEW_LINE> emitter.EmitComment('StaticQuantization::Transform') <NEW_LINE> for (row, lhs_offset) in zip(data, self.lhs_offsets): <NEW_LINE> <INDENT> for row_register in row: <NEW_LINE> <INDENT> emitter.EmitVAdd('s32', row_register, row_register, lhs_offset) <NEW_LINE> <DEDENT> <DEDENT> for row in data: <NEW_LINE> <INDENT> for (row_register, rhs_offset_register) in zip(row, self.rhs_offsets): <NEW_LINE> <INDENT> emitter.EmitVAdd('s32', row_register, row_register, rhs_offset_register) <NEW_LINE> <DEDENT> <DEDENT> for row in data: <NEW_LINE> <INDENT> for row_register in row: <NEW_LINE> <INDENT> emitter.EmitVMul('i32', row_register, row_register, self.multiplicative_offset) <NEW_LINE> <DEDENT> <DEDENT> for row in data: <NEW_LINE> <INDENT> for row_register in row: <NEW_LINE> <INDENT> emitter.EmitVAdd('i32', row_register, row_register, self.rounding_offset) <NEW_LINE> <DEDENT> <DEDENT> for row in data: <NEW_LINE> <INDENT> for row_register in row: <NEW_LINE> <INDENT> emitter.EmitVShl('s32', row_register, row_register, self.shift) <NEW_LINE> <DEDENT> <DEDENT> if len(data[0]) is 1: <NEW_LINE> <INDENT> for row in data: <NEW_LINE> <INDENT> emitter.EmitVQmovn('s32', row[0], row[0]) <NEW_LINE> <DEDENT> for row in data: <NEW_LINE> <INDENT> emitter.EmitVQmovun('s16', row[0], row[0]) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> elif len(data[0]) is 2: <NEW_LINE> <INDENT> results = [] <NEW_LINE> for row in data: <NEW_LINE> <INDENT> emitter.EmitVQmovn2('s32', row[0], row[0], row[1]) <NEW_LINE> registers.FreeRegister(row[1]) <NEW_LINE> results.append([row[0]]) <NEW_LINE> <DEDENT> for row in results: <NEW_LINE> <INDENT> emitter.EmitVQmovun('s16', row[0], row[0]) <NEW_LINE> <DEDENT> return results <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert False <NEW_LINE> <DEDENT> <DEDENT> def Type(self): <NEW_LINE> <INDENT> return 8 | Calculate quantized values and cast back to uint8. | 6259907e5fcc89381b266e90 |
class OverSampler(DatasetMixin): <NEW_LINE> <INDENT> def __init__(self, dataset, min_samples=5, virtual_size=10000): <NEW_LINE> <INDENT> assert hasattr(dataset, 'all_labels') <NEW_LINE> self.dataset = dataset <NEW_LINE> self.virtual_size = virtual_size <NEW_LINE> samples_per_class = defaultdict(int) <NEW_LINE> self.class_sample_mapping = defaultdict(list) <NEW_LINE> for i, label in enumerate(dataset.all_labels): <NEW_LINE> <INDENT> samples_per_class[label] += 1 <NEW_LINE> self.class_sample_mapping[label].append(i) <NEW_LINE> <DEDENT> self.labels = sorted(samples_per_class.keys()) <NEW_LINE> num_samples = np.array( [samples_per_class[k] for k in self.labels], dtype=np.float32) <NEW_LINE> num_samples_mod = np.maximum(num_samples, min_samples) <NEW_LINE> self.class_probs = num_samples_mod / num_samples_mod.sum() <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.virtual_size <NEW_LINE> <DEDENT> def get_example(self, _): <NEW_LINE> <INDENT> label = random.choices(self.labels, weights=self.class_probs)[0] <NEW_LINE> index = random.choice(self.class_sample_mapping[label]) <NEW_LINE> return self.dataset[index] | Dataset wrapper to enagle oversampling. | 6259907e63b5f9789fe86bd0 |
class TemplateHelper(ServerPlugin): <NEW_LINE> <INDENT> __serverplugin__ = 'TemplateHelper' <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> ServerPlugin.__init__(self, *args, **kwargs) <NEW_LINE> dummy = HelperModule("foo.py", None) <NEW_LINE> self.reserved_keywords = dir(dummy) <NEW_LINE> self.reserved_defaults = dummy.reserved_defaults <NEW_LINE> <DEDENT> def Run(self): <NEW_LINE> <INDENT> for helper in self.core.plugins['TemplateHelper'].entries.values(): <NEW_LINE> <INDENT> if self.HandlesFile(helper.name): <NEW_LINE> <INDENT> self.check_helper(helper.name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def check_helper(self, helper): <NEW_LINE> <INDENT> module_name = MODULE_RE.search(helper).group(1) <NEW_LINE> try: <NEW_LINE> <INDENT> module = imp.load_source( safe_module_name('TemplateHelper', module_name), helper) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> err = sys.exc_info()[1] <NEW_LINE> self.LintError("templatehelper-import-error", "Failed to import %s: %s" % (helper, err)) <NEW_LINE> return <NEW_LINE> <DEDENT> if not hasattr(module, "__export__"): <NEW_LINE> <INDENT> self.LintError("templatehelper-no-export", "%s has no __export__ list" % helper) <NEW_LINE> return <NEW_LINE> <DEDENT> elif not isinstance(module.__export__, list): <NEW_LINE> <INDENT> self.LintError("templatehelper-nonlist-export", "__export__ is not a list in %s" % helper) <NEW_LINE> return <NEW_LINE> <DEDENT> for sym in module.__export__: <NEW_LINE> <INDENT> if not hasattr(module, sym): <NEW_LINE> <INDENT> self.LintError("templatehelper-nonexistent-export", "%s: exported symbol %s does not exist" % (helper, sym)) <NEW_LINE> <DEDENT> elif sym in self.reserved_keywords: <NEW_LINE> <INDENT> self.LintError("templatehelper-reserved-export", "%s: exported symbol %s is reserved" % (helper, sym)) <NEW_LINE> <DEDENT> elif sym.startswith("_"): <NEW_LINE> <INDENT> self.LintError("templatehelper-underscore-export", "%s: exported symbol %s starts with underscore" % (helper, sym)) <NEW_LINE> <DEDENT> if sym in getattr(module, "__default__", []): <NEW_LINE> <INDENT> self.LintError("templatehelper-export-and-default", "%s: %s is listed in both __default__ and " "__export__" % (helper, sym)) <NEW_LINE> <DEDENT> <DEDENT> for sym in getattr(module, "__default__", []): <NEW_LINE> <INDENT> if sym in self.reserved_defaults: <NEW_LINE> <INDENT> self.LintError("templatehelper-reserved-default", "%s: default symbol %s is reserved" % (helper, sym)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def Errors(cls): <NEW_LINE> <INDENT> return {"templatehelper-import-error": "error", "templatehelper-no-export": "error", "templatehelper-nonlist-export": "error", "templatehelper-nonexistent-export": "error", "templatehelper-reserved-export": "error", "templatehelper-reserved-default": "error", "templatehelper-underscore-export": "warning", "templatehelper-export-and-default": "warning"} | ``bcfg2-lint`` plugin to ensure that all :ref:`TemplateHelper
<server-plugins-connectors-templatehelper>` modules are valid.
This can check for:
* A TemplateHelper module that cannot be imported due to syntax or
other compile-time errors;
* A TemplateHelper module that does not have an ``__export__``
attribute, or whose ``__export__`` is not a list;
* Bogus symbols listed in ``__export__``, including symbols that
don't exist, that are reserved, or that start with underscores. | 6259907eaad79263cf430223 |
@dataclass <NEW_LINE> class Retry: <NEW_LINE> <INDENT> attempts: int = 1 <NEW_LINE> delay: float = 0.1 <NEW_LINE> backoff: float = 2.0 <NEW_LINE> jitter: float = 0.1 <NEW_LINE> async def sleep(self, *, layer: Layer, attempt: int) -> None: <NEW_LINE> <INDENT> sleep = layer.configuration.retry.delay * (layer.configuration.retry.backoff ** (attempt - 1)) <NEW_LINE> sleep = sleep + random.uniform(0, sleep * layer.configuration.retry.jitter) <NEW_LINE> sleep = round(sleep, 2) <NEW_LINE> logger.info("Retrying layer '%s' after backing off for '%.2f' seconds.", layer.name, sleep) <NEW_LINE> await asyncio.sleep(sleep) | Configure a Layer to retry on failure using exponential backoff.
Notes:
Computes the retry backoff with:
>>> sleep = <delay> * (<backoff> ** (attempt - 1))
>>> sleep = sleep + random(0, sleep * <jitter>)
Usage::
@flow.register(retry=Retry(...)) | 6259907e4428ac0f6e659f98 |
class BackendRule(_messages.Message): <NEW_LINE> <INDENT> class PathTranslationValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> PATH_TRANSLATION_UNSPECIFIED = 0 <NEW_LINE> CONSTANT_ADDRESS = 1 <NEW_LINE> APPEND_PATH_TO_ADDRESS = 2 <NEW_LINE> <DEDENT> address = _messages.StringField(1) <NEW_LINE> deadline = _messages.FloatField(2) <NEW_LINE> jwtAudience = _messages.StringField(3) <NEW_LINE> minDeadline = _messages.FloatField(4) <NEW_LINE> operationDeadline = _messages.FloatField(5) <NEW_LINE> pathTranslation = _messages.EnumField('PathTranslationValueValuesEnum', 6) <NEW_LINE> selector = _messages.StringField(7) | A backend rule provides configuration for an individual API element.
Enums:
PathTranslationValueValuesEnum:
Fields:
address: The address of the API backend.
deadline: The number of seconds to wait for a response from a request.
The default deadline for gRPC is infinite (no deadline) and HTTP
requests is 5 seconds.
jwtAudience: The JWT audience is used when generating a JWT id token for
the backend.
minDeadline: Minimum deadline in seconds needed for this method. Calls
having deadline value lower than this will be rejected.
operationDeadline: The number of seconds to wait for the completion of a
long running operation. The default is no deadline.
pathTranslation: A PathTranslationValueValuesEnum attribute.
selector: Selects the methods to which this rule applies. Refer to
selector for syntax details. | 6259907ebf627c535bcb2f3b |
class AvailableProvidersList(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'countries': {'required': True}, } <NEW_LINE> _attribute_map = { 'countries': {'key': 'countries', 'type': '[AvailableProvidersListCountry]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(AvailableProvidersList, self).__init__(**kwargs) <NEW_LINE> self.countries = kwargs['countries'] | List of available countries with details.
All required parameters must be populated in order to send to Azure.
:param countries: Required. List of available countries.
:type countries: list[~azure.mgmt.network.v2020_03_01.models.AvailableProvidersListCountry] | 6259907eaad79263cf430224 |
class Dumper: <NEW_LINE> <INDENT> def __init__(self, api, types): <NEW_LINE> <INDENT> self.api = api <NEW_LINE> self.types = types <NEW_LINE> <DEDENT> def dumperFactory(self): <NEW_LINE> <INDENT> return ValueDumper() <NEW_LINE> <DEDENT> def dump(self): <NEW_LINE> <INDENT> self.header() <NEW_LINE> for module in api.modules: <NEW_LINE> <INDENT> for header in module.headers: <NEW_LINE> <INDENT> print(header) <NEW_LINE> <DEDENT> <DEDENT> print() <NEW_LINE> types = api.getAllTypes() <NEW_LINE> for type in self.types: <NEW_LINE> <INDENT> self.dumpType(type) <NEW_LINE> <DEDENT> <DEDENT> def dumpType(self, type): <NEW_LINE> <INDENT> print(r'void') <NEW_LINE> print(r'dumpStateObject(StateWriter &writer, const %s & so)' % type) <NEW_LINE> print(r'{') <NEW_LINE> visitor = self.dumperFactory() <NEW_LINE> visitor.visit(type, 'so') <NEW_LINE> print(r'}') <NEW_LINE> print() <NEW_LINE> <DEDENT> def header(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def footer(self): <NEW_LINE> <INDENT> pass | Base class to orchestrate the code generation of state object dumpers. | 6259907e7d43ff248742814a |
@python_2_unicode_compatible <NEW_LINE> class UserProfile(models.Model): <NEW_LINE> <INDENT> user = models.OneToOneField( User, related_name='profile', on_delete=models.CASCADE) <NEW_LINE> title = models.CharField(max_length=256, null=True, blank=True) <NEW_LINE> institution = models.TextField() <NEW_LINE> referred_by = models.TextField() <NEW_LINE> user_story = models.TextField(null=True, blank=True) <NEW_LINE> self_registered = models.BooleanField(default=False) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.user.username | UserProfile adds extra information to a user,
and associates the user with a group, school,
and country. | 6259907e92d797404e389891 |
@register_plugin <NEW_LINE> class CantReach(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super().__init__(message) | Raises when cant find path | 6259907e23849d37ff852b23 |
class PowerLawFlux(object): <NEW_LINE> <INDENT> def __init__(self, emin, emax, phi0, gamma): <NEW_LINE> <INDENT> self.emin = emin <NEW_LINE> self.emax = emax <NEW_LINE> self.gamma = gamma <NEW_LINE> self.phi0 = phi0 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def E2_1E8(energy): <NEW_LINE> <INDENT> return 1e-8*np.power(energy, -2) <NEW_LINE> <DEDENT> def __call__(self, energy): <NEW_LINE> <INDENT> energy = energy.astype(np.float64) <NEW_LINE> fl = self.phi0 * np.power(energy, self.gamma) <NEW_LINE> fl[energy < self.emin] = 0. <NEW_LINE> fl[energy > self.emax] = 0. <NEW_LINE> return fl <NEW_LINE> <DEDENT> def fluxsum(self): <NEW_LINE> <INDENT> if self.gamma < -1: <NEW_LINE> <INDENT> ex = 1 + self.gamma <NEW_LINE> return self.phi0 * (self.emax ** ex - self.emin ** ex) / ex <NEW_LINE> <DEDENT> elif self.gamma == -1: <NEW_LINE> <INDENT> return self.phi0 * (np.log(self.emax) - np.log(self.emin)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Integration of positive gamma not supported") | A flux only dependent on the energy of a particle, following a power law. Defined in
an energy interval [emin, emax] with fluence phi0 and spectral index gamma | 6259907eec188e330fdfa313 |
class RegistroC791(Registro): <NEW_LINE> <INDENT> campos = [ CampoFixo(1, 'REG', 'C791'), Campo(2, 'UF'), CampoNumerico(3, 'VL_BC_ICMS_ST'), CampoNumerico(4, 'VL_ICMS_ST'), ] <NEW_LINE> nivel = 4 | REGISTRO DE INFORMAÇÕES DE ST POR UF | 6259907e32920d7e50bc7aac |
class ReverseStyleTransformation(StyleTransformation): <NEW_LINE> <INDENT> def transform_attrs(self, attrs: Attrs) -> Attrs: <NEW_LINE> <INDENT> return attrs._replace(reverse=not attrs.reverse) | Swap the 'reverse' attribute.
(This is still experimental.) | 6259907e283ffb24f3cf530b |
class Solution: <NEW_LINE> <INDENT> def removeElement(self, A, elem): <NEW_LINE> <INDENT> st, lenA = 0, len(A) <NEW_LINE> while st < lenA: <NEW_LINE> <INDENT> if A[st] == elem: <NEW_LINE> <INDENT> del A[st] <NEW_LINE> lenA -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> st += 1 <NEW_LINE> <DEDENT> <DEDENT> return len(A) | @param A: A list of integers
@param elem: An integer
@return: The new length after remove | 6259907e3617ad0b5ee07bba |
class IWebhookDeliveryAttemptSucceededEvent(IWebhookDeliveryAttemptResolvedEvent): <NEW_LINE> <INDENT> pass | A delivery attempt succeeded.
The ``succeeded`` attribute will be true. | 6259907ef548e778e596cffd |
class RandomContrast(object): <NEW_LINE> <INDENT> def __init__(self, lower=0.5, upper=1.5): <NEW_LINE> <INDENT> super(RandomContrast, self).__init__() <NEW_LINE> self.lower = lower <NEW_LINE> self.upper = upper <NEW_LINE> assert self.upper >= self.lower, 'contrast upper must be >= lower.' <NEW_LINE> assert self.lower >= 0, 'contrast lower must be non-negative.' <NEW_LINE> <DEDENT> def __call__(self, image, label=None): <NEW_LINE> <INDENT> if random.randint(2): <NEW_LINE> <INDENT> alpha = random.uniform(self.lower, self.upper) <NEW_LINE> image *= alpha <NEW_LINE> <DEDENT> return image, label | This class adjusts the contrast of the image. This multiplies a random
constant to the pixel values of the image. | 6259907ef548e778e596cffe |
class ChemicalPotential(dict, MSONable): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> d = dict(*args, **kwargs) <NEW_LINE> super(ChemicalPotential, self).__init__((get_el_sp(k), v) for k, v in d.items()) <NEW_LINE> if len(d) != len(self): <NEW_LINE> <INDENT> raise ValueError("Duplicate potential specified") <NEW_LINE> <DEDENT> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> if isinstance(other, numbers.Number): <NEW_LINE> <INDENT> return ChemicalPotential({k: v * other for k, v in self.items()}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> __rmul__ = __mul__ <NEW_LINE> def __truediv__(self, other): <NEW_LINE> <INDENT> if isinstance(other, numbers.Number): <NEW_LINE> <INDENT> return ChemicalPotential({k: v / other for k, v in self.items()}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> __div__ = __truediv__ <NEW_LINE> def __sub__(self, other): <NEW_LINE> <INDENT> if isinstance(other, ChemicalPotential): <NEW_LINE> <INDENT> els = set(self.keys()).union(other.keys()) <NEW_LINE> return ChemicalPotential({e: self.get(e, 0) - other.get(e, 0) for e in els}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> if isinstance(other, ChemicalPotential): <NEW_LINE> <INDENT> els = set(self.keys()).union(other.keys()) <NEW_LINE> return ChemicalPotential({e: self.get(e, 0) + other.get(e, 0) for e in els}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def get_energy(self, composition, strict=True): <NEW_LINE> <INDENT> if strict and set(composition.keys()) > set(self.keys()): <NEW_LINE> <INDENT> s = set(composition.keys()) - set(self.keys()) <NEW_LINE> raise ValueError("Potentials not specified for {}".format(s)) <NEW_LINE> <DEDENT> return sum(self.get(k, 0) * v for k, v in composition.items()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "ChemPots: " + super(ChemicalPotential, self).__repr__() | Class to represent set of chemical potentials. Can be:
multiplied/divided by a Number
multiplied by a Composition (returns an energy)
added/subtracted with other ChemicalPotentials. | 6259907e23849d37ff852b25 |
class HTTPBadRequestException(HTTPException): <NEW_LINE> <INDENT> STATUS = 400 <NEW_LINE> def __init__(self, status, reason, data): <NEW_LINE> <INDENT> super().__init__(status, reason, data) | classdocs | 6259907e97e22403b383c96d |
class Data_Getter_Pred: <NEW_LINE> <INDENT> def __init__(self, loggerObj): <NEW_LINE> <INDENT> self.prediction_file='Prediction_FileFromDB/InputFile.csv' <NEW_LINE> self.loggerObj = loggerObj <NEW_LINE> self.features = ['family', 'product-type', 'steel', 'carbon', 'hardness', 'temper_rolling', 'condition', 'formability', 'strength', 'non-ageing', 'surface-finish', 'surface-quality', 'enamelability', 'bc', 'bf', 'bt', 'bw/me', 'bl', 'm', 'chrom', 'phos', 'cbond', 'marvi', 'exptl', 'ferro', 'corr', 'blue/bright/varn/clean', 'lustre', 'jurofm', 's', 'p', 'shape', 'thick', 'width', 'len', 'oil', 'bore', 'packing'] <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> self.loggerObj.logger_log('Entered the get_data method of the Data_Getter class') <NEW_LINE> try: <NEW_LINE> <INDENT> self.data= pd.read_csv(self.prediction_file, header = None, names = self.features) <NEW_LINE> self.loggerObj.logger_log('Data Load Successful.Exited the get_data method of the Data_Getter class') <NEW_LINE> return self.data <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.loggerObj.logger_log('Exception occured in get_data method of the Data_Getter class. Exception message: '+str(e)) <NEW_LINE> self.loggerObj.logger_log('Data Load Unsuccessful.Exited the get_data method of the Data_Getter class') <NEW_LINE> raise Exception() <NEW_LINE> <DEDENT> <DEDENT> def get_data_for_rec(self,jsondata): <NEW_LINE> <INDENT> self.loggerObj.logger_log('Entered the get_data_for_rec method of the Data_Getter class') <NEW_LINE> try: <NEW_LINE> <INDENT> data = pd.DataFrame([jsondata]) <NEW_LINE> self.loggerObj.logger_log('Data Load Successful.Exited the get_data method of the Data_Getter class') <NEW_LINE> return data <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.loggerObj.logger_log('Exception occured in get_data method of the Data_Getter class. Exception message: '+str(e)) <NEW_LINE> self.loggerObj.logger_log('Data Load Unsuccessful.Exited the get_data method of the Data_Getter class') <NEW_LINE> raise Exception() | This class shall be used for obtaining the data from the source for prediction.
Written By: iNeuron Intelligence
Version: 1.0
Revisions: None | 6259907e5fcc89381b266e92 |
class Splitter(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.folds = 5 <NEW_LINE> self.min_playlist_size = 10 <NEW_LINE> self.test_size = 100 <NEW_LINE> <DEDENT> def cross_validation(self, interaction): <NEW_LINE> <INDENT> sample_list = [] <NEW_LINE> target_list = [] <NEW_LINE> for i in range(0, self.folds): <NEW_LINE> <INDENT> sample_list.append({}) <NEW_LINE> target_list.append(list()) <NEW_LINE> <DEDENT> f_playlists = [x for x in interaction.keys() if len(interaction[x]) >= self.min_playlist_size] <NEW_LINE> num_f_pls = len(f_playlists) <NEW_LINE> fold_size = math.ceil(num_f_pls / self.folds) <NEW_LINE> random.shuffle(f_playlists) <NEW_LINE> fold_playlists = [f_playlists[x:x + fold_size] for x in range(0, len(f_playlists), fold_size)] <NEW_LINE> num_sample = 5 <NEW_LINE> fold_idx = 0 <NEW_LINE> for fold_pl in fold_playlists: <NEW_LINE> <INDENT> fold_tg_trs = set() <NEW_LINE> for pl in fold_pl: <NEW_LINE> <INDENT> fold_sample_trs = random.sample(interaction[pl], num_sample) <NEW_LINE> sample_list[fold_idx][pl] = fold_sample_trs <NEW_LINE> fold_tg_trs = fold_tg_trs.union(fold_sample_trs) <NEW_LINE> <DEDENT> target_list[fold_idx] = fold_tg_trs <NEW_LINE> fold_idx += 1 <NEW_LINE> <DEDENT> return sample_list, target_list <NEW_LINE> <DEDENT> def build_testset(self, ds, surname): <NEW_LINE> <INDENT> path = './test_data/' <NEW_LINE> for i in tqdm(range(0, self.test_size)): <NEW_LINE> <INDENT> name_count = i * self.folds <NEW_LINE> interaction = ds.get_interaction() <NEW_LINE> sample_list, target_list = self.cross_validation(interaction) <NEW_LINE> for k in range(0, self.folds): <NEW_LINE> <INDENT> idx = name_count + k <NEW_LINE> name = str(idx).zfill(5) <NEW_LINE> name = surname + name + ".txt" <NEW_LINE> itr_file = path + "itr" + name <NEW_LINE> urm_file = path + "urm" + name <NEW_LINE> ev_file = path + "ev" + name <NEW_LINE> tg_file = path + "tg" + name <NEW_LINE> urm = ds.build_urm() <NEW_LINE> interaction = ds.get_interaction() <NEW_LINE> for pl in sample_list[k].keys(): <NEW_LINE> <INDENT> pl_idx = ds.map_id_index_pl(pl) <NEW_LINE> for tr in sample_list[k][pl]: <NEW_LINE> <INDENT> tr_idx = ds.map_id_index_tr(tr) <NEW_LINE> urm[pl_idx, tr_idx] = 0 <NEW_LINE> interaction[pl].remove(tr) <NEW_LINE> <DEDENT> <DEDENT> target_tracks = target_list[k] <NEW_LINE> evaluation = sample_list[k] <NEW_LINE> pickle_ops.save(itr_file, interaction) <NEW_LINE> lil_ops.save_lil(urm_file, urm) <NEW_LINE> pickle_ops.save(ev_file, evaluation) <NEW_LINE> pickle_ops.save(tg_file, target_tracks) | A Splitter is used to split the given Dataset | 6259907e3d592f4c4edbc895 |
class GenerateToken(View): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> session_token = request.GET.get('session_token') <NEW_LINE> user_token = generate_token(session_token) <NEW_LINE> data = simplejson.dumps({'token':user_token}) <NEW_LINE> return HttpResponse(data, mimetype='application/json') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return HttpResponse('', mimetype='application/json') | Purpose of this view is to generate a token given a session_token | 6259907e55399d3f05627f82 |
class RandomCrop(object): <NEW_LINE> <INDENT> def __init__(self, output_size): <NEW_LINE> <INDENT> assert isinstance(output_size, (int, tuple)) <NEW_LINE> if isinstance(output_size, int): <NEW_LINE> <INDENT> self.output_size = (output_size, output_size) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert len(output_size) == 2 <NEW_LINE> self.output_size = output_size <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> image, landmarks = sample['image'], sample['landmarks'] <NEW_LINE> h, w = image.shape[:2] <NEW_LINE> new_h, new_w = self.output_size <NEW_LINE> top = np.random.randint(0, h - new_h) <NEW_LINE> left = np.random.randint(0, w - new_w) <NEW_LINE> image = image[top: top + new_h, left: left + new_w] <NEW_LINE> landmarks = landmarks - [left, top] <NEW_LINE> return {'image': image, 'landmarks': landmarks} | Crop randomly the image in a sample.
Args:
output_size (tuple or int): Desired output size. If int, square crop
is made. | 6259907e66673b3332c31e6d |
@toolbar_pool.register <NEW_LINE> class PlaceholderToolbar(CMSToolbar): <NEW_LINE> <INDENT> def populate(self): <NEW_LINE> <INDENT> self.page = get_page_draft(self.request.current_page) <NEW_LINE> <DEDENT> def post_template_populate(self): <NEW_LINE> <INDENT> super().post_template_populate() <NEW_LINE> self.add_wizard_button() <NEW_LINE> <DEDENT> def add_wizard_button(self): <NEW_LINE> <INDENT> from cms.wizards.wizard_pool import entry_choices <NEW_LINE> title = _("Create") <NEW_LINE> if self.page: <NEW_LINE> <INDENT> user = self.request.user <NEW_LINE> page_pk = self.page.pk <NEW_LINE> disabled = len(list(entry_choices(user, self.page))) == 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> page_pk = '' <NEW_LINE> disabled = True <NEW_LINE> <DEDENT> url = '{url}?page={page}&language={lang}&edit'.format( url=reverse("cms_wizard_create"), page=page_pk, lang=self.toolbar.site_language, ) <NEW_LINE> self.toolbar.add_modal_button(title, url, side=self.toolbar.RIGHT, disabled=disabled, on_close=REFRESH_PAGE) | Adds placeholder edit buttons if placeholders or static placeholders are detected in the template | 6259907ef548e778e596cfff |
class TypographyPlugin(Plugin): <NEW_LINE> <INDENT> NNBSP = u' ' <NEW_LINE> def __init__(self, site): <NEW_LINE> <INDENT> from typogrify import filters <NEW_LINE> original_process_ignores = filters.process_ignores <NEW_LINE> filters.applyfilters = lambda text: self.owntypo(filters.smartypants(text)) <NEW_LINE> filters.process_ignores = self.process_ignores(original_process_ignores) <NEW_LINE> filters.widont = lambda t: t <NEW_LINE> <DEDENT> def process_ignores(self, orig): <NEW_LINE> <INDENT> def process(text, ignore_tags=None): <NEW_LINE> <INDENT> if ignore_tags is None: <NEW_LINE> <INDENT> ignore_tags = [] <NEW_LINE> <DEDENT> ignore_tags.append("x-latex") <NEW_LINE> return orig(text, ignore_tags) <NEW_LINE> <DEDENT> return process <NEW_LINE> <DEDENT> def owntypo(self, text): <NEW_LINE> <INDENT> tag_pattern = '</?\w+((\s+\w+(\s*=\s*(?:".*?"|\'.*?\'|[^\'">\s]+))?)+\s*|\s*)/?>' <NEW_LINE> fix_closing_double_quote = re.compile(r"""^“([,:;!\?])""") <NEW_LINE> fix_possessive_quote = re.compile(r"""^‘(s\s)""") <NEW_LINE> space_before_punct_finder = re.compile(r"""(\s| )([:;!\?%»])""") <NEW_LINE> space_after_punct_finder = re.compile(r"""([«])(\s| )""") <NEW_LINE> space_between_figures_finder = re.compile(r"""([0-9]|^)(\s| )([0-9]+(?:\W|$))""") <NEW_LINE> version_number_finder = re.compile(r"""(\b[A-Z][a-zA-Z]+)(\s| )([0-9]+(?:\W|$))""") <NEW_LINE> si_unit_finder = re.compile(r"""(\b[0-9,.]+)( | )(\w|€)""") <NEW_LINE> intra_tag_finder = re.compile(r'(?P<prefix>(%s)?)(?P<text>([^<]*))(?P<suffix>(%s)?)' % (tag_pattern, tag_pattern)) <NEW_LINE> def _process(groups): <NEW_LINE> <INDENT> prefix = groups.group('prefix') or '' <NEW_LINE> text = groups.group('text') <NEW_LINE> text = fix_closing_double_quote.sub(r'”\1', text) <NEW_LINE> text = fix_possessive_quote.sub(r'’\1', text) <NEW_LINE> text = space_before_punct_finder.sub(self.NNBSP + r"\2", text) <NEW_LINE> text = space_after_punct_finder.sub(r"\1" + self.NNBSP, text) <NEW_LINE> text = space_between_figures_finder.sub(r"\1" + self.NNBSP + r"\3", text) <NEW_LINE> text = version_number_finder.sub(r"\1" + self.NNBSP + r"\3", text) <NEW_LINE> text = si_unit_finder.sub(r"\1" + self.NNBSP + r"\3", text) <NEW_LINE> suffix = groups.group('suffix') or '' <NEW_LINE> return prefix + text + suffix <NEW_LINE> <DEDENT> output = intra_tag_finder.sub(_process, text) <NEW_LINE> return output | Monkey-patch typogrify to correctly handle french punctuation and
various other aspects not handled by typogrify. | 6259907e5fdd1c0f98e5f9ed |
class UserList(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> users = Student.objects.all() <NEW_LINE> serializer = UserSerializer(users, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> serializer = UserSerializer(data=request.data) <NEW_LINE> if(serializer.initial_data['username'].isdigit()): <NEW_LINE> <INDENT> return Response(status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def delete(self, request, pk, format=None): <NEW_LINE> <INDENT> user = self.get_objectid(pk) <NEW_LINE> user.delete() <NEW_LINE> return Response(status=status.HTTP_204_NO_CONTENT) | List all users, or create a new user. | 6259907e1b99ca400229026c |
class Expected: <NEW_LINE> <INDENT> def __init__(self, status: int, tokens: List[str], **kwargs): <NEW_LINE> <INDENT> self.status = status <NEW_LINE> self.tokens = tokens <NEW_LINE> for key, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, key, value) | Result object type for parametrized tests. Expand as necessary... | 6259907e796e427e538501e9 |
class Tag(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=100) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = u"Тег" <NEW_LINE> verbose_name_plural = u"Теги" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def all(cls): <NEW_LINE> <INDENT> return cls.objects.all() <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return u"/tags/%s/" % self.title <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.title | Tag
Keyword arguments:
@param title: name for tag | 6259907e4a966d76dd5f0955 |
class LegacyRegistrationMapping(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'legacy_registration_map' <NEW_LINE> __table_args__ = {'schema': 'event_registration'} <NEW_LINE> event_id = db.Column( db.Integer, db.ForeignKey('events.events.id'), primary_key=True, autoincrement=False ) <NEW_LINE> legacy_registrant_id = db.Column( db.Integer, primary_key=True, autoincrement=False ) <NEW_LINE> legacy_registrant_key = db.Column( db.String, nullable=False ) <NEW_LINE> registration_id = db.Column( db.Integer, db.ForeignKey('event_registration.registrations.id'), index=True, nullable=False ) <NEW_LINE> registration = db.relationship( 'Registration', lazy=False, backref=db.backref( 'legacy_mapping', cascade='all, delete-orphan', uselist=False, lazy=True ) ) <NEW_LINE> @return_ascii <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return format_repr(self, 'event_id', 'legacy_registrant_id', 'legacy_registrant_key', 'registration_id') | Legacy registration id/token mapping
Legacy registrations had tokens which are not compatible with the
new UUID-based ones. | 6259907e1f5feb6acb164668 |
class TestMethods(unittest.TestCase): <NEW_LINE> <INDENT> def test_activation(self): <NEW_LINE> <INDENT> network = NeuralNetwork(3, 2, 1, 0.5) <NEW_LINE> self.assertTrue(np.all(network.activation_function(0.5) == 1/(1+np.exp(-0.5)))) <NEW_LINE> <DEDENT> def test_train(self): <NEW_LINE> <INDENT> network = NeuralNetwork(3, 2, 1, 0.5) <NEW_LINE> network.weights_input_to_hidden = test_w_i_h.copy() <NEW_LINE> network.weights_hidden_to_output = test_w_h_o.copy() <NEW_LINE> network.train(inputs, targets) <NEW_LINE> self.assertTrue(np.allclose(network.weights_hidden_to_output, np.array([[ 0.37275328], [-0.03172939]]))) <NEW_LINE> self.assertTrue(np.allclose(network.weights_input_to_hidden, np.array([[ 0.10562014, -0.20185996], [0.39775194, 0.50074398], [-0.29887597, 0.19962801]]))) <NEW_LINE> <DEDENT> def test_run(self): <NEW_LINE> <INDENT> network = NeuralNetwork(3, 2, 1, 0.5) <NEW_LINE> network.weights_input_to_hidden = test_w_i_h.copy() <NEW_LINE> network.weights_hidden_to_output = test_w_h_o.copy() <NEW_LINE> self.assertTrue(np.allclose(network.run(inputs), 0.09998924)) | def test_data_path(self):
# Test that file path to dataset has been unaltered
global data_path
self.assertTrue(data_path.lower() == 'bike-sharing-dataset/hour.csv')
def test_data_loaded(self):
# Test that data frame loaded
global rides
self.assertTrue(isinstance(rides, pd.DataFrame)) | 6259907e3346ee7daa338399 |
class Scanner: <NEW_LINE> <INDENT> def __init__(self, input_file): <NEW_LINE> <INDENT> self.input_string = input_file.read() <NEW_LINE> self.current_char_index = 0 <NEW_LINE> self.current_token = self.get_token() <NEW_LINE> <DEDENT> def skip_white_space(self): <NEW_LINE> <INDENT> while (self.current_char_index < len(self.input_string) and self.input_string[self.current_char_index].isspace()): <NEW_LINE> <INDENT> self.current_char_index +=1 <NEW_LINE> <DEDENT> <DEDENT> def no_token(self): <NEW_LINE> <INDENT> print('lexical error: no token found at the start of ' + self.input_string[self.current_char_index:]) <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> def get_token(self): <NEW_LINE> <INDENT> self.skip_white_space() <NEW_LINE> token, longest = None, '' <NEW_LINE> for (t, r) in Token.token_regexp: <NEW_LINE> <INDENT> match = re.match(r, self.input_string[self.current_char_index:]) <NEW_LINE> if match and match.end() > len(longest): <NEW_LINE> <INDENT> token, longest = t, match.group() <NEW_LINE> <DEDENT> <DEDENT> self.current_char_index += len(longest) <NEW_LINE> if token is None and (self.current_char_index < len(self.input_string)): <NEW_LINE> <INDENT> self.no_token() <NEW_LINE> <DEDENT> return (token, longest) <NEW_LINE> <DEDENT> def lookahead(self): <NEW_LINE> <INDENT> return self.current_token[0] <NEW_LINE> <DEDENT> def unexpected_token(self, found_token, expected_tokens): <NEW_LINE> <INDENT> print('syntax error: token in ' + repr(sorted(expected_tokens)) + ' expected but ' + repr(found_token) + ' found') <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> def consume(self, *expected_tokens): <NEW_LINE> <INDENT> prev_token = self.current_token <NEW_LINE> if prev_token[0] in expected_tokens: <NEW_LINE> <INDENT> self.current_token = self.get_token() <NEW_LINE> if (prev_token[0] == 'NUM') or (prev_token[0] == 'ID'): <NEW_LINE> <INDENT> return prev_token <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return prev_token[0] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.unexpected_token(prev_token[0], expected_tokens) | The interface comprises the methods lookahead and consume.
Other methods should not be called from outside of this class. | 6259907e4c3428357761bd29 |
class Disconnected(Event): <NEW_LINE> <INDENT> __slots__ = ['graceful', 'reason'] <NEW_LINE> name = 'disconnected' <NEW_LINE> def __init__(self, reason='closed', graceful=False): <NEW_LINE> <INDENT> self.reason = reason <NEW_LINE> self.graceful = graceful <NEW_LINE> super(Disconnected, self).__init__() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{}(reason='{}', graceful={!r})".format( self.__class__.__name__, self.reason, self.graceful ) | Generated when a websocket connection has
been dropped.
:param str reason: A description of why the websocket was closed.
:param bool graceful: Flag indicating if the connection was dropped
gracefully (`True`), or disconnected due to a socket failure
(`False`) or other problem. | 6259907e2c8b7c6e89bd5255 |
class OpenIDHybridInterferenceTest(AuthorizationCodeGrantTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.auth = HybridGrant(request_validator=self.mock_validator) | Test that OpenID don't interfere with normal OAuth 2 flows. | 6259907e55399d3f05627f84 |
class FTIRhelp(QDialog, Ui_help_FTIR): <NEW_LINE> <INDENT> def __init__(self, root): <NEW_LINE> <INDENT> QDialog.__init__(self, root) <NEW_LINE> Ui_help_FTIR.__init__(self) <NEW_LINE> self.setupUi(self) | Help window with update logs. | 6259907e283ffb24f3cf5310 |
class Sorts(): <NEW_LINE> <INDENT> def __init__(self,mylist): <NEW_LINE> <INDENT> self.mylist = mylist <NEW_LINE> <DEDENT> def selection_sort(self): <NEW_LINE> <INDENT> left_list = list() <NEW_LINE> right_list = self.mylist <NEW_LINE> assert type(right_list) == list <NEW_LINE> x = len(right_list) <NEW_LINE> y = 1 <NEW_LINE> smallest = None <NEW_LINE> first = None <NEW_LINE> for i in range(0,x): <NEW_LINE> <INDENT> first = right_list[0] <NEW_LINE> while y < len(right_list): <NEW_LINE> <INDENT> if first > right_list[y]: <NEW_LINE> <INDENT> smallest = right_list[y] <NEW_LINE> first = smallest <NEW_LINE> <DEDENT> elif first == right_list[y]: <NEW_LINE> <INDENT> smallest = first <NEW_LINE> <DEDENT> elif first < right_list[y]: <NEW_LINE> <INDENT> smallest = first <NEW_LINE> <DEDENT> y = y+1 <NEW_LINE> <DEDENT> y = 1 <NEW_LINE> left_list.append(smallest) <NEW_LINE> right_list.remove(smallest) <NEW_LINE> if len(right_list) == 1: <NEW_LINE> <INDENT> left_list.append(right_list[0]) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return left_list <NEW_LINE> <DEDENT> def insert_sort(self): <NEW_LINE> <INDENT> x = 0 <NEW_LINE> y = 1 <NEW_LINE> myindex = 0 <NEW_LINE> mylist = self.mylist <NEW_LINE> assert type(mylist) == list <NEW_LINE> for i in range(0,len(mylist)): <NEW_LINE> <INDENT> while x < len(mylist) and y < len(mylist): <NEW_LINE> <INDENT> if mylist[x] > mylist[y]: <NEW_LINE> <INDENT> myindex = y <NEW_LINE> mylist.insert(y+1,mylist[x]) <NEW_LINE> mylist.remove(mylist[x]) <NEW_LINE> <DEDENT> x = x+1 <NEW_LINE> y = y+1 <NEW_LINE> <DEDENT> x = 0 <NEW_LINE> y = 1 <NEW_LINE> myindex = 0 <NEW_LINE> sorted_list = mylist <NEW_LINE> <DEDENT> return sorted_list <NEW_LINE> <DEDENT> def merge_sort(self): <NEW_LINE> <INDENT> startlist = self.mylist <NEW_LINE> assert type(startlist) == list <NEW_LINE> mylist = list() <NEW_LINE> sublist = list() <NEW_LINE> for i in startlist: <NEW_LINE> <INDENT> sublist.append(i) <NEW_LINE> mylist.append(sublist) <NEW_LINE> sublist = list() <NEW_LINE> <DEDENT> sublist1 = list() <NEW_LINE> sublist2 = list() <NEW_LINE> newlist = list() <NEW_LINE> sublist1 = mylist[0] <NEW_LINE> sublist2 = mylist[1] <NEW_LINE> while len(mylist) >1: <NEW_LINE> <INDENT> if sublist1 == [] and sublist2 == []: <NEW_LINE> <INDENT> mylist.remove([]) <NEW_LINE> mylist.remove([]) <NEW_LINE> mylist.append(newlist) <NEW_LINE> if len(mylist) >= 2: <NEW_LINE> <INDENT> newlist = list() <NEW_LINE> sublist1 = mylist[0] <NEW_LINE> sublist2 = mylist[1] <NEW_LINE> <DEDENT> <DEDENT> elif sublist1 == [] and sublist2 != []: <NEW_LINE> <INDENT> newlist.append(sublist2[0]) <NEW_LINE> sublist2.remove(sublist2[0]) <NEW_LINE> <DEDENT> elif sublist2 == [] and sublist1 != []: <NEW_LINE> <INDENT> newlist.append(sublist1[0]) <NEW_LINE> sublist1.remove(sublist1[0]) <NEW_LINE> <DEDENT> elif sublist1[0] >= sublist2[0]: <NEW_LINE> <INDENT> newlist.append(sublist2[0]) <NEW_LINE> sublist2.remove(sublist2[0]) <NEW_LINE> <DEDENT> elif sublist1[0] < sublist2[0]: <NEW_LINE> <INDENT> newlist.append(sublist1[0]) <NEW_LINE> sublist1.remove(sublist1[0]) <NEW_LINE> <DEDENT> <DEDENT> return newlist | Contains three different sorting functions | 6259907efff4ab517ebcf288 |
class CATMAID_OP_material_randomize(Operator): <NEW_LINE> <INDENT> bl_idname = "material.randomize" <NEW_LINE> bl_label = "Assign (semi-) random colors" <NEW_LINE> bl_description = "Assign (semi-) random colors" <NEW_LINE> bl_options = {'UNDO'} <NEW_LINE> which_neurons: EnumProperty(name="Which Neurons?", items=[('Selected', 'Selected', 'Selected'), ('All', 'All', 'All')], description="Choose which neurons to give random color.", default='All') <NEW_LINE> color_range: EnumProperty(name="Range", items=(('RGB', 'RGB', 'RGB'), ("Grayscale", "Grayscale", "Grayscale"),), default="RGB", description="Choose mode of randomizing colors") <NEW_LINE> start_color: FloatVectorProperty(name="Color range start", description="Set start of color range (for RGB). Keep start and end the same to use full range.", default=(1, 0.0, 0.0), min=0.0, max=1.0, subtype='COLOR') <NEW_LINE> end_color: FloatVectorProperty(name="Color range end", description="Set end of color range (for RGB). Keep start and end the same to use full range.", default=(1, 0.0, 0.0), min=0.0, max=1.0, subtype='COLOR') <NEW_LINE> def invoke(self, context, event): <NEW_LINE> <INDENT> return context.window_manager.invoke_props_dialog(self) <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> if self.which_neurons == 'All': <NEW_LINE> <INDENT> to_process = bpy.data.objects <NEW_LINE> <DEDENT> elif self.which_neurons == 'Selected': <NEW_LINE> <INDENT> to_process = bpy.context.selected_objects <NEW_LINE> <DEDENT> to_process = [o for o in to_process if 'type' in o] <NEW_LINE> to_process = [o for o in to_process if o['type'] == 'NEURON'] <NEW_LINE> neurons = set([o['id'] for o in to_process]) <NEW_LINE> colors = random_colors(len(neurons), color_range=self.color_range, start_rgb=self.start_color, end_rgb=self.end_color, alpha=1) <NEW_LINE> colormap = dict(zip(neurons, colors)) <NEW_LINE> for ob in to_process: <NEW_LINE> <INDENT> ob.active_material.diffuse_color = colormap[ob['id']] <NEW_LINE> <DEDENT> return {'FINISHED'} | Assigns new semi-random colors to neurons | 6259907e4f6381625f19a1e6 |
class Puck(object): <NEW_LINE> <INDENT> def __init__(self, canvas, background): <NEW_LINE> <INDENT> self.background = background <NEW_LINE> self.screen = self.background.get_screen() <NEW_LINE> self.x, self.y = self.screen[0]/2, self.screen[1]/2 <NEW_LINE> self.can, self.w = canvas, self.background.get_goal_w()/12 <NEW_LINE> c, d = rand() <NEW_LINE> self.vx, self.vy = 4*c, 6*d <NEW_LINE> self.a = .99 <NEW_LINE> self.cushion = self.w*0.25 <NEW_LINE> self.puck = PuckManager(canvas, self.w, (self.y, self.x)) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.vx > 0.25: self.vx *= self.a <NEW_LINE> if self.vy > 0.25: self.vy *= self.a <NEW_LINE> x, y = self.x + self.vx, self.y + self.vy <NEW_LINE> if not self.background.is_position_valid((x, y), self.w): <NEW_LINE> <INDENT> if x - self.w < ZERO or x + self.w > self.screen[0]: <NEW_LINE> <INDENT> self.vx *= -1 <NEW_LINE> <DEDENT> if y - self.w < ZERO or y + self.w > self.screen[1]: <NEW_LINE> <INDENT> self.vy *= -1 <NEW_LINE> <DEDENT> x, y = self.x+self.vx, self.y+self.vy <NEW_LINE> <DEDENT> self.x, self.y = x, y <NEW_LINE> self.puck.update((self.x, self.y)) <NEW_LINE> <DEDENT> def hit(self, paddle, moving): <NEW_LINE> <INDENT> x, y = paddle.get_position() <NEW_LINE> if moving: <NEW_LINE> <INDENT> if (x > self.x - self.cushion and x < self.x + self.cushion or abs(self.vx) > MAX_SPEED): <NEW_LINE> <INDENT> xpower = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xpower = 5 if self.vx < 2 else 2 <NEW_LINE> <DEDENT> if (y > self.y - self.cushion and y < self.y + self.cushion or abs(self.vy) > MAX_SPEED): <NEW_LINE> <INDENT> ypower = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ypower = 5 if self.vy < 2 else 2 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> xpower, ypower = 1, 1 <NEW_LINE> <DEDENT> if self.x + self.cushion < x: <NEW_LINE> <INDENT> xpower *= -1 <NEW_LINE> <DEDENT> if self.y + self.cushion < y: <NEW_LINE> <INDENT> ypower *= -1 <NEW_LINE> <DEDENT> self.vx = abs(self.vx)*xpower <NEW_LINE> self.vy = abs(self.vy)*ypower <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return other == self.puck <NEW_LINE> <DEDENT> def in_goal(self): <NEW_LINE> <INDENT> return self.background.is_in_goal((self.x, self.y), self.w) | canvas: tk.Canvas object.
background: Background object. | 6259907e4a966d76dd5f0957 |
@override_settings( LANGUAGES=( ('en', 'English'), ), LANGUAGE_CODE='en', TEMPLATE_LOADERS=global_settings.TEMPLATE_LOADERS, TEMPLATE_DIRS=( os.path.join(os.path.dirname(upath(__file__)), 'templates'), ), USE_TZ=False, PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ) <NEW_LINE> class AuthViewsTestCase(TestCase): <NEW_LINE> <INDENT> fixtures = ['authtestdata.json'] <NEW_LINE> urls = 'django.contrib.auth.tests.urls' <NEW_LINE> def login(self, username='testclient', password='password'): <NEW_LINE> <INDENT> response = self.client.post('/login/', { 'username': username, 'password': password, }) <NEW_LINE> self.assertTrue(SESSION_KEY in self.client.session) <NEW_LINE> return response <NEW_LINE> <DEDENT> def logout(self): <NEW_LINE> <INDENT> response = self.client.get('/admin/logout/') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertTrue(SESSION_KEY not in self.client.session) <NEW_LINE> <DEDENT> def assertFormError(self, response, error): <NEW_LINE> <INDENT> form_errors = list(itertools.chain(*response.context['form'].errors.values())) <NEW_LINE> self.assertIn(force_text(error), form_errors) <NEW_LINE> <DEDENT> def assertURLEqual(self, url, expected, parse_qs=False): <NEW_LINE> <INDENT> fields = ParseResult._fields <NEW_LINE> for attr, x, y in zip(fields, urlparse(url), urlparse(expected)): <NEW_LINE> <INDENT> if parse_qs and attr == 'query': <NEW_LINE> <INDENT> x, y = QueryDict(x), QueryDict(y) <NEW_LINE> <DEDENT> if x and y and x != y: <NEW_LINE> <INDENT> self.fail("%r != %r (%s doesn't match)" % (url, expected, attr)) | Helper base class for all the follow test cases. | 6259907eaad79263cf43022b |
class CLine(GeometricalEntity): <NEW_LINE> <INDENT> def __init__(self, kw): <NEW_LINE> <INDENT> argDescription={"CLINE_0":Point, "CLINE_1":Point} <NEW_LINE> GeometricalEntity.__init__(self,kw, argDescription) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Construction line through point %s at %s " % (self.p1, self.p2) <NEW_LINE> <DEDENT> @property <NEW_LINE> def info(self): <NEW_LINE> <INDENT> return "CLine: %s, %s"%(str(self.p1), str(self.p2)) <NEW_LINE> <DEDENT> def rotate(self, rotationPoint, angle): <NEW_LINE> <INDENT> self.p1=GeometricalEntity.rotate(self, rotationPoint,self.p1, angle ) <NEW_LINE> self.p2=GeometricalEntity.rotate(self, rotationPoint,self.p2, angle ) <NEW_LINE> <DEDENT> def isVertical(self): <NEW_LINE> <INDENT> x1, y1=self.p1.getCoords() <NEW_LINE> x2, y2=self.p1.getCoords() <NEW_LINE> return abs(y1 - y2) < 1e-10 <NEW_LINE> <DEDENT> def isHorizontal(self): <NEW_LINE> <INDENT> x1, y1=self.p1.getCoords() <NEW_LINE> x2, y2=self.p1.getCoords() <NEW_LINE> return abs(x1 - x2) < 1e-10 <NEW_LINE> <DEDENT> def getP1(self): <NEW_LINE> <INDENT> return self['CLINE_0'] <NEW_LINE> <DEDENT> def setP1(self, p): <NEW_LINE> <INDENT> if not isinstance(p, Point): <NEW_LINE> <INDENT> raise TypeError("Unexpected type for point: " + repr(type(p))) <NEW_LINE> <DEDENT> self['CLINE_0']=p <NEW_LINE> <DEDENT> p1=property(getP1, setP1, None, "Set the location of the first point of the line") <NEW_LINE> def getP2(self): <NEW_LINE> <INDENT> return self['CLINE_1'] <NEW_LINE> <DEDENT> def setP2(self, p): <NEW_LINE> <INDENT> if not isinstance(p, Point): <NEW_LINE> <INDENT> raise TypeError("Unexpected type for point: " + repr(type(p))) <NEW_LINE> <DEDENT> self['CLINE_1']=p <NEW_LINE> <DEDENT> p2=property(getP2, setP2, None, "Set the location of the first point of the line") <NEW_LINE> def getKeypoints(self): <NEW_LINE> <INDENT> return p1, p2 <NEW_LINE> <DEDENT> def getAngle(self): <NEW_LINE> <INDENT> return float(mainSympy.atan(getSympy.slope)) <NEW_LINE> <DEDENT> def clone(self): <NEW_LINE> <INDENT> return CLine(self) <NEW_LINE> <DEDENT> def getSympy(self): <NEW_LINE> <INDENT> _sp1=self.p1.getSympy() <NEW_LINE> _sp2=self.p2.getSympy() <NEW_LINE> return geoSympy.Line(_sp1, _sp2) <NEW_LINE> <DEDENT> def setFromSympy(self, sympySegment): <NEW_LINE> <INDENT> self.p1.setFromSympy(sympySegment.p1) <NEW_LINE> self.p2.setFromSympy(sympySegment.p2) <NEW_LINE> <DEDENT> @property <NEW_LINE> def vector(self): <NEW_LINE> <INDENT> return Vector(self.p1, self.p2) <NEW_LINE> <DEDENT> def mirror(self, mirrorRef): <NEW_LINE> <INDENT> from Kernel.GeoEntity.segment import Segment <NEW_LINE> if not isinstance(mirrorRef, (CLine, Segment)): <NEW_LINE> <INDENT> raise TypeError("mirrorObject must be Cline Segment or a tuple of points") <NEW_LINE> <DEDENT> self.p1.mirror(mirrorRef) <NEW_LINE> self.p2.mirror(mirrorRef) | A class for single point construction lines From Two points. | 6259907e4428ac0f6e659fa0 |
class CommandHandler: <NEW_LINE> <INDENT> def __init__(self , prefix , client): <NEW_LINE> <INDENT> queuehelper = QueueHelper() <NEW_LINE> self.commandlist = [ Ping() , Say() , Translate() , HelloWorld(), News(), Crypto(), Math(), Play(queuehelper), Playing(queuehelper), Queue(queuehelper), Shuffle(queuehelper), Hash(), Encrypt(), Decrypt(), Wiki(), ] <NEW_LINE> self.prefix = prefix <NEW_LINE> self.client = client <NEW_LINE> self.commandlist.append(Help(self.commandlist , self.prefix)) <NEW_LINE> <DEDENT> async def handle(self , message): <NEW_LINE> <INDENT> for command in self.commandlist: <NEW_LINE> <INDENT> if self.is_alias(command, message.content): <NEW_LINE> <INDENT> if not await command.execute(self.client , message , self.get_args(message.content)): <NEW_LINE> <INDENT> await self.client.send_message(message.channel , content=command.get_wrong_usage()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def get_args(message): <NEW_LINE> <INDENT> args = message.split(" ") <NEW_LINE> args.pop(0) <NEW_LINE> return args <NEW_LINE> <DEDENT> def is_alias(self, cmd, message): <NEW_LINE> <INDENT> for alias in cmd.aliases: <NEW_LINE> <INDENT> if message.lower().startswith(self.prefix + alias.lower()): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | CommandHandler is used to call the correct command and handle help | 6259907ea05bb46b3848be61 |
class Pad(object): <NEW_LINE> <INDENT> def __init__(self, padding, fill=0, padding_mode='constant'): <NEW_LINE> <INDENT> assert isinstance(padding, (numbers.Number, tuple)) <NEW_LINE> assert isinstance(fill, (numbers.Number, str, tuple)) <NEW_LINE> assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'] <NEW_LINE> if isinstance(padding, collections.Sequence) and len(padding) not in [2, 4]: <NEW_LINE> <INDENT> raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " + "{} element tuple".format(len(padding))) <NEW_LINE> <DEDENT> self.padding = padding <NEW_LINE> self.fill = fill <NEW_LINE> self.padding_mode = padding_mode <NEW_LINE> <DEDENT> def __call__(self, img): <NEW_LINE> <INDENT> return F.pad(img, self.padding, self.fill, self.padding_mode) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ + '(padding={0}, fill={1}, padding_mode={2})'. format(self.padding, self.fill, self.padding_mode) | Pad the given PIL Image on all sides with the given "pad" value.
Args:
padding (int or tuple): Padding on each border. If a single int is provided this
is used to pad all borders. If tuple of length 2 is provided this is the padding
on left/right and top/bottom respectively. If a tuple of length 4 is provided
this is the padding for the left, top, right and bottom borders
respectively.
fill (int or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of
length 3, it is used to fill R, G, B channels respectively.
This value is only used when the padding_mode is constant
padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
Default is constant.
- constant: pads with a constant value, this value is specified with fill
- edge: pads with the last value at the edge of the image
- reflect: pads with reflection of image without repeating the last value on the edge
For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
will result in [3, 2, 1, 2, 3, 4, 3, 2]
- symmetric: pads with reflection of image repeating the last value on the edge
For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
will result in [2, 1, 1, 2, 3, 4, 4, 3] | 6259907e1b99ca400229026e |
class UserGenerator(PtbGenerator): <NEW_LINE> <INDENT> FIRST_NAMES = [ "James", "Mary", "John", "Patricia", "Robert", "Jennifer", "Michael", "Elizabeth", "William", "Linda", "David", "Barbara", "Richard", "Susan", "Joseph", "Jessica", "Thomas", "Margaret", "Charles", "Sarah" ] <NEW_LINE> LAST_NAMES = [ "Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Taylor" ] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> PtbGenerator.__init__(self) <NEW_LINE> <DEDENT> def get_user(self, first_name=None, last_name=None, username=None, id=None, is_bot=False): <NEW_LINE> <INDENT> if not first_name: <NEW_LINE> <INDENT> first_name = random.choice(self.FIRST_NAMES) <NEW_LINE> <DEDENT> if not last_name: <NEW_LINE> <INDENT> last_name = random.choice(self.LAST_NAMES) <NEW_LINE> <DEDENT> if not username: <NEW_LINE> <INDENT> username = first_name + last_name <NEW_LINE> <DEDENT> return User( id or self.gen_id(), first_name, is_bot=is_bot, last_name=last_name, username=username) | User generator class. placeholder for random names and mainly used
via it's get_user() method | 6259907e99fddb7c1ca63b11 |
class IMB(Benchmark): <NEW_LINE> <INDENT> DEFAULT_EXECUTABLE = 'IMB-MPI1' <NEW_LINE> PING_PONG = 'PingPong' <NEW_LINE> ALL_TO_ALL = 'Alltoallv' <NEW_LINE> ALL_GATHER = 'Allgather' <NEW_LINE> DEFAULT_CATEGORIES = [PING_PONG, ALL_TO_ALL, ALL_GATHER] <NEW_LINE> DEFAULT_ARGUMENTS = { ALL_GATHER: ["-npmin", "{process_count}"], ALL_TO_ALL: ["-npmin", "{process_count}"], } <NEW_LINE> NODE_PAIRING = {'node', 'tag'} <NEW_LINE> DEFAULT_NODE_PAIRING = 'node' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(IMB, self).__init__( attributes=dict( executable=IMB.DEFAULT_EXECUTABLE, categories=IMB.DEFAULT_CATEGORIES, arguments=IMB.DEFAULT_ARGUMENTS, srun_nodes=0, node_pairing=IMB.DEFAULT_NODE_PAIRING, ) ) <NEW_LINE> <DEDENT> name = 'imb' <NEW_LINE> @cached_property <NEW_LINE> def executable(self): <NEW_LINE> <INDENT> return self.attributes['executable'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def categories(self): <NEW_LINE> <INDENT> return self.attributes['categories'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def arguments(self): <NEW_LINE> <INDENT> return self.attributes['arguments'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def srun_nodes(self): <NEW_LINE> <INDENT> return self.attributes['srun_nodes'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def node_pairing(self): <NEW_LINE> <INDENT> value = self.attributes['node_pairing'] <NEW_LINE> if value not in IMB.NODE_PAIRING: <NEW_LINE> <INDENT> msg = 'Unexpected {0} value: got "{1}" but valid values are {2}' <NEW_LINE> msg = msg.format('node_pairing', value, IMB.NODE_PAIRING) <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def _node_pairs(self, context): <NEW_LINE> <INDENT> if self.node_pairing == 'node': <NEW_LINE> <INDENT> return context.cluster.node_pairs <NEW_LINE> <DEDENT> elif self.node_pairing == 'tag': <NEW_LINE> <INDENT> return context.cluster.tag_node_pairs <NEW_LINE> <DEDENT> assert False <NEW_LINE> <DEDENT> def execution_matrix(self, context): <NEW_LINE> <INDENT> for category in self.categories: <NEW_LINE> <INDENT> arguments = self.arguments.get(category) or [] <NEW_LINE> if category == IMB.PING_PONG: <NEW_LINE> <INDENT> for pair in self._node_pairs(context): <NEW_LINE> <INDENT> yield dict( category=category, command=[ find_executable(self.executable, required=False), category, ] + arguments, srun_nodes=pair, metas=dict(from_node=pair[0], to_node=pair[1]), ) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> yield dict( category=category, command=[find_executable(self.executable, required=False), category] + list(arguments), srun_nodes=self.srun_nodes, ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @cached_property <NEW_LINE> def metrics_extractors(self): <NEW_LINE> <INDENT> return { IMB.PING_PONG: IMBPingPongExtractor(), IMB.ALL_TO_ALL: IMBAllToAllExtractor(), IMB.ALL_GATHER: IMBAllGatherExtractor(), } | Provides latency/bandwidth of the network.
the `srun_nodes` does not apply to the PingPong benchmark. | 6259907e7d43ff248742814e |
class HomeHandler(BaseHandler): <NEW_LINE> <INDENT> @web.authenticated <NEW_LINE> def get(self): <NEW_LINE> <INDENT> self.x = list() <NEW_LINE> self.mypath = "." <NEW_LINE> self.onlyfiles = [ f for f in listdir(join("/home", self.get_current_user().name, "dds-notebooks/notebooks")) if bool(re.search("\w+.ipynb",f))] <NEW_LINE> print(self.onlyfiles) <NEW_LINE> self.x = tornado.escape.json_encode(self.onlyfiles) <NEW_LINE> uname = str(self.get_current_user().name) <NEW_LINE> html = self.render_template('home.html', uname=[uname], user=self.get_current_user(), test=self.x ) <NEW_LINE> self.finish(html) <NEW_LINE> <DEDENT> @web.authenticated <NEW_LINE> def post(self): <NEW_LINE> <INDENT> a = self.get_argument("test", "") <NEW_LINE> shuffle(self.onlyfiles) <NEW_LINE> self.x = tornado.escape.json_encode(self.onlyfiles) <NEW_LINE> print(self.x) <NEW_LINE> print("post: " + str(a)) <NEW_LINE> print("################") <NEW_LINE> print("HAPPENED") | Render the user's home page. | 6259907ea8370b77170f1e42 |
class UserProfile(base_models.TimeStampedModel, Verification): <NEW_LINE> <INDENT> ACTIVATED = "ALREADY ACTIVATED" <NEW_LINE> user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) <NEW_LINE> verification_key = models.CharField( max_length=40 ) <NEW_LINE> image = models.ImageField(blank=True, null=False, upload_to = 'images/bikes/') <NEW_LINE> phn_no = models.CharField(null=True, max_length=10, validators=[RegexValidator(regex='^.{10}$', message='Length has to be 10', code='nomatch')]) <NEW_LINE> objects = UserProfileRegistrationManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = u'user profile' <NEW_LINE> verbose_name_plural = u'user profiles' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.user) <NEW_LINE> <DEDENT> def verification_key_expired(self): <NEW_LINE> <INDENT> expiration_date = datetime.timedelta( days=getattr(settings, 'VERIFICATION_KEY_EXPIRY_DAYS', 4) ) <NEW_LINE> return self.verification_key == self.ACTIVATED or (self.user.date_joined + expiration_date <= timezone.now()) <NEW_LINE> <DEDENT> def send_activation_email(self, site): <NEW_LINE> <INDENT> context = { 'verification_key': self.verification_key, 'expiration_days': getattr(settings, 'VERIFICATION_KEY_EXPIRY_DAYS', 4), 'user': self.user, 'site': site, 'site_name': getattr(settings, 'SITE_NAME', None) } <NEW_LINE> subject = render_to_string( 'registration/activation_email_subject.txt', context ) <NEW_LINE> subject = ''.join(subject.splitlines()) <NEW_LINE> message = render_to_string( 'registration/activation_email_content.txt', context ) <NEW_LINE> msg = EmailMultiAlternatives(subject, "", settings.DEFAULT_FROM_EMAIL, [self.user.email]) <NEW_LINE> msg.attach_alternative(message, "text/html") <NEW_LINE> msg.send() <NEW_LINE> <DEDENT> def send_password_reset_email(self, site): <NEW_LINE> <INDENT> context = { 'email': self.user.email, 'site': site, 'site_name': getattr(settings, 'SITE_NAME', None), 'uid': base_utils.base36encode(self.user.pk), 'user': self.user, 'token': token_generator.make_token(self.user) } <NEW_LINE> subject = render_to_string( 'password_reset/password_reset_email_subject.txt', context ) <NEW_LINE> subject = ''.join(subject.splitlines()) <NEW_LINE> message = render_to_string( 'password_reset/password_reset_email_content.txt', context ) <NEW_LINE> msg = EmailMultiAlternatives(subject, "", settings.DEFAULT_FROM_EMAIL, [self.user.email]) <NEW_LINE> msg.attach_alternative(message, "text/html") <NEW_LINE> msg.send() | A model for user profile that also stores verification key.
Any methods under User will reside here. | 6259907ed486a94d0ba2da29 |
@unique <NEW_LINE> class SpecialByte(Enum): <NEW_LINE> <INDENT> ESCAPE_BYTE = 0x7D <NEW_LINE> HEADER_BYTE = 0x7E <NEW_LINE> XON_BYTE = 0x11 <NEW_LINE> XOFF_BYTE = 0x13 <NEW_LINE> def __init__(self, code): <NEW_LINE> <INDENT> self.__code = code <NEW_LINE> <DEDENT> def __get_code(self): <NEW_LINE> <INDENT> return self.__code <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get(cls, value): <NEW_LINE> <INDENT> return SpecialByte.lookupTable[value] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def escape(value): <NEW_LINE> <INDENT> return value ^ 0x20 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_special_byte(value): <NEW_LINE> <INDENT> return True if value in [i.value for i in SpecialByte] else False <NEW_LINE> <DEDENT> code = property(__get_code) | Enumerates all the special bytes of the XBee protocol that must be escaped
when working on API 2 mode.
| Inherited properties:
| **name** (String): name (ID) of this SpecialByte.
| **value** (String): the value of this SpecialByte. | 6259907e7d847024c075de50 |
class RunnerIdentity(Identity): <NEW_LINE> <INDENT> pass | A corp identity card. | 6259907ee1aae11d1e7cf54b |
class BaseDeliveryEvent(BaseWebhookEvent): <NEW_LINE> <INDENT> def __init__(self, request, data): <NEW_LINE> <INDENT> super(BaseDeliveryEvent, self).__init__(request, data) <NEW_LINE> self.smtp_id = self.data['smtp-id'] | Basic interface shared for all delivery events
- bounce
- deferred
- delivered
- dropped
- processed | 6259907e5166f23b2e244e4b |
class OWNCommand(OWNMessage): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def parse(cls, data): <NEW_LINE> <INDENT> _match = re.match(r"^\*#?(?P<who>\d+)\*.+##$", data) <NEW_LINE> if _match: <NEW_LINE> <INDENT> _who = int(_match.group("who")) <NEW_LINE> if _who == 0: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 1: <NEW_LINE> <INDENT> return OWNLightingCommand(data) <NEW_LINE> <DEDENT> elif _who == 2: <NEW_LINE> <INDENT> return OWNAutomationCommand(data) <NEW_LINE> <DEDENT> elif _who == 3: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 4: <NEW_LINE> <INDENT> return OWNHeatingCommand(data) <NEW_LINE> <DEDENT> elif _who == 5: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 6: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 7: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 9: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 13: <NEW_LINE> <INDENT> return OWNGatewayCommand(data) <NEW_LINE> <DEDENT> elif _who == 14: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 15: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 16: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 17: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 18: <NEW_LINE> <INDENT> return OWNEnergyCommand(data) <NEW_LINE> <DEDENT> elif _who == 22: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 24: <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _who == 25: <NEW_LINE> <INDENT> _where = re.match(r"^\*.+\*(?P<where>\d+)##$", data).group("where") <NEW_LINE> if _where.startswith("2"): <NEW_LINE> <INDENT> return cls(data) <NEW_LINE> <DEDENT> elif _where.startswith("3"): <NEW_LINE> <INDENT> return OWNDryContactCommand(data) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None | This class is a subclass of messages.
All messages sent during a command session are commands.
Dividing this in a subclass provides better clarity | 6259907ef9cc0f698b1c6006 |
class BaseOrganizationQuerySet(models.QuerySet): <NEW_LINE> <INDENT> def for_user(self, user): <NEW_LINE> <INDENT> return self.filter( Q(owners__in=[user]) | Q(teams__members__in=[user]), ).distinct() <NEW_LINE> <DEDENT> def for_admin_user(self, user): <NEW_LINE> <INDENT> return self.filter(owners__in=[user],).distinct() <NEW_LINE> <DEDENT> def created_days_ago(self, days, field='pub_date'): <NEW_LINE> <INDENT> when = timezone.now() - timedelta(days=days) <NEW_LINE> query_filter = {} <NEW_LINE> query_filter[field + '__year'] = when.year <NEW_LINE> query_filter[field + '__month'] = when.month <NEW_LINE> query_filter[field + '__day'] = when.day <NEW_LINE> return self.filter(**query_filter) | Organizations queryset. | 6259907e3617ad0b5ee07bc2 |
class Ligotools(Package): <NEW_LINE> <INDENT> homepage = "http://www.example.com" <NEW_LINE> url = "http://software.ligo.org/lscsoft/source/ligotools-1.1.0.tar.gz" <NEW_LINE> version('1.2.0', '6933a83410e0bab5c4f390a26b6cf816') <NEW_LINE> version('1.1.0', '57ec7134faf031ce84e409856150c00c') <NEW_LINE> version('1.0.4', 'ad147cd4240a280465728883692903a1') <NEW_LINE> version('1.0.3', '6f09863c07bfc35eb7288e35865853aa') <NEW_LINE> version('1.0.2', 'a5665a267cd10048ea8c15b608b6b072') <NEW_LINE> version('1.0.1', 'a7ba3fef58f41f9ad1e0a721a83b7931') <NEW_LINE> variant('matlab', default=True) <NEW_LINE> depends_on('cmake') <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> with working_dir('spack-build', create=True): <NEW_LINE> <INDENT> cmake_args = [] <NEW_LINE> if '+matlab' in spec: <NEW_LINE> <INDENT> cmake_args.append('-DENABLE_BINARY_MATLAB=TRUE') <NEW_LINE> <DEDENT> cmake('..', *cmake_args + std_cmake_args) <NEW_LINE> make() <NEW_LINE> make('install') | FIXME: Put a proper description of your package here. | 6259907e2c8b7c6e89bd5259 |
class BridgeRpcCallbacks(n_rpc.RpcCallback, dhcp_rpc_base.DhcpRpcCallbackMixin, l3_rpc_base.L3RpcCallbackMixin, sg_db_rpc.SecurityGroupServerRpcCallbackMixin): <NEW_LINE> <INDENT> RPC_API_VERSION = '1.1' <NEW_LINE> TAP_PREFIX_LEN = 3 <NEW_LINE> @classmethod <NEW_LINE> def get_port_from_device(cls, device): <NEW_LINE> <INDENT> session = db.get_session() <NEW_LINE> port = brocade_db.get_port_from_device( session, device[cls.TAP_PREFIX_LEN:]) <NEW_LINE> if port: <NEW_LINE> <INDENT> port['device'] = device <NEW_LINE> port['device_owner'] = AGENT_OWNER_PREFIX <NEW_LINE> port['binding:vif_type'] = 'bridge' <NEW_LINE> <DEDENT> return port <NEW_LINE> <DEDENT> def get_device_details(self, rpc_context, **kwargs): <NEW_LINE> <INDENT> agent_id = kwargs.get('agent_id') <NEW_LINE> device = kwargs.get('device') <NEW_LINE> LOG.debug(_("Device %(device)s details requested from %(agent_id)s"), {'device': device, 'agent_id': agent_id}) <NEW_LINE> port = brocade_db.get_port(rpc_context, device[self.TAP_PREFIX_LEN:]) <NEW_LINE> if port: <NEW_LINE> <INDENT> entry = {'device': device, 'vlan_id': port.vlan_id, 'network_id': port.network_id, 'port_id': port.port_id, 'physical_network': port.physical_interface, 'admin_state_up': port.admin_state_up } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> entry = {'device': device} <NEW_LINE> LOG.debug(_("%s can not be found in database"), device) <NEW_LINE> <DEDENT> return entry <NEW_LINE> <DEDENT> def update_device_down(self, rpc_context, **kwargs): <NEW_LINE> <INDENT> device = kwargs.get('device') <NEW_LINE> port = self.get_port_from_device(device) <NEW_LINE> if port: <NEW_LINE> <INDENT> entry = {'device': device, 'exists': True} <NEW_LINE> port_id = port['port_id'] <NEW_LINE> brocade_db.update_port_state(rpc_context, port_id, False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> entry = {'device': device, 'exists': False} <NEW_LINE> LOG.debug(_("%s can not be found in database"), device) <NEW_LINE> <DEDENT> return entry | Agent callback. | 6259907e7cff6e4e811b74b4 |
class BilConDialog(ga._AnagDialog): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if not kwargs.has_key('title') and len(args) < 3: <NEW_LINE> <INDENT> kwargs['title'] = FRAME_TITLE <NEW_LINE> <DEDENT> ga._AnagDialog.__init__(self, *args, **kwargs) <NEW_LINE> self.LoadAnagPanel(BilConPanel(self, -1)) | Dialog Gestione tabella Conti di bilancio. | 6259907e60cbc95b06365aa6 |
class InventorySlot(Enum): <NEW_LINE> <INDENT> SMALL = "small" <NEW_LINE> MEDIUM = "medium" <NEW_LINE> BIG = "big" <NEW_LINE> HUGE = "huge" | A slot where unequipped items are stored. | 6259907e5fdd1c0f98e5f9f3 |
class LetterAdminView(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('id', 'title', 'summary') <NEW_LINE> list_filter = (('collection', RelatedDropdownFilter), ('repository', RelatedDropdownFilter), ('letter_type', RelatedDropdownFilter), ('commentary', RelatedDropdownFilter), ('location', RelatedDropdownFilter), ('estimated_proportion_of_letter', RelatedDropdownFilter)) <NEW_LINE> search_fields = ('title', 'summary', 'transcription_plain', 'transcription_normalized') <NEW_LINE> ordering = ('-id',) <NEW_LINE> inlines = [LetterLetterImageInline, LetterLetter1Inline, LetterLetter2Inline] <NEW_LINE> readonly_fields = ('created_by', 'created_datetime', 'lastupdated_by', 'lastupdated_datetime') <NEW_LINE> filter_horizontal = ('letter_type', 'commentary', 'location') <NEW_LINE> def save_model(self, request, obj, form, change): <NEW_LINE> <INDENT> if getattr(obj, 'created_by', None) is None: <NEW_LINE> <INDENT> obj.created_by = request.user <NEW_LINE> <DEDENT> obj.lastupdated_by = request.user <NEW_LINE> obj.save() | Customise the Letter section of the Django admin | 6259907ebf627c535bcb2f45 |
class Solution: <NEW_LINE> <INDENT> def convert_to_title(self, n: int) -> str: <NEW_LINE> <INDENT> s = "" <NEW_LINE> while n > 0: <NEW_LINE> <INDENT> n -= 1 <NEW_LINE> s = chr(n % 26 + ord('A')) + s <NEW_LINE> n //= 26 <NEW_LINE> <DEDENT> return s | Excel 表列名称 | 6259907e76e4537e8c3f0ff4 |
class Task: <NEW_LINE> <INDENT> bug_number = None <NEW_LINE> atoms = None <NEW_LINE> def __init__(self, task_spec): <NEW_LINE> <INDENT> bug_string, *atoms = task_spec.split('\n') <NEW_LINE> if not atoms: <NEW_LINE> <INDENT> raise ValueError("No atoms in '%s' task" % bug_string) <NEW_LINE> <DEDENT> self.bug_number = Spec.get_bug(bug_string) <NEW_LINE> self.atoms = [Spec.get_atom(atom_spec) for atom_spec in atoms] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Task(bug=%r,atoms=%r)" % (self.bug_number, self.atoms) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "# bug #%d\n%s" % (self.bug_number, '\n'.join(self.atoms)) | Task is a single bug to work on. As returned by getatoms.py | 6259907edc8b845886d5502f |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.