code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class StatMonitor(object): <NEW_LINE> <INDENT> def __init__(self, files, on_change=None, interval=0.5): <NEW_LINE> <INDENT> self._files = files <NEW_LINE> self._interval = interval <NEW_LINE> self._on_change = on_change <NEW_LINE> self._modify_times = defaultdict(int) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> modified = {} <NEW_LINE> for m in self._files: <NEW_LINE> <INDENT> mt = self._mtime(m) <NEW_LINE> if mt is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if self._modify_times[m] != mt: <NEW_LINE> <INDENT> modified[m] = mt <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if modified: <NEW_LINE> <INDENT> self.on_change(modified.keys()) <NEW_LINE> self._modify_times.update(modified) <NEW_LINE> <DEDENT> <DEDENT> time.sleep(self._interval) <NEW_LINE> <DEDENT> <DEDENT> def on_change(self, modified): <NEW_LINE> <INDENT> if self._on_change: <NEW_LINE> <INDENT> return self._on_change(modified) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def _mtime(cls, path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return os.stat(path).st_mtime <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return
File change monitor based on `stat` system call
6259904896565a6dacd2d959
class MetadataSolutionRelated(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'tables': {'required': True}, } <NEW_LINE> _attribute_map = { 'tables': {'key': 'tables', 'type': '[str]'}, 'functions': {'key': 'functions', 'type': '[str]'}, 'categories': {'key': 'categories', 'type': '[str]'}, 'queries': {'key': 'queries', 'type': '[str]'}, 'workspaces': {'key': 'workspaces', 'type': '[str]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(MetadataSolutionRelated, self).__init__(**kwargs) <NEW_LINE> self.tables = kwargs['tables'] <NEW_LINE> self.functions = kwargs.get('functions', None) <NEW_LINE> self.categories = kwargs.get('categories', None) <NEW_LINE> self.queries = kwargs.get('queries', None) <NEW_LINE> self.workspaces = kwargs.get('workspaces', None)
The related metadata items for the Log Analytics solution. All required parameters must be populated in order to send to Azure. :param tables: Required. The tables related to the Log Analytics solution. :type tables: list[str] :param functions: The functions related to the Log Analytics solution. :type functions: list[str] :param categories: The categories related to the Log Analytics solution. :type categories: list[str] :param queries: The saved queries related to the Log Analytics solution. :type queries: list[str] :param workspaces: The Workspaces referenced in the metadata request that are related to the Log Analytics solution. :type workspaces: list[str]
62599048287bf620b6272f88
class InfoPC(DebuggerSubcommand): <NEW_LINE> <INDENT> min_abbrev = 2 <NEW_LINE> max_args = 0 <NEW_LINE> need_stack = True <NEW_LINE> short_help = "Show Program Counter or Instruction Offset information" <NEW_LINE> def run(self, args): <NEW_LINE> <INDENT> mainfile = self.core.filename(None) <NEW_LINE> if self.core.is_running(): <NEW_LINE> <INDENT> curframe = self.proc.curframe <NEW_LINE> if curframe: <NEW_LINE> <INDENT> line_no = inspect.getlineno(curframe) <NEW_LINE> offset = curframe.f_lasti <NEW_LINE> self.msg("PC offset is %d." % offset) <NEW_LINE> offset = max(offset, 0) <NEW_LINE> code = curframe.f_code <NEW_LINE> co_code = code.co_code <NEW_LINE> disassemble_bytes( self.msg, self.msg_nocr, code = co_code, lasti = offset, cur_line = line_no, start_line = line_no - 1, end_line = line_no + 1, varnames=code.co_varnames, names=code.co_names, constants=code.co_consts, cells=code.co_cellvars, freevars=code.co_freevars, linestarts=dict(findlinestarts(code)), end_offset=offset + 10, ) <NEW_LINE> pass <NEW_LINE> <DEDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if mainfile: <NEW_LINE> <INDENT> part1 = "Python program '%s'" % mainfile <NEW_LINE> msg = "is not currently running. " <NEW_LINE> self.msg(wrapped_lines(part1, msg, self.settings["width"])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.msg("No Python program is currently running.") <NEW_LINE> pass <NEW_LINE> <DEDENT> self.msg(self.core.execution_status) <NEW_LINE> pass <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> pass
**info pc** List the current program counter or bytecode offset, and disassemble the instructions around that. See also: --------- `info line`, `info program`
625990488e71fb1e983bce64
class TestCustomer(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(self): <NEW_LINE> <INDENT> self.customer = Customer('Mike Mead', 'yourmomshouse', 'nashville', 'TN', 37075, '615-200-1919') <NEW_LINE> <DEDENT> def test_create_customer(self): <NEW_LINE> <INDENT> self.assertEqual(self.customer.name, 'Mike Mead') <NEW_LINE> self.assertEqual(self.customer.address, 'yourmomshouse') <NEW_LINE> self.assertEqual(self.customer.city, 'nashville') <NEW_LINE> self.assertEqual(self.customer.state, 'TN') <NEW_LINE> self.assertEqual(self.customer.zip_code, 37075) <NEW_LINE> self.assertEqual(self.customer.phone, '615-200-1919') <NEW_LINE> self.assertIsNotNone(self.customer.obj_id)
Set up and test a new customer
6259904821a7993f00c67309
class Char(Node): <NEW_LINE> <INDENT> def __init__(self, c, state): <NEW_LINE> <INDENT> Node.__init__(self) <NEW_LINE> self.c = c <NEW_LINE> self.font_output = state.font_output <NEW_LINE> assert isinstance(state.font, (str, int)) <NEW_LINE> self.font = state.font <NEW_LINE> self.font_class = state.font_class <NEW_LINE> self.fontsize = state.fontsize <NEW_LINE> self.dpi = state.dpi <NEW_LINE> self._update_metrics() <NEW_LINE> <DEDENT> def __internal_repr__(self): <NEW_LINE> <INDENT> return '`%s`' % self.c <NEW_LINE> <DEDENT> def _update_metrics(self): <NEW_LINE> <INDENT> metrics = self._metrics = self.font_output.get_metrics( self.font, self.font_class, self.c, self.fontsize, self.dpi) <NEW_LINE> if self.c == ' ': <NEW_LINE> <INDENT> self.width = metrics.advance <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.width = metrics.width <NEW_LINE> <DEDENT> self.height = metrics.iceberg <NEW_LINE> self.depth = -(metrics.iceberg - metrics.height) <NEW_LINE> <DEDENT> def is_slanted(self): <NEW_LINE> <INDENT> return self._metrics.slanted <NEW_LINE> <DEDENT> def get_kerning(self, next): <NEW_LINE> <INDENT> advance = self._metrics.advance - self.width <NEW_LINE> kern = 0. <NEW_LINE> if isinstance(next, Char): <NEW_LINE> <INDENT> kern = self.font_output.get_kern( self.font, self.font_class, self.c, self.fontsize, next.font, next.font_class, next.c, next.fontsize, self.dpi) <NEW_LINE> <DEDENT> return advance + kern <NEW_LINE> <DEDENT> def render(self, x, y): <NEW_LINE> <INDENT> self.font_output.render_glyph( x, y, self.font, self.font_class, self.c, self.fontsize, self.dpi) <NEW_LINE> <DEDENT> def shrink(self): <NEW_LINE> <INDENT> Node.shrink(self) <NEW_LINE> if self.size < NUM_SIZE_LEVELS: <NEW_LINE> <INDENT> self.fontsize *= SHRINK_FACTOR <NEW_LINE> self.width *= SHRINK_FACTOR <NEW_LINE> self.height *= SHRINK_FACTOR <NEW_LINE> self.depth *= SHRINK_FACTOR <NEW_LINE> <DEDENT> <DEDENT> def grow(self): <NEW_LINE> <INDENT> Node.grow(self) <NEW_LINE> self.fontsize *= GROW_FACTOR <NEW_LINE> self.width *= GROW_FACTOR <NEW_LINE> self.height *= GROW_FACTOR <NEW_LINE> self.depth *= GROW_FACTOR
Represents a single character. Unlike TeX, the font information and metrics are stored with each :class:`Char` to make it easier to lookup the font metrics when needed. Note that TeX boxes have a width, height, and depth, unlike Type1 and Truetype which use a full bounding box and an advance in the x-direction. The metrics must be converted to the TeX way, and the advance (if different from width) must be converted into a :class:`Kern` node when the :class:`Char` is added to its parent :class:`Hlist`.
62599048d4950a0f3b111812
class PiglitCLTest(PiglitBaseTest): <NEW_LINE> <INDENT> def __init__(self, command, run_concurrent=CL_CONCURRENT, **kwargs): <NEW_LINE> <INDENT> super(PiglitCLTest, self).__init__(command, run_concurrent, **kwargs)
OpenCL specific Test class. Set concurrency based on CL requirements.
6259904815baa72349463331
class LinkedList(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._begin = None <NEW_LINE> <DEDENT> def insert(self, x): <NEW_LINE> <INDENT> self._begin = [x, self._begin] <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> assert self._begin is not None, "List is empty" <NEW_LINE> x = self._begin[0] <NEW_LINE> self._begin = self._begin[1] <NEW_LINE> return x <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> if self._begin == None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Класс описывающи связный список. >>> A = LinkedList() >>> print(A.is_empty()) True >>> A.insert(5) >>> print(A.is_empty()) False >>> A.insert(10) >>> print(A.pop()) 10 >>> print(A.is_empty()) False >>> print(A.pop()) 5 >>> print(A.is_empty()) True
6259904826068e7796d4dce4
class FineTuningLR(LearningRateScheduler, LRVisualizer): <NEW_LINE> <INDENT> def __init__(self, lr_start=0.00001, lr_max=0.00005, lr_min=0.00001, lr_rampup_epochs=5, lr_sustain_epochs=0, lr_exp_decay=.8, verbose=0): <NEW_LINE> <INDENT> self.lr_start = lr_start <NEW_LINE> self.lr_max = lr_max <NEW_LINE> self.lr_min = lr_min <NEW_LINE> self.lr_rampup_epochs = lr_rampup_epochs <NEW_LINE> self.lr_sustain_epochs = lr_sustain_epochs <NEW_LINE> self.lr_exp_decay = lr_exp_decay <NEW_LINE> super().__init__(self.schedule, verbose) <NEW_LINE> <DEDENT> def schedule(self, epoch): <NEW_LINE> <INDENT> if epoch < self.lr_rampup_epochs: <NEW_LINE> <INDENT> lr = (self.lr_max - self.lr_start) / self.lr_rampup_epochs * epoch + self.lr_start <NEW_LINE> <DEDENT> elif epoch < self.lr_rampup_epochs + self.lr_sustain_epochs: <NEW_LINE> <INDENT> lr = self.lr_max <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lr = (self.lr_max - self.lr_min) * self.lr_exp_decay ** (epoch - self.lr_rampup_epochs - self.lr_sustain_epochs) + self.lr_min <NEW_LINE> <DEDENT> return lr <NEW_LINE> <DEDENT> def _lr_by_batchnum(self, steps_per_epoch, epochs): <NEW_LINE> <INDENT> ret = np.zeros(shape=(steps_per_epoch * epochs)) <NEW_LINE> for epoch in range(epochs): <NEW_LINE> <INDENT> ret[epoch * steps_per_epoch: (epoch + 1) * steps_per_epoch] = self.schedule(epoch) <NEW_LINE> <DEDENT> return ret
Starts small (to not ruin delicate pre-trained weights), increases, then decays exponentially. # Arguments: lr_start: the initial learning rate lr_max: the peak learning rate lr_min: the lowest learning rate at the end lr_rampup_epochs: number of epochs before peak lr_sustain_epochs: number of epochs at the peak lr_exp_decay: exponential lr decay parameter verbose: int. 0: quiet, 1: update messages.
6259904824f1403a9268629d
class PomoSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> owner = serializers.ReadOnlyField(source='owner.username') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Pomo <NEW_LINE> fields = ('id', 'name', 'observation', 'start', 'end', 'owner')
Serializer to map the Model instance into JSON format.
62599048d7e4931a7ef3d417
class dummyfile_document(document): <NEW_LINE> <INDENT> contexts = [] <NEW_LINE> lines = []
A totally fake document.
6259904829b78933be26aa93
class PseudoScreen: <NEW_LINE> <INDENT> def __init__(self, x, y, width, height): <NEW_LINE> <INDENT> self.x, self.y, self.width, self.height = x, y, width, height
This may be a Xinerama screen or a RandR CRTC, both of which are rectagular sections of an actual Screen.
62599048435de62698e9d1a7
class SpeedTestResult(object): <NEW_LINE> <INDENT> def __init__(self, download, startTime, ping=None, upload=None, endTime=None): <NEW_LINE> <INDENT> super(SpeedTestResult, self).__init__() <NEW_LINE> self.download = download <NEW_LINE> self.upload = upload <NEW_LINE> self.ping = ping <NEW_LINE> self.startTime = startTime <NEW_LINE> self.endTime = endTime <NEW_LINE> if self.endTime is None: <NEW_LINE> <INDENT> self.endTime = datetime.datetime.now() <NEW_LINE> <DEDENT> self.duration = round((self.endTime - self.startTime).total_seconds(), 2) <NEW_LINE> <DEDENT> def description(self): <NEW_LINE> <INDENT> durationString = "{}s".format(self.duration) <NEW_LINE> downloadSpeedString = "{} Kbps".format(self.download) <NEW_LINE> uploadSpeedString = "{} Kbps".format(self.upload) <NEW_LINE> return "\t".join((self.startTime.isoformat(), downloadSpeedString, uploadSpeedString, durationString)) <NEW_LINE> <DEDENT> def toString(self): <NEW_LINE> <INDENT> return json.dumps(self) <NEW_LINE> <DEDENT> def toJSON(self): <NEW_LINE> <INDENT> return { "start": self.startTime.isoformat(), "end": self.endTime.isoformat(), "duration": self.duration, "download": self.download, "upload": self.upload, "ping": self.ping } <NEW_LINE> <DEDENT> def fromJSON(json): <NEW_LINE> <INDENT> startTime = dateutil.parser.parse(json["start"]) <NEW_LINE> endTime = dateutil.parser.parse(json["end"]) <NEW_LINE> return SpeedTestResult(json["download"], startTime, ping=json["ping"], upload=json["upload"], endTime=endTime)
Represents the results of a test performed by a SpeedTester.
62599048d10714528d69f05e
class RandomCrop(): <NEW_LINE> <INDENT> def __init__(self, out_size): <NEW_LINE> <INDENT> assert isinstance(out_size, (int, tuple)) <NEW_LINE> if isinstance(out_size, int): <NEW_LINE> <INDENT> self.out_size = (out_size, out_size) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert len(out_size) == 2 <NEW_LINE> self.out_size = out_size <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> image, landmark = sample['image'], sample['landmarks'] <NEW_LINE> h, w = image.shape[:2] <NEW_LINE> new_h, new_w = self.out_size <NEW_LINE> top = np.random.randint(0, h - new_h) <NEW_LINE> left = np.random.randint(0, w - new_w) <NEW_LINE> image = image[top:top + new_h, left:left + new_w] <NEW_LINE> landmark = landmark - [left, top] <NEW_LINE> return {'image': image, 'landmarks': landmark}
随机裁剪制定大小的图片
62599048287bf620b6272f8a
class Redis(MakefilePackage): <NEW_LINE> <INDENT> homepage = "https://redis.io" <NEW_LINE> url = "http://download.redis.io/releases/redis-5.0.3.tar.gz" <NEW_LINE> version('5.0.3', sha256='e290b4ddf817b26254a74d5d564095b11f9cd20d8f165459efa53eb63cd93e02') <NEW_LINE> version('5.0.2', sha256='937dde6164001c083e87316aa20dad2f8542af089dfcb1cbb64f9c8300cd00ed') <NEW_LINE> version('5.0.1', sha256='82a67c0eec97f9ad379384c30ec391b269e17a3e4596393c808f02db7595abcb') <NEW_LINE> version('5.0.0', sha256='70c98b2d0640b2b73c9d8adb4df63bcb62bad34b788fe46d1634b6cf87dc99a4') <NEW_LINE> version('4.0.13', sha256='17d955227966dcd68590be6139e5fe7f2d19fc4fb7334248a904ea9cdd30c1d4') <NEW_LINE> version('4.0.12', sha256='6447259d2eed426a949c9c13f8fdb2d91fb66d9dc915dd50db13b87f46d93162') <NEW_LINE> version('4.0.11', sha256='fc53e73ae7586bcdacb4b63875d1ff04f68c5474c1ddeda78f00e5ae2eed1bbb') <NEW_LINE> @property <NEW_LINE> def install_targets(self): <NEW_LINE> <INDENT> return [ 'PREFIX={0}'.format(self.spec.prefix), 'install' ] <NEW_LINE> <DEDENT> @run_after('install') <NEW_LINE> def install_conf(self): <NEW_LINE> <INDENT> mkdirp(self.prefix.conf) <NEW_LINE> install('redis.conf', self.prefix.conf)
Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster
6259904807f4c71912bb07d4
class Gift(Advert, Location): <NEW_LINE> <INDENT> gift_type = models.ForeignKey(GiftType, on_delete=models.CASCADE, verbose_name=_('gift type')) <NEW_LINE> image = models.ImageField(upload_to=user_directory_path, null=True, blank=True) <NEW_LINE> favourites = models.ManyToManyField(User, related_name='favourite_gifts', default=None, blank=True) <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('gifts:detail', args=[self.id]) <NEW_LINE> <DEDENT> def get_api_fav_url(self): <NEW_LINE> <INDENT> return reverse('favourite_add', kwargs={'name': 'Gift', 'record_id': self.id}) <NEW_LINE> <DEDENT> def delete(self, *args, **kwargs): <NEW_LINE> <INDENT> self.image.delete() <NEW_LINE> super().delete(*args, **kwargs)
handmade free classes free ticket volunteering pet items
62599048ec188e330fdf9c3f
class TestGridPointLinkToParticles(amusetest.TestCase): <NEW_LINE> <INDENT> def test1(self): <NEW_LINE> <INDENT> grid = datamodel.Grid(2,3) <NEW_LINE> grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 <NEW_LINE> particles = datamodel.Particles(3) <NEW_LINE> particles.mass = [2,3,4] | units.kg <NEW_LINE> grid[0][0].particles = particles <NEW_LINE> self.assertAlmostRelativeEquals(grid[0][0].particles[1].mass, 3 | units.kg) <NEW_LINE> self.assertEqual(grid[0][0].particles[1], particles[1]) <NEW_LINE> self.assertEqual(grid[1][1].particles, None) <NEW_LINE> <DEDENT> def test2(self): <NEW_LINE> <INDENT> grid = datamodel.Grid(2,3) <NEW_LINE> grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 <NEW_LINE> particles = datamodel.Particles(3) <NEW_LINE> particles.mass = [2,3,4] | units.kg <NEW_LINE> grid[0][0].particles = particles <NEW_LINE> grid_copy = grid.copy() <NEW_LINE> self.assertAlmostRelativeEquals(grid_copy[0][0].particles[1].mass, 3 | units.kg) <NEW_LINE> grid[0][0].particles[1].mass = 10 | units.kg <NEW_LINE> <DEDENT> def test3(self): <NEW_LINE> <INDENT> grid = datamodel.Grid(2,3) <NEW_LINE> grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 <NEW_LINE> particles = datamodel.Particles(3) <NEW_LINE> particles.mass = [2,3,4] | units.kg <NEW_LINE> grid_copy = grid.copy() <NEW_LINE> grid[0][0].particles = particles <NEW_LINE> channel = grid.new_channel_to(grid_copy) <NEW_LINE> channel.copy() <NEW_LINE> self.assertAlmostRelativeEquals(grid_copy[0][0].particles[1].mass, 3 | units.kg) <NEW_LINE> grid[0][0].particles[1].mass = 10 | units.kg <NEW_LINE> self.assertAlmostRelativeEquals(grid_copy[0][0].particles[1].mass, 10 | units.kg)
Tests One-to-Many relation between gridpoints and particles
625990488a349b6b436875ef
class ConfigServiceV2Servicer(object): <NEW_LINE> <INDENT> def ListSinks(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def GetSink(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def CreateSink(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def UpdateSink(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def DeleteSink(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Service for configuring sinks used to export log entries outside of Stackdriver Logging.
62599048e76e3b2f99fd9dae
class DelayedSymval(DelayedSymbol): <NEW_LINE> <INDENT> def callback(self, value: gdb.Symbol) -> None: <NEW_LINE> <INDENT> symval = value.value() <NEW_LINE> if symval.type.code == gdb.TYPE_CODE_FUNC: <NEW_LINE> <INDENT> symval = symval.address <NEW_LINE> <DEDENT> self.value = symval <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return "{} attached with {}".format(self.__class__, str(self.cb))
A :obj:`DelayedSymbol` that returns the :obj:`gdb.Value` associated with the symbol. Args: name: The name of the symbol.
62599048d6c5a102081e34bf
class InspectRaw(LoggingMixin, Command): <NEW_LINE> <INDENT> def __init__(self, app, app_args): <NEW_LINE> <INDENT> super().__init__(app, app_args) <NEW_LINE> <DEDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super().get_parser(prog_name) <NEW_LINE> parser.add_argument("--basedir", type=Path, required=True, help="The data set base directory") <NEW_LINE> parser.add_argument("--parser", type=str, default="audeep.backend.parsers.meta.MetaParser", help="Parser for the data set file structure. Defaults to " "audeep.backend.parsers.meta.MetaParser, which supports several common file " "structures.") <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> module_name, class_name = parsed_args.parser.rsplit(".", 1) <NEW_LINE> parser_class = getattr(importlib.import_module(module_name), class_name) <NEW_LINE> if not issubclass(parser_class, Parser): <NEW_LINE> <INDENT> raise ValueError("specified parser does not inherit audeep.backend.parsers.Parser") <NEW_LINE> <DEDENT> parser = parser_class(parsed_args.basedir) <NEW_LINE> if not parser.can_parse(): <NEW_LINE> <INDENT> raise ValueError("specified parser is unable to parse data set at {}".format(parsed_args.basedir)) <NEW_LINE> <DEDENT> lengths = [] <NEW_LINE> sample_rates = [] <NEW_LINE> channels = [] <NEW_LINE> non_seekable_files = False <NEW_LINE> instance_metadata = parser.parse() <NEW_LINE> self.log.info("reading audio file information") <NEW_LINE> for index, metadata in enumerate(instance_metadata): <NEW_LINE> <INDENT> self.log.debug("processing %%s (%%%dd/%%d)" % int(math.ceil(math.log10(len(instance_metadata)))), metadata.path, index + 1, len(instance_metadata)) <NEW_LINE> with SoundFile(str(metadata.path)) as sf: <NEW_LINE> <INDENT> sample_rates.append(sf.samplerate) <NEW_LINE> channels.append(sf.channels) <NEW_LINE> if sf.seekable(): <NEW_LINE> <INDENT> lengths.append(sf.seek(0, SEEK_END) / sf.samplerate) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> non_seekable_files = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if non_seekable_files: <NEW_LINE> <INDENT> self.log.warning("could not determine the length of some files - information may be inaccurate") <NEW_LINE> <DEDENT> information = [ ("number of audio files", parser.num_instances), ("number of labels", len(parser.label_map) if parser.label_map else "0"), ("cross validation folds", parser.num_folds), ("minimum sample length", "%.2f s" % np.min(lengths)), ("maximum sample length", "%.2f s" % np.max(lengths)), ] <NEW_LINE> if len(np.unique(sample_rates)) > 1: <NEW_LINE> <INDENT> information.append(("sample rates", "%d Hz - %d Hz" % (np.min(sample_rates), np.max(sample_rates)))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> information.append(("sample rate", "%d Hz" % sample_rates[0])) <NEW_LINE> <DEDENT> if len(np.unique(channels)) > 1: <NEW_LINE> <INDENT> information.append(("channels", "%d - %d" % (np.min(channels), np.max(channels)))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> information.append(("channels", channels[0])) <NEW_LINE> <DEDENT> TableFormatter("lr").print(data=information, header="data set information")
Display information about a data set that has not yet been imported
62599048379a373c97d9a3cd
class HeadlessTarget(Target): <NEW_LINE> <INDENT> clientURL = None <NEW_LINE> def show(self, variable=None): <NEW_LINE> <INDENT> super(HeadlessTarget, self).show(variable) <NEW_LINE> if not(self.server.alive()): <NEW_LINE> <INDENT> self.clientURL = 'http://localhost:' + str(self.server.get_port()) + "/index.html" <NEW_LINE> print('Canvas is accessible via web browser at the URL: %s' % self.clientURL)
An interactive visualization canvas.
625990481f5feb6acb163f98
class ConfFake(object): <NEW_LINE> <INDENT> def __init__(self, params): <NEW_LINE> <INDENT> self.__dict__ = params <NEW_LINE> for k, v in self.__dict__.items(): <NEW_LINE> <INDENT> if isinstance(v, unicode): <NEW_LINE> <INDENT> self.__dict__[k] = v.encode('utf-8') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(self.__dict__)
minimal fake config object to replace oslo with controlled params
6259904882261d6c52730897
class TestIpamsvcUtilization(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testIpamsvcUtilization(self): <NEW_LINE> <INDENT> pass
IpamsvcUtilization unit test stubs
6259904829b78933be26aa94
@EnableDebugWindow <NEW_LINE> class SearchAddress(Transform): <NEW_LINE> <INDENT> input_type = Location <NEW_LINE> def do_transform(self, request, response, config): <NEW_LINE> <INDENT> location = request.entity <NEW_LINE> fields = location.fields <NEW_LINE> if fields.get("streetaddress"): <NEW_LINE> <INDENT> name = fields.get("streetaddress").value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = fields.get("location.name").value <NEW_LINE> <DEDENT> if fields.get("location.areacode"): <NEW_LINE> <INDENT> citystatezip = fields.get("location.areacode").value.split("-")[0] <NEW_LINE> <DEDENT> elif fields.get("city") and fields.get("location.area"): <NEW_LINE> <INDENT> citystatezip = fields.get("city").value + ", " + fields.get("location.area").value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> citystatezip = name.split(" ")[-1].split("-")[0] <NEW_LINE> <DEDENT> name = name.replace(" ", "%20").replace("\n", "%20") <NEW_LINE> path = "/results?streetaddress=%s&citystatezip=%s" % ( name, citystatezip) <NEW_LINE> base_url = config['TruePeopleSearch.local.base_url'] <NEW_LINE> soup = scrape(base_url + path) <NEW_LINE> if soup: <NEW_LINE> <INDENT> cards = soup.find_all(class_="card-summary") <NEW_LINE> for card in cards: <NEW_LINE> <INDENT> card_name = card.find(class_="h4").get_text().strip() <NEW_LINE> card_content = card.find_all(class_="content-value") <NEW_LINE> age = card_content[0].get_text() <NEW_LINE> if "Unknown" in age: <NEW_LINE> <INDENT> age = 0 <NEW_LINE> <DEDENT> elif "(age " in age: <NEW_LINE> <INDENT> age = int(age.split("(age ")[1].replace(")", "")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> age = int(age) <NEW_LINE> <DEDENT> location = card_content[1].get_text() <NEW_LINE> if ", " in location: <NEW_LINE> <INDENT> location_list = location.split(", ") <NEW_LINE> city = location_list[0] <NEW_LINE> state = location_list[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> city = location <NEW_LINE> state = "" <NEW_LINE> <DEDENT> response += TruePerson(card_name, properties_url=base_url + card['data-detail-link'], properties_city=city, properties_state=state, properties_age=age) <NEW_LINE> <DEDENT> <DEDENT> return response <NEW_LINE> <DEDENT> def on_terminate(self): <NEW_LINE> <INDENT> pass
Gathers people from TruePeopleSearch
62599048d53ae8145f919803
class Dependency(object): <NEW_LINE> <INDENT> def __init__(self, name, libs, check_headers): <NEW_LINE> <INDENT> self.build = True <NEW_LINE> self.name = name <NEW_LINE> self.libs = libs <NEW_LINE> self.check_headers = check_headers <NEW_LINE> for x in VALID_FIELDS: <NEW_LINE> <INDENT> self.__setattr__(x, None)
A dependency for the OXSX build, contains build locations, flags etc Effectively a python dict where the possible attributes are limited to the above
6259904815baa72349463334
@register_type <NEW_LINE> class Template(object): <NEW_LINE> <INDENT> type_id = 3 <NEW_LINE> __slots__ = ["parts", "id"] <NEW_LINE> def __init__(self, parts): <NEW_LINE> <INDENT> if type(parts) is str: <NEW_LINE> <INDENT> parts = parts.split("{}") <NEW_LINE> <DEDENT> self.parts = parts <NEW_LINE> self.id = intern.intern_all(self.type_id, parts) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{}".join(self.parts) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.id == other.id <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return self.id <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> return CompoundTerm(self, [to_term(arg, quote=False) for arg in args]) <NEW_LINE> <DEDENT> def num_args(self): <NEW_LINE> <INDENT> return len(self.parts)-1 <NEW_LINE> <DEDENT> def line_slots(self): <NEW_LINE> <INDENT> return self.num_args() <NEW_LINE> <DEDENT> def line_instantiate(self, *args): <NEW_LINE> <INDENT> return self(*args) <NEW_LINE> <DEDENT> def show_with(self, args): <NEW_LINE> <INDENT> return str(self).format(*args) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_id(cls, id): <NEW_LINE> <INDENT> return Template(intern.get_all(id, [""]))
A representation of the term template with list of parts [parts] and unique idenfitier [id].
62599048cad5886f8bdc5a50
class ICustomerSubscriptionDeletedEvent(BaseWebhookEvent): <NEW_LINE> <INDENT> pass
Occurs whenever a customer ends their subscription.
62599048d99f1b3c44d06a3e
class Ilastik05ImportDeserializer(AppletSerializer): <NEW_LINE> <INDENT> def __init__(self, topLevelOperator): <NEW_LINE> <INDENT> super(Ilastik05ImportDeserializer, self).__init__("") <NEW_LINE> self.mainOperator = topLevelOperator <NEW_LINE> <DEDENT> def serializeToHdf5(self, hdf5Group, projectFilePath): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def deserializeFromHdf5(self, hdf5File, projectFilePath, headless=False): <NEW_LINE> <INDENT> ilastikVersion = hdf5File["ilastikVersion"][()] <NEW_LINE> if ilastikVersion == 0.5: <NEW_LINE> <INDENT> numImages = len(hdf5File["DataSets"]) <NEW_LINE> self.mainOperator.LabelInputs.resize(numImages) <NEW_LINE> for index, (datasetName, datasetGroup) in enumerate(sorted(hdf5File["DataSets"].items())): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dataset = datasetGroup["labels/data"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> slicing = [slice(0, s) for s in dataset.shape] <NEW_LINE> self.mainOperator.LabelInputs[index][slicing] = dataset[...] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def importClassifier(self, hdf5File): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def isDirty(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def unload(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _serializeToHdf5(self, topGroup, hdf5File, projectFilePath): <NEW_LINE> <INDENT> assert False <NEW_LINE> <DEDENT> def _deserializeFromHdf5(self, topGroup, groupVersion, hdf5File, projectFilePath, headless=False): <NEW_LINE> <INDENT> assert False
Special (de)serializer for importing ilastik 0.5 projects. For now, this class is import-only. Only the deserialize function is implemented. If the project is not an ilastik0.5 project, this serializer does nothing.
625990488e71fb1e983bce68
class ExactlyOnceResultsChecker: <NEW_LINE> <INDENT> def __init__(self, topology_name, expected_results_handler, actual_results_handler): <NEW_LINE> <INDENT> self.topology_name = topology_name <NEW_LINE> self.expected_results_handler = expected_results_handler <NEW_LINE> self.actual_results_handler = actual_results_handler <NEW_LINE> <DEDENT> def check_results(self): <NEW_LINE> <INDENT> actual_result = self.actual_results_handler.fetch_results() <NEW_LINE> expected_result = self.expected_results_handler.fetch_results() <NEW_LINE> decoder = json.JSONDecoder(strict=False) <NEW_LINE> actual_results = sorted(decoder.decode(actual_result)) <NEW_LINE> expected_results = sorted(decoder.decode(expected_result)) <NEW_LINE> return self._compare(expected_results, actual_results) <NEW_LINE> <DEDENT> def _compare(self, expected_results, actual_results): <NEW_LINE> <INDENT> if actual_results == expected_results: <NEW_LINE> <INDENT> return status.TestSuccess( "Topology %s result matches expected result: %s expected tuples found exactly once" % (len(expected_results), self.topology_name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> failure = status.TestFailure("Actual result did not match expected result") <NEW_LINE> logging.info("Actual result ---------- \n" + str([str(x) for x in actual_results])) <NEW_LINE> logging.info("Expected result ---------- \n" + str([str(x) for x in expected_results])) <NEW_LINE> raise failure
Compares what results we found against what was expected. Verifies and exact match
625990487cff6e4e811b6ddd
@registry.register_problem <NEW_LINE> class TranslateEncsWmt32k(TranslateProblem): <NEW_LINE> <INDENT> @property <NEW_LINE> def targeted_vocab_size(self): <NEW_LINE> <INDENT> return 2 ** 15 <NEW_LINE> <DEDENT> @property <NEW_LINE> def vocab_name(self): <NEW_LINE> <INDENT> return "vocab.encs" <NEW_LINE> <DEDENT> def generator(self, data_dir, tmp_dir, train): <NEW_LINE> <INDENT> datasets = _ENCS_TRAIN_DATASETS if train else _ENCS_TEST_DATASETS <NEW_LINE> source_datasets = [[item[0], [item[1][0]]] for item in datasets] <NEW_LINE> target_datasets = [[item[0], [item[1][1]]] for item in datasets] <NEW_LINE> symbolizer_vocab = generator_utils.get_or_generate_vocab( data_dir, tmp_dir, self.vocab_file, self.targeted_vocab_size, source_datasets + target_datasets) <NEW_LINE> tag = "train" if train else "dev" <NEW_LINE> data_path = _compile_data(tmp_dir, datasets, "wmt_encs_tok_%s" % tag) <NEW_LINE> return token_generator(data_path + ".lang1", data_path + ".lang2", symbolizer_vocab, EOS) <NEW_LINE> <DEDENT> @property <NEW_LINE> def input_space_id(self): <NEW_LINE> <INDENT> return problem.SpaceID.EN_TOK <NEW_LINE> <DEDENT> @property <NEW_LINE> def target_space_id(self): <NEW_LINE> <INDENT> return problem.SpaceID.CS_TOK
Problem spec for WMT English-Czech translation.
62599048d4950a0f3b111814
class AbstractFunctor(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def __or__(self, func: Callable) -> "AbstractFunctor": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @enrichFunction <NEW_LINE> def fmap(self, func: Callable) -> "AbstractFunctor": <NEW_LINE> <INDENT> return self.__or__(func)
An abstract class which represents a Functor conception.
625990488a43f66fc4bf3539
class ExplorationStatisticsHandler(EditorHandler): <NEW_LINE> <INDENT> @require_editor <NEW_LINE> def get(self, exploration_id): <NEW_LINE> <INDENT> self.render_json({ 'num_visits': stats_services.get_exploration_visit_count( exploration_id), 'num_completions': stats_services.get_exploration_completed_count( exploration_id), 'state_stats': stats_services.get_state_stats_for_exploration( exploration_id), 'imp': stats_services.get_top_improvable_states( [exploration_id], 10), })
Returns statistics for an exploration.
62599048baa26c4b54d5064e
class DelimitedTextConfiguration(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'column_separator': {'key': 'ColumnSeparator', 'type': 'str', 'xml': {'name': 'ColumnSeparator'}}, 'field_quote': {'key': 'FieldQuote', 'type': 'str', 'xml': {'name': 'FieldQuote'}}, 'record_separator': {'key': 'RecordSeparator', 'type': 'str', 'xml': {'name': 'RecordSeparator'}}, 'escape_char': {'key': 'EscapeChar', 'type': 'str', 'xml': {'name': 'EscapeChar'}}, 'headers_present': {'key': 'HeadersPresent', 'type': 'bool', 'xml': {'name': 'HasHeaders'}}, } <NEW_LINE> _xml_map = { 'name': 'DelimitedTextConfiguration' } <NEW_LINE> def __init__( self, *, column_separator: Optional[str] = None, field_quote: Optional[str] = None, record_separator: Optional[str] = None, escape_char: Optional[str] = None, headers_present: Optional[bool] = None, **kwargs ): <NEW_LINE> <INDENT> super(DelimitedTextConfiguration, self).__init__(**kwargs) <NEW_LINE> self.column_separator = column_separator <NEW_LINE> self.field_quote = field_quote <NEW_LINE> self.record_separator = record_separator <NEW_LINE> self.escape_char = escape_char <NEW_LINE> self.headers_present = headers_present
Groups the settings used for interpreting the blob data if the blob is delimited text formatted. :param column_separator: The string used to separate columns. :type column_separator: str :param field_quote: The string used to quote a specific field. :type field_quote: str :param record_separator: The string used to separate records. :type record_separator: str :param escape_char: The string used as an escape character. :type escape_char: str :param headers_present: Represents whether the data has headers. :type headers_present: bool
62599048462c4b4f79dbcda4
class Category(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=200, help_text='Enter a book category (e.g. Best seller)') <NEW_LINE> book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f'{self.book.book_id}, {self.book.title},{self.name}'
Model representing a book category.
62599048596a897236128f81
class Takeoff(BaseTask): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> cube_size = 300.0 <NEW_LINE> self.observation_space = spaces.Box( np.array([- cube_size / 2, - cube_size / 2, 0.0, -1.0, -1.0, -1.0, -1.0]), np.array([ cube_size / 2, cube_size / 2, cube_size, 1.0, 1.0, 1.0, 1.0])) <NEW_LINE> print("Takeoff(): observation_space = {}".format(self.observation_space)) <NEW_LINE> max_force = 25.0 <NEW_LINE> max_torque = 25.0 <NEW_LINE> self.action_space = spaces.Box( np.array([-max_force, -max_force, -max_force, -max_torque, -max_torque, -max_torque]), np.array([ max_force, max_force, max_force, max_torque, max_torque, max_torque])) <NEW_LINE> print("Takeoff(): action_space = {}".format(self.action_space)) <NEW_LINE> self.max_duration = 10.0 <NEW_LINE> self.target_z = 10.0 <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> return Pose( position=Point(0.0, 0.0, np.random.normal(0.5, 0.1)), orientation=Quaternion(0.0, 0.0, 0.0, 0.0), ), Twist( linear=Vector3(0.0, 0.0, 0.0), angular=Vector3(0.0, 0.0, 0.0) ) <NEW_LINE> <DEDENT> def update(self, timestamp, pose, angular_velocity, linear_acceleration): <NEW_LINE> <INDENT> state = np.array([ pose.position.x, pose.position.y, pose.position.z, pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w]) <NEW_LINE> done = False <NEW_LINE> reward = -min(abs(self.target_z - pose.position.z), 20.0) <NEW_LINE> if pose.position.z >= self.target_z: <NEW_LINE> <INDENT> reward += 10.0 <NEW_LINE> done = True <NEW_LINE> <DEDENT> elif timestamp > self.max_duration: <NEW_LINE> <INDENT> reward -= 10.0 <NEW_LINE> done = True <NEW_LINE> <DEDENT> action = self.agent.step(state, reward, done) <NEW_LINE> if action is not None: <NEW_LINE> <INDENT> action = np.clip(action.flatten(), self.action_space.low, self.action_space.high) <NEW_LINE> return Wrench( force=Vector3(action[0], action[1], action[2]), torque=Vector3(action[3], action[4], action[5]) ), done <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Wrench(), done
Simple task where the goal is to lift off the ground and reach a target height.
62599048097d151d1a2c2411
class SimplePandasDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, pd, transform=None): <NEW_LINE> <INDENT> self.pd_frame = pd.copy() <NEW_LINE> self.transform = transform <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.pd_frame) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> X = self.pd_frame.iloc[idx, 0] <NEW_LINE> labels = np.array(self.pd_frame.iloc[idx, 1:].values).astype('int64') <NEW_LINE> sample = {'X': X, 'labels': labels} <NEW_LINE> if self.transform: <NEW_LINE> <INDENT> sample = self.transform(sample) <NEW_LINE> <DEDENT> return sample
Pandas dataset.
625990488e05c05ec3f6f82d
class ResultSet(list): <NEW_LINE> <INDENT> pass
A list like object that holds results from a Musixmatch API query.
62599048d53ae8145f919805
class ItemList(list): <NEW_LINE> <INDENT> def __init__(self, key): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> if isinstance(index, int): <NEW_LINE> <INDENT> return super(ItemList, self).__getitem__(index) <NEW_LINE> <DEDENT> for item in self: <NEW_LINE> <INDENT> if getattr(item, self.key) == index: <NEW_LINE> <INDENT> return item <NEW_LINE> <DEDENT> <DEDENT> raise KeyError("%s not in list" % index) <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.__getitem__(key) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return default
List with keys Raises: KeyError is item is not in list Example: >>> Obj = type("Object", (object,), {}) >>> obj = Obj() >>> obj.name = "Test" >>> l = ItemList(key="name") >>> l.append(obj) >>> l[0] == obj True >>> l["Test"] == obj True >>> try: ... l["NotInList"] ... except KeyError: ... print(True) True
62599048a8ecb033258725b7
class GameUnit: <NEW_LINE> <INDENT> def __init__(self, unitinfo, sprite, team, position): <NEW_LINE> <INDENT> self.unitinfo = unitinfo <NEW_LINE> self.name = unitinfo["name"] <NEW_LINE> self.maxHealth = unitinfo["stats"][0] <NEW_LINE> self.currentHealth = self.maxHealth <NEW_LINE> self.attack = unitinfo["stats"][1] <NEW_LINE> self.speed = unitinfo["stats"][2] <NEW_LINE> self.currentSpeed = self.speed <NEW_LINE> self.attacksPerTurn = unitinfo["stats"][3] <NEW_LINE> self.availableAttacks = self.attacksPerTurn <NEW_LINE> self.range = unitinfo["stats"][4] <NEW_LINE> self.cost = unitinfo["stats"][5] <NEW_LINE> self.unittype = unitinfo["type"] <NEW_LINE> self.sprite = sprite <NEW_LINE> self.spriteRect = sprite.get_rect() <NEW_LINE> self.team = team <NEW_LINE> self.position = position <NEW_LINE> self.requiredBuilding = None <NEW_LINE> <DEDENT> def targetAction(self, targetunit): <NEW_LINE> <INDENT> if targetunit.team.number != self.team.number and self.availableAttacks > 0: <NEW_LINE> <INDENT> targetunit.takeDamage(self.attack) <NEW_LINE> self.availableAttacks -= 1 <NEW_LINE> <DEDENT> <DEDENT> def onCreation(self): <NEW_LINE> <INDENT> self.currentSpeed = 0 <NEW_LINE> self.availableAttacks = 0 <NEW_LINE> <DEDENT> def onTurnStart(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def onTurnEnd(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def onDeath(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> """cool stuff""" <NEW_LINE> def setHealth(self, health): <NEW_LINE> <INDENT> self.currentHealth = health <NEW_LINE> <DEDENT> def healUnit(self, amount): <NEW_LINE> <INDENT> self.currentHealth += amount <NEW_LINE> if self.currentHealth > self.maxHealth: <NEW_LINE> <INDENT> self.currentHealth = self.maxHealth <NEW_LINE> <DEDENT> <DEDENT> def takeDamage(self, damage): <NEW_LINE> <INDENT> self.currentHealth -= damage <NEW_LINE> <DEDENT> def resetSpeed(self): <NEW_LINE> <INDENT> self.currentSpeed = self.speed <NEW_LINE> <DEDENT> def resetAttack(self): <NEW_LINE> <INDENT> self.availableAttacks = self.attacksPerTurn <NEW_LINE> <DEDENT> """display stuff""" <NEW_LINE> def displayUnit(self, tileRect): <NEW_LINE> <INDENT> self.spriteRect.center = tileRect.center <NEW_LINE> highlightSurface = pygame.Surface((self.spriteRect.width, self.spriteRect.height)) <NEW_LINE> highlightSurface = highlightSurface.convert_alpha(Window.SURFACE) <NEW_LINE> highlightSurface.fill(Colors.teamcolors[self.team.color]) <NEW_LINE> Window.SURFACE.blit(highlightSurface, self.spriteRect.topleft) <NEW_LINE> Window.SURFACE.blit(self.sprite, self.spriteRect) <NEW_LINE> Window().displayText("Health: " + str(self.currentHealth) + "/" + str(self.maxHealth), tileRect.x + 5, tileRect.y + 5, 20) <NEW_LINE> if self.unittype == UnitType.SOLDIER: <NEW_LINE> <INDENT> Window().displayText("Speed: " + str(self.currentSpeed) + "/" + str(self.speed), tileRect.bottomleft[0] + 5, tileRect.bottomleft[1] - 15, 20)
base class for a generic unit buildings have 0 speed for reasons :parameter unitinfo: the basic stats and info for the units :parameter sprite (Surface): the sprite of the unit, preferably pixel art :parameter team (Team()): what team this unit is on :parameter position (int[y, x]): the position of the unit on the board, with a reversed axis :var requiredBuilding: unitinfo of building required to build unit
6259904807f4c71912bb07d9
class ClearDbView(LoginRequiredMixin, View): <NEW_LINE> <INDENT> def post(self, request): <NEW_LINE> <INDENT> return JsonResponse({"code": 1, "msg": "this operation not allow!", "data": ""}) <NEW_LINE> data = {"code": 0, "msg": "successful", "data": ""} <NEW_LINE> redis_name = request.POST.get("redis_name", None) <NEW_LINE> db_id = request.POST.get("db_id", None) <NEW_LINE> try: <NEW_LINE> <INDENT> cl, cur_server_index, cur_db_index = get_cl(redis_name=redis_name, db_id=db_id) <NEW_LINE> cl.flushdb() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logs.error(e) <NEW_LINE> data["code"] = 1 <NEW_LINE> data["msg"] = "failed" <NEW_LINE> <DEDENT> return JsonResponse(data=data, safe=False)
清空DB
6259904863b5f9789fe86513
class KeyAuthorizationAnnotatedChallenge(AnnotatedChallenge): <NEW_LINE> <INDENT> __slots__ = ('challb', 'domain', 'account_key') <NEW_LINE> def response_and_validation(self): <NEW_LINE> <INDENT> return self.challb.chall.response_and_validation(self.account_key)
Client annotated `KeyAuthorizationChallenge` challenge.
62599048ec188e330fdf9c43
class ExtendedMessage(object): <NEW_LINE> <INDENT> template = None <NEW_LINE> html = None <NEW_LINE> msg = None <NEW_LINE> status = None <NEW_LINE> def __init__(self, template, status, **kwds): <NEW_LINE> <INDENT> self.html = template % kwds <NEW_LINE> self.msg = kwds['msg'] <NEW_LINE> self.status = status <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.html
An string to be rendered as HTML It holds metadata about the contained information
625990488a349b6b436875f3
@dataclass <NEW_LINE> class BoxAnnotation(Annotation): <NEW_LINE> <INDENT> label: str <NEW_LINE> x: Union[float, int] <NEW_LINE> y: Union[float, int] <NEW_LINE> width: Union[float, int] <NEW_LINE> height: Union[float, int] <NEW_LINE> reference_id: str <NEW_LINE> annotation_id: Optional[str] = None <NEW_LINE> metadata: Optional[Dict] = None <NEW_LINE> def __post_init__(self): <NEW_LINE> <INDENT> self.metadata = self.metadata if self.metadata else {} <NEW_LINE> if self.annotation_id is None: <NEW_LINE> <INDENT> self.annotation_id = f"{self.label}-{self.x}-{self.y}-{self.width}-{self.height}-{self.reference_id}" <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def from_json(cls, payload: dict): <NEW_LINE> <INDENT> geometry = payload.get(GEOMETRY_KEY, {}) <NEW_LINE> return cls( label=payload.get(LABEL_KEY, 0), x=geometry.get(X_KEY, 0), y=geometry.get(Y_KEY, 0), width=geometry.get(WIDTH_KEY, 0), height=geometry.get(HEIGHT_KEY, 0), reference_id=payload[REFERENCE_ID_KEY], annotation_id=payload.get(ANNOTATION_ID_KEY, None), metadata=payload.get(METADATA_KEY, {}), ) <NEW_LINE> <DEDENT> def to_payload(self) -> dict: <NEW_LINE> <INDENT> return { LABEL_KEY: self.label, TYPE_KEY: BOX_TYPE, GEOMETRY_KEY: { X_KEY: self.x, Y_KEY: self.y, WIDTH_KEY: self.width, HEIGHT_KEY: self.height, }, REFERENCE_ID_KEY: self.reference_id, ANNOTATION_ID_KEY: self.annotation_id, METADATA_KEY: self.metadata, }
A bounding box annotation. :: from nucleus import BoxAnnotation box = BoxAnnotation( label="car", x=0, y=0, width=10, height=10, reference_id="image_1", annotation_id="image_1_car_box_1", metadata={"vehicle_color": "red"} ) Parameters: label (str): The label for this annotation. x (Union[float, int]): The distance, in pixels, between the left border of the bounding box and the left border of the image. y (Union[float, int]): The distance, in pixels, between the top border of the bounding box and the top border of the image. width (Union[float, int]): The width in pixels of the annotation. height (Union[float, int]): The height in pixels of the annotation. reference_id (str): User-defined ID of the image to which to apply this annotation. annotation_id (Optional[str]): The annotation ID that uniquely identifies this annotation within its target dataset item. Upon ingest, a matching annotation id will be ignored by default, and overwritten if update=True for dataset.annotate. If no annotation ID is passed, one will be automatically generated using the label, x, y, width, and height, so that you can make inserts idempotently as identical boxes will be ignored. metadata (Optional[Dict]): Arbitrary key/value dictionary of info to attach to this annotation. Strings, floats and ints are supported best by querying and insights features within Nucleus. For more details see our `metadata guide <https://nucleus.scale.com/docs/upload-metadata>`_.
6259904873bcbd0ca4bcb634
class ExocrineStage8(_CaseInsensitiveEnum): <NEW_LINE> <INDENT> n0 = 'N0' <NEW_LINE> n1 = 'N1' <NEW_LINE> n2 = 'N2' <NEW_LINE> nx = 'NX' <NEW_LINE> unknown = 'Unknown'
Extent of the regional lymph node involvement for exocrine pancreatic carcinoma based on clinical stage information combined with operative findings, and evidence obtained from pathology review when surgery is the first definitive therapy, using AJCC Ed. 8 criteria. Yikes.
62599048462c4b4f79dbcda6
class BaseCartItem(models.Model): <NEW_LINE> <INDENT> cart = models.ForeignKey(get_model_string('Cart'), related_name="items") <NEW_LINE> quantity = models.IntegerField() <NEW_LINE> product = models.ForeignKey(get_model_string('Product')) <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> abstract = True <NEW_LINE> app_label = 'shop' <NEW_LINE> verbose_name = _('Cart item') <NEW_LINE> verbose_name_plural = _('Cart items') <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(BaseCartItem, self).__init__(*args, **kwargs) <NEW_LINE> self.extra_price_fields = [] <NEW_LINE> self.line_subtotal = Decimal('0.0') <NEW_LINE> self.line_total = Decimal('0.0') <NEW_LINE> self.current_total = Decimal('0.0') <NEW_LINE> <DEDENT> def update(self, state): <NEW_LINE> <INDENT> self.extra_price_fields = [] <NEW_LINE> self.line_subtotal = self.product.get_price() * self.quantity <NEW_LINE> self.current_total = self.line_subtotal <NEW_LINE> for modifier in cart_modifiers_pool.get_modifiers_list(): <NEW_LINE> <INDENT> modifier.process_cart_item(self, state) <NEW_LINE> <DEDENT> self.line_total = self.current_total <NEW_LINE> return self.line_total
This is a holder for the quantity of items in the cart and, obviously, a pointer to the actual Product being purchased :)
62599048a79ad1619776b427
class CustomFieldWidgetVisibility(object): <NEW_LINE> <INDENT> implements(IATWidgetVisibility) <NEW_LINE> def __init__(self, context): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.sort = 10 <NEW_LINE> self.hidden_fields = ['AdHoc', 'Composite', 'InvoiceExclude'] <NEW_LINE> self.random = 4 <NEW_LINE> <DEDENT> def __call__(self, context, mode, field, default): <NEW_LINE> <INDENT> state = default if default else 'hidden' <NEW_LINE> fieldName = field.getName() <NEW_LINE> if not self.context.getClient(): <NEW_LINE> <INDENT> if fieldName in []: <NEW_LINE> <INDENT> return 'invisible' <NEW_LINE> <DEDENT> <DEDENT> return state
Forces a set of AnalysisRequest fields to be invisible depending on some arbitrary condition.
62599048d7e4931a7ef3d41d
class PostDetail(DetailView): <NEW_LINE> <INDENT> template_name = 'post/detail.html' <NEW_LINE> context_object_name = 'post' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> content_type_obj = ContentType.objects.get_for_model(self.model) <NEW_LINE> comments_list = context['object'].comments.get_grand_parents() .select_related('user') <NEW_LINE> paginator = Paginator(comments_list, comment_consts.PAGINATE_BY) <NEW_LINE> context['comments'] = paginator.get_page(1) <NEW_LINE> context['content_type_id'] = content_type_obj.pk <NEW_LINE> if self.request.user.is_authenticated: <NEW_LINE> <INDENT> context['subscribe'] = context['object'].subscribes.filter( user=self.request.user ).exists() <NEW_LINE> <DEDENT> return context
Blog and News detail view
62599048379a373c97d9a3d1
class TestSnrAntenna(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> nants = 5 <NEW_LINE> self.shape = (2, 10, 2, nants*(nants-1)//2) <NEW_LINE> self.vis = np.ones(self.shape, np.complex64) <NEW_LINE> self.weights = np.ones(self.shape, np.float32) <NEW_LINE> self.bls_lookup = np.array([ (0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4) ]) <NEW_LINE> self.vis *= np.exp(1.j * 0.01) <NEW_LINE> vis_angle = np.array([(0.01, 0.01, 0.01, 0.01, 0.01, 0.02, 0.02, 0.04, 0.04, 0.01)]) <NEW_LINE> self.vis[0] = np.exp(1.j * vis_angle) <NEW_LINE> self.weights[0] = np.array([(2, 2, 2, 1, 2, 2, 1, 1, 1, 4)]) <NEW_LINE> self.vis[0, 5, 1, 0] = np.nan <NEW_LINE> nan_bls = [np.any(2 == b) for b in self.bls_lookup] <NEW_LINE> self.vis[1, :, 0, nan_bls] = np.nan <NEW_LINE> self.high_bls = [np.any(1 == b) for b in self.bls_lookup] <NEW_LINE> self.vis[1, :, 1, self.high_bls] = np.exp(1.j * 0.5) <NEW_LINE> self.expected = 100 * np.ones((2, 2, nants), np.float32) <NEW_LINE> self.expected[0] = [100, 100 / np.sqrt(16 / 7), 100 / np.sqrt(6), 100 / np.sqrt(30 / 9), 100 / np.sqrt(25 / 7)] <NEW_LINE> self.expected[0, 1, 1] = 100 / (np.sqrt(158 / 68)) <NEW_LINE> self.expected[1, 0, 2] = np.nan <NEW_LINE> <DEDENT> def test_basic(self): <NEW_LINE> <INDENT> expected = self.expected <NEW_LINE> expected[1, 1, :] = 100 / np.sqrt(2503 / 4) <NEW_LINE> expected[1, 1, 1] = 100 / 50 <NEW_LINE> snr = calprocs.snr_antenna(self.vis, self.weights, self.bls_lookup) <NEW_LINE> np.testing.assert_allclose(expected, snr, rtol=1e-3) <NEW_LINE> <DEDENT> def test_mask(self): <NEW_LINE> <INDENT> expected = self.expected <NEW_LINE> ant_flags = np.ones(self.shape, bool) <NEW_LINE> ant_flags[1, :, 1, self.high_bls] = True <NEW_LINE> expected[1, 1, 1] = 2 <NEW_LINE> snr = calprocs.snr_antenna(self.vis, self.weights, self.bls_lookup, ant_flags) <NEW_LINE> np.testing.assert_allclose(expected, snr, rtol=1e3)
Tests for :func:`katsdpcal.calprocs.snr_antenna`
6259904816aa5153ce401894
class TestQueryFunction(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestQueryFunction, self).setUp() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(TestQueryFunction, self).tearDown() <NEW_LINE> <DEDENT> def _test_init(self, value): <NEW_LINE> <INDENT> if (isinstance(value, QueryFunctionEnum)) or (value is None): <NEW_LINE> <INDENT> query_function = QueryFunction(value) <NEW_LINE> msg = "expected {0}, observed {1}".format( value, query_function.enum) <NEW_LINE> self.assertEqual(value, query_function.enum, msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertRaises(TypeError, QueryFunction, value) <NEW_LINE> <DEDENT> <DEDENT> def test_init_with_none(self): <NEW_LINE> <INDENT> self._test_init(None) <NEW_LINE> <DEDENT> def test_init_with_valid(self): <NEW_LINE> <INDENT> self._test_init(QueryFunctionEnum.QUERY_OBJECTS) <NEW_LINE> <DEDENT> def test_init_with_invalid(self): <NEW_LINE> <INDENT> self._test_init("invalid")
A test suite for the QueryFunction class. Since QueryFunction is a simple wrapper for the Enumeration primitive, only a few tests pertaining to construction are needed.
625990481f5feb6acb163f9c
@dbus_interface(DISK_INITIALIZATION.interface_name) <NEW_LINE> class DiskInitializationInterface(KickstartModuleInterfaceTemplate): <NEW_LINE> <INDENT> def connect_signals(self): <NEW_LINE> <INDENT> super().connect_signals() <NEW_LINE> self.watch_property("InitializationMode", self.implementation.initialization_mode_changed) <NEW_LINE> self.watch_property("DevicesToClear", self.implementation.devices_to_clear_changed) <NEW_LINE> self.watch_property("DrivesToClear", self.implementation.drives_to_clear_changed) <NEW_LINE> self.watch_property("DefaultDiskLabel", self.implementation.default_disk_label_changed) <NEW_LINE> self.watch_property("FormatLDLEnabled", self.implementation.format_ldl_enabled_changed) <NEW_LINE> self.watch_property("FormatUnrecognizedEnabled", self.implementation.format_unrecognized_enabled_changed) <NEW_LINE> self.watch_property("InitializeLabelsEnabled", self.implementation.initialize_labels_enabled_changed) <NEW_LINE> <DEDENT> @property <NEW_LINE> def InitializationMode(self) -> Int: <NEW_LINE> <INDENT> return self.implementation.initialization_mode.value <NEW_LINE> <DEDENT> @emits_properties_changed <NEW_LINE> def SetInitializationMode(self, mode: Int): <NEW_LINE> <INDENT> self.implementation.set_initialization_mode(InitializationMode(mode)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def DevicesToClear(self) -> List[Str]: <NEW_LINE> <INDENT> return self.implementation.devices_to_clear <NEW_LINE> <DEDENT> @emits_properties_changed <NEW_LINE> def SetDevicesToClear(self, devices: List[Str]): <NEW_LINE> <INDENT> self.implementation.set_devices_to_clear(devices) <NEW_LINE> <DEDENT> @property <NEW_LINE> def DrivesToClear(self) -> List[Str]: <NEW_LINE> <INDENT> return self.implementation.drives_to_clear <NEW_LINE> <DEDENT> @emits_properties_changed <NEW_LINE> def SetDrivesToClear(self, drives: List[Str]): <NEW_LINE> <INDENT> self.implementation.set_drives_to_clear(drives) <NEW_LINE> <DEDENT> @property <NEW_LINE> def DefaultDiskLabel(self) -> Str: <NEW_LINE> <INDENT> return self.implementation.default_disk_label <NEW_LINE> <DEDENT> @emits_properties_changed <NEW_LINE> def SetDefaultDiskLabel(self, label: Str): <NEW_LINE> <INDENT> self.implementation.set_default_disk_label(label) <NEW_LINE> <DEDENT> @property <NEW_LINE> def FormatUnrecognizedEnabled(self) -> Bool: <NEW_LINE> <INDENT> return self.implementation.format_unrecognized_enabled <NEW_LINE> <DEDENT> @emits_properties_changed <NEW_LINE> def SetFormatUnrecognizedEnabled(self, value: Bool): <NEW_LINE> <INDENT> self.implementation.set_format_unrecognized_enabled(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def InitializeLabelsEnabled(self) -> Bool: <NEW_LINE> <INDENT> return self.implementation.initialize_labels_enabled <NEW_LINE> <DEDENT> @emits_properties_changed <NEW_LINE> def SetInitializeLabelsEnabled(self, value: Bool): <NEW_LINE> <INDENT> self.implementation.set_initialize_labels_enabled(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def FormatLDLEnabled(self) -> Bool: <NEW_LINE> <INDENT> return self.implementation.format_ldl_enabled <NEW_LINE> <DEDENT> @emits_properties_changed <NEW_LINE> def SetFormatLDLEnabled(self, value: Bool): <NEW_LINE> <INDENT> self.implementation.set_format_ldl_enabled(value)
DBus interface for the disk initialization module.
6259904810dbd63aa1c71f82
class Tube: <NEW_LINE> <INDENT> def __init__(self, server): <NEW_LINE> <INDENT> self.incoming = os.path.join('/tmp', '{}.in'.format(server)) <NEW_LINE> self.outgoing = os.path.join('/tmp', '{}.out'.format(server)) <NEW_LINE> <DEDENT> def identify(self, nick, gecos): <NEW_LINE> <INDENT> with open(self.outgoing, 'w', encoding='utf-8') as send: <NEW_LINE> <INDENT> send.write('NICK {}\r\n'.format(nick)) <NEW_LINE> send.write('USER {} * 8 :{}\r\n'.format(nick, gecos)) <NEW_LINE> <DEDENT> <DEDENT> def join(self, channel): <NEW_LINE> <INDENT> with open(self.outgoing, 'w', encoding='utf-8') as send: <NEW_LINE> <INDENT> send.write('JOIN {}\r\n'.format(channel)) <NEW_LINE> <DEDENT> <DEDENT> def notice(self, message, channel): <NEW_LINE> <INDENT> with open(self.outgoing, 'w', encoding='utf-8') as send: <NEW_LINE> <INDENT> send.write('NOTICE {} :{}\r\n'.format(channel, message)) <NEW_LINE> <DEDENT> <DEDENT> def privmsg(self, message, channel): <NEW_LINE> <INDENT> if message[:7] == '\x01ACTION': <NEW_LINE> <INDENT> with open(self.outgoing, 'w', encoding='utf-8') as send: <NEW_LINE> <INDENT> sanitised = ''.join(c for c in message if c.isprintable()) <NEW_LINE> send.write('PRIVMSG {} :\x01{}\x01\r\n'.format(channel, sanitised)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with open(self.outgoing, 'w', encoding='utf-8') as send: <NEW_LINE> <INDENT> sanitised = message.replace('\n', ' ',).replace('\r', '') <NEW_LINE> send.write('PRIVMSG {} :{}\r\n'.format(channel, sanitised)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def pong(self, reply): <NEW_LINE> <INDENT> with open(self.outgoing, 'w', encoding='utf-8') as send: <NEW_LINE> <INDENT> send.write('PONG {0}\r\n'.format(reply))
Object for interacting with tubes.
62599048009cb60464d028dc
class V1beta1ResourceAttributes(object): <NEW_LINE> <INDENT> def __init__(self, namespace=None, verb=None, group=None, version=None, resource=None, subresource=None, name=None): <NEW_LINE> <INDENT> self.swagger_types = { 'namespace': 'str', 'verb': 'str', 'group': 'str', 'version': 'str', 'resource': 'str', 'subresource': 'str', 'name': 'str' } <NEW_LINE> self.attribute_map = { 'namespace': 'namespace', 'verb': 'verb', 'group': 'group', 'version': 'version', 'resource': 'resource', 'subresource': 'subresource', 'name': 'name' } <NEW_LINE> self._namespace = namespace <NEW_LINE> self._verb = verb <NEW_LINE> self._group = group <NEW_LINE> self._version = version <NEW_LINE> self._resource = resource <NEW_LINE> self._subresource = subresource <NEW_LINE> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def namespace(self): <NEW_LINE> <INDENT> return self._namespace <NEW_LINE> <DEDENT> @namespace.setter <NEW_LINE> def namespace(self, namespace): <NEW_LINE> <INDENT> self._namespace = namespace <NEW_LINE> <DEDENT> @property <NEW_LINE> def verb(self): <NEW_LINE> <INDENT> return self._verb <NEW_LINE> <DEDENT> @verb.setter <NEW_LINE> def verb(self, verb): <NEW_LINE> <INDENT> self._verb = verb <NEW_LINE> <DEDENT> @property <NEW_LINE> def group(self): <NEW_LINE> <INDENT> return self._group <NEW_LINE> <DEDENT> @group.setter <NEW_LINE> def group(self, group): <NEW_LINE> <INDENT> self._group = group <NEW_LINE> <DEDENT> @property <NEW_LINE> def version(self): <NEW_LINE> <INDENT> return self._version <NEW_LINE> <DEDENT> @version.setter <NEW_LINE> def version(self, version): <NEW_LINE> <INDENT> self._version = version <NEW_LINE> <DEDENT> @property <NEW_LINE> def resource(self): <NEW_LINE> <INDENT> return self._resource <NEW_LINE> <DEDENT> @resource.setter <NEW_LINE> def resource(self, resource): <NEW_LINE> <INDENT> self._resource = resource <NEW_LINE> <DEDENT> @property <NEW_LINE> def subresource(self): <NEW_LINE> <INDENT> return self._subresource <NEW_LINE> <DEDENT> @subresource.setter <NEW_LINE> def subresource(self, subresource): <NEW_LINE> <INDENT> self._subresource = subresource <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1beta1ResourceAttributes): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259904823e79379d538d8a5
class ModInt(object): <NEW_LINE> <INDENT> def __init__(self, x, n): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.n = n <NEW_LINE> <DEDENT> def __add__(self, m): <NEW_LINE> <INDENT> if isinstance(m, ModInt): <NEW_LINE> <INDENT> assert self.n == m.n <NEW_LINE> return ModInt((self.x + m.x) % self.n, self.n) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ModInt((self.x + m) % self.n, self.n) <NEW_LINE> <DEDENT> <DEDENT> def __radd__(self, m): <NEW_LINE> <INDENT> if isinstance(m, ModInt): <NEW_LINE> <INDENT> assert self.n == m.n <NEW_LINE> return ModInt((self.x + m.x) % self.n, self.n) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ModInt((self.x + m) % self.n, self.n) <NEW_LINE> <DEDENT> <DEDENT> def __sub__(self, m): <NEW_LINE> <INDENT> if isinstance(m, ModInt): <NEW_LINE> <INDENT> assert self.n == m.n <NEW_LINE> return ModInt((self.x - m.x) % self.n, self.n) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ModInt((self.x - m) % self.n, self.n) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.x) + ' [' + str(self.n) + ']' <NEW_LINE> <DEDENT> def __print__(self): <NEW_LINE> <INDENT> return self.__repr__()
A number in Z/nZ, i.e., modulo n. Variables: * x = number modulo n * n Implemented: additions and subtraction. N.B.: not a very useful class.
6259904807f4c71912bb07da
class VertexAStar(Vertex): <NEW_LINE> <INDENT> DEFAULT_MOVE_COST = 10 <NEW_LINE> def __init__(self, coords, father=None): <NEW_LINE> <INDENT> super(VertexAStar).__init__(coords, father) <NEW_LINE> if father: <NEW_LINE> <INDENT> self.g = father.g + self.DEFAULT_MOVE_COST <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.g = 0 <NEW_LINE> <DEDENT> self.h = None <NEW_LINE> self.f = None <NEW_LINE> <DEDENT> def calculate_h(self, end_coords): <NEW_LINE> <INDENT> horizontal_path_cost = abs(end_coords[0] - self.coords[0]) <NEW_LINE> vertical_path_cost = abs(end_coords[1] - self.coords[1]) <NEW_LINE> self.h = (horizontal_path_cost + vertical_path_cost) * self.DEFAULT_MOVE_COST <NEW_LINE> <DEDENT> def calculate_f(self): <NEW_LINE> <INDENT> self.f = self.g + self.h <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return super(VertexAStar).__str__() + "g={}; h={}; f={}".format(self.g, self.h, self.f)
Vertex for A* algorithm must implement 3 new fields: g - length from start vertex to current vertex. Initially it will be equals to 0, On each loop iteration it will be equals to father.g + cost of move from previous point to current point. For vertical and horizontal moves cost will be 10. For diagonal moves - 14 (sqrt(2) * 10) h - approximate cost of path to end point using only vertical and horizontal moves f - sum of g and h
62599048d99f1b3c44d06a42
class DummyMaker: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.levels = None <NEW_LINE> <DEDENT> def fit(self, categorical_array): <NEW_LINE> <INDENT> u, indices = np.unique(categorical_array, return_inverse=True) <NEW_LINE> self.levels = [u, indices] <NEW_LINE> <DEDENT> def transform(self, categorical_array, k_minus_one=False): <NEW_LINE> <INDENT> num_rows = len(categorical_array) <NEW_LINE> num_features = len(self.levels[0]) <NEW_LINE> dummies = np.zeros(shape=(num_rows, num_features)) <NEW_LINE> for idx, categ in enumerate(self.levels[0]): <NEW_LINE> <INDENT> column = np.where(self.levels[1] == idx, 1, 0) <NEW_LINE> dummies[:, idx:idx+1] += column.reshape(num_rows, 1) <NEW_LINE> <DEDENT> return pd.DataFrame(dummies, columns=self.levels[0])
Class takes a categorical variable and returns a DataFrame with a column for each category having values of 0 or 1 for each row.
6259904863d6d428bbee3b71
class _CommandRemove: <NEW_LINE> <INDENT> def GetResources(self): <NEW_LINE> <INDENT> return {'Pixmap' : 'Arch_Remove', 'MenuText': QtCore.QT_TRANSLATE_NOOP("Arch_Remove","Remove component"), 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Arch_Remove","Remove the selected components from their parents, or create a hole in a component")} <NEW_LINE> <DEDENT> def IsActive(self): <NEW_LINE> <INDENT> return bool(FreeCADGui.Selection.getSelection()) <NEW_LINE> <DEDENT> def Activated(self): <NEW_LINE> <INDENT> sel = FreeCADGui.Selection.getSelection() <NEW_LINE> if Draft.getType(sel[-1]) == "Space": <NEW_LINE> <INDENT> FreeCAD.ActiveDocument.openTransaction(translate("Arch","Remove space boundary")) <NEW_LINE> FreeCADGui.addModule("Arch") <NEW_LINE> FreeCADGui.doCommand("Arch.removeSpaceBoundaries( FreeCAD.ActiveDocument."+sel[-1].Name+", FreeCADGui.Selection.getSelection() )") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> FreeCAD.ActiveDocument.openTransaction(translate("Arch","Ungrouping")) <NEW_LINE> if (Draft.getType(sel[-1]) in ["Wall","Structure","Stairs","Roof","Window","Panel"]) and (len(sel) > 1): <NEW_LINE> <INDENT> host = sel.pop() <NEW_LINE> ss = "[" <NEW_LINE> for o in sel: <NEW_LINE> <INDENT> if len(ss) > 1: <NEW_LINE> <INDENT> ss += "," <NEW_LINE> <DEDENT> ss += "FreeCAD.ActiveDocument."+o.Name <NEW_LINE> <DEDENT> ss += "]" <NEW_LINE> FreeCADGui.addModule("Arch") <NEW_LINE> FreeCADGui.doCommand("Arch.removeComponents("+ss+",FreeCAD.ActiveDocument."+host.Name+")") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> FreeCADGui.addModule("Arch") <NEW_LINE> FreeCADGui.doCommand("Arch.removeComponents(FreeCAD.ActiveDocument."+sel[-1].Name+")") <NEW_LINE> <DEDENT> <DEDENT> FreeCAD.ActiveDocument.commitTransaction() <NEW_LINE> FreeCAD.ActiveDocument.recompute()
the Arch Add command definition
6259904830dc7b76659a0bda
class TestBuildsystem(unittest.TestCase): <NEW_LINE> <INDENT> def test_raises_not_implemented(self): <NEW_LINE> <INDENT> bs = buildsys.Buildsystem() <NEW_LINE> for method in ( bs.getBuild, bs.getLatestBuilds, bs.moveBuild, bs.ssl_login, bs.listBuildRPMs, bs.listTags, bs.listTagged, bs.taskFinished, bs.tagBuild, bs.untagBuild, bs.multiCall, bs.getTag): <NEW_LINE> <INDENT> self.assertRaises(NotImplementedError, method) <NEW_LINE> <DEDENT> <DEDENT> def test_raises_not_configured(self): <NEW_LINE> <INDENT> buildsys.teardown_buildsystem() <NEW_LINE> self.assertRaises(RuntimeError, buildsys.get_session) <NEW_LINE> <DEDENT> def test_raises_unknown_buildsys(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, buildsys.setup_buildsystem, {'buildsystem': 'invalid'})
This test class contains tests for the Buildsystem class.
6259904815baa72349463339
class AverageVariabilityOfTimeBetweenAttacksForEachVoiceFeature( featuresModule.FeatureExtractor): <NEW_LINE> <INDENT> id = 'R25' <NEW_LINE> def __init__(self, dataOrStream=None, *arguments, **keywords): <NEW_LINE> <INDENT> featuresModule.FeatureExtractor.__init__(self, dataOrStream=dataOrStream, *arguments, **keywords) <NEW_LINE> self.name = 'Average Variability of Time Between Attacks For Each Voice' <NEW_LINE> self.description = 'Average standard deviation, in seconds, of time between Note On events on individual channels that contain at least one note.' <NEW_LINE> self.isSequential = True <NEW_LINE> self.dimensions = 1 <NEW_LINE> <DEDENT> def _process(self): <NEW_LINE> <INDENT> onsetsByPart = [] <NEW_LINE> stdDeviationByPart = [] <NEW_LINE> if self.data.partsCount > 0: <NEW_LINE> <INDENT> for i in range(self.data.partsCount): <NEW_LINE> <INDENT> secondsMap = self.data['parts'][i]['secondsMap'] <NEW_LINE> onsets = [bundle['offsetSeconds'] for bundle in secondsMap] <NEW_LINE> onsetsByPart.append(onsets) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> secondsMap = self.data['secondsMap'] <NEW_LINE> onsets = [bundle['offsetSeconds'] for bundle in secondsMap] <NEW_LINE> onsetsByPart.append(onsets) <NEW_LINE> <DEDENT> for onsets in onsetsByPart: <NEW_LINE> <INDENT> onsets.sort() <NEW_LINE> differences = [] <NEW_LINE> for i, o in enumerate(onsets): <NEW_LINE> <INDENT> if i == len(onsets) - 1: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> oNext = onsets[i+1] <NEW_LINE> dif = oNext-o <NEW_LINE> if not common.almostEquals(dif, 0.0): <NEW_LINE> <INDENT> differences.append(dif) <NEW_LINE> <DEDENT> <DEDENT> stdDeviationByPart.append(common.standardDeviation(differences, bassel=False)) <NEW_LINE> <DEDENT> self._feature.vector[0] = (sum(stdDeviationByPart) / len(stdDeviationByPart))
Average standard deviation, in seconds, of time between Note On events on individual channels that contain at least one note. >>> s = corpus.parse('bwv66.6') >>> fe = features.jSymbolic.AverageVariabilityOfTimeBetweenAttacksForEachVoiceFeature(s) >>> f = fe.extract() >>> f.vector [0.1773926...]
62599049ec188e330fdf9c45
class Amenity(AbstractItem): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "amenities"
Amenity Model Definition
62599049baa26c4b54d50652
class MediafoneTransport(HttpRpcTransport): <NEW_LINE> <INDENT> transport_type = 'sms' <NEW_LINE> EXPECTED_FIELDS = set(['to', 'from', 'sms']) <NEW_LINE> def setup_transport(self): <NEW_LINE> <INDENT> self._username = self.config['username'] <NEW_LINE> self._password = self.config['password'] <NEW_LINE> self._outbound_url = self.config['outbound_url'] <NEW_LINE> return super(MediafoneTransport, self).setup_transport() <NEW_LINE> <DEDENT> @inlineCallbacks <NEW_LINE> def handle_outbound_message(self, message): <NEW_LINE> <INDENT> params = { 'username': self._username, 'password': self._password, 'phone': message['to_addr'], 'msg': message['content'], } <NEW_LINE> log.msg("Sending outbound message: %s" % (message,)) <NEW_LINE> url = '%s?%s' % (self._outbound_url, urlencode(params)) <NEW_LINE> log.msg("Making HTTP request: %s" % (url,)) <NEW_LINE> response = yield http_request_full(url, '', method='GET') <NEW_LINE> log.msg("Response: (%s) %r" % (response.code, response.delivered_body)) <NEW_LINE> yield self.publish_ack(user_message_id=message['message_id'], sent_message_id=message['message_id']) <NEW_LINE> <DEDENT> def get_field_values(self, request): <NEW_LINE> <INDENT> values = {} <NEW_LINE> errors = {} <NEW_LINE> for field in request.args: <NEW_LINE> <INDENT> if field not in self.EXPECTED_FIELDS: <NEW_LINE> <INDENT> errors.setdefault('unexpected_parameter', []).append(field) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> values[field] = str(request.args.get(field)[0]) <NEW_LINE> <DEDENT> <DEDENT> for field in self.EXPECTED_FIELDS: <NEW_LINE> <INDENT> if field not in values: <NEW_LINE> <INDENT> errors.setdefault('missing_parameter', []).append(field) <NEW_LINE> <DEDENT> <DEDENT> return values, errors <NEW_LINE> <DEDENT> @inlineCallbacks <NEW_LINE> def handle_raw_inbound_message(self, message_id, request): <NEW_LINE> <INDENT> values, errors = self.get_field_values(request) <NEW_LINE> if errors: <NEW_LINE> <INDENT> log.msg('Unhappy incoming message: %s' % (errors,)) <NEW_LINE> yield self.finish_request(message_id, json.dumps(errors), code=400) <NEW_LINE> return <NEW_LINE> <DEDENT> log.msg(('MediafoneTransport sending from %(from)s to %(to)s ' 'message "%(sms)s"') % values) <NEW_LINE> yield self.publish_message( message_id=message_id, content=values['sms'], to_addr=values['to'], from_addr=values['from'], provider='vumi', transport_type=self.transport_type, ) <NEW_LINE> yield self.finish_request( message_id, json.dumps({'message_id': message_id}))
HTTP transport for Mediafone Cameroun. :param str web_path: The HTTP path to listen on. :param int web_port: The HTTP port :param str transport_name: The name this transport instance will use to create its queues :param str username: Mediafone account username. :param str password: Mediafone account password. :param str outbound_url: The URL to send outbound messages to.
625990498a349b6b436875f5
class LessVariableDetail(LessVariableMixin, CreateModelMixin, generics.RetrieveUpdateDestroyAPIView): <NEW_LINE> <INDENT> lookup_field = 'name' <NEW_LINE> lookup_url_kwarg = 'name' <NEW_LINE> serializer_class = LessVariableSerializer <NEW_LINE> def delete(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(LessVariableDetail, self).delete(request, *args, **kwargs) <NEW_LINE> <DEDENT> def put(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(LessVariableDetail, self).put(request, *args, **kwargs) <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> return LessVariable.objects.filter( account=self.account, cssfile=self.get_cssfile()) <NEW_LINE> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(account=self.account, cssfile=self.get_cssfile())
Retrieves a css variable **Examples .. code-block:: http GET /api/themes/sitecss/variables/primary-color/ HTTP/1.1 responds .. code-block:: json { "name": "primary-color", "value": "#0000ff" }
62599049e76e3b2f99fd9db4
class TripletLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, margin=0.3): <NEW_LINE> <INDENT> super(TripletLoss, self).__init__() <NEW_LINE> self.margin = margin <NEW_LINE> if margin == 0.: <NEW_LINE> <INDENT> self.ranking_loss = nn.SoftMarginLoss() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ranking_loss = nn.MarginRankingLoss(margin=margin) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, inputs, targets): <NEW_LINE> <INDENT> n = inputs.size(0) <NEW_LINE> dist = torch.pow(inputs, 2).sum(dim=1, keepdim=True).expand(n, n) <NEW_LINE> dist = dist + dist.t() <NEW_LINE> dist.addmm_(1, -2, inputs, inputs.t()) <NEW_LINE> dist = dist.clamp(min=1e-12).sqrt() <NEW_LINE> mask = targets.expand(n, n).eq(targets.expand(n, n).t()) <NEW_LINE> dist_ap, dist_an = [], [] <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> tmp1 = dist[i][mask[i]] <NEW_LINE> tmp1 = tmp1.sort()[0][1:] <NEW_LINE> tmp1_sq = torch.pow(tmp1, 2) <NEW_LINE> sigma_p = tmp1_sq.mean() <NEW_LINE> dist_ap.append((-torch.log(torch.sum(torch.exp(-tmp1_sq / sigma_p))) + 0.5 * torch.log(sigma_p)).unsqueeze(0)) <NEW_LINE> tmp2 = dist[i][mask[i] == 0] <NEW_LINE> tmp2_sq = torch.pow(tmp2, 2) <NEW_LINE> sigma_n = tmp2_sq.mean() <NEW_LINE> dist_an.append((-torch.log(torch.sum(torch.exp(-tmp2_sq / sigma_n))) + 0.5 * torch.log(sigma_n)).unsqueeze(0)) <NEW_LINE> <DEDENT> dist_ap = torch.cat(dist_ap) <NEW_LINE> dist_an = torch.cat(dist_an) <NEW_LINE> y = torch.ones_like(dist_an) <NEW_LINE> if self.margin == 0.: <NEW_LINE> <INDENT> loss = self.ranking_loss(dist_an - dist_ap, y) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loss = self.ranking_loss(dist_an, dist_ap, y) <NEW_LINE> <DEDENT> return loss
Triplet loss with hard positive/negative mining. Reference: Hermans et al. In Defense of the Triplet Loss for Person Re-Identification. arXiv:1703.07737. Imported from `<https://github.com/Cysu/open-reid/blob/master/reid/loss/triplet.py>`_. Args: margin (float, optional): margin for triplet. Default is 0.3.
62599049009cb60464d028de
class c_ic_na_1(): <NEW_LINE> <INDENT> pass
class for IEC 104 interrogation command QOI information element IOA=0 CoT <control>: 6 or 8
62599049d53ae8145f919809
@api.resource('/list') <NEW_LINE> class ListAllAirports(Resource): <NEW_LINE> <INDENT> @swagger.operation( notes='Biggest first' ) <NEW_LINE> @cache.cached() <NEW_LINE> def get(self): <NEW_LINE> <INDENT> all_airports = Airports.query.all() <NEW_LINE> result = airports_schema.dump(all_airports) <NEW_LINE> return jsonify(result.data)
Retrieve all airports, sorted by number of passengers
62599049d10714528d69f062
class SampleRate(object): <NEW_LINE> <INDENT> def __init__(self, frequency, duration): <NEW_LINE> <INDENT> if frequency.astype(np.int) <= 0: <NEW_LINE> <INDENT> raise ValueError('frequency must be positive') <NEW_LINE> <DEDENT> if duration.astype(np.int) <= 0: <NEW_LINE> <INDENT> raise ValueError('duration must be positive') <NEW_LINE> <DEDENT> self.frequency = frequency <NEW_LINE> self.duration = duration <NEW_LINE> super(SampleRate, self).__init__() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> f = self.frequency / Seconds(1) <NEW_LINE> d = self.duration / Seconds(1) <NEW_LINE> return '{self.__class__.__name__}(f={f}, d={d})'.format(**locals()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter((self.frequency, self.duration)) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.frequency == other.frequency and self.duration == other.duration <NEW_LINE> <DEDENT> @property <NEW_LINE> def overlap(self): <NEW_LINE> <INDENT> return self.duration - self.frequency <NEW_LINE> <DEDENT> @property <NEW_LINE> def overlap_ratio(self): <NEW_LINE> <INDENT> return self.overlap / self.duration <NEW_LINE> <DEDENT> @property <NEW_LINE> def samples_per_second(self): <NEW_LINE> <INDENT> return int(Picoseconds(int(1e12)) / self.frequency) <NEW_LINE> <DEDENT> def __int__(self): <NEW_LINE> <INDENT> return self.samples_per_second <NEW_LINE> <DEDENT> @property <NEW_LINE> def nyquist(self): <NEW_LINE> <INDENT> return self.samples_per_second // 2 <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(other) == 1: <NEW_LINE> <INDENT> other *= 2 <NEW_LINE> <DEDENT> <DEDENT> except TypeError: <NEW_LINE> <INDENT> other = (other, other) <NEW_LINE> <DEDENT> freq = self.frequency * other[0] <NEW_LINE> duration = (self.frequency * other[1]) + self.overlap <NEW_LINE> new = SampleRate(freq, duration) <NEW_LINE> return new <NEW_LINE> <DEDENT> def discrete_samples(self, ts): <NEW_LINE> <INDENT> td = next(dim for dim in ts.dimensions if hasattr(dim, 'frequency')) <NEW_LINE> windowsize = np.round((self.duration - td.overlap) / td.frequency) <NEW_LINE> stepsize = np.round(self.frequency / td.frequency) <NEW_LINE> return int(stepsize), int(windowsize) <NEW_LINE> <DEDENT> def resample(self, ratio): <NEW_LINE> <INDENT> orig_freq = Picoseconds(int(self.frequency / Picoseconds(1))) <NEW_LINE> orig_duration = Picoseconds(int(self.duration / Picoseconds(1))) <NEW_LINE> f = orig_freq * ratio <NEW_LINE> d = orig_duration * ratio <NEW_LINE> return SampleRate(f, d)
`SampleRate` describes the constant frequency at which samples are taken from a continuous signal, and the duration of each sample. Instances of this class could describe an audio sampling rate (e.g. 44.1kHz) or the strided windows often used in short-time fourier transforms Args: frequency (numpy.timedelta64): The frequency at which the signal is sampled duration (numpy.timedelta64): The duration of each sample Raises: ValueError: when frequency or duration are less than or equal to zero Examples: >>> from zounds import Seconds, SampleRate >>> sr = SampleRate(Seconds(1), Seconds(2)) >>> sr.frequency numpy.timedelta64(1,'s') >>> sr.duration numpy.timedelta64(2,'s') >>> sr.overlap numpy.timedelta64(1,'s') >>> sr.overlap_ratio 0.5 See Also: :class:`SR96000` :class:`SR48000` :class:`SR44100` :class:`SR22050` :class:`SR11025`
6259904996565a6dacd2d95e
class TestEnabledQuirks(TestEnabled): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.purge() <NEW_LINE> self.quirks = True
Test enabled selectors with quirks.
6259904907f4c71912bb07dc
class Debug(enum.IntEnum): <NEW_LINE> <INDENT> NEXT_ARGS = (1 << 0) <NEW_LINE> EXTRACT = (1 << 1) <NEW_LINE> UPDATE_POS = (1 << 2) <NEW_LINE> NONE = 0 <NEW_LINE> ALL = (NEXT_ARGS | EXTRACT | UPDATE_POS)
Flags that enable/disable various debug logs in the tokeninzer.
625990498e71fb1e983bce6e
class INCRement(SCPINode, SCPIQuery, SCPISet): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _cmd = "INCRement" <NEW_LINE> args = ["1"]
SOURce:POWer:STARt:STEP:INCRement Arguments: 1
625990497cff6e4e811b6de3
class InvalidResolution(Error): <NEW_LINE> <INDENT> pass
The resolution is not valid because it is not listed within the resolutionlist for the checklist item.
62599049d4950a0f3b111817
@register('second') <NEW_LINE> class SecondSubfield(Subfield): <NEW_LINE> <INDENT> def run(self, val): <NEW_LINE> <INDENT> if val.precision >= 14: <NEW_LINE> <INDENT> return QuantityValue(amount=val.parsed.second)
>>> SecondSubfield()(TimeValue(time="+1996-03-17T04:15:08Z", precision=14)) QuantityValue(amount=8) >>> SecondSubfield()(TimeValue(time="+1996-03-17T04:15:00Z", precision=13)) UndefinedValue()
6259904945492302aabfd87c
class PageManager(PublisherManager): <NEW_LINE> <INDENT> def get_query_set(self): <NEW_LINE> <INDENT> return PageQuerySet(self.model) <NEW_LINE> <DEDENT> def drafts(self): <NEW_LINE> <INDENT> return super(PageManager, self).drafts().exclude( publisher_state=self.model.PUBLISHER_STATE_DELETE ) <NEW_LINE> <DEDENT> def public(self): <NEW_LINE> <INDENT> return super(PageManager, self).public().exclude( publisher_state=self.model.PUBLISHER_STATE_DELETE ) <NEW_LINE> <DEDENT> def on_site(self, site=None): <NEW_LINE> <INDENT> return self.get_query_set().on_site(site) <NEW_LINE> <DEDENT> def root(self): <NEW_LINE> <INDENT> return self.get_query_set().root() <NEW_LINE> <DEDENT> def all_root(self): <NEW_LINE> <INDENT> return self.get_query_set().all_root() <NEW_LINE> <DEDENT> def valid_targets(self, page_id, request, perms, page=None): <NEW_LINE> <INDENT> return self.get_query_set().valid_targets(page_id, request, perms, page) <NEW_LINE> <DEDENT> def published(self, site=None): <NEW_LINE> <INDENT> return self.get_query_set().published(site) <NEW_LINE> <DEDENT> def expired(self): <NEW_LINE> <INDENT> return self.drafts().expired() <NEW_LINE> <DEDENT> def get_all_pages_with_application(self): <NEW_LINE> <INDENT> return self.get_query_set().filter(title_set__application_urls__gt='').distinct() <NEW_LINE> <DEDENT> def get_home(self, site=None): <NEW_LINE> <INDENT> return self.get_query_set().get_home(site) <NEW_LINE> <DEDENT> def search(self, q, language=None, current_site_only=True): <NEW_LINE> <INDENT> from cms.plugin_pool import plugin_pool <NEW_LINE> qs = self.get_query_set() <NEW_LINE> if settings.CMS_MODERATOR: <NEW_LINE> <INDENT> qs = qs.public() <NEW_LINE> <DEDENT> if current_site_only: <NEW_LINE> <INDENT> site = Site.objects.get_current() <NEW_LINE> qs = qs.filter(site=site) <NEW_LINE> <DEDENT> qt = Q(title_set__title__icontains=q) <NEW_LINE> qp = Q() <NEW_LINE> plugins = plugin_pool.get_all_plugins() <NEW_LINE> for plugin in plugins: <NEW_LINE> <INDENT> c = plugin.model <NEW_LINE> if hasattr(c, 'search_fields'): <NEW_LINE> <INDENT> for field in c.search_fields: <NEW_LINE> <INDENT> qp |= Q(**{'placeholders__cmsplugin__%s__%s__icontains' % (c.__name__.lower(), field): q}) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if language: <NEW_LINE> <INDENT> qt &= Q(title_set__language=language) <NEW_LINE> qp &= Q(cmsplugin__language=language) <NEW_LINE> <DEDENT> qs = qs.filter(qt | qp) <NEW_LINE> return qs.distinct()
Use draft() and public() methods for accessing the corresponding instances.
6259904915baa7234946333b
class CollegeJiaowuBase(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.session = requests.session() <NEW_LINE> <DEDENT> def get_encoding_from_reponse(self, r): <NEW_LINE> <INDENT> encoding = requests.utils.get_encodings_from_content(r.text) <NEW_LINE> return encoding[0] if encoding else requests.utils.get_encoding_from_headers(r.headers) <NEW_LINE> <DEDENT> def get(self, url, **kwargs): <NEW_LINE> <INDENT> r = self.session.get(url, **kwargs) <NEW_LINE> if r.status_code == requests.codes.ok: <NEW_LINE> <INDENT> r.encoding = self.get_encoding_from_reponse(r) <NEW_LINE> return r <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise CollegeJiaowuRequestException(r.status_code, 'get url error: ' + url) <NEW_LINE> <DEDENT> <DEDENT> def post(self, url, data=None, json=None, **kwargs): <NEW_LINE> <INDENT> r = self.session.post(url, data=data, json=json, **kwargs) <NEW_LINE> if r.status_code == requests.codes.ok: <NEW_LINE> <INDENT> r.encoding = self.get_encoding_from_reponse(r) <NEW_LINE> return r <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise CollegeJiaowuRequestException(r.status_code, 'post url error: ' + url) <NEW_LINE> <DEDENT> <DEDENT> def get_request_param(self, url): <NEW_LINE> <INDENT> r = self.get(url) <NEW_LINE> __VIEWSTATE = re.findall('__VIEWSTATE" value="(.*?)"', r.text) <NEW_LINE> param = dict() <NEW_LINE> if __VIEWSTATE: <NEW_LINE> <INDENT> param['__VIEWSTATE'] = __VIEWSTATE[0] <NEW_LINE> <DEDENT> return param
基类
62599049a8ecb033258725bc
class ServiceContext(InstanceContext): <NEW_LINE> <INDENT> def __init__(self, version, sid): <NEW_LINE> <INDENT> super(ServiceContext, self).__init__(version) <NEW_LINE> self._solution = {'sid': sid, } <NEW_LINE> self._uri = '/Services/{sid}'.format(**self._solution) <NEW_LINE> self._sessions = None <NEW_LINE> self._phone_numbers = None <NEW_LINE> self._short_codes = None <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> params = values.of({}) <NEW_LINE> payload = self._version.fetch( 'GET', self._uri, params=params, ) <NEW_LINE> return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> return self._version.delete('delete', self._uri) <NEW_LINE> <DEDENT> def update(self, unique_name=values.unset, default_ttl=values.unset, callback_url=values.unset, geo_match_level=values.unset, number_selection_behavior=values.unset, intercept_callback_url=values.unset, out_of_session_callback_url=values.unset, chat_instance_sid=values.unset): <NEW_LINE> <INDENT> data = values.of({ 'UniqueName': unique_name, 'DefaultTtl': default_ttl, 'CallbackUrl': callback_url, 'GeoMatchLevel': geo_match_level, 'NumberSelectionBehavior': number_selection_behavior, 'InterceptCallbackUrl': intercept_callback_url, 'OutOfSessionCallbackUrl': out_of_session_callback_url, 'ChatInstanceSid': chat_instance_sid, }) <NEW_LINE> payload = self._version.update( 'POST', self._uri, data=data, ) <NEW_LINE> return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def sessions(self): <NEW_LINE> <INDENT> if self._sessions is None: <NEW_LINE> <INDENT> self._sessions = SessionList(self._version, service_sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._sessions <NEW_LINE> <DEDENT> @property <NEW_LINE> def phone_numbers(self): <NEW_LINE> <INDENT> if self._phone_numbers is None: <NEW_LINE> <INDENT> self._phone_numbers = PhoneNumberList(self._version, service_sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._phone_numbers <NEW_LINE> <DEDENT> @property <NEW_LINE> def short_codes(self): <NEW_LINE> <INDENT> if self._short_codes is None: <NEW_LINE> <INDENT> self._short_codes = ShortCodeList(self._version, service_sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._short_codes <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Proxy.V1.ServiceContext {}>'.format(context)
PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
6259904926068e7796d4dcee
class ServerVirtualInterfaceController(wsgi.Controller): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.compute_api = compute.API() <NEW_LINE> self.network_api = network.API() <NEW_LINE> super(ServerVirtualInterfaceController, self).__init__() <NEW_LINE> <DEDENT> def _items(self, req, server_id, entity_maker): <NEW_LINE> <INDENT> context = req.environ['nova.context'] <NEW_LINE> context.can(vif_policies.BASE_POLICY_NAME) <NEW_LINE> instance = common.get_instance(self.compute_api, context, server_id) <NEW_LINE> try: <NEW_LINE> <INDENT> vifs = self.network_api.get_vifs_by_instance(context, instance) <NEW_LINE> <DEDENT> except NotImplementedError: <NEW_LINE> <INDENT> msg = _('Listing virtual interfaces is not supported by this ' 'cloud.') <NEW_LINE> raise webob.exc.HTTPBadRequest(explanation=msg) <NEW_LINE> <DEDENT> limited_list = common.limited(vifs, req) <NEW_LINE> res = [entity_maker(req, vif) for vif in limited_list] <NEW_LINE> return {'virtual_interfaces': res} <NEW_LINE> <DEDENT> @wsgi.Controller.api_version("2.1", "2.43") <NEW_LINE> @extensions.expected_errors((400, 404)) <NEW_LINE> def index(self, req, server_id): <NEW_LINE> <INDENT> return self._items(req, server_id, entity_maker=_translate_vif_summary_view)
The instance VIF API controller for the OpenStack API. This API is deprecated from the Microversion '2.44'.
62599049d6c5a102081e34c6
class TPLinkWR740NDv1(cgm_devices.DeviceBase): <NEW_LINE> <INDENT> identifier = 'tp-wr740ndv1' <NEW_LINE> name = "WR740ND (v1)" <NEW_LINE> manufacturer = "TP-Link" <NEW_LINE> url = 'http://www.tp-link.com/' <NEW_LINE> architecture = 'ar71xx' <NEW_LINE> radios = [ cgm_devices.IntegratedRadio('wifi0', _("Integrated wireless radio"), [ cgm_protocols.IEEE80211BGN( cgm_protocols.IEEE80211BGN.SHORT_GI_20, cgm_protocols.IEEE80211BGN.SHORT_GI_40, cgm_protocols.IEEE80211BGN.RX_STBC1, cgm_protocols.IEEE80211BGN.DSSS_CCK_40, ) ], [ cgm_devices.AntennaConnector('a1', "Antenna0") ], [ cgm_devices.DeviceRadio.MultipleSSID, ]) ] <NEW_LINE> switches = [ cgm_devices.Switch( 'sw0', "Switch0", ports=5, cpu_port=0, vlans=16, configurable=False, presets=[ cgm_devices.SwitchPreset('default', _("Default VLAN configuration"), vlans=[ cgm_devices.SwitchVLANPreset( 'lan0', "Lan0", vlan=1, ports=[0, 1, 2, 3, 4], ) ]) ] ) ] <NEW_LINE> ports = [ cgm_devices.EthernetPort('wan0', "Wan0"), ] <NEW_LINE> antennas = [ cgm_devices.InternalAntenna( identifier='a1', polarization='horizontal', angle_horizontal=360, angle_vertical=75, gain=2, ) ] <NEW_LINE> port_map = { 'openwrt': { 'wifi0': 'radio0', 'sw0': cgm_devices.SwitchPortMap('switch0', vlans='eth0'), 'wan0': 'eth1', } } <NEW_LINE> drivers = { 'openwrt': { 'wifi0': 'mac80211' } } <NEW_LINE> profiles = { 'openwrt': { 'name': 'TLWR740', 'files': [ '*-ar71xx-generic-tl-wr740n-v1-squashfs-factory.bin', '*-ar71xx-generic-tl-wr740n-v1-squashfs-sysupgrade.bin' ] }, 'lede': { 'name': 'tl-wr740n-v1', 'files': [ '*-ar71xx-generic-tl-wr740n-v1-squashfs-factory.bin', '*-ar71xx-generic-tl-wr740n-v1-squashfs-sysupgrade.bin' ] } }
TP-Link WR740NDv1 device descriptor.
6259904976d4e153a661dc4b
class NFVIPoP(Model): <NEW_LINE> <INDENT> def __init__(self, id=None, location=None, gw_ip_address=None, capabilities=None, available_capabilities=None, failure_rate=None, internal_latency=None): <NEW_LINE> <INDENT> self.swagger_types = { 'id': str, 'location': Location, 'gw_ip_address': str, 'capabilities': NFVIPoPCapabilities, 'available_capabilities': NFVIPoPAvailableCapabilities, 'failure_rate': float, 'internal_latency': float } <NEW_LINE> self.attribute_map = { 'id': 'id', 'location': 'location', 'gw_ip_address': 'gw_ip_address', 'capabilities': 'capabilities', 'available_capabilities': 'availableCapabilities', 'failure_rate': 'failure_rate', 'internal_latency': 'internal_latency' } <NEW_LINE> self._id = id <NEW_LINE> self._location = location <NEW_LINE> self._gw_ip_address = gw_ip_address <NEW_LINE> self._capabilities = capabilities <NEW_LINE> self._available_capabilities = available_capabilities <NEW_LINE> self._failure_rate = failure_rate <NEW_LINE> self._internal_latency = internal_latency <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt): <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> if id is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `id`, must not be `None`") <NEW_LINE> <DEDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def location(self): <NEW_LINE> <INDENT> return self._location <NEW_LINE> <DEDENT> @location.setter <NEW_LINE> def location(self, location): <NEW_LINE> <INDENT> self._location = location <NEW_LINE> <DEDENT> @property <NEW_LINE> def gw_ip_address(self): <NEW_LINE> <INDENT> return self._gw_ip_address <NEW_LINE> <DEDENT> @gw_ip_address.setter <NEW_LINE> def gw_ip_address(self, gw_ip_address): <NEW_LINE> <INDENT> self._gw_ip_address = gw_ip_address <NEW_LINE> <DEDENT> @property <NEW_LINE> def capabilities(self): <NEW_LINE> <INDENT> return self._capabilities <NEW_LINE> <DEDENT> @capabilities.setter <NEW_LINE> def capabilities(self, capabilities): <NEW_LINE> <INDENT> if capabilities is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `capabilities`, must not be `None`") <NEW_LINE> <DEDENT> self._capabilities = capabilities <NEW_LINE> <DEDENT> @property <NEW_LINE> def available_capabilities(self): <NEW_LINE> <INDENT> return self._available_capabilities <NEW_LINE> <DEDENT> @available_capabilities.setter <NEW_LINE> def available_capabilities(self, available_capabilities): <NEW_LINE> <INDENT> self._available_capabilities = available_capabilities <NEW_LINE> <DEDENT> @property <NEW_LINE> def failure_rate(self): <NEW_LINE> <INDENT> return self._failure_rate <NEW_LINE> <DEDENT> @failure_rate.setter <NEW_LINE> def failure_rate(self, failure_rate): <NEW_LINE> <INDENT> self._failure_rate = failure_rate <NEW_LINE> <DEDENT> @property <NEW_LINE> def internal_latency(self): <NEW_LINE> <INDENT> return self._internal_latency <NEW_LINE> <DEDENT> @internal_latency.setter <NEW_LINE> def internal_latency(self, internal_latency): <NEW_LINE> <INDENT> self._internal_latency = internal_latency
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259904971ff763f4b5e8b4f
class PortletRenderer(ColumnPortletManagerRenderer): <NEW_LINE> <INDENT> adapts(Interface, IDefaultBrowserLayer, IBrowserView, IPortletManager) <NEW_LINE> template = ViewPageTemplateFile('templates/renderer.pt')
A renderer for the content portlets
62599049d7e4931a7ef3d421
class Course(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=64, unique=True) <NEW_LINE> price = models.PositiveSmallIntegerField() <NEW_LINE> period = models.PositiveSmallIntegerField(verbose_name='Period(Month)') <NEW_LINE> outline = models.TextField() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
Course Table
6259904973bcbd0ca4bcb638
class EditCustomLanguagePackInfo(Object): <NEW_LINE> <INDENT> ID = "editCustomLanguagePackInfo" <NEW_LINE> def __init__(self, info, extra=None, **kwargs): <NEW_LINE> <INDENT> self.extra = extra <NEW_LINE> self.info = info <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(q: dict, *args) -> "EditCustomLanguagePackInfo": <NEW_LINE> <INDENT> info = Object.read(q.get('info')) <NEW_LINE> return EditCustomLanguagePackInfo(info)
Edits information about a custom local language pack in the current localization target. Can be called before authorization Attributes: ID (:obj:`str`): ``EditCustomLanguagePackInfo`` Args: info (:class:`telegram.api.types.languagePackInfo`): New information about the custom local language pack Returns: Ok Raises: :class:`telegram.Error`
6259904982261d6c5273089b
class ComputeLogFileData( NamedTuple( "ComputeLogFileData", [ ("path", str), ("data", Optional[str]), ("cursor", int), ("size", int), ("download_url", Optional[str]), ], ) ): <NEW_LINE> <INDENT> def __new__( cls, path: str, data: Optional[str], cursor: int, size: int, download_url: Optional[str] ): <NEW_LINE> <INDENT> return super(ComputeLogFileData, cls).__new__( cls, path=check.str_param(path, "path"), data=check.opt_str_param(data, "data"), cursor=check.int_param(cursor, "cursor"), size=check.int_param(size, "size"), download_url=check.opt_str_param(download_url, "download_url"), )
Representation of a chunk of compute execution log data
62599049d6c5a102081e34c7
class Underlying(Base): <NEW_LINE> <INDENT> __tablename__ = 'underlying' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> wordtype_id = Column(Integer, ForeignKey('wordtype.id')) <NEW_LINE> segmenttype_id = Column(Integer, ForeignKey('segmenttype.id')) <NEW_LINE> segmenttype = relationship("SegmentType", backref="underlyings") <NEW_LINE> position = Column(Integer)
Many-to-many relation between word types and their underlying/canonical segments.
6259904907d97122c421804d
class PositiveSumConstraint(ArrayConstraint): <NEW_LINE> <INDENT> def __init__(self, sum_constraint): <NEW_LINE> <INDENT> if sum_constraint is None: <NEW_LINE> <INDENT> raise ValueError("Sum may not be None.") <NEW_LINE> <DEDENT> if math.isclose(sum_constraint, 0): <NEW_LINE> <INDENT> raise ValueError("Sum may not be 0.") <NEW_LINE> <DEDENT> self.sum = sum_constraint <NEW_LINE> <DEDENT> def satisfies(self, value): <NEW_LINE> <INDENT> return math.isclose(np.sum(value), self.sum)
Constrain a decision-mutable array so that all elements sum to a given value. All elements will be positive.
6259904915baa7234946333c
class ApplicationGatewayPrivateEndpointConnection(SubResource): <NEW_LINE> <INDENT> _validation = { 'etag': {'readonly': True}, 'type': {'readonly': True}, 'private_endpoint': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'link_identifier': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'}, 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'link_identifier': {'key': 'properties.linkIdentifier', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, private_link_service_connection_state: Optional["PrivateLinkServiceConnectionState"] = None, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayPrivateEndpointConnection, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.etag = None <NEW_LINE> self.type = None <NEW_LINE> self.private_endpoint = None <NEW_LINE> self.private_link_service_connection_state = private_link_service_connection_state <NEW_LINE> self.provisioning_state = None <NEW_LINE> self.link_identifier = None
Private Endpoint connection on an application gateway. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param name: Name of the private endpoint connection on an application gateway. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Type of the resource. :vartype type: str :ivar private_endpoint: The resource of private end point. :vartype private_endpoint: ~azure.mgmt.network.v2020_07_01.models.PrivateEndpoint :param private_link_service_connection_state: A collection of information about the state of the connection between service consumer and provider. :type private_link_service_connection_state: ~azure.mgmt.network.v2020_07_01.models.PrivateLinkServiceConnectionState :ivar provisioning_state: The provisioning state of the application gateway private endpoint connection resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed". :vartype provisioning_state: str or ~azure.mgmt.network.v2020_07_01.models.ProvisioningState :ivar link_identifier: The consumer link id. :vartype link_identifier: str
6259904923e79379d538d8a9
class Course(models.Model): <NEW_LINE> <INDENT> CourseID = models.AutoField(primary_key=True) <NEW_LINE> Faculty = models.ForeignKey(Faculty, on_delete=models.SET_NULL, null=True) <NEW_LINE> CourseName = models.CharField(max_length=60)
Course Model - Courses added manually at the this point in time
625990490a366e3fb87ddd91
class EventForwarder(object): <NEW_LINE> <INDENT> def __init__(self, hass, restrict_origin=None): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.restrict_origin = restrict_origin <NEW_LINE> self.logger = logging.getLogger(__name__) <NEW_LINE> self._targets = {} <NEW_LINE> self._lock = threading.Lock() <NEW_LINE> <DEDENT> def connect(self, api): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if len(self._targets) == 0: <NEW_LINE> <INDENT> self.hass.bus.listen(ha.MATCH_ALL, self._event_listener) <NEW_LINE> <DEDENT> key = (api.host, api.port) <NEW_LINE> self._targets[key] = api <NEW_LINE> <DEDENT> <DEDENT> def disconnect(self, api): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> key = (api.host, api.port) <NEW_LINE> did_remove = self._targets.pop(key, None) is None <NEW_LINE> if len(self._targets) == 0: <NEW_LINE> <INDENT> self.hass.bus.remove_listener(ha.MATCH_ALL, self._event_listener) <NEW_LINE> <DEDENT> return did_remove <NEW_LINE> <DEDENT> <DEDENT> def _event_listener(self, event): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if event.event_type == ha.EVENT_TIME_CHANGED or (self.restrict_origin and event.origin != self.restrict_origin): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for api in self._targets.values(): <NEW_LINE> <INDENT> fire_event(api, event.event_type, event.data, self.logger)
Listens for events and forwards to specified APIs.
6259904996565a6dacd2d95f
class ConflictError(ClientError): <NEW_LINE> <INDENT> def __init__(self, location): <NEW_LINE> <INDENT> self.location = location <NEW_LINE> super(ConflictError, self).__init__()
Error for when the server returns a 409 (Conflict) HTTP status. In the version of ACME implemented by Boulder, this is used to find an account if you only have the private key, but don't know the account URL.
6259904907f4c71912bb07de
class Accomplishment(TimeStampedModel): <NEW_LINE> <INDENT> user = models.ForeignKey(Reader, on_delete=models.CASCADE) <NEW_LINE> challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE) <NEW_LINE> books = models.ManyToManyField(Book) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return '{0} has accomplished {1} with {2} books'.format(self.user.username, self.challenge.name, len(self.books))
Accomplishment class is the definition for model returning short summary of challenge completed by user and with what book. This model contains 3 attributes namely user, challenge and books.
62599049287bf620b6272f94
class FTSRankCd(FTSRank): <NEW_LINE> <INDENT> sql_function = 'ts_rank_cd' <NEW_LINE> name = 'FTSRankCd'
Interface for PostgreSQL ts_rank_cd Provides a interface for :pg_docs:`12.3.3. Ranking Search Results *ts_rank_cd* <textsearch-controls.html#TEXTSEARCH-RANKING>` :param fieldlookup: required :param normalization: list or tuple of integers PostgreSQL normalization values :returns: rank_cd :raises: exceptions.FieldError if lookup isn't valid Example:: Article.objects.annotate( rank=FTSRank(fts_index__search='Hello world', normalization=[1,2])) SQL equivalent: .. code-block:: sql SELECT ..., ts_rank_cd("article"."fts_index" @@ to_tsquery('english', 'Hello & world'), 1|2) AS "rank" WHERE "article"."fts_index" @@ to_tsquery('english', 'Hello & world')
6259904915baa7234946333d
class BaseCallbackDispatcher(object): <NEW_LINE> <INDENT> def on_callback(self, callback, *args): <NEW_LINE> <INDENT> raise NotImplementedError
Base callback dispatcher class. Inherit from this class and override the :func:`on_callback` method to change how callbacks are dispatched.
6259904923e79379d538d8aa
class SelfAssessmentTest(OpenAssessmentTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp('self_only') <NEW_LINE> <DEDENT> @retry() <NEW_LINE> @pytest.mark.acceptance <NEW_LINE> def test_self_assessment(self): <NEW_LINE> <INDENT> self.do_self_assessment() <NEW_LINE> <DEDENT> @retry() <NEW_LINE> @pytest.mark.acceptance <NEW_LINE> def test_latex(self): <NEW_LINE> <INDENT> self.auto_auth_page.visit() <NEW_LINE> self.submission_page.visit() <NEW_LINE> self.assertTrue(self.submission_page.latex_preview_button_is_disabled) <NEW_LINE> self.submission_page.visit().fill_latex(self.LATEX_SUBMISSION) <NEW_LINE> self.assertFalse(self.submission_page.latex_preview_button_is_disabled) <NEW_LINE> self.submission_page.preview_latex()
Test the self-assessment flow.
62599049be383301e0254bc5
class StackAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> form = StackAdminForm <NEW_LINE> list_display = ("name", "course_id", "status", "provider", "launch_timestamp",) <NEW_LINE> list_filter = ("course_id", "status", "provider",) <NEW_LINE> list_editable = ("status", "provider") <NEW_LINE> list_select_related = True <NEW_LINE> actions = (mark_deleted,) <NEW_LINE> search_fields = ("name", "course_id", "status", "provider") <NEW_LINE> readonly_fields = ("name", student_email, "course_id", "run", "protocol", "port", "ip", "launch_timestamp", "suspend_timestamp", "created_on", "error_msg", "delete_age",) <NEW_LINE> exclude = ("student_id", "providers", "hook_script", "hook_events", "launch_task_id", "user", "key", "password",) <NEW_LINE> ordering = ("-launch_timestamp",) <NEW_LINE> def get_changelist_form(self, request, **kwargs): <NEW_LINE> <INDENT> return StackAdminForm <NEW_LINE> <DEDENT> def has_add_permission(self, request, obj=None): <NEW_LINE> <INDENT> return False
Custom stack admin class. Uses a custom form, enables searching and filtering, and totally excludes fields used by the XBlock solely to communicate with tasks or jobs. Of the remaining fields, only `status` and `provider` should be editable. Adding stacks manually is forbidden, but deleting records is allowed. A custom action allows marking stacks as `DELETE_COMPLETE` in bulk.
6259904926068e7796d4dcf0
class Generator(object): <NEW_LINE> <INDENT> def __init__(self, adapter, buddy_id, q_messages): <NEW_LINE> <INDENT> self.adapter = adapter <NEW_LINE> self.buddy_id = buddy_id <NEW_LINE> self.q_messages = q_messages <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> buddy = Buddy.get(id=self.buddy_id) <NEW_LINE> if buddy.enabled: <NEW_LINE> <INDENT> self.adapter.send_im_msg('?DUMMY:', buddy.identifier) <NEW_LINE> <DEDENT> sleep(5)
Simplisim Generator class.
62599049d6c5a102081e34c8
class AbstractCommand(PasswordPromptMixin, Command): <NEW_LINE> <INDENT> log = logging.getLogger(__name__) <NEW_LINE> save_strategy = SaveStrategy <NEW_LINE> get_strategy = GetStrategy <NEW_LINE> delete_strategy = SoftDeleteStrategy <NEW_LINE> skip_fields = ['remote_instance'] <NEW_LINE> def __init__(self, app, app_args, cmd_name=None): <NEW_LINE> <INDENT> super(AbstractCommand, self).__init__(app, app_args, cmd_name) <NEW_LINE> self.config = Config(self) <NEW_LINE> self.storage = ApplicationStorage( self, save_strategy=self.save_strategy, get_strategy=self.get_strategy, delete_strategy=self.delete_strategy ) <NEW_LINE> <DEDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(AbstractCommand, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( '--log-file', help='record output to FILE' ) <NEW_LINE> return self.extend_parser(parser) <NEW_LINE> <DEDENT> def extend_parser(self, parser): <NEW_LINE> <INDENT> return parser
Abstract Command with log.
6259904924f1403a926862a3
class TestRunme(unittest.TestCase): <NEW_LINE> <INDENT> def test_main_on_sample_in(self): <NEW_LINE> <INDENT> with io.StringIO() as target_output_stream: <NEW_LINE> <INDENT> sys.stdout, old_stdout = target_output_stream, sys.stdout <NEW_LINE> runme.main('sample.in') <NEW_LINE> from_main = target_output_stream.getvalue() <NEW_LINE> sys.stdout = old_stdout <NEW_LINE> <DEDENT> with open('sample.out', 'r', encoding='utf-8') as sample_out: <NEW_LINE> <INDENT> from_sample_out = sample_out.read() <NEW_LINE> <DEDENT> self.assertEqual(from_main, from_sample_out)
Simple tests for the Safety in Numbers problem for Google Code Jam 2012 Round 1B
62599049d7e4931a7ef3d423
class UploadToPathAndRenameTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.upload_to_path_and_rename = utils.UploadToPathAndRename('test') <NEW_LINE> self.instance = DummyInstance() <NEW_LINE> <DEDENT> def test_extension_preserved(self): <NEW_LINE> <INDENT> result = self.upload_to_path_and_rename(self.instance, "filename.jpg") <NEW_LINE> ext = result.split('.')[-1] <NEW_LINE> self.assertEqual(ext, 'jpg', "New filename has wrong extension") <NEW_LINE> <DEDENT> def test_path_appended(self): <NEW_LINE> <INDENT> result = self.upload_to_path_and_rename(self.instance, "filename.jpg") <NEW_LINE> path = result.split('/')[0] <NEW_LINE> self.assertEqual(path, 'test', "New filename has wrong path") <NEW_LINE> <DEDENT> def test_instance_with_no_pk(self): <NEW_LINE> <INDENT> result = self.upload_to_path_and_rename(self.instance, "filename.jpg") <NEW_LINE> generated_uuid_string = result.split('/')[1].split('.')[0] <NEW_LINE> generated_uuid = uuid.UUID(generated_uuid_string, version=4) <NEW_LINE> self.assertNotEqual(generated_uuid, self.instance.pk, "New filename did not get a random UUID") <NEW_LINE> <DEDENT> def test_instance_with_uuid_pk(self): <NEW_LINE> <INDENT> self.instance.pk = uuid.uuid4() <NEW_LINE> result = self.upload_to_path_and_rename(self.instance, "filename.jpg") <NEW_LINE> generated_uuid_string = result.split('/')[1].split('.')[0] <NEW_LINE> generated_uuid = uuid.UUID(generated_uuid_string, version=4) <NEW_LINE> self.assertEqual(generated_uuid, self.instance.pk, "New filename does not match UUID of instance") <NEW_LINE> <DEDENT> def test_insance_with_non_uuid_pk(self): <NEW_LINE> <INDENT> self.instance.pk = "test" <NEW_LINE> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> self.upload_to_path_and_rename(self.instance, "filename.jpg")
Tests for utils.UploadToPathAndRename
6259904910dbd63aa1c71f88
class TestRead: <NEW_LINE> <INDENT> def test_read_slack(self, testfs_ntfs_stable1): <NEW_LINE> <INDENT> for img_path in testfs_ntfs_stable1: <NEW_LINE> <INDENT> with open(img_path, 'rb+') as img: <NEW_LINE> <INDENT> ntfs = MftSlack(img_path, img) <NEW_LINE> teststring = "This is a simple write test." <NEW_LINE> with io.BytesIO() as mem: <NEW_LINE> <INDENT> mem.write(teststring.encode('utf-8')) <NEW_LINE> mem.seek(0) <NEW_LINE> with io.BufferedReader(mem) as reader: <NEW_LINE> <INDENT> write_res = ntfs.write(reader) <NEW_LINE> <DEDENT> <DEDENT> ntfs = MftSlack(img_path, img) <NEW_LINE> with io.BytesIO() as mem: <NEW_LINE> <INDENT> ntfs.read(mem, write_res) <NEW_LINE> mem.seek(0) <NEW_LINE> result = mem.read() <NEW_LINE> assert result.decode('utf-8') == teststring
Test reading slackspace
62599049a79ad1619776b42d
class Menu(models.Model): <NEW_LINE> <INDENT> name = models.CharField(unique=True, max_length=32, verbose_name="菜单名") <NEW_LINE> url_type = models.SmallIntegerField(choices=((0, 'relative_name'), (1, 'absolute_url')), verbose_name="菜单类型") <NEW_LINE> url_name = models.CharField(unique=True, max_length=128) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "动态菜单" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name
动态菜单
6259904915baa7234946333e
class OpenUvEntity(Entity): <NEW_LINE> <INDENT> def __init__(self, openuv): <NEW_LINE> <INDENT> self._attrs = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION} <NEW_LINE> self._name = None <NEW_LINE> self.openuv = openuv <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> return self._attrs <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name
Define a generic OpenUV entity.
62599049b57a9660fecd2e29
class ChimeraStats(object): <NEW_LINE> <INDENT> pass
stats used to assess quality of chimera
6259904930c21e258be99bb3
class ASTProcessor(object, metaclass=ASTProcessorMeta): <NEW_LINE> <INDENT> def __call__(self, node, **kw): <NEW_LINE> <INDENT> return getattr(self, node.__class__.__name__)(node, **kw)
The class hides the need to specify ASTProcessorMeta metaclass
62599049287bf620b6272f96
class HipchatAlerter(base.AlerterBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._async_client = None <NEW_LINE> <DEDENT> def _get_client(self): <NEW_LINE> <INDENT> if not self._async_client: <NEW_LINE> <INDENT> self._async_client = httpclient.AsyncHTTPClient() <NEW_LINE> log.debug('Generating a new client: %s' % self._async_client) <NEW_LINE> <DEDENT> return self._async_client <NEW_LINE> <DEDENT> def style_from_state(self, state): <NEW_LINE> <INDENT> styles = { states.OK: ('green', 'successful'), states.ERROR: ('red', 'failed') } <NEW_LINE> default = ('gray', 'unknown') <NEW_LINE> return styles.get(state) or default <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def _alert(self, path, state, message, params): <NEW_LINE> <INDENT> http_client = self._get_client() <NEW_LINE> color, icon = self.style_from_state(state) <NEW_LINE> hc_body = { 'auth_token': params['token'], 'room_id': params['room'], 'from': params.get('from', 'ZK Monitor'), 'color': color, 'message_format': 'text', 'message': '(%s) %s is in %s - %s' % (icon, path, state, message)} <NEW_LINE> hc_safe_body = urllib.urlencode(hc_body) <NEW_LINE> log.debug('URL: %s' % HIPCHAT_API_URL) <NEW_LINE> log.debug('BODY: %s' % hc_safe_body) <NEW_LINE> request = httpclient.HTTPRequest( url=HIPCHAT_API_URL, method='POST', body=hc_safe_body) <NEW_LINE> log.debug('Fetching RESTful api call: %s' % request) <NEW_LINE> log.debug('client: %s' % http_client) <NEW_LINE> http_client.fetch(request, self._handle_request) <NEW_LINE> <DEDENT> def _handle_request(self, response): <NEW_LINE> <INDENT> if response.error: <NEW_LINE> <INDENT> log.error('Response had an error: %s' % response.error) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.debug('Response successful: %s' % response.body) <NEW_LINE> <DEDENT> return not response.error
Send a notification to a HipChat room. For more details read the AlerterBase documentation. Expects the following configured alerter: >>> /services/food/barn alerter: hipchat: - room: Engineering - from: zk_monitor - token: <token> children: 1 The "from" parameter will default to 'ZK Monitor' if not specified.
6259904926238365f5fadf0a