code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Float(Field): <NEW_LINE> <INDENT> type = 'float' <NEW_LINE> _slots = { '_digits': None, 'group_operator': 'sum', } <NEW_LINE> def __init__(self, string=Default, digits=Default, **kwargs): <NEW_LINE> <INDENT> super(Float, self).__init__(string=string, _digits=digits, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def digits(self): <NEW_LINE> <INDENT> if callable(self._digits): <NEW_LINE> <INDENT> with LazyCursor() as cr: <NEW_LINE> <INDENT> return self._digits(cr) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return self._digits <NEW_LINE> <DEDENT> <DEDENT> _related__digits = property(attrgetter('_digits')) <NEW_LINE> _description_digits = property(attrgetter('digits')) <NEW_LINE> _column_digits = property(lambda self: not callable(self._digits) and self._digits) <NEW_LINE> _column_digits_compute = property(lambda self: callable(self._digits) and self._digits) <NEW_LINE> def convert_to_cache(self, value, record, validate=True): <NEW_LINE> <INDENT> value = float(value or 0.0) <NEW_LINE> if not validate: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> digits = self.digits <NEW_LINE> return float_round(value, precision_digits=digits[1]) if digits else value <NEW_LINE> <DEDENT> def convert_to_export(self, value, record): <NEW_LINE> <INDENT> if value or value == 0.0: <NEW_LINE> <INDENT> return value if record._context.get('export_raw_data') else ustr(value) <NEW_LINE> <DEDENT> return '' | The precision digits are given by the attribute
:param digits: a pair (total, decimal), or a function taking a database
cursor and returning a pair (total, decimal) | 62598fa3a17c0f6771d5c0da |
class TestItemVariationLocationOverrides(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 testItemVariationLocationOverrides(self): <NEW_LINE> <INDENT> model = squareconnect.models.item_variation_location_overrides.ItemVariationLocationOverrides() | ItemVariationLocationOverrides unit test stubs | 62598fa3d268445f26639ad4 |
class OsramLightifyLight(Light): <NEW_LINE> <INDENT> def __init__(self, light_id, light, update_lights): <NEW_LINE> <INDENT> self._light = light <NEW_LINE> self._light_id = light_id <NEW_LINE> self.update_lights = update_lights <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._light.name() <NEW_LINE> <DEDENT> @property <NEW_LINE> def rgb_color(self): <NEW_LINE> <INDENT> return self._light.rgb() <NEW_LINE> <DEDENT> @property <NEW_LINE> def color_temp(self): <NEW_LINE> <INDENT> o_temp = self._light.temp() <NEW_LINE> temperature = int(TEMP_MIN_HASS + (TEMP_MAX_HASS - TEMP_MIN_HASS) * (o_temp - TEMP_MIN) / (TEMP_MAX - TEMP_MIN)) <NEW_LINE> return temperature <NEW_LINE> <DEDENT> @property <NEW_LINE> def brightness(self): <NEW_LINE> <INDENT> return int(self._light.lum() * 2.55) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> self.update_lights() <NEW_LINE> _LOGGER.debug("is_on light state for light: %s is: %s", self._light.name(), self._light.on()) <NEW_LINE> return self._light.on() <NEW_LINE> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> brightness = 100 <NEW_LINE> if self.brightness: <NEW_LINE> <INDENT> brightness = int(self.brightness / 2.55) <NEW_LINE> <DEDENT> if ATTR_TRANSITION in kwargs: <NEW_LINE> <INDENT> fade = kwargs[ATTR_TRANSITION] * 10 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fade = 0 <NEW_LINE> <DEDENT> if ATTR_RGB_COLOR in kwargs: <NEW_LINE> <INDENT> red, green, blue = kwargs[ATTR_RGB_COLOR] <NEW_LINE> self._light.set_rgb(red, green, blue, fade) <NEW_LINE> <DEDENT> if ATTR_BRIGHTNESS in kwargs: <NEW_LINE> <INDENT> brightness = int(kwargs[ATTR_BRIGHTNESS] / 2.55) <NEW_LINE> <DEDENT> if ATTR_COLOR_TEMP in kwargs: <NEW_LINE> <INDENT> color_t = kwargs[ATTR_COLOR_TEMP] <NEW_LINE> kelvin = int(((TEMP_MAX - TEMP_MIN) * (color_t - TEMP_MIN_HASS) / (TEMP_MAX_HASS - TEMP_MIN_HASS)) + TEMP_MIN) <NEW_LINE> self._light.set_temperature(kelvin, fade) <NEW_LINE> <DEDENT> self._light.set_luminance(brightness, fade) <NEW_LINE> self.update_ha_state() <NEW_LINE> <DEDENT> def turn_off(self, **kwargs): <NEW_LINE> <INDENT> if ATTR_TRANSITION in kwargs: <NEW_LINE> <INDENT> fade = kwargs[ATTR_TRANSITION] * 10 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fade = 0 <NEW_LINE> <DEDENT> self._light.set_luminance(0, fade) <NEW_LINE> self.update_ha_state() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.update_lights(no_throttle=True) | Defines an Osram Lightify Light. | 62598fa3a8370b77170f027c |
class Squad(tfds.core.GeneratorBasedBuilder): <NEW_LINE> <INDENT> _URL = "https://rajpurkar.github.io/SQuAD-explorer/dataset/" <NEW_LINE> _DEV_FILE = "dev-v1.1.json" <NEW_LINE> _TRAINING_FILE = "train-v1.1.json" <NEW_LINE> BUILDER_CONFIGS = [ SquadConfig( name="plain_text", version=tfds.core.Version( "1.0.0", "New split API (https://tensorflow.org/datasets/splits)"), description="Plain text", ), ] <NEW_LINE> def _info(self): <NEW_LINE> <INDENT> return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ "id": tf.string, "title": tfds.features.Text(), "context": tfds.features.Text(), "question": tfds.features.Text(), "answers": tfds.features.Sequence({ "text": tfds.features.Text(), "answer_start": tf.int32, }), }), supervised_keys=None, homepage="https://rajpurkar.github.io/SQuAD-explorer/", citation=_CITATION, ) <NEW_LINE> <DEDENT> def _split_generators(self, dl_manager): <NEW_LINE> <INDENT> urls_to_download = { "train": os.path.join(self._URL, self._TRAINING_FILE), "dev": os.path.join(self._URL, self._DEV_FILE) } <NEW_LINE> downloaded_files = dl_manager.download_and_extract(urls_to_download) <NEW_LINE> return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, gen_kwargs={"filepath": downloaded_files["train"]}), tfds.core.SplitGenerator( name=tfds.Split.VALIDATION, gen_kwargs={"filepath": downloaded_files["dev"]}), ] <NEW_LINE> <DEDENT> def _generate_examples(self, filepath): <NEW_LINE> <INDENT> logging.info("generating examples from = %s", filepath) <NEW_LINE> with tf.io.gfile.GFile(filepath) as f: <NEW_LINE> <INDENT> squad = json.load(f) <NEW_LINE> for article in squad["data"]: <NEW_LINE> <INDENT> title = article.get("title", "").strip() <NEW_LINE> for paragraph in article["paragraphs"]: <NEW_LINE> <INDENT> context = paragraph["context"].strip() <NEW_LINE> for qa in paragraph["qas"]: <NEW_LINE> <INDENT> question = qa["question"].strip() <NEW_LINE> id_ = qa["id"] <NEW_LINE> answer_starts = [answer["answer_start"] for answer in qa["answers"]] <NEW_LINE> answers = [answer["text"].strip() for answer in qa["answers"]] <NEW_LINE> yield id_, { "title": title, "context": context, "question": question, "id": id_, "answers": { "answer_start": answer_starts, "text": answers, }, } | SQUAD: The Stanford Question Answering Dataset. Version 1.1. | 62598fa3cb5e8a47e493c0c8 |
class Do(Token): <NEW_LINE> <INDENT> __slots__ = ('body', 'counter', 'first', 'last', 'step', 'concurrent') <NEW_LINE> defaults = {'step': Integer(1), 'concurrent': false} <NEW_LINE> _construct_body = staticmethod(lambda body: CodeBlock(*body)) <NEW_LINE> _construct_counter = staticmethod(sympify) <NEW_LINE> _construct_first = staticmethod(sympify) <NEW_LINE> _construct_last = staticmethod(sympify) <NEW_LINE> _construct_step = staticmethod(sympify) <NEW_LINE> _construct_concurrent = staticmethod(lambda arg: true if arg else false) | Represents a Do loop in in Fortran.
Examples
========
>>> from sympy import fcode, symbols
>>> from sympy.codegen.ast import aug_assign, Print
>>> from sympy.codegen.fnodes import Do
>>> i, n = symbols('i n', integer=True)
>>> r = symbols('r', real=True)
>>> body = [aug_assign(r, '+', 1/i), Print([i, r])]
>>> do1 = Do(body, i, 1, n)
>>> print(fcode(do1, source_format='free'))
do i = 1, n
r = r + 1d0/i
print *, i, r
end do
>>> do2 = Do(body, i, 1, n, 2)
>>> print(fcode(do2, source_format='free'))
do i = 1, n, 2
r = r + 1d0/i
print *, i, r
end do | 62598fa301c39578d7f12c22 |
class TestAddToQueue: <NEW_LINE> <INDENT> def test_add_to_queue(self, soco): <NEW_LINE> <INDENT> old_queue = soco.get_queue(0, 1000) <NEW_LINE> assert (soco.add_to_queue(old_queue[-1])) == len(old_queue) + 1 <NEW_LINE> wait() <NEW_LINE> new_queue = soco.get_queue() <NEW_LINE> assert (len(new_queue) - 1) == len(old_queue) <NEW_LINE> assert (new_queue[-1].title) == (new_queue[-2].title) | Integration test for the add_to_queue method. | 62598fa32ae34c7f260aaf84 |
class kvget_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'key', None, None, ), ) <NEW_LINE> def __init__(self, key=None,): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.key = iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('kvget_args') <NEW_LINE> if self.key is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('key', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.key) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.key) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- key | 62598fa30c0af96317c56225 |
class ModelForm(BaseModelForm): <NEW_LINE> <INDENT> __metaclass__ = ModelFormMetaclass | All model forms must inherit from this class | 62598fa37b25080760ed734d |
class Pais(models.Model): <NEW_LINE> <INDENT> cod_iso = models.CharField(max_length=3, blank=True, null=True) <NEW_LINE> nombre = models.CharField(max_length=255, blank=True, null=True) <NEW_LINE> nombre_iso = models.CharField(max_length=255, blank=True, null=True) <NEW_LINE> alfa2 = models.CharField(max_length=2, blank=True, null=True) <NEW_LINE> alfa3 = models.CharField(max_length=3, blank=True, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.nombre <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'pais' | Gestión de paises
| 62598fa367a9b606de545e6e |
class SimpleFCN(BaseModel): <NEW_LINE> <INDENT> def __init__(self, prefix, data_description, modality, output_dir=None, **config): <NEW_LINE> <INDENT> self.prefix = prefix <NEW_LINE> self.modality = modality <NEW_LINE> standard_config = { 'train_encoder': True, 'dropout_rate': 0 } <NEW_LINE> standard_config.update(config) <NEW_LINE> BaseModel.__init__(self, data_description, output_dir=output_dir, **standard_config) <NEW_LINE> <DEDENT> def _build_graph(self, train_data, test_data): <NEW_LINE> <INDENT> with tf.name_scope('training'): <NEW_LINE> <INDENT> train_x = train_data[self.modality] <NEW_LINE> train_y = tf.to_float(train_data['labels']) <NEW_LINE> layers = fcn(train_x, self.prefix, self.config['num_units'], self.config['num_classes'], is_training=True, batchnorm=self.config['batch_normalization']) <NEW_LINE> prob = tf.nn.log_softmax(layers['score'], name='prob') <NEW_LINE> self.loss = cross_entropy(prob, train_y) <NEW_LINE> self.train_y = train_y <NEW_LINE> <DEDENT> with tf.name_scope('testing'): <NEW_LINE> <INDENT> test_x = test_data[self.modality] <NEW_LINE> layers = fcn(test_x, self.prefix, self.config['num_units'], self.config['num_classes'], is_training=False, batchnorm=self.config['batch_normalization']) <NEW_LINE> prob = tf.nn.softmax(layers['score'], name='prob_normalized') <NEW_LINE> self.prediction = tf.argmax(prob, 3, name='label_2d') | Model Implementation of FCN.
Args:
output_dir: if set, will output diagnostics and weights here
learning_rate: learning rate of the trainer
modality: name of the data modality, which has to be a valid key for the input
dataset batch
train_encoder (bool): If False, will keep the weights of the encoder static, may
be useful for finetuning.
num_units (int): Number of feature units in the FCN.
prefix (string): prefix of any variable name
batch_normalization (bool): Whether or not to use batch normalization. | 62598fa3b7558d58954634d2 |
class HomeHandler(BaseHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> self.render("home/index.html") | Renders the website index page - nothing more. | 62598fa38da39b475be03084 |
class SparseFeatureVector(SparseVector): <NEW_LINE> <INDENT> def __init__( self, save_to_cache=False, load_from_cache=False, cached_features_file=None, ): <NEW_LINE> <INDENT> SparseVector.__init__(self) <NEW_LINE> self.cached_features_file = cached_features_file <NEW_LINE> self.save_to_cache = save_to_cache <NEW_LINE> self.load_from_cache = load_from_cache <NEW_LINE> <DEDENT> def add_categorical_feature(self, name, value, allow_duplicates=False): <NEW_LINE> <INDENT> fname = name + "=" + value <NEW_LINE> assert allow_duplicates or fname not in self <NEW_LINE> self[fname] = 1.0 <NEW_LINE> <DEDENT> def add_binary_feature(self, name): <NEW_LINE> <INDENT> if name in self: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self[name] = 1.0 <NEW_LINE> <DEDENT> def add_numeric_feature(self, name, value): <NEW_LINE> <INDENT> self[name] = value <NEW_LINE> <DEDENT> def save_cached_features(self): <NEW_LINE> <INDENT> self.cached_features_file.write(str(len(self)) + '\n') <NEW_LINE> for key in self: <NEW_LINE> <INDENT> self.cached_features_file.write(key + '\t' + str(self[key]) + '\n') <NEW_LINE> <DEDENT> <DEDENT> def load_cached_features(self): <NEW_LINE> <INDENT> num_features = int(self.cached_features_file.next()) <NEW_LINE> for i in range(num_features): <NEW_LINE> <INDENT> key, value = ( self.cached_features_file.next().rstrip('\n').split('\t') ) <NEW_LINE> self[key] = float(value) | A generic class for a sparse feature vector. | 62598fa366656f66f7d5a293 |
class StructuralAssetClass(Enum,IComparable,IFormattable,IConvertible): <NEW_LINE> <INDENT> def __eq__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __format__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ge__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __gt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __le__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __lt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ne__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Basic=None <NEW_LINE> Concrete=None <NEW_LINE> Gas=None <NEW_LINE> Generic=None <NEW_LINE> Liquid=None <NEW_LINE> Metal=None <NEW_LINE> Plastic=None <NEW_LINE> Undefined=None <NEW_LINE> value__=None <NEW_LINE> Wood=None | Represents the type of material described by a structural asset. This enum value is returned by Autodesk::Revit::DB::StructuralAsset::StructuralAssetClass.
enum StructuralAssetClass,values: Basic (1),Concrete (4),Gas (7),Generic (2),Liquid (6),Metal (3),Plastic (8),Undefined (0),Wood (5) | 62598fa330bbd722464698c9 |
class AddAPTReconstructionForm(APTReconstructionForm): <NEW_LINE> <INDENT> name = StringField('Name', description='Name of reconstruction', render_kw=dict(pattern='\\w+', title='Only word characters allowed: A-Z, a-z, 0-9, and _'), validators=[Regexp('\\w+', message='Reconstruction name can only contain word ' 'characters: A-Z, a-z, 0-9, and _')]) | Form to add reconstruction metadata to a sample | 62598fa3d53ae8145f918330 |
class DataTimeSensor(TimeSensor): <NEW_LINE> <INDENT> Points_type = DataTimePoint <NEW_LINE> Slots_type = DataTimeSlot <NEW_LINE> @property <NEW_LINE> def Points_data_labels(self): <NEW_LINE> <INDENT> raise NotImplementedError('{}: Points_data_labels not implemented'.format(self.__class__.__name__)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def Slots_data_labels(self): <NEW_LINE> <INDENT> raise NotImplementedError('{}: Slots_data_labels not implemented'.format(self.__class__.__name__)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def Points_validity_interval(self): <NEW_LINE> <INDENT> raise NotImplementedError('{}: Points_validity_interval not implemented'.format(self.__class__.__name__)) | A time-based data sensor is a sensor that produces time-based data. | 62598fa326068e7796d4c7fc |
class SymbolTableEntry(object): <NEW_LINE> <INDENT> def __init__(self, symbol, visited=False): <NEW_LINE> <INDENT> self.symbol = symbol <NEW_LINE> self.visited = visited <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s<rva=0x%08X, tag=%s, kind=%s, name=%r, undecorated=%r>' % ( self.__class__.__name__, self.symbol.relativeVirtualAddress, self.symbol.symTag, self.symbol.dataKind, self.symbol.name, self.symbol.undecoratedName) <NEW_LINE> <DEDENT> __str__ = __repr__ | Denotes a code symbol and whether or not it was reached in a trace.
Attributes:
symbol: A DiaSymbol object.
visited: Whether or not the symbol was dynamically visited. | 62598fa36e29344779b00500 |
class JSONFormatterPlugin: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def format_json(unformatted: str, _info_str: str) -> str: <NEW_LINE> <INDENT> parsed = json.loads(unformatted) <NEW_LINE> return json.dumps(parsed, indent=2) + "\n" | A code formatter plugin that formats JSON. | 62598fa38e7ae83300ee8f45 |
class ConsultRss(TemplateView): <NEW_LINE> <INDENT> template_name = "base/update.html" <NEW_LINE> feeds = RSSFeeds.objects.all() <NEW_LINE> entries = RSSEntries.objects.all() <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context['feeds'] = self.feeds <NEW_LINE> context['entries'] = RSSEntries.objects.filter(id=self.request.GET['id']) <NEW_LINE> return context | Web page for rss entries viewing | 62598fa33c8af77a43b67e93 |
class buildings_SSS_units(gridcell_buildings_SSS_units): <NEW_LINE> <INDENT> def dependencies(self): <NEW_LINE> <INDENT> return [attribute_label("building", self.is_type_variable), attribute_label("building", "residential_units" ), attribute_label("building", "zone_id")] | Sum of residential units from buildings of given type across zones. | 62598fa45f7d997b871f9332 |
class JogoDoTesouroInca: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.templo = "Você está diante de um templo Inca." <NEW_LINE> self.baralho = Baralho() <NEW_LINE> <DEDENT> def vai(self): <NEW_LINE> <INDENT> continua = " Você vai entrar? (s/N)" <NEW_LINE> if input(self.templo+continua) == "s": <NEW_LINE> <INDENT> input("Você se embrenha no templo, e explora") <NEW_LINE> self.baralho.vai() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> input("Você sabiamente desiste desta loucura") | O jogo do tesouro inca.
O jogo começa quando se invoca o método vai | 62598fa4656771135c489525 |
class ScrollBar(ClickableWidget): <NEW_LINE> <INDENT> pass | A ScrollBar Widget().
* Supports mouse-wheels.
TODO: Implement! | 62598fa492d797404e388ab7 |
class SendConfigurationValidityReportOperation(model._SendConfigurationValidityReportOperation): <NEW_LINE> <INDENT> def activate(self, request: model.SendConfigurationValidityReportRequest): <NEW_LINE> <INDENT> return self._activate(request) <NEW_LINE> <DEDENT> def get_response(self): <NEW_LINE> <INDENT> return self._get_response() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> return super().close() | SendConfigurationValidityReportOperation
Create with GreengrassCoreIPCClient.new_send_configuration_validity_report() | 62598fa4462c4b4f79dbb8b0 |
class DefenderStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> PROTECTED = "Protected" <NEW_LINE> UNPROTECTED = "Unprotected" <NEW_LINE> UNKNOWN = "Unknown" | Status of Azure Defender.
| 62598fa445492302aabfc374 |
class ProcessQueue(object): <NEW_LINE> <INDENT> KEY_NAME = 'app:img:queue' <NEW_LINE> WAIT_NAME = 'app:img:wait_ack' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.r = redis_db.get_connect() <NEW_LINE> self.log = logger.get_log(ProcessQueue) <NEW_LINE> <DEDENT> def r(self): <NEW_LINE> <INDENT> return self.r <NEW_LINE> <DEDENT> def push(self, raw_content): <NEW_LINE> <INDENT> content = json.dumps(raw_content) <NEW_LINE> self.r.rpush(ProcessQueue.KEY_NAME, content) <NEW_LINE> self.log.info('rpush {} success, {}'.format(ProcessQueue.KEY_NAME, content)) <NEW_LINE> <DEDENT> def pop(self, timeout=5): <NEW_LINE> <INDENT> raw_tuple = self.r.blpop(ProcessQueue.KEY_NAME, timeout=timeout) <NEW_LINE> if not raw_tuple: <NEW_LINE> <INDENT> self.log.info('blpop timeout, {} is empty'.format(ProcessQueue.KEY_NAME)) <NEW_LINE> return None <NEW_LINE> <DEDENT> self.log.info('blpop {} success, {}'.format(ProcessQueue.KEY_NAME, raw_tuple[1])) <NEW_LINE> content = json.loads(raw_tuple[1]) <NEW_LINE> self.r.zadd(ProcessQueue.WAIT_NAME, {content['id']: 1}, incr=True) <NEW_LINE> self.log.info('zadd {} success, {}'.format(ProcessQueue.WAIT_NAME, content['id'])) <NEW_LINE> return content <NEW_LINE> <DEDENT> def ack(self, p_id): <NEW_LINE> <INDENT> self.r.zrem(ProcessQueue.WAIT_NAME, p_id) <NEW_LINE> self.log.info('zrem {} success, {}'.format(ProcessQueue.WAIT_NAME, p_id)) <NEW_LINE> <DEDENT> def scan(self): <NEW_LINE> <INDENT> self.log.info('zscan {}'.format(self.r.zscan(ProcessQueue.WAIT_NAME))) | 利用redis实现消息队列 | 62598fa47d847024c075c26a |
class _CFunctionDeclaration(object): <NEW_LINE> <INDENT> def as_dict(self): <NEW_LINE> <INDENT> keys = ["ret", "fname", "choset", "args", "fnget"] <NEW_LINE> return dict((k, getattr(self, k)) for k in keys if hasattr(self, k)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, cfstr): <NEW_LINE> <INDENT> cfstr = cfstr.strip() <NEW_LINE> match_func = RE_CFDEC_FUNC.match(cfstr) <NEW_LINE> if match_func: <NEW_LINE> <INDENT> return cls.from_groupdict(**match_func.groupdict()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( "%s is invalid as c-function cdt declaration" % cfstr) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def from_groupdict(cls, ret, fname, args): <NEW_LINE> <INDENT> parsed = cls() <NEW_LINE> (fname, choset, fnget) = cfdec_fname_parse(fname) <NEW_LINE> parsed.ret = ret <NEW_LINE> parsed.fname = fname <NEW_LINE> parsed.choset = choset <NEW_LINE> parsed.args = cfdec_args_parse(args) <NEW_LINE> parsed.fnget = fnget <NEW_LINE> return parsed | A class to sotre parsed information of C-function declaration
Attributes
----------
ret : str or None
returned value
fname : str
name of function
choset : list of {'choices': [str], 'key': str}
choice set
args : list of {'aname': [str], 'default': obj, 'cdt': str}
arguments
fnget : (str, str, ...) -> str
function name getter.
it constructs C function name from given "choices". | 62598fa4cb5e8a47e493c0c9 |
class SODARAPIPermissionTestMixin(SODARAPIViewTestMixin): <NEW_LINE> <INDENT> def assert_response_api( self, url, users, status_code, method='GET', format='json', data=None, media_type=None, version=None, knox=False, cleanup_method=None, req_kwargs=None, ): <NEW_LINE> <INDENT> if cleanup_method and not callable(cleanup_method): <NEW_LINE> <INDENT> raise ValueError('cleanup_method is not callable') <NEW_LINE> <DEDENT> def _send_request(): <NEW_LINE> <INDENT> req_method = getattr(self.client, method.lower(), None) <NEW_LINE> if not req_method: <NEW_LINE> <INDENT> raise ValueError('Invalid method "{}"'.format(method)) <NEW_LINE> <DEDENT> if req_kwargs: <NEW_LINE> <INDENT> r_kwargs.update(req_kwargs) <NEW_LINE> <DEDENT> return req_method(url, **r_kwargs) <NEW_LINE> <DEDENT> if not isinstance(users, (list, tuple)): <NEW_LINE> <INDENT> users = [users] <NEW_LINE> <DEDENT> for user in users: <NEW_LINE> <INDENT> r_kwargs = {'format': format} <NEW_LINE> if data: <NEW_LINE> <INDENT> r_kwargs['data'] = data <NEW_LINE> <DEDENT> if knox and not user: <NEW_LINE> <INDENT> raise ValueError( 'Unable to test Knox token auth with anonymous user' ) <NEW_LINE> <DEDENT> r_kwargs.update(self.get_accept_header(media_type, version)) <NEW_LINE> if knox: <NEW_LINE> <INDENT> r_kwargs.update(self.get_token_header(self.get_token(user))) <NEW_LINE> response = _send_request() <NEW_LINE> <DEDENT> elif user: <NEW_LINE> <INDENT> with self.login(user): <NEW_LINE> <INDENT> response = _send_request() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> response = _send_request() <NEW_LINE> <DEDENT> msg = 'user={}; content="{}"'.format(user, response.content) <NEW_LINE> self.assertEqual(response.status_code, status_code, msg=msg) <NEW_LINE> if cleanup_method: <NEW_LINE> <INDENT> cleanup_method() | Mixin for permission testing with knox auth | 62598fa4379a373c97d98eb6 |
class SlottyAPI(BaseNamespace, BroadcastMixin): <NEW_LINE> <INDENT> def process_packet(self, packet): <NEW_LINE> <INDENT> from pprint import pformat <NEW_LINE> app.logger.info("Received Packet: %s", pformat(packet)) <NEW_LINE> packet_type = packet['type'] <NEW_LINE> if packet_type == 'connect': <NEW_LINE> <INDENT> context = zmq.Context() <NEW_LINE> sock = context.socket(zmq.SUB) <NEW_LINE> sock.setsockopt(zmq.SUBSCRIBE, "") <NEW_LINE> sock.connect(app.config["API_ADDRESS"]) <NEW_LINE> gevent.spawn(self.outbound, context, sock) <NEW_LINE> <DEDENT> <DEDENT> def outbound(self, context, sock): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> data = sock.recv_json() <NEW_LINE> self.broadcast_event(data["event"], data["args"]) <NEW_LINE> gevent.sleep(0.01) <NEW_LINE> <DEDENT> <DEDENT> def inboud(self, context, sock): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> data = sock.recv_json() <NEW_LINE> app.logger.debug(data) <NEW_LINE> self.broadcast_event(data["event"], data["args"]) <NEW_LINE> gevent.sleep(0.01) | Endpoint for the socket.io connection.
Broadcasts all incoming zmq.green data to the connected
clients | 62598fa4be8e80087fbbef06 |
class TestStudentWithSituation(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.student = StudentWithSituation('1', 'Test', 10) <NEW_LINE> <DEDENT> def test_getters(self): <NEW_LINE> <INDENT> self.assertEqual(self.student.get_id(), '1') <NEW_LINE> self.assertEqual(self.student.get_name(), 'Test') <NEW_LINE> self.assertEqual(self.student.get_average_grade(), 10) <NEW_LINE> <DEDENT> def test_setters(self): <NEW_LINE> <INDENT> self.student.set_name('bob') <NEW_LINE> self.assertEqual(self.student.get_name(), 'bob') <NEW_LINE> <DEDENT> def test_str(self): <NEW_LINE> <INDENT> self.assertEqual(str(self.student), 'ID: 1, Name: Test, Average grade: 10') <NEW_LINE> <DEDENT> def test_eq(self): <NEW_LINE> <INDENT> student_equal = StudentWithSituation('1', 'blah', 7) <NEW_LINE> student_not_equal = StudentWithSituation('2', 'blah2', 4) <NEW_LINE> self.assertEqual(self.student, student_equal) <NEW_LINE> self.assertNotEqual(self.student, student_not_equal) <NEW_LINE> <DEDENT> def test_lt(self): <NEW_LINE> <INDENT> student_lower_than = StudentWithAverage('2', 'LT', ['CSA'], 8) <NEW_LINE> student_not_lower_than = StudentWithAverage('3', 'NLT', ['CDI'], 10) <NEW_LINE> self.assertTrue(student_lower_than < self.student) <NEW_LINE> self.assertFalse(student_not_lower_than < self.student) | Class for testing the StudentWithSituation class | 62598fa432920d7e50bc5efb |
class SimpleMessageSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Message <NEW_LINE> fields = ('id', 'body', 'sender', 'thread', 'sent_at') | Returns the messages without complementary information. | 62598fa4b7558d58954634d4 |
class Package(BASE, ModificationsTrackedObject): <NEW_LINE> <INDENT> __tablename__ = 'package' <NEW_LINE> id = sa.Column(sa.String(36), primary_key=True, default=uuidutils.generate_uuid) <NEW_LINE> archive = sa.Column(st.LargeBinary()) <NEW_LINE> fully_qualified_name = sa.Column(sa.String(128), nullable=False, index=True, unique=True) <NEW_LINE> type = sa.Column(sa.String(20), nullable=False, default='class') <NEW_LINE> author = sa.Column(sa.String(80), default='Openstack') <NEW_LINE> supplier = sa.Column(JsonBlob(), nullable=True, default={}) <NEW_LINE> name = sa.Column(sa.String(80), nullable=False) <NEW_LINE> enabled = sa.Column(sa.Boolean, default=True) <NEW_LINE> description = sa.Column(sa.String(512), nullable=False, default='The description is not provided') <NEW_LINE> is_public = sa.Column(sa.Boolean, default=True) <NEW_LINE> tags = sa_orm.relationship("Tag", secondary=package_to_tag, cascade='save-update, merge', lazy='joined') <NEW_LINE> logo = sa.Column(st.LargeBinary(), nullable=True) <NEW_LINE> owner_id = sa.Column(sa.String(36), nullable=False) <NEW_LINE> ui_definition = sa.Column(sa.Text) <NEW_LINE> supplier_logo = sa.Column(sa.LargeBinary, nullable=True) <NEW_LINE> categories = sa_orm.relationship("Category", secondary=package_to_category, cascade='save-update, merge', lazy='joined') <NEW_LINE> class_definitions = sa_orm.relationship( "Class", cascade='save-update, merge, delete', lazy='joined') <NEW_LINE> def to_dict(self): <NEW_LINE> <INDENT> d = self.__dict__.copy() <NEW_LINE> not_serializable = ['_sa_instance_state', 'archive', 'logo', 'ui_definition', 'supplier_logo'] <NEW_LINE> nested_objects = ['categories', 'tags', 'class_definitions'] <NEW_LINE> for key in not_serializable: <NEW_LINE> <INDENT> if key in d.keys(): <NEW_LINE> <INDENT> del d[key] <NEW_LINE> <DEDENT> <DEDENT> for key in nested_objects: <NEW_LINE> <INDENT> d[key] = [a.name for a in d.get(key, [])] <NEW_LINE> <DEDENT> return d | Represents a meta information about application package. | 62598fa432920d7e50bc5efc |
class PlantDataset(dataset.Dataset): <NEW_LINE> <INDENT> def __init__(self, root, transform=None, target_transform=None, image_size=32, train=True): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.transform = transform <NEW_LINE> self.target_transform = target_transform <NEW_LINE> self.total_data_size = 0 <NEW_LINE> if train: <NEW_LINE> <INDENT> files = glob.glob(root + '/**/train_*', recursive=True) <NEW_LINE> logging.info('Found the following train files: {}'.format(files)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> files = glob.glob(root + '/**/test_*', recursive=True) <NEW_LINE> logging.info('Found the following test files: {}'.format(files)) <NEW_LINE> <DEDENT> self.train_data = [] <NEW_LINE> self.train_labels = [] <NEW_LINE> for file in files: <NEW_LINE> <INDENT> logging.info('Opening pickled train data {}'.format(file)) <NEW_LINE> with open(file, 'rb') as fo: <NEW_LINE> <INDENT> data = pickle.load(fo) <NEW_LINE> self.train_labels.extend(data['labels']) <NEW_LINE> self.train_data.append(data['data']) <NEW_LINE> <DEDENT> self.total_data_size += len(data['labels']) <NEW_LINE> <DEDENT> self.train_data = np.concatenate(self.train_data) <NEW_LINE> self.train_data = self.train_data.reshape((self.total_data_size, 3, image_size, image_size)) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> img, target = self.train_data[index], self.train_labels[index] <NEW_LINE> img = Image.fromarray(np.transpose(img, (1, 2, 0))) <NEW_LINE> if self.transform is not None: <NEW_LINE> <INDENT> img = self.transform(img) <NEW_LINE> <DEDENT> if self.target_transform is not None: <NEW_LINE> <INDENT> target = self.target_transform(target) <NEW_LINE> <DEDENT> return img, target <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.total_data_size | We extend the PyTorch dataset class, zie: http://pytorch.org/docs/data.html | 62598fa47b25080760ed734f |
class TestJobScheduleDate(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 testJobScheduleDate(self): <NEW_LINE> <INDENT> pass | JobScheduleDate unit test stubs | 62598fa4ac7a0e7691f723b0 |
class card40(unittest.TestCase): <NEW_LINE> <INDENT> def testPlayable(self): <NEW_LINE> <INDENT> app = Labyrinth(1, 1, testBlankScenarioSetup) <NEW_LINE> self.assertFalse(app.deck["40"].playable("US", app)) <NEW_LINE> app.map["Libya"].governance = 3 <NEW_LINE> app.map["Libya"].alignment = "Adversary" <NEW_LINE> self.assertFalse(app.deck["40"].playable("US", app)) <NEW_LINE> app.map["Libya"].regimeChange = 1 <NEW_LINE> self.assertTrue(app.deck["40"].playable("US", app)) <NEW_LINE> <DEDENT> def testEvent(self): <NEW_LINE> <INDENT> app = Labyrinth(1, 1, testBlankScenarioSetup) <NEW_LINE> app.map["Libya"].governance = 3 <NEW_LINE> app.map["Libya"].alignment = "Adversary" <NEW_LINE> app.map["Libya"].regimeChange = 1 <NEW_LINE> app.deck["40"].playEvent("US", app) <NEW_LINE> self.assertTrue(app.map["Libya"].governance == 2) <NEW_LINE> app = Labyrinth(1, 1, testBlankScenarioSetup) <NEW_LINE> app.map["Libya"].governance = 2 <NEW_LINE> app.map["Libya"].alignment = "Adversary" <NEW_LINE> app.map["Libya"].regimeChange = 1 <NEW_LINE> app.map["Libya"].aid = 1 <NEW_LINE> app.deck["40"].playEvent("US", app) <NEW_LINE> self.assertTrue(app.map["Libya"].governance == 1) <NEW_LINE> self.assertTrue(app.map["Libya"].regimeChange == 0) <NEW_LINE> self.assertTrue(app.map["Libya"].aid == 0) <NEW_LINE> app = Labyrinth(1, 1, testBlankScenarioSetup,["Iraq"]) <NEW_LINE> app.map["Libya"].governance = 2 <NEW_LINE> app.map["Libya"].alignment = "Adversary" <NEW_LINE> app.map["Libya"].regimeChange = 1 <NEW_LINE> app.map["Libya"].aid = 1 <NEW_LINE> app.map["Iraq"].governance = 2 <NEW_LINE> app.map["Iraq"].alignment = "Adversary" <NEW_LINE> app.map["Iraq"].regimeChange = 1 <NEW_LINE> app.map["Iraq"].aid = 1 <NEW_LINE> app.deck["40"].playEvent("US", app) <NEW_LINE> self.assertTrue(app.map["Iraq"].governance == 1) <NEW_LINE> self.assertTrue(app.map["Iraq"].regimeChange == 0) <NEW_LINE> self.assertTrue(app.map["Iraq"].aid == 0) | Mass Turnout | 62598fa43317a56b869be49c |
class VersionInteger(Integer): <NEW_LINE> <INDENT> def from_json(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = int(value) <NEW_LINE> if value not in VERSION_TUPLES: <NEW_LINE> <INDENT> version_error_string = "Could not find version {0}, using version {1} instead" <NEW_LINE> log.error(version_error_string.format(value, DEFAULT_VERSION)) <NEW_LINE> value = DEFAULT_VERSION <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> value = DEFAULT_VERSION <NEW_LINE> <DEDENT> return value | A model type that converts from strings to integers when reading from json.
Also does error checking to see if version is correct or not. | 62598fa41b99ca400228f482 |
class FilterByHost(HierarchicalBucketFilter): <NEW_LINE> <INDENT> sweepInterval = 60 * 20 <NEW_LINE> def getBucketKey(self, transport): <NEW_LINE> <INDENT> return transport.getPeer()[1] | A bucket filter with a bucket for each host.
| 62598fa46e29344779b00502 |
class dom_weekend_holiday(dom_holiday): <NEW_LINE> <INDENT> fg = (0,0,0) <NEW_LINE> bg = (0.95,0.95,0.95) | day of month (weekend & holiday) | 62598fa407f4c71912baf2e9 |
class BfdIpv6(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.required = [ "local_ipv6","nexthop_ipv6"] <NEW_LINE> self.b_key = "bfd-ipv6" <NEW_LINE> self.a10_url="/axapi/v3/ipv6/route/static/bfd/bfd-ipv6/{local_ipv6}+{nexthop_ipv6}" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.local_ipv6 = "" <NEW_LINE> self.uuid = "" <NEW_LINE> self.nexthop_ipv6 = "" <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value) | Class Description::
Bidirectional Forwarding Detection.
Class bfd-ipv6 supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param local_ipv6: {"optional": false, "type": "string", "description": "Local IPv6 address", "format": "ipv6-address"}
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param nexthop_ipv6: {"optional": false, "type": "string", "description": "Nexthop IPv6 address", "format": "ipv6-address"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/ipv6/route/static/bfd/bfd-ipv6/{local_ipv6}+{nexthop_ipv6}`. | 62598fa41f037a2d8b9e3f90 |
class ZeroFloat(float): <NEW_LINE> <INDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return float(self) - float(other) if other != 0 else 0 | Special float type which returns zero if the amount to be subtracted is zero | 62598fa45f7d997b871f9333 |
class _NamespaceMerger: <NEW_LINE> <INDENT> def __init__(self, namespace: Any = None) -> None: <NEW_LINE> <INDENT> self.__namespace = namespace or Namespace() <NEW_LINE> <DEDENT> def merge(self, values: Dict[str, Any]) -> Any: <NEW_LINE> <INDENT> target = self.__namespace <NEW_LINE> if values is not None: <NEW_LINE> <INDENT> for key, value in values.items(): <NEW_LINE> <INDENT> if not isinstance(value, dict): <NEW_LINE> <INDENT> setattr(target, key, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> values_as_dict: dict = value.__dict__ <NEW_LINE> inner_target: Namespace = Namespace() <NEW_LINE> merger: _NamespaceMerger = _NamespaceMerger(inner_target) <NEW_LINE> inner_target = merger.merge(values_as_dict) <NEW_LINE> setattr(target, key, inner_target) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return target | Simple instance used to merge dictionary objects into an existing
object. | 62598fa456ac1b37e6302092 |
class PhysicalSignal(models.Model): <NEW_LINE> <INDENT> signal_name = models.CharField(max_length=25, default="None") <NEW_LINE> signal_description = models.CharField(max_length=30, blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.signal_name | Description of the physical phenomenon being measured, such as air temperature, pressure, etc. | 62598fa43539df3088ecc15a |
class DocumentViewNotFound(Exception): <NEW_LINE> <INDENT> pass | Exception returned when a view cannot be found. | 62598fa4009cb60464d013ca |
class Task(models.Model): <NEW_LINE> <INDENT> task_name = models.CharField(max_length=200) <NEW_LINE> task_points = models.IntegerField(default=5,validators=[MinValueValidator(0), MaxValueValidator(100)]) <NEW_LINE> task_description = models.CharField(default='default task_description', max_length=600) <NEW_LINE> task_place = models.ForeignKey(Place, default=get_default_task_place, on_delete=models.CASCADE) <NEW_LINE> task_frequency = models.IntegerField(default=7,validators=[MinValueValidator(0), MaxValueValidator(365)]) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.task_name | Table of the different tasks that have to be done, such as 'clean table', 'hover carpet'.... | 62598fa4d486a94d0ba2be77 |
class Shot(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> show_id = db.Column(db.Integer, db.ForeignKey('show.id')) <NEW_LINE> show = db.relationship('Show', backref=db.backref('shots', lazy='dynamic')) <NEW_LINE> frame_start = db.Column(db.Integer()) <NEW_LINE> frame_end = db.Column(db.Integer()) <NEW_LINE> chunk_size = db.Column(db.Integer()) <NEW_LINE> current_frame = db.Column(db.Integer()) <NEW_LINE> name = db.Column(db.String(120)) <NEW_LINE> filepath = db.Column(db.String(256)) <NEW_LINE> render_settings = db.Column(db.String(120)) <NEW_LINE> status = db.Column(db.String(64)) <NEW_LINE> priority = db.Column(db.Integer()) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<Shot %r>' % self.name | A Shot is one of the basic units of brender
The creation of a shot can happen in different ways:
* within brender (using a shot creation form)
* via a query from an external software (e.g. Attract) | 62598fa463d6d428bbee2658 |
class TestContainsAllDigits(unittest.TestCase): <NEW_LINE> <INDENT> def test_1(self): <NEW_LINE> <INDENT> self.assertEqual(True, solution.contains_digits(402123, [0, 3, 4])) <NEW_LINE> <DEDENT> def test_2(self): <NEW_LINE> <INDENT> self.assertEqual(False, solution.contains_digits(666, [6,4])) <NEW_LINE> <DEDENT> def test_3(self): <NEW_LINE> <INDENT> self.assertEqual(False, solution.contains_digits(123456789, [1,2,3,0])) <NEW_LINE> <DEDENT> def test_4(self): <NEW_LINE> <INDENT> self.assertEqual(True, solution.contains_digits(456, [])) | docstring for TestContainsAllDigits | 62598fa423849d37ff850f5b |
class WorkflowBase(object): <NEW_LINE> <INDENT> def get_workflow(self): <NEW_LINE> <INDENT> return utils.get_workflow(self) <NEW_LINE> <DEDENT> def remove_workflow(self): <NEW_LINE> <INDENT> return utils.remove_workflow_from_object(self) <NEW_LINE> <DEDENT> def set_workflow(self, workflow): <NEW_LINE> <INDENT> return utils.set_workflow_for_object(self, workflow) <NEW_LINE> <DEDENT> def get_state(self): <NEW_LINE> <INDENT> return utils.get_state(self) <NEW_LINE> <DEDENT> def set_state(self, state): <NEW_LINE> <INDENT> return utils.set_state(self, state) <NEW_LINE> <DEDENT> def set_initial_state(self): <NEW_LINE> <INDENT> return self.set_state(self.get_workflow().initial_state) <NEW_LINE> <DEDENT> def get_allowed_transitions(self, user): <NEW_LINE> <INDENT> return utils.get_allowed_transitions(self, user) <NEW_LINE> <DEDENT> def do_transition(self, transition, user): <NEW_LINE> <INDENT> return utils.do_transition(self, transition, user) | Mixin class to make objects workflow-aware. | 62598fa4be383301e025369e |
class BlogEngine(TextEngine): <NEW_LINE> <INDENT> DEFAULTS = Config( URL = '/blog', PERMALINK = '{time:%Y/%m/%d}/{slug}', DATETIME_FORMAT = '%Y/%m/%d %H:%M', DEFAULT_FIELDS = {}, CONTENT_DIR = 'blog', UNIT_FNAME_PATTERN = '*', UNIT_TEMPLATE = 'blog_unit.html', PAGINATION_TEMPLATE = 'blog_pagination.html', SORT_KEY = '-time', UNITS_PER_PAGINATION = 10, EXCERPT_LENGTH = 400, PAGINATIONS = ('',), PROTECTED = ('id', 'content', ), REQUIRED = ('title', 'time', ), FIELDS_AS_DATETIME = ('time', ), FIELDS_AS_LIST = ('tags', 'categories', ), LIST_SEP = ', ' ) <NEW_LINE> USER_CONF_ENTRY = 'ENGINE_BLOG' <NEW_LINE> def preprocess(self): <NEW_LINE> <INDENT> self.sort_units() <NEW_LINE> self.chain_units() <NEW_LINE> <DEDENT> def dispatch(self): <NEW_LINE> <INDENT> self.write_units() <NEW_LINE> self.write_paginations() | Engine for processing text files into a blog.
This engine uses the TextUnit class to represent its resource. Prior to
writing the output, the TextUnit objects are sorted according to the
configuration. They are then chained together by adding to each unit
permalinks that link to the previous and/or next units.
It also creates paginations according to the settings in voltconf.py | 62598fa410dbd63aa1c70a56 |
class NavigationUnit: <NEW_LINE> <INDENT> def __init__(self, perception_unit, drive_controller, vehicle_constants): <NEW_LINE> <INDENT> self._perception_unit = perception_unit <NEW_LINE> self._drive_controller = drive_controller <NEW_LINE> self._vehicle_constants = vehicle_constants <NEW_LINE> self._drive_ctrl = BasicPIDControl(vehicle_constants.pid_drive_gain_p, vehicle_constants.pid_drive_gain_i, vehicle_constants.pid_drive_gain_d, vehicle_constants.drive_dead_zone, vehicle_constants.drive_max_response) <NEW_LINE> self._heading_ctrl = BasicPIDControl(vehicle_constants.pid_heading_gain_p, vehicle_constants.pid_heading_gain_i, vehicle_constants.pid_heading_gain_d, vehicle_constants.heading_dead_zone, vehicle_constants.heading_max_response) <NEW_LINE> self._enabled = False <NEW_LINE> self._desired_speed = 0.0 <NEW_LINE> self._desired_heading = 0.0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def auto_mode_enabled(self): <NEW_LINE> <INDENT> return self._enabled <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self._enabled: <NEW_LINE> <INDENT> observed_speed = self._perception_unit.observed_speed <NEW_LINE> observed_heading = self.map_heading_range(self._perception_unit.observed_heading) <NEW_LINE> desired_speed, desired_heading = self._desired_speed, self._desired_heading <NEW_LINE> logging.debug("NAV:\tobserved vs desired (speed, heading):\t(%f, %f) vs (%f, %f)", observed_speed, observed_heading, desired_speed, desired_heading) <NEW_LINE> current_throttle = self._drive_controller.throttle_level <NEW_LINE> current_steering = self._drive_controller.steering_angle <NEW_LINE> dt = 0.2 <NEW_LINE> new_throttle = self._drive_ctrl.update(desired_speed, observed_speed, dt) <NEW_LINE> new_steering = self._heading_ctrl.update(desired_heading, observed_heading, dt) <NEW_LINE> logging.debug("NAV:\tcurrent vs new (throttle, steering):\t(%f, %f) vs (%f, %f)", current_throttle, current_steering, new_throttle, new_steering) <NEW_LINE> self._drive_controller.set_throttle(new_throttle) <NEW_LINE> self._drive_controller.set_steering(new_steering) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def navigate_to(self, route): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_speed(self, speed): <NEW_LINE> <INDENT> self._desired_speed = speed <NEW_LINE> self.start() <NEW_LINE> <DEDENT> def set_heading(self, heading): <NEW_LINE> <INDENT> self._desired_heading = self.map_heading_range(heading) <NEW_LINE> self.start() <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self._enabled = True <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self._enabled = False <NEW_LINE> self._drive_controller.halt() <NEW_LINE> self._desired_speed = 0.0 <NEW_LINE> self._desired_heading = 0.0 <NEW_LINE> <DEDENT> def map_heading_range(self, angle): <NEW_LINE> <INDENT> if angle > 180.0: <NEW_LINE> <INDENT> return self.map_heading_range(angle-360.0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return angle | Coordinator between internal perception model, outer high level command software (UI or AI), path planning through to drive control and course maintainence. | 62598fa48c0ade5d55dc35e3 |
class Metadata(ZeroArgAction): <NEW_LINE> <INDENT> def __call__(self, parser, ns, values, option_string=None): <NEW_LINE> <INDENT> md = discover_metadata_in_cyclus_path() <NEW_LINE> writer = CustomWriter("{", "}", "[", "]", ": ", ", ", " ", 80) <NEW_LINE> s = writer.write(md) <NEW_LINE> print(s.rstrip()) | Displays all known cyclus agents | 62598fa43d592f4c4edbad74 |
class PlaceholderTestItem(Item): <NEW_LINE> <INDENT> attr = integer() <NEW_LINE> other = integer() <NEW_LINE> characters = text() | Type used by the placeholder support test cases. | 62598fa44e4d5625663722ca |
@python_2_unicode_compatible <NEW_LINE> class Username(models.Model): <NEW_LINE> <INDENT> value = models.CharField( max_length=255, verbose_name=_(u"username"), help_text=_(u"username allowed to connect to the service") ) <NEW_LINE> service_pattern = models.ForeignKey( ServicePattern, related_name="usernames", on_delete=models.CASCADE ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.value | Bases: :class:`django.db.models.Model`
A list of allowed usernames on a :class:`ServicePattern` | 62598fa455399d3f056263c9 |
class ConnectionMonitorHttpConfiguration(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'port': {'key': 'port', 'type': 'int'}, 'method': {'key': 'method', 'type': 'str'}, 'path': {'key': 'path', 'type': 'str'}, 'request_headers': {'key': 'requestHeaders', 'type': '[HTTPHeader]'}, 'valid_status_code_ranges': {'key': 'validStatusCodeRanges', 'type': '[str]'}, 'prefer_https': {'key': 'preferHTTPS', 'type': 'bool'}, } <NEW_LINE> def __init__( self, *, port: Optional[int] = None, method: Optional[Union[str, "HTTPConfigurationMethod"]] = None, path: Optional[str] = None, request_headers: Optional[List["HTTPHeader"]] = None, valid_status_code_ranges: Optional[List[str]] = None, prefer_https: Optional[bool] = None, **kwargs ): <NEW_LINE> <INDENT> super(ConnectionMonitorHttpConfiguration, self).__init__(**kwargs) <NEW_LINE> self.port = port <NEW_LINE> self.method = method <NEW_LINE> self.path = path <NEW_LINE> self.request_headers = request_headers <NEW_LINE> self.valid_status_code_ranges = valid_status_code_ranges <NEW_LINE> self.prefer_https = prefer_https | Describes the HTTP configuration.
:param port: The port to connect to.
:type port: int
:param method: The HTTP method to use. Possible values include: "Get", "Post".
:type method: str or ~azure.mgmt.network.v2020_03_01.models.HTTPConfigurationMethod
:param path: The path component of the URI. For instance, "/dir1/dir2".
:type path: str
:param request_headers: The HTTP headers to transmit with the request.
:type request_headers: list[~azure.mgmt.network.v2020_03_01.models.HTTPHeader]
:param valid_status_code_ranges: HTTP status codes to consider successful. For instance,
"2xx,301-304,418".
:type valid_status_code_ranges: list[str]
:param prefer_https: Value indicating whether HTTPS is preferred over HTTP in cases where the
choice is not explicit.
:type prefer_https: bool | 62598fa47047854f4633f27f |
class LanguageRange(object): <NEW_LINE> <INDENT> def __init__(self, language, quality=1.0): <NEW_LINE> <INDENT> if language == "*": <NEW_LINE> <INDENT> language = "*-*" <NEW_LINE> <DEDENT> if "-" in language: <NEW_LINE> <INDENT> self.type, self.subtype = language.split("-") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.type, self.subtype = language, None <NEW_LINE> <DEDENT> self.quality = quality or 1.0 <NEW_LINE> <DEDENT> def __contains__(self, language): <NEW_LINE> <INDENT> if "-" in language: <NEW_LINE> <INDENT> type, subtype = language.split("-") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> type, subtype = language, None <NEW_LINE> <DEDENT> if type == self.type or self.type == "*": <NEW_LINE> <INDENT> if subtype == self.subtype or self.subtype == "*": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> comparison = 0 - cmp(self.quality, other.quality) <NEW_LINE> if not comparison: <NEW_LINE> <INDENT> if hasattr(self, "position") and hasattr(other, "position"): <NEW_LINE> <INDENT> comparison = cmp(self.position, other.position) <NEW_LINE> <DEDENT> <DEDENT> return comparison <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.subtype: <NEW_LINE> <INDENT> toreturn = self.type + "-" + self.subtype + ";q=" + str(self.quality) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> toreturn = self.type + ";q=" + str(self.quality) <NEW_LINE> <DEDENT> if hasattr(self, "position"): <NEW_LINE> <INDENT> toreturn += ";position=" + str(self.position) <NEW_LINE> <DEDENT> return toreturn <NEW_LINE> <DEDENT> __repr__ = __str__ | Represents one language range in an RFC 2616 Accept field | 62598fa401c39578d7f12c25 |
class TwistedEvent(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._waiters = [] <NEW_LINE> self._result = None <NEW_LINE> <DEDENT> def fire(self): <NEW_LINE> <INDENT> self._fire(('callback', True)) <NEW_LINE> <DEDENT> def fail(self, reason): <NEW_LINE> <INDENT> self._fire(('errback', reason)) <NEW_LINE> <DEDENT> def fail_if_not_fired(self, reason): <NEW_LINE> <INDENT> if self._result is None: <NEW_LINE> <INDENT> self.fail(reason) <NEW_LINE> <DEDENT> <DEDENT> def wait(self): <NEW_LINE> <INDENT> d = defer.Deferred() <NEW_LINE> if self._result is None: <NEW_LINE> <INDENT> self._waiters.append(d) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._fire_deferred(d) <NEW_LINE> <DEDENT> return d <NEW_LINE> <DEDENT> def _fire(self, result): <NEW_LINE> <INDENT> if self._result is not None: <NEW_LINE> <INDENT> raise AlreadyFiredError() <NEW_LINE> <DEDENT> self._result = result <NEW_LINE> waiters, self._waiters = self._waiters, [] <NEW_LINE> for w in waiters: <NEW_LINE> <INDENT> self._fire_deferred(w) <NEW_LINE> <DEDENT> <DEDENT> def _fire_deferred(self, d): <NEW_LINE> <INDENT> getattr(d, self._result[0])(self._result[1]) | An asynchronous event that is in one of three states:
1. Not fired
2. Fired succesfully
3. Failed
Clients wishing to be notified when the event has
either occurred or failed can call wait() to receive
a deferred that will be fired with callback(True) for
state 2 and with errback(reason) for state 3.
Each waiter gets an independent deferred that is not
affected by other waiters. | 62598fa444b2445a339b68c1 |
class Feature(models.Model): <NEW_LINE> <INDENT> title = models.TextField() <NEW_LINE> name = models.CharField(max_length=256) <NEW_LINE> description = models.TextField() <NEW_LINE> due_date = models.DateField() <NEW_LINE> class FeatureStatus(models.IntegerChoices): <NEW_LINE> <INDENT> TO_DO = 0 <NEW_LINE> IN_PROGRESS = 10 <NEW_LINE> DONE = 20 <NEW_LINE> <DEDENT> status = models.IntegerField(choices=FeatureStatus.choices, default=FeatureStatus.TO_DO) <NEW_LINE> class PriorityStatus(models.IntegerChoices): <NEW_LINE> <INDENT> LOW = 30 <NEW_LINE> ELEVATED = 20 <NEW_LINE> HIGHEST = 10 <NEW_LINE> <DEDENT> priority = models.IntegerField(choices=PriorityStatus.choices, default=PriorityStatus.LOW) <NEW_LINE> project = models.ForeignKey( Project, on_delete=models.CASCADE ) <NEW_LINE> assignee = models.ForeignKey( User, on_delete=models.CASCADE, related_name='assigned_user', null=True, blank=True, default=None ) | Model describing a Feature
For a Feature has a foreign key
to the Project - each Feature has one project it is under.
For a Feature has a foreign key
to the User - each Feature has one assigned user. | 62598fa42ae34c7f260aaf88 |
class TestStorage(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> os.environ["testing"] = "1" <NEW_LINE> dotenv.load_dotenv('.env.testing') <NEW_LINE> conn = sqlite3.connect('data/' + os.environ['DB_NAME']) <NEW_LINE> install.createSchema(conn) <NEW_LINE> conn.close() <NEW_LINE> df = pd.read_csv('xor.csv') <NEW_LINE> net = backpropagation.Net('xor.csv', [df["col1"], df["col2"]], [df["exp_result"]], 1) <NEW_LINE> self.train_phase_output = train.train(net, "[3, 1]", 1000) <NEW_LINE> print("result is", self.train_phase_output.getLayer(len(self.train_phase_output.getLayers()) - 1).getValues()) <NEW_LINE> net2 = backpropagation.Net('xor.csv', [df["col1"], df["col2"]], [df["exp_result"]], 1) <NEW_LINE> self.predict_phase_output = predict.predict(net2) <NEW_LINE> print("The result is ", self.predict_phase_output.getLayer(len(self.predict_phase_output.getLayers()) - 1).getValues()) <NEW_LINE> <DEDENT> def test_stored_network_equals_read_one(self): <NEW_LINE> <INDENT> self.assertAlmostEqual( self.train_phase_output.getLayer(len(self.train_phase_output.getLayers()) - 1).getValues().all(), self.predict_phase_output.getLayer(len(self.predict_phase_output.getLayers()) - 1).getValues().all() ) <NEW_LINE> <DEDENT> def tearDown(self) -> None: <NEW_LINE> <INDENT> os.remove('data/testing.db') | Testing reading and writing network to db | 62598fa45fdd1c0f98e5de3f |
class LogStream(pulumi.CustomResource): <NEW_LINE> <INDENT> def __init__(__self__, __name__, __opts__=None, log_group_name=None, name=None): <NEW_LINE> <INDENT> if not __name__: <NEW_LINE> <INDENT> raise TypeError('Missing resource name argument (for URN creation)') <NEW_LINE> <DEDENT> if not isinstance(__name__, basestring): <NEW_LINE> <INDENT> raise TypeError('Expected resource name to be a string') <NEW_LINE> <DEDENT> if __opts__ and not isinstance(__opts__, pulumi.ResourceOptions): <NEW_LINE> <INDENT> raise TypeError('Expected resource options to be a ResourceOptions instance') <NEW_LINE> <DEDENT> __props__ = dict() <NEW_LINE> if not log_group_name: <NEW_LINE> <INDENT> raise TypeError('Missing required property log_group_name') <NEW_LINE> <DEDENT> elif not isinstance(log_group_name, basestring): <NEW_LINE> <INDENT> raise TypeError('Expected property log_group_name to be a basestring') <NEW_LINE> <DEDENT> __self__.log_group_name = log_group_name <NEW_LINE> __props__['logGroupName'] = log_group_name <NEW_LINE> if name and not isinstance(name, basestring): <NEW_LINE> <INDENT> raise TypeError('Expected property name to be a basestring') <NEW_LINE> <DEDENT> __self__.name = name <NEW_LINE> __props__['name'] = name <NEW_LINE> __self__.arn = pulumi.runtime.UNKNOWN <NEW_LINE> super(LogStream, __self__).__init__( 'aws:cloudwatch/logStream:LogStream', __name__, __props__, __opts__) <NEW_LINE> <DEDENT> def set_outputs(self, outs): <NEW_LINE> <INDENT> if 'arn' in outs: <NEW_LINE> <INDENT> self.arn = outs['arn'] <NEW_LINE> <DEDENT> if 'logGroupName' in outs: <NEW_LINE> <INDENT> self.log_group_name = outs['logGroupName'] <NEW_LINE> <DEDENT> if 'name' in outs: <NEW_LINE> <INDENT> self.name = outs['name'] | Provides a CloudWatch Log Stream resource. | 62598fa4236d856c2adc938e |
class IPrincipalsAddedToGroupEvent(IPrincipalsGroupEvent): <NEW_LINE> <INDENT> pass | Interface of event fired when principals were added to group | 62598fa46aa9bd52df0d4d71 |
class ResultCallback(CallbackBase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ResultCallback, self).__init__(*args, **kwargs) <NEW_LINE> self.host_ok = {} <NEW_LINE> self.host_unreachable = {} <NEW_LINE> self.host_failed = {} <NEW_LINE> <DEDENT> def v2_runner_on_unreachable(self, result): <NEW_LINE> <INDENT> self.host_unreachable[result._host.get_name()] = result <NEW_LINE> <DEDENT> def v2_runner_on_ok(self, result, *args, **kwargs): <NEW_LINE> <INDENT> self.host_ok[result._host.get_name()] = result <NEW_LINE> <DEDENT> def v2_runner_on_failed(self, result, *args, **kwargs): <NEW_LINE> <INDENT> self.host_failed[result._host.get_name()] = result | A sample callback plugin used for performing an action as results come in
If you want to collect all results into a single object for processing at
the end of the execution, look into utilizing the ``json`` callback plugin
or writing your own custom callback plugin | 62598fa499cbb53fe6830d7b |
class RunFlowFlags(object): <NEW_LINE> <INDENT> def __init__(self, browser_auth): <NEW_LINE> <INDENT> self.auth_host_port = [8080, 8090] <NEW_LINE> self.auth_host_name = "localhost" <NEW_LINE> self.logging_level = "ERROR" <NEW_LINE> self.noauth_local_webserver = not browser_auth | Flags for oauth2client.tools.run_flow. | 62598fa491f36d47f2230df6 |
class StateCache(object): <NEW_LINE> <INDENT> def __init__(self, initial_state): <NEW_LINE> <INDENT> self.states = [None] * STATE_CACHE_SIZE <NEW_LINE> self.current_state_index = 0 <NEW_LINE> self.num_prev_states = 0 <NEW_LINE> self.num_next_states = 0 <NEW_LINE> self.states[0] = initial_state <NEW_LINE> self.update_actions() <NEW_LINE> <DEDENT> def save_new_state(self, state): <NEW_LINE> <INDENT> self.current_state_index = (self.current_state_index + 1)%STATE_CACHE_SIZE <NEW_LINE> self.states[self.current_state_index] = state <NEW_LINE> self.num_prev_states = self.num_prev_states + 1 <NEW_LINE> if self.num_prev_states == STATE_CACHE_SIZE: self.num_prev_states = STATE_CACHE_SIZE - 1 <NEW_LINE> self.num_next_states = 0 <NEW_LINE> self.update_actions() <NEW_LINE> <DEDENT> def get_current_state(self): <NEW_LINE> <INDENT> self.update_actions() <NEW_LINE> return self.states[self.current_state_index] <NEW_LINE> <DEDENT> def get_prev_state(self): <NEW_LINE> <INDENT> if self.num_prev_states > 0: <NEW_LINE> <INDENT> self.current_state_index = (self.current_state_index + STATE_CACHE_SIZE -1)%STATE_CACHE_SIZE <NEW_LINE> self.num_next_states = self.num_next_states + 1 <NEW_LINE> self.num_prev_states = self.num_prev_states - 1 <NEW_LINE> return self.get_current_state() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_next_state(self): <NEW_LINE> <INDENT> if self.num_next_states > 0: <NEW_LINE> <INDENT> self.current_state_index = (self.current_state_index + 1)%STATE_CACHE_SIZE <NEW_LINE> self.num_next_states = self.num_next_states - 1 <NEW_LINE> self.num_prev_states = self.num_prev_states + 1 <NEW_LINE> return self.get_current_state() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def update_actions(self): <NEW_LINE> <INDENT> Actions.FLOW_GRAPH_REDO.set_sensitive(self.num_next_states != 0) <NEW_LINE> Actions.FLOW_GRAPH_UNDO.set_sensitive(self.num_prev_states != 0) | The state cache is an interface to a list to record data/states and to revert to previous states.
States are recorded into the list in a circular fassion by using an index for the current state,
and counters for the range where states are stored. | 62598fa4e64d504609df930d |
class MetamodelBuilder: <NEW_LINE> <INDENT> def add_module_attribute(self, module, spec): <NEW_LINE> <INDENT> if not spec: <NEW_LINE> <INDENT> return module <NEW_LINE> <DEDENT> attribute_name = spec['name'] <NEW_LINE> attribute_value = spec['arguments'] <NEW_LINE> if attribute_name in module.attributes_to_ignore: <NEW_LINE> <INDENT> return module <NEW_LINE> <DEDENT> if attribute_name in vars(module).keys(): <NEW_LINE> <INDENT> current_value = getattr(module, attribute_name) <NEW_LINE> if isinstance(current_value, list): <NEW_LINE> <INDENT> current_value.extend(attribute_value.split(LIST_SEPARATOR)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(module, attribute_name, attribute_value) <NEW_LINE> <DEDENT> <DEDENT> return module <NEW_LINE> <DEDENT> def add_model_attribute(self, model, spec): <NEW_LINE> <INDENT> for attribute_name in vars(model).keys(): <NEW_LINE> <INDENT> if attribute_name in model.attributes_to_ignore: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> value = spec.get(attribute_name) <NEW_LINE> if value: <NEW_LINE> <INDENT> current_value = getattr(model, attribute_name) <NEW_LINE> if isinstance(current_value, list): <NEW_LINE> <INDENT> current_value.extend(value.split(LIST_SEPARATOR)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(model, attribute_name, value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return model <NEW_LINE> <DEDENT> def add_model_field(self, model, spec): <NEW_LINE> <INDENT> if not spec: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> field = metamodel.Field(spec['name'], model) <NEW_LINE> for attribute_name in vars(field).keys(): <NEW_LINE> <INDENT> if attribute_name in field.attributes_to_ignore: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> value = spec.get(attribute_name) <NEW_LINE> if value is None or value is '': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> current_value = getattr(field, attribute_name) <NEW_LINE> if isinstance(current_value, list): <NEW_LINE> <INDENT> current_value.extend(value.split(LIST_SEPARATOR)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(field, attribute_name, value) <NEW_LINE> <DEDENT> <DEDENT> model.fields.append(field) <NEW_LINE> field.build_methods() <NEW_LINE> return field <NEW_LINE> <DEDENT> def build(self, file_iterator, add_attributes_functions=[]): <NEW_LINE> <INDENT> module = metamodel.Module() <NEW_LINE> last_model_name = None <NEW_LINE> for line in file_iterator: <NEW_LINE> <INDENT> _logger.debug(line) <NEW_LINE> if line['model_name']: <NEW_LINE> <INDENT> last_model_name = line['model_name'] <NEW_LINE> <DEDENT> if not line['model_name'] and last_model_name: <NEW_LINE> <INDENT> line['model_name'] = last_model_name <NEW_LINE> <DEDENT> if not line['model_name']: <NEW_LINE> <INDENT> raise exceptions.ParserException('Line doesn\'t refer to any Model name') <NEW_LINE> <DEDENT> if last_model_name == '__manifest__': <NEW_LINE> <INDENT> self.add_module_attribute(module, line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not last_model_name in module.models: <NEW_LINE> <INDENT> module.models[last_model_name] = metamodel.Model(last_model_name, module) <NEW_LINE> <DEDENT> model = module.models[last_model_name] <NEW_LINE> self.add_model_attribute(model, line) <NEW_LINE> field = self.add_model_field(model, line) <NEW_LINE> for add_attribute_func in add_attributes_functions: <NEW_LINE> <INDENT> add_attribute_func(module, model, field, line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return module | This class generates a Module and all its Models and Fields from a spec | 62598fa48e7ae83300ee8f49 |
class Fractal: <NEW_LINE> <INDENT> def __init__(self, size, scale, computation): <NEW_LINE> <INDENT> self.scale = scale <NEW_LINE> self.size = size <NEW_LINE> self.computation = computation <NEW_LINE> self.coordinate_step_for_x = abs(self.scale[0][0] - self.scale[1][0]) / self.size[0] <NEW_LINE> self.coordinate_step_for_y = abs(self.scale[0][1] - self.scale[1][1]) / self.size[1] <NEW_LINE> self.iteration_for_pixel_dict = dict() <NEW_LINE> self.im = Image.new("RGB", self.size) <NEW_LINE> <DEDENT> def compute(self): <NEW_LINE> <INDENT> d = ImageDraw.Draw(self.im) <NEW_LINE> for y_num, y in enumerate([self.scale[1][1] - self.coordinate_step_for_y * a for a in range(self.size[1])]): <NEW_LINE> <INDENT> print("{} of {}".format(y_num, self.size[1])) <NEW_LINE> for x_num, x in enumerate([self.scale[0][0] + self.coordinate_step_for_x * b for b in range(self.size[0])]): <NEW_LINE> <INDENT> key = self.pixel_value((x, y)) <NEW_LINE> if self.iteration_for_pixel_dict.get(key) is None: <NEW_LINE> <INDENT> value = [(x_num, y_num)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.iteration_for_pixel_dict.get(key).append((x_num, y_num)) <NEW_LINE> <DEDENT> self.iteration_for_pixel_dict.setdefault(key, value) <NEW_LINE> <DEDENT> <DEDENT> for iteration in self.iteration_for_pixel_dict.keys(): <NEW_LINE> <INDENT> m = self.iteration_for_pixel_dict.get(iteration) <NEW_LINE> red = (iteration / len(self.iteration_for_pixel_dict)) * 50 <NEW_LINE> green = 0 <NEW_LINE> blue = (iteration / len(self.iteration_for_pixel_dict)) * 100 <NEW_LINE> color_string = "rgb({}%,{}%,{}%)".format(str(int(red)), str(green), str(int(blue))) <NEW_LINE> d.point(m, fill=color_string) <NEW_LINE> <DEDENT> <DEDENT> def pixel_value(self, pixel): <NEW_LINE> <INDENT> return self.computation(pixel) <NEW_LINE> <DEDENT> def save_image(self, filename): <NEW_LINE> <INDENT> self.im.save(filename) <NEW_LINE> self.im.show() | Class for drawing fractal. | 62598fa4cc0a2c111447aeb7 |
class TestTradeApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = swagger_client.apis.trade_api.TradeApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_trade_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_trade_get_bucketed(self): <NEW_LINE> <INDENT> pass | TradeApi unit test stubs | 62598fa4097d151d1a2c0ece |
class LayerNorm(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_features, eps=1e-6): <NEW_LINE> <INDENT> super(LayerNorm, self).__init__() <NEW_LINE> self.a = nn.Parameter(torch.ones(num_features)) <NEW_LINE> self.b = nn.Parameter(torch.zeros(num_features)) <NEW_LINE> self.eps = eps <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> mean = x.mean(-1, keepdim=True) <NEW_LINE> std = ((x - mean).pow(2).sum(-1, keepdim=True).div(x.size(-1) - 1) + self.eps).sqrt() <NEW_LINE> d = (std + self.eps) + self.b <NEW_LINE> return self.a * (x - mean) / d | Applies Layer Normalization over a mini-batch of inputs as described in
the paper `Layer Normalization`_ .
.. math::
y = rac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x]} + \epsilon} * \gamma + eta
This is provided in pytorch's master, and can be replaced in the near future.
For the time, being, this code is adapted from:
http://nlp.seas.harvard.edu/2018/04/03/attention.html
https://github.com/pytorch/pytorch/pull/2019 | 62598fa4baa26c4b54d4f158 |
class Encoder: <NEW_LINE> <INDENT> def __init__(self, classes): <NEW_LINE> <INDENT> self.class_to_ix = {} <NEW_LINE> self.ix_to_class = {} <NEW_LINE> for cl in classes: <NEW_LINE> <INDENT> if cl not in self.class_to_ix: <NEW_LINE> <INDENT> ix = len(self.class_to_ix) <NEW_LINE> self.class_to_ix[cl] = ix <NEW_LINE> self.ix_to_class[ix] = cl <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def size(self): <NEW_LINE> <INDENT> return len(self.class_to_ix) <NEW_LINE> <DEDENT> def encode(self, cl): <NEW_LINE> <INDENT> return self.class_to_ix[cl] <NEW_LINE> <DEDENT> def decode(self, ix): <NEW_LINE> <INDENT> return self.ix_to_class[ix] | Mapping between classes and the corresponding indices.
>>> classes = ["English", "German", "French"]
>>> enc = Encoder(classes)
>>> assert "English" == enc.decode(enc.encode("English"))
>>> assert "German" == enc.decode(enc.encode("German"))
>>> assert "French" == enc.decode(enc.encode("French"))
>>> set(range(3)) == set(enc.encode(cl) for cl in classes)
True
>>> for cl in classes:
... ix = enc.encode(cl)
... assert 0 <= ix <= enc.size()
... assert cl == enc.decode(ix) | 62598fa463d6d428bbee2659 |
class Checker(object): <NEW_LINE> <INDENT> @property <NEW_LINE> def checks(self): <NEW_LINE> <INDENT> condition = lambda a: a.startswith('check_') <NEW_LINE> return (getattr(self, a) for a in dir(self) if condition(a)) <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> err_messages = [] <NEW_LINE> for ch in self.checks: <NEW_LINE> <INDENT> msgs = ch(*args, **kwargs) <NEW_LINE> if msgs: <NEW_LINE> <INDENT> err_messages.extend(msgs) <NEW_LINE> <DEDENT> <DEDENT> for em in err_messages: <NEW_LINE> <INDENT> log.critical(em) <NEW_LINE> <DEDENT> return err_messages | An abstract class that allow for defining checks as methods.
Each check should have the same signature, so that `check_all` can iterate
over them. Checks follow an unix-like convention of returning a value that
evaluate to False if the for no error conditions, and a value evaluating
to True (namely a list of error messages) if such conditions arise. | 62598fa4d7e4931a7ef3bf43 |
class Config(object): <NEW_LINE> <INDENT> yaml = CFTBaseYAML() <NEW_LINE> def __init__(self, item, project=None): <NEW_LINE> <INDENT> self.source = item <NEW_LINE> if project: <NEW_LINE> <INDENT> self._project = project <NEW_LINE> <DEDENT> if os.path.exists(item): <NEW_LINE> <INDENT> with io.open(item) as _fd: <NEW_LINE> <INDENT> self.as_string = jinja2.Template(_fd.read() ).render(env=os.environ) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.as_string = jinja2.Template(item).render(env=os.environ) <NEW_LINE> <DEDENT> self.as_dict = self.yaml.load(self.as_string) <NEW_LINE> <DEDENT> @property <NEW_LINE> def as_file(self): <NEW_LINE> <INDENT> return io.StringIO(self.as_string) <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return Node(self.project, self.deployment) <NEW_LINE> <DEDENT> @property <NEW_LINE> def deployment(self): <NEW_LINE> <INDENT> return self.as_dict.get( 'name', os.path.basename(self.source).split('.')[0] ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def project(self): <NEW_LINE> <INDENT> if not hasattr(self, '_project'): <NEW_LINE> <INDENT> self._project = self.as_dict.get('project') or os.environ.get('CLOUD_FOUNDATION_PROJECT_ID') or dm_base.GetProject() <NEW_LINE> <DEDENT> return self._project <NEW_LINE> <DEDENT> @property <NEW_LINE> def dependencies(self): <NEW_LINE> <INDENT> if hasattr(self, '_dependencies'): <NEW_LINE> <INDENT> return self._dependencies <NEW_LINE> <DEDENT> self._dependencies = set() <NEW_LINE> for line in self.as_file.readlines(): <NEW_LINE> <INDENT> if re.match(r'^\s*#', line): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for match in DM_OUTPUT_QUERY_REGEX.finditer(line): <NEW_LINE> <INDENT> for k, v in match.groupdict().items(): <NEW_LINE> <INDENT> if not v: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if k == 'url': <NEW_LINE> <INDENT> url = parse_dm_output_url(v, self.project) <NEW_LINE> <DEDENT> elif k == 'token': <NEW_LINE> <INDENT> url = parse_dm_output_token(v, self.project) <NEW_LINE> <DEDENT> self._dependencies.add(Node(url.project, url.deployment)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self._dependencies <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{}({}:{})'.format(self.__class__, self.deployment, self.project) | Class representing a CFT config.
Attributes:
as_file (io.StringIO): A file-like interface to the
jinja-rendered config.
as_string (string): the jinja-rendered config.
id (string): A base64-encoded id representing the path or raw
content of the config. Could be used as a dict key.
source (string): The path or the raw content of config (obtained
by base64-decoding the 'id' attribute | 62598fa424f1403a92685807 |
class SupermarketRecruit(BasePage, ElementRecruit): <NEW_LINE> <INDENT> u <NEW_LINE> def add_recruit(self, position_name='random',recruit_number='10',contact_way='0371-7981225', experience='3-5年',work_property=u'全职',salary=u'面议',education=u'高中', province=u'河南省',city=u'许昌市',country=u'鄢陵县',email='test@test.com', describe='ITS ONLY A TEST~!',**kwargs): <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> find_element = self.find_element <NEW_LINE> select = self.select <NEW_LINE> try: <NEW_LINE> <INDENT> find_element(self.recruit_link).click() <NEW_LINE> driver.switch_to_frame('iframe') <NEW_LINE> num_before = self.get_list_num(self.num) <NEW_LINE> if position_name == "random":position_name = self.creat_random_string() <NEW_LINE> find_element(self.add_tab).click() <NEW_LINE> find_element(self.position_name).send_keys(position_name) <NEW_LINE> find_element(self.recruit_number).send_keys(recruit_number) <NEW_LINE> find_element(self.contact_way).send_keys(contact_way) <NEW_LINE> self.select_new(self.experience, experience) <NEW_LINE> self.select_new(self.work_property, work_property) <NEW_LINE> self.select_new(self.salary, salary) <NEW_LINE> self.select_new(self.education, education) <NEW_LINE> self.select_new(self.province, province) <NEW_LINE> self.select_new(self.city, city) <NEW_LINE> self.select_new(self.country, country) <NEW_LINE> find_element(self.email).send_keys(email) <NEW_LINE> self.insert_html_to_richtext(self.describe[1], describe) <NEW_LINE> find_element(self.submit).click() <NEW_LINE> time.sleep(1) <NEW_LINE> num_after = self.get_list_num(self.num) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return output.error_user_defined(driver, "发布招聘信息失败") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> driver.switch_to_default_content() <NEW_LINE> <DEDENT> if 1 == (num_after - num_before): <NEW_LINE> <INDENT> return output.pass_user_defined(driver, "发布招聘信息成功",position_name=position_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return output.error_user_defined(driver, "发布招聘信息失败,数量没有增加") <NEW_LINE> <DEDENT> <DEDENT> def del_recruit(self, title,**kwargs): <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> find_element = self.find_element <NEW_LINE> select = self.select <NEW_LINE> try: <NEW_LINE> <INDENT> find_element(self.recruit_link).click() <NEW_LINE> driver.switch_to_frame('iframe') <NEW_LINE> num_before = self.get_list_num(self.num) <NEW_LINE> find_element((By.XPATH, self.del_link[1]%title)).click() <NEW_LINE> driver.switch_to_default_content() <NEW_LINE> find_element(self.confirm).click() <NEW_LINE> time.sleep(1) <NEW_LINE> driver.switch_to_frame('iframe') <NEW_LINE> num_after = self.get_list_num(self.num) <NEW_LINE> time.sleep(1) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return output.error_user_defined(driver, "删除公告失败") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> driver.switch_to_default_content() <NEW_LINE> <DEDENT> if 1 == (num_before - num_after): <NEW_LINE> <INDENT> return output.pass_user_defined(driver, "删除公告成功") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return output.error_user_defined(driver, "删除公告失败,数量没有减少") | 超市招聘信息 | 62598fa4090684286d59362f |
class IntBinLengthTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_0(self): <NEW_LINE> <INDENT> self.assertEqual(1, ga._int_bin_length(0)) <NEW_LINE> <DEDENT> def test_1(self): <NEW_LINE> <INDENT> self.assertEqual(1, ga._int_bin_length(1)) <NEW_LINE> <DEDENT> def test_2(self): <NEW_LINE> <INDENT> self.assertEqual(2, ga._int_bin_length(2)) <NEW_LINE> <DEDENT> def test_3(self): <NEW_LINE> <INDENT> self.assertEqual(2, ga._int_bin_length(3)) <NEW_LINE> <DEDENT> def test_32(self): <NEW_LINE> <INDENT> self.assertEqual(6, ga._int_bin_length(32)) <NEW_LINE> <DEDENT> def test_63(self): <NEW_LINE> <INDENT> self.assertEqual(6, ga._int_bin_length(63)) <NEW_LINE> <DEDENT> def test_255(self): <NEW_LINE> <INDENT> self.assertEqual(8, ga._int_bin_length(255)) | Test _int_bin_length | 62598fa4d6c5a102081e1fee |
class JoinLayer(Layer): <NEW_LINE> <INDENT> def __init__(self, drop_p, is_global, global_path, **kwargs): <NEW_LINE> <INDENT> self.p = 1. - drop_p <NEW_LINE> self.is_global = is_global <NEW_LINE> self.global_path = global_path <NEW_LINE> self.uses_learning_phase = True <NEW_LINE> super(JoinLayer, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def build(self, input_shape): <NEW_LINE> <INDENT> self.average_shape = list(input_shape[0])[1:] <NEW_LINE> <DEDENT> def _random_arr(self, count, p): <NEW_LINE> <INDENT> return K.random_binomial((count,), p=p) <NEW_LINE> <DEDENT> def _arr_with_one(self, count): <NEW_LINE> <INDENT> return rand_one_in_array(count=count) <NEW_LINE> <DEDENT> def _gen_local_drops(self, count, p): <NEW_LINE> <INDENT> arr = self._random_arr(count, p) <NEW_LINE> drops = K.switch( K.any(arr), arr, self._arr_with_one(count) ) <NEW_LINE> return drops <NEW_LINE> <DEDENT> def _gen_global_path(self, count): <NEW_LINE> <INDENT> return self.global_path[:count] <NEW_LINE> <DEDENT> def _drop_path(self, inputs): <NEW_LINE> <INDENT> count = len(inputs) <NEW_LINE> drops = K.switch( self.is_global, self._gen_global_path(count), self._gen_local_drops(count, self.p) ) <NEW_LINE> ave = K.zeros(shape=self.average_shape) <NEW_LINE> for i in range(0, count): <NEW_LINE> <INDENT> ave += inputs[i] * drops[i] <NEW_LINE> <DEDENT> sum = K.sum(drops) <NEW_LINE> ave = K.switch( K.not_equal(sum, 0.), ave/sum, ave) <NEW_LINE> return ave <NEW_LINE> <DEDENT> def _ave(self, inputs): <NEW_LINE> <INDENT> ave = inputs[0] <NEW_LINE> for input in inputs[1:]: <NEW_LINE> <INDENT> ave += input <NEW_LINE> <DEDENT> ave /= len(inputs) <NEW_LINE> return ave <NEW_LINE> <DEDENT> def call(self, inputs, mask=None): <NEW_LINE> <INDENT> output = K.in_train_phase(self._drop_path(inputs), self._ave(inputs)) <NEW_LINE> return output <NEW_LINE> <DEDENT> def compute_output_shape(self, input_shape): <NEW_LINE> <INDENT> return input_shape[0] | This layer will behave as Merge(mode='ave') during testing but
during training it will randomly select between using local or
global droppath and apply the average of the paths alive after
aplying the drops.
- Global: use the random shared tensor to select the paths.
- Local: sample a random tensor to select the paths. | 62598fa463d6d428bbee265a |
class DownNbrReasonNaIdentity(DownNbrReasonIdentity): <NEW_LINE> <INDENT> _prefix = 'mpls-ldp-ios-xe-oper' <NEW_LINE> _revision = '2017-02-07' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> DownNbrReasonIdentity.__init__(self) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.cisco_ios_xe._meta import _Cisco_IOS_XE_mpls_ldp as meta <NEW_LINE> return meta._meta_table['DownNbrReasonNaIdentity']['meta_info'] | Not applicable, the neighbor is up.. | 62598fa4be383301e02536a0 |
class BaseReporter(object): <NEW_LINE> <INDENT> only_full_id = False <NEW_LINE> header = ["********************** Slide Deck {path}"] <NEW_LINE> footer = [""] <NEW_LINE> formatter = None <NEW_LINE> def __init__(self, show_id, mute_ids, path): <NEW_LINE> <INDENT> self.show_id = self.only_full_id or show_id <NEW_LINE> self.mute_ids = mute_ids <NEW_LINE> self.path = os.path.split(path)[1] <NEW_LINE> self.update_title() <NEW_LINE> <DEDENT> def update_title(self): <NEW_LINE> <INDENT> self.header[0] = self.header[0].format(path=self.path) <NEW_LINE> <DEDENT> def preformatfix(self, msg): <NEW_LINE> <INDENT> msg['msg_id'] = msg['id'][0] if not self.show_id else msg['id'] <NEW_LINE> msg['path'] = self.path <NEW_LINE> return msg <NEW_LINE> <DEDENT> def apply_formating(self, messages): <NEW_LINE> <INDENT> return [self.formatter.format(**msg) for msg in messages] <NEW_LINE> <DEDENT> def __call__(self, report): <NEW_LINE> <INDENT> filtred = [self.preformatfix(msg) for msg in report if msg['id'] not in self.mute_ids] <NEW_LINE> fixed_isd = [self.preformatfix(msg) for msg in filtred] <NEW_LINE> rez = self.header + self.apply_formating(fixed_isd) + self.footer <NEW_LINE> return "\n".join(rez) + "\n" | Basic class for creating reports from raw checks results | 62598fa4dd821e528d6d8ddc |
class ProximityPlacementGroup(Resource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, 'virtual_machines': {'readonly': True}, 'virtual_machine_scale_sets': {'readonly': True}, 'availability_sets': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'proximity_placement_group_type': {'key': 'properties.proximityPlacementGroupType', 'type': 'str'}, 'virtual_machines': {'key': 'properties.virtualMachines', 'type': '[SubResourceWithColocationStatus]'}, 'virtual_machine_scale_sets': {'key': 'properties.virtualMachineScaleSets', 'type': '[SubResourceWithColocationStatus]'}, 'availability_sets': {'key': 'properties.availabilitySets', 'type': '[SubResourceWithColocationStatus]'}, 'colocation_status': {'key': 'properties.colocationStatus', 'type': 'InstanceViewStatus'}, } <NEW_LINE> def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, proximity_placement_group_type: Optional[Union[str, "ProximityPlacementGroupType"]] = None, colocation_status: Optional["InstanceViewStatus"] = None, **kwargs ): <NEW_LINE> <INDENT> super(ProximityPlacementGroup, self).__init__(location=location, tags=tags, **kwargs) <NEW_LINE> self.proximity_placement_group_type = proximity_placement_group_type <NEW_LINE> self.virtual_machines = None <NEW_LINE> self.virtual_machine_scale_sets = None <NEW_LINE> self.availability_sets = None <NEW_LINE> self.colocation_status = colocation_status | Specifies information about the proximity placement group.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:ivar location: Required. Resource location.
:vartype location: str
:ivar tags: A set of tags. Resource tags.
:vartype tags: dict[str, str]
:ivar proximity_placement_group_type: Specifies the type of the proximity placement group.
:code:`<br>`:code:`<br>` Possible values are: :code:`<br>`:code:`<br>` **Standard** : Co-locate
resources within an Azure region or Availability Zone. :code:`<br>`:code:`<br>` **Ultra** : For
future use. Possible values include: "Standard", "Ultra".
:vartype proximity_placement_group_type: str or
~azure.mgmt.compute.v2021_11_01.models.ProximityPlacementGroupType
:ivar virtual_machines: A list of references to all virtual machines in the proximity placement
group.
:vartype virtual_machines:
list[~azure.mgmt.compute.v2021_11_01.models.SubResourceWithColocationStatus]
:ivar virtual_machine_scale_sets: A list of references to all virtual machine scale sets in the
proximity placement group.
:vartype virtual_machine_scale_sets:
list[~azure.mgmt.compute.v2021_11_01.models.SubResourceWithColocationStatus]
:ivar availability_sets: A list of references to all availability sets in the proximity
placement group.
:vartype availability_sets:
list[~azure.mgmt.compute.v2021_11_01.models.SubResourceWithColocationStatus]
:ivar colocation_status: Describes colocation status of the Proximity Placement Group.
:vartype colocation_status: ~azure.mgmt.compute.v2021_11_01.models.InstanceViewStatus | 62598fa45166f23b2e24327f |
class Function(DeclNode): <NEW_LINE> <INDENT> def __init__(self, args, child): <NEW_LINE> <INDENT> self.args = args <NEW_LINE> self.child = child <NEW_LINE> super().__init__() | Represents an function with given arguments and returning given type.
args (List(Node)) - arguments of the functions. | 62598fa4e1aae11d1e7ce777 |
class AoiView(aoi.AoiView): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(methods=["-DRAW", "-POINTS"], **kwargs) <NEW_LINE> self.elevation = False <NEW_LINE> self.btn.color = "secondary" <NEW_LINE> <DEDENT> @su.loading_button(debug=False) <NEW_LINE> def _update_aoi(self, widget, event, data): <NEW_LINE> <INDENT> self.model.set_object() <NEW_LINE> if self.map_: <NEW_LINE> <INDENT> [self.map_.remove_layer(lr) for lr in self.map_.layers if lr.name == "aoi"] <NEW_LINE> self.map_.zoom_bounds(self.model.total_bounds()) <NEW_LINE> if self.ee: <NEW_LINE> <INDENT> empty = ee.Image().byte() <NEW_LINE> outline = empty.paint( featureCollection=self.model.feature_collection, color=1, width=2 ) <NEW_LINE> self.map_.addLayer(outline, {"palette": sc.primary}, "aoi") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.map_.add_layer(self.model.get_ipygeojson()) <NEW_LINE> <DEDENT> self.map_.hide_dc() <NEW_LINE> <DEDENT> self.updated += 1 | Extend the aoi_view component from sepal_ui.mapping to add
the extra coloring parameter used in this application. To do so we were
forced to copy/paste the _update_aoi | 62598fa4a8ecb033258710b7 |
class Deposit(Asset): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> raise NotImplementedError | Short term cash deposit paying simple (not compounded) interest | 62598fa438b623060ffa8f3d |
class Run_attribute(Base): <NEW_LINE> <INDENT> __tablename__ = 'run_attribute' <NEW_LINE> __table_args__ = ( UniqueConstraint('run_id', 'attribute_name', 'attribute_value'), { 'mysql_engine':'InnoDB', 'mysql_charset':'utf8' }) <NEW_LINE> run_attribute_id = Column(INTEGER(unsigned=True), primary_key=True, nullable=False) <NEW_LINE> attribute_name = Column(String(30)) <NEW_LINE> attribute_value = Column(String(50)) <NEW_LINE> run_id = Column(INTEGER(unsigned=True), ForeignKey('run.run_id', onupdate="CASCADE", ondelete="CASCADE"), nullable=False) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "Run_attribute(run_attribute_id = '{self.run_attribute_id}'," "attribute_name = '{self.attribute_name}'," "attribute_value = '{self.attribute_value}'," "run_id = '{self.run_id}')".format(self=self) | A table for loading run attributes
:param run_attribute_id: An integer id for run_attribute table
:param attribute_name: An optional string attribute name, allowed length 30
:param attribute_value: An optional string attribute value, allowed length 50
:param run_id: An integer id from run table (foreign key) | 62598fa44428ac0f6e6583d4 |
class AwsProvisioningChecker(AbstractProvisioningChecker): <NEW_LINE> <INDENT> def get_state_file_path(self): <NEW_LINE> <INDENT> return "/var/lib/jenkins/workspace/dt_aws/provisioning/terraform/aws/terraform.tfstate" <NEW_LINE> <DEDENT> def get_grep_term(self): <NEW_LINE> <INDENT> return "public_dns = " | checks aws provisioning | 62598fa4a17c0f6771d5c0dd |
class DataPoint(Base): <NEW_LINE> <INDENT> __tablename__= "data_point" <NEW_LINE> id = Column(Integer(), primary_key=True) <NEW_LINE> name = Column(String(80), default="Anonymous") <NEW_LINE> N = Column(Float(), nullable=False) <NEW_LINE> Rstar = Column(Float(), nullable=False) <NEW_LINE> fp = Column(Float(), nullable=False) <NEW_LINE> ne = Column(Float(), nullable=False) <NEW_LINE> fl = Column(Float(), nullable=False) <NEW_LINE> fi = Column(Float(), nullable=False) <NEW_LINE> fc = Column(Float(), nullable=False) <NEW_LINE> L = Column(Float(), nullable=False) <NEW_LINE> created_on = Column(DateTime(timezone=True), server_default=func.now()) <NEW_LINE> @property <NEW_LINE> def serialize(self): <NEW_LINE> <INDENT> return { "id": self.id, "name": self.name, "N": self.N, "Rstar": self.Rstar, "fp": self.fp, "ne": self.ne, "fl": self.fl, "fi": self.fi, "fc": self.fc, "L": self.L, "created_on" : self.created_on } | A datapoint that the user has determined. | 62598fa45fdd1c0f98e5de41 |
class LatencyMetric(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name': {'readonly': True}, 'end_date_time_utc': {'readonly': True}, 'a_value': {'readonly': True}, 'b_value': {'readonly': True}, 'delta': {'readonly': True}, 'delta_percent': {'readonly': True}, 'a_c_lower95_ci': {'readonly': True}, 'a_h_upper95_ci': {'readonly': True}, 'b_c_lower95_ci': {'readonly': True}, 'b_upper95_ci': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'end_date_time_utc': {'key': 'endDateTimeUTC', 'type': 'str'}, 'a_value': {'key': 'aValue', 'type': 'float'}, 'b_value': {'key': 'bValue', 'type': 'float'}, 'delta': {'key': 'delta', 'type': 'float'}, 'delta_percent': {'key': 'deltaPercent', 'type': 'float'}, 'a_c_lower95_ci': {'key': 'aCLower95CI', 'type': 'float'}, 'a_h_upper95_ci': {'key': 'aHUpper95CI', 'type': 'float'}, 'b_c_lower95_ci': {'key': 'bCLower95CI', 'type': 'float'}, 'b_upper95_ci': {'key': 'bUpper95CI', 'type': 'float'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(LatencyMetric, self).__init__(**kwargs) <NEW_LINE> self.name = None <NEW_LINE> self.end_date_time_utc = None <NEW_LINE> self.a_value = None <NEW_LINE> self.b_value = None <NEW_LINE> self.delta = None <NEW_LINE> self.delta_percent = None <NEW_LINE> self.a_c_lower95_ci = None <NEW_LINE> self.a_h_upper95_ci = None <NEW_LINE> self.b_c_lower95_ci = None <NEW_LINE> self.b_upper95_ci = None | Defines the properties of a latency metric used in the latency scorecard.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: The name of the Latency Metric.
:vartype name: str
:ivar end_date_time_utc: The end time of the Latency Scorecard in UTC.
:vartype end_date_time_utc: str
:ivar a_value: The metric value of the A endpoint.
:vartype a_value: float
:ivar b_value: The metric value of the B endpoint.
:vartype b_value: float
:ivar delta: The difference in value between endpoint A and B.
:vartype delta: float
:ivar delta_percent: The percent difference between endpoint A and B.
:vartype delta_percent: float
:ivar a_c_lower95_ci: The lower end of the 95% confidence interval for endpoint A.
:vartype a_c_lower95_ci: float
:ivar a_h_upper95_ci: The upper end of the 95% confidence interval for endpoint A.
:vartype a_h_upper95_ci: float
:ivar b_c_lower95_ci: The lower end of the 95% confidence interval for endpoint B.
:vartype b_c_lower95_ci: float
:ivar b_upper95_ci: The upper end of the 95% confidence interval for endpoint B.
:vartype b_upper95_ci: float | 62598fa4435de62698e9bc9d |
class Cuboid: <NEW_LINE> <INDENT> def __init__(self, x_range, y_range, z_range): <NEW_LINE> <INDENT> if x_range[0] >= x_range[1]: raise RuntimeError("bad x") <NEW_LINE> if y_range[0] >= y_range[1]: raise RuntimeError("bad y") <NEW_LINE> if z_range[0] >= z_range[1]: raise RuntimeError("bad z") <NEW_LINE> self.x_range = x_range <NEW_LINE> self.y_range = y_range <NEW_LINE> self.z_range = z_range <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "(%s, %s, %s)" % (str(self.x_range), str(self.y_range), str(self.z_range)) <NEW_LINE> <DEDENT> def generate(self): <NEW_LINE> <INDENT> for x in range(*self.x_range): <NEW_LINE> <INDENT> for y in range(*self.y_range): <NEW_LINE> <INDENT> for z in range(*self.z_range): <NEW_LINE> <INDENT> yield (x, y, z) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def generate_xz(self): <NEW_LINE> <INDENT> for x in range(*self.x_range): <NEW_LINE> <INDENT> for z in range(*self.z_range): <NEW_LINE> <INDENT> yield (x, z) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def total_blocks(self): <NEW_LINE> <INDENT> return ((self.x_range[1] - self.x_range[0]) * (self.y_range[1] - self.y_range[0]) * (self.z_range[1] - self.z_range[0])) | A cuboid represents a 3-dimensional rectangular area
The constructor takes ranges along the x, y, and z axis,
where each range is a tuple(min, max) of world coordinates.
Ranges are integers and are used like the Python built-in range
function where the second number is one past the end. Specifically,
to get a single point along an axis, use something like tuple(0, 1).
Examples:
# A point at (100,12, 5)
>>> point = Cuboid((100,101), (12,13), (5,6))
# An 11 by 11 square centered around (0,0):
>>> c = Cuboid((-5, 6), (0, 1), (-5, 6))
>>> c.x_range
(-5, 6)
>>> g = c.generate()
>>> for point in g: print(p) | 62598fa432920d7e50bc5eff |
class VideoTagListResponse(messages.Message): <NEW_LINE> <INDENT> items = messages.MessageField( VideoTagResponseMessage, 1, repeated=True) <NEW_LINE> is_list = messages.BooleanField(2) | ProtoRPC message definition to represent a list of stored
video tags returned in a suitable format. | 62598fa4fbf16365ca793f65 |
class DeleteAMQPQueueResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RequestId = params.get("RequestId") | DeleteAMQPQueue返回参数结构体
| 62598fa43539df3088ecc15d |
class ProductionConfig(BaseConfig): <NEW_LINE> <INDENT> pass | 生产环境配置 | 62598fa430bbd722464698cc |
class itkSize1(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __swig_destroy__ = _itkSizePython.delete_itkSize1 <NEW_LINE> def GetSizeDimension(): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1_GetSizeDimension() <NEW_LINE> <DEDENT> GetSizeDimension = staticmethod(GetSizeDimension) <NEW_LINE> def __add__(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___add__(self, *args) <NEW_LINE> <DEDENT> def __iadd__(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___iadd__(self, *args) <NEW_LINE> <DEDENT> def __sub__(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___sub__(self, *args) <NEW_LINE> <DEDENT> def __isub__(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___isub__(self, *args) <NEW_LINE> <DEDENT> def __mul__(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___mul__(self, *args) <NEW_LINE> <DEDENT> def __imul__(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___imul__(self, *args) <NEW_LINE> <DEDENT> def __eq__(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___eq__(self, *args) <NEW_LINE> <DEDENT> def __ne__(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___ne__(self, *args) <NEW_LINE> <DEDENT> def GetSize(self): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1_GetSize(self) <NEW_LINE> <DEDENT> def SetSize(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1_SetSize(self, *args) <NEW_LINE> <DEDENT> def SetElement(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1_SetElement(self, *args) <NEW_LINE> <DEDENT> def GetElement(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1_GetElement(self, *args) <NEW_LINE> <DEDENT> def Fill(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1_Fill(self, *args) <NEW_LINE> <DEDENT> def __init__(self, *args): <NEW_LINE> <INDENT> _itkSizePython.itkSize1_swiginit(self,_itkSizePython.new_itkSize1(*args)) <NEW_LINE> <DEDENT> def __getitem__(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___getitem__(self, *args) <NEW_LINE> <DEDENT> def __setitem__(self, *args): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___setitem__(self, *args) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___len__(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return _itkSizePython.itkSize1___repr__(self) | Proxy of C++ itkSize1 class | 62598fa476e4537e8c3ef456 |
class TestContacts(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> copyfile('example_contacts.json', 'test_contacts.json') <NEW_LINE> self.json_file = 'test_contacts.json' <NEW_LINE> self.data = contacts.ContactData(self.json_file) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> os.remove('test_contacts.json') <NEW_LINE> <DEDENT> def test_read_json(self): <NEW_LINE> <INDENT> with open(self.json_file, 'r') as f: <NEW_LINE> <INDENT> raw = json.load(f) <NEW_LINE> raw.sort(key=lambda k: k['name']) <NEW_LINE> correct_result = raw <NEW_LINE> <DEDENT> self.assertEqual(self.data.contacts, correct_result) <NEW_LINE> <DEDENT> def test_repr(self): <NEW_LINE> <INDENT> correct_result = f'ContactData({self.json_file})' <NEW_LINE> self.assertEqual(repr(self.data), correct_result) <NEW_LINE> <DEDENT> def test_overwrite(self): <NEW_LINE> <INDENT> with patch('sys.stderr', new=StringIO()) as mock_stderr: <NEW_LINE> <INDENT> self.data.overwrite() <NEW_LINE> correct_stderr = 'overwriting ... test_contacts.json' <NEW_LINE> self.assertEqual(mock_stderr.getvalue(), correct_stderr) <NEW_LINE> <DEDENT> with open(self.json_file, 'r') as overwritten_f: <NEW_LINE> <INDENT> test_data = json.load(overwritten_f) <NEW_LINE> <DEDENT> with open('example_contacts.json', 'r') as correct_f: <NEW_LINE> <INDENT> example_data = json.load(correct_f) <NEW_LINE> <DEDENT> correct_result = sorted(example_data, key=lambda k: k['name']) <NEW_LINE> self.assertEqual(test_data, correct_result) <NEW_LINE> <DEDENT> def test_query(self): <NEW_LINE> <INDENT> query_string = 'Rick' <NEW_LINE> test_indices = self.data.query(query_string) <NEW_LINE> correct_indices = {68, 13, 15, 18, 21, 56, 59} <NEW_LINE> self.assertEqual(test_indices, correct_indices) <NEW_LINE> <DEDENT> def test_list_matches(self): <NEW_LINE> <INDENT> test_indices = {56, 46} <NEW_LINE> test_matches = self.data.list_matches(test_indices) <NEW_LINE> correct_result = [ {'name': 'Rick Sanchez', 'email': ['rick.sanchez@plumbus.com'], 'phone': ['07655266089'], 'uuid': 'ca064182-6b04-11eb-844f-274375519e58', 'tags': []}, {'name': 'Morty Smith', 'email': ['morty.smith@plumbus.com'], 'phone': ['07698312584'], 'uuid': 'ca063a5c-6b04-11eb-844f-274375519e58', 'tags': []} ] <NEW_LINE> self.assertEqual(test_matches, correct_result) <NEW_LINE> <DEDENT> def test_show(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_export(self): <NEW_LINE> <INDENT> with patch('sys.stdout', new=StringIO()) as mock_stdout: <NEW_LINE> <INDENT> self.data.export(range(len(self.data.contacts))) <NEW_LINE> test_export = mock_stdout.getvalue() <NEW_LINE> correct_export = json.dumps(self.data.contacts) <NEW_LINE> self.assertEqual(test_export, correct_export) <NEW_LINE> <DEDENT> <DEDENT> def test_edit(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_modify(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_add(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_import_json(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_field(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_delete(self): <NEW_LINE> <INDENT> pass | Test contact management utilities | 62598fa48e7ae83300ee8f4a |
class ModelSelector(object): <NEW_LINE> <INDENT> def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str, n_constant=3, min_n_components=2, max_n_components=10, random_state=14, verbose=False): <NEW_LINE> <INDENT> self.words = all_word_sequences <NEW_LINE> self.hwords = all_word_Xlengths <NEW_LINE> self.sequences = all_word_sequences[this_word] <NEW_LINE> self.X, self.lengths = all_word_Xlengths[this_word] <NEW_LINE> self.this_word = this_word <NEW_LINE> self.n_constant = n_constant <NEW_LINE> self.min_n_components = min_n_components <NEW_LINE> self.max_n_components = max_n_components <NEW_LINE> self.random_state = random_state <NEW_LINE> self.verbose = verbose <NEW_LINE> self.n_components = range(self.min_n_components, self.max_n_components + 1) <NEW_LINE> <DEDENT> def select(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def base_model(self, num_states): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", category=DeprecationWarning) <NEW_LINE> try: <NEW_LINE> <INDENT> hmm_model = GaussianHMM(n_components=num_states, covariance_type="diag", n_iter=1000, random_state=self.random_state, verbose=False).fit(self.X, self.lengths) <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> print("Model created for {} with {} states" .format(self.this_word, num_states)) <NEW_LINE> <DEDENT> return hmm_model <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> print("failure on {} with {} states". format(self.this_word, num_states)) <NEW_LINE> <DEDENT> return None | Base class for model selection (strategy design pattern).
| 62598fa48e7ae83300ee8f4b |
class Cell: <NEW_LINE> <INDENT> def __init__(self, x, y, data, state): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.data = data <NEW_LINE> self.state = state <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> print("x: " + str(self.x) + ", y: " + str(self.y) + ", data: " + str(self.data) + ", state: " + str(self.state)) | Initialises a new cell. | 62598fa476e4537e8c3ef457 |
class TPTextureRenderer(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "uv.tp_texture_renderer" <NEW_LINE> bl_label = "Texture renderer" <NEW_LINE> __handle = None <NEW_LINE> __timer = None <NEW_LINE> @staticmethod <NEW_LINE> def handle_add(self, context): <NEW_LINE> <INDENT> TPTextureRenderer.__handle = bpy.types.SpaceView3D.draw_handler_add( TPTextureRenderer.draw_texture, (self, context), 'WINDOW', 'POST_PIXEL') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def handle_remove(self, context): <NEW_LINE> <INDENT> if TPTextureRenderer.__handle is not None: <NEW_LINE> <INDENT> bpy.types.SpaceView3D.draw_handler_remove( TPTextureRenderer.__handle, 'WINDOW') <NEW_LINE> TPTextureRenderer.__handle = None <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def draw_texture(self, context): <NEW_LINE> <INDENT> wm = context.window_manager <NEW_LINE> sc = context.scene <NEW_LINE> if sc.tex_image == "None": <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> rect = get_canvas(context, sc.tex_magnitude) <NEW_LINE> positions = [ [rect.x0, rect.y0], [rect.x0, rect.y1], [rect.x1, rect.y1], [rect.x1, rect.y0] ] <NEW_LINE> tex_coords = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]] <NEW_LINE> img = bpy.data.images[sc.tex_image] <NEW_LINE> bgl.glEnable(bgl.GL_BLEND) <NEW_LINE> bgl.glEnable(bgl.GL_TEXTURE_2D) <NEW_LINE> if img.bindcode: <NEW_LINE> <INDENT> bind = img.bindcode <NEW_LINE> bgl.glBindTexture(bgl.GL_TEXTURE_2D, bind) <NEW_LINE> bgl.glTexParameteri( bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MIN_FILTER, bgl.GL_LINEAR) <NEW_LINE> bgl.glTexParameteri( bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER, bgl.GL_LINEAR) <NEW_LINE> bgl.glTexEnvi( bgl.GL_TEXTURE_ENV, bgl.GL_TEXTURE_ENV_MODE, bgl.GL_MODULATE) <NEW_LINE> <DEDENT> bgl.glBegin(bgl.GL_QUADS) <NEW_LINE> bgl.glColor4f(1.0, 1.0, 1.0, sc.tex_transparency) <NEW_LINE> for (v1, v2), (u, v) in zip(positions, tex_coords): <NEW_LINE> <INDENT> bgl.glTexCoord2f(u, v) <NEW_LINE> bgl.glVertex2f(v1, v2) <NEW_LINE> <DEDENT> bgl.glEnd() | Rendering texture | 62598fa421bff66bcd722b10 |
class Top_Endzone(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self,screen,colour,y_position): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.image = pygame.Surface(((screen.get_width()-50),40)) <NEW_LINE> self.image = self.image.convert() <NEW_LINE> self.image.fill (colour) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.left = 50 <NEW_LINE> self.rect.top = y_position | This class defines the sprite for the top endzones | 62598fa48c0ade5d55dc35e5 |
class Gaussian(_Prior): <NEW_LINE> <INDENT> density = "gaussian" <NEW_LINE> def __init__(self, mean, standard_deviation, lower=float("-inf"), upper=float("inf"), eta=None, name=None): <NEW_LINE> <INDENT> super().__init__(name=name) <NEW_LINE> _validate_bounds(lower, mean, upper) <NEW_LINE> _validate_standard_deviation(standard_deviation) <NEW_LINE> self.lower = lower <NEW_LINE> self.upper = upper <NEW_LINE> self.mean = mean <NEW_LINE> self.standard_deviation = standard_deviation <NEW_LINE> self.eta = eta <NEW_LINE> <DEDENT> def mle(self, draws): <NEW_LINE> <INDENT> mean, std = stats.norm.fit(draws) <NEW_LINE> return self.assign( mean=min(self.upper, max(self.lower, mean)), standard_deviation=std ) <NEW_LINE> <DEDENT> def make_draws(self, size: int, random_state: Optional[np.random.RandomState] = None): <NEW_LINE> <INDENT> return stats.norm.rvs( loc=self.mean, scale=self.standard_deviation, size=size, random_state=random_state ) <NEW_LINE> <DEDENT> def _parameters(self): <NEW_LINE> <INDENT> return { "lower": self.lower, "upper": self.upper, "mean": self.mean, "std": self.standard_deviation, "eta": self.eta, } | A Gaussian is
.. math::
f(x) = \frac{1}{2\pi \sigma^2} e^{-(x-\mu)^2/(2\sigma^2)}
where :math:`\sigma` is the variance and :math:`\mu` the mean.
Args:
mean (float): This is :math:`\mu`.
standard_deviation (float): This is :math:`\sigma`.
lower (float): lower limit.
upper (float): upper limit.
eta (float): Offset for calculating standard deviation.
name (str): Name for this prior. | 62598fa4d486a94d0ba2be79 |
class CanSubmitToAgency(permissions.BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> deqar_profile = DEQARProfile.objects.get(user=request.user) <NEW_LINE> try: <NEW_LINE> <INDENT> report_file = ReportFile.objects.get(pk=view.kwargs['pk']) <NEW_LINE> return deqar_profile.submitting_agency.agency_allowed(report_file.report.agency) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return False | Object-level permission to only allow users who are allowed to submit for a particular agency. | 62598fa4796e427e5384e63e |
class Game: <NEW_LINE> <INDENT> def __init__(self, player1, player2): <NEW_LINE> <INDENT> self.p1 = player1 <NEW_LINE> self.p2 = player2 <NEW_LINE> self.turn = 0 <NEW_LINE> <DEDENT> def play(self): <NEW_LINE> <INDENT> while not self.game_over: <NEW_LINE> <INDENT> if self.turn % 2 == 0: <NEW_LINE> <INDENT> self.p1.choose(self.p2)(self.p2) <NEW_LINE> <DEDENT> elif self.turn % 2 == 1: <NEW_LINE> <INDENT> self.p2.choose(self.p1)(self.p1) <NEW_LINE> <DEDENT> self.turn += 1 <NEW_LINE> <DEDENT> return self.winner <NEW_LINE> <DEDENT> @property <NEW_LINE> def game_over(self): <NEW_LINE> <INDENT> return max(self.p1.votes, self.p2.votes) >= 50 or self.turn >= 10 <NEW_LINE> <DEDENT> @property <NEW_LINE> def winner(self): <NEW_LINE> <INDENT> if self.p1.votes > self.p2.votes: <NEW_LINE> <INDENT> return self.p1 <NEW_LINE> <DEDENT> elif self.p2.votes < self.p1.votes: <NEW_LINE> <INDENT> return self.p2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | >>> p1, p2 = Player('Hill'), Player('Don')
>>> g = Game(p1, p2)
>>> winner = g.play()
>>> p1 is winner
True | 62598fa401c39578d7f12c2a |
class ValidationPolicy(object): <NEW_LINE> <INDENT> proxy_ip: ProxyIP = None <NEW_LINE> def __init__(self, proxy_ip: ProxyIP): <NEW_LINE> <INDENT> self.proxy_ip = proxy_ip <NEW_LINE> <DEDENT> def should_validate(self) -> bool: <NEW_LINE> <INDENT> if self.proxy_ip.attempts == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.proxy_ip.attempts < 3 and datetime.now() - self.proxy_ip.created_at < timedelta(hours=24) and not self.proxy_ip.is_valid: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif timedelta(hours=48) > datetime.now() - self.proxy_ip.created_at > timedelta(hours=24) and self.proxy_ip.attempts < 6: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif datetime.now() - self.proxy_ip.created_at < timedelta(days=7) and self.proxy_ip.attempts < 21 and self.proxy_ip.is_valid: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def should_try_https(self) -> bool: <NEW_LINE> <INDENT> if self.proxy_ip.is_valid and self.proxy_ip.attempts < 3 and self.proxy_ip.https_attempts == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | ValidationPolicy will make decision about validating a proxy IP from the following aspects:
1. Whether or not to validate the proxy
2. Use http or https to validate the proxy
After 3 attempts, the validator should try no more attempts in 24 hours after its creation. | 62598fa432920d7e50bc5f01 |
class ProjectPictureUpload(GalleryAccessMixin, View): <NEW_LINE> <INDENT> template_name = 'projects/picture_form.html' <NEW_LINE> form_class = ProjectPictureForm <NEW_LINE> gallery = None <NEW_LINE> def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> self.object = self.get_object() <NEW_LINE> self.gallery = get_gallery(self.object, kwargs.get('gallery_pk')) <NEW_LINE> return super(ProjectPictureUpload, self).dispatch(*args, **kwargs) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(ProjectPictureUpload, self).get_context_data(**kwargs) <NEW_LINE> return context <NEW_LINE> <DEDENT> def get(self, request, **kwargs): <NEW_LINE> <INDENT> context = self.get_context_data(**kwargs) <NEW_LINE> context['form'] = self.form_class() <NEW_LINE> return render(request, self.template_name, context) <NEW_LINE> <DEDENT> def post(self, request, **kwargs): <NEW_LINE> <INDENT> form = self.form_class(request.POST, request.FILES) <NEW_LINE> if not form.is_valid(): <NEW_LINE> <INDENT> context = self.get_context_data(**kwargs) <NEW_LINE> context['form'] = form <NEW_LINE> return render(request, self.template_name, context) <NEW_LINE> <DEDENT> obj = form.save(commit=False) <NEW_LINE> obj.gallery = self.gallery <NEW_LINE> obj.uploaded_by = self.request.user <NEW_LINE> obj.save() <NEW_LINE> uploaded_picture(obj) <NEW_LINE> return redirect(reverse('projects:gallery-preview', kwargs={ 'slug': self.object.slug, 'gallery_pk': self.gallery.pk, })) | Upload new picture to selected gallery.
| 62598fa46aa9bd52df0d4d75 |
class DeleteComponent(ControlSurfaceComponent, Messenger): <NEW_LINE> <INDENT> def __init__(self, *a, **k): <NEW_LINE> <INDENT> super(DeleteComponent, self).__init__(*a, **k) <NEW_LINE> self._delete_button = None <NEW_LINE> return <NEW_LINE> <DEDENT> def set_delete_button(self, button): <NEW_LINE> <INDENT> self._delete_button = button <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_deleting(self): <NEW_LINE> <INDENT> return self._delete_button and self._delete_button.is_pressed() <NEW_LINE> <DEDENT> def delete_clip_envelope(self, parameter): <NEW_LINE> <INDENT> playing_clip = self._get_playing_clip() <NEW_LINE> if playing_clip and parameter.automation_state != AutomationState.none: <NEW_LINE> <INDENT> playing_clip.clear_envelope(parameter) <NEW_LINE> self.show_notification(MessageBoxText.DELETE_ENVELOPE % dict(automation=parameter.name)) <NEW_LINE> <DEDENT> <DEDENT> def _get_playing_clip(self): <NEW_LINE> <INDENT> selected_track = self.song().view.selected_track <NEW_LINE> playing_slot_index = selected_track.playing_slot_index <NEW_LINE> if playing_slot_index >= 0: <NEW_LINE> <INDENT> return selected_track.clip_slots[playing_slot_index].clip | Component for handling deletion of parameters | 62598fa467a9b606de545e76 |
class Bullet(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen, ship): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height) <NEW_LINE> self.rect.centerx = ship.rect.centerx <NEW_LINE> self.rect.top = ship.rect.top <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> self.color = ai_settings.bullet_color <NEW_LINE> self.speed_factor = ai_settings.bullet_speed_factor <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.y -= self.speed_factor <NEW_LINE> self.rect.y = self.y <NEW_LINE> <DEDENT> def draw_bullet(self): <NEW_LINE> <INDENT> pygame.draw.rect(self.screen, self.color, self.rect) | A class to manage bullets fired from the ship. | 62598fa4435de62698e9bca0 |
class TweetListener(tw.streaming.StreamListener): <NEW_LINE> <INDENT> def __init__(self, pref = None): <NEW_LINE> <INDENT> super(TweetListener, self).__init__() <NEW_LINE> self.pref = pref <NEW_LINE> <DEDENT> def on_data(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tweet = Tweet.parse(api, json.loads(data)) <NEW_LINE> print(tweet) <NEW_LINE> if (self.pref is not None): <NEW_LINE> <INDENT> with open('%s.json' % self.pref, 'a') as f: <NEW_LINE> <INDENT> f.write(data) <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> except BaseException as e: <NEW_LINE> <INDENT> print('Error on_data: %s' % str(e)) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def on_error(self, status): <NEW_LINE> <INDENT> print(status) <NEW_LINE> return True <NEW_LINE> <DEDENT> def on_timeout(self): <NEW_LINE> <INDENT> print("Timeout...") <NEW_LINE> return True | StreamListener that channels tweets to a JSON file. | 62598fa48e7ae83300ee8f4c |
class Abort401(Abort): <NEW_LINE> <INDENT> pass | Error 401 class for aborting execution. | 62598fa457b8e32f52508071 |
class QuadeMock: <NEW_LINE> <INDENT> def __init__(self, mdle, funcs=Default): <NEW_LINE> <INDENT> self.module = mdle <NEW_LINE> if funcs == Default: <NEW_LINE> <INDENT> funcs = [customer, staff_user] <NEW_LINE> <DEDENT> self.funcs = funcs <NEW_LINE> <DEDENT> def __call__(self, fn): <NEW_LINE> <INDENT> @wraps(fn) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> original_registry = self.module.manager._registry <NEW_LINE> self.module.manager._registry = {func.__name__: func for func in self.funcs} <NEW_LINE> try: <NEW_LINE> <INDENT> wrapped_fn_return_value = fn(*args, **kwargs) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return wrapped_fn_return_value <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.module.manager._registry = original_registry <NEW_LINE> <DEDENT> <DEDENT> return wrapper | Monkey patch the FixtureManager's registry, and automatically unapply the patch afterwards. | 62598fa463d6d428bbee265d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.