code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class MockProcess(Process): <NEW_LINE> <INDENT> def __init__(self, rc=None, lines=None, func=None): <NEW_LINE> <INDENT> Process.__init__(self, quiet=True) <NEW_LINE> self.rc = rc or 0 <NEW_LINE> self.lines = lines or [] <NEW_LINE> self.func = func <NEW_LINE> <DEDENT> def popen(self, cmd, echo=True, echo2=True): <NEW_LINE> <INDENT> if self.func is not None: <NEW_LINE> <INDENT> rc_lines = self.func(cmd) <NEW_LINE> if rc_lines is not None: <NEW_LINE> <INDENT> return rc_lines <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise MockProcessError('Unhandled command: %s' % cmd) <NEW_LINE> <DEDENT> <DEDENT> return self.rc, self.lines | A Process we can tell what to return by
- passing rc and lines, or
- passing a function called as ``func(cmd)`` which returns
rc and lines. | 62598fcd656771135c489a52 |
class ProfileReport(object): <NEW_LINE> <INDENT> html = '' <NEW_LINE> file = None <NEW_LINE> def __init__(self, df, **kwargs): <NEW_LINE> <INDENT> sample = kwargs.get('sample', df.head()) <NEW_LINE> description_set = describe_df(df, **kwargs) <NEW_LINE> self.html = to_html(sample, description_set) <NEW_LINE> self.description_set = description_set <NEW_LINE> <DEDENT> def get_description(self): <NEW_LINE> <INDENT> return self.description_set <NEW_LINE> <DEDENT> def get_rejected_variables(self, threshold=0.9): <NEW_LINE> <INDENT> variable_profile = self.description_set['variables'] <NEW_LINE> result = [] <NEW_LINE> if hasattr(variable_profile, 'correlation'): <NEW_LINE> <INDENT> result = variable_profile.index[variable_profile.correlation > threshold].tolist() <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def to_file(self, outputfile=DEFAULT_OUTPUTFILE): <NEW_LINE> <INDENT> if outputfile != NO_OUTPUTFILE: <NEW_LINE> <INDENT> if outputfile == DEFAULT_OUTPUTFILE: <NEW_LINE> <INDENT> outputfile = 'profile_' + str(hash(self)) + ".html" <NEW_LINE> <DEDENT> with codecs.open(outputfile, 'w+b', encoding='utf8') as self.file: <NEW_LINE> <INDENT> self.file.write(templates.template('wrapper').render(content=self.html)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def to_html(self): <NEW_LINE> <INDENT> return templates.template('wrapper').render(content=self.html) <NEW_LINE> <DEDENT> def _repr_html_(self): <NEW_LINE> <INDENT> return self.html <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Output written to file " + str(self.file.name) | Generate a profile report from a Dataset stored as a pandas `DataFrame`.
Used has is it will output its content as an HTML report in a Jupyter notebook.
Attributes
----------
df : DataFrame
Data to be analyzed
bins : int
Number of bins in histogram.
The default is 10.
check_correlation : boolean
Whether or not to check correlation.
It's `True` by default.
correlation_threshold: float
Threshold to determine if the variable pair is correlated.
The default is 0.9.
correlation_overrides : list
Variable names not to be rejected because they are correlated.
There is no variable in the list (`None`) by default.
check_recoded : boolean
Whether or not to check recoded correlation (memory heavy feature).
Since it's an expensive computation it can be activated for small datasets.
`check_correlation` must be true to disable this check.
It's `False` by default.
pool_size : int
Number of workers in thread pool
The default is equal to the number of CPU.
Methods
-------
get_description
Return the description (a raw statistical summary) of the dataset.
get_rejected_variables
Return the list of rejected variable or an empty list if there is no rejected variables.
to_file
Write the report to a file.
to_html
Return the report as an HTML string. | 62598fcd851cf427c66b8695 |
class TransformerEncoder(nn.Module): <NEW_LINE> <INDENT> def __init__(self, embed_dim, num_heads, layers, attn_dropout=0.0, relu_dropout=0.0, res_dropout=0.0, embed_dropout=0.0, attn_mask=False): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.dropout = embed_dropout <NEW_LINE> self.attn_dropout = attn_dropout <NEW_LINE> self.embed_dim = embed_dim <NEW_LINE> self.embed_scale = math.sqrt(embed_dim) <NEW_LINE> self.attn_mask = attn_mask <NEW_LINE> self.layers = nn.ModuleList([]) <NEW_LINE> for layer in range(layers): <NEW_LINE> <INDENT> new_layer = TransformerEncoderLayer(embed_dim, num_heads=num_heads, attn_dropout=attn_dropout, relu_dropout=relu_dropout, res_dropout=res_dropout, attn_mask=attn_mask) <NEW_LINE> self.layers.append(new_layer) <NEW_LINE> <DEDENT> self.register_buffer('version', torch.Tensor([2])) <NEW_LINE> self.normalize = True <NEW_LINE> if self.normalize: <NEW_LINE> <INDENT> self.layer_norm = LayerNorm(embed_dim) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x_in, x_in_k = None, x_in_v = None): <NEW_LINE> <INDENT> x = F.dropout(x_in, p=self.dropout, training=self.training) <NEW_LINE> if x_in_k is not None and x_in_v is not None: <NEW_LINE> <INDENT> x_k = F.dropout(x_in_k, p=self.dropout, training=self.training) <NEW_LINE> x_v = F.dropout(x_in_v, p=self.dropout, training=self.training) <NEW_LINE> <DEDENT> intermediates = [x] <NEW_LINE> for layer in self.layers: <NEW_LINE> <INDENT> if x_in_k is not None and x_in_v is not None: <NEW_LINE> <INDENT> x = layer(x, x_k, x_v) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = layer(x) <NEW_LINE> <DEDENT> intermediates.append(x) <NEW_LINE> <DEDENT> if self.normalize: <NEW_LINE> <INDENT> x = self.layer_norm(x) <NEW_LINE> <DEDENT> return x | Transformer encoder consisting of *args.encoder_layers* layers. Each layer
is a :class:`TransformerEncoderLayer`.
Args:
embed_tokens (torch.nn.Embedding): input embedding
num_heads (int): number of heads
layers (int): number of layers
attn_dropout (float): dropout applied on the attention weights
relu_dropout (float): dropout applied on the first layer of the residual block
res_dropout (float): dropout applied on the residual block
attn_mask (bool): whether to apply mask on the attention weights | 62598fcd3d592f4c4edbb296 |
class ImageView(ViewBase): <NEW_LINE> <INDENT> @memoize <NEW_LINE> @decode <NEW_LINE> def image(self): <NEW_LINE> <INDENT> return self.context.tag() | View for IImage.
| 62598fcd091ae3566870500d |
class SchemeMorphism_spec(SchemeMorphism): <NEW_LINE> <INDENT> def __init__(self, parent, phi, check=True): <NEW_LINE> <INDENT> SchemeMorphism.__init__(self, parent) <NEW_LINE> if check: <NEW_LINE> <INDENT> if not is_RingHomomorphism(phi): <NEW_LINE> <INDENT> raise TypeError("phi (=%s) must be a ring homomorphism" % phi) <NEW_LINE> <DEDENT> if phi.domain() != parent.codomain().coordinate_ring(): <NEW_LINE> <INDENT> raise TypeError("phi (=%s) must have domain %s" % (phi, parent.codomain().coordinate_ring())) <NEW_LINE> <DEDENT> if phi.codomain() != parent.domain().coordinate_ring(): <NEW_LINE> <INDENT> raise TypeError("phi (=%s) must have codomain %s" % (phi, parent.domain().coordinate_ring())) <NEW_LINE> <DEDENT> <DEDENT> self.__ring_homomorphism = phi <NEW_LINE> <DEDENT> def _call_(self, x): <NEW_LINE> <INDENT> S = self.ring_homomorphism().inverse_image(x.prime_ideal()) <NEW_LINE> return self._codomain(S) <NEW_LINE> <DEDENT> def _repr_type(self): <NEW_LINE> <INDENT> return "Affine Scheme" <NEW_LINE> <DEDENT> def _repr_defn(self): <NEW_LINE> <INDENT> return repr(self.ring_homomorphism()) <NEW_LINE> <DEDENT> def ring_homomorphism(self): <NEW_LINE> <INDENT> return self.__ring_homomorphism | Morphism of spectra of rings
INPUT:
- ``parent`` -- Hom-set whose domain and codomain are affine schemes.
- ``phi`` -- a ring morphism with matching domain and codomain.
- ``check`` -- boolean (optional, default:``True``). Whether to
check the input for consistency.
EXAMPLES::
sage: R.<x> = PolynomialRing(QQ)
sage: phi = R.hom([QQ(7)]); phi
Ring morphism:
From: Univariate Polynomial Ring in x over Rational Field
To: Rational Field
Defn: x |--> 7
sage: X = Spec(QQ); Y = Spec(R)
sage: f = X.hom(phi); f
Affine Scheme morphism:
From: Spectrum of Rational Field
To: Spectrum of Univariate Polynomial Ring in x over Rational Field
Defn: Ring morphism:
From: Univariate Polynomial Ring in x over Rational Field
To: Rational Field
Defn: x |--> 7
sage: f.ring_homomorphism()
Ring morphism:
From: Univariate Polynomial Ring in x over Rational Field
To: Rational Field
Defn: x |--> 7 | 62598fcd7cff6e4e811b5e0a |
class Test_login(unittest.TestCase): <NEW_LINE> <INDENT> def test_login_success(self): <NEW_LINE> <INDENT> test_data ={'username':'amdin','password':'beidouxing'}; <NEW_LINE> expect_data ={'code':'0','msg':'登录成功'}; <NEW_LINE> res = login_check(**test_data); <NEW_LINE> self.assertEqual(res,expect_data); <NEW_LINE> <DEDENT> def test_login_pwderror(self): <NEW_LINE> <INDENT> test_data={'username':'amdin','password':'beidouxing1'}; <NEW_LINE> expect_data={'code':'1','msg':'账号密码不匹配'}; <NEW_LINE> res = login_check(**test_data); <NEW_LINE> self.assertEqual(res,expect_data); <NEW_LINE> <DEDENT> def test_login_acterror(self): <NEW_LINE> <INDENT> test_data ={'username':'amdin1','password':'beidouxing'}; <NEW_LINE> expect_data = {'code':'1','msg':'账号密码不匹配'}; <NEW_LINE> res = login_check(**test_data); <NEW_LINE> self.assertEqual(res, expect_data); <NEW_LINE> <DEDENT> def test_login_pwdlen_01(self): <NEW_LINE> <INDENT> test_data ={'username':'amdin','password':'bei'}; <NEW_LINE> expect_data = {'code':'2','msg':'密码长度请在6到18之间'}; <NEW_LINE> res = login_check(**test_data); <NEW_LINE> self.assertEqual(res, expect_data); <NEW_LINE> <DEDENT> def test_login_pwdlen_02(self): <NEW_LINE> <INDENT> test_data = {'username':'amdin','password':'beidouxing1234567890'}; <NEW_LINE> expect_data ={'code':'2','msg':'密码长度请在6到18之间'}; <NEW_LINE> res = login_check(**test_data); <NEW_LINE> self.assertEqual(res, expect_data); | 如果有前置条件和后置条件,需要重写脚手架
定义单元测试,但是测试函数(方法)必须是要以test开头 | 62598fcd7c178a314d78d882 |
class UpdateBook(PermissionRequiredMixin, UpdateView): <NEW_LINE> <INDENT> permission_required = ( "catalogbooks.create_book_bystaff", ) <NEW_LINE> model = Books <NEW_LINE> context_object_name = 'book' <NEW_LINE> fields = ['title', 'author', 'language', 'genre', 'summary', 'isbn'] <NEW_LINE> template_name = 'catalogbooks/update_book.html' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(UpdateBook, self).get_context_data(**kwargs) <NEW_LINE> context['title'] = f"Изменить: {Books.objects.get(pk=self.kwargs['pk']).title}" <NEW_LINE> return context | Обновляем книгу | 62598fcdaad79263cf42ebb1 |
class Coordinates: <NEW_LINE> <INDENT> def __init__(self, x=0, y=0): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Coordinates(%g, %g)" % (self.x, self.y) <NEW_LINE> <DEDENT> def point(self): <NEW_LINE> <INDENT> return (self.x, self.y) | Coordinates class for storing xy coordinates | 62598fcddc8b845886d539a0 |
class RfamInitialAnnotations(models.Model): <NEW_LINE> <INDENT> rfam_initial_annotation_id = models.AutoField(primary_key=True) <NEW_LINE> upi = models.ForeignKey('Rna', db_column='upi', to_field='upi', on_delete=models.CASCADE) <NEW_LINE> rfam_model = models.ForeignKey( RfamModel, db_column='rfam_model_id', to_field='rfam_model_id', on_delete=models.CASCADE ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'rfam_initial_annotations' | This table represents the given Rfam annotations for a sequence. For
example when we take sequences from Rfam we already know what the
'correct' family is. In addition, we get sequences from people who have
performed their own Rfam scans. We keep track of this to decide if things
should be suppressed or handled differently here. | 62598fcda219f33f346c6bec |
class DataVendorQuandl(DataVendor): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(DataVendorQuandl, self).__init__() <NEW_LINE> <DEDENT> def load_ticker(self, market_data_request): <NEW_LINE> <INDENT> logger = LoggerManager().getLogger(__name__) <NEW_LINE> market_data_request_vendor = self.construct_vendor_market_data_request(market_data_request) <NEW_LINE> logger.info("Request Quandl data") <NEW_LINE> data_frame = self.download_daily(market_data_request_vendor) <NEW_LINE> if data_frame is None or data_frame.index is []: return None <NEW_LINE> if data_frame is not None: <NEW_LINE> <INDENT> returned_tickers = data_frame.columns <NEW_LINE> <DEDENT> if data_frame is not None: <NEW_LINE> <INDENT> returned_fields = [(x.split(' - ')[1]).lower().replace(' ', '-').replace('.', '-').replace('--', '-') for x in returned_tickers] <NEW_LINE> returned_fields = [x.replace('value', 'close') for x in returned_fields] <NEW_LINE> for i in range(0,len(returned_fields)): <NEW_LINE> <INDENT> ticker = returned_tickers[i].split('/')[1].split(' - ')[0].lower() <NEW_LINE> if ticker == returned_fields[i]: <NEW_LINE> <INDENT> returned_fields[i] = 'close' <NEW_LINE> <DEDENT> <DEDENT> for i in range(0, 10): <NEW_LINE> <INDENT> returned_fields = [x.replace('0'+ str(i) + ':00', str(i) + ':00') for x in returned_fields] <NEW_LINE> <DEDENT> returned_tickers = [x.replace('.', '/') for x in returned_tickers] <NEW_LINE> returned_tickers = [x.split(' - ')[0] for x in returned_tickers] <NEW_LINE> try: <NEW_LINE> <INDENT> fields = self.translate_from_vendor_field(returned_fields, market_data_request) <NEW_LINE> tickers = self.translate_from_vendor_ticker(returned_tickers, market_data_request) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print('error') <NEW_LINE> <DEDENT> ticker_combined = [] <NEW_LINE> for i in range(0, len(tickers)): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ticker_combined.append(tickers[i] + "." + fields[i]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> ticker_combined.append(tickers[i] + ".close") <NEW_LINE> <DEDENT> <DEDENT> data_frame.columns = ticker_combined <NEW_LINE> data_frame.index.name = 'Date' <NEW_LINE> <DEDENT> logger.info("Completed request from Quandl for " + str(ticker_combined)) <NEW_LINE> return data_frame <NEW_LINE> <DEDENT> def download_daily(self, market_data_request): <NEW_LINE> <INDENT> logger = LoggerManager().getLogger(__name__) <NEW_LINE> trials = 0 <NEW_LINE> data_frame = None <NEW_LINE> while(trials < 5): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data_frame = Quandl.get(market_data_request.tickers, authtoken=DataConstants().quandl_api_key, trim_start=market_data_request.start_date, trim_end=market_data_request.finish_date) <NEW_LINE> break <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> trials = trials + 1 <NEW_LINE> logger.info("Attempting... " + str(trials) + " request to download from Quandl due to following error: " + str(e)) <NEW_LINE> <DEDENT> <DEDENT> if trials == 5: <NEW_LINE> <INDENT> logger.error("Couldn't download from Quandl after several attempts!") <NEW_LINE> <DEDENT> return data_frame | Reads in data from Quandl into findatapy library
| 62598fcd099cdd3c636755d1 |
class ReplacingViewPageTemplateFile(ViewPageTemplateFile): <NEW_LINE> <INDENT> regexp = None <NEW_LINE> replacement = None <NEW_LINE> def __init__(self, filename, _prefix=None, content_type=None, module=None, regexp=None, replacement=None): <NEW_LINE> <INDENT> if module is not None: <NEW_LINE> <INDENT> _prefix = os.path.dirname(module.__file__) <NEW_LINE> <DEDENT> self.regexp = re.compile(regexp) <NEW_LINE> self.replacement = replacement <NEW_LINE> super(ViewPageTemplateFile, self).__init__(filename, _prefix) <NEW_LINE> <DEDENT> def write(self, text): <NEW_LINE> <INDENT> text = self.regexp.sub(self.replacement, text) <NEW_LINE> super(ViewPageTemplateFile, self).write(text) | A page template that applies a regexp-based replacement when the
template is loaded or modified. | 62598fcdcc40096d6161a3c9 |
class HardShutdownAction(Action): <NEW_LINE> <INDENT> def action_code(self): <NEW_LINE> <INDENT> return "QApplication.quit()" <NEW_LINE> <DEDENT> def required_imports(self): <NEW_LINE> <INDENT> return ['from PyQt5.QtWidgets import QApplication'] | This action shuts down Tribler in a more forced way. | 62598fcd5fc7496912d48469 |
class SysChangeMonConfigError(SysChangeMonError): <NEW_LINE> <INDENT> pass | Config related errors. | 62598fcdff9c53063f51aa30 |
class WorkerPool(Queue): <NEW_LINE> <INDENT> def __init__(self, size=1, maxjobs=0, worker_factory=default_worker_factory): <NEW_LINE> <INDENT> if not isinstance(worker_factory, collections.Callable): <NEW_LINE> <INDENT> raise TypeError("worker_factory must be callable") <NEW_LINE> <DEDENT> self.worker_factory = worker_factory <NEW_LINE> self._size = 0 <NEW_LINE> Queue.__init__(self, maxjobs) <NEW_LINE> self._jobs = self <NEW_LINE> for i in range(size): <NEW_LINE> <INDENT> self.grow() <NEW_LINE> <DEDENT> <DEDENT> def grow(self): <NEW_LINE> <INDENT> t = self.worker_factory(self) <NEW_LINE> t.start() <NEW_LINE> self._size += 1 <NEW_LINE> <DEDENT> def shrink(self): <NEW_LINE> <INDENT> if self._size <= 0: <NEW_LINE> <INDENT> raise IndexError("pool is already empty") <NEW_LINE> <DEDENT> self._size -= 1 <NEW_LINE> self.put(SuicideJob()) <NEW_LINE> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> for i in range(self.size()): <NEW_LINE> <INDENT> self.put(SuicideJob()) <NEW_LINE> <DEDENT> <DEDENT> def size(self): <NEW_LINE> <INDENT> return self._size <NEW_LINE> <DEDENT> def map(self, fn, *seq): <NEW_LINE> <INDENT> results = Queue() <NEW_LINE> args = list(zip(*seq)) <NEW_LINE> for seq in args: <NEW_LINE> <INDENT> j = SimpleJob(results, fn, seq) <NEW_LINE> self.put(j) <NEW_LINE> <DEDENT> r = [] <NEW_LINE> for i in range(len(args)): <NEW_LINE> <INDENT> r.append(results.get()) <NEW_LINE> <DEDENT> return r <NEW_LINE> <DEDENT> def wait(self): <NEW_LINE> <INDENT> self.join() | WorkerPool servers two functions: It is a Queue and a master of Worker
threads. The Queue accepts Job objects and passes it on to Workers, who are
initialized during the construction of the pool and by using grow().
Jobs are inserted into the WorkerPool with the `put` method.
Hint: Have the Job append its result into a shared queue that the caller
holds and then the caller reads an expected number of results from it.
The shutdown() method must be explicitly called to terminate the Worker
threads when the pool is no longer needed.
Construction parameters:
size = 1
Number of active worker threads the pool should contain.
maxjobs = 0
Maximum number of jobs to allow in the queue at a time. Will block on
`put` if full.
default_worker = default_worker_factory
The default worker factory is called with one argument, which is the
jobs Queue object that it will read from to acquire jobs. The factory
will produce a Worker object which will be added to the pool. | 62598fcd4c3428357761a6a3 |
class NotNullConstraintsRequest: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'db_name', None, None, ), (2, TType.STRING, 'tbl_name', None, None, ), ) <NEW_LINE> def __init__(self, db_name=None, tbl_name=None,): <NEW_LINE> <INDENT> self.db_name = db_name <NEW_LINE> self.tbl_name = tbl_name <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.db_name = iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.tbl_name = iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('NotNullConstraintsRequest') <NEW_LINE> if self.db_name is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('db_name', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.db_name) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.tbl_name is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('tbl_name', TType.STRING, 2) <NEW_LINE> oprot.writeString(self.tbl_name) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if self.db_name is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field db_name is unset!') <NEW_LINE> <DEDENT> if self.tbl_name is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field tbl_name is unset!') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.db_name) <NEW_LINE> value = (value * 31) ^ hash(self.tbl_name) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- db_name
- tbl_name | 62598fcd7c178a314d78d884 |
class User(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True, autoincrement=True) <NEW_LINE> username = db.Column(db.String(20), unique=True) <NEW_LINE> password = db.Column(db.String(500)) <NEW_LINE> def __init__(self, username, password): <NEW_LINE> <INDENT> self. username = username <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> def addUser(_username, _password): <NEW_LINE> <INDENT> addedUser = User(username=_username, password=_password) <NEW_LINE> db.session.add(addedUser) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> userObject = { "Username":self.username, "Password":self.password } <NEW_LINE> return json.dumps(userObject) | class User that represents the user database model | 62598fcd956e5f7376df5870 |
@implementer(IVocabularyFactory) <NEW_LINE> class AvailableFooterOptionsVocabulary(BaseVocabulary): <NEW_LINE> <INDENT> def __call__(self, context): <NEW_LINE> <INDENT> options = self._get_registry_record(name='available_footer_options') <NEW_LINE> items = [SimpleTerm(value=i, title=i) for i in sorted(options)] <NEW_LINE> return SimpleVocabulary(items) | Vocabulary for available footer options. | 62598fcd55399d3f056268fe |
class ofdm_chanest_vcvc(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def make(*args, **kwargs): <NEW_LINE> <INDENT> return _howto_swig.ofdm_chanest_vcvc_make(*args, **kwargs) <NEW_LINE> <DEDENT> make = staticmethod(make) <NEW_LINE> __swig_destroy__ = _howto_swig.delete_ofdm_chanest_vcvc <NEW_LINE> __del__ = lambda self : None; | Estimate channel and coarse frequency offset for OFDM from preambles
Input: OFDM symbols (in frequency domain). The first one (or two) symbols are expected to be synchronisation symbols, which are used to estimate the coarse freq offset and the initial equalizer taps (these symbols are removed from the stream). The following are passed through unmodified (the actual equalisation must be done elsewhere). Output: The data symbols, without the synchronisation symbols. The first data symbol passed through has two tags: 'ofdm_sync_carr_offset' (integer), the coarse frequency offset as number of carriers, and 'ofdm_sync_eq_taps' (complex vector). Any tags attached to the synchronisation symbols are attached to the first data symbol. All other tags are propagated as expected.
Note: The vector on ofdm_sync_eq_taps is already frequency-corrected, whereas the rest is not.
This block assumes the frequency offset is even (i.e. an integer multiple of 2).
[1] Schmidl, T.M. and Cox, D.C., "Robust frequency and timing synchronization for OFDM", Communications, IEEE Transactions on, 1997. [2] K.D. Kammeyer, "Nachrichtenuebertragung," Chapter. 16.3.2. | 62598fcd283ffb24f3cf3c6a |
class VenueViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Venue.objects.all() <NEW_LINE> serializer_class = VenueSerializer | ViewSet for class Venue. | 62598fcd5fcc89381b26633f |
class VTReportObject(AbstractMISPObjectGenerator): <NEW_LINE> <INDENT> def __init__(self, apikey, indicator): <NEW_LINE> <INDENT> super(VTReportObject, self).__init__("virustotal-report") <NEW_LINE> indicator = indicator.strip() <NEW_LINE> self._resource_type = self.__validate_resource(indicator) <NEW_LINE> if self._resource_type: <NEW_LINE> <INDENT> self._report = self.__query_virustotal(apikey, indicator) <NEW_LINE> self.generate_attributes() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error_msg = "A valid indicator is required. (One of type url, md5, sha1, sha256). Received '{}' instead".format(indicator) <NEW_LINE> raise InvalidMISPObject(error_msg) <NEW_LINE> <DEDENT> self.update_not_jsonable('ObjectReference') <NEW_LINE> <DEDENT> def generate_attributes(self): <NEW_LINE> <INDENT> self.add_attribute("last-submission", value=self._report["scan_date"]) <NEW_LINE> self.add_attribute("permalink", value=self._report["permalink"]) <NEW_LINE> ratio = "{}/{}".format(self._report["positives"], self._report["total"]) <NEW_LINE> self.add_attribute("detection-ratio", value=ratio) <NEW_LINE> <DEDENT> def __validate_resource(self, ioc): <NEW_LINE> <INDENT> if not has_validators: <NEW_LINE> <INDENT> raise Exception('You need to install validators: pip install validators') <NEW_LINE> <DEDENT> if validators.url(ioc): <NEW_LINE> <INDENT> return "url" <NEW_LINE> <DEDENT> elif re.match(r"\b([a-fA-F0-9]{32}|[a-fA-F0-9]{40}|[a-fA-F0-9]{64})\b", ioc): <NEW_LINE> <INDENT> return "file" <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __query_virustotal(self, apikey, resource): <NEW_LINE> <INDENT> url = "https://www.virustotal.com/vtapi/v2/{}/report".format(self._resource_type) <NEW_LINE> params = {"apikey": apikey, "resource": resource} <NEW_LINE> report = requests.get(url, params=params) <NEW_LINE> report = report.json() <NEW_LINE> if report["response_code"] == 1: <NEW_LINE> <INDENT> return report <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error_msg = "{}: {}".format(resource, report["verbose_msg"]) <NEW_LINE> raise InvalidMISPObject(error_msg) | VirusTotal Report
:apikey: VirusTotal API key (private works, but only public features are supported right now)
:indicator: IOC to search VirusTotal for | 62598fcdcc40096d6161a3ca |
class ActiveCarouselManager(models.Manager): <NEW_LINE> <INDENT> def get_query_set(self, *args, **kwargs): <NEW_LINE> <INDENT> now = datetime.now() <NEW_LINE> return super(ActiveCarouselManager, self) .get_query_set(*args, **kwargs).filter(is_active=True) .filter(Q(end_date__gte=now) | Q(end_date__isnull=True)) .filter(Q(start_date__lte=now) | Q(start_date__isnull=True)) | Queryset com foto carroussel da home ativa (active=True) e datas de início
e final, válidas (de acordo com o número de dias definido pela
assinatura). | 62598fcdad47b63b2c5a7c41 |
class TensorMapper(object): <NEW_LINE> <INDENT> def __init__(self, subgraph_data): <NEW_LINE> <INDENT> self.data = subgraph_data <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> html = "" <NEW_LINE> html += "<span class='tooltip'><span class='tooltipcontent'>" <NEW_LINE> for i in x: <NEW_LINE> <INDENT> tensor = self.data["tensors"][i] <NEW_LINE> html += str(i) + " " <NEW_LINE> html += tensor["name"] + " " <NEW_LINE> html += str(tensor["type"]) + " " <NEW_LINE> html += repr(tensor["shape"]) + "<br>" <NEW_LINE> <DEDENT> html += "</span>" <NEW_LINE> html += repr(x) <NEW_LINE> html += "</span>" <NEW_LINE> return html | Maps a list of tensor indices to a tooltip hoverable indicator of more. | 62598fcd60cbc95b06364724 |
class SongBinary: <NEW_LINE> <INDENT> def __init__(self,filename): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.filetype = '' <NEW_LINE> <DEDENT> def get_binary_mapping(self): <NEW_LINE> <INDENT> import re <NEW_LINE> f = open(self.filename) <NEW_LINE> line = f.readline() <NEW_LINE> if self.filetype not in line: <NEW_LINE> <INDENT> raise Exception('songy.'+self.__class__.__name__+' expects filetype <'+self.filetype+'>, but '+self.filename+' reports:\n'+line) <NEW_LINE> <DEDENT> while line.find('BLOCK')==-1: <NEW_LINE> <INDENT> line = f.readline() <NEW_LINE> <DEDENT> line = f.readline() <NEW_LINE> self.mapping = [] <NEW_LINE> while line[0]=='#': <NEW_LINE> <INDENT> tmp = re.split(r'\s{2,}', line) <NEW_LINE> self.mapping.append(tmp[1:]) <NEW_LINE> line = f.readline() <NEW_LINE> <DEDENT> f.close() <NEW_LINE> <DEDENT> def read_block(self,blocknumber): <NEW_LINE> <INDENT> if not hasattr(self, 'mapping'): <NEW_LINE> <INDENT> self.get_binary_mapping() <NEW_LINE> <DEDENT> mapelement = self.mapping[blocknumber]; <NEW_LINE> f = open(self.filename,'rb') <NEW_LINE> f.seek(int(mapelement[4])) <NEW_LINE> if mapelement[1][0]=='c': <NEW_LINE> <INDENT> val = np.fromfile(f,dtype='uint8', count=int(mapelement[2]), sep="") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val = np.fromfile(f,dtype=mapelement[1][0], count=int(mapelement[2]), sep="") <NEW_LINE> <DEDENT> f.close() <NEW_LINE> return val <NEW_LINE> <DEDENT> def get_name_array(self,blocknumnumber,blocknumnames): <NEW_LINE> <INDENT> numsources = self.read_block(blocknumnumber)[0] <NEW_LINE> names = self.read_block(blocknumnames) <NEW_LINE> names = names.reshape(numsources,-1) <NEW_LINE> name_array = [] <NEW_LINE> for name in names: <NEW_LINE> <INDENT> name = name[name.nonzero()].tostring() <NEW_LINE> name_array.append(name) <NEW_LINE> <DEDENT> return name_array | This class holds the basic routines for manipulating the
binary files created by SONG. Normally this class should
not be initialised directly, but you should use the
appropriate child class instead.
Example:
dat = songy.SongBinary(filename) | 62598fcdf9cc0f698b1c54c7 |
class ConsoleInterfaceDefault(ConsoleInterface): <NEW_LINE> <INDENT> def _add_arguments(self): <NEW_LINE> <INDENT> self._parser.add_argument('-k', type=int, default=5, help="Beam size (default: %(default)s))") <NEW_LINE> self._parser.add_argument('-n', type=float, default=0.0, nargs="?", const=1.0, metavar="ALPHA", help="Normalize scores by sentence length (with argument, exponentiate lengths by ALPHA)") <NEW_LINE> self._parser.add_argument('-c', action="store_true", help="Character-level") <NEW_LINE> self._parser.add_argument('--input', '-i', type=argparse.FileType('r'), default=sys.stdin, metavar='PATH', help="Input file (default: standard input)") <NEW_LINE> self._parser.add_argument('--output', '-o', type=argparse.FileType('w'), default=sys.stdout, metavar='PATH', help="Output file (default: standard output)") <NEW_LINE> self._parser.add_argument('--output_alignment', '-a', type=argparse.FileType('w'), default=None, metavar='PATH', help="Output file for alignment weights (default: standard output)") <NEW_LINE> self._parser.add_argument('--json_alignment', action="store_true", help="Output alignment in json format") <NEW_LINE> self._parser.add_argument('--n-best', action="store_true", help="Write n-best list (of size k)") <NEW_LINE> self._parser.add_argument('--suppress-unk', action="store_true", help="Suppress hypotheses containing UNK.") <NEW_LINE> self._parser.add_argument('--print-word-probabilities', '-wp', action="store_true", help="Print probabilities of each word") <NEW_LINE> self._parser.add_argument('--search_graph', '-sg', help="Output file for search graph rendered as PNG image") <NEW_LINE> <DEDENT> def get_translation_settings(self): <NEW_LINE> <INDENT> args = self.parse_args() <NEW_LINE> return TranslationSettings(args) | Console interface for default mode | 62598fcdd8ef3951e32c804f |
class CompositePicker(PickerScreen): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_paths(): <NEW_LINE> <INDENT> return composites_path, composites_path, composites_path, composites_path <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_images(): <NEW_LINE> <INDENT> return sorted(glob.glob('{0}/*.png'.format(composites_path))) | Image browser that displays composites | 62598fcd099cdd3c636755d3 |
class PositionalEncoding(nn.Module): <NEW_LINE> <INDENT> def __init__(self,d_model,dropout,max_len=5000): <NEW_LINE> <INDENT> super(PositionalEncoding,self).__init__() <NEW_LINE> self.dropout = nn.Dropout(p=dropout) <NEW_LINE> pe = torch.zeros(max_len,d_model) <NEW_LINE> position = torch.arange(0,max_len).unsqueeze(1).float() <NEW_LINE> div_term = torch.exp((torch.arange(0,d_model,2)*-math.log(10000) /d_model).float()) <NEW_LINE> pe[:,0::2] = torch.sin(position * div_term) <NEW_LINE> pe[:,1::2] = torch.cos(position * div_term) <NEW_LINE> pe = pe.unsqueeze(0) <NEW_LINE> self.register_buffer('pe',pe) <NEW_LINE> <DEDENT> def forward (self,x): <NEW_LINE> <INDENT> x =x +Variable(self.pe[:,:x.size(1)],requires_grad =False) <NEW_LINE> return self.dropout(x) | 实现位置编码函数 | 62598fcdcc40096d6161a3cb |
class Alias(ComplexModel): <NEW_LINE> <INDENT> pass | Different type_name, same _type_info. | 62598fcd5fcc89381b266340 |
class IJWPlayerSettings(interface.Interface): <NEW_LINE> <INDENT> skin = schema.ASCIILine( title=u"Skin", description=u"A path. For example: /skins/modieus/modieus.zip", required=False ) | Site wide settings for jwplayer | 62598fcd50812a4eaa620dd8 |
class class_linear_regression: <NEW_LINE> <INDENT> x_data = [] <NEW_LINE> y_data = [] <NEW_LINE> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> def draw_plot_input_data(self, x_data, y_data): <NEW_LINE> <INDENT> plt.plot(x_data, y_data, 'ro') <NEW_LINE> plt.show() <NEW_LINE> <DEDENT> def input_data(self): <NEW_LINE> <INDENT> num_points = 1000 <NEW_LINE> vectors_set = [] <NEW_LINE> for i in range(num_points): <NEW_LINE> <INDENT> x1 = np.random.normal(0.0, 0.55) <NEW_LINE> y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03) <NEW_LINE> vectors_set.append([x1, y1]) <NEW_LINE> <DEDENT> self.x_data = [v[0] for v in vectors_set] <NEW_LINE> self.y_data = [v[1] for v in vectors_set] <NEW_LINE> self.draw_plot_input_data(self.x_data, self.y_data) <NEW_LINE> <DEDENT> def def_variables(self): <NEW_LINE> <INDENT> self.W = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) <NEW_LINE> self.b = tf.Variable(tf.zeros([1])) <NEW_LINE> self.y = self.W * self.x_data + self.b <NEW_LINE> <DEDENT> def def_cost_function(self): <NEW_LINE> <INDENT> self.loss = tf.reduce_mean(tf.square(self.y - self.y_data)) <NEW_LINE> self.optimizer = tf.train.GradientDescentOptimizer(0.5) <NEW_LINE> self.train = self.optimizer.minimize(self.loss) <NEW_LINE> <DEDENT> def draw_plot_training(self, sess, x_data, y_data, W, b): <NEW_LINE> <INDENT> plt.plot(x_data, y_data, 'ro') <NEW_LINE> plt.plot(x_data, sess.run(W) * x_data + sess.run(b)) <NEW_LINE> plt.xlabel('x') <NEW_LINE> plt.xlim(-2, 2) <NEW_LINE> plt.ylabel('y') <NEW_LINE> plt.ylim(0.1, 0.6) <NEW_LINE> plt.show() <NEW_LINE> <DEDENT> def training(self, sess, learning_count): <NEW_LINE> <INDENT> for step in range(learning_count): <NEW_LINE> <INDENT> sess.run(self.train) <NEW_LINE> print("step:{0} W:{1} b:{2}".format(step, sess.run(self.W), sess.run(self.b))) <NEW_LINE> print("step:{0} loss:{1}".format(step, sess.run(self.loss))) <NEW_LINE> self.draw_plot_training(sess, self.x_data, self.y_data, self.W, self.b) <NEW_LINE> <DEDENT> <DEDENT> def run(self, learning_count): <NEW_LINE> <INDENT> init = tf.global_variables_initializer() <NEW_LINE> sess = tf.Session() <NEW_LINE> sess.run(init) <NEW_LINE> lr.training(sess, learning_count) <NEW_LINE> <DEDENT> def evaluation(self): <NEW_LINE> <INDENT> print("evaluation") | Linear Regression CLASS | 62598fcd60cbc95b06364726 |
class NeurioData: <NEW_LINE> <INDENT> def __init__(self, api_key, api_secret, sensor_id): <NEW_LINE> <INDENT> self.api_key = api_key <NEW_LINE> self.api_secret = api_secret <NEW_LINE> self.sensor_id = sensor_id <NEW_LINE> self._daily_usage = None <NEW_LINE> self._active_power = None <NEW_LINE> self._state = None <NEW_LINE> neurio_tp = neurio.TokenProvider(key=api_key, secret=api_secret) <NEW_LINE> self.neurio_client = neurio.Client(token_provider=neurio_tp) <NEW_LINE> if not self.sensor_id: <NEW_LINE> <INDENT> user_info = self.neurio_client.get_user_information() <NEW_LINE> _LOGGER.warning( "Sensor ID auto-detected: %s", user_info["locations"][0]["sensors"][0]["sensorId"], ) <NEW_LINE> self.sensor_id = user_info["locations"][0]["sensors"][0]["sensorId"] <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def daily_usage(self): <NEW_LINE> <INDENT> return self._daily_usage <NEW_LINE> <DEDENT> @property <NEW_LINE> def active_power(self): <NEW_LINE> <INDENT> return self._active_power <NEW_LINE> <DEDENT> def get_active_power(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sample = self.neurio_client.get_samples_live_last(self.sensor_id) <NEW_LINE> self._active_power = sample["consumptionPower"] <NEW_LINE> <DEDENT> except (requests.exceptions.RequestException, ValueError, KeyError): <NEW_LINE> <INDENT> _LOGGER.warning("Could not update current power usage") <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> def get_daily_usage(self): <NEW_LINE> <INDENT> kwh = 0 <NEW_LINE> start_time = dt_util.start_of_local_day().astimezone(dt_util.UTC).isoformat() <NEW_LINE> end_time = dt_util.utcnow().isoformat() <NEW_LINE> _LOGGER.debug("Start: %s, End: %s", start_time, end_time) <NEW_LINE> try: <NEW_LINE> <INDENT> history = self.neurio_client.get_samples_stats( self.sensor_id, start_time, "days", end_time ) <NEW_LINE> <DEDENT> except (requests.exceptions.RequestException, ValueError, KeyError): <NEW_LINE> <INDENT> _LOGGER.warning("Could not update daily power usage") <NEW_LINE> return None <NEW_LINE> <DEDENT> for result in history: <NEW_LINE> <INDENT> kwh += result["consumptionEnergy"] / 3600000 <NEW_LINE> <DEDENT> self._daily_usage = round(kwh, 2) | Stores data retrieved from Neurio sensor. | 62598fcd3617ad0b5ee06531 |
class SierraWireless875(DBusDevicePlugin): <NEW_LINE> <INDENT> name = "SierraWireless 875" <NEW_LINE> version = "0.1" <NEW_LINE> author = "anmsid & kgb0y" <NEW_LINE> custom = SierraWirelessCustomizer <NEW_LINE> __remote_name__ = "AC875" <NEW_LINE> __properties__ = { 'usb_device.vendor_id' : [0x1199], 'usb_device.product_id': [0x6820], } | L{vmc.common.plugin.DBusDevicePlugin} for SierraWireless 875 | 62598fcd8a349b6b43686629 |
class RepositoryEnv(RepositoryBase): <NEW_LINE> <INDENT> def __init__(self, source): <NEW_LINE> <INDENT> self.data = {} <NEW_LINE> for line in open(source): <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if not line or line.startswith('#') or '=' not in line: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> k, v = line.split('=', 1) <NEW_LINE> k = k.strip() <NEW_LINE> v = v.strip().strip('\'"') <NEW_LINE> self.data[k] = v <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self.data or key in os.environ <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.data[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return os.environ[key] | Retrieves option keys from .env files with fall back to os.environ. | 62598fcda219f33f346c6bf2 |
class Network(BaseAccountingType): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> BaseAccountingType.__init__(self) <NEW_LINE> self.definitionKeyFields = [ ('SourceIP', 'VARCHAR(50)'), ('DestinationIP', 'VARCHAR(50)'), ('SourceHostName', 'VARCHAR(50)'), ('DestinationHostName', 'VARCHAR(50)'), ('Source', 'VARCHAR(50)'), ('Destination', 'VARCHAR(50)') ] <NEW_LINE> self.definitionAccountingFields = [ ('Jitter', 'FLOAT'), ('OneWayDelay', 'FLOAT'), ('PacketLossRate', 'TINYINT UNSIGNED'), ] <NEW_LINE> self.bucketsLength = [ (86400 * 3, 900), (86400 * 8, 3600), (15552000, 86400), (31104000, 604800), ] <NEW_LINE> self.checkType() | Accounting type to stores network metrics gathered by perfSONARs. | 62598fcd5fdd1c0f98e5e376 |
class ListBatchSubscribeCSVResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_SuccessList(self): <NEW_LINE> <INDENT> return self._output.get('SuccessList', None) <NEW_LINE> <DEDENT> def get_ErrorList(self): <NEW_LINE> <INDENT> return self._output.get('ErrorList', None) | A ResultSet with methods tailored to the values returned by the ListBatchSubscribeCSV Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 62598fcd7b180e01f3e49244 |
class ListItem(Component): <NEW_LINE> <INDENT> @_explicitize_args <NEW_LINE> def __init__(self, children=None, alignItems=Component.UNDEFINED, button=Component.UNDEFINED, className=Component.UNDEFINED, component=Component.UNDEFINED, ContainerComponent=Component.UNDEFINED, ContainerProps=Component.UNDEFINED, dense=Component.UNDEFINED, disabled=Component.UNDEFINED, disableGutters=Component.UNDEFINED, divider=Component.UNDEFINED, href=Component.UNDEFINED, id=Component.UNDEFINED, selected=Component.UNDEFINED, style=Component.UNDEFINED, **kwargs): <NEW_LINE> <INDENT> self._prop_names = ['children', 'alignItems', 'button', 'className', 'component', 'ContainerComponent', 'ContainerProps', 'dense', 'disabled', 'disableGutters', 'divider', 'href', 'id', 'selected', 'style'] <NEW_LINE> self._type = 'ListItem' <NEW_LINE> self._namespace = 'dashmaterialui' <NEW_LINE> self._valid_wildcard_attributes = [] <NEW_LINE> self.available_properties = ['children', 'alignItems', 'button', 'className', 'component', 'ContainerComponent', 'ContainerProps', 'dense', 'disabled', 'disableGutters', 'divider', 'href', 'id', 'selected', 'style'] <NEW_LINE> self.available_wildcard_properties = [] <NEW_LINE> _explicit_args = kwargs.pop('_explicit_args') <NEW_LINE> _locals = locals() <NEW_LINE> _locals.update(kwargs) <NEW_LINE> args = {k: _locals[k] for k in _explicit_args if k != 'children'} <NEW_LINE> for k in []: <NEW_LINE> <INDENT> if k not in args: <NEW_LINE> <INDENT> raise TypeError( 'Required argument `' + k + '` was not specified.') <NEW_LINE> <DEDENT> <DEDENT> super(ListItem, self).__init__(children=children, **args) | A ListItem component.
ExampleComponent is an example component.
It takes a property, `label`, and
displays it.
It renders an input with the property `value`
which is editable by the user.
Keyword arguments:
- children (a list of or a singular dash component, string or number; optional): The content of the component. If a ListItemSecondaryAction is used it must be the last child.
- alignItems (a value equal to: 'flex-start', 'center'; optional): Defines the align-items style property.
- button (boolean; optional): If true, the list item will be a button (using ButtonBase).
- className (string; optional): Override or extend the styles applied to the component. See CSS API below for more details.
- component (optional): The component used for the root node. Either a string to use a DOM element or a component. By default, it's a li when button is false and a div when button is true.
- ContainerComponent (optional): The container component used when a ListItemSecondaryAction is the last child.
- ContainerProps (dict; optional): Properties applied to the container component if used.
- dense (boolean; optional): If true, compact vertical padding designed for keyboard and mouse input will be used.
- disabled (boolean; optional): If true, the list item will be disabled.
- disableGutters (boolean; optional): If true, the left and right padding is removed.
- divider (boolean; optional): If true, a 1px light border is added to the bottom of the list item.
- href (string; optional): The url
- id (string; optional): The components id
- selected (boolean; optional): Use to apply selected styling.
- style (dict; optional): Add style object | 62598fcdcc40096d6161a3cc |
class LogoutView(View): <NEW_LINE> <INDENT> def get(self,request): <NEW_LINE> <INDENT> logout(request) <NEW_LINE> return HttpResponseRedirect(reverse('index')) | 注销 | 62598fcdf9cc0f698b1c54c9 |
class UnknownVersionException(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> self.message = message | Exception raised for unknown Mojang version file format versions.
Attributes:
message -- explanation of the error | 62598fcdbf627c535bcb1896 |
class ArticleView(S13CMSMixin, TemplateView): <NEW_LINE> <INDENT> template_name = 'defaults/article.html' <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.settings = Setting.objects.get(is_active=True) <NEW_LINE> self.sections = Article.objects.get_sections() <NEW_LINE> self.section, self.article = Article.objects.get_article( kwargs['section_slug'], kwargs['article_slug'] ) <NEW_LINE> if not self.article: <NEW_LINE> <INDENT> return self.not_found({'s': self.settings}) <NEW_LINE> <DEDENT> if not self.request.user.is_authenticated: <NEW_LINE> <INDENT> if not self.article.is_public or not self.section.is_public: <NEW_LINE> <INDENT> return self.not_found({'s': self.settings}) <NEW_LINE> <DEDENT> <DEDENT> self.articles = self.paginate_children() <NEW_LINE> self.tweak_settings(self.__class__.__name__) <NEW_LINE> self.template_name = self.get_template() <NEW_LINE> return super().get(self.request, *self.args, **self.kwargs) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context['section'] = self.section <NEW_LINE> context['previous_article'], context['next_article'] = self.article.get_previous_and_next() <NEW_LINE> return context | Responds with an Article that has a given parent. | 62598fcda219f33f346c6bf4 |
class Apply(Parser, Infix()): <NEW_LINE> <INDENT> op = "*" <NEW_LINE> def parse(self, stream): <NEW_LINE> <INDENT> result0 = self.left.parse(stream) <NEW_LINE> if result0: <NEW_LINE> <INDENT> result1 = self.right.parse(result0[1]) <NEW_LINE> return result1 and (result0[0](result1[0]), result1[1]) | Applying the parser to the parser.
type: (Parser (a -> b), Parser a) -> Parser b | 62598fcd7b180e01f3e49245 |
class HomeView(RedirectView): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> self.url = reverse("home_dashboard") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.url = reverse("login") <NEW_LINE> <DEDENT> return super(HomeView, self).get(self, request, *args, **kwargs) | Redirect accordingly. If user's not logged in redirect to login view
else redirect to... prospections for now | 62598fcdad47b63b2c5a7c47 |
class CSVExporter(Exporter): <NEW_LINE> <INDENT> def export(self, segments, exportLocation , withHeader=False , withIndices=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(exportLocation, 'w') as exportFile: <NEW_LINE> <INDENT> exp = csv.writer(exportFile) <NEW_LINE> if withHeader: <NEW_LINE> <INDENT> if withIndices: <NEW_LINE> <INDENT> header = ['Index'] <NEW_LINE> header.extend(shared.Sensorsegment._fields) <NEW_LINE> exp.writerow(header) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> header = shared.Sensorsegment._fields <NEW_LINE> exp.writerow(header) <NEW_LINE> <DEDENT> <DEDENT> if withIndices: <NEW_LINE> <INDENT> exp.writerows([( index+1 , value.accelX , value.accelY , value.accelZ , value.gyroX , value.gyroY , value.gyroZ ) for index,value in enumerate(segments)]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> exp.writerows([( value.accelX , value.accelY , value.accelZ , value.gyroX , value.gyroY , value.gyroZ ) for value in segments]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> return True | This Exporter handles the export of the RawValidation files to CSV files.
After the :class:`Sensorsegments <lib.shared.Sensorsegment>` are
normalized they can be exported back to the filesystem as CSV files. | 62598fcd60cbc95b0636472a |
class WdHwServer(SocketListener): <NEW_LINE> <INDENT> def __init__(self, hw_daemon, socket_path, socket_group=None, max_clients=10): <NEW_LINE> <INDENT> self.__hw_daemon = hw_daemon <NEW_LINE> socket_factory = UnixSocketFactory(socket_path) <NEW_LINE> server_socket = socket_factory.bindSocket(socket_group) <NEW_LINE> super().__init__(server_socket, max_clients, server_thread_class=ServerThreadImpl) <NEW_LINE> <DEDENT> @property <NEW_LINE> def hw_daemon(self): <NEW_LINE> <INDENT> return self.__hw_daemon | WD Hardware Controller Server.
Attributes:
hw_daemon: The parent hardware controller daemon. | 62598fcd55399d3f05626906 |
class STEPPartImporter(Importer): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def _mangled_filename(cls, name): <NEW_LINE> <INDENT> name = os.path.basename(name) <NEW_LINE> name = name.encode('ascii', 'ignore') <NEW_LINE> if type(name).__name__ == 'bytes': <NEW_LINE> <INDENT> name = name.decode() <NEW_LINE> <DEDENT> if re.search(r'^\d', name): <NEW_LINE> <INDENT> name = '_' + name <NEW_LINE> <DEDENT> name = re.sub(r'[^a-z0-9_]', '_', name, flags=re.I) <NEW_LINE> return name | Abstraction layer to avoid duplicate code for :meth:`_mangled_filename`. | 62598fcd9f28863672818a73 |
class UntargetedF7Objective(Objective): <NEW_LINE> <INDENT> def __call__(self, logits, perturbations=None): <NEW_LINE> <INDENT> assert self.true_classes is not None <NEW_LINE> if logits.size(1) > 1: <NEW_LINE> <INDENT> current_logits = logits - common.torch.one_hot(self.true_classes, logits.size(1))*1e12 <NEW_LINE> return - torch.max(current_logits, dim=1)[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return common.torch.binary_labels(self.true_classes.float())*logits.view(-1) | Untargeted objective based on logits, similar to Carlini+Wagner. | 62598fcd0fa83653e46f52d5 |
@implementer(IMetadataLanguages) <NEW_LINE> class MetadataLanguages(Languages, MetadataLanguageAvailability): <NEW_LINE> <INDENT> id = 'plone_app_metadata_languages' <NEW_LINE> title = 'Manages available metadata languages' <NEW_LINE> meta_type = 'Plone App I18N Metadata Languages' | A local utility storing a list of available metadata languages.
Let's make sure that this implementation actually fulfills the API.
>>> from zope.interface.verify import verifyClass
>>> verifyClass(IMetadataLanguages, MetadataLanguages)
True | 62598fcd3346ee7daa33783e |
class NavFft(NavMenu): <NEW_LINE> <INDENT> replot = pyqtSignal(str, str, str) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(NavFft, self).__init__() <NEW_LINE> self.nthFftFrame = QVBoxLayout() <NEW_LINE> self.nthFftText = QLabel("n-th Octave") <NEW_LINE> self.nthFftText.setAlignment(Qt.AlignHCenter) <NEW_LINE> self.nthFft = QComboBox() <NEW_LINE> self.nthFft.addItems(["1", "3", "6", "12", "24"]) <NEW_LINE> self.nthFft.currentIndexChanged.connect(self.sendReplot) <NEW_LINE> self.nthFftFrame.addWidget(self.nthFftText) <NEW_LINE> self.nthFftFrame.addWidget(self.nthFft) <NEW_LINE> self.selectionLayout = QHBoxLayout() <NEW_LINE> self.selectionLayout.addLayout(self.fqWeightingFrame) <NEW_LINE> self.selectionLayout.addLayout(self.nthFftFrame) <NEW_LINE> self.layout.addLayout(self.deleteFrame) <NEW_LINE> self.layout.addLayout(self.selectionLayout) <NEW_LINE> self.layout.addLayout(self.buttonFrame) <NEW_LINE> self.setLayout(self.layout) <NEW_LINE> <DEDENT> def sendReplot(self): <NEW_LINE> <INDENT> timeWeight = str(self.timeWeighting.currentText()) <NEW_LINE> fqWeight = str(self.fqWeighting.currentText()) <NEW_LINE> nthoctave = str(self.nthFft.currentText()) <NEW_LINE> self.replot.emit(timeWeight, fqWeight, nthoctave) | Class for Analyze Widget Navigation. Derivated from "NavMenu" because additional Navigation (nth FFT)
selection is needed. | 62598fcd5fcc89381b266343 |
@destructiveTest <NEW_LINE> @skipIf(salt.utils.path.which('crond') is None, 'crond not installed') <NEW_LINE> class ServiceTest(ModuleCase, SaltReturnAssertsMixin): <NEW_LINE> <INDENT> def check_service_status(self, exp_return): <NEW_LINE> <INDENT> check_status = self.run_function('service.status', name=SERVICE_NAME) <NEW_LINE> if check_status is not exp_return: <NEW_LINE> <INDENT> self.fail('status of service is not returning correctly') <NEW_LINE> <DEDENT> <DEDENT> def test_service_dead(self): <NEW_LINE> <INDENT> start_service = self.run_state('service.running', name=SERVICE_NAME) <NEW_LINE> self.assertSaltTrueReturn(start_service) <NEW_LINE> self.check_service_status(True) <NEW_LINE> ret = self.run_state('service.dead', name=SERVICE_NAME) <NEW_LINE> self.assertSaltTrueReturn(ret) <NEW_LINE> self.check_service_status(False) <NEW_LINE> <DEDENT> def test_service_dead_init_delay(self): <NEW_LINE> <INDENT> start_service = self.run_state('service.running', name=SERVICE_NAME) <NEW_LINE> self.assertSaltTrueReturn(start_service) <NEW_LINE> self.check_service_status(True) <NEW_LINE> ret = self.run_state('service.dead', name=SERVICE_NAME, init_delay=INIT_DELAY) <NEW_LINE> self.assertSaltTrueReturn(ret) <NEW_LINE> self.check_service_status(False) | Validate the service state | 62598fcd60cbc95b0636472c |
class Label(Element, TimestampsMixin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Label, self).__init__() <NEW_LINE> create_time = time.time() <NEW_LINE> self.id = self._generateId(create_time) <NEW_LINE> self._name = '' <NEW_LINE> self.timestamps = NodeTimestamps(create_time) <NEW_LINE> self._merged = NodeTimestamps.int_to_dt(0) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _generateId(cls, tz): <NEW_LINE> <INDENT> return 'tag.%s.%x' % ( ''.join([random.choice('abcdefghijklmnopqrstuvwxyz0123456789') for _ in range(12)]), int(tz * 1000) ) <NEW_LINE> <DEDENT> def _load(self, raw): <NEW_LINE> <INDENT> super(Label, self)._load(raw) <NEW_LINE> self.id = raw['mainId'] <NEW_LINE> self._name = raw['name'] <NEW_LINE> self.timestamps.load(raw['timestamps']) <NEW_LINE> self._merged = NodeTimestamps.str_to_dt(raw['lastMerged']) if 'lastMerged' in raw else NodeTimestamps.int_to_dt(0) <NEW_LINE> <DEDENT> def save(self, clean=True): <NEW_LINE> <INDENT> ret = super(Label, self).save(clean) <NEW_LINE> ret['mainId'] = self.id <NEW_LINE> ret['name'] = self._name <NEW_LINE> ret['timestamps'] = self.timestamps.save(clean) <NEW_LINE> ret['lastMerged'] = NodeTimestamps.dt_to_str(self._merged) <NEW_LINE> return ret <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, value): <NEW_LINE> <INDENT> self._name = value <NEW_LINE> self.touch(True) <NEW_LINE> <DEDENT> @property <NEW_LINE> def merged(self): <NEW_LINE> <INDENT> return self._merged <NEW_LINE> <DEDENT> @merged.setter <NEW_LINE> def merged(self, value): <NEW_LINE> <INDENT> self._merged = value <NEW_LINE> self.touch() <NEW_LINE> <DEDENT> @property <NEW_LINE> def dirty(self): <NEW_LINE> <INDENT> return super(Label, self).dirty or self.timestamps.dirty <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name | Represents a label. | 62598fcd3617ad0b5ee06537 |
class ModifyLivePushAuthKeyRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.DomainName = None <NEW_LINE> self.Enable = None <NEW_LINE> self.MasterAuthKey = None <NEW_LINE> self.BackupAuthKey = None <NEW_LINE> self.AuthDelta = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.DomainName = params.get("DomainName") <NEW_LINE> self.Enable = params.get("Enable") <NEW_LINE> self.MasterAuthKey = params.get("MasterAuthKey") <NEW_LINE> self.BackupAuthKey = params.get("BackupAuthKey") <NEW_LINE> self.AuthDelta = params.get("AuthDelta") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | ModifyLivePushAuthKey请求参数结构体
| 62598fcd7cff6e4e811b5e16 |
class solution4: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.mutex=threading.RLock() <NEW_LINE> self.read = threading.Condition(self.mutex) <NEW_LINE> self.write = threading.Condition(self.mutex) <NEW_LINE> self.rw = 0 <NEW_LINE> self.wlist = 0 <NEW_LINE> <DEDENT> def acquire_read(self, x): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> with self.mutex: <NEW_LINE> <INDENT> if self.rw<0 or self.wlist: <NEW_LINE> <INDENT> self.read.wait() <NEW_LINE> <DEDENT> self.rw+=1 <NEW_LINE> <DEDENT> print('now read begin', x) <NEW_LINE> time.sleep(1) <NEW_LINE> print('now read end', x) <NEW_LINE> <DEDENT> <DEDENT> def acquire_write(self, x): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> with self.mutex: <NEW_LINE> <INDENT> if self.rw: <NEW_LINE> <INDENT> self.wlist+=1 <NEW_LINE> self.write.wait() <NEW_LINE> self.wlist-=1 <NEW_LINE> <DEDENT> self.rw-=1 <NEW_LINE> <DEDENT> print('now is writing', x) <NEW_LINE> time.sleep(1) <NEW_LINE> print('now writing ending', x) <NEW_LINE> <DEDENT> <DEDENT> def release(self): <NEW_LINE> <INDENT> with self.mutex: <NEW_LINE> <INDENT> if self.rw < 0: <NEW_LINE> <INDENT> self.rw = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rw -= 1 <NEW_LINE> <DEDENT> wake_writer = self.wlist and self.rw == 0 <NEW_LINE> wake_reader = self.wlist == 0 <NEW_LINE> <DEDENT> if wake_writer: <NEW_LINE> <INDENT> with self.write: <NEW_LINE> <INDENT> self.write.notify_all() <NEW_LINE> <DEDENT> <DEDENT> if wake_reader: <NEW_LINE> <INDENT> with self.read: <NEW_LINE> <INDENT> self.read.notify_all() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test(self): <NEW_LINE> <INDENT> t1 = threading.Thread(target=self.acquire_read, args=[1]) <NEW_LINE> t2 = threading.Thread(target=self.acquire_read, args=[2]) <NEW_LINE> t3 = threading.Thread(target=self.acquire_write, args=[3]) <NEW_LINE> t4 = threading.Thread(target=self.acquire_write, args=[4]) <NEW_LINE> t1.start() <NEW_LINE> t2.start() <NEW_LINE> t3.start() <NEW_LINE> t4.start() | A lock object that allows many simultaneous "read locks", but
only one "write lock." | 62598fcd7c178a314d78d88e |
class CoNLLDataset(object): <NEW_LINE> <INDENT> def __init__(self, filename, processing_word=None, processing_tag=None, max_iter=None): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.processing_word = processing_word <NEW_LINE> self.processing_tag = processing_tag <NEW_LINE> self.max_iter = max_iter <NEW_LINE> self.length = None <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> n_iter = 0 <NEW_LINE> with open(self.filename) as f: <NEW_LINE> <INDENT> words, tags = [], [] <NEW_LINE> for line in f: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if len(line) == 0: <NEW_LINE> <INDENT> if len(words) != 0: <NEW_LINE> <INDENT> n_iter += 1 <NEW_LINE> if self.max_iter and n_iter > self.max_iter: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> yield words, tags <NEW_LINE> words, tags = [], [] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ls = re.split("\s+|\t+", line) <NEW_LINE> word, tag = ls[0], ls[-1] <NEW_LINE> if self.processing_word: <NEW_LINE> <INDENT> word = self.processing_word(word) <NEW_LINE> <DEDENT> if self.processing_tag: <NEW_LINE> <INDENT> tag = self.processing_tag(tag) <NEW_LINE> <DEDENT> words.append(word) <NEW_LINE> tags.append(tag) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> if self.length is None: <NEW_LINE> <INDENT> self.length = 0 <NEW_LINE> for _ in self: <NEW_LINE> <INDENT> self.length += 1 <NEW_LINE> <DEDENT> <DEDENT> return self.length | Class that iterates over CoNLL Dataset
__iter__ method yields a tuple (words, tags)
words: list of raw words
tags: list of raw tags
If processing_word and processing_tag are not None,
optional preprocessing is appplied
Example:
```python
data = CoNLLDataset(filename)
for sentence, tags in data:
pass
``` | 62598fcd3346ee7daa33783f |
class BundleField(tuple, PayloadField): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def _hash_bundle(bundle): <NEW_LINE> <INDENT> hasher = sha1() <NEW_LINE> hasher.update(bundle.rel_path.encode('utf-8')) <NEW_LINE> for abs_path in sorted(bundle.filemap.keys()): <NEW_LINE> <INDENT> buildroot_relative_path = os.path.relpath(abs_path, get_buildroot()).encode('utf-8') <NEW_LINE> hasher.update(buildroot_relative_path) <NEW_LINE> hasher.update(bundle.filemap[abs_path].encode('utf-8')) <NEW_LINE> if os.path.isfile(abs_path): <NEW_LINE> <INDENT> hasher.update(b'e') <NEW_LINE> with open(abs_path, 'rb') as f: <NEW_LINE> <INDENT> hasher.update(f.read()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return hasher.hexdigest() <NEW_LINE> <DEDENT> def _compute_fingerprint(self): <NEW_LINE> <INDENT> return combine_hashes(list(map(BundleField._hash_bundle, self))) | A tuple subclass that mixes in PayloadField.
Must be initialized with an iterable of Bundle instances. | 62598fcdbe7bc26dc9252051 |
class ReduceOperator(Operator): <NEW_LINE> <INDENT> def __init__(self, operator, identity=None, unpack=False): <NEW_LINE> <INDENT> super(ReduceOperator, self).__init__(operator, unpack=unpack) <NEW_LINE> self.identity = identity <NEW_LINE> <DEDENT> def _operate(self, pool, name): <NEW_LINE> <INDENT> if not pool: <NEW_LINE> <INDENT> if self.identity: <NEW_LINE> <INDENT> return constant(self.identity) <NEW_LINE> <DEDENT> raise ValueError <NEW_LINE> <DEDENT> drvs = self._prepare(pool) <NEW_LINE> return self._reduce(drvs, name) <NEW_LINE> <DEDENT> def _prepare(self, pool): <NEW_LINE> <INDENT> return pool.drvs <NEW_LINE> <DEDENT> def _pack(self, drv, name): <NEW_LINE> <INDENT> return drv <NEW_LINE> <DEDENT> force_int = True <NEW_LINE> def _reduce(self, drvs, name): <NEW_LINE> <INDENT> res = drvs[0] <NEW_LINE> for rv in drvs[1:]: <NEW_LINE> <INDENT> _pool = RandomVariablePool(res, rv) <NEW_LINE> res = super(ReduceOperator, self)._operate( _pool, name, force_int=self.force_int) <NEW_LINE> <DEDENT> return self._pack(res, name) | This is a class of operators which may be reduced to simple memoryless
binary operators. | 62598fcd50812a4eaa620ddc |
class TournamentDB(InteractDB): <NEW_LINE> <INDENT> def __init__(self, db_file_name): <NEW_LINE> <INDENT> super(TournamentDB, self).__init__(db_file_name) <NEW_LINE> <DEDENT> def list_tournaments_in_db(self): <NEW_LINE> <INDENT> all_tournaments = self.tournaments.search(self.info["tournament_data"].exists()) <NEW_LINE> return all_tournaments <NEW_LINE> <DEDENT> def save_tournament_in_db(self, serialized_info, update=False): <NEW_LINE> <INDENT> tournament_name = serialized_info["tournament_data"]["tournament_info"]["name"] <NEW_LINE> if self.tournaments.search(self.info["tournament_data"]["tournament_info"]["name"] == tournament_name): <NEW_LINE> <INDENT> if update is True: <NEW_LINE> <INDENT> self.tournaments.update(delete("tournament_data"), self.info["tournament_data"]["tournament_info"]["name"] == tournament_name) <NEW_LINE> self.tournaments.insert(serialized_info) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Warning("Tournoi déjà sauvegardé dans la base de données.") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.tournaments.insert(serialized_info) <NEW_LINE> <DEDENT> <DEDENT> def load_tournament_from_db(self, tournament_name): <NEW_LINE> <INDENT> global_data = self.tournaments.get(self.info["tournament_data"]["tournament_info"]["name"] == tournament_name) <NEW_LINE> if global_data: <NEW_LINE> <INDENT> trn_info = global_data["tournament_data"]["tournament_info"] <NEW_LINE> try: <NEW_LINE> <INDENT> players_info = global_data["tournament_data"]["players_list"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> players_info = None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> rounds_info = global_data["tournament_data"]["rounds_list"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> rounds_info = None <NEW_LINE> <DEDENT> return (trn_info, players_info, rounds_info) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Warning("Tournoi inexistant dans la base de données.") | Class to write informations from controller into tournament DB file
and read informations from tournament DB file to be sent to the
controller. | 62598fcd97e22403b383b2f7 |
class IconTreeItem(TreeItem): <NEW_LINE> <INDENT> def __init__(self, key, value, image=None, icon_filename=None): <NEW_LINE> <INDENT> TreeItem.__init__(self, key, value) <NEW_LINE> if image is not None: <NEW_LINE> <INDENT> self.__image = image <NEW_LINE> <DEDENT> elif icon_filename is not None: <NEW_LINE> <INDENT> self.__image = gtk.Image() <NEW_LINE> self.__image.set_from_file(icon_filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__image = gtk.Image() <NEW_LINE> <DEDENT> <DEDENT> def get_icon(self): <NEW_LINE> <INDENT> return self.__image <NEW_LINE> <DEDENT> icon = property(get_icon) <NEW_LINE> def get_pixbuf(self): <NEW_LINE> <INDENT> return getattr(self.icon, 'get_pixbuf', lambda: self.icon)() <NEW_LINE> <DEDENT> pixbuf = property(get_pixbuf) | I tree item with an icon. | 62598fcd3617ad0b5ee06539 |
class KokuDBAccess: <NEW_LINE> <INDENT> _savepoints = [] <NEW_LINE> def __init__(self, schema): <NEW_LINE> <INDENT> self.schema = schema <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> connection = get_connection() <NEW_LINE> if connection.get_autocommit(): <NEW_LINE> <INDENT> connection.set_autocommit(False) <NEW_LINE> <DEDENT> KokuDBAccess._savepoints.append(transaction.savepoint()) <NEW_LINE> connection.set_schema(self.schema) <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, exception_type, exception_value, traceback): <NEW_LINE> <INDENT> connection = get_connection() <NEW_LINE> with schema_context(self.schema): <NEW_LINE> <INDENT> if KokuDBAccess._savepoints: <NEW_LINE> <INDENT> if exception_type: <NEW_LINE> <INDENT> transaction.savepoint_rollback(KokuDBAccess._savepoints.pop()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> transaction.savepoint_commit(KokuDBAccess._savepoints.pop()) <NEW_LINE> <DEDENT> <DEDENT> if not connection.in_atomic_block: <NEW_LINE> <INDENT> transaction.commit() <NEW_LINE> connection.set_autocommit(True) <NEW_LINE> <DEDENT> <DEDENT> connection.set_schema_to_public() <NEW_LINE> <DEDENT> def close_session(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_base(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def get_session(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def get_engine(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def get_meta(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def _get_db_obj_query(self, **filter_args): <NEW_LINE> <INDENT> with schema_context(self.schema): <NEW_LINE> <INDENT> queryset = self._table.objects.all() <NEW_LINE> if filter_args: <NEW_LINE> <INDENT> queryset = queryset.filter(**filter_args) <NEW_LINE> <DEDENT> return queryset <NEW_LINE> <DEDENT> <DEDENT> def does_db_entry_exist(self): <NEW_LINE> <INDENT> with schema_context(self.schema): <NEW_LINE> <INDENT> return self._get_db_obj_query().exists() <NEW_LINE> <DEDENT> <DEDENT> def add(self, **kwargs): <NEW_LINE> <INDENT> with schema_context(self.schema): <NEW_LINE> <INDENT> new_entry = self._table.objects.create(**kwargs) <NEW_LINE> new_entry.save() <NEW_LINE> return new_entry <NEW_LINE> <DEDENT> <DEDENT> def commit(self): <NEW_LINE> <INDENT> with schema_context(self.schema): <NEW_LINE> <INDENT> transaction.commit() <NEW_LINE> <DEDENT> <DEDENT> def delete(self, obj=None): <NEW_LINE> <INDENT> if obj: <NEW_LINE> <INDENT> deleteme = obj <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> deleteme = self._obj <NEW_LINE> <DEDENT> with schema_context(self.schema): <NEW_LINE> <INDENT> deleteme.delete() <NEW_LINE> <DEDENT> <DEDENT> def savepoint(self, func, *args, **kwargs): <NEW_LINE> <INDENT> with schema_context(self.schema): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sid = django_savepoint() <NEW_LINE> func(*args, **kwargs) <NEW_LINE> savepoint_commit(sid) <NEW_LINE> <DEDENT> except IntegrityError as exc: <NEW_LINE> <INDENT> LOG.warning('query transaction failed: %s', exc) <NEW_LINE> savepoint_rollback(sid) | Base Class to connect to the koku database.
Subclass of Django Atomic class to make use of atomic transactions
with a schema/tenant context. | 62598fcd7c178a314d78d890 |
class Accuracy(EvalMetric): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Accuracy, self).__init__('accuracy') <NEW_LINE> <DEDENT> def update(self, labels, preds): <NEW_LINE> <INDENT> check_label_shapes(labels, preds) <NEW_LINE> for label, pred_label in zip(labels, preds): <NEW_LINE> <INDENT> if pred_label.shape != label.shape: <NEW_LINE> <INDENT> pred_label = ndarray.argmax_channel(pred_label) <NEW_LINE> <DEDENT> pred_label = pred_label.asnumpy().astype('int32') <NEW_LINE> label = label.asnumpy().astype('int32') <NEW_LINE> check_label_shapes(label, pred_label) <NEW_LINE> self.sum_metric += (pred_label.flat == label.flat).sum() <NEW_LINE> self.num_inst += len(pred_label.flat) | Calculate accuracy | 62598fcd851cf427c66b86a3 |
class WSGI_HTTPSConnection(HTTPSConnection, WSGI_HTTPConnection): <NEW_LINE> <INDENT> def get_app(self, host, port): <NEW_LINE> <INDENT> key = (host, int(port)) <NEW_LINE> app, script_name = None, None <NEW_LINE> if key in _wsgi_intercept: <NEW_LINE> <INDENT> (app_fn, script_name) = _wsgi_intercept[key] <NEW_LINE> app = app_fn() <NEW_LINE> <DEDENT> return app, script_name <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> if debuglevel: <NEW_LINE> <INDENT> sys.stderr.write('connect: %s, %s\n' % (self.host, self.port,)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> (app, script_name) = self.get_app(self.host, self.port) <NEW_LINE> if app: <NEW_LINE> <INDENT> if debuglevel: <NEW_LINE> <INDENT> sys.stderr.write('INTERCEPTING call to %s:%s\n' % (self.host, self.port,)) <NEW_LINE> <DEDENT> self.sock = wsgi_fake_socket(app, self.host, self.port, script_name, https=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import ssl <NEW_LINE> if hasattr(self, '_context'): <NEW_LINE> <INDENT> self._context.check_hostname = self.assert_hostname <NEW_LINE> self._check_hostname = self.assert_hostname <NEW_LINE> if hasattr(ssl, 'VerifyMode'): <NEW_LINE> <INDENT> if isinstance(self.cert_reqs, ssl.VerifyMode): <NEW_LINE> <INDENT> self._context.verify_mode = self.cert_reqs <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._context.verify_mode = ssl.VerifyMode[ self.cert_reqs] <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(self.cert_reqs, six.string_types): <NEW_LINE> <INDENT> self._context.verify_mode = getattr(ssl, self.cert_reqs, self._context.verify_mode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._context.verify_mode = self.cert_reqs <NEW_LINE> <DEDENT> <DEDENT> if not hasattr(self, 'key_file'): <NEW_LINE> <INDENT> self.key_file = None <NEW_LINE> <DEDENT> if not hasattr(self, 'cert_file'): <NEW_LINE> <INDENT> self.cert_file = None <NEW_LINE> <DEDENT> if not hasattr(self, '_context'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._context = ssl.create_default_context() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self._context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) <NEW_LINE> self._context.options |= ssl.OP_NO_SSLv2 <NEW_LINE> if not hasattr(self, 'check_hostname'): <NEW_LINE> <INDENT> self._check_hostname = ( self._context.verify_mode != ssl.CERT_NONE ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._check_hostname = self.check_hostname <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except (ImportError, AttributeError): <NEW_LINE> <INDENT> import traceback <NEW_LINE> traceback.print_exc() <NEW_LINE> <DEDENT> HTTPSConnection.connect(self) <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> if debuglevel: <NEW_LINE> <INDENT> traceback.print_exc() <NEW_LINE> <DEDENT> raise | Intercept all traffic to certain hosts & redirect into a WSGI
application object. | 62598fcddc8b845886d539ae |
class Config(object): <NEW_LINE> <INDENT> SECRET_KEY = os.environ.get('ABG_STATS_SECRET', 'secret-key') <NEW_LINE> APP_DIR = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir)) <NEW_LINE> BCRYPT_LOG_ROUNDS = 13 <NEW_LINE> ASSETS_DEBUG = False <NEW_LINE> DEBUG_TB_ENABLED = False <NEW_LINE> DEBUG_TB_INTERCEPT_REDIRECTS = False <NEW_LINE> CACHE_TYPE = 'simple' <NEW_LINE> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> XP_THRESHOLD = 100 <NEW_LINE> DATA_DIR = PROJECT_ROOT + "/data" | Base configuration. | 62598fcd5fdd1c0f98e5e37e |
class Glass(BaseModel): <NEW_LINE> <INDENT> type: Enum('Glass', {'type': 'Glass'}) <NEW_LINE> name: str = Schema( ..., regex=r'^[.A-Za-z0-9_-]*$' ) <NEW_LINE> r_transmittance: float = Schema( ..., ge=0, le=1 ) <NEW_LINE> g_transmittance: float = Schema( ..., ge=0, le=1 ) <NEW_LINE> b_transmittance: float = Schema( ..., ge=0, le=1 ) <NEW_LINE> refraction_index: float = Schema( ..., ge=0, le=5 ) <NEW_LINE> modifier: str = 'void' | Glass Material Schema | 62598fcdec188e330fdf8c87 |
class Reference(ReferenceBase): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> ReferenceBase.__init__(self, value) <NEW_LINE> self.split = value.split('/') <NEW_LINE> self.resolved = None <NEW_LINE> <DEDENT> def getPaths(self): <NEW_LINE> <INDENT> return [self.value] <NEW_LINE> <DEDENT> def resolve(self, thissetting): <NEW_LINE> <INDENT> if self.resolved: <NEW_LINE> <INDENT> return self.resolved <NEW_LINE> <DEDENT> item = thissetting.parent <NEW_LINE> parts = list(self.split) <NEW_LINE> if parts[0] == '': <NEW_LINE> <INDENT> while item.parent is not None: <NEW_LINE> <INDENT> item = item.parent <NEW_LINE> <DEDENT> parts = parts[1:] <NEW_LINE> <DEDENT> for p in parts: <NEW_LINE> <INDENT> if p == '..': <NEW_LINE> <INDENT> if item.parent is not None: <NEW_LINE> <INDENT> item = item.parent <NEW_LINE> <DEDENT> <DEDENT> elif p == '': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if item.iswidget: <NEW_LINE> <INDENT> child = item.getChild(p) <NEW_LINE> if not child: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> item = item.settings.get(p) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise self.ResolveException() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> item = child <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> item = item.get(p) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise self.ResolveException() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if len(self.split) > 2 and self.split[1] == 'StyleSheet': <NEW_LINE> <INDENT> self.resolved = item <NEW_LINE> <DEDENT> return item <NEW_LINE> <DEDENT> def setOnModified(self, setn, fn): <NEW_LINE> <INDENT> resolved = self.resolve(setn) <NEW_LINE> resolved.setOnModified(fn) | A value a setting can have to point to another setting.
Formats of a reference are like
/foo/bar/setting or
../Line/width
alternatively style sheets can be used with the format, e.g.
/StyleSheet/linewidth | 62598fcd4527f215b58ea2c0 |
class LoggerProxy(object): <NEW_LINE> <INDENT> def __init__(self, logger=None): <NEW_LINE> <INDENT> self.log = logger <NEW_LINE> <DEDENT> @property <NEW_LINE> def log_path(self): <NEW_LINE> <INDENT> if self.log: <NEW_LINE> <INDENT> return self.log.log_path <NEW_LINE> <DEDENT> return "/tmp/logs" <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> def log_call(*args): <NEW_LINE> <INDENT> if self.log: <NEW_LINE> <INDENT> return getattr(self.log, name)(*args) <NEW_LINE> <DEDENT> print(*args) <NEW_LINE> <DEDENT> return log_call | This class is for situations where a logger may or may not exist.
e.g. In controller classes, sometimes we don't have a logger to pass in,
like during a quick try in python console. In these cases, we don't want to
crash on the log lines because logger is None, so we should set self.log to
an object of this class in the controller classes, instead of the actual
logger object. | 62598fcdad47b63b2c5a7c4d |
class sc(crystal): <NEW_LINE> <INDENT> def __init__(self, E, N, a, repeats=None, rotangles=(0, 0, 0), fwhm=None, rho=None): <NEW_LINE> <INDENT> lconst = [a, a, a] <NEW_LINE> unitcell = [[0, 0, 0]] <NEW_LINE> langle = _np.array([90, 90, 90]) * pi / 180.0 <NEW_LINE> super().__init__(E, lconst, langle, unitcell, N, repeats, rotangles, fwhm, rho) | a sc crystal | 62598fcd3d592f4c4edbb2a7 |
class Sketch(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def fromParameters(cls, delta, epsilon): <NEW_LINE> <INDENT> width = int(math.ceil(math.exp(1) / epsilon)) <NEW_LINE> rnd_width = int(pow(2, math.ceil(math.log(width, 2)))) <NEW_LINE> depth = int(math.ceil(math.log(1 / delta))) <NEW_LINE> return cls([mshash.MultiplyShift(rnd_width) for _ in xrange(depth)], rnd_width) <NEW_LINE> <DEDENT> def __init__(self, hashes, width): <NEW_LINE> <INDENT> assert len(hashes) >= 1 <NEW_LINE> assert width > 0 <NEW_LINE> print("Using %d hashes, width: %d - total size: %d" % (len(hashes), width, len(hashes) * width)) <NEW_LINE> self.hashes = hashes <NEW_LINE> self.width = width <NEW_LINE> self.counters = [[0] * self.width for _ in xrange(len(self.hashes))] <NEW_LINE> self.observed = 0 <NEW_LINE> <DEDENT> def obs(self, num): <NEW_LINE> <INDENT> self.observed += 1 <NEW_LINE> for i in xrange(len(self.hashes)): <NEW_LINE> <INDENT> self.counters[i][self.hashes[i].apply(num) % self.width] += 1 <NEW_LINE> <DEDENT> <DEDENT> def count_obs(self, num): <NEW_LINE> <INDENT> return min(self.counters[i][self.hashes[i].apply(num) % self.width] for i in xrange(len(self.hashes))) | Count-min sketch summary of data
Estimate upper bounded by e(x) <= f(x) + eps * num_distinct(input) with probability 1 - delta
Where e(x) estimate count, f(x) actual count | 62598fcd091ae3566870501d |
class MappingSet(Set): <NEW_LINE> <INDENT> @property <NEW_LINE> def mutable(self): <NEW_LINE> <INDENT> return isinstance(self._lst, set) <NEW_LINE> <DEDENT> def freeze(self): <NEW_LINE> <INDENT> if self.mutable: <NEW_LINE> <INDENT> self._lst = frozenset(self._lst) <NEW_LINE> <DEDENT> <DEDENT> def fromVM(self, vmaddr): <NEW_LINE> <INDENT> return _fromToVM(self._lst, vmaddr, Mapping.fromVM) <NEW_LINE> <DEDENT> def toVM(self, offset): <NEW_LINE> <INDENT> return _fromToVM(self._lst, offset, Mapping.toVM) <NEW_LINE> <DEDENT> def optimize(self): <NEW_LINE> <INDENT> def _optimized(): <NEW_LINE> <INDENT> sortedMappings = iter(sorted(self._lst, key=attrgetter('address'))) <NEW_LINE> lastMapping = next(sortedMappings).copy() <NEW_LINE> for mapping in sortedMappings: <NEW_LINE> <INDENT> if lastMapping.offset >= 0 and mapping.address - lastMapping.address == lastMapping.size and mapping.offset - lastMapping.offset == lastMapping.size and mapping.initprot == lastMapping.initprot and mapping.maxprot == lastMapping.maxprot: <NEW_LINE> <INDENT> lastMapping.size += mapping.size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield lastMapping <NEW_LINE> lastMapping = mapping.copy() <NEW_LINE> <DEDENT> <DEDENT> yield lastMapping <NEW_LINE> <DEDENT> self._lst = set(_optimized()) <NEW_LINE> <DEDENT> def __init__(self, lst=None): <NEW_LINE> <INDENT> self._lst = set(lst or []) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._lst) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._lst) <NEW_LINE> <DEDENT> def __contains__(self, mapping): <NEW_LINE> <INDENT> return mapping in self._lst <NEW_LINE> <DEDENT> def add(self, mapping): <NEW_LINE> <INDENT> self._lst.add(mapping) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'MappingSet({0!r})'.format(self._lst) | A container that stores :class:`Mapping`\s. | 62598fcd55399d3f0562690c |
class PerfectLensModel(Model): <NEW_LINE> <INDENT> def __init__(self, scatterer, alpha=1.0, lens_angle=1.0, noise_sd=None, medium_index=None, illum_wavelen=None, theory='auto', illum_polarization=None, constraints=[]): <NEW_LINE> <INDENT> super().__init__(scatterer, noise_sd, medium_index, illum_wavelen, illum_polarization, theory, constraints) <NEW_LINE> self._maps['model'] = self._convert_to_map({'alpha': alpha}) <NEW_LINE> self._maps['theory'] = self._convert_to_map({'lens_angle': lens_angle}) <NEW_LINE> <DEDENT> @property <NEW_LINE> def alpha(self): <NEW_LINE> <INDENT> return read_map(self._maps['model'], self._parameters)['alpha'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def lens_angle(self): <NEW_LINE> <INDENT> return read_map(self._maps['theory'], self._parameters)['lens_angle'] <NEW_LINE> <DEDENT> def _forward(self, pars, detector): <NEW_LINE> <INDENT> alpha = read_map(self._maps['model'], pars)['alpha'] <NEW_LINE> optics_kwargs = self._find_optics(pars, detector) <NEW_LINE> scatterer = self._scatterer_from_parameters(pars) <NEW_LINE> theory_kwargs = read_map(self._maps['theory'], pars) <NEW_LINE> theory = MieLens(**theory_kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> return calc_holo(detector, scatterer, theory=theory, scaling=alpha, **optics_kwargs) <NEW_LINE> <DEDENT> except InvalidScatterer: <NEW_LINE> <INDENT> return -np.inf | Model of hologram image formation through a high-NA objective. | 62598fcd656771135c489a64 |
class Hand(Deck): <NEW_LINE> <INDENT> def __init__(self,label=''): <NEW_LINE> <INDENT> self.cards=[]; <NEW_LINE> self.label=label; <NEW_LINE> <DEDENT> def move_cards(self,hand,num): <NEW_LINE> <INDENT> for i in range(num): <NEW_LINE> <INDENT> hand.add_card(self.pop_card()); | Represents a hand of playing cards. | 62598fcd71ff763f4b5e7b74 |
class StringReader(TextReader,IDisposable): <NEW_LINE> <INDENT> def Close(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Dispose(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def MemberwiseClone(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Peek(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Read(self,buffer=None,index=None,count=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReadAsync(self,buffer,index,count): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReadBlockAsync(self,buffer,index,count): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReadLine(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReadLineAsync(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReadToEnd(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReadToEndAsync(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __enter__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(self,s): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self,*args): <NEW_LINE> <INDENT> pass | Implements a System.IO.TextReader that reads from a string.
StringReader(s: str) | 62598fcd283ffb24f3cf3c78 |
class StopWorkerOperator(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "bitwrk.stopworker" <NEW_LINE> bl_label = "Stop worker" <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return worker.can_stop_worker() <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> worker.stop_worker() <NEW_LINE> return {'FINISHED'} | Stop rendering on this computer | 62598fcd4527f215b58ea2c2 |
class Element: <NEW_LINE> <INDENT> def __init__(self, columns, background = None, foreground = None): <NEW_LINE> <INDENT> self.content = columns <NEW_LINE> self.background = background <NEW_LINE> self.foreground = foreground <NEW_LINE> <DEDENT> def getColumn(self, col): <NEW_LINE> <INDENT> return self.content[col] <NEW_LINE> <DEDENT> def getColumnCount(self): <NEW_LINE> <INDENT> return len(self.content) <NEW_LINE> <DEDENT> def getAttributes(self, selected): <NEW_LINE> <INDENT> attr = theme.normal <NEW_LINE> if self.background or self.foreground: <NEW_LINE> <INDENT> attr = theme.getPair(self.foreground, self.background) <NEW_LINE> <DEDENT> if selected: <NEW_LINE> <INDENT> attr = theme.selected <NEW_LINE> <DEDENT> return attr <NEW_LINE> <DEDENT> def applyAttributes(self, win, selected): <NEW_LINE> <INDENT> win.attron(self.getAttributes(selected)) <NEW_LINE> <DEDENT> def resetAttributes(self, win, selected): <NEW_LINE> <INDENT> win.attroff(self.getAttributes(selected)) | A single element in a list | 62598fcdcc40096d6161a3d1 |
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA) <NEW_LINE> class Add(base.Command): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Add, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> flags.AddKeyFlags(parser, 'add to') <NEW_LINE> flags.AddTtlFlag(parser) <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> key = flags.GetKeyFromArgs(args) <NEW_LINE> oslogin_client = client.OsloginClient(self.ReleaseTrack()) <NEW_LINE> user_email = properties.VALUES.core.account.Get() <NEW_LINE> expiry = oslogin_utils.ConvertTtlArgToExpiry(args.ttl) <NEW_LINE> return oslogin_client.ImportSshPublicKey(user_email, key, expiration_time=expiry) | SSH into a virtual machine instance. | 62598fcd50812a4eaa620dde |
class BulkCountryUpdateList(ListResource): <NEW_LINE> <INDENT> def __init__(self, version): <NEW_LINE> <INDENT> super(BulkCountryUpdateList, self).__init__(version) <NEW_LINE> self._solution = {} <NEW_LINE> self._uri = '/VoicePermissions/BulkCountryUpdates'.format(**self._solution) <NEW_LINE> <DEDENT> def create(self, update_request): <NEW_LINE> <INDENT> data = values.of({'UpdateRequest': update_request, }) <NEW_LINE> payload = self._version.create( 'POST', self._uri, data=data, ) <NEW_LINE> return BulkCountryUpdateInstance(self._version, payload, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Preview.Permissions.BulkCountryUpdateList>' | PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. | 62598fcdad47b63b2c5a7c4f |
class PiCameraWarning(Warning): <NEW_LINE> <INDENT> pass | Base class for PiCamera warnings. | 62598fcd091ae3566870501f |
class PlanConstructor(Type): <NEW_LINE> <INDENT> pass | An abstract base class for plan constructors. | 62598fcd7b180e01f3e4924a |
class SearchTree(): <NEW_LINE> <INDENT> def __init__(self, root): <NEW_LINE> <INDENT> self.root = root <NEW_LINE> self.limit = 1 <NEW_LINE> <DEDENT> def expand(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def expand_nodes(self, nodes): <NEW_LINE> <INDENT> for i in nodes: <NEW_LINE> <INDENT> i.child = i.next_states() <NEW_LINE> <DEDENT> <DEDENT> def search(self): <NEW_LINE> <INDENT> raise NotImplementedError | Search Tree Data type | 62598fcdec188e330fdf8c8b |
class MappingUsersRulesRules(object): <NEW_LINE> <INDENT> swagger_types = { 'parameters': 'MappingUsersRulesRulesParameters', 'rules': 'list[MappingUsersRulesRule]' } <NEW_LINE> attribute_map = { 'parameters': 'parameters', 'rules': 'rules' } <NEW_LINE> def __init__(self, parameters=None, rules=None): <NEW_LINE> <INDENT> self._parameters = None <NEW_LINE> self._rules = None <NEW_LINE> self.discriminator = None <NEW_LINE> if parameters is not None: <NEW_LINE> <INDENT> self.parameters = parameters <NEW_LINE> <DEDENT> if rules is not None: <NEW_LINE> <INDENT> self.rules = rules <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def parameters(self): <NEW_LINE> <INDENT> return self._parameters <NEW_LINE> <DEDENT> @parameters.setter <NEW_LINE> def parameters(self, parameters): <NEW_LINE> <INDENT> self._parameters = parameters <NEW_LINE> <DEDENT> @property <NEW_LINE> def rules(self): <NEW_LINE> <INDENT> return self._rules <NEW_LINE> <DEDENT> @rules.setter <NEW_LINE> def rules(self, rules): <NEW_LINE> <INDENT> self._rules = rules <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, MappingUsersRulesRules): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fcdcc40096d6161a3d2 |
class Crawler: <NEW_LINE> <INDENT> def __init__(self, url_pattern, page_number, css_alt=None): <NEW_LINE> <INDENT> self.url_pattern = url_pattern <NEW_LINE> self.page_number = page_number <NEW_LINE> self.image_urls = [] <NEW_LINE> self.css_alt = css_alt <NEW_LINE> self.local_path = path.join(path.dirname(path.realpath(__file__))) <NEW_LINE> self.drop_folder = path.join(self.local_path, self.url_pattern.strip().split('/')[-3]) <NEW_LINE> <DEDENT> def get_images_url_list(self): <NEW_LINE> <INDENT> for num, image_url in enumerate(self.image_urls): <NEW_LINE> <INDENT> print("Number: {}\t Url: {}\n".format(num, image_url)) <NEW_LINE> <DEDENT> <DEDENT> def images_urls(self, url_): <NEW_LINE> <INDENT> r = requests.get(url_) <NEW_LINE> soup = BeautifulSoup(r.content.decode(), "html.parser") <NEW_LINE> if self.css_alt: <NEW_LINE> <INDENT> allfind = ("img", {"alt": self.css_alt}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> allfind = ("img") <NEW_LINE> <DEDENT> for img in soup.findAll(allfind): <NEW_LINE> <INDENT> self.image_urls.append(img.get('src')) <NEW_LINE> <DEDENT> <DEDENT> def images(self, url_, drop_name): <NEW_LINE> <INDENT> if not path.isdir(self.drop_folder): <NEW_LINE> <INDENT> makedirs(self.drop_folder, mode=0o777, exist_ok=True) <NEW_LINE> <DEDENT> drop_path = path.join(self.drop_folder, drop_name) <NEW_LINE> try: <NEW_LINE> <INDENT> wget.download(url_.strip(), drop_path) <NEW_LINE> <DEDENT> except (ValueError, urllib.error.HTTPError) as e: <NEW_LINE> <INDENT> print("Can't get url {} on page {} because errors {}".format(url_, self.page_number, e)) <NEW_LINE> pass <NEW_LINE> <DEDENT> <DEDENT> def main(self): <NEW_LINE> <INDENT> page_url = self.url_pattern.format(num=self.page_number) <NEW_LINE> self.images_urls(page_url) <NEW_LINE> self.get_images_url_list() <NEW_LINE> if int(self.page_number) < 10: <NEW_LINE> <INDENT> self.page_number = '0{}'.format(self.page_number) <NEW_LINE> <DEDENT> for num, image_url in enumerate(self.image_urls): <NEW_LINE> <INDENT> drop_name = '{}.{}.jpg'.format(self.page_number, num) <NEW_LINE> self.images(image_url, drop_name) | Class for crawl by page ulr-like 'http(s)://page_path/page_name_{number}/ and download pictures | 62598fcdf9cc0f698b1c54cf |
class SkipError(MongoDBQueriesManagerBaseError): <NEW_LINE> <INDENT> pass | Raised when skip is negative / bad value. | 62598fcd3d592f4c4edbb2ab |
class MapRecord(object): <NEW_LINE> <INDENT> def __init__(self, mapper, source, parent=None): <NEW_LINE> <INDENT> self._source = source <NEW_LINE> self._mapper = mapper <NEW_LINE> self._parent = parent <NEW_LINE> self._forced_values = {} <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> return self._source <NEW_LINE> <DEDENT> @property <NEW_LINE> def parent(self): <NEW_LINE> <INDENT> return self._parent <NEW_LINE> <DEDENT> def values(self, for_create=None, fields=None, **kwargs): <NEW_LINE> <INDENT> options = MapOptions(for_create=for_create, fields=fields, **kwargs) <NEW_LINE> values = self._mapper._apply(self, options=options) <NEW_LINE> values.update(self._forced_values) <NEW_LINE> return values <NEW_LINE> <DEDENT> def update(self, *args, **kwargs): <NEW_LINE> <INDENT> self._forced_values.update(*args, **kwargs) | A record prepared to be converted using a :py:class:`Mapper`.
MapRecord instances are prepared by :py:meth:`Mapper.map_record`.
Usage::
>>> map_record = mapper.map_record(record)
>>> output_values = map_record.values()
See :py:meth:`values` for more information on the available arguments. | 62598fcdfbf16365ca7944b2 |
class CmdSetParamString(UndoableCommand): <NEW_LINE> <INDENT> def __init__(self, param, newValue): <NEW_LINE> <INDENT> self._param = param <NEW_LINE> self._oldValue = param.getOldValue() <NEW_LINE> self._newValue = newValue <NEW_LINE> <DEDENT> def undoCmd(self): <NEW_LINE> <INDENT> self._param.getTuttleParam().setValue(self._oldValue) <NEW_LINE> self._param.setOldValue(self._oldValue) <NEW_LINE> self._param.paramChanged() <NEW_LINE> <DEDENT> def redoCmd(self): <NEW_LINE> <INDENT> self.doCmd() <NEW_LINE> <DEDENT> def doCmd(self): <NEW_LINE> <INDENT> self._param.getTuttleParam().setValue(self._newValue) <NEW_LINE> self._param.setOldValue(self._newValue) <NEW_LINE> self._param.paramChanged() | Command that update the value of a paramString.
Attributes :
- _param : the target buttle param which will be changed by the update.
- _oldValue : the old value of the target param, which will be used for reset the target in case of undo command.
- _newValue : the value which will be mofidied. | 62598fcd4c3428357761a6b4 |
@register_strategy('HR_SYMM') <NEW_LINE> class HashroutingSymmetric(Hashrouting): <NEW_LINE> <INDENT> @inheritdoc(Strategy) <NEW_LINE> def __init__(self, view, controller, params=None): <NEW_LINE> <INDENT> super(HashroutingSymmetric, self).__init__(view, controller) <NEW_LINE> <DEDENT> @inheritdoc(Strategy) <NEW_LINE> def process_event(self, time, receiver, content, log): <NEW_LINE> <INDENT> source = self.view.content_source(content) <NEW_LINE> cache = self.authoritative_cache(content) <NEW_LINE> self.controller.start_session(time, receiver, content, log) <NEW_LINE> self.controller.forward_request_path(receiver, cache) <NEW_LINE> if self.controller.get_content(cache): <NEW_LINE> <INDENT> self.controller.forward_content_path(cache, receiver) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.controller.forward_request_path(cache, source) <NEW_LINE> if not self.controller.get_content(source): <NEW_LINE> <INDENT> raise RuntimeError('The content is not found the expected source') <NEW_LINE> <DEDENT> self.controller.forward_content_path(source, cache) <NEW_LINE> self.controller.put_content(cache) <NEW_LINE> self.controller.forward_content_path(cache, receiver) <NEW_LINE> <DEDENT> self.controller.end_session() | Hash-routing with symmetric routing (HR SYMM)
| 62598fcd283ffb24f3cf3c7c |
class InterstitialTransformation(AbstractTransformation): <NEW_LINE> <INDENT> def __init__(self, interstitial_specie, supercell_dim, valences=None, radii=None): <NEW_LINE> <INDENT> self.supercell_dim = supercell_dim <NEW_LINE> self.valences = valences or {} <NEW_LINE> self.radii = radii or {} <NEW_LINE> self.interstitial_specie = interstitial_specie <NEW_LINE> <DEDENT> def apply_transformation(self, structure, return_ranked_list=False): <NEW_LINE> <INDENT> if not return_ranked_list: <NEW_LINE> <INDENT> raise ValueError("InterstitialTransformation has no single best " "structure output. Must use return_ranked_list.") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> num_to_return = int(return_ranked_list) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> num_to_return = 1 <NEW_LINE> <DEDENT> if self.radii: <NEW_LINE> <INDENT> inter = Interstitial(structure, self.valences, self.radii) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = structure.copy() <NEW_LINE> valrad_eval = ValenceIonicRadiusEvaluator(s) <NEW_LINE> s = valrad_eval.structure <NEW_LINE> val = valrad_eval.valences <NEW_LINE> rad = valrad_eval.radii <NEW_LINE> inter = Interstitial(s,val,rad,oxi_state=True) <NEW_LINE> <DEDENT> scs = inter.make_supercells_with_defects( self.supercell_dim, self.interstitial_specie) <NEW_LINE> structures = [] <NEW_LINE> num_to_return = min(num_to_return,len(scs)-1) <NEW_LINE> for sc in scs[1:num_to_return+1]: <NEW_LINE> <INDENT> structures.append({'structure':sc}) <NEW_LINE> <DEDENT> return structures <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> inp_args = ["Supercell scaling matrix = {}".format(self.supercell_dim), "Valences of ions = {}".format(self.valences), "Radii of ions = {}".format(self.radii), "interstitial specie = {}".format(self.interstitial_specie)] <NEW_LINE> return "Interstitial Transformation : " + ", ".join(inp_args) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> @property <NEW_LINE> def inverse(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_one_to_many(self): <NEW_LINE> <INDENT> return True | Generates interstitial structures from the input structure | 62598fcd7b180e01f3e4924b |
class TestFruitBasket: <NEW_LINE> <INDENT> def test_fruit_basket_main_000(self): <NEW_LINE> <INDENT> basket = FruitBasket(Path(__file__).parent.joinpath("data", "given.csv")) <NEW_LINE> print("Inventory Data:") <NEW_LINE> pprint(dict(basket.inventory)) <NEW_LINE> assert basket.total_fruittypes == 5 <NEW_LINE> assert basket.total_fruits == 22 <NEW_LINE> for k, v in {"apple": 5, "orange": 6}.items(): <NEW_LINE> <INDENT> assert basket.totals_byfruit[k] == v <NEW_LINE> <DEDENT> assert basket.oldestfruits == ({"pineapple", "orange"}, 6) <NEW_LINE> assert basket.totals_bychar["apple"] == Counter( {("red", "sweet"): 3, ("yellow", "sweet"): 1, ("green", "tart"): 1}, ) <NEW_LINE> <DEDENT> def test_report(self): <NEW_LINE> <INDENT> basket = FruitBasket(Path(__file__).parent.joinpath("data", "given.csv")) <NEW_LINE> result = report(basket) <NEW_LINE> print(result) <NEW_LINE> assert result.count("\n") == 28 | Tests for `fruit_basket` package. | 62598fcdbe7bc26dc9252055 |
class Vectorizer: <NEW_LINE> <INDENT> def __init__(self, mfi=100, ngram_type='word', ngram_size=1, vocabulary=None, vector_space='tf', lowercase=True, min_df=0.0, max_df=1.0, ignore=[]): <NEW_LINE> <INDENT> if vector_space not in ('tf', 'tf_scaled', 'tf_std', 'tf_idf', 'bin'): <NEW_LINE> <INDENT> raise ValueError('Unsupported vector space model: %s' %(vector_space)) <NEW_LINE> <DEDENT> self.params = {'max_features': mfi, 'max_df': max_df, 'min_df': min_df, 'preprocessor': None, 'ngram_range': (ngram_size, ngram_size), 'lowercase': False, 'decode_error': 'ignore', 'stop_words': ignore, } <NEW_LINE> if ngram_type == 'word': <NEW_LINE> <INDENT> self.params['tokenizer'] = identity <NEW_LINE> <DEDENT> elif ngram_type in ('char', 'char_wb'): <NEW_LINE> <INDENT> self.params['analyzer'] = ngram_type <NEW_LINE> <DEDENT> if vocabulary: <NEW_LINE> <INDENT> self.params['vocabulary'] = vocabulary <NEW_LINE> <DEDENT> if vector_space == 'tf': <NEW_LINE> <INDENT> self.params['use_idf'] = False <NEW_LINE> v = TfidfVectorizer(**self.params) <NEW_LINE> self.transformer = Pipeline([('s1', v)]) <NEW_LINE> <DEDENT> elif vector_space == 'tf_scaled': <NEW_LINE> <INDENT> self.params['use_idf'] = False <NEW_LINE> v = TfidfVectorizer(**self.params) <NEW_LINE> scaler = StandardScaler(with_mean=False) <NEW_LINE> self.transformer = Pipeline([('s1', v), ('s2', scaler)]) <NEW_LINE> <DEDENT> elif vector_space == 'tf_std': <NEW_LINE> <INDENT> self.params['use_idf'] = False <NEW_LINE> v = TfidfVectorizer(**self.params) <NEW_LINE> scaler = StdDevScaler() <NEW_LINE> self.transformer = Pipeline([('s1', v), ('s2', scaler)]) <NEW_LINE> <DEDENT> elif vector_space == 'tf_idf': <NEW_LINE> <INDENT> self.params['use_idf'] = True <NEW_LINE> v = TfidfVectorizer(**self.params) <NEW_LINE> self.transformer = Pipeline([('s1', v)]) <NEW_LINE> <DEDENT> elif vector_space == 'bin': <NEW_LINE> <INDENT> self.params['binary'] = True <NEW_LINE> v = CountVectorizer(**self.params) <NEW_LINE> self.transformer = Pipeline([('s1', v)]) <NEW_LINE> <DEDENT> <DEDENT> def fit(self, texts): <NEW_LINE> <INDENT> self.transformer.fit(texts) <NEW_LINE> self.feature_names = self.transformer.named_steps['s1'].get_feature_names() <NEW_LINE> <DEDENT> def transform(self, texts): <NEW_LINE> <INDENT> return self.transformer.transform(texts) <NEW_LINE> <DEDENT> def fit_transform(self, texts): <NEW_LINE> <INDENT> self.X = self.transformer.fit_transform(texts) <NEW_LINE> self.feature_names = self.transformer.named_steps['s1'].get_feature_names() <NEW_LINE> return self.X <NEW_LINE> <DEDENT> vectorize = fit_transform | Vectorize texts into a sparse, two-dimensional
matrix. | 62598fcdcc40096d6161a3d3 |
class CircuitoForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Circuito | Clase de donde se define la estructura del formulario `Circuito`. | 62598fcd3d592f4c4edbb2ad |
class powerKb(hw_driver.HwDriver): <NEW_LINE> <INDENT> def __init__(self, interface, params): <NEW_LINE> <INDENT> super(powerKb, self).__init__(interface, params.copy()) <NEW_LINE> self._handler = keyboard_handlers._BaseHandler(self._interface) <NEW_LINE> <DEDENT> def set(self, duration): <NEW_LINE> <INDENT> self._handler.power_key(press_secs=duration) | HwDriver wrapper around servod's power key functions. | 62598fcdad47b63b2c5a7c53 |
class LoginView(APIView): <NEW_LINE> <INDENT> authentication_classes = () <NEW_LINE> def post(self, request,): <NEW_LINE> <INDENT> username = request.data.get("username") <NEW_LINE> password = request.data.get("password") <NEW_LINE> user = authenticate(username=username, password=password) <NEW_LINE> if user: <NEW_LINE> <INDENT> Token.objects.get_or_create(user=user) <NEW_LINE> return Response({ "token": user.auth_token.key }) <NEW_LINE> <DEDENT> return Response({ "message": "We cant authenticate u {}".format(username) }) | Login User | 62598fcdfbf16365ca7944b4 |
class TransactionTokenGenerator: <NEW_LINE> <INDENT> key_salt = "sagepaypi.tokens.TransactionTokenGenerator" <NEW_LINE> secret = settings.SECRET_KEY <NEW_LINE> def make_token(self, transaction): <NEW_LINE> <INDENT> return self._make_token_with_timestamp(transaction, self._num_days(self._today())) <NEW_LINE> <DEDENT> def check_token(self, transaction, token): <NEW_LINE> <INDENT> if not (transaction and token): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ts_b36, _ = token.split("-") <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ts = base36_to_int(ts_b36) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not constant_time_compare(self._make_token_with_timestamp(transaction, ts), token): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if (self._num_days(self._today()) - ts) > get_setting('TOKEN_URL_DAYS_VALID'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def _make_token_with_timestamp(self, transaction, timestamp): <NEW_LINE> <INDENT> ts_b36 = int_to_base36(timestamp) <NEW_LINE> hash_string = salted_hmac( self.key_salt, self._make_hash_value(transaction, timestamp), secret=self.secret, ).hexdigest()[::2] <NEW_LINE> return "%s-%s" % (ts_b36, hash_string) <NEW_LINE> <DEDENT> def _make_hash_value(self, transaction, timestamp): <NEW_LINE> <INDENT> transaction_timestamp = transaction.updated_at.replace(microsecond=0, tzinfo=None) <NEW_LINE> return str(transaction.pk) + str(transaction_timestamp) + str(timestamp) <NEW_LINE> <DEDENT> def _num_days(self, dt): <NEW_LINE> <INDENT> return (dt - date(2001, 1, 1)).days <NEW_LINE> <DEDENT> def _today(self): <NEW_LINE> <INDENT> return date.today() | Strategy object used to generate and check tokens for the transaction mechanism. | 62598fcd3617ad0b5ee06541 |
class Logger(object): <NEW_LINE> <INDENT> def __init__(self, log_path, mode='w'): <NEW_LINE> <INDENT> if mode == 'a': <NEW_LINE> <INDENT> self._log_fout = open(log_path, 'a') <NEW_LINE> <DEDENT> elif mode == 'w': <NEW_LINE> <INDENT> self._log_fout = open(log_path, 'w') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid mode') <NEW_LINE> <DEDENT> <DEDENT> def write(self, out_str): <NEW_LINE> <INDENT> self._log_fout.write(out_str+'\n') <NEW_LINE> self._log_fout.flush() <NEW_LINE> print(out_str) <NEW_LINE> sys.stdout.flush() | logger that can print on terminal and save log to file simultaneously | 62598fcd7c178a314d78d898 |
class ProposalGenerator: <NEW_LINE> <INDENT> def __init__(self, nms_threshold=0.7, num_pre_nms_train=12000, num_post_nms_train=2000, num_pre_nms_val=6000, num_post_nms_val=300, min_size=0): <NEW_LINE> <INDENT> super(ProposalGenerator, self).__init__() <NEW_LINE> self.nms_threshold = nms_threshold <NEW_LINE> self.num_pre_nms_train = num_pre_nms_train <NEW_LINE> self.num_post_nms_train = num_post_nms_train <NEW_LINE> self.num_pre_nms_val = num_pre_nms_val <NEW_LINE> self.num_post_nms_val = num_post_nms_val <NEW_LINE> self.min_size = min_size <NEW_LINE> <DEDENT> def __call__(self, boxes, scores, training): <NEW_LINE> <INDENT> if training: <NEW_LINE> <INDENT> num_pre_nms = self.num_pre_nms_train <NEW_LINE> num_post_nms = self.num_post_nms_train <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> num_pre_nms = self.num_pre_nms_val <NEW_LINE> num_post_nms = self.num_post_nms_val <NEW_LINE> <DEDENT> proposals = [] <NEW_LINE> for bbx_i, obj_i in zip(boxes, scores): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.min_size > 0: <NEW_LINE> <INDENT> bbx_size = bbx_i[:, 2:] - bbx_i[:, :2] <NEW_LINE> valid = (bbx_size[:, 0] >= self.min_size) & (bbx_size[:, 1] >= self.min_size) <NEW_LINE> if valid.any().item(): <NEW_LINE> <INDENT> bbx_i, obj_i = bbx_i[valid], obj_i[valid] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Empty <NEW_LINE> <DEDENT> <DEDENT> obj_i, idx = obj_i.topk(min(obj_i.size(0), num_pre_nms)) <NEW_LINE> bbx_i = bbx_i[idx] <NEW_LINE> idx = nms(bbx_i, obj_i, self.nms_threshold, num_post_nms) <NEW_LINE> if idx.numel() == 0: <NEW_LINE> <INDENT> raise Empty <NEW_LINE> <DEDENT> bbx_i = bbx_i[idx] <NEW_LINE> proposals.append(bbx_i) <NEW_LINE> <DEDENT> except Empty: <NEW_LINE> <INDENT> proposals.append(None) <NEW_LINE> <DEDENT> <DEDENT> return PackedSequence(proposals) | Perform NMS-based selection of proposals
Parameters
----------
nms_threshold : float
Intersection over union threshold for the NMS
num_pre_nms_train : int
Number of top-scoring proposals to feed to NMS, training mode
num_post_nms_train : int
Number of top-scoring proposal to keep after NMS, training mode
num_pre_nms_val : int
Number of top-scoring proposals to feed to NMS, validation mode
num_post_nms_val : int
Number of top-scoring proposal to keep after NMS, validation mode
min_size : int
Minimum size for proposals, discard anything with a side smaller than this | 62598fcd60cbc95b06364736 |
class TestLivePhysDomain(TestLiveAPIC): <NEW_LINE> <INDENT> def create_unique_live_phys_domain(self): <NEW_LINE> <INDENT> session = self.login_to_apic() <NEW_LINE> phys_domains = PhysDomain.get(session) <NEW_LINE> non_existing_phys_domain = phys_domains[0] <NEW_LINE> while non_existing_phys_domain in phys_domains: <NEW_LINE> <INDENT> non_existing_phys_domain = PhysDomain(random_size_string(), None) <NEW_LINE> <DEDENT> return non_existing_phys_domain <NEW_LINE> <DEDENT> def get_all_phys_domains(self): <NEW_LINE> <INDENT> session = self.login_to_apic() <NEW_LINE> phys_domains = PhysDomain.get(session) <NEW_LINE> self.assertTrue(len(phys_domains) > 0) <NEW_LINE> return phys_domains <NEW_LINE> <DEDENT> def get_all_phys_domain_names(self): <NEW_LINE> <INDENT> phys_domains = self.get_all_phys_domains() <NEW_LINE> names = [] <NEW_LINE> for phys_domain in phys_domains: <NEW_LINE> <INDENT> names.append(phys_domain.name) <NEW_LINE> <DEDENT> return names <NEW_LINE> <DEDENT> def test_get_by_name(self): <NEW_LINE> <INDENT> session = self.login_to_apic() <NEW_LINE> new_phys_domain = PhysDomain('phys_domain_toolkit_test', None) <NEW_LINE> new_phys_domain.push_to_apic(session) <NEW_LINE> self.assertTrue(new_phys_domain.push_to_apic(session).ok) <NEW_LINE> phys_domain_by_name = PhysDomain.get_by_name(session, 'phys_domain_toolkit_test') <NEW_LINE> self.assertEqual(phys_domain_by_name, new_phys_domain) <NEW_LINE> new_phys_domain.mark_as_deleted() <NEW_LINE> new_phys_domain.push_to_apic(session) <NEW_LINE> self.assertTrue(new_phys_domain.push_to_apic(session).ok) <NEW_LINE> phys_domain_by_name = PhysDomain.get_by_name(session, 'phys_domain_toolkit_test') <NEW_LINE> self.assertIsNone(phys_domain_by_name) <NEW_LINE> names = self.get_all_phys_domain_names() <NEW_LINE> self.assertTrue(new_phys_domain.name not in names) | Class to test live phys domain | 62598fce283ffb24f3cf3c7f |
class CustomizableProperty(property): <NEW_LINE> <INDENT> def __init__(self, field, *, description): <NEW_LINE> <INDENT> self.field = field <NEW_LINE> self.description = description <NEW_LINE> def uncustomized(instance): <NEW_LINE> <INDENT> raise UncustomizedInstance(instance=instance, field=field) <NEW_LINE> <DEDENT> super().__init__(uncustomized) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<%s %s>" % (self.__class__.__name__, self.field) | Declares a class variable to require customization. See help on getattr_customized for details. | 62598fcecc40096d6161a3d4 |
class ValueSortedDict(SortedDict): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> args = list(args) <NEW_LINE> if args and callable(args[0]): <NEW_LINE> <INDENT> func = self._func = args[0] <NEW_LINE> def key_func(key): <NEW_LINE> <INDENT> return func(self[key]) <NEW_LINE> <DEDENT> args[0] = key_func <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._func = None <NEW_LINE> def key_func(key): <NEW_LINE> <INDENT> return self[key] <NEW_LINE> <DEDENT> if args and args[0] is None: <NEW_LINE> <INDENT> args[0] = key_func <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args.insert(0, key_func) <NEW_LINE> <DEDENT> <DEDENT> super(ValueSortedDict, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> if key not in self: <NEW_LINE> <INDENT> raise KeyError(key) <NEW_LINE> <DEDENT> self._list_remove(key) <NEW_LINE> self._delitem(key) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> self._list_remove(key) <NEW_LINE> self._delitem(key) <NEW_LINE> <DEDENT> self._setitem(key, value) <NEW_LINE> self._list_add(key) <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return self.__class__(self._func, self._load, self.iteritems()) <NEW_LINE> <DEDENT> __copy__ = copy <NEW_LINE> def __reduce__(self): <NEW_LINE> <INDENT> items = [(key, self[key]) for key in self._list] <NEW_LINE> args = (self._func, self._load, items) <NEW_LINE> return (self.__class__, args) <NEW_LINE> <DEDENT> @recursive_repr <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> temp = '{0}({1}, {2}, {{{3}}})' <NEW_LINE> items = ', '.join('{0}: {1}'.format(repr(key), repr(self[key])) for key in self._list) <NEW_LINE> return temp.format( self.__class__.__name__, repr(self._func), repr(self._load), items ) | Sorted dictionary that maintains (key, value) item pairs sorted by value.
- ``ValueSortedDict()`` -> new empty dictionary.
- ``ValueSortedDict(mapping)`` -> new dictionary initialized from a mapping
object's (key, value) pairs.
- ``ValueSortedDict(iterable)`` -> new dictionary initialized as if via::
d = ValueSortedDict()
for k, v in iterable:
d[k] = v
- ``ValueSortedDict(**kwargs)`` -> new dictionary initialized with the
name=value pairs in the keyword argument list. For example::
ValueSortedDict(one=1, two=2)
An optional key function callable may be specified as the first
argument. When so, the callable will be applied to the value of each item
pair to determine the comparable for sort order as with Python's builtin
``sorted`` function. | 62598fce50812a4eaa620de1 |
class InputCategorizer: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ignore_words = [ "JARVIS" ] <NEW_LINE> <DEDENT> def categorize_input(self, user_input): <NEW_LINE> <INDENT> category = "" <NEW_LINE> normalized_user_input = self.normalize_input(user_input) <NEW_LINE> pos_sentence = nltk.pos_tag(nltk.word_tokenize(str(normalized_user_input))) <NEW_LINE> if "VB" in pos_sentence[0][1]: <NEW_LINE> <INDENT> category = "command" <NEW_LINE> <DEDENT> elif "?" in user_input: <NEW_LINE> <INDENT> category = "question" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> category = "chat" <NEW_LINE> <DEDENT> return category <NEW_LINE> <DEDENT> def normalize_input(self, text): <NEW_LINE> <INDENT> for word_to_ignore in self.ignore_words: <NEW_LINE> <INDENT> for word_index in range(0, len(text.split(' '))): <NEW_LINE> <INDENT> if word_to_ignore in text.split(' ')[word_index]: <NEW_LINE> <INDENT> text = ' '.join(text.split(' ')[: word_index]) + ' '.join(text.split(' ')[word_index + 1 :]) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return text | Categorizes the user input to determine whether the user is:
- Asking a question
- Giving a command
- Or just chatting | 62598fce377c676e912f6f75 |
class PygaarstRasterError(Exception): <NEW_LINE> <INDENT> pass | Custom exception for errors during raster processing in Pygaarst | 62598fce3d592f4c4edbb2af |
class EditionPatchRequest(BaseModel): <NEW_LINE> <INDENT> slug: Optional[str] = None <NEW_LINE> title: Optional[str] = None <NEW_LINE> pending_rebuild: Optional[bool] = None <NEW_LINE> tracked_ref: Optional[str] = None <NEW_LINE> mode: Optional[str] = None <NEW_LINE> build_url: Optional[HttpUrl] = None <NEW_LINE> @validator("slug") <NEW_LINE> def check_slug(cls, v: Optional[str]) -> Optional[str]: <NEW_LINE> <INDENT> if v is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> validate_path_slug(v) <NEW_LINE> <DEDENT> except ValidationError: <NEW_LINE> <INDENT> raise ValueError(f"Slug {v!r} is incorrectly formatted.") <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> <DEDENT> @validator("mode") <NEW_LINE> def check_mode(cls, v: Optional[str]) -> Optional[str]: <NEW_LINE> <INDENT> if v is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> modes = EditionTrackingModes() <NEW_LINE> if v not in modes: <NEW_LINE> <INDENT> raise ValueError(f"Tracking mode {v!r} is not known.") <NEW_LINE> <DEDENT> return v | The model for a PATCH /editions/:id request. | 62598fce091ae35668705025 |
class MetadataReader(object): <NEW_LINE> <INDENT> def __init__(self, globstring, cache=None): <NEW_LINE> <INDENT> super(MetadataReader, self).__init__() <NEW_LINE> self.globstring = globstring <NEW_LINE> if cache: <NEW_LINE> <INDENT> from cache import Cache <NEW_LINE> self.cache = Cache(cache) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cache = None <NEW_LINE> <DEDENT> <DEDENT> def read(self): <NEW_LINE> <INDENT> files = glob.glob(self.globstring) <NEW_LINE> if self.cache: <NEW_LINE> <INDENT> self.cache.update(files, metadata_read) <NEW_LINE> metadatas = self.cache.get_metadatas() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> metadatas = [] <NEW_LINE> for fname in files: <NEW_LINE> <INDENT> timestamp, meta, mtime = metadata_read(fname) <NEW_LINE> d = dict(file=os.path.basename(fname), meta=meta, timestamp=unicode(timestamp)) <NEW_LINE> metadatas.append(d) <NEW_LINE> <DEDENT> <DEDENT> return metadatas | Get metadata from images | 62598fce3617ad0b5ee06543 |
class Search(Action): <NEW_LINE> <INDENT> pass | 'Search' Action on a collection of resource | 62598fce7cff6e4e811b5e22 |
class MockRunner(Runner): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> func = import_name(self.task.app.importable) <NEW_LINE> job = WrapperJob(None, self.task.task_id, self.task.arguments, self.task.resources, None) <NEW_LINE> cwd = os.path.abspath('.') <NEW_LINE> task_dir = self.task.task_id <NEW_LINE> os.mkdir(task_dir) <NEW_LINE> os.chdir(task_dir) <NEW_LINE> try: <NEW_LINE> <INDENT> return func(job) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.chdir(cwd) | Runs the app/mock/python jobs. A directory is created for each job. | 62598fce7c178a314d78d89a |
class PowderSample(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=80) <NEW_LINE> chemistry = models.CharField(max_length=80) <NEW_LINE> locality = models.CharField(max_length=120) <NEW_LINE> source = models.CharField(max_length=120) <NEW_LINE> description = models.CharField(max_length=120) <NEW_LINE> user = models.ForeignKey(User, on_delete=models.CASCADE, default=lambda: User.objects.get(username='elvis')) <NEW_LINE> _powder_diffrac = models.TextField(db_column='data', blank=True) <NEW_LINE> @property <NEW_LINE> def powder_diffrac(self): <NEW_LINE> <INDENT> return pickle.loads(base64.decodestring( bytes(self._powder_diffrac, 'utf8'))) <NEW_LINE> <DEDENT> @powder_diffrac.setter <NEW_LINE> def powder_diffrac(self, data): <NEW_LINE> <INDENT> self._powder_diffrac = base64.encodestring(pickle.dumps(data)) | This model represents a powder crystal sample | 62598fce851cf427c66b86ad |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.