code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class SchedulingService(Service): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.coop = Cooperator(started=False) <NEW_LINE> <DEDENT> def addIterator(self, iterator): <NEW_LINE> <INDENT> return self.coop.coiterate(iterator) <NEW_LINE> <DEDENT> def startService(self): <NEW_LINE> <INDENT> self.coop.start() <NEW_LINE> <DEDENT> def stopService(self): <NEW_LINE> <INDENT> self.coop.stop()
Simple L{IService} implementation.
62598fc5dc8b845886d538ae
class Grammar: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.rules = defaultdict(list) <NEW_LINE> self.starting_symbol = None <NEW_LINE> <DEDENT> def add(self, rule): <NEW_LINE> <INDENT> self.rules[rule.lhs].append(rule) <NEW_LINE> <DEDENT> def __getitem__(self, nt): <NEW_LINE> <INDENT> return self.rules[nt] <NEW_LINE> <DEDENT> def is_terminal(self, sym): <NEW_LINE> <INDENT> return len(self.rules[sym]) == 0 <NEW_LINE> <DEDENT> def init_set(self): <NEW_LINE> <INDENT> return ItemSet([Item(x) for x in self.rules[self.starting_symbol]])
Represents a CFG.
62598fc5ad47b63b2c5a7b4b
class Entj(Extrovert): <NEW_LINE> <INDENT> attrs = AttributeMatrix( strength=0, endurance=0, defense=0, intelligence=0, agility=0, charisma=0, wisdom=0, willpower=0, perception=0, luck=0, ) <NEW_LINE> def interact_with(self, neighbor): <NEW_LINE> <INDENT> super(Entj, self).interact_with(neighbor)
A Meyer-Briggs personality type indicator. Frank, decisive, assume leadership readily. Quickly see illogical and inefficient procedures and policies, develop and implement comprehensive systems to solve organizational problems. Enjoy long-term planning and goal setting. Usually well informed, well read, enjoy expanding their knowledge and passing it on to others. Forceful in presenting their ideas.
62598fc5656771135c489962
class EditarAccionista(View): <NEW_LINE> <INDENT> def post(self, request): <NEW_LINE> <INDENT> accionista = None <NEW_LINE> try: <NEW_LINE> <INDENT> filter = Storage( pk = int(request.POST['pk_element']), pst = Pst.objects.get(user=request.user), cached = True ) <NEW_LINE> accionista = Accionista.objects.get(**filter) <NEW_LINE> fecha_incorporacion = request.POST['fecha_incorporacion'] <NEW_LINE> incorporacion = datetime.strptime(fecha_incorporacion, '%d/%m/%Y').date() <NEW_LINE> accionista.nombres = request.POST['nombre'] <NEW_LINE> accionista.apellidos = request.POST['apellido'] <NEW_LINE> accionista.cedula = request.POST['cedula'] <NEW_LINE> accionista.rif = request.POST['rif'] <NEW_LINE> accionista.numero_acciones = request.POST['numero_acciones'] <NEW_LINE> accionista.fecha_incorporacion = incorporacion <NEW_LINE> accionista.archivo_cedula = request.FILES.get('archivo_cedula') <NEW_LINE> accionista.archivo_rif = request.FILES.get('archivo_rif') <NEW_LINE> accionista.director = False <NEW_LINE> if str(request.POST['director']) == 'on': <NEW_LINE> <INDENT> accionista.director = True <NEW_LINE> <DEDENT> accionista.save() <NEW_LINE> <DEDENT> except Accionista.DoesNotExist: <NEW_LINE> <INDENT> response = dict(success=False, message=u"El registro no existe") <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> response = dict(success=False, message=u"Los parametros enviados no son correctos") <NEW_LINE> <DEDENT> except MultipleObjectsReturned: <NEW_LINE> <INDENT> response = dict(success=False, message=u"Error al realizar la consulta 'MultipleObjectsReturned' ") <NEW_LINE> <DEDENT> if accionista: <NEW_LINE> <INDENT> response = dict(success=True, message=u"Se modifico correctamente el accionista") <NEW_LINE> <DEDENT> response = json.dumps(response, ensure_ascii=True) <NEW_LINE> return HttpResponse(response, content_type='application/json') <NEW_LINE> <DEDENT> def get(self, request, pk): <NEW_LINE> <INDENT> if pk: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filter = dict(pk=int(pk), pst=Pst.objects.get(user=request.user), cached=True) <NEW_LINE> accionista = Accionista.objects.get(**filter) <NEW_LINE> S_accionista = AccionistaSerializer(accionista) <NEW_LINE> response = dict(success=True, message=u"existe", data=S_accionista.data) <NEW_LINE> <DEDENT> except Accionista.DoesNotExist: <NEW_LINE> <INDENT> response = dict(success=False, message=u"Error al Obtener el objeto, no hay registro que coincida") <NEW_LINE> <DEDENT> except MultipleObjectsReturned: <NEW_LINE> <INDENT> response = dict(success=False, message=u"Error obtener el objeto, se retornan mas de lo esperado") <NEW_LINE> <DEDENT> except MultiValueDictKeyError: <NEW_LINE> <INDENT> response = dict(success=False, message=u"Error al extraer los parametros enviados") <NEW_LINE> <DEDENT> <DEDENT> response = json.dumps(response, ensure_ascii=True) <NEW_LINE> return HttpResponse(response, content_type='application/json')
Clase para para editar el Accionista
62598fc5d8ef3951e32c7fd5
class BuildExt(build_ext): <NEW_LINE> <INDENT> c_opts = { 'msvc': ['/EHsc'], 'unix': [], } <NEW_LINE> if sys.platform == 'darwin': <NEW_LINE> <INDENT> c_opts['unix'] += ['-stdlib=libc++', '-mmacosx-version-min=10.8'] <NEW_LINE> <DEDENT> def build_extensions(self): <NEW_LINE> <INDENT> ct = self.compiler.compiler_type <NEW_LINE> opts = self.c_opts.get(ct, []) <NEW_LINE> if ct == 'unix': <NEW_LINE> <INDENT> opts.append('-DVERSION_INFO="%s"' % self.distribution.get_version()) <NEW_LINE> opts.append(cpp_flag(self.compiler)) <NEW_LINE> if has_flag(self.compiler, '-fvisibility=hidden'): <NEW_LINE> <INDENT> opts.append('-fvisibility=hidden') <NEW_LINE> <DEDENT> <DEDENT> elif ct == 'msvc': <NEW_LINE> <INDENT> opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version()) <NEW_LINE> <DEDENT> for ext in self.extensions: <NEW_LINE> <INDENT> ext.extra_compile_args = opts <NEW_LINE> <DEDENT> build_ext.build_extensions(self)
A custom build extension for adding compiler-specific options.
62598fc550812a4eaa620d5e
class BTNode(object): <NEW_LINE> <INDENT> def __init__(self, value, left=None, right=None): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.left = left <NEW_LINE> self.right = right <NEW_LINE> self.depth = 0 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._str_helper("") <NEW_LINE> <DEDENT> def _str_helper(self, indentation=""): <NEW_LINE> <INDENT> ret = "" <NEW_LINE> if(self.right is not None): <NEW_LINE> <INDENT> ret += self.right._str_helper(indentation + "\t") + "\n" <NEW_LINE> <DEDENT> ret += indentation + str(self.value) + "\n" <NEW_LINE> if(self.left is not None): <NEW_LINE> <INDENT> ret += self.left._str_helper(indentation + "\t") + "\n" <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def set_depth(self, depth=0): <NEW_LINE> <INDENT> if(self.right is not None): <NEW_LINE> <INDENT> self.right.set_depth(depth + 1) <NEW_LINE> <DEDENT> if(self.left is not None): <NEW_LINE> <INDENT> self.left.set_depth(depth + 1) <NEW_LINE> <DEDENT> self.depth = depth <NEW_LINE> <DEDENT> def leaves_and_internals(self, is_root=True): <NEW_LINE> <INDENT> ret_tuple = (set(), set()) <NEW_LINE> if(self.right is None and self.left is None): <NEW_LINE> <INDENT> ret_tuple[0].add(self.value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if(not is_root): <NEW_LINE> <INDENT> ret_tuple[1].add(self.value) <NEW_LINE> <DEDENT> if(self.right is not None): <NEW_LINE> <INDENT> right_tuple = self.right.leaves_and_internals(False) <NEW_LINE> ret_tuple[1].update(right_tuple[1]) <NEW_LINE> ret_tuple[0].update(right_tuple[0]) <NEW_LINE> <DEDENT> if(self.left is not None): <NEW_LINE> <INDENT> left_tuple = self.left.leaves_and_internals(False) <NEW_LINE> ret_tuple[1].update(left_tuple[1]) <NEW_LINE> ret_tuple[0].update(left_tuple[0]) <NEW_LINE> <DEDENT> <DEDENT> return ret_tuple <NEW_LINE> <DEDENT> def sum_to_deepest(self): <NEW_LINE> <INDENT> return self._sum_to_deepest_helper()[0] <NEW_LINE> <DEDENT> def _sum_to_deepest_helper(self, depth=0): <NEW_LINE> <INDENT> right_sum = [0, depth] <NEW_LINE> left_sum = [0, depth] <NEW_LINE> if(self.right is not None): <NEW_LINE> <INDENT> right_sum = self.right._sum_to_deepest_helper(depth + 1) <NEW_LINE> <DEDENT> if(self.left is not None): <NEW_LINE> <INDENT> left_sum = self.left._sum_to_deepest_helper(depth + 1) <NEW_LINE> <DEDENT> depth = right_sum[1] <NEW_LINE> max_sum = self.value + right_sum[0] <NEW_LINE> if(right_sum[1] == left_sum[1]): <NEW_LINE> <INDENT> if(right_sum[0] < left_sum[0]): <NEW_LINE> <INDENT> max_sum = self.value + left_sum[0] <NEW_LINE> <DEDENT> <DEDENT> elif(right_sum[1] < left_sum[1]): <NEW_LINE> <INDENT> depth = left_sum[1] <NEW_LINE> max_sum = self.value + left_sum[0] <NEW_LINE> <DEDENT> return [max_sum, depth]
A node in a binary tree.
62598fc5aad79263cf42eac8
class DagsterUnknownResourceError(DagsterError, AttributeError): <NEW_LINE> <INDENT> def __init__(self, resource_name, *args, **kwargs): <NEW_LINE> <INDENT> self.resource_name = check.str_param(resource_name, "resource_name") <NEW_LINE> msg = ( "Unknown resource `{resource_name}`. Specify `{resource_name}` as a required resource " "on the compute / config function that accessed it." ).format(resource_name=resource_name) <NEW_LINE> super(DagsterUnknownResourceError, self).__init__(msg, *args, **kwargs)
Indicates that an unknown resource was accessed in the body of an execution step. May often happen by accessing a resource in the compute function of an op without first supplying the op with the correct `required_resource_keys` argument.
62598fc576e4537e8c3ef898
class WeightNorm(KernelNorm): <NEW_LINE> <INDENT> NAME = "weight_norm" <NEW_LINE> def __init__(self, scale=True, axis=-1, epsilon=1e-5, name=None): <NEW_LINE> <INDENT> super().__init__(name=name) <NEW_LINE> self.use_scale = scale <NEW_LINE> self.axis = axis <NEW_LINE> self.epsilon = epsilon <NEW_LINE> self.g = None <NEW_LINE> <DEDENT> @build_with_name_scope <NEW_LINE> def build_parameters(self, kernel): <NEW_LINE> <INDENT> if self.use_scale: <NEW_LINE> <INDENT> shape = kernel._shape_as_list() <NEW_LINE> try: <NEW_LINE> <INDENT> shape[self.axis] = 1 <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> for i in self.axis: <NEW_LINE> <INDENT> shape[i] = 1 <NEW_LINE> <DEDENT> <DEDENT> self.g = tf.Variable(tf.ones(shape), trainable=True) <NEW_LINE> <DEDENT> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> if self.use_scale: <NEW_LINE> <INDENT> self.g.assign(tf.ones(self.g.shape)) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, kernel): <NEW_LINE> <INDENT> return self.normalize(kernel, self.g, self.axis, self.epsilon) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def normalize(kernel, g, axis, epsilon): <NEW_LINE> <INDENT> kernel = kernel * tf.rsqrt( tf.reduce_sum(tf.square(kernel), axis=axis, keepdims=True) + epsilon) <NEW_LINE> if g is not None: <NEW_LINE> <INDENT> kernel = kernel * g <NEW_LINE> <DEDENT> return kernel <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def add(module, scale=True, axis=-1, epsilon=1e-5): <NEW_LINE> <INDENT> KernelNorm.add(module, WeightNorm(scale, axis, epsilon)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def remove(module): <NEW_LINE> <INDENT> KernelNorm.remove(module, WeightNorm.NAME) <NEW_LINE> <DEDENT> def extra_repr(self): <NEW_LINE> <INDENT> return "({}, {}, {})".format(self.use_scale, self.axis, self.epsilon)
Weight Normalization class.
62598fc54428ac0f6e658819
@dataclass_json <NEW_LINE> @dataclass <NEW_LINE> class Sampler(Property): <NEW_LINE> <INDENT> input: Optional[int] = None <NEW_LINE> interpolation: Optional[str] = None <NEW_LINE> output: Optional[int] = None <NEW_LINE> magFilter: Optional[int] = None <NEW_LINE> minFilter: Optional[int] = None <NEW_LINE> wrapS: Optional[int] = REPEAT <NEW_LINE> wrapT: Optional[int] = REPEAT
Samplers are stored in the samplers array of the asset. Each sampler specifies filter and wrapping options corresponding to the GL types
62598fc6aad79263cf42eac9
class DictOutputMethod(OutputMethod): <NEW_LINE> <INDENT> def __init__(self, *engines, filename=None): <NEW_LINE> <INDENT> OutputMethod.__init__(self, *engines) <NEW_LINE> self.results = {} <NEW_LINE> self.filename = filename <NEW_LINE> <DEDENT> def _update(self, engine, results): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not engine.name in self.results: <NEW_LINE> <INDENT> self.results[engine.name] = {} <NEW_LINE> <DEDENT> self.results[engine.name][engine._number_of_processed_traces] = np.copy( results ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> self.logger.warning( "Engine %s with %d traces: cannot be used with DictOutputMethod" % (engine.name, engine._number_of_processed_traces) ) <NEW_LINE> <DEDENT> <DEDENT> def _finalize(self): <NEW_LINE> <INDENT> if self.filename is not None: <NEW_LINE> <INDENT> with open(self.filename, "wb") as file: <NEW_LINE> <INDENT> pickle.dump(self.results, file) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def load(filename): <NEW_LINE> <INDENT> out = DictOutputMethod() <NEW_LINE> with open(filename, "rb") as file: <NEW_LINE> <INDENT> out.results = pickle.load(file) <NEW_LINE> <DEDENT> return out <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> if len(self.results[item]) > 1: <NEW_LINE> <INDENT> return self.results[item] <NEW_LINE> <DEDENT> elif len(self.results[item]) == 1: <NEW_LINE> <INDENT> return self.results[item][list(self.results[item])[0]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("%s not set for this output method." % (item))
DictOutputMethod is an OutputMethod that will store inside a dict the results from its tracked engines (for each output_step). For each engine tracked, a key is added to the PickleOuputMethod, containing a sub-dict. For each output_step, a key is added inside the sub-dict corresponding to each engine. in the end: pickle_output_method[engine_name][output_step] contains engine.results after output_step traces processed. If a filename is specified, the finalize() method will store the dict inside a file using pickle.
62598fc663b5f9789fe85468
class DatasetLike(Like[xarray.Dataset]): <NEW_LINE> <INDENT> TYPE = Optional[Union[xarray.Dataset, pandas.DataFrame]] <NEW_LINE> @classmethod <NEW_LINE> def convert(cls, value: Any) -> Optional[xarray.Dataset]: <NEW_LINE> <INDENT> from cate.core.opimpl import adjust_temporal_attrs_impl <NEW_LINE> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(value, xarray.Dataset): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if isinstance(value, pandas.DataFrame): <NEW_LINE> <INDENT> return adjust_temporal_attrs_impl(xarray.Dataset.from_dataframe(value)) <NEW_LINE> <DEDENT> raise ValidationError('Value must be an xarray.Dataset or pandas.DataFrame.') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def format(cls, value: Optional[xarray.Dataset]) -> str: <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> raise ValidationError('Values of type DatasetLike cannot be converted to text.')
Accepts xarray.Dataset, pandas.DataFrame and converts to xarray.Dataset.
62598fc6fff4ab517ebcdadc
class BashMalformedKoji(TestKoji): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> TestKoji.setUp(self) <NEW_LINE> self.rpm.add_installed_file( "/usr/share/data/invalid_bash.sh", rpmfluff.SourceFile("invalid_bash.sh", invalid_bash), ) <NEW_LINE> self.inspection = "shellsyntax" <NEW_LINE> self.result = "BAD" <NEW_LINE> self.waiver_auth = "Anyone"
Invalid /bin/bash script is BAD for Koji build
62598fc63317a56b869be6cb
class MainUserManager(BaseUserManager): <NEW_LINE> <INDENT> def create_user(self, phone, password): <NEW_LINE> <INDENT> if not phone or not password: <NEW_LINE> <INDENT> raise ValueError('Users must have an phone and password') <NEW_LINE> <DEDENT> user = self.model(phone=phone.lower()) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_superuser(self, phone, password): <NEW_LINE> <INDENT> user = self.create_user(phone=phone, password=password) <NEW_LINE> user.is_admin = True <NEW_LINE> user.is_superuser = True <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user
Custom user manager.
62598fc6851cf427c66b85aa
class TerminalSkin: <NEW_LINE> <INDENT> def __init__(self, chords=()): <NEW_LINE> <INDENT> self.traceback = None <NEW_LINE> self.reply = TerminalReplyOut() <NEW_LINE> self.cursor_style = _VIEW_CURSOR_STYLE_ <NEW_LINE> self.keyboard = None <NEW_LINE> self.chord_ints_ahead = list(chords) <NEW_LINE> self.nudge = TerminalNudgeIn() <NEW_LINE> self.arg0_chords = None <NEW_LINE> self.arg1 = None <NEW_LINE> self.arg2_chars = None <NEW_LINE> self.doing_less = None <NEW_LINE> self.doing_more = None <NEW_LINE> self.doing_done = None <NEW_LINE> self.doing_funcs = list() <NEW_LINE> self.doing_traceback = None
Form a Skin out of keyboard Input Chords and an Output Reply
62598fc65fdd1c0f98e5e288
class PaletteColormap: <NEW_LINE> <INDENT> def __init__(self, *colors, intervals=None): <NEW_LINE> <INDENT> self.colors = tmap(RGBA, colors) <NEW_LINE> self.cmap = SequenceColormap(*tmap(ConstantColormap, self.colors), intervals=intervals) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "PaletteColormap({})".format( ", ".join( "{:.0%}-{:.0%}={}".format(p, q, c.to_hex(True)) for p, q, c in zip(self.cmap.accumulated, self.cmap.accumulated[1:], self.colors) ) ) <NEW_LINE> <DEDENT> def __call__(self, p, bytes=False): <NEW_LINE> <INDENT> if isinstance(p, Integral) or getattr(getattr(p, "dtype", None), "kind", None) == "i": <NEW_LINE> <INDENT> cols = [ np.select([np.mod(p, len(cs)) == i for i in range(len(cs))], cs) for cs in zip(*self.colors) ] <NEW_LINE> return np.uint8(np.stack(cols, -1)) if bytes else np.stack(cols, -1) / 255 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.cmap(p, bytes=bytes) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, p): <NEW_LINE> <INDENT> if not isinstance(p, Integral): <NEW_LINE> <INDENT> raise TypeError("Colormap index is not an integer. Did you mean application?") <NEW_LINE> <DEDENT> return RGBA(self(p, bytes=True))
A matplotlib colormap generated from constant colors and optional spacing intervals. Can also be used as a discrete cycling colormap.
62598fc64428ac0f6e65881b
class JSONDecoder(object): <NEW_LINE> <INDENT> _scanner = Scanner(ANYTHING) <NEW_LINE> __all__ = ['__init__', 'decode', 'raw_decode'] <NEW_LINE> def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True): <NEW_LINE> <INDENT> self.encoding = encoding <NEW_LINE> self.object_hook = object_hook <NEW_LINE> self.parse_float = parse_float <NEW_LINE> self.parse_int = parse_int <NEW_LINE> self.parse_constant = parse_constant <NEW_LINE> self.strict = strict <NEW_LINE> <DEDENT> def decode(self, s, _w=WHITESPACE.match): <NEW_LINE> <INDENT> obj, end = self.raw_decode(s, idx=_w(s, 0).end()) <NEW_LINE> end = _w(s, end).end() <NEW_LINE> if end != len(s): <NEW_LINE> <INDENT> raise ValueError(errmsg("Extra data", s, end, len(s))) <NEW_LINE> <DEDENT> return obj <NEW_LINE> <DEDENT> def raw_decode(self, s, **kw): <NEW_LINE> <INDENT> kw.setdefault('context', self) <NEW_LINE> try: <NEW_LINE> <INDENT> obj, end = self._scanner.iterscan(s, **kw).next() <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> raise ValueError("No JSON object could be decoded") <NEW_LINE> <DEDENT> return obj, end
Simple JSON <http://json.org> decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | unicode | +---------------+-------------------+ | number (int) | int, long | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec.
62598fc65fdd1c0f98e5e289
class Job(models.Model): <NEW_LINE> <INDENT> last_updated = models.DateTimeField(auto_now_add=True, auto_now=True) <NEW_LINE> update_on = models.DateTimeField(blank=True, null=True) <NEW_LINE> active = models.BooleanField(default=False) <NEW_LINE> language = models.ForeignKey(Language, db_index=True) <NEW_LINE> package = models.ForeignKey(Package, db_index=True) <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Job, self).save(*args, **kwargs) <NEW_LINE> end_queue = Job.objects.latest("update_on") <NEW_LINE> if not end_queue or not end_queue.update_on: <NEW_LINE> <INDENT> end_of_line = self.last_updated <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> end_of_line = end_queue.update_on <NEW_LINE> <DEDENT> from datetime import timedelta <NEW_LINE> five_minutes = timedelta(minutes=5) <NEW_LINE> self.update_on = end_of_line + five_minutes <NEW_LINE> super(Job, self).save(*args, **kwargs)
In [1]: languages = Language.objects.all() In [2]: packages = Package.objects.all() In [3]: for package in packages: for language in languages: (job, created) = Job.objects.get_or_create(language=language, package=package) ....: job.save() ....:
62598fc6091ae35668704f1f
class Net: <NEW_LINE> <INDENT> def __init__(self, inputs, dropout_rate=None, reuse=tf.AUTO_REUSE, training=True, scope='description'): <NEW_LINE> <INDENT> self.loss = None <NEW_LINE> self.train = None <NEW_LINE> self.validation = None <NEW_LINE> self.scope = scope <NEW_LINE> with tf.variable_scope(scope, reuse=reuse): <NEW_LINE> <INDENT> net = inputs <NEW_LINE> filters_ls = [32, 32, 64, 64, 128, 128] <NEW_LINE> strides_ls = [1, 1, 2, 1, 2, 1] <NEW_LINE> i = 1 <NEW_LINE> for filters, strides in zip(filters_ls, strides_ls): <NEW_LINE> <INDENT> net = tf.layers.conv2d( net, filters=filters, kernel_size=3, strides=strides, padding='same', activation=tf.nn.relu, use_bias=False, name='conv_{}'.format(i), reuse=reuse) <NEW_LINE> net = tf.layers.batch_normalization( net, training=training, name='batchnorm_{}'.format(i), reuse=reuse) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> if dropout_rate is not None: <NEW_LINE> <INDENT> net = tf.layers.dropout(net, rate=dropout_rate, training=training) <NEW_LINE> <DEDENT> net = tf.layers.conv2d( net, filters=128, kernel_size=8, strides=1, padding='valid', activation=None, use_bias=False, name='conv_{}'.format(i), reuse=reuse) <NEW_LINE> net = tf.layers.batch_normalization( net, training=training, name='batchnorm_{}'.format(i), reuse=reuse) <NEW_LINE> spatial_descriptors = tf.nn.l2_normalize( net, axis=-1, name='spatial_descriptors') <NEW_LINE> self.descriptors = tf.reshape( spatial_descriptors, [-1, 128], name='descriptors') <NEW_LINE> <DEDENT> <DEDENT> def build_loss(self, labels, decay_weight=None): <NEW_LINE> <INDENT> with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE): <NEW_LINE> <INDENT> with tf.name_scope('loss'): <NEW_LINE> <INDENT> labels = tf.reshape(labels, (-1, )) <NEW_LINE> self.loss = tf.contrib.losses.metric_learning.triplet_semihard_loss( labels, self.descriptors) <NEW_LINE> if decay_weight is not None: <NEW_LINE> <INDENT> weight_decay = 0 <NEW_LINE> for var in tf.trainable_variables(self.scope): <NEW_LINE> <INDENT> if 'kernel' in var.name: <NEW_LINE> <INDENT> weight_decay += tf.nn.l2_loss(var) <NEW_LINE> <DEDENT> <DEDENT> self.loss += decay_weight * weight_decay <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self.loss <NEW_LINE> <DEDENT> def build_train(self, learning_rate): <NEW_LINE> <INDENT> with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE): <NEW_LINE> <INDENT> with tf.name_scope('train'): <NEW_LINE> <INDENT> global_step = tf.Variable(1, name='global_step', trainable=False) <NEW_LINE> optimizer = tf.train.GradientDescentOptimizer(learning_rate) <NEW_LINE> update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) <NEW_LINE> with tf.control_dependencies(update_ops): <NEW_LINE> <INDENT> self.train = optimizer.minimize(self.loss, global_step=global_step) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self.train
Adapted HardNet (Working hard to know your neighbor's margins: Local descriptor learning loss, 2017) model. Differs from HardNet in its loss function, using instead triplet semi-hard loss (FaceNet: A Unified Embedding for Face Recognition and Clustering, 2015). Net.descriptors is the model's output op. It has shape [batch_size, 128]. Net.loss and Net.train are respectively the model's loss op and training step op, if built with Net.build_loss and Net.build_train.
62598fc65fcc89381b2662c8
class ClassificationScore: <NEW_LINE> <INDENT> def __init__(self, true_positive=0, false_negative=0, false_positive=0): <NEW_LINE> <INDENT> self.true_positive = true_positive <NEW_LINE> self.false_negative = false_negative <NEW_LINE> self.false_positive = false_positive <NEW_LINE> <DEDENT> def get_iou(self): <NEW_LINE> <INDENT> denominator = self.true_positive + self.false_negative + self.false_positive <NEW_LINE> if denominator == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return self.true_positive / denominator <NEW_LINE> <DEDENT> def get_precision(self): <NEW_LINE> <INDENT> denominator = self.true_positive + self.false_positive <NEW_LINE> return self.true_positive / denominator <NEW_LINE> <DEDENT> def get_recall(self): <NEW_LINE> <INDENT> denominator = self.true_positive + self.false_negative <NEW_LINE> return self.true_positive / denominator <NEW_LINE> <DEDENT> def get_F1score(self): <NEW_LINE> <INDENT> p=self.true_positive/(self.true_positive + self.false_positive) <NEW_LINE> r=self.true_positive/(self.true_positive + self.false_negative) <NEW_LINE> return 2*p*r/(p+r) <NEW_LINE> <DEDENT> def add(self, other): <NEW_LINE> <INDENT> self.true_positive += other.true_positive <NEW_LINE> self.false_positive += other.false_positive <NEW_LINE> self.false_negative += other.false_negative
Used to store and compute metric scores
62598fc63617ad0b5ee0643e
class CreateTopicRuleRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RuleName = None <NEW_LINE> self.TopicRulePayload = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RuleName = params.get("RuleName") <NEW_LINE> if params.get("TopicRulePayload") is not None: <NEW_LINE> <INDENT> self.TopicRulePayload = TopicRulePayload() <NEW_LINE> self.TopicRulePayload._deserialize(params.get("TopicRulePayload")) <NEW_LINE> <DEDENT> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
CreateTopicRule请求参数结构体
62598fc6ad47b63b2c5a7b4f
@admin.register(User) <NEW_LINE> class UserAdmin(UserBaseAdmin): <NEW_LINE> <INDENT> ordering = ("email",) <NEW_LINE> list_display = ("email", "is_staff", "is_admin", "is_active") <NEW_LINE> list_per_page = 10 <NEW_LINE> list_display_links = ("email",) <NEW_LINE> search_fields = ("email",) <NEW_LINE> add_fieldsets = ( (None, {"fields": ("email", "fullname", "mobile", "image", "password1", "password2")}), ) <NEW_LINE> fieldsets = ((None, {"fields": ("email", "fullname","password")}), ("Personal Option", { "fields": ("image",)}), ("Status", {"fields": ("is_staff", "is_active")})) <NEW_LINE> inlines = ( EmailAdmin, AddressAdmin, )
User admin, which to use for mange User data
62598fc6ff9c53063f51a944
class LMThdu(object): <NEW_LINE> <INDENT> def __init__(self, data=None, header=None, filename=None): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.header = header <NEW_LINE> self.filename = filename <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.filename: <NEW_LINE> <INDENT> return "HDU for file: %s" % self.filename <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "HDU"
The LMThdu is a class that contains the basic Header-Data Unit. This is meant to be similar to pyfits HDU. The two main attributes are the header and data. In addition, there can be a filename attribute that contains the name of the file from which the data was read
62598fc6d8ef3951e32c7fd7
class HRDisciplinaryActionModel(S3Model): <NEW_LINE> <INDENT> names = ("hrm_disciplinary_type", "hrm_disciplinary_action", ) <NEW_LINE> def model(self): <NEW_LINE> <INDENT> T = current.T <NEW_LINE> define_table = self.define_table <NEW_LINE> tablename = "hrm_disciplinary_type" <NEW_LINE> define_table(tablename, self.org_organisation_id( requires = self.org_organisation_requires(updateable=True), ), Field("name", label = T("Disciplinary Action Type"), ), s3_comments(), *s3_meta_fields()) <NEW_LINE> self.configure(tablename, deduplicate = S3Duplicate(primary = ("name", "organisation_id", ), ), ) <NEW_LINE> disciplinary_type_represent = hrm_OrgSpecificTypeRepresent(lookup=tablename) <NEW_LINE> tablename = "hrm_disciplinary_action" <NEW_LINE> define_table(tablename, self.pr_person_id(), s3_date(), Field("disciplinary_body"), Field("disciplinary_type_id", "reference hrm_disciplinary_type", label = T("Disciplinary Action Type"), represent = disciplinary_type_represent, requires = IS_ONE_OF(current.db, "hrm_disciplinary_type.id", disciplinary_type_represent, ), comment = S3PopupLink(f = "disciplinary_type", label = T("Add Disciplinary Action Type"), ), ), s3_comments(), *s3_meta_fields()) <NEW_LINE> return None
Data model for staff disciplinary record
62598fc6aad79263cf42eacd
class SceneQuit(Exception): <NEW_LINE> <INDENT> pass
Wyjście z ekranu gry.
62598fc663b5f9789fe8546c
class ISheetBackReferenceModified(IObjectEvent): <NEW_LINE> <INDENT> object = Attribute('The referenced resource') <NEW_LINE> isheet = Attribute('The referenced sheet.') <NEW_LINE> reference = Attribute('The Reference with `object` as target.') <NEW_LINE> registry = Attribute('The pyramid registry')
An event type sent when a sheet back reference was added/removed. See Subtypes for more detailed semantic.
62598fc6cc40096d6161a354
class TestHiveClientCase(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> @patch('ppytools.hiveclient.hive.connect') <NEW_LINE> def setUpClass(cls, mock_hive_conn): <NEW_LINE> <INDENT> mock_hive_conn.return_value = mock.Mock(autospec=True) <NEW_LINE> cls.hc = HiveClient('127.0.0.1', 10000, 'hive', 'default') <NEW_LINE> mock_hive_conn.assert_called_with(database='default', host='127.0.0.1', port=10000, username='hive') <NEW_LINE> cls.mock_obj = cls.hc.conn = mock_hive_conn <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> cls.hc.closeConn() <NEW_LINE> <DEDENT> def testExecQuery(self): <NEW_LINE> <INDENT> result, size = self.hc.execQuery(MOCK_SQL) <NEW_LINE> logger.info('mock hive query result: %s', result) <NEW_LINE> self.assertIsNotNone(result) <NEW_LINE> self.assertEquals(size, 0) <NEW_LINE> <DEDENT> def testExecCount(self): <NEW_LINE> <INDENT> count = self.hc.execCount(MOCK_SQL) <NEW_LINE> logger.info('mock hive count result: %d', count) <NEW_LINE> self.assertIsNotNone(count)
TestHiveClientCase
62598fc697e22403b383b1fc
class GradientHardClipping(object): <NEW_LINE> <INDENT> name = 'GradientHardClipping' <NEW_LINE> def __init__(self, lower_bound, upper_bound): <NEW_LINE> <INDENT> self.lower_bound = lower_bound <NEW_LINE> self.upper_bound = upper_bound <NEW_LINE> <DEDENT> def __call__(self, opt): <NEW_LINE> <INDENT> xp = opt.target.xp <NEW_LINE> for param in opt.target.params(): <NEW_LINE> <INDENT> grad = param.grad <NEW_LINE> with cuda.get_device(grad): <NEW_LINE> <INDENT> grad = xp.clip(grad, self.lower_bound, self.upper_bound, out=grad)
Optimizer hook function for gradient clipping. This hook function clips all gradient arrays to be within a lower and upper bound. Args: lower_bound (float): The lower bound of the gradient value. upper_bound (float): The upper bound of the gradient value. Attributes: lower_bound (float): The lower bound of the gradient value. upper_bound (float): The upper bound of the gradient value.
62598fc68a349b6b43686537
class OneTimePassword(SmartModel): <NEW_LINE> <INDENT> key = models.CharField( verbose_name=_('key'), max_length=128, unique=True, db_index=True, null=False, blank=False ) <NEW_LINE> expires_at = models.DateTimeField( verbose_name=_('expires at'), null=True, blank=True, ) <NEW_LINE> slug = models.SlugField( verbose_name=_('slug'), null=False, blank=False ) <NEW_LINE> is_active = models.BooleanField( verbose_name=_('is active'), default=True ) <NEW_LINE> data = models.JSONField( verbose_name=_('data'), null=True, blank=True, encoder=DjangoJSONEncoder ) <NEW_LINE> related_objects = GenericManyToManyField() <NEW_LINE> secret_key = None <NEW_LINE> objects = OneTimePasswordManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('-created_at',) <NEW_LINE> verbose_name = _('one time password') <NEW_LINE> verbose_name_plural = _('one time passwords') <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_expired(self): <NEW_LINE> <INDENT> return self.expires_at and self.expires_at < timezone.now()
Specific verification tokens that can be send via e-mail, SMS or another transmission medium to check user authorization (example password reset)
62598fc666673b3332c306ce
class Area3_3_LeftInnerArea(area_base.Area): <NEW_LINE> <INDENT> def __init__(self: "Area", window_width: int = 500, window_height: int = 500, player_obj: "Snake"=None, enemies: "Group"=None): <NEW_LINE> <INDENT> area_base.Area.__init__(self, window_width, window_height, player_obj, enemies) <NEW_LINE> self.is_checkpoint = False <NEW_LINE> self._draw_south_inner_room() <NEW_LINE> <DEDENT> def _formation1(self): <NEW_LINE> <INDENT> if self.e_group != None: <NEW_LINE> <INDENT> self.gen_patrol_route1(list(self.e_group)[0]) <NEW_LINE> self.gen_patrol_route2(list(self.e_group)[1]) <NEW_LINE> <DEDENT> <DEDENT> def _formation2(self): <NEW_LINE> <INDENT> if self.e_group != None: <NEW_LINE> <INDENT> self.gen_patrol_route3(list(self.e_group)[0]) <NEW_LINE> self.gen_patrol_route4(list(self.e_group)[1]) <NEW_LINE> <DEDENT> <DEDENT> def gen_patrol_route1(self, enemy): <NEW_LINE> <INDENT> if self.e_group != None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def gen_patrol_route2(self, enemy): <NEW_LINE> <INDENT> if self.e_group != None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def draw(self: "Area", window: "Surface"): <NEW_LINE> <INDENT> self._set_background(window, "floor.png") <NEW_LINE> self.obj_group.draw(window) <NEW_LINE> <DEDENT> def check_transition(self: "Area", area_dict: dict): <NEW_LINE> <INDENT> new_area = old_area = self <NEW_LINE> if self.player_obj != None: <NEW_LINE> <INDENT> if (self.player_obj.rect.y <= 0 and self.player_obj.rect.centerx >= self.width*0.35 and self.player_obj.rect.centerx <= self.width*0.65 and self.player_obj.moving_north): <NEW_LINE> <INDENT> print("in 3_3") <NEW_LINE> new_area = self._make_transition(self.width*0.20, self.height*0.65-70, area_dict, "north1") <NEW_LINE> new_area._reset_enemy_state() <NEW_LINE> new_area._formation1() <NEW_LINE> <DEDENT> self._handle_corners_and_boundaries() <NEW_LINE> if new_area != old_area and old_area.is_safe_haven: <NEW_LINE> <INDENT> old_area.ticks = 0 <NEW_LINE> <DEDENT> self._clean_up_attack_objects(new_area, old_area) <NEW_LINE> <DEDENT> return new_area
A class to represent a left inner Area of Area3_3
62598fc64527f215b58ea1c8
class ModelChannel(BaseFrontendChannel): <NEW_LINE> <INDENT> BackendChannel = ForwardBackendChannel <NEW_LINE> namespace = 'model' <NEW_LINE> def __init__(self, session, endpoint=None): <NEW_LINE> <INDENT> super(ModelChannel, self).__init__(session, endpoint) <NEW_LINE> self.resources = { } <NEW_LINE> <DEDENT> def on_event(self, name, args=None, kwargs=None): <NEW_LINE> <INDENT> resource, method = name.split(':') <NEW_LINE> assert resource in self.resources <NEW_LINE> return self.resources[resource].dispatch(method, args, kwargs)
REST over Socket.io.
62598fc65fcc89381b2662c9
class TearDownHandler(webapp.RequestHandler): <NEW_LINE> <INDENT> @decorator.oauth_required <NEW_LINE> def get(self): <NEW_LINE> <INDENT> ComputeEngineController(decorator.credentials).TearDownCluster() <NEW_LINE> LoadInfo.RemoveAllInstancesAndServers()
URL handler class for cluster shut down.
62598fc6a219f33f346c6b00
class QueueHandler(logging.Handler): <NEW_LINE> <INDENT> def __init__(self, queue): <NEW_LINE> <INDENT> logging.Handler.__init__(self) <NEW_LINE> self.queue = queue <NEW_LINE> <DEDENT> def enqueue(self, record): <NEW_LINE> <INDENT> self.queue.put_nowait(record) <NEW_LINE> <DEDENT> def prepare(self, record): <NEW_LINE> <INDENT> msg = self.format(record) <NEW_LINE> record.message = msg <NEW_LINE> record.msg = msg <NEW_LINE> record.args = None <NEW_LINE> record.exc_info = None <NEW_LINE> return record <NEW_LINE> <DEDENT> def emit(self, record): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.enqueue(self.prepare(record)) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.handleError(record)
This handler sends events to a queue. Typically, it would be used together with a multiprocessing Queue to centralise logging to file in one process (in a multi-process application), so as to avoid file write contention between processes. This code is new in Python 3.2, but this class can be copy pasted into user code for use with earlier Python versions.
62598fc6ad47b63b2c5a7b51
class RibbonTableaux(Parent, UniqueRepresentation): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def __classcall_private__(cls, shape=None, weight=None, length=None): <NEW_LINE> <INDENT> if shape is None and weight is None and length is None: <NEW_LINE> <INDENT> return super(RibbonTableaux, cls).__classcall__(cls) <NEW_LINE> <DEDENT> return RibbonTableaux_shape_weight_length(shape, weight, length) <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> Parent.__init__(self, category=Sets()) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "Ribbon tableaux" <NEW_LINE> <DEDENT> def _element_constructor_(self, rt): <NEW_LINE> <INDENT> return self.element_class(self, rt) <NEW_LINE> <DEDENT> def from_expr(self, l): <NEW_LINE> <INDENT> return self.element_class(self, SkewTableaux().from_expr(l)) <NEW_LINE> <DEDENT> Element = RibbonTableau <NEW_LINE> global_options = TableauOptions
Ribbon tableaux. A ribbon tableau is a skew tableau whose skew shape ``shape`` is tiled by ribbons of length ``length``. The weight ``weight`` is calculated from the labels on the ribbons. .. NOTE:: Here we inpose the condition that the ribbon tableaux are semistandard. INPUT(Optional): - ``shape`` -- skew shape as a list of lists or an object of type SkewPartition - ``length`` -- integer, ``shape`` is partitioned into ribbons of length ``length`` - ``weight`` -- list of integers, computed from the values of non-zero entries labeling the ribbons EXAMPLES:: sage: RibbonTableaux([[2,1],[]], [1,1,1], 1) Ribbon tableaux of shape [2, 1] / [] and weight [1, 1, 1] with 1-ribbons sage: R = RibbonTableaux([[5,4,3],[2,1]], [2,1], 3) sage: for i in R: i.pp(); print . . 0 0 0 . 0 0 2 1 0 1 <BLANKLINE> . . 1 0 0 . 0 0 0 1 0 2 <BLANKLINE> . . 0 0 0 . 1 0 1 2 0 0 <BLANKLINE> REFRENCES: .. [vanLeeuwen91] Marc. A. A. van Leeuwen *Edge sequences, ribbon tableaux, and an action of affine permutations*. Europe J. Combinatorics. **20** (1999). http://wwwmathlabo.univ-poitiers.fr/~maavl/pdf/edgeseqs.pdf
62598fc67c178a314d78d798
@app_utils.singleton <NEW_LINE> class ActivityManager(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._parent = None <NEW_LINE> self._activitylist = [] <NEW_LINE> <DEDENT> def set_parent(self, parentwidget): <NEW_LINE> <INDENT> self._parent = parentwidget <NEW_LINE> <DEDENT> def init_activities(self): <NEW_LINE> <INDENT> self._activitylist.append(app_activities.StartActivity('Welcome', self._parent)) <NEW_LINE> self._activitylist.append(app_activities.WorkspaceActivity('Workspace', self._parent)) <NEW_LINE> self._activitylist.append(app_activities.SurveyActivity('Survey', self._parent)) <NEW_LINE> self._activitylist.append(app_activities.WavefilesActivity('Wave files', self._parent)) <NEW_LINE> self._activitylist.append(app_activities.ScannerActivity('Scanner', self._parent)) <NEW_LINE> self._activitylist.append(app_activities.AnalysisActivity('(Analysis)', self._parent)) <NEW_LINE> self._activitylist.append(app_activities.ExportImportActivity('(Export/import)', self._parent)) <NEW_LINE> self._activitylist.append(app_activities.UploadDownloadActivity('(Upload/download)', self._parent)) <NEW_LINE> self._activitylist.append(app_activities.CloudActivity('(Cloud)', self._parent)) <NEW_LINE> self._activitylist.append(app_activities.DarwinCoreActivity('(Darwin core)', self._parent)) <NEW_LINE> <DEDENT> def show_activity_by_name(self, object_name): <NEW_LINE> <INDENT> for activity in self._activitylist: <NEW_LINE> <INDENT> if activity.objectName() == object_name: <NEW_LINE> <INDENT> activity._parent.showActivity(activity) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_activity_list(self): <NEW_LINE> <INDENT> return self._activitylist
The activity manager is used to set up available activites.
62598fc655399d3f05626811
class RemBertEmbeddings(nn.Module): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.word_embeddings = nn.Embedding( config.vocab_size, config.input_embedding_size, padding_idx=config.pad_token_id ) <NEW_LINE> self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.input_embedding_size) <NEW_LINE> self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.input_embedding_size) <NEW_LINE> self.LayerNorm = nn.LayerNorm(config.input_embedding_size, eps=config.layer_norm_eps) <NEW_LINE> self.dropout = nn.Dropout(config.hidden_dropout_prob) <NEW_LINE> self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) <NEW_LINE> <DEDENT> def forward( self, input_ids: Optional[torch.LongTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, past_key_values_length: int = 0, ) -> torch.Tensor: <NEW_LINE> <INDENT> if input_ids is not None: <NEW_LINE> <INDENT> input_shape = input_ids.size() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> input_shape = inputs_embeds.size()[:-1] <NEW_LINE> <DEDENT> seq_length = input_shape[1] <NEW_LINE> if position_ids is None: <NEW_LINE> <INDENT> position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length] <NEW_LINE> <DEDENT> if token_type_ids is None: <NEW_LINE> <INDENT> token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) <NEW_LINE> <DEDENT> if inputs_embeds is None: <NEW_LINE> <INDENT> inputs_embeds = self.word_embeddings(input_ids) <NEW_LINE> <DEDENT> token_type_embeddings = self.token_type_embeddings(token_type_ids) <NEW_LINE> embeddings = inputs_embeds + token_type_embeddings <NEW_LINE> position_embeddings = self.position_embeddings(position_ids) <NEW_LINE> embeddings += position_embeddings <NEW_LINE> embeddings = self.LayerNorm(embeddings) <NEW_LINE> embeddings = self.dropout(embeddings) <NEW_LINE> return embeddings
Construct the embeddings from word, position and token_type embeddings.
62598fc6956e5f7376df57fa
class IDesignerSerializationManager(IServiceProvider): <NEW_LINE> <INDENT> def AddSerializationProvider(self,provider): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CreateInstance(self,type,arguments,name,addToContainer): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetInstance(self,name): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetName(self,value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetSerializer(self,objectType,serializerType): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetType(self,typeName): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def RemoveSerializationProvider(self,provider): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReportError(self,errorInformation): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def SetName(self,instance,name): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Context=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> Properties=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> ResolveName=None <NEW_LINE> SerializationComplete=None
Provides an interface that can manage design-time serialization.
62598fc67cff6e4e811b5d1f
class SessionHighlightsForm(messages.Message): <NEW_LINE> <INDENT> highlights = messages.StringField(1)
SessionHighlightsForm -- get sessions that have a given highlight
62598fc64c3428357761a5b6
class Solver: <NEW_LINE> <INDENT> def solve(self, env, timeout=None, vf=False): <NEW_LINE> <INDENT> info = env.get_solver_info() <NEW_LINE> return self._solve(env, timeout, info, vf) <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def _solve(self, env, timeout=None, info=None, vf=False): <NEW_LINE> <INDENT> raise NotImplementedError("Override me!") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @abc.abstractmethod <NEW_LINE> def is_online(): <NEW_LINE> <INDENT> raise NotImplementedError("Override me!")
Base class for a solver.
62598fc6bf627c535bcb17a1
class Life(): <NEW_LINE> <INDENT> def __init__(self, dimensions, pattern = None): <NEW_LINE> <INDENT> self.grid = [] <NEW_LINE> self.rows, self.cols = dimensions <NEW_LINE> if pattern == None: <NEW_LINE> <INDENT> r.seed() <NEW_LINE> for i in range(self.rows): <NEW_LINE> <INDENT> self.grid.append([]) <NEW_LINE> for j in range(self.cols): <NEW_LINE> <INDENT> self.grid[i].append(r.getrandbits(1) == 0) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.grid = [[False for j in range(self.cols)] for i in range(self.rows)] <NEW_LINE> start_row = self.rows//2 - len(pattern)//2 <NEW_LINE> start_col = self.cols//2 - len(pattern[0])//2 <NEW_LINE> for i in range(len(pattern)): <NEW_LINE> <INDENT> for j in range(len(pattern[i])): <NEW_LINE> <INDENT> self.grid[start_row + i][start_col + j] = pattern[i][j] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def next_gen(self): <NEW_LINE> <INDENT> new_grid = [] <NEW_LINE> for i in range(self.rows): <NEW_LINE> <INDENT> new_grid.append([]) <NEW_LINE> for j in range(self.cols): <NEW_LINE> <INDENT> count = self._neighbour_count(i, j) <NEW_LINE> if self.grid[i][j]: <NEW_LINE> <INDENT> new_grid[i].append(count == 2 or count == 3) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_grid[i].append(count == 3) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.grid = new_grid <NEW_LINE> <DEDENT> def _neighbour_count(self, row, col): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for i in range(row-1, row+2): <NEW_LINE> <INDENT> for j in range(col-1, col+2): <NEW_LINE> <INDENT> count += self.grid[i % self.rows][j % self.cols] <NEW_LINE> <DEDENT> <DEDENT> return count - self.grid[row][col]
Class to simulate Conways game of Life
62598fc6aad79263cf42eace
class API: <NEW_LINE> <INDENT> def __init__(self, app_root=None, cgroup_prefix=None): <NEW_LINE> <INDENT> reader = engine.CgroupReader(app_root, cgroup_prefix) <NEW_LINE> def system(path, *paths): <NEW_LINE> <INDENT> return reader.read_system(path, *paths) <NEW_LINE> <DEDENT> def service(svc): <NEW_LINE> <INDENT> return reader.read_service(svc) <NEW_LINE> <DEDENT> def services(detail=False): <NEW_LINE> <INDENT> return reader.read_services(detail=detail) <NEW_LINE> <DEDENT> def app(name): <NEW_LINE> <INDENT> return reader.read_app(name) <NEW_LINE> <DEDENT> def apps(detail=False): <NEW_LINE> <INDENT> return reader.read_apps(detail=detail) <NEW_LINE> <DEDENT> self.system = system <NEW_LINE> self.service = service <NEW_LINE> self.services = services <NEW_LINE> self.app = app <NEW_LINE> self.apps = apps
Treadmill Cgroup REST api.
62598fc63d592f4c4edbb1ab
class ProductProductDocnaet(orm.Model): <NEW_LINE> <INDENT> _inherit = 'product.product.docnaet' <NEW_LINE> _columns = { 'docnaet_id': fields.integer('Docnaet ID migration'), }
Object product.product.docnaet
62598fc676e4537e8c3ef89e
class CharmstoreRepoDownloader(CharmstoreDownloader): <NEW_LINE> <INDENT> EXTRA_INFO_URL = CharmstoreDownloader.STORE_URL + '/meta/extra-info' <NEW_LINE> def fetch(self, dir_): <NEW_LINE> <INDENT> url = self.EXTRA_INFO_URL.format(self.entity) <NEW_LINE> repo_url = get(url).json().get('bzr-url') <NEW_LINE> if repo_url: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fetcher = fetchers.get_fetcher(repo_url) <NEW_LINE> <DEDENT> except fetchers.FetchError: <NEW_LINE> <INDENT> log.debug( "No fetcher for %s, downloading from charmstore", repo_url) <NEW_LINE> return super(CharmstoreRepoDownloader, self).fetch(dir_) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return fetcher.fetch(dir_) <NEW_LINE> <DEDENT> <DEDENT> return super(CharmstoreRepoDownloader, self).fetch(dir_)
Clones a charm's bzr repo. If the a bzr repo is not set, falls back to :class:`fetchers.CharmstoreDownloader`.
62598fc65fc7496912d483f7
class IteratorResourceDeleter(object): <NEW_LINE> <INDENT> __slots__ = ["_deleter", "_handle", "_eager_mode"] <NEW_LINE> def __init__(self, handle, deleter): <NEW_LINE> <INDENT> self._deleter = deleter <NEW_LINE> self._handle = handle <NEW_LINE> self._eager_mode = context.executing_eagerly() <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self._eager_mode: <NEW_LINE> <INDENT> with context.eager_mode(): <NEW_LINE> <INDENT> gen_dataset_ops.delete_iterator( handle=self._handle, deleter=self._deleter) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with context.graph_mode(): <NEW_LINE> <INDENT> gen_dataset_ops.delete_iterator( handle=self._handle, deleter=self._deleter)
An object which cleans up an iterator resource handle. An alternative to defining a __del__ method on an object. Even if the parent object is part of a reference cycle, the cycle will be collectable.
62598fc6be7bc26dc9251fd8
class WaterContent(object): <NEW_LINE> <INDENT> __slots__ = ("minimum", "maximum", "residual", "wilting", "field_cap") <NEW_LINE> def __init__(self, minimum: float = 0.08, maximum: float = 0.30, residual: float = 0.05, wilting: float = -1500.0, field_cap: float = 340.0): <NEW_LINE> <INDENT> self.minimum = WaterContent.inRange(minimum) <NEW_LINE> self.maximum = WaterContent.inRange(maximum) <NEW_LINE> self.residual = WaterContent.inRange(residual) <NEW_LINE> if not self._checkValues(): <NEW_LINE> <INDENT> raise ValueError(f" {self.__class__.__name__}:" f" The volumetric water content input values are incorrect.") <NEW_LINE> <DEDENT> self.wilting = wilting <NEW_LINE> self.field_cap = field_cap <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def inRange(new_value: float): <NEW_LINE> <INDENT> return np_max(np_min(1.0, new_value), 0.0) <NEW_LINE> <DEDENT> def _checkValues(self): <NEW_LINE> <INDENT> return 0.0 <= self.residual < self.minimum < self.maximum <= 1.0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def min(self): <NEW_LINE> <INDENT> return self.minimum <NEW_LINE> <DEDENT> @min.setter <NEW_LINE> def min(self, new_value): <NEW_LINE> <INDENT> old_value = self.minimum <NEW_LINE> self.minimum = new_value <NEW_LINE> if not self._checkValues(): <NEW_LINE> <INDENT> self.minimum = old_value <NEW_LINE> raise ValueError(f" {self.__class__.__name__}: The new minimum: " f" {new_value}, is not consistent with the rest" f" of the values.") <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def max(self): <NEW_LINE> <INDENT> return self.maximum <NEW_LINE> <DEDENT> @max.setter <NEW_LINE> def max(self, new_value): <NEW_LINE> <INDENT> old_value = self.maximum <NEW_LINE> self.maximum = new_value <NEW_LINE> if not self._checkValues(): <NEW_LINE> <INDENT> self.maximum = old_value <NEW_LINE> raise ValueError(f" {self.__class__.__name__}: The new maximum: {new_value}" f" is not consistent with the rest of the values.") <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def mid(self): <NEW_LINE> <INDENT> return 0.5*(self.maximum + self.minimum) <NEW_LINE> <DEDENT> @property <NEW_LINE> def res(self): <NEW_LINE> <INDENT> return self.residual <NEW_LINE> <DEDENT> @res.setter <NEW_LINE> def res(self, new_value): <NEW_LINE> <INDENT> old_value = self.residual <NEW_LINE> self.residual = new_value <NEW_LINE> if not self._checkValues(): <NEW_LINE> <INDENT> self.residual = old_value <NEW_LINE> raise ValueError(f" {self.__class__.__name__}: The new residual: {new_value}" f" is not consistent with the rest of the values.") <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def wlt(self): <NEW_LINE> <INDENT> return self.wilting <NEW_LINE> <DEDENT> @wlt.setter <NEW_LINE> def wlt(self, new_value): <NEW_LINE> <INDENT> self.wilting = new_value <NEW_LINE> <DEDENT> @property <NEW_LINE> def flc(self): <NEW_LINE> <INDENT> return self.field_cap <NEW_LINE> <DEDENT> @flc.setter <NEW_LINE> def flc(self, new_value): <NEW_LINE> <INDENT> self.field_cap = new_value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> new_line = '\n' <NEW_LINE> return f" WaterContent Id({id(self)}): {new_line}" f" Minimum={self.minimum}, Maximum={self.maximum} {new_line}" f" Residual={self.residual}, Wilting={self.wilting} {new_line}" f" Field capacity={self.field_cap}"
This class represents Water content, or soil moisture content.
62598fc663b5f9789fe8546e
class FloatSchema(NumberSchema): <NEW_LINE> <INDENT> __data_types__ = [float] <NEW_LINE> default = 0.
Float Schema.
62598fc6ad47b63b2c5a7b53
class KeywordEvaluator: <NEW_LINE> <INDENT> TXT_FILE_LINE_SEPARATOR = '\n' <NEW_LINE> def __init__(self, kw_filename): <NEW_LINE> <INDENT> self.keywords_list = [] <NEW_LINE> kw_file = None <NEW_LINE> try: <NEW_LINE> <INDENT> print('Reading keyword file: {}...'.format(kw_filename)) <NEW_LINE> with open(kw_filename, 'r') as kw_file: <NEW_LINE> <INDENT> for line in kw_file: <NEW_LINE> <INDENT> self.keywords_list.append(line.split(self.TXT_FILE_LINE_SEPARATOR)[0]) <NEW_LINE> <DEDENT> <DEDENT> print('Keyword file: {} read successfully'.format(kw_filename)) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print('Caught Exception opening / reading keyword file: {}', err) <NEW_LINE> raise <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if kw_file: <NEW_LINE> <INDENT> kw_file.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def evaluate_keywords(self, file_to_evaluate_str): <NEW_LINE> <INDENT> evaluation_file = None <NEW_LINE> try: <NEW_LINE> <INDENT> print('Opening file: {} for keywords evaluation...'.format(file_to_evaluate_str)) <NEW_LINE> with open(file_to_evaluate_str, 'r') as evaluation_file: <NEW_LINE> <INDENT> evaluation_contents_str = evaluation_file.read() <NEW_LINE> <DEDENT> kw_results_list = [] <NEW_LINE> for keyword in self.keywords_list: <NEW_LINE> <INDENT> keyword_count_int = evaluation_contents_str.count(keyword) <NEW_LINE> kw_results_list.append((keyword, keyword_count_int)) <NEW_LINE> <DEDENT> print('Successfully evaluated file: {} for keywords'.format(file_to_evaluate_str)) <NEW_LINE> return sorted(kw_results_list, key=lambda x: x[1], reverse=True) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print('Caught Exception opening / evaluating file for keywords file', err) <NEW_LINE> raise <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if evaluation_file: <NEW_LINE> <INDENT> evaluation_file.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def stats(self, keyword_results_list): <NEW_LINE> <INDENT> found_keywords_count = 0 <NEW_LINE> for result in keyword_results_list: <NEW_LINE> <INDENT> if result[1] > 0: <NEW_LINE> <INDENT> found_keywords_count += 1 <NEW_LINE> <DEDENT> <DEDENT> return round(found_keywords_count/len(keyword_results_list)*100,2), found_keywords_count, len(keyword_results_list) <NEW_LINE> <DEDENT> def write_output(self, keyword_results_list, output_file_str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(output_file_str, 'w') as output_file: <NEW_LINE> <INDENT> output_file.write("Keyword, Result" + self.TXT_FILE_LINE_SEPARATOR) <NEW_LINE> for result in keyword_results_list: <NEW_LINE> <INDENT> output_file.write("'" + result[0] + "'," + str(result[1]) + self.TXT_FILE_LINE_SEPARATOR) <NEW_LINE> <DEDENT> <DEDENT> print('Successfully wrote output file: {} for keywords results'.format(output_file_str)) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print('Caught Exception opening / writing keyword results to file: {}'.format(output_file_str)) <NEW_LINE> raise <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if output_file: <NEW_LINE> <INDENT> output_file.close()
A simple class to evaluate files for occurrences of defined keywords - originally designed to review your resume against a defined set of keywords. You can create multiple keyword definition files and evaluate your file against any set. You could use a file for general keywords and another file for keywords you have detected on a specific job description.
62598fc67c178a314d78d79a
class ProjectMember(models.Model): <NEW_LINE> <INDENT> project = models.ForeignKey("Project", related_name="members", verbose_name=u"项目") <NEW_LINE> member = models.ForeignKey("tcis_base.User", verbose_name=u"项目成员") <NEW_LINE> position = models.ForeignKey('tcis_base.Position', verbose_name=u"职位", null=True, blank=True) <NEW_LINE> active = models.BooleanField(default=True, verbose_name=u"是否有效") <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.project.name + ":" + self.member.username_zh <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.project.name + ":" + self.member.username_zh <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = [("project", "member")] <NEW_LINE> db_table = "project_member" <NEW_LINE> verbose_name = u'项目成员' <NEW_LINE> verbose_name_plural = u"项目成员管理"
项目成员
62598fc67b180e01f3e491cd
class QuestionQueryFormatKind(Enum): <NEW_LINE> <INDENT> listen = 1 <NEW_LINE> watch = 2 <NEW_LINE> read = 3
问询形式: 暂不用
62598fc6bf627c535bcb17a3
class Ackley(Benchmark): <NEW_LINE> <INDENT> def __init__(self, dim): <NEW_LINE> <INDENT> Benchmark.__init__(self, name='Ackley', dim=dim, fitness_min=0.0, lower_bound=-30.0, upper_bound=30.0, lower_init=15.0, upper_init=30.0) <NEW_LINE> <DEDENT> def fitness(self, x, limit=np.Infinity): <NEW_LINE> <INDENT> value = np.e + 20.0 - 20.0 * np.exp(-0.2 * np.sqrt(np.sum(x ** 2) / self.dim)) - np.exp(np.sum(np.cos(2 * np.pi * x)) / self.dim) <NEW_LINE> if value < 0.0: <NEW_LINE> <INDENT> value = 0.0 <NEW_LINE> <DEDENT> return value
The Ackley benchmark problem.
62598fc62c8b7c6e89bd3abe
class Card: <NEW_LINE> <INDENT> def __init__(self, ident, cardType, text, numAnswers, expansion): <NEW_LINE> <INDENT> self.ident = ident <NEW_LINE> self.cardType = cardType <NEW_LINE> self.text = text <NEW_LINE> self.numAnswers = numAnswers <NEW_LINE> self.expansion = expansion <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"{self.cardType}: {self.text}" <NEW_LINE> <DEDENT> def __repl__(self): <NEW_LINE> <INDENT> return f"{self.cardType}: {self.text}"
Card object to hold induvidual cards. Attributes: ident (int): unique ID (probably not needed) cardType (str): Q for question cards, A for answer cards text (str): Card main text numAnswers (int): Number of answers needed for question card expansion (str): Expansion set the card is found in
62598fc660cbc95b06364639
class Archive(lzma.LZMAFile): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Archive, self).__init__(*args, **kwargs) <NEW_LINE> self.compressed = True <NEW_LINE> <DEDENT> def _proxy(self, method, *args, **kwargs): <NEW_LINE> <INDENT> if not self.compressed: <NEW_LINE> <INDENT> return getattr(self._fp, method)(*args, **kwargs) <NEW_LINE> <DEDENT> if self.compressed: <NEW_LINE> <INDENT> previous = self._fp.tell() <NEW_LINE> try: <NEW_LINE> <INDENT> return getattr(super(Archive, self), method)(*args, **kwargs) <NEW_LINE> <DEDENT> except lzma._lzma.LZMAError: <NEW_LINE> <INDENT> self._fp.seek(previous) <NEW_LINE> self.compressed = False <NEW_LINE> return getattr(self._fp, method)(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def tell(self): <NEW_LINE> <INDENT> return self._proxy('tell') <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> return self._proxy('close') <NEW_LINE> <DEDENT> def seek(self, offset, whence=0): <NEW_LINE> <INDENT> return self._proxy('seek', offset, whence) <NEW_LINE> <DEDENT> def read(self, size=-1): <NEW_LINE> <INDENT> return self._proxy('read', size) <NEW_LINE> <DEDENT> def _check_can_seek(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def seekable(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def readable(self): <NEW_LINE> <INDENT> return True
file-object wrapper for decompressing xz compressed tar archives This class wraps a file-object that contains tar archive data. The data will be optionally decompressed with lzma/xz if found to be a compressed archive. The file-object itself must be seekable.
62598fc6ec188e330fdf8b90
class Explicit_RK5(Runge_Kutta): <NEW_LINE> <INDENT> def __init__(self, u0, T, tau, function): <NEW_LINE> <INDENT> super().__init__(u0, T, tau, function) <NEW_LINE> self.A = np.array( [ [0, 0, 0, 0, 0, 0], [1 / 3, 0, 0, 0, 0, 0], [4 / 25, 6 / 25, 0, 0, 0, 0], [1 / 4, -3, 15 / 4, 0, 0, 0], [2 / 27, 10 / 9, -50 / 81, 8 / 81, 0, 0], [2 / 25, 12 / 25, 2 / 15, 8 / 75, 0, 0], ] ) <NEW_LINE> self.b = np.array([23 / 192, 0, 125 / 192, 0, -27 / 64, 125 / 192]) <NEW_LINE> self.s = len(self.b) <NEW_LINE> <DEDENT> def apply_alternative_solver(self): <NEW_LINE> <INDENT> self.A = np.array( [ [0, 0, 0, 0, 0, 0], [1 / 4, 0, 0, 0, 0, 0], [1 / 8, 1 / 8, 0, 0, 0, 0], [0, 0, 1 / 2, 0, 0, 0], [3 / 16, -3 / 8, 3 / 8, 9 / 16, 0, 0], [-3 / 7, 8 / 7, 6 / 7, -12 / 7, 8 / 7, 0], ] ) <NEW_LINE> self.b = np.array([7 / 90, 0, 16 / 45, 2 / 15, 16 / 45, 7 / 90]) <NEW_LINE> self.s = len(self.b)
Subclass implementing the Runge Kutta method of order 5.
62598fc6aad79263cf42ead1
class Instruction(ndb.Model): <NEW_LINE> <INDENT> instruction = msgprop.MessageProperty(rpc_messages.Instruction) <NEW_LINE> state = ndb.StringProperty(choices=InstructionStates)
Datastore representation of an instruction for a machine. Standalone instances should not be present in the datastore.
62598fc65166f23b2e2436de
class Prelu(Activation): <NEW_LINE> <INDENT> __extra_registration_keys__ = ['leaky-relu'] <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Prelu, self).__init__(*args, **kwargs) <NEW_LINE> self.leak = theano.shared( np.ones((self.layer.size, ), FLOAT) * 0.1, name=self.layer._fmt('leak')) <NEW_LINE> self.params.append(self.leak) <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> return (x + abs(x)) / 2 + self.leak * (x - abs(x)) / 2
Parametric rectified linear activation with learnable leak rate. This activation is characterized by two linear pieces joined at the origin. For negative inputs, the unit response is a linear function of the input with slope :math:`r` (the "leak rate"). For positive inputs, the unit response is the identity function: .. math:: f(x) = \left\{ \begin{eqnarray*} rx &\qquad& \mbox{if } x < 0 \\ x &\qquad& \mbox{otherwise} \end{eqnarray*} \right. This activation allocates a separate leak rate for each unit in its layer. References ---------- K He, X Zhang, S Ren, J Sun (2015), "Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification" http://arxiv.org/abs/1502.01852
62598fc6091ae35668704f25
class BERTRegression(Block): <NEW_LINE> <INDENT> def __init__(self, bert, dropout=0.0, prefix=None, params=None): <NEW_LINE> <INDENT> super(BERTRegression, self).__init__(prefix=prefix, params=params) <NEW_LINE> self.bert = bert <NEW_LINE> with self.name_scope(): <NEW_LINE> <INDENT> self.regression = nn.HybridSequential(prefix=prefix) <NEW_LINE> if dropout: <NEW_LINE> <INDENT> self.regression.add(nn.Dropout(rate=dropout)) <NEW_LINE> <DEDENT> self.regression.add(nn.Dense(1)) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, inputs, token_types, valid_length=None): <NEW_LINE> <INDENT> _, pooler_out = self.bert(inputs, token_types, valid_length) <NEW_LINE> return self.regression(pooler_out)
Model for sentence (pair) regression task with BERT. The model feeds token ids and token type ids into BERT to get the pooled BERT sequence representation, then apply a Dense layer for regression. Parameters ---------- bert: BERTModel Bidirectional encoder with transformer. dropout : float or None, default 0.0. Dropout probability for the bert output. prefix : str or None See document of `mx.gluon.Block`. params : ParameterDict or None See document of `mx.gluon.Block`.
62598fc6f9cc0f698b1c5450
class ParamExample: <NEW_LINE> <INDENT> def __init__(self, link_uri): <NEW_LINE> <INDENT> self._ed = Espdrone(rw_cache='./cache') <NEW_LINE> self._ed.connected.add_callback(self._connected) <NEW_LINE> self._ed.disconnected.add_callback(self._disconnected) <NEW_LINE> self._ed.connection_failed.add_callback(self._connection_failed) <NEW_LINE> self._ed.connection_lost.add_callback(self._connection_lost) <NEW_LINE> print('Connecting to %s' % link_uri) <NEW_LINE> self._ed.open_link(link_uri) <NEW_LINE> self.is_connected = True <NEW_LINE> self._param_check_list = [] <NEW_LINE> self._param_groups = [] <NEW_LINE> random.seed() <NEW_LINE> <DEDENT> def _connected(self, link_uri): <NEW_LINE> <INDENT> print('Connected to %s' % link_uri) <NEW_LINE> p_toc = self._ed.param.toc.toc <NEW_LINE> for group in sorted(p_toc.keys()): <NEW_LINE> <INDENT> print('{}'.format(group)) <NEW_LINE> for param in sorted(p_toc[group].keys()): <NEW_LINE> <INDENT> print('\t{}'.format(param)) <NEW_LINE> self._param_check_list.append('{0}.{1}'.format(group, param)) <NEW_LINE> <DEDENT> self._param_groups.append('{}'.format(group)) <NEW_LINE> self._ed.param.add_update_callback(group=group, name=None, cb=self._param_callback) <NEW_LINE> <DEDENT> self._ed.param.add_update_callback(group='cpu', name='flash', cb=self._cpu_flash_callback) <NEW_LINE> print('') <NEW_LINE> <DEDENT> def _cpu_flash_callback(self, name, value): <NEW_LINE> <INDENT> print('The connected Espdrone has {}kb of flash'.format(value)) <NEW_LINE> <DEDENT> def _param_callback(self, name, value): <NEW_LINE> <INDENT> print('{0}: {1}'.format(name, value)) <NEW_LINE> self._param_check_list.remove(name) <NEW_LINE> if len(self._param_check_list) == 0: <NEW_LINE> <INDENT> print('Have fetched all parameter values.') <NEW_LINE> for g in self._param_groups: <NEW_LINE> <INDENT> self._ed.param.remove_update_callback(group=g, cb=self._param_callback) <NEW_LINE> <DEDENT> pkd = random.random() <NEW_LINE> print('') <NEW_LINE> print('Write: pid_attitude.pitch_kd={:.2f}'.format(pkd)) <NEW_LINE> self._ed.param.set_value('pid_attitude.pitch_kd', '{:.2f}'.format(pkd)) <NEW_LINE> self._ed.param.add_update_callback(group='pid_attitude', name='pitch_kd', cb=self._a_pitch_kd_callback) <NEW_LINE> <DEDENT> <DEDENT> def _a_pitch_kd_callback(self, name, value): <NEW_LINE> <INDENT> print('Readback: {0}={1}'.format(name, value)) <NEW_LINE> self._ed.close_link() <NEW_LINE> <DEDENT> def _connection_failed(self, link_uri, msg): <NEW_LINE> <INDENT> print('Connection to %s failed: %s' % (link_uri, msg)) <NEW_LINE> self.is_connected = False <NEW_LINE> <DEDENT> def _connection_lost(self, link_uri, msg): <NEW_LINE> <INDENT> print('Connection to %s lost: %s' % (link_uri, msg)) <NEW_LINE> <DEDENT> def _disconnected(self, link_uri): <NEW_LINE> <INDENT> print('Disconnected from %s' % link_uri) <NEW_LINE> self.is_connected = False
Simple logging example class that logs the Stabilizer from a supplied link uri and disconnects after 5s.
62598fc6099cdd3c63675560
class Libxml2Seeker(Seeker): <NEW_LINE> <INDENT> NAME = 'libxml2' <NEW_LINE> def searchLib(self, logger): <NEW_LINE> <INDENT> extra_parts = ['CVS', 'SVN', 'GIT'] <NEW_LINE> key_string = ": program compiled against libxml %d using older %d\n" <NEW_LINE> key_indices = [] <NEW_LINE> for idx, bin_str in enumerate(self._all_strings): <NEW_LINE> <INDENT> if key_string in str(bin_str): <NEW_LINE> <INDENT> logger.debug("Located a key string of %s in address 0x%x", self.NAME, bin_str.ea) <NEW_LINE> key_indices.append(idx) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> self._version_strings = [] <NEW_LINE> for key_index in key_indices: <NEW_LINE> <INDENT> for bin_str in self._all_strings[max(key_index - 10000, 0):min(key_index + 10000, len(self._all_strings))]: <NEW_LINE> <INDENT> cur_str = str(bin_str) <NEW_LINE> if cur_str.find('-') != -1 and cur_str.split('-')[1][:3] in extra_parts: <NEW_LINE> <INDENT> logger.debug("Located a version string of %s in address 0x%x", self.NAME, bin_str.ea) <NEW_LINE> self._version_strings.append(cur_str) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return len(self._version_strings) <NEW_LINE> <DEDENT> def identifyVersions(self, logger): <NEW_LINE> <INDENT> results = [] <NEW_LINE> for work_str in self._version_strings: <NEW_LINE> <INDENT> results.append(self.extractVersion(work_str)) <NEW_LINE> <DEDENT> return results
Seeker (Identifier) for the libxml(2) open source library.
62598fc62c8b7c6e89bd3ac0
class UnicodeRegex(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> punctuation = self.property_chars("P") <NEW_LINE> self.nondigit_punct_re = re.compile(r"([^\d])([" + punctuation + r"])") <NEW_LINE> self.punct_nondigit_re = re.compile(r"([" + punctuation + r"])([^\d])") <NEW_LINE> self.symbol_re = re.compile("([" + self.property_chars("S") + "])") <NEW_LINE> <DEDENT> def property_chars(self, prefix): <NEW_LINE> <INDENT> return "".join(six.unichr(x) for x in range(sys.maxunicode) if unicodedata.category(six.unichr(x)).startswith(prefix))
Ad-hoc hack to recognize all punctuation and symbols.
62598fc6aad79263cf42ead2
class PlanNutrients(object): <NEW_LINE> <INDENT> def __init__(self, plan): <NEW_LINE> <INDENT> self.plan = plan <NEW_LINE> self.price = 0 <NEW_LINE> self.keys = [] <NEW_LINE> self.quantities = {} <NEW_LINE> for product in self.plan['products']: <NEW_LINE> <INDENT> print('product:', product) <NEW_LINE> quantity = product['quantity'] <NEW_LINE> name = product['name'] <NEW_LINE> self.price += float(product['price']) * float(quantity) <NEW_LINE> self.keys.append(name) <NEW_LINE> self.quantities[name] = quantity <NEW_LINE> <DEDENT> <DEDENT> def get_amount(self, nutr_no): <NEW_LINE> <INDENT> applicable = False <NEW_LINE> amount = 0 <NEW_LINE> details = {} <NEW_LINE> for product in self.plan['products']: <NEW_LINE> <INDENT> quantity = float(product['quantity']) <NEW_LINE> product_amount = 0 <NEW_LINE> for ingredient in product['ingredients']: <NEW_LINE> <INDENT> nutrients = content_dict[ingredient['ndbno']] <NEW_LINE> if nutr_no not in nutrients.keys(): continue <NEW_LINE> applicable = True <NEW_LINE> m = quantity * float(ingredient['amount']) * 0.01 <NEW_LINE> product_amount = nutrients[nutr_no] * m <NEW_LINE> amount += product_amount <NEW_LINE> <DEDENT> details[product['name']] = product_amount <NEW_LINE> <DEDENT> return (applicable, amount, details) <NEW_LINE> <DEDENT> def get_name(self, key): <NEW_LINE> <INDENT> return self.quantities[key] + ' ' + key
provides nutrient amounts of a product
62598fc64a966d76dd5ef1d3
class KNearestNeighbor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def train(self, X, y): <NEW_LINE> <INDENT> self.X_train = X <NEW_LINE> self.y_train = y <NEW_LINE> <DEDENT> def predict(self, X, k=1, num_loops=0): <NEW_LINE> <INDENT> if num_loops == 0: <NEW_LINE> <INDENT> dists = self.compute_distances_no_loops(X) <NEW_LINE> <DEDENT> elif num_loops == 1: <NEW_LINE> <INDENT> dists = self.compute_distances_one_loop(X) <NEW_LINE> <DEDENT> elif num_loops == 2: <NEW_LINE> <INDENT> dists = self.compute_distances_two_loops(X) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid value %d for num_loops' % num_loops) <NEW_LINE> <DEDENT> return self.predict_labels(dists, k=k) <NEW_LINE> <DEDENT> def compute_distances_two_loops(self, X): <NEW_LINE> <INDENT> from numpy import linalg as LA <NEW_LINE> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> for j in range(num_train): <NEW_LINE> <INDENT> dists[i, j] = LA.norm(X[i, :] - self.X_train[j, :] , 2) <NEW_LINE> <DEDENT> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distances_one_loop(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> dists[i, :] = np.sqrt(np.sum(np.power(X[i, :] - self.X_train, 2), axis = 1)) <NEW_LINE> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distances_no_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> partx = np.sum(np.square(X), axis = 1) <NEW_LINE> partxt = np.sum(np.square(self.X_train), axis = 1) <NEW_LINE> partxxt = np.dot(X, self.X_train.T) <NEW_LINE> dists = np.sqrt(np.matrix(partx).T + partxt - 2 * partxxt) <NEW_LINE> return dists <NEW_LINE> <DEDENT> def predict_labels(self, dists, k=1): <NEW_LINE> <INDENT> num_test = dists.shape[0] <NEW_LINE> y_pred = np.zeros(num_test) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> closest_y = [] <NEW_LINE> index = np.argsort(dists[i, :]).tolist()[0] <NEW_LINE> kInd = index[:k] <NEW_LINE> closest_y = self.y_train[kInd] <NEW_LINE> y_pred[i] = np.argmax(np.bincount(closest_y)) <NEW_LINE> <DEDENT> return y_pred
a kNN classifier with L2 distance
62598fc63d592f4c4edbb1af
class URLSafetyHandler(urlreq.BaseHandler): <NEW_LINE> <INDENT> def __init__(self, check_func=check_url_safety): <NEW_LINE> <INDENT> self.check_url = check_func <NEW_LINE> <DEDENT> def default_open(self, req, *args, **kwargs): <NEW_LINE> <INDENT> self.check_url(req.get_full_url())
urllib handler to safety check all URLs. This is a simple handler that will pass all URLs through a safety check function before opening it. You can instantiate this class with the safety check function to use as an argument; by default, it uses this module's check_url_safety function. Each time a request is passed through this handler, the check function will be called with the request URL as an argument. It should raise an exception if the URL is unsafe to handle.
62598fc676e4537e8c3ef8a2
class ManagedClusterUpgradeProfile(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'control_plane_profile': {'required': True}, 'agent_pool_profiles': {'required': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'control_plane_profile': {'key': 'properties.controlPlaneProfile', 'type': 'ManagedClusterPoolUpgradeProfile'}, 'agent_pool_profiles': {'key': 'properties.agentPoolProfiles', 'type': '[ManagedClusterPoolUpgradeProfile]'}, } <NEW_LINE> def __init__( self, *, control_plane_profile: "ManagedClusterPoolUpgradeProfile", agent_pool_profiles: List["ManagedClusterPoolUpgradeProfile"], **kwargs ): <NEW_LINE> <INDENT> super(ManagedClusterUpgradeProfile, self).__init__(**kwargs) <NEW_LINE> self.id = None <NEW_LINE> self.name = None <NEW_LINE> self.type = None <NEW_LINE> self.control_plane_profile = control_plane_profile <NEW_LINE> self.agent_pool_profiles = agent_pool_profiles
The list of available upgrades for compute pools. 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: The ID of the upgrade profile. :vartype id: str :ivar name: The name of the upgrade profile. :vartype name: str :ivar type: The type of the upgrade profile. :vartype type: str :ivar control_plane_profile: Required. The list of available upgrade versions for the control plane. :vartype control_plane_profile: ~azure.mgmt.containerservice.v2021_08_01.models.ManagedClusterPoolUpgradeProfile :ivar agent_pool_profiles: Required. The list of available upgrade versions for agent pools. :vartype agent_pool_profiles: list[~azure.mgmt.containerservice.v2021_08_01.models.ManagedClusterPoolUpgradeProfile]
62598fc60fa83653e46f51e4
class ProduceFilter(ResultFilter): <NEW_LINE> <INDENT> allow_multiple = False <NEW_LINE> def __init__(self, *content_types, order=-1): <NEW_LINE> <INDENT> super().__init__(order) <NEW_LINE> self.content_type = ';'.join(content_types) <NEW_LINE> <DEDENT> def on_result_execution(self, context, next_filter): <NEW_LINE> <INDENT> request.environ['HTTP_ACCEPT'] = self.content_type <NEW_LINE> next_filter(context)
A filter that specifies the supported response content types. :param content_types: The list of content types. :param int order: The order in which the filter is executed.
62598fc69f288636728189fb
class Server: <NEW_LINE> <INDENT> def __init__(self, host, port) -> None: <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.repositories = {} <NEW_LINE> self.identifyRepositories() <NEW_LINE> <DEDENT> def get_databases(self): <NEW_LINE> <INDENT> client = pymongo.MongoClient(self.uri) <NEW_LINE> try: <NEW_LINE> <INDENT> db_list = client.list_database_names() <NEW_LINE> <DEDENT> except ServerSelectionTimeoutError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> db_to_ignore = "admin config local".split() <NEW_LINE> return [ db_name for db_name in db_list if db_name not in db_to_ignore ] <NEW_LINE> <DEDENT> def identifyRepositories(self): <NEW_LINE> <INDENT> db_list = self.get_databases() <NEW_LINE> if db_list is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> run_db, ref_db = BROKER_DATABASE_NAMES <NEW_LINE> if run_db in db_list: <NEW_LINE> <INDENT> db_list.remove(run_db) <NEW_LINE> if ref_db in db_list: <NEW_LINE> <INDENT> db_list.remove(ref_db) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ref_db = run_db <NEW_LINE> <DEDENT> repo = DatabaseNamePair(run_db, ref_db) <NEW_LINE> self.repositories["production-v1"] = repo <NEW_LINE> <DEDENT> while len(db_list): <NEW_LINE> <INDENT> db_name = db_list.pop() <NEW_LINE> def _check_pattern(run_suffix, ref_suffix): <NEW_LINE> <INDENT> if not db_name.endswith(run_suffix): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> run_db = db_name <NEW_LINE> instrument = db_name[: -len(run_suffix)].rstrip("-") <NEW_LINE> ref_db = f"{instrument}-{ref_suffix}" <NEW_LINE> if ref_db in db_list: <NEW_LINE> <INDENT> db_list.remove(ref_db) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ref_db = run_db <NEW_LINE> <DEDENT> return instrument, run_db, ref_db <NEW_LINE> <DEDENT> for pair in DATABASE_NAME_SUFFIXES: <NEW_LINE> <INDENT> args = _check_pattern(pair.runs, pair.refs) <NEW_LINE> if args is not None: <NEW_LINE> <INDENT> instrument, run_db, ref_db = args <NEW_LINE> repo = DatabaseNamePair(run_db, ref_db) <NEW_LINE> self.repositories[instrument] = repo <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def host(self): <NEW_LINE> <INDENT> return self._host <NEW_LINE> <DEDENT> @host.setter <NEW_LINE> def host(self, value): <NEW_LINE> <INDENT> self._host = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def port(self): <NEW_LINE> <INDENT> return self._port <NEW_LINE> <DEDENT> @port.setter <NEW_LINE> def port(self, value): <NEW_LINE> <INDENT> self._port = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def uri(self): <NEW_LINE> <INDENT> return f"mongodb://{self.host}:{self.port}/"
A Mongodb server for databroker.
62598fc65fcc89381b2662cc
class IPersonalPreferences(Interface): <NEW_LINE> <INDENT> visible_ids = Bool( title=_( u'label_edit_short_names', default=u'Allow editing of Short Names' ), description=_( u'help_display_names', default=(u'Determines if Short Names (also known ' u'as IDs) are changable when editing items. If Short ' u'Names are not displayed, they will be generated ' u'automatically.')), required=False ) <NEW_LINE> wysiwyg_editor = Choice( title=_(u'label_wysiwyg_editor', default=u'Wysiwyg editor'), description=_( u'help_wysiwyg_editor', default=u'Wysiwyg editor to use.' ), vocabulary="plone.app.vocabularies.AvailableEditors", required=False, ) <NEW_LINE> ext_editor = Bool( title=_(u'label_ext_editor', default=u'Enable external editing'), description=_( u'help_content_ext_editor', default=u'When checked, an option will be made visible on each ' 'page which allows you to edit content with your favorite editor ' 'instead of using browser-based editors. This requires an ' 'additional application, most often ExternalEditor or ' 'ZopeEditManager, installed client-side. Ask your administrator ' 'for more information if needed.' ), ) <NEW_LINE> language = Choice( title=_(u'label_language', default=u'Language'), description=_(u'help_preferred_language', u'Your preferred language.'), vocabulary="plone.app.vocabularies.AvailableContentLanguages", required=False ) <NEW_LINE> if HAS_PAE and HAS_DT_VOCAB: <NEW_LINE> <INDENT> timezone = Choice( title=_(u'label_timezone', default=u'Time zone'), description=_(u'help_timezone', default=u'Your time zone'), vocabulary='plone.app.vocabularies.AvailableTimezones', required=False, ) <NEW_LINE> <DEDENT> elif HAS_PAE: <NEW_LINE> <INDENT> timezone = Choice( title=_(u'label_timezone', default=u'Time zone'), description=_(u'help_timezone', default=u'Your time zone'), vocabulary='plone.app.vocabularies.Timezones', required=False, )
Provide schema for personalize form.
62598fc67b180e01f3e491cf
class SaveImage(Task): <NEW_LINE> <INDENT> def __init__(self, sequence, trigger: Trigger, file_writer, plotting_function, name): <NEW_LINE> <INDENT> super().__init__(sequence, trigger) <NEW_LINE> self.file_writer = file_writer <NEW_LINE> self.plotting_function = plotting_function <NEW_LINE> self.im = tf.placeholder(tf.float64, [1, None, None, None]) <NEW_LINE> self.op = tf.summary.image(name, self.im) <NEW_LINE> <DEDENT> def _event_handler(self, manager): <NEW_LINE> <INDENT> fig = self.plotting_function() <NEW_LINE> buf = io.BytesIO() <NEW_LINE> fig.savefig(buf, format='png', bbox_inches='tight') <NEW_LINE> buf.seek(0) <NEW_LINE> image = tf.image.decode_png(buf.getvalue()) <NEW_LINE> image = manager.session.run(tf.expand_dims(image, 0)) <NEW_LINE> summary = manager.session.run([self.op, manager.global_step], {self.im: image}) <NEW_LINE> self.file_writer.add_summary(*summary) <NEW_LINE> plt.close(fig)
Store and display matplotlib images
62598fc6ff9c53063f51a94c
class Player(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.width = 75 <NEW_LINE> self.height = 15 <NEW_LINE> self.image = pygame.Surface([self.width, self.height]) <NEW_LINE> self.image.fill((white)) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.screenheight = pygame.display.get_surface().get_height() <NEW_LINE> self.screenwidth = pygame.display.get_surface().get_width() <NEW_LINE> self.rect.x = 0 <NEW_LINE> self.rect.y = self.screenheight - self.height <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> pos = pygame.mouse.get_pos() <NEW_LINE> result = model.predict(np.expand_dims(data, axis=0)) <NEW_LINE> point = int(result[0, 0]) <NEW_LINE> print(point) <NEW_LINE> self.rect.x = point <NEW_LINE> if self.rect.x > self.screenwidth - self.width: <NEW_LINE> <INDENT> self.rect.x = self.screenwidth - self.width
This class represents the bar at the bottom that the player controls.
62598fc64c3428357761a5bc
class AIPSImage(_AIPSData): <NEW_LINE> <INDENT> def __init__(self, name, klass, disk, seq): <NEW_LINE> <INDENT> self.desc = _AIPSDataDesc(name, klass, AIPS.disks[disk].disk, seq) <NEW_LINE> self.proxy = AIPS.disks[disk].proxy() <NEW_LINE> self.disk = disk <NEW_LINE> self.url = AIPS.disks[disk].url <NEW_LINE> self.dirs = None <NEW_LINE> self.myClass = "AIPSImage" <NEW_LINE> self.FileType= "AIPS" <NEW_LINE> self.Aname = name <NEW_LINE> self.Aclass = klass <NEW_LINE> self.Aseq = seq <NEW_LINE> self.Disk = disk <NEW_LINE> self.Atype = "MA" <NEW_LINE> self.Otype = "Image" <NEW_LINE> self.name = "noname" <NEW_LINE> self.exist = self.exists() <NEW_LINE> return <NEW_LINE> <DEDENT> def display(self, dispURL="http://localhost:8765/RPC2"): <NEW_LINE> <INDENT> (thedisk,dirs) = adjust_disk(self.disk, self.url) <NEW_LINE> self.desc.disk = thedisk <NEW_LINE> self.desc.dirs = dirs <NEW_LINE> return self._method(_whoami())(self.desc, dispURL)
This class describes an AIPS image.
62598fc67d847024c075c6bc
class Dom(object): <NEW_LINE> <INDENT> def __init__(self, root=None): <NEW_LINE> <INDENT> self.set_root(root) <NEW_LINE> <DEDENT> def get_tags(self, root, recursive=True): <NEW_LINE> <INDENT> tags = [] <NEW_LINE> for child in root.children: <NEW_LINE> <INDENT> tags.append(child) <NEW_LINE> if recursive: <NEW_LINE> <INDENT> tags += self.get_tags(child) <NEW_LINE> <DEDENT> <DEDENT> return tags <NEW_LINE> <DEDENT> def set_root(self, root): <NEW_LINE> <INDENT> self.root = root <NEW_LINE> if self.root is not None: <NEW_LINE> <INDENT> correct_type(root, Tag)
Document Object Model class. Contains root of the HTML tag tree.
62598fc6d8ef3951e32c7fdb
class UnrecognizedApiHttpError(UnrecognizedApiError): <NEW_LINE> <INDENT> def __init__(self, exc: googleapiclient.errors.HttpError) -> None: <NEW_LINE> <INDENT> self.response: httplib2.Response = exc.resp <NEW_LINE> self.response_content: bytes = exc.content <NEW_LINE> self.request_uri: str = exc.uri <NEW_LINE> self.error_reason = "unknown error reason" <NEW_LINE> try: <NEW_LINE> <INDENT> self.error_reason = exc._get_reason().strip() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return "Unrecognized Google API HTTP error: {error_reason}.".format( error_reason=self.error_reason)
Unrecognized Google API ``HttpError``.
62598fc65fc7496912d483fa
class TranslatableModelForm(compat.with_metaclass(TranslatableModelFormMetaclass, TranslatableModelFormMixin, forms.ModelForm)): <NEW_LINE> <INDENT> pass
The model form to use for translated models.
62598fc6adb09d7d5dc0a87b
class Photo(DB.Model): <NEW_LINE> <INDENT> object_id = DB.Column( DB.Integer(), primary_key=True, nullable=False ) <NEW_LINE> filename = DB.Column( DB.Unicode(50), nullable=False ) <NEW_LINE> full_url = DB.Column( DB.Unicode(250), nullable=False ) <NEW_LINE> thumb_url = DB.Column( DB.Unicode(250), nullable=False ) <NEW_LINE> def __init__(self, filename, full_url, thumb_url): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.full_url = full_url <NEW_LINE> self.thumb_url = thumb_url <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Photo {0}: {1}>'.format(self.object_id, self.filename) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_by_id(object_id): <NEW_LINE> <INDENT> photo = Photo.query.filter( Photo.object_id == int(object_id) ).first() <NEW_LINE> if not photo: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return photo
Model for representing a photo stored on S3.
62598fc65fdd1c0f98e5e293
class GxToolset(CoClass): <NEW_LINE> <INDENT> _reg_clsid_ = GUID('{4A7874DE-0020-4F35-8955-CB414813FE78}') <NEW_LINE> _idlflags_ = [] <NEW_LINE> _typelib_path_ = typelib_path <NEW_LINE> _reg_typelib_ = ('{ADC7DE29-DC0B-448E-BBF6-27E4E34CF2EC}', 10, 2)
Catalog object corresponding to toolsets.
62598fc666673b3332c306d6
class WMLParser(SGMLParser): <NEW_LINE> <INDENT> PARSE_TAGS = SGMLParser.TAGS_WITH_URLS.union({'go', 'postfield', 'setvar', 'input', 'select', 'option'}) <NEW_LINE> def __init__(self, http_response): <NEW_LINE> <INDENT> self._select_tag_name = '' <NEW_LINE> self._source_url = http_response.get_url() <NEW_LINE> SGMLParser.__init__(self, http_response) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def can_parse(http_resp): <NEW_LINE> <INDENT> if 'wml' in http_resp.content_type: <NEW_LINE> <INDENT> document = http_resp.get_body().lower() <NEW_LINE> if WML_HEADER in document: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def _handle_go_tag_start(self, tag, tag_name, attrs): <NEW_LINE> <INDENT> self._inside_form = True <NEW_LINE> method = attrs.get('method', 'GET').upper() <NEW_LINE> action = attrs.get('href', None) <NEW_LINE> if action is None: <NEW_LINE> <INDENT> action = self._source_url <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = self._decode_url(action) <NEW_LINE> try: <NEW_LINE> <INDENT> action = self._base_url.url_join(action, encoding=self._encoding) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> action = self._source_url <NEW_LINE> <DEDENT> <DEDENT> f = FormParameters(encoding=self._encoding) <NEW_LINE> f.set_method(method) <NEW_LINE> f.set_action(action) <NEW_LINE> self._forms.append(f) <NEW_LINE> <DEDENT> def _handle_go_tag_end(self, tag): <NEW_LINE> <INDENT> self._inside_form = False <NEW_LINE> <DEDENT> def _handle_input_tag_start(self, tag, tag_name, attrs): <NEW_LINE> <INDENT> if not self._inside_form: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> f = self._forms[-1] <NEW_LINE> f.add_field_by_attrs(attrs) <NEW_LINE> <DEDENT> def _handle_select_tag_start(self, tag, tag_name, attrs): <NEW_LINE> <INDENT> if not self._inside_form: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._select_tag_name = get_value_by_key(attrs, 'name', 'id') <NEW_LINE> if self._select_tag_name: <NEW_LINE> <INDENT> self._inside_select = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._inside_select = False <NEW_LINE> <DEDENT> <DEDENT> def _handle_option_tag_start(self, tag, tag_name, attrs): <NEW_LINE> <INDENT> if not self._inside_form: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self._inside_select: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> f = self._forms[-1] <NEW_LINE> attrs['name'] = self._select_tag_name <NEW_LINE> f.add_field_by_attrs(attrs) <NEW_LINE> <DEDENT> _handle_postfield_tag_start = _handle_input_tag_start <NEW_LINE> _handle_setvar_tag_start = _handle_input_tag_start
This class is a WML parser. WML is used in cellphone "web" pages. :author: Andres Riancho (andres.riancho@gmail.com)
62598fc6377c676e912f6ef5
class people: <NEW_LINE> <INDENT> eat='喜欢吃饭喜欢睡觉' <NEW_LINE> def __init__(self,name,age,sex): <NEW_LINE> <INDENT> self.name=name <NEW_LINE> self.age=age <NEW_LINE> self.sex=sex <NEW_LINE> print('这是一个初始化方法!') <NEW_LINE> <DEDENT> def getinfo(self): <NEW_LINE> <INDENT> print('这个人叫%s,然后年纪是%d,最后呢性别竟然是%s'%(self.name,self.age,self.sex)) <NEW_LINE> print('%s%s'%(self.name,people.eat)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def static1(): <NEW_LINE> <INDENT> print('人们几乎都%s'%people.eat) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def class1(cls): <NEW_LINE> <INDENT> print('人们几乎都%s' % cls.eat)
这个类是一个人类,实例属性包含name,age,sex
62598fc6fff4ab517ebcdae8
class RouteViewSet(viewsets.ViewSet): <NEW_LINE> <INDENT> def list(self, request): <NEW_LINE> <INDENT> queryset = [] <NEW_LINE> serializer = RouteSerializer(queryset, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def retrieve(self, request, pk=None): <NEW_LINE> <INDENT> ds = str(pk) <NEW_LINE> dssyear = int(ds[0:4]) <NEW_LINE> dssmonth = int(ds[4:6]) <NEW_LINE> dssday = int(ds[6:8]) <NEW_LINE> dsshour = int(ds[8:10]) <NEW_LINE> dssmin = int(ds[10:12]) <NEW_LINE> dsssec = int(ds[12:14]) <NEW_LINE> dseyear = int(ds[14:18]) <NEW_LINE> dsemonth = int(ds[18:20]) <NEW_LINE> dseday = int(ds[20:22]) <NEW_LINE> dsehour = int(ds[22:24]) <NEW_LINE> dsemin = int(ds[24:26]) <NEW_LINE> dsesec = int(ds[26:]) <NEW_LINE> dts = datetime.datetime(dssyear, dssmonth, dssday, dsshour, dssmin, dsssec, tzinfo=pytz.UTC) <NEW_LINE> dte = datetime.datetime(dseyear, dsemonth, dseday, dsehour, dsemin, dsesec, tzinfo=pytz.UTC) <NEW_LINE> event = Event(timestart=dts, timeend=dte) <NEW_LINE> data = {"timestart": event.timestart, "timeend": event.timeend, "geo": event.geojson()} <NEW_LINE> return Response(data)
The Route namespace is for querying positions in batch, as a route
62598fc65fdd1c0f98e5e294
class OAuthCreateAppTestCase(TestCase): <NEW_LINE> <INDENT> def test_command_output(self): <NEW_LINE> <INDENT> out = StringIO() <NEW_LINE> call_command('oauth_create_app', stdout=out) <NEW_LINE> self.assertIn('Successfully created application', out.getvalue()) <NEW_LINE> exception = False <NEW_LINE> try: <NEW_LINE> <INDENT> call_command('oauth_create_app') <NEW_LINE> <DEDENT> except CommandError: <NEW_LINE> <INDENT> exception = True <NEW_LINE> <DEDENT> self.assertTrue(exception) <NEW_LINE> <DEDENT> def test_command_function(self): <NEW_LINE> <INDENT> self.assertEqual(Application.objects.count(), 0) <NEW_LINE> out = StringIO() <NEW_LINE> call_command('oauth_create_app', stdout=out) <NEW_LINE> self.assertEqual(Application.objects.count(), 1)
oauth_create_app test case
62598fc67047854f4633f6d5
class CleanController(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._controller = None <NEW_LINE> <DEDENT> async def __aenter__(self): <NEW_LINE> <INDENT> self._controller = Controller() <NEW_LINE> await self._controller.connect() <NEW_LINE> return self._controller <NEW_LINE> <DEDENT> async def __aexit__(self, exc_type, exc, tb): <NEW_LINE> <INDENT> await self._controller.disconnect()
Context manager that automatically connects and disconnects from the currently active controller. Note: Unlike CleanModel, this will not create a new controller for you, and an active controller must already be available.
62598fc67c178a314d78d7a2
class RestThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, url: str, method: str, params: Optional[dict], data: Optional[str], headers: Optional[dict]): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.url = url <NEW_LINE> self.method = method <NEW_LINE> self.params = params <NEW_LINE> self.data = data <NEW_LINE> self.headers = headers <NEW_LINE> self.response = {} <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.response = RestRequest.send(url=self.url, method=self.method, params=self.params, data=self.data, headers=self.headers)
A class used to easily send asynchronous calls to the REST API. After constructing the call, the response can be read with the response property.
62598fc6656771135c489972
class FRBHost(FRBGalaxy): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def by_frb(cls, frb, **kwargs): <NEW_LINE> <INDENT> if frb.frb_name[0:3] == 'FRB': <NEW_LINE> <INDENT> name = frb.frb_name[3:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = frb.frb_name <NEW_LINE> <DEDENT> path = os.path.join(resource_filename('frb', 'data/Galaxies/'), name) <NEW_LINE> json_file = os.path.join(path, FRBHost._make_outfile(name)) <NEW_LINE> slf = cls.from_json(frb, json_file, **kwargs) <NEW_LINE> return slf <NEW_LINE> <DEDENT> def __init__(self, ra, dec, frb, z_frb=None, **kwargs): <NEW_LINE> <INDENT> super(FRBHost, self).__init__(ra, dec, frb, **kwargs) <NEW_LINE> idname = utils.parse_frb_name(frb.frb_name, prefix='') <NEW_LINE> self.name = 'HG{}'.format(idname) <NEW_LINE> if z_frb is not None: <NEW_LINE> <INDENT> self.redshift['z_FRB'] = z_frb <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _make_outfile(frbname): <NEW_LINE> <INDENT> if frbname[0:3] != 'FRB': <NEW_LINE> <INDENT> prefix = 'FRB' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prefix = '' <NEW_LINE> <DEDENT> outfile = '{}{}_host.json'.format(prefix, frbname) <NEW_LINE> return outfile <NEW_LINE> <DEDENT> def make_outfile(self): <NEW_LINE> <INDENT> outfile = self._make_outfile(self.frb.frb_name) <NEW_LINE> return outfile <NEW_LINE> <DEDENT> def set_z(self, z, origin, err=None): <NEW_LINE> <INDENT> super(FRBHost,self).set_z(z, origin, err=err) <NEW_LINE> self.redshift['z_FRB'] = z <NEW_LINE> if err is not None: <NEW_LINE> <INDENT> self.redshift['z_FRB_err'] = err
Child of FRBGalaxy specific for an FRB host Args: ra (float): RA in deg dec (float): DEC in deg FRB (frb.FRB):
62598fc623849d37ff8513b6
class NotChecker(checkers.BaseChecker): <NEW_LINE> <INDENT> __implements__ = (interfaces.IAstroidChecker,) <NEW_LINE> msgs = { "C0113": ( 'Consider changing "%s" to "%s"', "unneeded-not", "Used when a boolean expression contains an unneeded negation.", ) } <NEW_LINE> name = "refactoring" <NEW_LINE> reverse_op = { "<": ">=", "<=": ">", ">": "<=", ">=": "<", "==": "!=", "!=": "==", "in": "not in", "is": "is not", } <NEW_LINE> skipped_nodes = (nodes.Set,) <NEW_LINE> skipped_classnames = [f"builtins.{qname}" for qname in ("set", "frozenset")] <NEW_LINE> @utils.check_messages("unneeded-not") <NEW_LINE> def visit_unaryop(self, node: nodes.UnaryOp) -> None: <NEW_LINE> <INDENT> if node.op != "not": <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> operand = node.operand <NEW_LINE> if isinstance(operand, nodes.UnaryOp) and operand.op == "not": <NEW_LINE> <INDENT> self.add_message( "unneeded-not", node=node, args=(node.as_string(), operand.operand.as_string()), ) <NEW_LINE> <DEDENT> elif isinstance(operand, nodes.Compare): <NEW_LINE> <INDENT> left = operand.left <NEW_LINE> if len(operand.ops) > 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> operator, right = operand.ops[0] <NEW_LINE> if operator not in self.reverse_op: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> frame = node.frame(future=True) <NEW_LINE> if frame.name == "__ne__" and operator == "==": <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for _type in (utils.node_type(left), utils.node_type(right)): <NEW_LINE> <INDENT> if not _type: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if isinstance(_type, self.skipped_nodes): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if ( isinstance(_type, astroid.Instance) and _type.qname() in self.skipped_classnames ): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> suggestion = ( f"{left.as_string()} {self.reverse_op[operator]} {right.as_string()}" ) <NEW_LINE> self.add_message( "unneeded-not", node=node, args=(node.as_string(), suggestion) )
Checks for too many not in comparison expressions. - "not not" should trigger a warning - "not" followed by a comparison should trigger a warning
62598fc64c3428357761a5c0
class TaskContainer(dict, t.MutableMapping[str, Task]): <NEW_LINE> <INDENT> def __iter__(self) -> t.Iterator[Task]: <NEW_LINE> <INDENT> return iter(self.values())
A container for task objects.
62598fc6f548e778e596b8a0
class StaySerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> review = ReviewSerializer(read_only=True) <NEW_LINE> customer = BaseUserSerializer(read_only=True) <NEW_LINE> hotel = HotelDetailsSerializer(read_only=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Stay <NEW_LINE> fields = ("id", "start_date", "end_date", "customer", "hotel", "review",)
Serializer to represent the Stay model
62598fc650812a4eaa620d66
class JobRuntimeSpec: <NEW_LINE> <INDENT> def __init__( self, args: List[str], env_vars: Optional[Dict[str, str]] = None, gcs_mounts: Optional[Dict[str, str]] = None, gcs_target: Optional[Dict[str, str]] = None, ): <NEW_LINE> <INDENT> self.args = args <NEW_LINE> self.env_vars = env_vars or {} <NEW_LINE> self.gcs_mounts = gcs_mounts or {} <NEW_LINE> self.gcs_target = gcs_target or {}
Specifies runtime properties of jobs
62598fc65fc7496912d483fc
class ChoiceParser(AbstractParser): <NEW_LINE> <INDENT> def __init__(self, this, that): <NEW_LINE> <INDENT> self.expected = merge_expected(this, that, " or ") <NEW_LINE> self.parsers = merge_parser_lists(this, that, ChoiceParser) <NEW_LINE> <DEDENT> def scan(self, text, start=0): <NEW_LINE> <INDENT> for this in self.parsers: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return this.scan(text, start) <NEW_LINE> <DEDENT> except Failure: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> raise Failure(text, start, self.expected)
A parser that matches any of a list of choices. Backtracks to the beginning of consumption in case of failure.
62598fc6be7bc26dc9251fdd
class Cxt(Format): <NEW_LINE> <INDENT> suffix = '.cxt' <NEW_LINE> dumps_rstrip = False <NEW_LINE> symbols = SYMBOLS <NEW_LINE> values = {s: b for b, s in symbols.items()} <NEW_LINE> @classmethod <NEW_LINE> def loadf(cls, file): <NEW_LINE> <INDENT> source = file.read().strip() <NEW_LINE> b, yx, table = source.split('\n\n') <NEW_LINE> y, x = map(int, yx.split()) <NEW_LINE> lines = [l.strip() for l in table.strip().split('\n')] <NEW_LINE> objects = lines[:y] <NEW_LINE> properties = lines[y:y + x] <NEW_LINE> bools = [tuple(map(cls.values.__getitem__, l)) for l in lines[y + x:]] <NEW_LINE> return ContextArgs(objects, properties, bools) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def dumpf(cls, file, objects, properties, bools, *, _serialized=None): <NEW_LINE> <INDENT> write = functools.partial(print, file=file) <NEW_LINE> for line in iter_cxt_lines(objects, properties, bools, symbols=cls.symbols): <NEW_LINE> <INDENT> write(line)
Formal context in the classic CXT format.
62598fc63617ad0b5ee0644c
@mock.patch('adefa.cli.print_api_response') <NEW_LINE> class TestList(TestCase): <NEW_LINE> <INDENT> def test_list(self, mocked_print): <NEW_LINE> <INDENT> items = ['devices', 'projects', 'groups', 'uploads', 'runs', 'jobs'] <NEW_LINE> for pos, item in enumerate(items): <NEW_LINE> <INDENT> cli.client = mock.MagicMock() <NEW_LINE> if pos > 1: <NEW_LINE> <INDENT> with mock.patch('click.prompt') as mocked_click: <NEW_LINE> <INDENT> result = runner.invoke(cli.list, [item]) <NEW_LINE> self.assertTrue(mocked_click.called) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result = runner.invoke(cli.list, [item]) <NEW_LINE> <DEDENT> self.assertTrue(mocked_print.called) <NEW_LINE> self.assertEqual(result.exit_code, 0)
Unit test class to test get list of data.
62598fc6d486a94d0ba2c2d6
class BooleanSetting(Setting): <NEW_LINE> <INDENT> YES_VALUES = ('yes', 'true', '1', 1, True) <NEW_LINE> NO_VALUES = ('no', 'false', '0', 0, False) <NEW_LINE> def __init__(self, default=False): <NEW_LINE> <INDENT> super(BooleanSetting, self).__init__(default) <NEW_LINE> <DEDENT> def validate(self, new_value): <NEW_LINE> <INDENT> if isinstance(new_value, basestring): <NEW_LINE> <INDENT> new_value = new_value.lower() <NEW_LINE> <DEDENT> return new_value in (BooleanSetting.YES_VALUES + BooleanSetting.NO_VALUES) <NEW_LINE> <DEDENT> def transform(self, new_value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> new_value = new_value.lower() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if new_value in BooleanSetting.YES_VALUES: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if new_value in BooleanSetting.NO_VALUES: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> raise ValueError('Invalid boolean value: {}'.format(new_value))
A boolean value.
62598fc623849d37ff8513b8
class MissingInputDataException(Exception): <NEW_LINE> <INDENT> rc = 103
Raised when a script can't run because some information is missing
62598fc6167d2b6e312b727c
class EnvironmentResource(CommonResource): <NEW_LINE> <INDENT> class Meta(CommonMeta): <NEW_LINE> <INDENT> queryset = models.Environment.objects.all() <NEW_LINE> filtering = { 'uuid': ('exact',), 'name': ('exact', 'in',)}
API Resource for 'Environment' model.
62598fc64a966d76dd5ef1db
class NeighborsClassifier(BaseEstimator, ClassifierMixin): <NEW_LINE> <INDENT> def __init__(self, n_neighbors=5, algorithm='auto', window_size=1): <NEW_LINE> <INDENT> self.n_neighbors = n_neighbors <NEW_LINE> self.window_size = window_size <NEW_LINE> self.algorithm = algorithm <NEW_LINE> <DEDENT> def fit(self, X, y, **params): <NEW_LINE> <INDENT> X = np.asanyarray(X) <NEW_LINE> if y is None: <NEW_LINE> <INDENT> raise ValueError("y must not be None") <NEW_LINE> <DEDENT> self._y = np.asanyarray(y) <NEW_LINE> self._set_params(**params) <NEW_LINE> if self.algorithm == 'ball_tree' or (self.algorithm == 'auto' and X.shape[1] < 20): <NEW_LINE> <INDENT> self.ball_tree = BallTree(X, self.window_size) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ball_tree = None <NEW_LINE> self._fit_X = X <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def kneighbors(self, data, return_distance=True, **params): <NEW_LINE> <INDENT> self._set_params(**params) <NEW_LINE> return self.ball_tree.query( data, k=self.n_neighbors, return_distance=return_distance) <NEW_LINE> <DEDENT> def predict(self, X, **params): <NEW_LINE> <INDENT> X = np.atleast_2d(X) <NEW_LINE> self._set_params(**params) <NEW_LINE> if self.ball_tree is None: <NEW_LINE> <INDENT> if self.algorithm == 'brute_inplace': <NEW_LINE> <INDENT> neigh_ind = knn_brute(self._fit_X, X, self.n_neighbors) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from .metrics import euclidean_distances <NEW_LINE> dist = euclidean_distances( X, self._fit_X, squared=True) <NEW_LINE> neigh_ind = dist.argsort(axis=1)[:, :self.n_neighbors] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> neigh_ind = self.ball_tree.query( X, self.n_neighbors, return_distance=False) <NEW_LINE> <DEDENT> pred_labels = self._y[neigh_ind] <NEW_LINE> from scipy import stats <NEW_LINE> mode, _ = stats.mode(pred_labels, axis=1) <NEW_LINE> return mode.flatten().astype(np.int)
Classifier implementing k-Nearest Neighbor Algorithm. Parameters ---------- n_neighbors : int, optional Default number of neighbors. Defaults to 5. window_size : int, optional Window size passed to BallTree algorithm : {'auto', 'ball_tree', 'brute', 'brute_inplace'}, optional Algorithm used to compute the nearest neighbors. 'ball_tree' will construct a BallTree, 'brute' and 'brute_inplace' will perform brute-force search.'auto' will guess the most appropriate based on current dataset. Examples -------- >>> samples = [[0, 0, 1], [1, 0, 0]] >>> labels = [0, 1] >>> from scikits.learn.neighbors import NeighborsClassifier >>> neigh = NeighborsClassifier(n_neighbors=1) >>> neigh.fit(samples, labels) NeighborsClassifier(n_neighbors=1, window_size=1, algorithm='auto') >>> print neigh.predict([[0,0,0]]) [1] See also -------- BallTree References ---------- http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
62598fc62c8b7c6e89bd3ac8
class AbstractItem(core_models.AbstractTimeStamped): <NEW_LINE> <INDENT> name = models.CharField(max_length=80) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name
Abstract Item
62598fc6aad79263cf42eada
class DummyObject: <NEW_LINE> <INDENT> def __init__(self, base=None): <NEW_LINE> <INDENT> if base is not None: <NEW_LINE> <INDENT> if hasattr(base, "location"): <NEW_LINE> <INDENT> self.pos = Vec3(base.location.x, base.location.y, base.location.z) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.pos = Vec3(base.pos) <NEW_LINE> <DEDENT> if hasattr(base, "velocity"): <NEW_LINE> <INDENT> self.vel = Vec3(base.velocity.x, base.velocity.y, base.velocity.z) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.vel = Vec3(base.vel) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.pos = Vec3(0, 0, 0) <NEW_LINE> self.vel = Vec3(0, 0, 0)
Holds a position and velocity. The base can be either a physics object from the rlbot framework or any object that has a pos and vel attribute.
62598fc65fc7496912d483fd
class Weather(models.Model): <NEW_LINE> <INDENT> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> longitude = models.FloatField() <NEW_LINE> latitude = models.FloatField() <NEW_LINE> temperature = models.FloatField() <NEW_LINE> humidity = models.FloatField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('-created',)
A model for the weather datas.
62598fc65166f23b2e2436e8
class CustomListener(StreamListener): <NEW_LINE> <INDENT> def __init__(self, fname): <NEW_LINE> <INDENT> safe_fname = format_filename(fname) <NEW_LINE> self.outfile = "stream_%s.jsonl" % safe_fname <NEW_LINE> <DEDENT> def on_data(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.outfile, 'a') as f: <NEW_LINE> <INDENT> f.write(data) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> except BaseException as e: <NEW_LINE> <INDENT> sys.stderr.write("Error on_data: {}\n".format(e)) <NEW_LINE> time.sleep(5) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def on_error(self, status): <NEW_LINE> <INDENT> if status == 420: <NEW_LINE> <INDENT> sys.stderr.write("Rate limit exceeded\n".format(status)) <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.stderr.write("Error {}\n".format(status)) <NEW_LINE> return True
Custom StreamListener for streaming Twitter data.
62598fc68a349b6b43686545
class RGensa(RPackage): <NEW_LINE> <INDENT> homepage = "https://cloud.r-project.org/package=GenSA" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/GenSA_1.1.7.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/GenSA/" <NEW_LINE> version('1.1.7', sha256='9d99d3d0a4b7770c3c3a6de44206811272d78ab94481713a8c369f7d6ae7b80f') <NEW_LINE> depends_on('r@2.12.0:', type=('build', 'run'))
GenSA: Generalized Simulated Annealing Performs search for global minimum of a very complex non-linear objective function with a very large number of optima.
62598fc666673b3332c306dc
class NewLinkViewSelectWdg(BaseRefreshWdg): <NEW_LINE> <INDENT> def init(my): <NEW_LINE> <INDENT> web = WebContainer.get_web() <NEW_LINE> my.search_type = web.get_form_value('search_type') <NEW_LINE> my.refresh = web.get_form_value('is_refresh')=='true' <NEW_LINE> <DEDENT> def get_display(my): <NEW_LINE> <INDENT> widget = DivWdg(id='link_view_select') <NEW_LINE> widget.add_class("link_view_select") <NEW_LINE> if my.refresh: <NEW_LINE> <INDENT> widget = Widget() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> my.set_as_panel(widget) <NEW_LINE> <DEDENT> views = [] <NEW_LINE> if my.search_type: <NEW_LINE> <INDENT> from pyasm.search import WidgetDbConfig <NEW_LINE> search = Search( WidgetDbConfig.SEARCH_TYPE ) <NEW_LINE> search.add_filter("search_type", my.search_type) <NEW_LINE> search.add_regex_filter("view", "link_search:|saved_search:", op="NEQI") <NEW_LINE> search.add_order_by('view') <NEW_LINE> widget_dbs = search.get_sobjects() <NEW_LINE> views = SObject.get_values(widget_dbs, 'view') <NEW_LINE> <DEDENT> labels = [view for view in views] <NEW_LINE> views.insert(0, 'table') <NEW_LINE> labels.insert(0, 'table (Default)') <NEW_LINE> st_select = SelectWdg('new_link_view', label='View: ') <NEW_LINE> st_select.set_option('values', views) <NEW_LINE> st_select.set_option('labels', labels) <NEW_LINE> widget.add(st_select) <NEW_LINE> return widget
A widget for the view select when creating a new link
62598fc6283ffb24f3cf3b8b
class Const(WireVector): <NEW_LINE> <INDENT> _code = 'C' <NEW_LINE> def __init__(self, val, bitwidth=None, name='', signed=False, block=None): <NEW_LINE> <INDENT> self._validate_bitwidth(bitwidth) <NEW_LINE> from .helperfuncs import infer_val_and_bitwidth <NEW_LINE> num, bitwidth = infer_val_and_bitwidth(val, bitwidth, signed) <NEW_LINE> if num < 0: <NEW_LINE> <INDENT> raise PyrtlInternalError( 'Const somehow evaluating to negative integer after checks') <NEW_LINE> <DEDENT> if (num >> bitwidth) != 0: <NEW_LINE> <INDENT> raise PyrtlInternalError( 'constant %d returned by infer_val_and_bitwidth somehow not fitting in %d bits' % (num, bitwidth)) <NEW_LINE> <DEDENT> name = name if name else _constIndexer.make_valid_string() + '_' + str(val) <NEW_LINE> super(Const, self).__init__(bitwidth=bitwidth, name=name, block=block) <NEW_LINE> self.val = num <NEW_LINE> <DEDENT> def __ilshift__(self, other): <NEW_LINE> <INDENT> raise PyrtlError( 'ConstWires, such as "%s", should never be assigned to with <<=' % str(self.name)) <NEW_LINE> <DEDENT> def __ior__(self, _): <NEW_LINE> <INDENT> raise PyrtlError( 'Connection using |= operator attempted on Const. ' 'ConstWires, such as "%s", cannot have values generated internally. ' "aka they cannot have other wires driving it" % str(self.name))
A WireVector representation of a constant value. Converts from bool, integer, or Verilog-style strings to a constant of the specified bitwidth. If the bitwidth is too short to represent the specified constant, then an error is raised. If a positive integer is specified, the bitwidth can be inferred from the constant. If a negative integer is provided in the simulation, it is converted to a two's complement representation of the specified bitwidth.
62598fc623849d37ff8513ba
class ErrorMonitor(BasicMonitor): <NEW_LINE> <INDENT> def __init__(self, mainEngine, eventEngine, parent=None): <NEW_LINE> <INDENT> super(ErrorMonitor, self).__init__(mainEngine, eventEngine, parent) <NEW_LINE> d = OrderedDict() <NEW_LINE> d['errorTime'] = {'chinese':u'错误时间', 'cellType':BasicCell} <NEW_LINE> d['errorID'] = {'chinese':u'错误代码', 'cellType':BasicCell} <NEW_LINE> d['errorMsg'] = {'chinese':u'错误信息', 'cellType':BasicCell} <NEW_LINE> d['gatewayName'] = {'chinese':u'接口', 'cellType':BasicCell} <NEW_LINE> self.setHeaderDict(d) <NEW_LINE> self.setEventType(EVENT_ERROR) <NEW_LINE> self.setFont(BASIC_FONT) <NEW_LINE> self.initTable() <NEW_LINE> self.registerEvent()
错误监控
62598fc6956e5f7376df5801
class RemarksInLatex: <NEW_LINE> <INDENT> def __init__(self, project_db): <NEW_LINE> <INDENT> self.project_db = project_db <NEW_LINE> self.remark_re = re.compile( ''.join([r"(?ms)^\\begin{(?P<type>remark)}", r"(\\label{(?P<label>.*?)})(?P<remark>.+?)", r"\\end{(?P=type)}"])) <NEW_LINE> self.owner_re = re.compile(r"\\owner{(?P<owner>.*?)}") <NEW_LINE> <DEDENT> def collect_remarks(self, abspath, contents): <NEW_LINE> <INDENT> if os.path.splitext(abspath)[1] == ".tex" and abspath.find("--obj") < 0: <NEW_LINE> <INDENT> if not "remarks" in self.project_db: <NEW_LINE> <INDENT> self.project_db["remarks"] = {} <NEW_LINE> remarks = self.project_db["remarks"] <NEW_LINE> remarks[abspath] = [] <NEW_LINE> <DEDENT> for remark in self.remark_re.finditer(contents): <NEW_LINE> <INDENT> rem = {"owner": "No"} <NEW_LINE> rem["text"] = self.owner_re.sub("", remark.group('remark')).replace("\r","") <NEW_LINE> rem["label"] = remark.group('label') <NEW_LINE> for own in self.owner_re.finditer(remark.group('remark')): <NEW_LINE> <INDENT> rem["owner"] = own.group("owner").upper() <NEW_LINE> <DEDENT> remarks[abspath].append(copy(rem))
Класс присоединяется к проектной БД, и при запуске обработки загружает туда заметки из заданного файла.
62598fc67cff6e4e811b5d2d