code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class RandomZoomTransformer(BaseSequenceTransformer): <NEW_LINE> <INDENT> def __init__(self, zoom_range): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.zoom_range = zoom_range <NEW_LINE> self.transformation = random_zoom <NEW_LINE> <DEDENT> def get_args(self): <NEW_LINE> <INDENT> if self.zoom_range[0] == 1 and self.zoom_range[1] == 1: <NEW_LINE> <INDENT> dt = [(1, 1) for _ in range(self.batch_size)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dt = [np.random.uniform(self.zoom_range[0], self.zoom_range[1], 2) for _ in range(self.batch_size)] <NEW_LINE> <DEDENT> return [{'z_known': d, 'zoom_range': self.zoom_range} for d in dt] | Transformer to do random zoom.
# Arguments
zoom_range: Tuple of floats; zoom range for width and height. | 62598fa6cc0a2c111447aef5 |
class User(): <NEW_LINE> <INDENT> __password = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.id = str(uuid.uuid4()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def password(self): <NEW_LINE> <INDENT> return self.__password <NEW_LINE> <DEDENT> @password.setter <NEW_LINE> def password(self, pwd): <NEW_LINE> <INDENT> if pwd is None or type(pwd) is not str: <NEW_LINE> <INDENT> self.__password = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__password = hashlib.md5(pwd.encode()).hexdigest().lower() <NEW_LINE> <DEDENT> <DEDENT> def is_valid_password(self, pwd): <NEW_LINE> <INDENT> if pwd is None or type(pwd) is not str: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.__password is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return hashlib.md5(pwd.encode()).hexdigest().upper() == self.__password | User class:
- id: public string unique (uuid)
- password: private string hash in MD5 | 62598fa68a43f66fc4bf2062 |
class ApiError(Model): <NEW_LINE> <INDENT> _attribute_map = { 'details': {'key': 'details', 'type': '[ApiErrorBase]'}, 'innererror': {'key': 'innererror', 'type': 'InnerError'}, 'code': {'key': 'code', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, } <NEW_LINE> def __init__(self, *, details=None, innererror=None, code: str=None, target: str=None, message: str=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(ApiError, self).__init__(**kwargs) <NEW_LINE> self.details = details <NEW_LINE> self.innererror = innererror <NEW_LINE> self.code = code <NEW_LINE> self.target = target <NEW_LINE> self.message = message | Api error.
:param details: The Api error details
:type details:
list[~azure.mgmt.compute.v2016_04_30_preview.models.ApiErrorBase]
:param innererror: The Api inner error
:type innererror:
~azure.mgmt.compute.v2016_04_30_preview.models.InnerError
:param code: The error code.
:type code: str
:param target: The target of the particular error.
:type target: str
:param message: The error message.
:type message: str | 62598fa63539df3088ecc19a |
class AdaptiveMetropolisLearnScale(AdaptiveMetropolis): <NEW_LINE> <INDENT> is_symmetric=True <NEW_LINE> adapt_scale = True <NEW_LINE> def __init__(self, distribution, mean_est=None, cov_est=None, sample_discard=500, sample_lag=20, accstar=0.234): <NEW_LINE> <INDENT> AdaptiveMetropolis.__init__(self, distribution, mean_est, cov_est, sample_discard, sample_lag, accstar) | Plain Adaptive Metropolis by Haario et al
adapt_scale=True adapts scaling to reach "optimal acceptance rate" | 62598fa623849d37ff850f9a |
class ComparisonTestFramework(BitcoinTestFramework): <NEW_LINE> <INDENT> def set_test_params(self): <NEW_LINE> <INDENT> self.num_nodes = 2 <NEW_LINE> self.setup_clean_chain = True <NEW_LINE> <DEDENT> def add_options(self, parser): <NEW_LINE> <INDENT> parser.add_option("--testbinary", dest="testbinary", default=os.getenv("BITCOIND", "donud"), help="donud binary to test") <NEW_LINE> parser.add_option("--refbinary", dest="refbinary", default=os.getenv("BITCOIND", "donud"), help="donud binary to use for reference nodes (if any)") <NEW_LINE> <DEDENT> def setup_network(self): <NEW_LINE> <INDENT> extra_args = [['-whitelist=127.0.0.1']] * self.num_nodes <NEW_LINE> if hasattr(self, "extra_args"): <NEW_LINE> <INDENT> extra_args = self.extra_args <NEW_LINE> <DEDENT> self.add_nodes(self.num_nodes, extra_args, binary=[self.options.testbinary] + [self.options.refbinary] * (self.num_nodes - 1)) <NEW_LINE> self.start_nodes() | Test framework for doing p2p comparison testing
Sets up some donud binaries:
- 1 binary: test binary
- 2 binaries: 1 test binary, 1 ref binary
- n>2 binaries: 1 test binary, n-1 ref binaries | 62598fa6dd821e528d6d8e1b |
class Rotate(object): <NEW_LINE> <INDENT> def __init__(self, angle): <NEW_LINE> <INDENT> self.angle = angle <NEW_LINE> <DEDENT> def __call__(self, img, bboxes): <NEW_LINE> <INDENT> angle = self.angle <NEW_LINE> w,h = img.shape[1], img.shape[0] <NEW_LINE> cx, cy = w//2, h//2 <NEW_LINE> corners = get_corners(bboxes) <NEW_LINE> corners = np.hstack((corners, bboxes[:,4:])) <NEW_LINE> img = rotate_im(img, angle) <NEW_LINE> corners[:,:8] = rotate_box(corners[:,:8], angle, cx, cy, h, w) <NEW_LINE> new_bbox = get_enclosing_box(corners) <NEW_LINE> scale_factor_x = img.shape[1] / w <NEW_LINE> scale_factor_y = img.shape[0] / h <NEW_LINE> img = cv2.resize(img, (w,h)) <NEW_LINE> new_bbox[:,:4] /= [scale_factor_x, scale_factor_y, scale_factor_x, scale_factor_y] <NEW_LINE> bboxes = new_bbox <NEW_LINE> bboxes = clip_box(bboxes, [0,0,w, h], 0.25) <NEW_LINE> return img, bboxes | Rotates an image
Bounding boxes which have an area of less than 25% in the remaining in the
transformed image is dropped. The resolution is maintained, and the remaining
area if any is filled by black color.
Parameters
----------
angle: float
The angle by which the image is to be rotated
Returns
-------
numpy.ndaaray
Rotated image in the numpy format of shape `HxWxC`
numpy.ndarray
Tranformed bounding box co-ordinates of the format `n x 4` where n is
number of bounding boxes and 4 represents `x1,y1,x2,y2` of the box
| 62598fa699cbb53fe6830dbb |
class DocFeaturizer(object): <NEW_LINE> <INDENT> def __init__(self, vocab_embedding): <NEW_LINE> <INDENT> self.ve = vocab_embedding <NEW_LINE> <DEDENT> def doc2embedding(self, doc): <NEW_LINE> <INDENT> return pd.DataFrame({'order': range(len(doc))}, index=doc ).join(self.ve, how='left').sort_values('order').drop('order', axis=1) <NEW_LINE> <DEDENT> def featurize_doc(self, doc): <NEW_LINE> <INDENT> emb = self.doc2embedding(doc) <NEW_LINE> N = emb.shape[1] <NEW_LINE> mean = emb.mean() <NEW_LINE> mean.index = ['wv_' + str(k) + '_mean' for k in range(N)] <NEW_LINE> qts = emb.quantile(q=[0.05, 0.95]) <NEW_LINE> pct5 = qts.iloc[0] <NEW_LINE> pct95 = qts.iloc[1] <NEW_LINE> pct5.index = ['wv_' + str(k) + '_pct_5' for k in range(N)] <NEW_LINE> pct95.index = ['wv_' + str(k) + '_pct_95' for k in range(N)] <NEW_LINE> sequential_euclidean_dist = np.mean((emb[:-1].values - emb[1:].values)**2, axis = 1) <NEW_LINE> sed = pd.Series({ 'seq_dist_mean': np.mean(sequential_euclidean_dist), 'seq_dist_pct_5': np.percentile(sequential_euclidean_dist, 5), 'seq_dist_pct_95': np.percentile(sequential_euclidean_dist, 95) }) <NEW_LINE> return pd.concat([pct5, pct95, mean, sed]) <NEW_LINE> <DEDENT> def featurize_corpus(self, doc_list): <NEW_LINE> <INDENT> n_docs = len(doc_list) <NEW_LINE> lpm = wwie.LoopProgressMonitor(n = n_docs) <NEW_LINE> def fd(doc): <NEW_LINE> <INDENT> lpm() <NEW_LINE> return self.featurize_doc(doc) <NEW_LINE> <DEDENT> df = pd.concat([fd(doc) for doc in doc_list], axis=1).transpose() <NEW_LINE> return df | Methods to derive numerical features for a tokenized document (i.e. a list of strings) | 62598fa6b7558d5895463515 |
class QuestionSuggestionAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ["__str__", "author_email", "created_at"] <NEW_LINE> ordering = ["created_at"] <NEW_LINE> actions = ["make_published"] <NEW_LINE> def get_queryset(self, request: HttpRequest) -> QuerySet: <NEW_LINE> <INDENT> qs = super().get_queryset(request) <NEW_LINE> return qs.filter(is_public=False) <NEW_LINE> <DEDENT> def make_published(self, request: HttpRequest, queryset: QuerySet) -> None: <NEW_LINE> <INDENT> updated = queryset.update(is_public=True) <NEW_LINE> self.message_user( request, ngettext( "%d question was successfully marked as published.", "%d questions were successfully marked as published.", updated, ) % updated, messages.SUCCESS, ) <NEW_LINE> <DEDENT> make_published.short_description = "Mark selected questions as published" | Admin model for question suggestion category. | 62598fa676e4537e8c3ef492 |
class CopyGenerator(nn.Module): <NEW_LINE> <INDENT> def __init__(self, output_size, input_size, pad_idx): <NEW_LINE> <INDENT> super(CopyGenerator, self).__init__() <NEW_LINE> self.linear = nn.Linear(input_size, output_size) <NEW_LINE> self.linear_copy = nn.Linear(input_size, 1) <NEW_LINE> self.softmax = nn.LogSoftmax(dim=-1) <NEW_LINE> self.pad_idx = pad_idx <NEW_LINE> <DEDENT> def forward(self, hidden, attn, src_map, use_gumbel_softmax=False): <NEW_LINE> <INDENT> batch_by_tlen, _ = hidden.size() <NEW_LINE> batch_by_tlen_, slen = attn.size() <NEW_LINE> batch, slen_, cvocab = src_map.size() <NEW_LINE> aeq(batch_by_tlen, batch_by_tlen_) <NEW_LINE> aeq(slen, slen_) <NEW_LINE> logits = self.linear(hidden) <NEW_LINE> logits[:, self.pad_idx] = -float('inf') <NEW_LINE> if use_gumbel_softmax: <NEW_LINE> <INDENT> prob = gumbel_softmax(logits, log_mode=False, dim=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prob = torch.softmax(logits, 1) <NEW_LINE> <DEDENT> p_copy = torch.sigmoid(self.linear_copy(hidden)) <NEW_LINE> out_prob = torch.mul(prob, 1 - p_copy) <NEW_LINE> mul_attn = torch.mul(attn, p_copy) <NEW_LINE> copy_prob = torch.bmm( mul_attn.view(batch, -1, slen), src_map ) <NEW_LINE> copy_prob = copy_prob.contiguous().view(-1, cvocab) <NEW_LINE> return torch.cat([out_prob, copy_prob], 1) | An implementation of pointer-generator networks
:cite:`DBLP:journals/corr/SeeLM17`.
These networks consider copying words
directly from the source sequence.
The copy generator is an extended version of the standard
generator that computes three values.
* :math:`p_{softmax}` the standard softmax over `tgt_dict`
* :math:`p(z)` the probability of copying a word from
the source
* :math:`p_{copy}` the probility of copying a particular word.
taken from the attention distribution directly.
The model returns a distribution over the extend dictionary,
computed as
:math:`p(w) = p(z=1) p_{copy}(w) + p(z=0) p_{softmax}(w)`
.. mermaid::
graph BT
A[input]
S[src_map]
B[softmax]
BB[switch]
C[attn]
D[copy]
O[output]
A --> B
A --> BB
S --> D
C --> D
D --> O
B --> O
BB --> O
Args:
input_size (int): size of input representation
output_size (int): size of output vocabulary
pad_idx (int) | 62598fa6bd1bec0571e15036 |
class DataBase(Base): <NEW_LINE> <INDENT> __abstract__ = True <NEW_LINE> @declared_attr <NEW_LINE> def __tablename__(cls): <NEW_LINE> <INDENT> return cls.__name__.lower() <NEW_LINE> <DEDENT> id = Column(Integer, primary_key=True) <NEW_LINE> def as_dictionary(self): <NEW_LINE> <INDENT> return { column.name : getattr(self, column.name) for column in self.__table__.columns } <NEW_LINE> <DEDENT> def as_serializable_dictionary(self): <NEW_LINE> <INDENT> s_dict = dict() <NEW_LINE> for column in self.__table__.columns: <NEW_LINE> <INDENT> value = getattr(self, column.name) <NEW_LINE> value = getattr(column.type, 'serialize', lambda x : x)(value) <NEW_LINE> s_dict[column.name] = value <NEW_LINE> <DEDENT> return s_dict <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_serializeable_dictionary(cls, s_dict): <NEW_LINE> <INDENT> columns = { column.name:column for column in cls.__table__.columns } <NEW_LINE> kwargs = dict() <NEW_LINE> for key in s_dict.keys(): <NEW_LINE> <INDENT> column = columns[key] <NEW_LINE> kwargs[key] = getattr(column.type, 'deserialize', lambda x : x)(s_dict[key]) <NEW_LINE> <DEDENT> return cls(**kwargs) | A mixin class for nebulous SQLAlchemy objects. | 62598fa67d847024c075c2ab |
class TwitterSearchRequest(Request): <NEW_LINE> <INDENT> def __init__(self, *args: Any, q: str, max_id: Optional[str] = None, **kwargs: Any) -> None: <NEW_LINE> <INDENT> self.q = q <NEW_LINE> self.max_id = max_id <NEW_LINE> super(TwitterSearchRequest, self).__init__('http://twitter.com', *args, dont_filter=True, **kwargs) | Request adapter for search requests | 62598fa6adb09d7d5dc0a471 |
class Average(VariableAccumulation): <NEW_LINE> <INDENT> def __init__(self, output_transform: Callable = lambda x: x, device: Optional[Union[str, torch.device]] = 'cpu'): <NEW_LINE> <INDENT> def _mean_op(a, x): <NEW_LINE> <INDENT> if isinstance(x, torch.Tensor) and x.ndim > 1: <NEW_LINE> <INDENT> x = x.sum(dim=0) <NEW_LINE> <DEDENT> return a + x <NEW_LINE> <DEDENT> super(Average, self).__init__(op=_mean_op, output_transform=output_transform, device=device) <NEW_LINE> <DEDENT> def compute(self) -> Union[Any, torch.Tensor, numbers.Number]: <NEW_LINE> <INDENT> if self.num_examples < 1: <NEW_LINE> <INDENT> raise NotComputableError( "{} must have at least one example before" " it can be computed.".format(self.__class__.__name__) ) <NEW_LINE> <DEDENT> return self.accumulator / self.num_examples | Helper class to compute arithmetic average of a single variable.
- ``update`` must receive output of the form `x`.
- `x` can be a number or `torch.Tensor`.
Note:
Number of samples is updated following the rule:
- `+1` if input is a number
- `+1` if input is a 1D `torch.Tensor`
- `+batch_size` if input is an ND `torch.Tensor`. Batch size is the first dimension (`shape[0]`).
For input `x` being an ND `torch.Tensor` with N > 1, the first dimension is seen as the number of samples and
is summed up and added to the accumulator: `accumulator += x.sum(dim=0)`
Examples:
.. code-block:: python
evaluator = ...
custom_var_mean = Average(output_transform=lambda output: output['custom_var'])
custom_var_mean.attach(evaluator, 'mean_custom_var')
state = evaluator.run(dataset)
# state.metrics['mean_custom_var'] -> average of output['custom_var']
Args:
output_transform (callable, optional): a callable that is used to transform the
:class:`~ignite.engine.engine.Engine`'s ``process_function``'s output into the
form expected by the metric. This can be useful if, for example, you have a multi-output model and
you want to compute the metric with respect to one of the outputs.
device (str of torch.device, optional): optional device specification for internal storage. | 62598fa6e5267d203ee6b7f2 |
class LookupError(bb.Union): <NEW_LINE> <INDENT> _catch_all = 'other' <NEW_LINE> not_found = None <NEW_LINE> not_file = None <NEW_LINE> not_folder = None <NEW_LINE> restricted_content = None <NEW_LINE> other = None <NEW_LINE> @classmethod <NEW_LINE> def malformed_path(cls, val): <NEW_LINE> <INDENT> return cls('malformed_path', val) <NEW_LINE> <DEDENT> def is_malformed_path(self): <NEW_LINE> <INDENT> return self._tag == 'malformed_path' <NEW_LINE> <DEDENT> def is_not_found(self): <NEW_LINE> <INDENT> return self._tag == 'not_found' <NEW_LINE> <DEDENT> def is_not_file(self): <NEW_LINE> <INDENT> return self._tag == 'not_file' <NEW_LINE> <DEDENT> def is_not_folder(self): <NEW_LINE> <INDENT> return self._tag == 'not_folder' <NEW_LINE> <DEDENT> def is_restricted_content(self): <NEW_LINE> <INDENT> return self._tag == 'restricted_content' <NEW_LINE> <DEDENT> def is_other(self): <NEW_LINE> <INDENT> return self._tag == 'other' <NEW_LINE> <DEDENT> def get_malformed_path(self): <NEW_LINE> <INDENT> if not self.is_malformed_path(): <NEW_LINE> <INDENT> raise AttributeError("tag 'malformed_path' not set") <NEW_LINE> <DEDENT> return self._value <NEW_LINE> <DEDENT> def _process_custom_annotations(self, annotation_type, processor): <NEW_LINE> <INDENT> super(LookupError, self)._process_custom_annotations(annotation_type, processor) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'LookupError(%r, %r)' % (self._tag, self._value) | This class acts as a tagged union. Only one of the ``is_*`` methods will
return true. To get the associated value of a tag (if one exists), use the
corresponding ``get_*`` method.
:ivar file_properties.LookupError.not_found: There is nothing at the given
path.
:ivar file_properties.LookupError.not_file: We were expecting a file, but
the given path refers to something that isn't a file.
:ivar file_properties.LookupError.not_folder: We were expecting a folder,
but the given path refers to something that isn't a folder.
:ivar file_properties.LookupError.restricted_content: The file cannot be
transferred because the content is restricted. For example, sometimes
there are legal restrictions due to copyright claims. | 62598fa6627d3e7fe0e06d93 |
class FileNotFoundInSuccessor(Exception): <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> self.msg = 'FILE WAS NOT FOUND IN SUCCESSOR' <NEW_LINE> super(self.__class__, self).__init__(self.msg) | To be raised if a file is no longer traceable for whatever reason. | 62598fa62c8b7c6e89bd36ac |
class NudgeAxis(object): <NEW_LINE> <INDENT> def __init__(self, origin, length, targets): <NEW_LINE> <INDENT> super(NudgeAxis, self).__init__() <NEW_LINE> self.origin = origin <NEW_LINE> self.length = length <NEW_LINE> self.targets = targets <NEW_LINE> <DEDENT> def serve(self, plotter, location): <NEW_LINE> <INDENT> distance = canvas.calculate_distance(location, self.origin) <NEW_LINE> if distance < 300: <NEW_LINE> <INDENT> index_axis = canvas.SimpleFunction(0) <NEW_LINE> index_axis.set_region(self.origin, 0, self.length, 600) <NEW_LINE> index_axis.place_nudges_on_target(self.targets) <NEW_LINE> index_axis.enable_pen_up() <NEW_LINE> index_axis.disable_guide() <NEW_LINE> index_axis.disable_boosts() <NEW_LINE> plotter.place(index_axis) <NEW_LINE> <DEDENT> <DEDENT> def check_if_inside(self, location): <NEW_LINE> <INDENT> x, y = location <NEW_LINE> low_x = self.origin[0] - 300 <NEW_LINE> high_x = self.origin[0] + self.length + 300 <NEW_LINE> if x > low_x and x < high_x: <NEW_LINE> <INDENT> if y > self.origin[1] - 300 and y < self.origin[1] + 300: <NEW_LINE> <INDENT> return True | Defines a nudge axis
| 62598fa6435de62698e9bcdb |
class Category(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255) <NEW_LINE> slug = models.SlugField(unique=True) <NEW_LINE> timestamp = models.DateTimeField(auto_now_add=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name | Category registration model | 62598fa663d6d428bbee2698 |
class EarlyStoppingFScore(Callback): <NEW_LINE> <INDENT> def __init__(self, val_data, dumpfn, baseline=0, patience=3, min_delta=0): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.val_data = val_data <NEW_LINE> self.dumpfn = str(dumpfn) <NEW_LINE> self.patience = patience <NEW_LINE> self.min_delta = min_delta <NEW_LINE> self.wait = 0 <NEW_LINE> self.best = baseline <NEW_LINE> <DEDENT> def on_epoch_end(self, epoch, logs=None): <NEW_LINE> <INDENT> logging.info('Epoch %d: evaluate validation set', epoch + 1) <NEW_LINE> current = self.evaluate() <NEW_LINE> if current - self.min_delta > self.best: <NEW_LINE> <INDENT> logging.info('Improved F1 -- saving weights to %s', self.dumpfn) <NEW_LINE> self.wait = 0 <NEW_LINE> self.best = current <NEW_LINE> self.model.save_weights(self.dumpfn) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.wait += 1 <NEW_LINE> if self.wait >= self.patience: <NEW_LINE> <INDENT> self.model.stop_training = True <NEW_LINE> if epoch > 0: <NEW_LINE> <INDENT> logging.info('Epoch %d: early stopping', epoch + 1) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def evaluate(self): <NEW_LINE> <INDENT> scores = _run_test(*self.val_data, self.model) <NEW_LINE> return scores[-1].fscore | Stop training when CR F-score has stopped improving.
Based on keras.callbacks.EarlyStopping. | 62598fa667a9b606de545eb2 |
class Tamano(models.Model): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Tamano, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> descripcion = models.CharField(max_length=100, unique=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.descripcion <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "Tamano" <NEW_LINE> verbose_name_plural = "Tamanos" <NEW_LINE> ordering = ['id'] | docstring for Tamano | 62598fa656ac1b37e63020d3 |
class Filter(Block): <NEW_LINE> <INDENT> def block_code(self): <NEW_LINE> <INDENT> inputs = self._get_all_input_values() <NEW_LINE> filter_result = self.user_function(**inputs) <NEW_LINE> if filter_result: <NEW_LINE> <INDENT> self.pass_data_through(inputs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.clear_outputs() | User function should return a Boolean.
If True, all input args will be passed unmodified as output args.
If False, all output args will have a value of None. | 62598fa616aa5153ce4003e9 |
class Subtract(StochasticParameter): <NEW_LINE> <INDENT> def __init__(self, other_param, val, elementwise=False): <NEW_LINE> <INDENT> super(Subtract, self).__init__() <NEW_LINE> self.other_param = handle_continuous_param(other_param, "other_param") <NEW_LINE> self.val = handle_continuous_param(val, "val") <NEW_LINE> self.elementwise = elementwise <NEW_LINE> <DEDENT> def _draw_samples(self, size, random_state): <NEW_LINE> <INDENT> seed = random_state.randint(0, 10**6, 1)[0] <NEW_LINE> samples = self.other_param.draw_samples( size, random_state=eu.new_random_state(seed)) <NEW_LINE> elementwise = self.elementwise and not isinstance(self.val, Deterministic) <NEW_LINE> if elementwise: <NEW_LINE> <INDENT> val_samples = self.val.draw_samples( size, random_state=eu.new_random_state(seed+1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val_samples = self.val.draw_sample( random_state=eu.new_random_state(seed+1)) <NEW_LINE> <DEDENT> if elementwise: <NEW_LINE> <INDENT> return np.subtract(samples, val_samples) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return samples - val_samples <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Subtract(%s, %s, %s)" % (str(self.other_param), str(self.val), self.elementwise) | Parameter to subtract from another parameter's results.
Parameters
----------
other_param : number or tuple of two number or list of number or StochasticParameter
Other parameter which's sampled values are to be
modified.
val : number or tuple of two number or list of number or StochasticParameter
Value to add to the other parameter's results. If this is a
StochasticParameter, either a single or multiple values will be
sampled and subtracted.
elementwise : bool, optional(default=False)
Controls the sampling behaviour when `val` is a StochasticParameter.
If set to False, a single value will be sampled from val and subtracted
from all values generated by `other_param`.
If set to True and `_draw_samples(size=S)` is called, `S` values will
be sampled from `val` and subtracted from the results of `other_param`.
Examples
--------
>>> param = Add(Uniform(0.0, 1.0), 1.0)
Converts a uniform range [0.0, 1.0) to [1.0, 2.0). | 62598fa607f4c71912baf32a |
class Mortgage(object): <NEW_LINE> <INDENT> def __init__(self, loan, annRate, months): <NEW_LINE> <INDENT> self.loan = loan <NEW_LINE> self.rate = annRate/12.0 <NEW_LINE> self.months = months <NEW_LINE> self.paid = [0.0] <NEW_LINE> self.owed = [loan] <NEW_LINE> self.payment = findPayment(loan, self.rate, months) <NEW_LINE> self.legend = None <NEW_LINE> <DEDENT> def makePayment(self): <NEW_LINE> <INDENT> self.paid.append(self.payment) <NEW_LINE> reduction = self.payment - self.owed[-1]*self.rate <NEW_LINE> self.owed.append(self.owed[-1]-reduction) <NEW_LINE> <DEDENT> def getTotalPaid(self): <NEW_LINE> <INDENT> return sum(self.paid) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.legend <NEW_LINE> <DEDENT> def plotPayments(self, style): <NEW_LINE> <INDENT> pylab.plot(self.paid[1:], style, label = self.legend) <NEW_LINE> <DEDENT> def plotBalance(self, style): <NEW_LINE> <INDENT> pylab.plot(self.owed, style, label = self.legend) <NEW_LINE> <DEDENT> def plotTotPd(self, style): <NEW_LINE> <INDENT> totPd = [self.paid[0]] <NEW_LINE> for i in range(1, len(self.paid)): <NEW_LINE> <INDENT> totPd.append(totPd[-1] + self.paid[i]) <NEW_LINE> <DEDENT> pylab.plot(totPd, style, label = self.legend) <NEW_LINE> <DEDENT> def plotNet(self, style): <NEW_LINE> <INDENT> totPd = [self.paid[0]] <NEW_LINE> for i in range(1, len(self.paid)): <NEW_LINE> <INDENT> totPd.append(totPd[-1] + self.paid[i]) <NEW_LINE> <DEDENT> equityAcquired = pylab.array([self.loan]*len(self.owed)) <NEW_LINE> equityAcquired = equityAcquired - pylab.array(self.owed) <NEW_LINE> net = pylab.array(totPd) - equityAcquired <NEW_LINE> pylab.plot(net, style, label = self.legend) | Abstract class for building different kinds of mortgates | 62598fa644b2445a339b68e2 |
class SSLClientTestsMixin(TLSMixin, ReactorBuilder, ConnectionTestsMixin): <NEW_LINE> <INDENT> def serverEndpoint(self, reactor): <NEW_LINE> <INDENT> return SSL4ServerEndpoint(reactor, 0, self.getServerContext()) <NEW_LINE> <DEDENT> def clientEndpoint(self, reactor, serverAddress): <NEW_LINE> <INDENT> return SSL4ClientEndpoint( reactor, '127.0.0.1', serverAddress.port, ClientContextFactory()) <NEW_LINE> <DEDENT> def test_disconnectAfterWriteAfterStartTLS(self): <NEW_LINE> <INDENT> class ShortProtocol(Protocol): <NEW_LINE> <INDENT> def connectionMade(self): <NEW_LINE> <INDENT> if not ITLSTransport.providedBy(self.transport): <NEW_LINE> <INDENT> finished = self.factory.finished <NEW_LINE> self.factory.finished = None <NEW_LINE> finished.errback(SkipTest("No ITLSTransport support")) <NEW_LINE> return <NEW_LINE> <DEDENT> self.transport.startTLS(self.factory.context) <NEW_LINE> self.transport.write("x") <NEW_LINE> <DEDENT> def dataReceived(self, data): <NEW_LINE> <INDENT> self.transport.write("y") <NEW_LINE> self.transport.loseConnection() <NEW_LINE> <DEDENT> def connectionLost(self, reason): <NEW_LINE> <INDENT> finished = self.factory.finished <NEW_LINE> if finished is not None: <NEW_LINE> <INDENT> self.factory.finished = None <NEW_LINE> finished.callback(reason) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> reactor = self.buildReactor() <NEW_LINE> serverFactory = ServerFactory() <NEW_LINE> serverFactory.finished = Deferred() <NEW_LINE> serverFactory.protocol = ShortProtocol <NEW_LINE> serverFactory.context = self.getServerContext() <NEW_LINE> clientFactory = ClientFactory() <NEW_LINE> clientFactory.finished = Deferred() <NEW_LINE> clientFactory.protocol = ShortProtocol <NEW_LINE> clientFactory.context = ClientContextFactory() <NEW_LINE> clientFactory.context.method = serverFactory.context.method <NEW_LINE> lostConnectionResults = [] <NEW_LINE> finished = DeferredList( [serverFactory.finished, clientFactory.finished], consumeErrors=True) <NEW_LINE> def cbFinished(results): <NEW_LINE> <INDENT> lostConnectionResults.extend([results[0][1], results[1][1]]) <NEW_LINE> <DEDENT> finished.addCallback(cbFinished) <NEW_LINE> port = reactor.listenTCP(0, serverFactory, interface='127.0.0.1') <NEW_LINE> self.addCleanup(port.stopListening) <NEW_LINE> connector = reactor.connectTCP( port.getHost().host, port.getHost().port, clientFactory) <NEW_LINE> self.addCleanup(connector.disconnect) <NEW_LINE> finished.addCallback(lambda ign: reactor.stop()) <NEW_LINE> self.runReactor(reactor) <NEW_LINE> lostConnectionResults[0].trap(ConnectionClosed) <NEW_LINE> lostConnectionResults[1].trap(ConnectionClosed) | Mixin defining tests relating to L{ITLSTransport}. | 62598fa676e4537e8c3ef493 |
class SQLQueryTriggered(Exception): <NEW_LINE> <INDENT> pass | Thrown when template panel triggers a query | 62598fa67047854f4633f2c0 |
class ConfigurationValues(db.Model, DbMixin): <NEW_LINE> <INDENT> __tablename__='configurationvalues' <NEW_LINE> friendly_name="Configuration Values" <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> version = db.Column(db.String(15)) <NEW_LINE> model = db.Column(db.String(20)) <NEW_LINE> configuration_id = db.Column(db.Integer(), db.ForeignKey('configuration.id')) <NEW_LINE> vulncve = db.relationship('VulnCve', secondary=configurationvalues_vulncve, backref=db.backref('configurations', lazy='dynamic')) <NEW_LINE> vulnbasic = db.relationship('VulnBasic', secondary=configurationvalues_vulnbasic, backref=db.backref('configurations', lazy='dynamic')) <NEW_LINE> vulnperm = db.relationship('VulnPerm', secondary=configurationvalues_vulnperm, backref=db.backref('configurations', lazy='dynamic')) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return self.id | Represents value from config file | 62598fa6009cb60464d0140a |
class BaudRates(enum.Enum): <NEW_LINE> <INDENT> DISABLED = -1 <NEW_LINE> B0 = 0 <NEW_LINE> B110 = 110 <NEW_LINE> B300 = 300 <NEW_LINE> B600 = 600 <NEW_LINE> B1200 = 1200 <NEW_LINE> B2400 = 2400 <NEW_LINE> B4800 = 4800 <NEW_LINE> B9600 = 9600 <NEW_LINE> B14400 = 14400 <NEW_LINE> B19200 = 19200 <NEW_LINE> B38400 = 38400 <NEW_LINE> B57600 = 57600 <NEW_LINE> B115200 = 115200 <NEW_LINE> B128000 = 128000 <NEW_LINE> B256000 = 256000 | This enum describes all baud rates which are commonly used. | 62598fa6aad79263cf42e6bc |
class CommonOptionGroup(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.options = [] <NEW_LINE> self.pass_state = click.make_pass_decorator(State, ensure=True) <NEW_LINE> <DEDENT> def add(self, *args, **kwargs): <NEW_LINE> <INDENT> def decorator(f): <NEW_LINE> <INDENT> def callback(ctx, param, value): <NEW_LINE> <INDENT> if 'extra_callback' in kwargs: <NEW_LINE> <INDENT> value = kwargs['extra_callback'](ctx, param, value) <NEW_LINE> <DEDENT> state = ctx.ensure_object(State) <NEW_LINE> setattr(state, param.name, value) <NEW_LINE> return value <NEW_LINE> <DEDENT> kwargs['callback'] = callback <NEW_LINE> kwargs['expose_value'] = False <NEW_LINE> return click.option(*args, **{k: v for k, v in kwargs.iteritems() if k != 'extra_callback'})(f) <NEW_LINE> <DEDENT> self.options.append(decorator) <NEW_LINE> <DEDENT> def __call__(self, f): <NEW_LINE> <INDENT> for option in self.options: <NEW_LINE> <INDENT> f = option(f) <NEW_LINE> <DEDENT> return self.pass_state(f) | Generate common options and decorate the command with the resulting object.
Use thus::
>>> common_options = CommonOptionGroup()
>>> common_options.add('--some-option', '-s', type=int, default=10, nargs=1,
... help="Here's an interesting option.",
... extra_callback=lambda ctx, param, value: value + 10)
>>>
>>> @click.argument('anotherarg')
... @common_options
... def some_command(common_state, anotherarg):
... print common_state.some_option, anotherarg | 62598fa6a8370b77170f02c2 |
class TestReadme(object): <NEW_LINE> <INDENT> def test_readme(self): <NEW_LINE> <INDENT> GP = gs.Github_Profile() <NEW_LINE> url = 'https://api.github.com/repos/silburt/DeepMoon/contents' <NEW_LINE> gf.get_readme_length(url, GP) <NEW_LINE> assert GP.readme_lines == 99 | Test readme length feature. | 62598fa610dbd63aa1c70a99 |
class State: <NEW_LINE> <INDENT> __slots__ = "arcs", "letter_set" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.arcs = dict() <NEW_LINE> self.letter_set = set() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for char in self.arcs: <NEW_LINE> <INDENT> yield self.arcs[char] <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, char): <NEW_LINE> <INDENT> return char in self.arcs <NEW_LINE> <DEDENT> def get_arc(self, char) -> "Arc": <NEW_LINE> <INDENT> return self.arcs[char] if char in self.arcs else None <NEW_LINE> <DEDENT> def add_arc(self, char: str, destination: "State" = None) -> "State": <NEW_LINE> <INDENT> if char not in self.arcs: <NEW_LINE> <INDENT> self.arcs[char] = Arc(char, destination) <NEW_LINE> <DEDENT> return self.get_next(char) <NEW_LINE> <DEDENT> def add_final_arc(self, char: str, final: str) -> "State": <NEW_LINE> <INDENT> if char not in self.arcs: <NEW_LINE> <INDENT> self.arcs[char] = Arc(char) <NEW_LINE> <DEDENT> self.get_next(char).add_letter(final) <NEW_LINE> return self.get_next(char) <NEW_LINE> <DEDENT> def add_letter(self, char: str): <NEW_LINE> <INDENT> self.letter_set.add(char) <NEW_LINE> <DEDENT> def get_next(self, char: str) -> "State": <NEW_LINE> <INDENT> return self.arcs[char].destination if char in self.arcs else None | a state in a GADDAG | 62598fa63cc13d1c6d465653 |
class SourceCatalog3FHL(SourceCatalog): <NEW_LINE> <INDENT> name = '3fhl' <NEW_LINE> description = 'LAT third high-energy source catalog' <NEW_LINE> source_object_class = SourceCatalogObject3FHL <NEW_LINE> source_categories = { 'galactic': ['glc', 'hmb', 'psr', 'pwn', 'sfr', 'snr', 'spp'], 'extra-galactic': ['agn', 'bcu', 'bll', 'fsrq', 'rdg', 'sbg'], 'GALACTIC': ['BIN', 'HMB', 'PSR', 'PWN', 'SFR', 'SNR'], 'EXTRA-GALACTIC': ['BLL', 'FSRQ', 'NLSY1', 'RDG'], 'unassociated': [''], } <NEW_LINE> def __init__(self, filename='$GAMMAPY_EXTRA/datasets/catalogs/fermi/gll_psch_v13.fit.gz'): <NEW_LINE> <INDENT> filename = str(make_path(filename)) <NEW_LINE> with warnings.catch_warnings(): <NEW_LINE> <INDENT> warnings.simplefilter("ignore", u.UnitsWarning) <NEW_LINE> table = Table.read(filename, hdu='LAT_Point_Source_Catalog') <NEW_LINE> <DEDENT> table_standardise_units_inplace(table) <NEW_LINE> source_name_key = 'Source_Name' <NEW_LINE> source_name_alias = ('ASSOC1', 'ASSOC2', 'ASSOC_TEV', 'ASSOC_GAM') <NEW_LINE> super(SourceCatalog3FHL, self).__init__( table=table, source_name_key=source_name_key, source_name_alias=source_name_alias, ) <NEW_LINE> self.extended_sources_table = Table.read(filename, hdu='ExtendedSources') <NEW_LINE> self.rois = Table.read(filename, hdu='ROIs') <NEW_LINE> self.energy_bounds_table = Table.read(filename, hdu='EnergyBounds') <NEW_LINE> <DEDENT> def is_source_class(self, source_class): <NEW_LINE> <INDENT> source_class_info = np.array([_.strip() for _ in self.table['CLASS']]) <NEW_LINE> if source_class in self.source_categories: <NEW_LINE> <INDENT> category = set(self.source_categories[source_class]) <NEW_LINE> <DEDENT> elif source_class == 'ALL': <NEW_LINE> <INDENT> category = set(self.source_categories['EXTRA-GALACTIC'] + self.source_categories['GALACTIC']) <NEW_LINE> <DEDENT> elif source_class == 'all': <NEW_LINE> <INDENT> category = set(self.source_categories['extra-galactic'] + self.source_categories['galactic']) <NEW_LINE> <DEDENT> elif source_class in np.unique(source_class_info): <NEW_LINE> <INDENT> category = set([source_class]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("'{}' ist not a valid source class.".format(source_class)) <NEW_LINE> <DEDENT> selection = np.array([_ in category for _ in source_class_info]) <NEW_LINE> return selection <NEW_LINE> <DEDENT> def select_source_class(self, source_class): <NEW_LINE> <INDENT> catalog = self.copy() <NEW_LINE> selection = self.is_source_class(source_class) <NEW_LINE> catalog.table = catalog.table[selection] <NEW_LINE> return catalog | Fermi-LAT 3FHL source catalog.
One source is represented by `~gammapy.catalog.SourceCatalogObject3FHL`. | 62598fa64e4d56256637230c |
class GetKeys(Method): <NEW_LINE> <INDENT> roles = ['admin', 'pi', 'user', 'tech', 'node'] <NEW_LINE> accepts = [ Auth(), Mixed([Mixed(Key.fields['key_id'])], Filter(Key.fields)), Parameter([str], "List of fields to return", nullok = True) ] <NEW_LINE> returns = [Key.fields] <NEW_LINE> def call(self, auth, key_filter = None, return_fields = None): <NEW_LINE> <INDENT> keys = Keys(self.api, key_filter, return_fields) <NEW_LINE> if isinstance(self.caller, Person) and 'admin' not in self.caller['roles']: <NEW_LINE> <INDENT> keys = [key for key in keys if key['key_id'] in self.caller['key_ids']] <NEW_LINE> <DEDENT> return keys | Returns an array of structs containing details about keys. If
key_filter is specified and is an array of key identifiers, or a
struct of key attributes, only keys matching the filter will be
returned. If return_fields is specified, only the specified
details will be returned.
Admin may query all keys. Non-admins may only query their own
keys. | 62598fa60c0af96317c5626a |
class TestLDAPGroupWrite(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testLDAPGroupWrite(self): <NEW_LINE> <INDENT> pass | LDAPGroupWrite unit test stubs | 62598fa6379a373c97d98efa |
@register_relay_attr_node <NEW_LINE> class L2NormalizeAttrs(Attrs): <NEW_LINE> <INDENT> pass | Attributes for nn.l2_normalize | 62598fa64e4d56256637230d |
class GradeCell(Base): <NEW_LINE> <INDENT> __tablename__ = "grade_cell" <NEW_LINE> __table_args__ = (UniqueConstraint('name', 'notebook_id'),) <NEW_LINE> id = Column(String(32), primary_key=True, default=new_uuid) <NEW_LINE> name = Column(String(128), nullable=False) <NEW_LINE> max_score = Column(Float(), nullable=False) <NEW_LINE> cell_type = Column(Enum("code", "markdown", name="grade_cell_type"), nullable=False) <NEW_LINE> notebook = None <NEW_LINE> notebook_id = Column(String(32), ForeignKey('notebook.id')) <NEW_LINE> assignment = association_proxy("notebook", "assignment") <NEW_LINE> grades = relationship("Grade", backref="cell") <NEW_LINE> def to_dict(self): <NEW_LINE> <INDENT> return { "id": self.id, "name": self.name, "max_score": self.max_score, "cell_type": self.cell_type, "notebook": self.notebook.name, "assignment": self.assignment.name } <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "GradeCell<{}/{}/{}>".format( self.assignment.name, self.notebook.name, self.name) | Database representation of the master/source version of a grade cell. | 62598fa601c39578d7f12c68 |
class LineObjTestCase(MapPrimitivesTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.points = (mapscript.pointObj(0.0, 1.0), mapscript.pointObj(2.0, 3.0)) <NEW_LINE> self.line = mapscript.lineObj() <NEW_LINE> self.addPointToLine(self.line, self.points[0]) <NEW_LINE> self.addPointToLine(self.line, self.points[1]) <NEW_LINE> <DEDENT> def testCreateLine(self): <NEW_LINE> <INDENT> assert self.line.numpoints == 2 <NEW_LINE> <DEDENT> def testGetPointsFromLine(self): <NEW_LINE> <INDENT> for i in range(len(self.points)): <NEW_LINE> <INDENT> got_point = self.getPointFromLine(self.line, i) <NEW_LINE> self.assertPointsEqual(got_point, self.points[i]) <NEW_LINE> <DEDENT> <DEDENT> def testAddPointToLine(self): <NEW_LINE> <INDENT> new_point = mapscript.pointObj(4.0, 5.0) <NEW_LINE> self.addPointToLine(self.line, new_point) <NEW_LINE> assert self.line.numpoints == 3 <NEW_LINE> <DEDENT> def testAlterNumPoints(self): <NEW_LINE> <INDENT> self.assertRaises(AttributeError, setattr, self.line, 'numpoints', 3) | Testing the lineObj class in stand-alone mode | 62598fa663d6d428bbee269a |
class TaskView(CreateView): <NEW_LINE> <INDENT> model = Task <NEW_LINE> form_class = TaskForm <NEW_LINE> success_url = "/" <NEW_LINE> template_name = "task.html" <NEW_LINE> context_object_name = "tasks" <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> task = form.save() <NEW_LINE> parse.delay(task.pk, task.word) <NEW_LINE> return super().form_valid(form) | Отображение и обработка формы ввода новой задачи | 62598fa66e29344779b00545 |
class SetUpTestesDadosValidos(EstoqueTest): <NEW_LINE> <INDENT> def test_quantidade_de_categorias_criadas(self): <NEW_LINE> <INDENT> self.assertEqual(9, len(self.todas_categorias)) <NEW_LINE> <DEDENT> def test_quantidade_de_subcategorias_criadas(self): <NEW_LINE> <INDENT> self.assertEqual(8, len(self.todas_subcategorias)) <NEW_LINE> <DEDENT> def test_quantidade_fornecedores_criados(self): <NEW_LINE> <INDENT> self.assertEqual(1, len(Fornecedor.objects.all())) <NEW_LINE> <DEDENT> def test_nome_Fornecedor(self): <NEW_LINE> <INDENT> fornecedor = Fornecedor.objects.first() <NEW_LINE> self.assertEqual("Renner", fornecedor.nome_empresa) <NEW_LINE> <DEDENT> def test_quantidade_de_usuarios_criados(self): <NEW_LINE> <INDENT> self.assertEqual(1, len(User.objects.all())) <NEW_LINE> <DEDENT> def test_nome_usuario_criado(self): <NEW_LINE> <INDENT> self.assertEqual("admin", User.objects.first().username) <NEW_LINE> <DEDENT> def test_quantidade_de_produtos_criados(self): <NEW_LINE> <INDENT> self.assertEqual(10, len(Produto.objects.all())) <NEW_LINE> <DEDENT> def test_gera_unico_codigo_de_barras(self): <NEW_LINE> <INDENT> for i in range(10): <NEW_LINE> <INDENT> choice_produto = choice(self.todos_produtos) <NEW_LINE> ean_one_product = choice_produto.ean <NEW_LINE> barcode = generate_barcode(ean_one_product) <NEW_LINE> with self.subTest(): <NEW_LINE> <INDENT> self.assertNotEqual(ean_one_product, barcode) <NEW_LINE> self.assertEqual(0, len(Produto.objects.filter(ean=barcode))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_gera_codigo_sku(self): <NEW_LINE> <INDENT> for produto in self.todos_produtos: <NEW_LINE> <INDENT> genero = produto.genero[:1] <NEW_LINE> codigo_categoria = produto.categoria.codigo <NEW_LINE> codigo_subcategoria = produto.subcategoria.codigo <NEW_LINE> tamanho_sku = f"{(2 - len(produto.tamanho)) * '0'}{produto.tamanho}" <NEW_LINE> with self.subTest(): <NEW_LINE> <INDENT> self.assertEqual(produto.sku, f"{genero}{codigo_categoria}{codigo_subcategoria}{tamanho_sku}") | Testes com dados válidos informados | 62598fa6ac7a0e7691f723f3 |
class UciShowWireless(rootfs_boot.RootFSBootTest): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> wlan_iface = wifi_interface(board) <NEW_LINE> if wlan_iface is None: <NEW_LINE> <INDENT> self.skipTest("No wifi interfaces detected, skipping..") <NEW_LINE> <DEDENT> board.sendline('\nuci show wireless') <NEW_LINE> board.expect('uci show wireless') <NEW_LINE> board.expect(prompt) <NEW_LINE> wifi_interfaces = re.findall('wireless.*=wifi-device', board.before) <NEW_LINE> self.result_message = "UCI shows %s wifi interface(s)." % (len(wifi_interfaces)) <NEW_LINE> self.logged['num_ifaces'] = len(wifi_interfaces) <NEW_LINE> assert len(wifi_interfaces) > 0 | UCI lists wifi interfaces. | 62598fa6097d151d1a2c0f10 |
class ApiRoot(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> data = OrderedDict() <NEW_LINE> for method in API_METHODS: <NEW_LINE> <INDENT> data[method] = reverse(method, request=request, format=format) <NEW_LINE> <DEDENT> return Response(data) | # Welcome to The Good Foot Club API
Welcome to The Good Foot Club project REST API!
## Explore
Down below you can see the list of available api methods. Feel free to
follow each url and learn details about each method. | 62598fa644b2445a339b68e3 |
class Described(WavesBaseModel): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> description = RichTextField('Description', null=True, blank=True, help_text='Description (HTML)') <NEW_LINE> short_description = models.TextField('Short Description', null=True, blank=True, help_text='Short description (Text)') | A model object which inherit from this class add two description fields to model objects | 62598fa6e76e3b2f99fd891f |
class Machine(Resource): <NEW_LINE> <INDENT> ENDPOINT = '/machines' <NEW_LINE> def get(self, machine_id): <NEW_LINE> <INDENT> machine_res = {} <NEW_LINE> with database.session() as session: <NEW_LINE> <INDENT> machine = session.query(ModelMachine) .filter_by(id=machine_id) .first() <NEW_LINE> logging.info('machine for id %s: %s', machine_id, machine) <NEW_LINE> if not machine: <NEW_LINE> <INDENT> error_msg = "Cannot find the machine with id=%s" % machine_id <NEW_LINE> logging.error("[/api/machines/{id}]error_msg: %s", error_msg) <NEW_LINE> return errors.handle_not_exist( errors.ObjectDoesNotExist(error_msg)) <NEW_LINE> <DEDENT> machine_res['id'] = machine.id <NEW_LINE> machine_res['mac'] = machine.mac <NEW_LINE> machine_res['port'] = machine.port <NEW_LINE> machine_res['vlan'] = machine.vlan <NEW_LINE> if machine.switch: <NEW_LINE> <INDENT> machine_res['switch_ip'] = machine.switch.ip <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> machine_res['switch_ip'] = None <NEW_LINE> <DEDENT> machine_res['link'] = { 'rel': 'self', 'href': '/'.join((self.ENDPOINT, str(machine.id)))} <NEW_LINE> <DEDENT> logging.info('machine info for %s: %s', machine_id, machine_res) <NEW_LINE> return util.make_json_response( 200, {"status": "OK", "machine": machine_res}) | List details of the machine with specific machine id | 62598fa6d58c6744b42dc249 |
class FFMpegRecipe(Recipe): <NEW_LINE> <INDENT> version = 'libpng16' <NEW_LINE> url = 'git+https://github.com/brussee/ffmpeg-android.git' <NEW_LINE> patches = ['settings.patch'] <NEW_LINE> def should_build(self, arch): <NEW_LINE> <INDENT> return not exists(self.get_build_bin(arch)) <NEW_LINE> <DEDENT> def build_arch(self, arch): <NEW_LINE> <INDENT> super(FFMpegRecipe, self).build_arch(arch) <NEW_LINE> env = self.get_recipe_env(arch) <NEW_LINE> build_dir = self.get_build_dir(arch.arch) <NEW_LINE> with current_directory(build_dir): <NEW_LINE> <INDENT> bash = sh.Command('bash') <NEW_LINE> shprint(bash, 'init_update_libs.sh') <NEW_LINE> shprint(bash, 'android_build.sh', _env=env) <NEW_LINE> <DEDENT> <DEDENT> def get_build_bin(self, arch): <NEW_LINE> <INDENT> build_dir = self.get_build_dir(arch.arch) <NEW_LINE> return join(build_dir, 'build', arch.arch, 'bin', 'ffmpeg') <NEW_LINE> <DEDENT> def get_recipe_env(self, arch): <NEW_LINE> <INDENT> env = super(FFMpegRecipe, self).get_recipe_env(arch) <NEW_LINE> env['ANDROID_NDK'] = self.ctx.ndk_dir <NEW_LINE> env['ANDROID_API'] = str(self.ctx.android_api) <NEW_LINE> return env | FFmpeg for Android compiled with x264, libass, fontconfig, freetype, fribidi and lame (Supports Android 4.1+)
http://writingminds.github.io/ffmpeg-android/ | 62598fa64f6381625f199432 |
class CopyToBoot(Actor): <NEW_LINE> <INDENT> name = 'copy_to_boot' <NEW_LINE> consumes = () <NEW_LINE> produces = (BootContent,) <NEW_LINE> tags = (IPUWorkflowTag, InterimPreparationPhaseTag) <NEW_LINE> def process(self): <NEW_LINE> <INDENT> copy_to_boot() | Copy Leapp provided initramfs to boot partition.
In order to execute upgrade, Leapp provides a special initramfs and kernel to be used during
the process. Such artifacts need to be placed inside boot partition. | 62598fa65fdd1c0f98e5de81 |
class IRCEvent(O): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> O.__init__(self, *args, **kwargs) <NEW_LINE> self.parse() <NEW_LINE> <DEDENT> def parse(self): <NEW_LINE> <INDENT> if not self.input: raise NoInput() <NEW_LINE> rawstr = self.input <NEW_LINE> self.servermsg = False <NEW_LINE> splitted = re.split('\s+', rawstr) <NEW_LINE> if not rawstr[0] == ':': self.servermsg = True <NEW_LINE> self.prefix = splitted[0] <NEW_LINE> if self.servermsg: self.cbtype = self.prefix <NEW_LINE> else: self.cbtype = splitted[1] <NEW_LINE> try: <NEW_LINE> <INDENT> nickuser = self.prefix.split('!') <NEW_LINE> self.origin = nickuser[1] <NEW_LINE> self.nick = nickuser[0][1:] <NEW_LINE> <DEDENT> except IndexError: self.origin = self.prefix ; self.servermsg = True <NEW_LINE> if self.cbtype in pfc: <NEW_LINE> <INDENT> self.arguments = splitted[2:pfc[self.cbtype]+2] <NEW_LINE> txtsplit = re.split('\s+', rawstr, pfc[self.cbtype]+2) <NEW_LINE> self.txt = txtsplit[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.debug("cmnd not in pfc - %s" % rawstr) <NEW_LINE> self.arguments = splitted[2:] <NEW_LINE> <DEDENT> if self.arguments: self.target = self.arguments[0] <NEW_LINE> self.postfix = ' '.join(self.arguments) <NEW_LINE> if not "txt" in self: self.txt = rawstr.rsplit(":")[-1] <NEW_LINE> if self.txt.startswith(":"): self.txt = self.txt[1:] <NEW_LINE> if not "channel" in self: <NEW_LINE> <INDENT> for c in self.arguments + [self.txt, ]: <NEW_LINE> <INDENT> if c.startswith("#"): self.channel = c <NEW_LINE> <DEDENT> <DEDENT> if self.servermsg: <NEW_LINE> <INDENT> self.origin = self.origin[1:-1] <NEW_LINE> self.channel = self.origin <NEW_LINE> <DEDENT> if not "origin" in self: self.origin = self.channel <NEW_LINE> if not "target" in self: self.target = self.channel or self.origin <NEW_LINE> return self | represents an IRC event. | 62598fa660cbc95b06364235 |
class LBXPlus(LBX, object): <NEW_LINE> <INDENT> def __init__(self, formula, use_cld=False, use_timer=False): <NEW_LINE> <INDENT> super(LBXPlus, self).__init__(formula, use_cld=use_cld, solver_name='mc', use_timer=use_timer) <NEW_LINE> for am in formula.atms: <NEW_LINE> <INDENT> self.oracle.add_atmost(*am) | Algorithm LBX for CNF+/WCNF+ formulas. | 62598fa6009cb60464d0140b |
class PerformanceInfo(Structure): <NEW_LINE> <INDENT> _fields_ = [ ('size', c_ulong), ('CommitTotal', c_size_t), ('CommitLimit', c_size_t), ('CommitPeak', c_size_t), ('PhysicalTotal', c_size_t), ('PhysicalAvailable', c_size_t), ('SystemCache', c_size_t), ('KernelTotal', c_size_t), ('KernelPaged', c_size_t), ('KernelNonpaged', c_size_t), ('PageSize', c_size_t), ('HandleCount', c_ulong), ('ProcessCount', c_ulong), ('ThreadCount', c_ulong), ] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.size = sizeof(self) <NEW_LINE> super(PerformanceInfo, self).__init__() | I/O struct for Windows .GetPerformanceInfo() call.
Docs:
http://msdn.microsoft.com/en-us/library/ms684824 | 62598fa626068e7796d4c842 |
class Account(_BaseCerp): <NEW_LINE> <INDENT> ROOT_NAME = 'Account' <NEW_LINE> XSD_SCHEMA = 'http://www.history.ncdcr.gov/SHRAB/ar/emailpreservation/mail-account/mail-account.xsd' <NEW_LINE> email_address = xmlmap.StringField('xm:EmailAddress') <NEW_LINE> global_id = xmlmap.StringField('xm:GlobalId') <NEW_LINE> references_accounts = xmlmap.NodeListField('xm:ReferencesAccount', ReferencesAccount) <NEW_LINE> folders = xmlmap.NodeListField('xm:Folder', Folder) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<%s %s>' % (self.__class__.__name__, self.global_id or self.email_address or '(no id)') | A single email account associated with a single email address and
composed of multiple :class:`Folder` objects and additional metadata. | 62598fa6cc0a2c111447aef9 |
class HistoricalDataObj: <NEW_LINE> <INDENT> vOpen = array([]) <NEW_LINE> vClose = array([]) <NEW_LINE> stockTicker = "" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.stockTicker= "" <NEW_LINE> self.vDateInt = array([]) <NEW_LINE> self.vDate = array([]) <NEW_LINE> self.vOpen = array([]) <NEW_LINE> self.vClose = array([]) <NEW_LINE> self.vHigh = array([]) <NEW_LINE> self.vLow = array([]) <NEW_LINE> self.vVolume = array([]) <NEW_LINE> self.vLdata = array([]) <NEW_LINE> self.N = 0; <NEW_LINE> self.quotes = []; <NEW_LINE> <DEDENT> def initialize( self, stockTicker, daysBack, interval = 1, resolution = 1, dataFeedType = "yahoo", dateFormat="raw"): <NEW_LINE> <INDENT> date1 = date.today() - timedelta(days=daysBack) <NEW_LINE> date2 = date.today() <NEW_LINE> self.initialize1(stockTicker, date1, date2, interval, resolution, dataFeedType) <NEW_LINE> <DEDENT> def init(self,initType): <NEW_LINE> <INDENT> if(initType =="logData"): <NEW_LINE> <INDENT> self.vLdata = zeros(self.N) <NEW_LINE> vLdata = log(self.vClose[1:] /self.vClose[:-1] ) <NEW_LINE> <DEDENT> <DEDENT> def initialize1( self,stockTicker, date1, date2, interval, resolution, dataFeedType): <NEW_LINE> <INDENT> self.stockTicker = stockTicker; <NEW_LINE> if(dataFeedType =="yahoo"): <NEW_LINE> <INDENT> self.quotes = quotes_historical_yahoo(self.stockTicker, date1, date2) <NEW_LINE> self.N = self.quotes.__len__(); <NEW_LINE> self.vDateInt = zeros(self.N) <NEW_LINE> self.vDate = empty(self.N, dtype=object); <NEW_LINE> self.vOpen = zeros(self.N) <NEW_LINE> self.vClose = zeros(self.N) <NEW_LINE> self.vHigh = zeros(self.N) <NEW_LINE> self.vLow = zeros(self.N) <NEW_LINE> self.vVolume = zeros(self.N) <NEW_LINE> index = 0; <NEW_LINE> for line in self.quotes: <NEW_LINE> <INDENT> self.vDateInt[index]= line [0]; <NEW_LINE> self.vDate[index] = date.fromordinal( int( line [0] ) ) <NEW_LINE> self.vOpen[index] = line [1]; <NEW_LINE> self.vClose[index] = line [2]; <NEW_LINE> self.vHigh[index] = line [3]; <NEW_LINE> self.vLow[index] = line [4]; <NEW_LINE> self.vVolume[index] = line [5]; <NEW_LINE> index = index +1; <NEW_LINE> <DEDENT> <DEDENT> elif (dataFeedType == "google"): <NEW_LINE> <INDENT> self.vDateInt, self.vOpen, self.vHigh, self.vLow, self.vClose, self.vVolume = quotes_historical_google.getData(symbol=self.stockTicker, startDate=date1, endDate=date2, resolution=resolution); <NEW_LINE> self.N = size(self.vDateInt); <NEW_LINE> self.vDate = empty(self.N, dtype=object); <NEW_LINE> index = 0; <NEW_LINE> for d in self.vDateInt: <NEW_LINE> <INDENT> self.vDate[index] = date.fromordinal( int( d) ); <NEW_LINE> index = index + 1; | Historical Finance Data Object | 62598fa63cc13d1c6d465655 |
class ConversationProcessView(http.HomeAssistantView): <NEW_LINE> <INDENT> url = '/api/conversation/process' <NEW_LINE> name = "api:conversation:process" <NEW_LINE> @asyncio.coroutine <NEW_LINE> def post(self, request): <NEW_LINE> <INDENT> hass = request.app['hass'] <NEW_LINE> try: <NEW_LINE> <INDENT> data = yield from request.json() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return self.json_message('Invalid JSON specified', HTTP_BAD_REQUEST) <NEW_LINE> <DEDENT> text = data.get('text') <NEW_LINE> if text is None: <NEW_LINE> <INDENT> return self.json_message('Missing "text" key in JSON.', HTTP_BAD_REQUEST) <NEW_LINE> <DEDENT> intent_result = yield from _process(hass, text) <NEW_LINE> if intent_result is None: <NEW_LINE> <INDENT> intent_result = intent.IntentResponse() <NEW_LINE> intent_result.async_set_speech("Sorry, I didn't understand that") <NEW_LINE> <DEDENT> return self.json(intent_result) | View to retrieve shopping list content. | 62598fa6090684286d593650 |
class ABC(Network): <NEW_LINE> <INDENT> def get_show(self, show_info): <NEW_LINE> <INDENT> if not super(self.__class__, self).get_show(show_info): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> base_url = "http://abc.go.com" <NEW_LINE> show_title = show_info['show_title'] <NEW_LINE> show_url = "{0}/shows/{1}/episode-guide/".format(base_url, show_info['show_id']) <NEW_LINE> response = self.caller.request_data({"url": show_url}) <NEW_LINE> if response is not False: <NEW_LINE> <INDENT> episode_data = {'show': show_title, 'episodes': {}} <NEW_LINE> base_dom = BeautifulSoup(response.text, 'html.parser') <NEW_LINE> elements = base_dom.find_all('select') <NEW_LINE> for element in elements: <NEW_LINE> <INDENT> if element['name'] == 'blog-select': <NEW_LINE> <INDENT> seasons = element.find_all('option') <NEW_LINE> for season in seasons: <NEW_LINE> <INDENT> season_url = season['value'] <NEW_LINE> season_number = season_url.split('-')[-1].lstrip('0') <NEW_LINE> contents = self.caller.request_data({"url": "{0}{1}".format(base_url, season_url)}) <NEW_LINE> season_dom = BeautifulSoup(contents.text, 'html.parser') <NEW_LINE> season_divs = season_dom.find_all('div') <NEW_LINE> for season_div in season_divs: <NEW_LINE> <INDENT> if 'data-sm-type' in season_div.attrs and season_div['data-sm-type'] == 'episode': <NEW_LINE> <INDENT> links = season_div.find_all('a') <NEW_LINE> watch = False <NEW_LINE> for link in links: <NEW_LINE> <INDENT> if link.text.lower() == 'watch': <NEW_LINE> <INDENT> watch = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if watch: <NEW_LINE> <INDENT> episode_divs = season_div.find_all('div') <NEW_LINE> locked = False <NEW_LINE> for episode_div in episode_divs: <NEW_LINE> <INDENT> if 'class' in episode_div.attrs and 'locked' in episode_div['class']: <NEW_LINE> <INDENT> locked = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not locked: <NEW_LINE> <INDENT> spans = season_div.find_all('span') <NEW_LINE> for span in spans: <NEW_LINE> <INDENT> if 'class' in span.attrs and 'episode-number' in span['class']: <NEW_LINE> <INDENT> episode_number = span.text.replace("E", "", ).strip() <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> episode_string = self.caller.get_episode_string(season_number, [episode_number]) <NEW_LINE> filenames = self.caller.get_filenames(show_title, season_number, episode_string) <NEW_LINE> episode_url = "{0}{1}".format(base_url, season_div.attrs['data-url']).strip() <NEW_LINE> if season_number not in episode_data['episodes']: <NEW_LINE> <INDENT> episode_data['episodes'][season_number] = {} <NEW_LINE> <DEDENT> if episode_number not in episode_data['episodes'][season_number]: <NEW_LINE> <INDENT> episode_data['episodes'][season_number][episode_number] = { 'url': episode_url, 'filenames': filenames } <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> self.caller.process_episodes(episode_data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.caller.logger.error("Request returned False: {0}".format(show_url)) <NEW_LINE> <DEDENT> return True | ABC network class | 62598fa61f037a2d8b9e3fd5 |
class Planet: <NEW_LINE> <INDENT> def __init__(self, initialPosition, initialVelocity, initialAcceleration, Name, mass, method): <NEW_LINE> <INDENT> if len(initialPosition) != 3: <NEW_LINE> <INDENT> raise ValueError("The initial position array must be of length 3") <NEW_LINE> <DEDENT> self.position = np.array(initialPosition) * 1. <NEW_LINE> if len(initialVelocity) != 3: <NEW_LINE> <INDENT> raise ValueError("The initial velocity array must be of length 3") <NEW_LINE> <DEDENT> self.velocity = np.array(initialVelocity) * 1. <NEW_LINE> if len(initialAcceleration) != 3: <NEW_LINE> <INDENT> raise ValueError("The initial acceleration array must be of length 3") <NEW_LINE> <DEDENT> self.acceleration = np.array(initialAcceleration) * 1. <NEW_LINE> self.Name = Name <NEW_LINE> self.mass = mass <NEW_LINE> self.setMethod(method) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Particle: %10s, Mass: %.5e, Position: %s, Velocity: %s, Acceleration:%s'%(self.Name,self.mass,self.position, self.velocity,self.acceleration) <NEW_LINE> <DEDENT> def setMethod(self,method): <NEW_LINE> <INDENT> self.updateMethod = self.EulerCromer <NEW_LINE> if method == 2: <NEW_LINE> <INDENT> self.updateMethod = self.EulerForward <NEW_LINE> <DEDENT> <DEDENT> def update(self, deltaT): <NEW_LINE> <INDENT> self.updateMethod(deltaT) <NEW_LINE> <DEDENT> def EulerCromer(self, deltaT): <NEW_LINE> <INDENT> self.velocity += (self.acceleration * deltaT) <NEW_LINE> self.position += (self.velocity * deltaT) <NEW_LINE> <DEDENT> def EulerForward(self, deltaT): <NEW_LINE> <INDENT> self.position += (self.velocity * deltaT) <NEW_LINE> self.velocity += (self.acceleration * deltaT) <NEW_LINE> <DEDENT> def GForce(self,massList,positionList): <NEW_LINE> <INDENT> G = 6.67408e-11 <NEW_LINE> force = 0 <NEW_LINE> for i in range(0,len(massList)): <NEW_LINE> <INDENT> if positionList[i].all == self.position.all: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> distanceVector = positionList[i] - self.position <NEW_LINE> distance = math.sqrt(distanceVector.dot(distanceVector)) <NEW_LINE> force = force + ((G * self.mass * massList[i])/(distance*distance*distance))*distanceVector <NEW_LINE> <DEDENT> return force <NEW_LINE> <DEDENT> def accelerationUpdater(self,massList,positionList): <NEW_LINE> <INDENT> acceleration = self.GForce(massList,positionList)/(self.mass) <NEW_LINE> return acceleration <NEW_LINE> <DEDENT> position = np.array([0,0,0]) <NEW_LINE> velocity = np.array([0,0,0]) <NEW_LINE> acceleration = np.array([0,0,0]) <NEW_LINE> name = "default" <NEW_LINE> mass = 1. <NEW_LINE> method = 1 | Class of methods including the Force to iterate over and the acceleration. Setting method = 1 uses Euler-Cromer, and setting method = 2 uses Euler-Forward. | 62598fa6d486a94d0ba2beb7 |
class override_method(object): <NEW_LINE> <INDENT> def __init__(self, view, request, method): <NEW_LINE> <INDENT> self.view = view <NEW_LINE> self.request = request <NEW_LINE> self.method = method <NEW_LINE> self.action = getattr(view, 'action', None) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.view.request = clone_request(self.request, self.method) <NEW_LINE> if self.action is not None: <NEW_LINE> <INDENT> action_map = getattr(self.view, 'action_map', {}) <NEW_LINE> self.view.action = action_map.get(self.method.lower()) <NEW_LINE> <DEDENT> return self.view.request <NEW_LINE> <DEDENT> def __exit__(self, *args, **kwarg): <NEW_LINE> <INDENT> self.view.request = self.request <NEW_LINE> if self.action is not None: <NEW_LINE> <INDENT> self.view.action = self.action | A context manager that temporarily overrides the method on a request,
additionally setting the `view.request` attribute.
Usage:
with override_method(view, request, 'POST') as request:
... # Do stuff with `view` and `request` | 62598fa6dd821e528d6d8e1f |
class QualnameTest(CoverageTest): <NEW_LINE> <INDENT> run_in_temp_dir = False <NEW_LINE> def test_method(self): <NEW_LINE> <INDENT> assert Parent().meth() == "tests.test_context.Parent.meth" <NEW_LINE> <DEDENT> def test_inherited_method(self): <NEW_LINE> <INDENT> assert Child().meth() == "tests.test_context.Parent.meth" <NEW_LINE> <DEDENT> def test_mi_inherited_method(self): <NEW_LINE> <INDENT> assert MultiChild().meth() == "tests.test_context.Parent.meth" <NEW_LINE> <DEDENT> def test_no_arguments(self): <NEW_LINE> <INDENT> assert no_arguments() == "tests.test_context.no_arguments" <NEW_LINE> <DEDENT> def test_plain_old_function(self): <NEW_LINE> <INDENT> assert plain_old_function(0, 1) == "tests.test_context.plain_old_function" <NEW_LINE> <DEDENT> def test_fake_out(self): <NEW_LINE> <INDENT> assert fake_out(0) == "tests.test_context.fake_out" <NEW_LINE> <DEDENT> def test_property(self): <NEW_LINE> <INDENT> assert Parent().a_property == "tests.test_context.Parent.a_property" <NEW_LINE> <DEDENT> def test_changeling(self): <NEW_LINE> <INDENT> c = Child() <NEW_LINE> c.meth = patch_meth <NEW_LINE> assert c.meth(c) == "tests.test_context.patch_meth" <NEW_LINE> <DEDENT> def test_bug_829(self): <NEW_LINE> <INDENT> class test_something: <NEW_LINE> <INDENT> assert get_qualname() is None <NEW_LINE> <DEDENT> <DEDENT> def test_bug_1210(self): <NEW_LINE> <INDENT> co = mock.Mock(co_name="a_co_name", co_argcount=1, co_varnames=["self"]) <NEW_LINE> frame = mock.Mock(f_code=co, f_locals={}) <NEW_LINE> assert qualname_from_frame(frame) == "unittest.mock.a_co_name" | Tests of qualname_from_frame. | 62598fa67d43ff2487427377 |
class BadImage(CloudRecoException): <NEW_LINE> <INDENT> pass | Exception raised when Vuforia returns a response with a result code
'BadImage'. | 62598fa64a966d76dd5eedcd |
class Solution(object): <NEW_LINE> <INDENT> def sortColors(self, nums): <NEW_LINE> <INDENT> color_count = [0] * 3 <NEW_LINE> for c in nums: <NEW_LINE> <INDENT> color_count[c] += 1 <NEW_LINE> <DEDENT> ind = 0 <NEW_LINE> for c in range(3): <NEW_LINE> <INDENT> for i in range(0, color_count[c]): <NEW_LINE> <INDENT> nums[ind] = c <NEW_LINE> ind += 1 | :type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead. | 62598fa676e4537e8c3ef496 |
class StringListView(object_rectangle.ObjectRectangle): <NEW_LINE> <INDENT> def __init__(self, rect, items, row_num): <NEW_LINE> <INDENT> object_rectangle.ObjectRectangle.__init__(self, rect) <NEW_LINE> self.row_num = row_num <NEW_LINE> self.items = [] <NEW_LINE> self._items_font = None <NEW_LINE> self.string_items = items <NEW_LINE> self.selected_index = None <NEW_LINE> self.on_selected = callback.Signal() <NEW_LINE> self.items_surface = pygame.Surface((self.rect.w - self.border_widths * 2, self.rect.h - self.border_widths * 2)).convert() <NEW_LINE> <DEDENT> @property <NEW_LINE> def items_font(self): <NEW_LINE> <INDENT> return self._items_font <NEW_LINE> <DEDENT> @items_font.setter <NEW_LINE> def items_font(self, new_font): <NEW_LINE> <INDENT> self._items_font = new_font <NEW_LINE> self.string_items = self._string_items <NEW_LINE> <DEDENT> @property <NEW_LINE> def string_items(self): <NEW_LINE> <INDENT> return self._string_items <NEW_LINE> <DEDENT> @string_items.setter <NEW_LINE> def string_items(self, new_items): <NEW_LINE> <INDENT> del self.items[:] <NEW_LINE> self._string_items = new_items <NEW_LINE> x = 0 <NEW_LINE> y = 0 <NEW_LINE> w = self.rect.w <NEW_LINE> h = (self.rect.h - self.border_widths) / self.row_num <NEW_LINE> for item in self._string_items: <NEW_LINE> <INDENT> string_list_item = StringListItem(Rect(x, y, w, h), item) <NEW_LINE> if self._items_font is not None: <NEW_LINE> <INDENT> string_list_item.font = self._items_font <NEW_LINE> <DEDENT> self.add_item(string_list_item) <NEW_LINE> y += h <NEW_LINE> <DEDENT> self.dirty = True <NEW_LINE> <DEDENT> def add_item(self, item): <NEW_LINE> <INDENT> assert item is not None <NEW_LINE> self.rm_item(item) <NEW_LINE> self.items.append(item) <NEW_LINE> <DEDENT> def rm_item(self, child): <NEW_LINE> <INDENT> for index, ch in enumerate(self.items): <NEW_LINE> <INDENT> if ch == child: <NEW_LINE> <INDENT> del self.items[index] <NEW_LINE> break; <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def all_dirty_item(self): <NEW_LINE> <INDENT> for item in self.items: <NEW_LINE> <INDENT> item.dirty = True <NEW_LINE> <DEDENT> <DEDENT> def deselect(self): <NEW_LINE> <INDENT> if self.selected_index is not None: <NEW_LINE> <INDENT> self.items[self.selected_index].selected = False <NEW_LINE> <DEDENT> self.selected_index = None <NEW_LINE> <DEDENT> def select(self, index): <NEW_LINE> <INDENT> self.deselect() <NEW_LINE> self.selected_index = index <NEW_LINE> if index is not None: <NEW_LINE> <INDENT> item = self.items[self.selected_index] <NEW_LINE> item.selected = True <NEW_LINE> self.on_selected(self, item, index) <NEW_LINE> <DEDENT> <DEDENT> def mouse_down(self, point): <NEW_LINE> <INDENT> for index, item in enumerate(self.items): <NEW_LINE> <INDENT> item_rect = Rect(self.rect.x, self.rect.y + item.rect.y, item.rect.w, item.rect.h) <NEW_LINE> if item_rect.collidepoint(point): <NEW_LINE> <INDENT> self.select(index) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _draw(self, screen): <NEW_LINE> <INDENT> if not object_rectangle.ObjectRectangle._draw(self, screen) : <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.all_dirty_item() <NEW_LINE> self.items_surface.fill(self.background_color) <NEW_LINE> for item in self.items: <NEW_LINE> <INDENT> item.draw_blit(self.items_surface) <NEW_LINE> <DEDENT> self.surface.blit(self.items_surface, (self.border_widths, self.border_widths)) <NEW_LINE> return True | classdocs | 62598fa6be383301e02536e2 |
class Rogue(Character): <NEW_LINE> <INDENT> def __init__(self, name: str, battle_queue: 'BattleQueue', playstyle: 'Playstlyle') -> None: <NEW_LINE> <INDENT> super().__init__(name, battle_queue, playstyle) <NEW_LINE> self.defense = 10 <NEW_LINE> self.style = 'Rogue' <NEW_LINE> self.sprite = 'rogue' <NEW_LINE> <DEDENT> def attack(self) -> None: <NEW_LINE> <INDENT> self.last_animation = ('attack', -1) <NEW_LINE> self.enemy.health = max(0, self.enemy.health - 15 + self.enemy.defense) <NEW_LINE> self.skill_points = max(0, self.skill_points - 3) <NEW_LINE> self.battle_queue.add(self) <NEW_LINE> <DEDENT> def special_attack(self) -> None: <NEW_LINE> <INDENT> self.last_animation = ('special', -1) <NEW_LINE> self.enemy.health = max(0, self.enemy.health - 20 + self.enemy.defense) <NEW_LINE> self.skill_points = max(0, self.skill_points - 10) <NEW_LINE> self.battle_queue.add(self) <NEW_LINE> self.battle_queue.add(self) <NEW_LINE> <DEDENT> def get_available_actions(self) -> list: <NEW_LINE> <INDENT> if self.skill_points >= 10: <NEW_LINE> <INDENT> return ['A', 'S'] <NEW_LINE> <DEDENT> elif self.skill_points >= 3: <NEW_LINE> <INDENT> return ['A'] <NEW_LINE> <DEDENT> return [] <NEW_LINE> <DEDENT> def is_valid_action(self, move: str) -> bool: <NEW_LINE> <INDENT> if self.skill_points >= 10: <NEW_LINE> <INDENT> return move in ['A', 'S'] <NEW_LINE> <DEDENT> elif self.skill_points >= 3: <NEW_LINE> <INDENT> return move in ['A'] <NEW_LINE> <DEDENT> return False | A rogue type character class. Inherits from character | 62598fa6796e427e5384e67e |
class TestThreadGetByUser(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.group = mommy.make('groups.Group', private=True) <NEW_LINE> self.user = mommy.make( 'accounts.User', is_active=True, invite_verified=True) <NEW_LINE> self.thread = mommy.make( 'connectmessages.Thread', group=self.group) <NEW_LINE> sender = mommy.make('accounts.User') <NEW_LINE> sender.add_to_group(self.group.pk) <NEW_LINE> mommy.make( 'connectmessages.Message', thread=self.thread, sender=sender) <NEW_LINE> <DEDENT> def test_thread_is_not_moderated(self): <NEW_LINE> <INDENT> self.assertRaises( ObjectDoesNotExist, Thread.public.get_by_user, **{'thread_id': self.thread.pk, 'user': self.user} ) <NEW_LINE> self.group.private = False <NEW_LINE> self.group.save() <NEW_LINE> self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread ) <NEW_LINE> <DEDENT> def test_user_is_superuser(self): <NEW_LINE> <INDENT> self.user.is_superuser = True <NEW_LINE> self.user.save() <NEW_LINE> self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread ) <NEW_LINE> <DEDENT> def test_user_is_recipient(self): <NEW_LINE> <INDENT> UserThread.objects.create(user=self.user, thread=self.thread) <NEW_LINE> self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread ) <NEW_LINE> <DEDENT> def test_user_is_group_member(self): <NEW_LINE> <INDENT> self.user.add_to_group(self.thread.group.pk) <NEW_LINE> self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread ) <NEW_LINE> <DEDENT> def test_user_is_group_owner(self): <NEW_LINE> <INDENT> self.thread.group.owners.add(self.user) <NEW_LINE> self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread ) <NEW_LINE> <DEDENT> def test_user_does_not_have_access(self): <NEW_LINE> <INDENT> self.assertRaises( ObjectDoesNotExist, Thread.public.get_by_user, **{'thread_id': self.thread.pk, 'user': self.user} ) | Tests for Thread.get_by_user. | 62598fa692d797404e388ada |
class ContactRowSerializer(serializers.Serializer): <NEW_LINE> <INDENT> addresses = serializers.ListField(child=serializers.CharField(), help_text=( 'A list of the contact row\'s addresses. This will never be null, but it may be an ' 'empty list.')) <NEW_LINE> bold = serializers.BooleanField( help_text='Flag indicating if the contact row\'s text is normally displayed in bold.') <NEW_LINE> description = serializers.CharField(help_text='The contact row\'s text.') <NEW_LINE> emails = serializers.ListField(child=serializers.EmailField(), help_text=( 'A list of the contact row\'s email addresses. This will never be null, but it may ' 'be an empty list.')) <NEW_LINE> italic = serializers.BooleanField( help_text='Flag indicating if the contact row\'s text is normally displayed in italics.') <NEW_LINE> people = PersonSummarySerializer(many=True, help_text=( 'A list of the people referred to by the contact row. This will never be null, but it ' 'may be an empty list.')) <NEW_LINE> phoneNumbers = ContactPhoneNumberSerializer(many=True, help_text=( 'A list of the contact row\'s phone numbers. This will never be None, but it may be ' 'an empty list.')) <NEW_LINE> webPages = ContactWebPageSerializer(many=True, help_text=( 'A list of the contact row\'s web pages. This will never be None, but it may be an ' 'empty list.')) | Serializer for IbisContactRow. | 62598fa68e71fb1e983bb99c |
class V1ReloadableComponentConfiguration(object): <NEW_LINE> <INDENT> swagger_types = { 'rest_client': 'V1RESTClientConfiguration' } <NEW_LINE> attribute_map = { 'rest_client': 'restClient' } <NEW_LINE> def __init__(self, rest_client=None): <NEW_LINE> <INDENT> self._rest_client = None <NEW_LINE> if rest_client is not None: <NEW_LINE> <INDENT> self.rest_client = rest_client <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def rest_client(self): <NEW_LINE> <INDENT> return self._rest_client <NEW_LINE> <DEDENT> @rest_client.setter <NEW_LINE> def rest_client(self, rest_client): <NEW_LINE> <INDENT> self._rest_client = rest_client <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in 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 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, V1ReloadableComponentConfiguration): <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. | 62598fa64f88993c371f047f |
class LiveEventInputTrackSelection(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'property': {'key': 'property', 'type': 'str'}, 'operation': {'key': 'operation', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, property: Optional[str] = None, operation: Optional[str] = None, value: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(LiveEventInputTrackSelection, self).__init__(**kwargs) <NEW_LINE> self.property = property <NEW_LINE> self.operation = operation <NEW_LINE> self.value = value | A track selection condition. This property is reserved for future use, any value set on this property will be ignored.
:param property: Property name to select. This property is reserved for future use, any value
set on this property will be ignored.
:type property: str
:param operation: Comparing operation. This property is reserved for future use, any value set
on this property will be ignored.
:type operation: str
:param value: Property value to select. This property is reserved for future use, any value set
on this property will be ignored.
:type value: str | 62598fa616aa5153ce4003ed |
class RosterGroup(object): <NEW_LINE> <INDENT> def __init__(self, name, contacts=None, folded=False): <NEW_LINE> <INDENT> if not contacts: <NEW_LINE> <INDENT> contacts = [] <NEW_LINE> <DEDENT> self.contacts = set(contacts) <NEW_LINE> self.name = name if name is not None else '' <NEW_LINE> self.folded = folded <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.contacts) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Roster_group: %s; %s>' % (self.name, self.contacts) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.contacts) <NEW_LINE> <DEDENT> def __contains__(self, contact): <NEW_LINE> <INDENT> return contact in self.contacts <NEW_LINE> <DEDENT> def add(self, contact): <NEW_LINE> <INDENT> self.contacts.add(contact) <NEW_LINE> <DEDENT> def remove(self, contact): <NEW_LINE> <INDENT> if contact in self.contacts: <NEW_LINE> <INDENT> self.contacts.remove(contact) <NEW_LINE> <DEDENT> <DEDENT> def get_contacts(self, contact_filter=None, sort=''): <NEW_LINE> <INDENT> contact_list = self.contacts.copy() if not contact_filter else [contact for contact in self.contacts.copy() if contact_filter[0](contact, contact_filter[1])] <NEW_LINE> contact_list = sorted(contact_list, key=SORTING_METHODS['name']) <NEW_LINE> for sorting in sort.split(':'): <NEW_LINE> <INDENT> if sorting == 'reverse': <NEW_LINE> <INDENT> contact_list = list(reversed(contact_list)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> method = SORTING_METHODS.get(sorting, lambda x: 0) <NEW_LINE> contact_list = sorted(contact_list, key=method) <NEW_LINE> <DEDENT> <DEDENT> return contact_list <NEW_LINE> <DEDENT> def toggle_folded(self): <NEW_LINE> <INDENT> self.folded = not self.folded <NEW_LINE> if self.folded: <NEW_LINE> <INDENT> if self.name not in roster.folded_groups: <NEW_LINE> <INDENT> roster.folded_groups.add(self.name) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.name in roster.folded_groups: <NEW_LINE> <INDENT> roster.folded_groups.remove(self.name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_nb_connected_contacts(self): <NEW_LINE> <INDENT> return len([1 for contact in self.contacts if len(contact)]) | A RosterGroup is a group containing contacts
It can be Friends/Family etc, but also can be
Online/Offline or whatever | 62598fa656b00c62f0fb279d |
class cmd_processes(Command): <NEW_LINE> <INDENT> synopsis = "%prog [options]" <NEW_LINE> takes_optiongroups = { "sambaopts": options.SambaOptions, "versionopts": options.VersionOptions } <NEW_LINE> takes_options = [ Option("--name", type=str, help="Return only processes associated with one particular name"), Option("--pid", type=int, help="Return only names assoicated with one particular PID"), ] <NEW_LINE> takes_args = [] <NEW_LINE> def run(self, sambaopts, versionopts, section_name=None, name=None, pid=None): <NEW_LINE> <INDENT> lp = sambaopts.get_loadparm() <NEW_LINE> logger = self.get_logger("processes") <NEW_LINE> msg_ctx = Messaging() <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ids = msg_ctx.irpc_servers_byname(name) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> ids = [] <NEW_LINE> <DEDENT> for server_id in ids: <NEW_LINE> <INDENT> self.outf.write("%d\n" % server_id.pid) <NEW_LINE> <DEDENT> <DEDENT> elif pid is not None: <NEW_LINE> <INDENT> names = msg_ctx.irpc_all_servers() <NEW_LINE> for name in names: <NEW_LINE> <INDENT> for server_id in name.ids: <NEW_LINE> <INDENT> if server_id.pid == int(pid): <NEW_LINE> <INDENT> self.outf.write("%s\n" % name.name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> names = msg_ctx.irpc_all_servers() <NEW_LINE> self.outf.write(" Service: PID \n") <NEW_LINE> self.outf.write("-----------------------------\n") <NEW_LINE> for name in names: <NEW_LINE> <INDENT> for server_id in name.ids: <NEW_LINE> <INDENT> self.outf.write("%-16s %6d\n" % (name.name, server_id.pid)) | List processes (to aid debugging on systems without setproctitle). | 62598fa6fff4ab517ebcd6cf |
class UploadCopy(object): <NEW_LINE> <INDENT> def __init__(self, upload, group=None): <NEW_LINE> <INDENT> self.directory = None <NEW_LINE> self.upload = upload <NEW_LINE> self.group = group <NEW_LINE> <DEDENT> def export(self, directory, mode=None, symlink=True, ignore_existing=False): <NEW_LINE> <INDENT> with FilesystemTransaction() as fs: <NEW_LINE> <INDENT> source = self.upload.source <NEW_LINE> queue = self.upload.policy_queue <NEW_LINE> if source is not None: <NEW_LINE> <INDENT> for dsc_file in source.srcfiles: <NEW_LINE> <INDENT> f = dsc_file.poolfile <NEW_LINE> dst = os.path.join(directory, os.path.basename(f.filename)) <NEW_LINE> if not os.path.exists(dst) or not ignore_existing: <NEW_LINE> <INDENT> fs.copy(f.fullpath, dst, mode=mode, symlink=symlink) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for binary in self.upload.binaries: <NEW_LINE> <INDENT> f = binary.poolfile <NEW_LINE> dst = os.path.join(directory, os.path.basename(f.filename)) <NEW_LINE> if not os.path.exists(dst) or not ignore_existing: <NEW_LINE> <INDENT> fs.copy(f.fullpath, dst, mode=mode, symlink=symlink) <NEW_LINE> <DEDENT> <DEDENT> for byhand in self.upload.byhand: <NEW_LINE> <INDENT> src = os.path.join(queue.path, byhand.filename) <NEW_LINE> dst = os.path.join(directory, byhand.filename) <NEW_LINE> if not os.path.exists(dst) or not ignore_existing: <NEW_LINE> <INDENT> fs.copy(src, dst, mode=mode, symlink=symlink) <NEW_LINE> <DEDENT> <DEDENT> src = os.path.join(queue.path, self.upload.changes.changesname) <NEW_LINE> dst = os.path.join(directory, self.upload.changes.changesname) <NEW_LINE> if not os.path.exists(dst) or not ignore_existing: <NEW_LINE> <INDENT> fs.copy(src, dst, mode=mode, symlink=symlink) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> assert self.directory is None <NEW_LINE> mode = 0o0700 <NEW_LINE> symlink = True <NEW_LINE> if self.group is not None: <NEW_LINE> <INDENT> mode = 0o2750 <NEW_LINE> symlink = False <NEW_LINE> <DEDENT> cnf = Config() <NEW_LINE> self.directory = utils.temp_dirname(parent=cnf.get('Dir::TempPath'), mode=mode, group=self.group) <NEW_LINE> self.export(self.directory, symlink=symlink) <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> if self.directory is not None: <NEW_LINE> <INDENT> shutil.rmtree(self.directory) <NEW_LINE> self.directory = None <NEW_LINE> <DEDENT> return None | export a policy queue upload
This class can be used in a with-statement::
with UploadCopy(...) as copy:
...
Doing so will provide a temporary copy of the upload in the directory
given by the C{directory} attribute. The copy will be removed on leaving
the with-block. | 62598fa6d58c6744b42dc24a |
class SafePluginTester(SafeTester): <NEW_LINE> <INDENT> def __init__(self, test_name): <NEW_LINE> <INDENT> SafeTester.__init__(self, test_name) <NEW_LINE> <DEDENT> def set_dir(self): <NEW_LINE> <INDENT> self.working_dir = os.path.join(os.path.join(os.path.join(os.path.dirname(__file__), 'tmp'), self.test_class), self.test_function) <NEW_LINE> self.data_dir = os.path.join(os.path.join(os.path.dirname(__file__), 'data'), self.test_class) | General template for safe "Plugin" modules testing | 62598fa64f6381625f199433 |
class ModelRefMixin: <NEW_LINE> <INDENT> def __init__(self, **kwargs) -> None: <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self._model = lambda: None <NEW_LINE> <DEDENT> @property <NEW_LINE> def model(self) -> "Model": <NEW_LINE> <INDENT> return self.get_model() <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_model(self) -> bool: <NEW_LINE> <INDENT> return self._model() is not None <NEW_LINE> <DEDENT> def get_model(self) -> "Model": <NEW_LINE> <INDENT> model = self._model() <NEW_LINE> if model is None: <NEW_LINE> <INDENT> raise RuntimeError( f"You must add this {type(self).__name__} element to a model instance " f"first." ) <NEW_LINE> <DEDENT> return model <NEW_LINE> <DEDENT> def set_model(self, model: "Model") -> None: <NEW_LINE> <INDENT> self._model = ref(model) | Define a model reference mixin. | 62598fa65166f23b2e2432c2 |
class CurrentGradesByUser(CurrentGrades): <NEW_LINE> <INDENT> def __init__(self, current_grade_list): <NEW_LINE> <INDENT> super(CurrentGradesByUser, self).__init__(current_grade_list) <NEW_LINE> self.username = None <NEW_LINE> self.current_grades = {} <NEW_LINE> for current_grade in current_grade_list: <NEW_LINE> <INDENT> if not isinstance(current_grade, CurrentGrade): <NEW_LINE> <INDENT> raise ValueError("Only CurrentGrade objects are allowed") <NEW_LINE> <DEDENT> self.current_grades[current_grade.course_id] = current_grade <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<Current Grades for user {username}>".format( username=self.username ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def all_course_ids(self): <NEW_LINE> <INDENT> return self.current_grades.keys() <NEW_LINE> <DEDENT> def get_current_grade(self, course_id): <NEW_LINE> <INDENT> return self.current_grades.get(course_id) | Represents the current grades for a specific user | 62598fa60a50d4780f7052c7 |
class Domain(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._tasks = {} <NEW_LINE> <DEDENT> def add_task(self, task): <NEW_LINE> <INDENT> if task.name in self._tasks.keys(): <NEW_LINE> <INDENT> print('Warning: overriding %s with a new task' % task.name) <NEW_LINE> <DEDENT> self._tasks[task.name] = task <NEW_LINE> return task <NEW_LINE> <DEDENT> def find_task(self, task_name): <NEW_LINE> <INDENT> return self._tasks[task_name] <NEW_LINE> <DEDENT> def tasks(self): <NEW_LINE> <INDENT> return self._tasks <NEW_LINE> <DEDENT> def _compile_compound(self, task): <NEW_LINE> <INDENT> methods = task.methods() <NEW_LINE> if len(methods) == 0: <NEW_LINE> <INDENT> print('Compound task %s has no methods' % task.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for method in methods: <NEW_LINE> <INDENT> for subtask_name in method.subtasks(): <NEW_LINE> <INDENT> if subtask_name not in self._tasks.keys(): <NEW_LINE> <INDENT> print('Task %s is using undefined task %s' % (task.name, subtask_name)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def compile(self): <NEW_LINE> <INDENT> for task in self._tasks.values(): <NEW_LINE> <INDENT> if isinstance(task, CompoundTask): <NEW_LINE> <INDENT> self._compile_compound(task) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> result = '' <NEW_LINE> for task in self._tasks.values(): <NEW_LINE> <INDENT> result += '- %s\n' % task.name <NEW_LINE> if isinstance(task, CompoundTask): <NEW_LINE> <INDENT> for method in task.methods(): <NEW_LINE> <INDENT> result += '--- %s\n' % str(method.conditions()) <NEW_LINE> for subtask in method.subtasks(): <NEW_LINE> <INDENT> result += '------ %s\n' % subtask <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return result | A set if possible tasks, some of which can be decomposed
into other tasks. | 62598fa6f548e778e596b490 |
class TestV1EnvFromSource(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testV1EnvFromSource(self): <NEW_LINE> <INDENT> model = kubernetes.client.models.v1_env_from_source.V1EnvFromSource() | V1EnvFromSource unit test stubs | 62598fa60a50d4780f7052c8 |
class ImageSchemaField(FileSchemaField): <NEW_LINE> <INDENT> pass | An image field.
| 62598fa610dbd63aa1c70a9d |
class TestCkanIndex: <NEW_LINE> <INDENT> __external__ = True <NEW_LINE> index = dpm.index.ckan.CkanIndex('http://thedatahub.org/api/') <NEW_LINE> def test_get(self): <NEW_LINE> <INDENT> name = u'ckan' <NEW_LINE> out = self.index.get(name) <NEW_LINE> assert out.name == name <NEW_LINE> <DEDENT> def test_search(self): <NEW_LINE> <INDENT> out = [ x for x in self.index.search('ckanclient') ] <NEW_LINE> assert len(out) == 1, out <NEW_LINE> assert out[0].name in [u'ckanclient'], out[0] | Read only test.
Don't want to duplicate too much of what is in ckanclient tests | 62598fa67b25080760ed7397 |
class Hive_Device_Heating_Boost(Entity): <NEW_LINE> <INDENT> def __init__(self, HiveComponent_HiveObjects): <NEW_LINE> <INDENT> self.HiveObjects = HiveComponent_HiveObjects <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return 'Hive Heating Boost' <NEW_LINE> <DEDENT> @property <NEW_LINE> def force_update(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self.HiveObjects.Get_Heating_Boost() <NEW_LINE> <DEDENT> @property <NEW_LINE> def state_attributes(self): <NEW_LINE> <INDENT> return self.HiveObjects.Get_Heating_Boost_State_Attributes() <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> DeviceIcon = 'mdi:radiator' <NEW_LINE> return DeviceIcon <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.HiveObjects.UpdateData() | Hive Heating current Boost (ON / OFF) | 62598fa691f36d47f2230e19 |
class Movie: <NEW_LINE> <INDENT> def __init__(self, title, poster_image_url, trailer_youtube_url): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.poster_image_url = poster_image_url <NEW_LINE> self.trailer_youtube_url = trailer_youtube_url <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s' % self.title | Movie template for individual movies | 62598fa61f037a2d8b9e3fd7 |
class Actor(nn.Module): <NEW_LINE> <INDENT> def __init__(self, state_size, action_size, seed, fc1_units=200, fc2_units=150): <NEW_LINE> <INDENT> super(Actor, self).__init__() <NEW_LINE> self.seed = torch.manual_seed(seed) <NEW_LINE> self.fc1 = nn.Linear(state_size, fc1_units) <NEW_LINE> self.fc2 = nn.Linear(fc1_units, fc2_units) <NEW_LINE> self.fc3 = nn.Linear(fc2_units, action_size) <NEW_LINE> self.reset_parameters() <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> self.fc1.weight.data.uniform_(*hidden_init(self.fc1)) <NEW_LINE> self.fc2.weight.data.uniform_(*hidden_init(self.fc2)) <NEW_LINE> self.fc3.weight.data.uniform_(-3e-3, 3e-3) <NEW_LINE> <DEDENT> def forward(self, state): <NEW_LINE> <INDENT> x = F.relu(self.fc1(state)) <NEW_LINE> x = F.relu(self.fc2(x)) <NEW_LINE> return F.tanh(self.fc3(x)) | Actor (Policy) Model. | 62598fa64e4d562566372310 |
class AuthorizeKey(object): <NEW_LINE> <INDENT> def __init__(self, ssh_key, user="root"): <NEW_LINE> <INDENT> self.attributes = {} <NEW_LINE> self.attributes["user"] = user <NEW_LINE> self.attributes["key"] = ssh_key <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> runner = ansible_module_runner.AnsibleRunner( ANSIBLE_MODULE_PATH, **self.attributes ) <NEW_LINE> <DEDENT> except ansible_module_runner.AnsibleModuleNotFound: <NEW_LINE> <INDENT> runner = ansible_module_runner.AnsibleRunner( "core/" + ANSIBLE_MODULE_PATH, **self.attributes ) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result, err = runner.run() <NEW_LINE> if 'failed' in result: <NEW_LINE> <INDENT> err = result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.log( "debug", NS.publisher_id, {"message": "Authorize key: %s" % result} ) <NEW_LINE> <DEDENT> <DEDENT> except ansible_module_runner.AnsibleExecutableGenerationFailed as e: <NEW_LINE> <INDENT> logger.log( "debug", NS.publisher_id, {"message": "Copying authorize key failed %s. " "Error: %s" % (self.attributes["_raw_params"], str(e.message)) } ) <NEW_LINE> err = str(e.message) <NEW_LINE> <DEDENT> if err != "": <NEW_LINE> <INDENT> logger.log( "debug", NS.publisher_id, {"message": "Unable to copy authorize key " ".err:%s" % err} ) <NEW_LINE> return False, err <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True, err | AuthorizeKey class is used to copy the given ssh-key
to particular user. A default user is root.
Here ssh_key is mandatory and user is optional.
At the time of initalize it will take user and ssh-key as
parameter.
input:
ssh_key
user(optional)
output:
True/False, None/error | 62598fa61b99ca400228f4a5 |
class ThreeLayerConvNet(object): <NEW_LINE> <INDENT> def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0, dtype=np.float32): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.reg = reg <NEW_LINE> self.dtype = dtype <NEW_LINE> C, H, W = input_dim <NEW_LINE> self.params['W1'] = np.random.randn(num_filters, C, filter_size, filter_size) * weight_scale <NEW_LINE> self.params['W2'] = np.random.randn(num_filters * H * W // 4, hidden_dim) * weight_scale <NEW_LINE> self.params['W3'] = np.random.randn(hidden_dim, num_classes) * weight_scale <NEW_LINE> self.params['b1'] = np.zeros(num_filters) <NEW_LINE> self.params['b2'] = np.zeros(hidden_dim) <NEW_LINE> self.params['b3'] = np.zeros(num_classes) <NEW_LINE> for k, v in self.params.items(): <NEW_LINE> <INDENT> self.params[k] = v.astype(dtype) <NEW_LINE> <DEDENT> <DEDENT> def loss(self, X, y=None): <NEW_LINE> <INDENT> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> W3, b3 = self.params['W3'], self.params['b3'] <NEW_LINE> filter_size = W1.shape[2] <NEW_LINE> conv_param = {'stride': 1, 'pad': (filter_size - 1) // 2} <NEW_LINE> pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2} <NEW_LINE> scores = None <NEW_LINE> conv_out, conv_cahce = conv_relu_pool_forward(X, W1, b1, conv_param, pool_param) <NEW_LINE> hidden_out, hidden_cache = affine_relu_forward(conv_out, W2, b2) <NEW_LINE> scores, scores_cache = affine_forward(hidden_out, W3, b3) <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss, grads = 0, {} <NEW_LINE> loss, dout = softmax_loss(scores, y) <NEW_LINE> loss += self.reg * 0.5 * (np.sum(np.square(W1)) + np.sum(np.square(W2)) + np.sum(np.square(W3))) <NEW_LINE> dscore, dW3, db3 = affine_backward(dout, scores_cache) <NEW_LINE> drelu, dW2, db2 = affine_relu_backward(dscore, hidden_cache) <NEW_LINE> dx, dW1, db1 = conv_relu_pool_backward(drelu, conv_cahce) <NEW_LINE> grads['W1'] = dW1 <NEW_LINE> grads['W2'] = dW2 <NEW_LINE> grads['W3'] = dW3 <NEW_LINE> grads['b1'] = db1 <NEW_LINE> grads['b2'] = db2 <NEW_LINE> grads['b3'] = db3 <NEW_LINE> return loss, grads | A three-layer convolutional network with the following architecture:
conv - relu - 2x2 max pool - affine - relu - affine - softmax
The network operates on minibatches of data that have shape (N, C, H, W)
consisting of N images, each with height H and width W and with C input
channels. | 62598fa6d486a94d0ba2beba |
class ProgressMeter(object): <NEW_LINE> <INDENT> def __init__(self, num_batches, meters, prefix=""): <NEW_LINE> <INDENT> self.batch_fmtstr = self._get_batch_fmtstr(num_batches) <NEW_LINE> self.meters = meters <NEW_LINE> self.prefix = prefix <NEW_LINE> <DEDENT> def display(self, batch): <NEW_LINE> <INDENT> entries = [self.prefix + self.batch_fmtstr.format(batch)] <NEW_LINE> entries += [str(meter) for meter in self.meters] <NEW_LINE> print('\t'.join(entries)) <NEW_LINE> <DEDENT> def _get_batch_fmtstr(self, num_batches): <NEW_LINE> <INDENT> num_digits = len(str(num_batches // 1)) <NEW_LINE> fmt = '{:' + str(num_digits) + 'd}' <NEW_LINE> return '[' + fmt + '/' + fmt.format(num_batches) + ']' | Default PyTorch pogress meter | 62598fa68a43f66fc4bf2069 |
class SourceType(Enum): <NEW_LINE> <INDENT> NONE = None <NEW_LINE> PUSH = None <NEW_LINE> PULL = None <NEW_LINE> def __init__(self, string): <NEW_LINE> <INDENT> Enum.__init__(string) | The ``File.SourceType`` class defines how the file content is retrieved.
.. note::
This class represents an enumerated type in the interface language
definition. The class contains class attributes which represent the
values in the current version of the enumerated type. Newer versions of
the enumerated type may contain new values. To use new values of the
enumerated type in communication with a server that supports the newer
version of the API, you instantiate this class. See :ref:`enumerated
type description page <enumeration_description>`. | 62598fa67d43ff2487427378 |
class ActiveProfileManager(models.Manager): <NEW_LINE> <INDENT> def get_queryset(self): <NEW_LINE> <INDENT> qs = super(ActiveProfileManager, self).get_queryset() <NEW_LINE> return qs.filter(user__is_active=True) | A custom model manager limited only to active profiles | 62598fa67047854f4633f2c5 |
class GameObject(ABC): <NEW_LINE> <INDENT> def __init__(self, pos: typing.Tuple[int, int] = (0, 0), render: str = '', size: typing.Tuple[int, int] = (0, 0)): <NEW_LINE> <INDENT> self.x: int = pos[0] <NEW_LINE> self.y: int = pos[1] <NEW_LINE> self.render: str = render <NEW_LINE> self.delta_time = 0 <NEW_LINE> self.width: int = size[0] <NEW_LINE> self.height: int = size[1] <NEW_LINE> self.__parent = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def parent(self): <NEW_LINE> <INDENT> return self.__parent <NEW_LINE> <DEDENT> def draw(self, board: list): <NEW_LINE> <INDENT> render_text = self.render.split('\n') <NEW_LINE> x, y = int(self.x), int(self.y) <NEW_LINE> if len(render_text) == 1 and render_text[0] == '': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for i in range(len(render_text)): <NEW_LINE> <INDENT> if not (0 <= y - i < len(board)): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> for j in range(len(render_text[i])): <NEW_LINE> <INDENT> if not (0 <= x + j < len(board[0])): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> board[~(y - i)][x + j] = render_text[i][j] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def on_collision(self, other: 'GameObject') -> bool: <NEW_LINE> <INDENT> return ( other.x - other.width <= self.x <= other.x + other.width ) and ( other.y - other.height <= self.y <= other.y + other.height ) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> pass | An abstract base class for pyplayscii game objects. | 62598fa6a219f33f346c6704 |
class Ui_Dialog_Quit(QDialog): <NEW_LINE> <INDENT> save_as_signal = pyqtSignal() <NEW_LINE> do_not_save_signal = pyqtSignal() <NEW_LINE> cancel_signal = pyqtSignal() <NEW_LINE> def __init__(self, database): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.database = database <NEW_LINE> self.bool_exit = False <NEW_LINE> self.setWindowTitle("Confirm exit") <NEW_LINE> label = QLabel(self) <NEW_LINE> label.setText('Do you want to exit without saving ' + self.database.getName() + '?') <NEW_LINE> push_button_save_as = QPushButton("Save", self) <NEW_LINE> push_button_do_not_save = QPushButton("Do not save", self) <NEW_LINE> push_button_cancel = QPushButton("Cancel", self) <NEW_LINE> hbox = QHBoxLayout() <NEW_LINE> hbox.addStretch(1) <NEW_LINE> hbox.addWidget(push_button_save_as) <NEW_LINE> hbox.addWidget(push_button_do_not_save) <NEW_LINE> hbox.addWidget(push_button_cancel) <NEW_LINE> hbox.addStretch(1) <NEW_LINE> vbox = QVBoxLayout() <NEW_LINE> vbox.addWidget(label) <NEW_LINE> vbox.addLayout(hbox) <NEW_LINE> self.setLayout(vbox) <NEW_LINE> push_button_save_as.clicked.connect(self.save_as_clicked) <NEW_LINE> push_button_do_not_save.clicked.connect(self.do_not_save_clicked) <NEW_LINE> push_button_cancel.clicked.connect(self.cancel_clicked) <NEW_LINE> <DEDENT> def save_as_clicked(self): <NEW_LINE> <INDENT> self.save_as_signal.emit() <NEW_LINE> self.bool_exit = True <NEW_LINE> self.close() <NEW_LINE> <DEDENT> def do_not_save_clicked(self): <NEW_LINE> <INDENT> self.bool_exit = True <NEW_LINE> self.close() <NEW_LINE> <DEDENT> def cancel_clicked(self): <NEW_LINE> <INDENT> self.bool_exit = False <NEW_LINE> self.close() <NEW_LINE> <DEDENT> def can_exit(self): <NEW_LINE> <INDENT> return self.bool_exit | Is called when the user closes the software and the current project
has been modified | 62598fa63317a56b869be4c0 |
class ListCosEnableRegionResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.EnableRegions = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("EnableRegions") is not None: <NEW_LINE> <INDENT> self.EnableRegions = [] <NEW_LINE> for item in params.get("EnableRegions"): <NEW_LINE> <INDENT> obj = CosRegionInfo() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.EnableRegions.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RequestId = params.get("RequestId") | `ListCosEnableRegion` response parameters structure
| 62598fa6eab8aa0e5d30bc76 |
class BoundPinnedRow(BoundRow): <NEW_LINE> <INDENT> @property <NEW_LINE> def attrs(self): <NEW_LINE> <INDENT> row_attrs = computed_values(self._table.pinned_row_attrs, self._record) <NEW_LINE> css_class = ' '.join([ self.get_even_odd_css_class(), 'pinned-row', row_attrs.get('class', '') ]) <NEW_LINE> row_attrs['class'] = css_class <NEW_LINE> return AttributeDict(row_attrs) <NEW_LINE> <DEDENT> def _get_and_render_with(self, name, render_func, default): <NEW_LINE> <INDENT> accessor = A(name) <NEW_LINE> value = accessor.resolve(context=self._record, quiet=True) or default <NEW_LINE> return value | Represents a *pinned* row in a table.
Inherited from BoundRow. | 62598fa6b7558d589546351c |
class none(): <NEW_LINE> <INDENT> def run(self, model): <NEW_LINE> <INDENT> pass | Just output populate without do nonthing | 62598fa616aa5153ce4003ef |
class IgnoreAttribute: <NEW_LINE> <INDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter([self, ]) | This is a hack to let Spyne not append elements, which weren't asked in the scope. | 62598fa63539df3088ecc1a1 |
@dataclasses.dataclass(frozen=True) <NEW_LINE> class UserApplicationService: <NEW_LINE> <INDENT> _user_repository: Final[IUserRepository] <NEW_LINE> _user_service: Final[UserService] <NEW_LINE> def register(self, name: str): <NEW_LINE> <INDENT> user : User = User(UserName(name)) <NEW_LINE> if self._user_service.exists(user): <NEW_LINE> <INDENT> raise CanNotRegisterUserException(user, "ユーザはすでに存在しています") <NEW_LINE> <DEDENT> self._user_repository.save(user) <NEW_LINE> <DEDENT> def get(self, user_id: str) -> Optional[UserData]: <NEW_LINE> <INDENT> target_id: UserId = UserId(user_id) <NEW_LINE> user: User = self._user_repository.find_by_id(target_id) <NEW_LINE> if user is None: return None <NEW_LINE> return UserData(user) <NEW_LINE> <DEDENT> def update(self, command: UserUpdateCommand): <NEW_LINE> <INDENT> target_id: UserId = UserId(command.id) <NEW_LINE> user: Optional[User] = self._user_repository.find_by_id(target_id) <NEW_LINE> if user is None: raise UserNotFoundException(target_id) <NEW_LINE> name: Optional[str] = command.name <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> new_user_name: UserName = UserName(name) <NEW_LINE> user.change_name(new_user_name) <NEW_LINE> if self._user_service.exists(user): <NEW_LINE> <INDENT> raise CanNotRegisterUserException(user, "ユーザはすでに存在しています") <NEW_LINE> <DEDENT> <DEDENT> mail_address: Optional[str] = command.mail_address <NEW_LINE> if mail_address is not None: <NEW_LINE> <INDENT> new_mail_address: MailAddress = MailAddress(mail_address) <NEW_LINE> user.change_mail_address(new_mail_address) <NEW_LINE> <DEDENT> self._user_repository.save(user) | ユーザのアプリケーションサービス
Attributes:
_user_repository (IUserRepository): ユーザのレポジトリ
_user_service (UserService): ユーザのドメインサービス | 62598fa6e5267d203ee6b7f9 |
class QNNParam: <NEW_LINE> <INDENT> def __init__(self, weight, bias, scale, zero_point): <NEW_LINE> <INDENT> self.weight = weight <NEW_LINE> if bias is not None: <NEW_LINE> <INDENT> self.bias = bias.detach().numpy() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.bias = None <NEW_LINE> <DEDENT> self.scale = _expr.const(scale) <NEW_LINE> self.zero_point = _expr.const(zero_point, dtype="int32") | A placeholder for weight quantization parameters | 62598fa676e4537e8c3ef499 |
class ExpectimaxAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> score, action = self.maxFunction(gameState, self.depth) <NEW_LINE> return action <NEW_LINE> <DEDENT> def maxFunction(self, gameState, depth): <NEW_LINE> <INDENT> if depth == 0 or gameState.isWin() or gameState.isLose(): <NEW_LINE> <INDENT> return self.evaluationFunction(gameState), "noMove" <NEW_LINE> <DEDENT> legalAction = gameState.getLegalActions() <NEW_LINE> val = [] <NEW_LINE> act = [] <NEW_LINE> for action in legalAction: <NEW_LINE> <INDENT> scoreVal, scoreAct = self.minFunction(gameState.generateSuccessor(self.index, action), depth, 1) <NEW_LINE> val.append(scoreVal) <NEW_LINE> act.append(scoreAct) <NEW_LINE> <DEDENT> alpha = max(val) <NEW_LINE> for i in range(len(val)): <NEW_LINE> <INDENT> if val[i] == alpha: alphaIdx = i <NEW_LINE> <DEDENT> bestIndex = alphaIdx <NEW_LINE> return alpha, legalAction[bestIndex] <NEW_LINE> <DEDENT> def minFunction(self, gameState, depth, agent): <NEW_LINE> <INDENT> if depth == 0 or gameState.isWin() or gameState.isLose(): <NEW_LINE> <INDENT> return self.evaluationFunction(gameState), "noMove" <NEW_LINE> <DEDENT> ghostCount = gameState.getNumAgents() - 1 <NEW_LINE> legalAction = gameState.getLegalActions(agent) <NEW_LINE> val = [] <NEW_LINE> act = [] <NEW_LINE> if agent != ghostCount: <NEW_LINE> <INDENT> for action in legalAction: <NEW_LINE> <INDENT> scoreVal , scoreAct = self.minFunction(gameState.generateSuccessor(agent, action), depth, agent + 1) <NEW_LINE> val.append(scoreVal) <NEW_LINE> act.append(scoreAct) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for action in legalAction: <NEW_LINE> <INDENT> scoreVal, scoreAct = self.maxFunction(gameState.generateSuccessor(agent, action), (depth - 1)) <NEW_LINE> val.append(scoreVal) <NEW_LINE> act.append(scoreAct) <NEW_LINE> <DEDENT> <DEDENT> valSum = 0 <NEW_LINE> for i in range(len(val)): <NEW_LINE> <INDENT> valSum += val[i] <NEW_LINE> <DEDENT> beta = valSum / len(val) <NEW_LINE> leastIndex = random.randint(0, len(val) - 1) <NEW_LINE> return beta, legalAction[leastIndex] | Your expectimax agent (question 4) | 62598fa67cff6e4e811b5916 |
class GDCClient(object): <NEW_LINE> <INDENT> def __init__(self, host=GDC_API_HOST, port=GDC_API_PORT, token=None): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.token = token <NEW_LINE> self.session = requests.Session() <NEW_LINE> agent = " ".join( [ "GDC-Client/{version}".format(version=version.__version__), self.session.headers.get("User-Agent", "Unknown"), ] ) <NEW_LINE> self.session.headers = { "User-Agent": agent, } <NEW_LINE> <DEDENT> @contextmanager <NEW_LINE> def request(self, verb, path, **kwargs): <NEW_LINE> <INDENT> res = self.session.request( verb, "https://{host}:{port}{path}".format( host=self.host, port=self.port, path=path, ), auth=auth.GDCTokenAuth(self.token), **kwargs ) <NEW_LINE> with closing(res): <NEW_LINE> <INDENT> yield res <NEW_LINE> <DEDENT> <DEDENT> def get(self, path, **kwargs): <NEW_LINE> <INDENT> return self.request("GET", path, **kwargs) <NEW_LINE> <DEDENT> def put(self, path, **kwargs): <NEW_LINE> <INDENT> return self.request("PUT", path, **kwargs) <NEW_LINE> <DEDENT> def post(self, path, **kwargs): <NEW_LINE> <INDENT> return self.request("POST", path, **kwargs) <NEW_LINE> <DEDENT> def head(self, path, **kwargs): <NEW_LINE> <INDENT> return self.request("HEAD", path, **kwargs) <NEW_LINE> <DEDENT> def patch(self, path, **kwargs): <NEW_LINE> <INDENT> return self.request("PATCH", path, **kwargs) <NEW_LINE> <DEDENT> def delete(self, path, **kwargs): <NEW_LINE> <INDENT> return self.request("DELETE", path, **kwargs) | GDC API Requests Client
| 62598fa65fdd1c0f98e5de85 |
class EthereumAddressField(serializers.Field): <NEW_LINE> <INDENT> def __init__(self, allow_zero_address=False, allow_sentinel_address=False, **kwargs): <NEW_LINE> <INDENT> self.allow_zero_address = allow_zero_address <NEW_LINE> self.allow_sentinel_address = allow_sentinel_address <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> <DEDENT> def to_representation(self, obj): <NEW_LINE> <INDENT> return obj <NEW_LINE> <DEDENT> def to_internal_value(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if checksum_encode(data) != data: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> elif int(data, 16) == 0 and not self.allow_zero_address: <NEW_LINE> <INDENT> raise ValidationError("0x0 address is not allowed") <NEW_LINE> <DEDENT> elif int(data, 16) == 1 and not self.allow_sentinel_address: <NEW_LINE> <INDENT> raise ValidationError("0x1 address is not allowed") <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValidationError("Address %s is not checksumed" % data) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise ValidationError("Address %s is not valid" % data) <NEW_LINE> <DEDENT> return data | Ethereum address checksumed
https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md | 62598fa6d58c6744b42dc24b |
class PQuestActionOp(Parsing.Precedence): <NEW_LINE> <INDENT> pass | %left pQuestActionOp >pAttrKey | 62598fa63617ad0b5ee06040 |
class UserIdentity(models.Model): <NEW_LINE> <INDENT> identity = models.CharField(max_length=50, blank=False, unique=True, choices=AUTH_CHOICES, default=VISITOR_USER, verbose_name="身份级别") <NEW_LINE> auth_groups = models.ManyToManyField(User, related_name="identities") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = "登录权限" <NEW_LINE> verbose_name_plural = "登录权限" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.get_identity_display() | Login User identity: AdminStaff, AdminSystem, Expert, SchoolTeam, visitor,
Teacher, Student | 62598fa65f7d997b871f9357 |
class Stack(MeanFunction): <NEW_LINE> <INDENT> def __init__(self, list_of_means): <NEW_LINE> <INDENT> output_dim = 0 <NEW_LINE> for m in list_of_means: <NEW_LINE> <INDENT> output_dim += m.output_dim <NEW_LINE> <DEDENT> MeanFunction.__init__(self, output_dim) <NEW_LINE> self.mean_list = ParamList(list_of_means) <NEW_LINE> <DEDENT> def __call__(self, X): <NEW_LINE> <INDENT> return tf.concat(1, [l(X) for l in self.mean_list]) | Mean function that returns multiple kinds of mean values, stacked
vertically.
Input for the initializer is a list of MeanFunctions, [m_1,m_2,...,m_M].
The function call returns [m_1(X),m_2(X),...,m_M(X)].
The size of the return is n x (sum_i m_i.output_dim). | 62598fa626068e7796d4c847 |
class GRNTestNtf(GRANITEISIMessage): <NEW_LINE> <INDENT> notify = None <NEW_LINE> def __init__(self, **isi_message_fields): <NEW_LINE> <INDENT> debug.vrb("GRNTestNtf: __init__()") <NEW_LINE> GRANITEISIMessage.__init__(self, **isi_message_fields) <NEW_LINE> self.initDefaults( msg_id = None) <NEW_LINE> self.assertFields( msg_id = inc.GRN_TEST_NTF) <NEW_LINE> <DEDENT> def _get_msg_id_str(self): <NEW_LINE> <INDENT> debug.vrb("GRNTestNtf: _get_msg_id_str()") <NEW_LINE> return 'GRN_TEST_NTF' <NEW_LINE> <DEDENT> def _get_msg_data(self): <NEW_LINE> <INDENT> debug.vrb("GRNTestNtf: _get_msg_data()") <NEW_LINE> return xpack('>B', self.msg_id) <NEW_LINE> <DEDENT> def _check_set_msg_data(self, new_msg_data): <NEW_LINE> <INDENT> debug.vrb("GRNTestNtf: _check_set_msg_data()") <NEW_LINE> self.failFieldUnless('"msg_id check"', self.msg_id == inc.GRN_TEST_NTF, 'Invalid msg_id: %s in GRN_TEST_NTF!' % str(self.msg_id)) <NEW_LINE> self.failFieldUnless('"msg_data check"', len(new_msg_data) >= 6, 'GRN_TEST_NTF msg_data was invalid') <NEW_LINE> GRNTestNtf.notify = new_msg_data[3] <NEW_LINE> valid_notify_names = [ 'GRN_NTF_NONE', 'GRN_NTF_PARSE_START', 'GRN_NTF_PARSE_CONTINUE', 'GRN_NTF_PARSE_DONE', 'GRN_NTF_RUN_START', 'GRN_NTF_RUN_DONE'] <NEW_LINE> valid_notify_values = _lookupNames(valid_notify_names) <NEW_LINE> if not GRNTestNtf.notify in valid_notify_values: <NEW_LINE> <INDENT> debug.vrb('Invalid notify in GRN_TEST_NTF: %d' % GRNTestNtf.notify) <NEW_LINE> <DEDENT> return new_msg_data | ISI message class for GRN_TEST_NTF
Parameters Data type
- isi_message ISIMessage instance
Fields Data type
- msg_id integer
- notify integer (not an isi field) | 62598fa6fff4ab517ebcd6d2 |
class Device(_AttributeKind): <NEW_LINE> <INDENT> pass | Represents a device for ``AutoDB`` to process.
| 62598fa666673b3332c302b7 |
class valoresViewSet(APIView): <NEW_LINE> <INDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> datos = (request.data) <NEW_LINE> password = datos['password'] <NEW_LINE> register = User(username = datos['username'], first_name = datos['first_name'], last_name = datos['last_name'], is_staff = datos['is_staff'], email = datos['email']) <NEW_LINE> register.set_password(password) <NEW_LINE> register.save() <NEW_LINE> return HttpResponse(status=200) | Recollemos valores do formulario de alta | 62598fa691f36d47f2230e1a |
class Room(Enum): <NEW_LINE> <INDENT> BALLROOM = 'BALLROOM' <NEW_LINE> BILLIARD_ROOM = 'BILLIARD_ROOM' <NEW_LINE> CONSERVATORY = 'CONSERVATORY' <NEW_LINE> DINING_ROOM = 'DINING_ROOM' <NEW_LINE> HALL = 'HALL' <NEW_LINE> KITCHEN = 'KITCHEN' <NEW_LINE> LIBRARY = 'LIBRARY' <NEW_LINE> LOUNGE = 'LOUNGE' <NEW_LINE> STUDY = 'STUDY' | The set of locations where the murder may have occurred. | 62598fa685dfad0860cbf9eb |
class CreateTargetGroupResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TargetGroupId = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TargetGroupId = params.get("TargetGroupId") <NEW_LINE> self.RequestId = params.get("RequestId") | CreateTargetGroup返回参数结构体
| 62598fa64e4d562566372312 |
class MaxAndSkip(gym.Wrapper): <NEW_LINE> <INDENT> def __init__(self, env, skip=4): <NEW_LINE> <INDENT> super().__init__(env) <NEW_LINE> self._obs_buffer = np.zeros((2, ) + env.observation_space.shape, dtype=np.uint8) <NEW_LINE> self._skip = skip <NEW_LINE> <DEDENT> def step(self, action): <NEW_LINE> <INDENT> total_reward = 0.0 <NEW_LINE> done = None <NEW_LINE> for i in range(self._skip): <NEW_LINE> <INDENT> obs, reward, done, info = self.env.step(action) <NEW_LINE> if i == self._skip - 2: <NEW_LINE> <INDENT> self._obs_buffer[0] = obs <NEW_LINE> <DEDENT> elif i == self._skip - 1: <NEW_LINE> <INDENT> self._obs_buffer[1] = obs <NEW_LINE> <DEDENT> total_reward += reward <NEW_LINE> if done: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> max_frame = self._obs_buffer.max(axis=0) <NEW_LINE> return max_frame, total_reward, done, info <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> return self.env.reset() | Max and skip wrapper for gym.Env.
It returns only every `skip`-th frame. Action are repeated and rewards are
sum for the skipped frames.
It also takes element-wise maximum over the last two consecutive frames,
which helps algorithm deal with the problem of how certain Atari games only
render their sprites every other game frame.
Args:
env: The environment to be wrapped.
skip: The environment only returns `skip`-th frame. | 62598fa699cbb53fe6830dc3 |
class Attention(nn.Module): <NEW_LINE> <INDENT> def __init__(self, dimensions, attention_type="general", device=torch.device('cpu')): <NEW_LINE> <INDENT> super(Attention, self).__init__() <NEW_LINE> if attention_type not in ["dot", "general"]: <NEW_LINE> <INDENT> raise ValueError("Invalid attention type selected.") <NEW_LINE> <DEDENT> self.device = device <NEW_LINE> self.attention_type = attention_type <NEW_LINE> if self.attention_type == "general": <NEW_LINE> <INDENT> self.linear_in = nn.Linear(dimensions, dimensions, bias=True) <NEW_LINE> <DEDENT> self.linear_out = nn.Linear(dimensions * 2, dimensions, bias=True) <NEW_LINE> self.softmax = nn.Softmax(dim=-1) <NEW_LINE> self.tanh = nn.Tanh() <NEW_LINE> <DEDENT> def forward(self, query, context, query_mask=None, context_mask=None, temperature=1.): <NEW_LINE> <INDENT> batch_size, output_len, dimensions = query.size() <NEW_LINE> context_len = context.size(1) <NEW_LINE> if query_mask is not None: <NEW_LINE> <INDENT> query_mask = query_mask.float() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query_mask = torch.ones_like(query, dtype=torch.float, device=self.device) <NEW_LINE> <DEDENT> if context_mask is not None: <NEW_LINE> <INDENT> context_mask = context_mask.float() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context_mask = torch.ones_like(context, dtype=torch.float, device=self.device) <NEW_LINE> <DEDENT> bit_att_mask = torch.bmm(query_mask[:, :, 0].unsqueeze(-1), context_mask[:, :, 0].unsqueeze(-1).transpose(1, 2)) <NEW_LINE> extended_attention_mask = (1. - bit_att_mask) * -10000.0 <NEW_LINE> if self.attention_type == "general": <NEW_LINE> <INDENT> query = query.reshape(batch_size * output_len, dimensions) <NEW_LINE> query = self.linear_in(query) <NEW_LINE> query = query.reshape(batch_size, output_len, dimensions) <NEW_LINE> <DEDENT> attention_scores = torch.bmm(query, context.transpose(1, 2).contiguous()) + extended_attention_mask <NEW_LINE> attention_scores = attention_scores.view(batch_size * output_len, context_len) <NEW_LINE> attention_weights = self.softmax(attention_scores / temperature) <NEW_LINE> attention_weights = attention_weights.view(batch_size, output_len, context_len) <NEW_LINE> mix = torch.bmm(attention_weights, context) <NEW_LINE> combined = torch.cat((mix, query), dim=2) <NEW_LINE> combined = combined.view(batch_size * output_len, 2 * dimensions) <NEW_LINE> output = self.linear_out(combined).view(batch_size, output_len, dimensions) <NEW_LINE> output = self.tanh(output) <NEW_LINE> return output, attention_weights | Applies attention mechanism on the `context` using the `query`.
**Thank you** to IBM for their initial implementation of :class:`Attention`. Here is
their `License
<https://github.com/IBM/pytorch-seq2seq/blob/master/LICENSE>`__.
Args:
dimensions (int): Dimensionality of the query and context.
attention_type (str, optional): How to compute the attention score:
* dot: :math:`score(H_j,q) = H_j^T q`
* general: :math:`score(H_j, q) = H_j^T W_a q`
Example:
>>> attention = Attention(256)
>>> query = torch.randn(5, 1, 256)
>>> context = torch.randn(5, 5, 256)
>>> output, weights = attention(query, context)
>>> output.size()
torch.Size([5, 1, 256])
>>> weights.size()
torch.Size([5, 1, 5]) | 62598fa66aa9bd52df0d4db7 |
class SimpleStemIN(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_w, out_w): <NEW_LINE> <INDENT> super(SimpleStemIN, self).__init__() <NEW_LINE> self._construct(in_w, out_w) <NEW_LINE> <DEDENT> def _construct(self, in_w, out_w): <NEW_LINE> <INDENT> self.conv = nn.Conv2d( in_w, out_w, kernel_size=3, stride=2, padding=1, bias=False ) <NEW_LINE> self.bn = BN(out_w) <NEW_LINE> self.relu = nn.ReLU(True) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> for layer in self.children(): <NEW_LINE> <INDENT> x = layer(x) <NEW_LINE> <DEDENT> return x | Simple stem for ImageNet. | 62598fa6dd821e528d6d8e23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.