code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ApplicationIdentifiersCollectorTest(shared_test_lib.BaseTestCase): <NEW_LINE> <INDENT> def _CreateTestRegistry(self): <NEW_LINE> <INDENT> key_path_prefix = 'HKEY_LOCAL_MACHINE\\Software' <NEW_LINE> registry_file = dfwinreg_fake.FakeWinRegistryFile( key_path_prefix=key_path_prefix) <NEW_LINE> registry_key = dfwinreg_fake.FakeWinRegistryKey( '{fd6c8b29-e936-4a61-8da6-b0c12ad3ba00}') <NEW_LINE> registry_file.AddKeyByPath('\\Classes\\AppID', registry_key) <NEW_LINE> value_data = 'Wordpad'.encode('utf-16-le') <NEW_LINE> registry_value = dfwinreg_fake.FakeWinRegistryValue( '', data=value_data, data_type=dfwinreg_definitions.REG_SZ) <NEW_LINE> registry_key.AddValue(registry_value) <NEW_LINE> registry_file.Open(None) <NEW_LINE> registry = dfwinreg_registry.WinRegistry() <NEW_LINE> registry.MapFile(key_path_prefix, registry_file) <NEW_LINE> return registry <NEW_LINE> <DEDENT> def testCollect(self): <NEW_LINE> <INDENT> registry = self._CreateTestRegistry() <NEW_LINE> collector_object = application_identifiers.ApplicationIdentifiersCollector() <NEW_LINE> test_results = list(collector_object.Collect(registry)) <NEW_LINE> self.assertEqual(len(test_results), 1) <NEW_LINE> application_identifier = test_results[0] <NEW_LINE> self.assertIsNotNone(application_identifier) <NEW_LINE> self.assertEqual(application_identifier.description, 'Wordpad') <NEW_LINE> self.assertEqual( application_identifier.guid, '{fd6c8b29-e936-4a61-8da6-b0c12ad3ba00}') <NEW_LINE> <DEDENT> def testCollectEmpty(self): <NEW_LINE> <INDENT> registry = dfwinreg_registry.WinRegistry() <NEW_LINE> collector_object = application_identifiers.ApplicationIdentifiersCollector() <NEW_LINE> test_results = list(collector_object.Collect(registry)) <NEW_LINE> self.assertEqual(len(test_results), 0)
Tests for the Windows application identifiers (AppID) collector.
625990777047854f46340d3f
class Statistics(models.Model): <NEW_LINE> <INDENT> total_clients = models.BigIntegerField(default=0, help_text='total of clients ' 'served until today') <NEW_LINE> max_concurrent_clients = models.IntegerField(default=0, help_text='max concurrent ' 'clients ever') <NEW_LINE> max_concurrent_domains = models.IntegerField(default=0, help_text='max_concurrent' 'domains ever') <NEW_LINE> total_messages_broadcasted = models.BigIntegerField(default=0, help_text='total' 'messaged broadcasted' 'until today') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = 'statistics'
Holds simple stats about the application, such as, total clients served maximum concurrent clients ever served.
62599077009cb60464d02ec2
class CommandRollershutter(RollershutterDevice): <NEW_LINE> <INDENT> def __init__(self, hass, name, command_up, command_down, command_stop, command_state, value_template): <NEW_LINE> <INDENT> self._hass = hass <NEW_LINE> self._name = name <NEW_LINE> self._state = None <NEW_LINE> self._command_up = command_up <NEW_LINE> self._command_down = command_down <NEW_LINE> self._command_stop = command_stop <NEW_LINE> self._command_state = command_state <NEW_LINE> self._value_template = value_template <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _move_rollershutter(command): <NEW_LINE> <INDENT> _LOGGER.info('Running command: %s', command) <NEW_LINE> success = (subprocess.call(command, shell=True) == 0) <NEW_LINE> if not success: <NEW_LINE> <INDENT> _LOGGER.error('Command failed: %s', command) <NEW_LINE> <DEDENT> return success <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _query_state_value(command): <NEW_LINE> <INDENT> _LOGGER.info('Running state command: %s', command) <NEW_LINE> try: <NEW_LINE> <INDENT> return_value = subprocess.check_output(command, shell=True) <NEW_LINE> return return_value.strip().decode('utf-8') <NEW_LINE> <DEDENT> except subprocess.CalledProcessError: <NEW_LINE> <INDENT> _LOGGER.error('Command failed: %s', command) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return self._command_state is not None <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def current_position(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> def _query_state(self): <NEW_LINE> <INDENT> if not self._command_state: <NEW_LINE> <INDENT> _LOGGER.error('No state command specified') <NEW_LINE> return <NEW_LINE> <DEDENT> return self._query_state_value(self._command_state) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self._command_state: <NEW_LINE> <INDENT> payload = str(self._query_state()) <NEW_LINE> if self._value_template: <NEW_LINE> <INDENT> payload = template.render_with_possible_json_value( self._hass, self._value_template, payload) <NEW_LINE> <DEDENT> self._state = int(payload) <NEW_LINE> <DEDENT> <DEDENT> def move_up(self, **kwargs): <NEW_LINE> <INDENT> self._move_rollershutter(self._command_up) <NEW_LINE> <DEDENT> def move_down(self, **kwargs): <NEW_LINE> <INDENT> self._move_rollershutter(self._command_down) <NEW_LINE> <DEDENT> def stop(self, **kwargs): <NEW_LINE> <INDENT> self._move_rollershutter(self._command_stop)
Represents a rollershutter - can be controlled using shell cmd.
625990777047854f46340d40
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) <NEW_LINE> class GroupAdminTest(TestCase): <NEW_LINE> <INDENT> urls = "admin_views.urls" <NEW_LINE> fixtures = ['admin-views-users.xml'] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.client.login(username='super', password='secret') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.client.logout() <NEW_LINE> <DEDENT> def test_save_button(self): <NEW_LINE> <INDENT> group_count = Group.objects.count() <NEW_LINE> response = self.client.post('/test_admin/admin/auth/group/add/', { 'name': 'newgroup', }) <NEW_LINE> Group.objects.order_by('-id')[0] <NEW_LINE> self.assertRedirects(response, '/test_admin/admin/auth/group/') <NEW_LINE> self.assertEqual(Group.objects.count(), group_count + 1) <NEW_LINE> <DEDENT> def test_group_permission_performance(self): <NEW_LINE> <INDENT> g = Group.objects.create(name="test_group") <NEW_LINE> expected_queries = 8 <NEW_LINE> if connection.vendor == 'oracle': <NEW_LINE> <INDENT> expected_queries -= 1 <NEW_LINE> <DEDENT> with self.assertNumQueries(expected_queries): <NEW_LINE> <INDENT> response = self.client.get('/test_admin/admin/auth/group/%s/' % g.pk) <NEW_LINE> self.assertEqual(response.status_code, 200)
Tests group CRUD functionality.
625990777cff6e4e811b73c6
class MissingPlaceholder(BlueprintWithNameException): <NEW_LINE> <INDENT> def __init__( self, domain: str, blueprint_name: str, placeholder_names: Iterable[str] ) -> None: <NEW_LINE> <INDENT> super().__init__( domain, blueprint_name, f"Missing placeholder {', '.join(sorted(placeholder_names))}", )
When we miss a placeholder.
625990775fc7496912d48f2d
class CustomSettingsTestCase(TestCase): <NEW_LINE> <INDENT> new_settings = {} <NEW_LINE> _override = None <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls._override = override_settings(**cls.new_settings) <NEW_LINE> cls._override.enable() <NEW_LINE> if 'INSTALLED_APPS' in cls.new_settings: <NEW_LINE> <INDENT> cls.syncdb() <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> cls._override.disable() <NEW_LINE> if 'INSTALLED_APPS' in cls.new_settings: <NEW_LINE> <INDENT> cls.syncdb() <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def syncdb(cls): <NEW_LINE> <INDENT> loading.cache.loaded = False <NEW_LINE> call_command('syncdb', verbosity=0)
A TestCase which makes extra models available in the Django project, just for testing. Based on http://djangosnippets.org/snippets/1011/ in Django 1.4 style.
625990777b180e01f3e49d28
class linux_pslist(linux_common.AbstractLinuxCommand): <NEW_LINE> <INDENT> def __init__(self, config, *args, **kwargs): <NEW_LINE> <INDENT> linux_common.AbstractLinuxCommand.__init__(self, config, *args, **kwargs) <NEW_LINE> config.add_option('PID', short_option = 'p', default = None, help = 'Operate on these Process IDs (comma-separated)', action = 'store', type = 'str') <NEW_LINE> <DEDENT> def calculate(self): <NEW_LINE> <INDENT> linux_common.set_plugin_members(self) <NEW_LINE> init_task_addr = self.addr_space.profile.get_symbol("init_task") <NEW_LINE> init_task = obj.Object("task_struct", vm = self.addr_space, offset = init_task_addr) <NEW_LINE> pidlist = self._config.PID <NEW_LINE> if pidlist: <NEW_LINE> <INDENT> pidlist = [int(p) for p in self._config.PID.split(',')] <NEW_LINE> <DEDENT> for task in init_task.tasks: <NEW_LINE> <INDENT> if not pidlist or task.pid in pidlist: <NEW_LINE> <INDENT> yield task <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def render_text(self, outfd, data): <NEW_LINE> <INDENT> self.table_header(outfd, [("Offset", "[addrpad]"), ("Name", "20"), ("Pid", "15"), ("Uid", "15"), ("Gid", "6"), ("DTB", "[addrpad]"), ("Start Time", "")]) <NEW_LINE> for task in data: <NEW_LINE> <INDENT> if task.mm.pgd == None: <NEW_LINE> <INDENT> dtb = task.mm.pgd <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dtb = self.addr_space.vtop(task.mm.pgd) or task.mm.pgd <NEW_LINE> <DEDENT> self.table_row(outfd, task.obj_offset, task.comm, str(task.pid), str(task.uid) if task.uid else "-", str(task.gid) if task.gid else "-", dtb, task.get_task_start_time())
Gather active tasks by walking the task_struct->task list
62599077fff4ab517ebcf19e
class Trampa(Objeto): <NEW_LINE> <INDENT> def __init__(self, nombre, texto, ejecucion, desarme, suicidio): <NEW_LINE> <INDENT> super(Trampa, self).__init__(nombre, True) <NEW_LINE> self.texto = texto <NEW_LINE> self.ejecucion = ejecucion <NEW_LINE> self.desarme = desarme <NEW_LINE> self.suicidio = suicidio <NEW_LINE> <DEDENT> def ejecutar_accion(self, activo, pasivo): <NEW_LINE> <INDENT> _str = self.texto.format(activo.nombre, pasivo.nombre) + ". " <NEW_LINE> interaccion = activo.buscar_interaccion(pasivo) <NEW_LINE> if interaccion is not None: <NEW_LINE> <INDENT> _str += ( "Pero " + activo.nombre + " recuerda cuando " + interaccion.identificador + " con " + pasivo.nombre + " y opta por quitar la trampa." ) <NEW_LINE> activo.quitar_interaccion(interaccion) <NEW_LINE> return _str, None <NEW_LINE> <DEDENT> r = random.randrange(0, 100) <NEW_LINE> if r <= 40: <NEW_LINE> <INDENT> _str += self.ejecucion.format(activo.nombre, pasivo.nombre) <NEW_LINE> activo.agregar_asesinato(pasivo) <NEW_LINE> return _str, pasivo <NEW_LINE> <DEDENT> elif r > 40 or r <= 80: <NEW_LINE> <INDENT> _str += self.desarme.format(activo.nombre, pasivo.nombre) <NEW_LINE> return _str, None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _str += self.suicidio.format(activo.nombre, pasivo.nombre) <NEW_LINE> pasivo.agregar_asesinato(activo) <NEW_LINE> return _str, activo
Clase que representa a los objetos trampa. Son objetos utilizables por los tributos, siempre son consumibles, y poseen tres posibles resultados. Parametros: @texto: str. Texto desplegado al usar la trampa @ejecucion: str. Texto usado cuando el arma tiene exito. @desarme: str. Texto usado cuando el objetivo logra evitar la trampa. @suicidio: str. Texto usado cuando el tributo cae en su propia trampa.
6259907763b5f9789fe86aec
class LasagneMnistConvExample(ConvNet): <NEW_LINE> <INDENT> def _build_middle(self, l_in, **_): <NEW_LINE> <INDENT> return super(LasagneMnistConvExample, self)._build_middle( l_in, num_conv_layers=2, num_dense_layers=1, lc0_num_filters=32, lc0_filter_size=(5, 5), lc1_num_filters=32, lc1_filter_size=(5, 5), ld0_num_units=256 )
Builder of Lasagne's MNIST basic CNN example (examples/mnist_conv.py). The network's architecture is: in -> conv(5, 5) x 32 -> max-pool(2, 2) -> conv(5, 5) x 32 -> max-pool(2, 2) -> dense (256) -> dropout -> out.
625990774527f215b58eb664
class Hero: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.positive_effects = [] <NEW_LINE> self.negative_effects = [] <NEW_LINE> self.stats = { "HP": 128, "MP": 42, "SP": 100, "Strength": 15, "Perception": 4, "Endurance": 8, "Charisma": 2, "Intelligence": 3, "Agility": 8, "Luck": 1 } <NEW_LINE> <DEDENT> def get_positive_effects(self): <NEW_LINE> <INDENT> return self.positive_effects.copy() <NEW_LINE> <DEDENT> def get_negative_effects(self): <NEW_LINE> <INDENT> return self.negative_effects.copy() <NEW_LINE> <DEDENT> def get_stats(self): <NEW_LINE> <INDENT> return self.stats.copy()
Given class.
6259907797e22403b383c88a
class FlakyRetryPolicy(RetryPolicy): <NEW_LINE> <INDENT> def __init__(self, max_retries=5): <NEW_LINE> <INDENT> self.max_retries = max_retries <NEW_LINE> <DEDENT> def on_read_timeout(self, *args, **kwargs): <NEW_LINE> <INDENT> if kwargs['retry_num'] < self.max_retries: <NEW_LINE> <INDENT> logger.debug("Retrying read after timeout. Attempt #" + str(kwargs['retry_num'])) <NEW_LINE> return (self.RETRY, None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self.RETHROW, None) <NEW_LINE> <DEDENT> <DEDENT> def on_write_timeout(self, *args, **kwargs): <NEW_LINE> <INDENT> if kwargs['retry_num'] < self.max_retries: <NEW_LINE> <INDENT> logger.debug("Retrying write after timeout. Attempt #" + str(kwargs['retry_num'])) <NEW_LINE> return (self.RETRY, None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self.RETHROW, None) <NEW_LINE> <DEDENT> <DEDENT> def on_unavailable(self, *args, **kwargs): <NEW_LINE> <INDENT> if kwargs['retry_num'] < self.max_retries: <NEW_LINE> <INDENT> logger.debug("Retrying request after UE. Attempt #" + str(kwargs['retry_num'])) <NEW_LINE> return (self.RETRY, None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self.RETHROW, None)
A retry policy that retries 5 times by default, but can be configured to retry more times.
62599077ec188e330fdfa22e
class AuthException(AiopogoError): <NEW_LINE> <INDENT> pass
Raised when logging in fails
625990774a966d76dd5f0872
@benchmark.Disabled('reference') <NEW_LINE> class V8InfiniteScrollIgnition(V8InfiniteScroll): <NEW_LINE> <INDENT> def SetExtraBrowserOptions(self, options): <NEW_LINE> <INDENT> super(V8InfiniteScrollIgnition, self).SetExtraBrowserOptions(options) <NEW_LINE> v8_helper.EnableIgnition(options) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def Name(cls): <NEW_LINE> <INDENT> return 'v8.infinite_scroll-ignition_tbmv2'
Measures V8 GC metrics using Ignition.
6259907766673b3332c31d87
class Piecewise1D(object): <NEW_LINE> <INDENT> def __init__(self, x_grid, x_interp): <NEW_LINE> <INDENT> if not np.all(x_grid[1:] > x_grid[:-1]): <NEW_LINE> <INDENT> raise ValueError("x_grid must be sorted in ascending order") <NEW_LINE> <DEDENT> self.x_grid = x_grid <NEW_LINE> self.x_interp = x_interp <NEW_LINE> self.index = np.searchsorted(x_grid, x_interp) - 1 <NEW_LINE> <DEDENT> def __call__(self, y_grid): <NEW_LINE> <INDENT> x_grid = self.x_grid <NEW_LINE> x_interp = self.x_interp <NEW_LINE> a = (y_grid[1:] - y_grid[:-1]) / (x_grid[1:] - x_grid[:-1]) <NEW_LINE> b = y_grid[1:] - a * x_grid[1:] <NEW_LINE> return a.take(self.index) * x_interp + b.take(self.index)
Fast piecewise linear interpolation in one dimension. Optimized for the special case that the interpolation is done many times on the same positions, on datapoints with a constant x grid, but varying y values. Parameters ---------- x_grid : ndarray Horizontal (x) grid on which the datapoints will be given x_interp : ndarray Values on which interpolation will be performed
625990779c8ee82313040e4b
class Endpoints(ApiObject): <NEW_LINE> <INDENT> obj_type = client.V1Endpoints <NEW_LINE> api_clients = { "preferred": client.CoreV1Api, "v1": client.CoreV1Api, } <NEW_LINE> def create(self, namespace: str = None) -> None: <NEW_LINE> <INDENT> if namespace is None: <NEW_LINE> <INDENT> namespace = self.namespace <NEW_LINE> <DEDENT> log.info(f'creating endpoints "{self.name}" in namespace "{self.namespace}"') <NEW_LINE> log.debug(f"endpoints: {self.obj}") <NEW_LINE> self.obj = self.api_client.create_namespaced_endpoints( namespace=namespace, body=self.obj, ) <NEW_LINE> <DEDENT> def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status: <NEW_LINE> <INDENT> if options is None: <NEW_LINE> <INDENT> options = client.V1DeleteOptions() <NEW_LINE> <DEDENT> log.info(f'deleting endpoints "{self.name}"') <NEW_LINE> log.debug(f"delete options: {options}") <NEW_LINE> log.debug(f"endpoints: {self.obj}") <NEW_LINE> return self.api_client.delete_namespaced_endpoints( name=self.name, namespace=self.namespace, body=options, ) <NEW_LINE> <DEDENT> def refresh(self) -> None: <NEW_LINE> <INDENT> self.obj = self.api_client.read_namespaced_endpoints( name=self.name, namespace=self.namespace, ) <NEW_LINE> <DEDENT> def is_ready(self) -> bool: <NEW_LINE> <INDENT> self.refresh() <NEW_LINE> if self.obj.subsets is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for subset in self.obj.subsets: <NEW_LINE> <INDENT> if ( subset.not_ready_addresses is not None and len(subset.not_ready_addresses) > 0 ): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Kubetest wrapper around a Kubernetes `Endpoints`_ API Object. The actual ``kubernetes.client.V1Endpoints`` instance that this wraps can be accessed via the ``obj`` instance member. This wrapper provides some convenient functionality around the API Object and provides some state management for the `Endpoints`_. .. _Endpoints: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.18/#endpoints-v1-core
62599077283ffb24f3cf5233
class Pendulum(ODEsim): <NEW_LINE> <INDENT> def __init__(self, ax, g, l, phi, omega, x0, y0): <NEW_LINE> <INDENT> self.ax = ax <NEW_LINE> self.g = g <NEW_LINE> self.l = l <NEW_LINE> self.state = np.array([phi, omega]) <NEW_LINE> self.x0 = x0 <NEW_LINE> self.y0 = y0 <NEW_LINE> self.line, = ax.plot([], [], 'o-', lw=2) <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> self.line.set_data([],[]) <NEW_LINE> return self.line, <NEW_LINE> <DEDENT> def F(self, state): <NEW_LINE> <INDENT> dOmega = - self.g / self.l * sin(state[0]) <NEW_LINE> dPhi = state[1] <NEW_LINE> dState = np.array([dPhi, dOmega]) <NEW_LINE> return dState <NEW_LINE> <DEDENT> def calculateCoordinates(self): <NEW_LINE> <INDENT> self.xCoords=[self.x0, self.x0 + self.l* sin(self.state[0])] <NEW_LINE> self.yCoords=[self.y0, self.y0 - self.l* cos(self.state[0])] <NEW_LINE> <DEDENT> def drawing(self): <NEW_LINE> <INDENT> self.calculateCoordinates() <NEW_LINE> self.line.set_data(self.xCoords,self.yCoords) <NEW_LINE> return self.line,
Simulation of a pendulum
62599077097d151d1a2c29fe
class UserSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = get_user_model() <NEW_LINE> fields = ('email', 'password', 'name') <NEW_LINE> extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> return get_user_model().objects.create_user(**validated_data) <NEW_LINE> <DEDENT> def update(self, instance, validated_data): <NEW_LINE> <INDENT> password = validated_data.pop('password', None) <NEW_LINE> user = super().update(instance, validated_data) <NEW_LINE> if password: <NEW_LINE> <INDENT> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> <DEDENT> return user
Serializer para objecto user
62599077d268445f2663a822
class CourseUpdatesView(CourseTabView): <NEW_LINE> <INDENT> @method_decorator(login_required) <NEW_LINE> @method_decorator(cache_control(no_cache=True, no_store=True, must_revalidate=True)) <NEW_LINE> def get(self, request, course_id, **kwargs): <NEW_LINE> <INDENT> return super(CourseUpdatesView, self).get(request, course_id, 'courseware', **kwargs) <NEW_LINE> <DEDENT> def uses_bootstrap(self, request, course, tab): <NEW_LINE> <INDENT> return USE_BOOTSTRAP_FLAG.is_enabled(course.id) <NEW_LINE> <DEDENT> def render_to_fragment(self, request, course=None, tab=None, **kwargs): <NEW_LINE> <INDENT> course_id = unicode(course.id) <NEW_LINE> updates_fragment_view = CourseUpdatesFragmentView() <NEW_LINE> return updates_fragment_view.render_to_fragment(request, course_id=course_id, **kwargs)
The course updates page.
6259907716aa5153ce401e63
class ClearPresetStatus(OptionalParameterTestFixture): <NEW_LINE> <INDENT> CATEGORY = TestCategory.CONTROL <NEW_LINE> PID = 'PRESET_STATUS' <NEW_LINE> REQUIRES = ['scene_writable_states', 'preset_info'] <NEW_LINE> def Test(self): <NEW_LINE> <INDENT> self.scene = None <NEW_LINE> scene_writable_states = self.Property('scene_writable_states') <NEW_LINE> if scene_writable_states is not None: <NEW_LINE> <INDENT> for scene_number, is_writeable in scene_writable_states.items(): <NEW_LINE> <INDENT> if is_writeable: <NEW_LINE> <INDENT> self.scene = scene_number <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self.scene is None: <NEW_LINE> <INDENT> self.SetNotRun('No writeable scenes found') <NEW_LINE> return <NEW_LINE> <DEDENT> self.AddIfSetSupported(self.AckSetResult(action=self.VerifySet)) <NEW_LINE> self.SendSet(ROOT_DEVICE, self.pid, [self.scene, 10, 10, 20, True]) <NEW_LINE> <DEDENT> def VerifySet(self): <NEW_LINE> <INDENT> self.AddExpectedResults(self.AckGetResult(field_values={ 'up_fade_time': 0.0, 'wait_time': 0.0, 'scene_number': self.scene, 'programmed': 0, 'down_fade_time': 0.0, })) <NEW_LINE> self.SendGet(ROOT_DEVICE, self.pid, [self.scene])
Set the PRESET_STATUS with clear preset = 1
6259907799fddb7c1ca63a9a
class KsotpGateway(VtGateway): <NEW_LINE> <INDENT> def __init__(self, eventEngine, gatewayName='KSOTP'): <NEW_LINE> <INDENT> super(KsotpGateway, self).__init__(eventEngine, gatewayName) <NEW_LINE> self.mdApi = KsotpMdApi(self) <NEW_LINE> self.tdApi = KsotpTdApi(self) <NEW_LINE> self.mdConnected = False <NEW_LINE> self.tdConnected = False <NEW_LINE> self.qryEnabled = False <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> fileName = self.gatewayName + '_connect.json' <NEW_LINE> path = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> fileName = os.path.join(path, fileName) <NEW_LINE> try: <NEW_LINE> <INDENT> f = file(fileName) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> log = VtLogData() <NEW_LINE> log.gatewayName = self.gatewayName <NEW_LINE> log.logContent = '读取连接配置出错,请检查' <NEW_LINE> self.onLog(log) <NEW_LINE> return <NEW_LINE> <DEDENT> setting = json.load(f) <NEW_LINE> try: <NEW_LINE> <INDENT> userID = str(setting['userID']) <NEW_LINE> password = str(setting['password']) <NEW_LINE> brokerID = str(setting['brokerID']) <NEW_LINE> tdAddress = str(setting['tdAddress']) <NEW_LINE> mdAddress = str(setting['mdAddress']) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> log = VtLogData() <NEW_LINE> log.gatewayName = self.gatewayName <NEW_LINE> log.logContent = '连接配置缺少字段,请检查' <NEW_LINE> self.onLog(log) <NEW_LINE> return <NEW_LINE> <DEDENT> self.mdApi.connect(userID, password, brokerID, mdAddress) <NEW_LINE> self.tdApi.connect(userID, password, brokerID, tdAddress) <NEW_LINE> self.initQuery() <NEW_LINE> <DEDENT> def subscribe(self, subscribeReq): <NEW_LINE> <INDENT> self.mdApi.subscribe(subscribeReq) <NEW_LINE> <DEDENT> def sendOrder(self, orderReq): <NEW_LINE> <INDENT> return self.tdApi.sendOrder(orderReq) <NEW_LINE> <DEDENT> def cancelOrder(self, cancelOrderReq): <NEW_LINE> <INDENT> self.tdApi.cancelOrder(cancelOrderReq) <NEW_LINE> <DEDENT> def qryAccount(self): <NEW_LINE> <INDENT> self.tdApi.qryAccount() <NEW_LINE> <DEDENT> def qryPosition(self): <NEW_LINE> <INDENT> self.tdApi.qryPosition() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self.mdConnected: <NEW_LINE> <INDENT> self.mdApi.close() <NEW_LINE> <DEDENT> if self.tdConnected: <NEW_LINE> <INDENT> self.tdApi.close() <NEW_LINE> <DEDENT> <DEDENT> def initQuery(self): <NEW_LINE> <INDENT> if self.qryEnabled: <NEW_LINE> <INDENT> self.qryFunctionList = [self.qryAccount, self.qryPosition] <NEW_LINE> self.qryCount = 0 <NEW_LINE> self.qryTrigger = 2 <NEW_LINE> self.qryNextFunction = 0 <NEW_LINE> self.startQuery() <NEW_LINE> <DEDENT> <DEDENT> def query(self, event): <NEW_LINE> <INDENT> self.qryCount += 1 <NEW_LINE> if self.qryCount > self.qryTrigger: <NEW_LINE> <INDENT> self.qryCount = 0 <NEW_LINE> function = self.qryFunctionList[self.qryNextFunction] <NEW_LINE> function() <NEW_LINE> self.qryNextFunction += 1 <NEW_LINE> if self.qryNextFunction == len(self.qryFunctionList): <NEW_LINE> <INDENT> self.qryNextFunction = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def startQuery(self): <NEW_LINE> <INDENT> self.eventEngine.register(EVENT_TIMER, self.query) <NEW_LINE> <DEDENT> def setQryEnabled(self, qryEnabled): <NEW_LINE> <INDENT> self.qryEnabled = qryEnabled
金仕达期权接口
6259907701c39578d7f143f9
class ADDON(object): <NEW_LINE> <INDENT> NAME = "Visual Feedback for Reviews" <NEW_LINE> MODULE = "review_feedback" <NEW_LINE> ID = "1749604199" <NEW_LINE> VERSION = __version__ <NEW_LINE> LICENSE = "GNU AGPLv3" <NEW_LINE> AUTHORS = ( { "name": "Aristotelis P. (Glutanimate)", "years": "2017-2020", "contact": "Glutanimate", }, ) <NEW_LINE> AUTHOR_MAIL = "ankiglutanimate [αt] gmail . com" <NEW_LINE> LIBRARIES = () <NEW_LINE> CONTRIBUTORS = () <NEW_LINE> SPONSORS = () <NEW_LINE> MEMBERS_CREDITED = MEMBERS_CREDITED <NEW_LINE> MEMBERS_TOP = MEMBERS_TOP <NEW_LINE> LINKS = { "patreon": "https://www.patreon.com/glutanimate", "bepatron": "https://www.patreon.com/bePatron?u=7522179", "coffee": "http://ko-fi.com/glutanimate", "description": "https://ankiweb.net/shared/info/{}".format(ID), "rate": "https://ankiweb.net/shared/review/{}".format(ID), "twitter": "https://twitter.com/glutanimate", "youtube": "https://www.youtube.com/c/glutanimate", "help": "", }
Class storing general add-on properties Property names need to be all-uppercase with no leading underscores
62599077442bda511e95da1c
class Envelope(xsd.ComplexType): <NEW_LINE> <INDENT> Header = xsd.Element(Header, nillable=True) <NEW_LINE> Body = xsd.Element(Body) <NEW_LINE> @classmethod <NEW_LINE> def response(cls, tagname, return_object, header=None): <NEW_LINE> <INDENT> envelope = cls() <NEW_LINE> if header is not None: <NEW_LINE> <INDENT> envelope.Header = header <NEW_LINE> <DEDENT> envelope.Body = Body() <NEW_LINE> envelope.Body.message = xsd.NamedType(name=tagname, value=return_object) <NEW_LINE> return envelope.xml('Envelope', namespace=ENVELOPE_NAMESPACE, elementFormDefault=xsd.ElementFormDefault.QUALIFIED) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def error_response(cls, code, message, header=None, actor=None): <NEW_LINE> <INDENT> envelope = cls() <NEW_LINE> if header is not None: <NEW_LINE> <INDENT> envelope.Header = header <NEW_LINE> <DEDENT> envelope.Body = Body() <NEW_LINE> code = Code(Value=code) <NEW_LINE> reason = Reason(Text=message) <NEW_LINE> envelope.Body.Fault = Fault(Code=code, Reason=reason, Role=actor) <NEW_LINE> return envelope.xml('Envelope', namespace=ENVELOPE_NAMESPACE, elementFormDefault=xsd.ElementFormDefault.QUALIFIED)
SOAP Envelope.
625990773317a56b869bf20a
class InputMoveRequest(): <NEW_LINE> <INDENT> def __init__(self, direction, strafing=False, rotating=False): <NEW_LINE> <INDENT> self.direction = direction <NEW_LINE> self.strafing = strafing <NEW_LINE> self.rotating = rotating
sent from input controller to model
6259907755399d3f05627e9d
class View(Action): <NEW_LINE> <INDENT> pass
Definition associated with a model that represents the information to be used for the display of associated set of elements/items of a model.
6259907721bff66bcd7245f2
class station_info: <NEW_LINE> <INDENT> def GET(self): <NEW_LINE> <INDENT> web.header('Access-Control-Allow-Origin', '*') <NEW_LINE> web.header('Content-Type', 'application/json') <NEW_LINE> names = data('snames') <NEW_LINE> nlst = re.findall('[\'|"](.*?)[\'|"]', names) <NEW_LINE> jpinfo = {"snames":nlst,"ignore_rain":gv.sd['ir'],"masop":gv.sd['mo'],"maxlen":gv.sd['snlen']} <NEW_LINE> return json.dumps(jpinfo)
Returns station information as json.
625990774a966d76dd5f0874
class Configuration: <NEW_LINE> <INDENT> URL = os.environ["PROMETHEUS_HOST_URL"] <NEW_LINE> PROMETHEUS_SERVICE_ACCOUNT_TOKEN = os.environ["PROMETHEUS_SERVICE_ACCOUNT_TOKEN"] <NEW_LINE> HEADERS = {"Authorization": f"bearer {PROMETHEUS_SERVICE_ACCOUNT_TOKEN}"} <NEW_LINE> PROM = PrometheusConnect(url=URL, disable_ssl=True, headers=HEADERS) <NEW_LINE> THOTH_BACKEND_NAMESPACE = os.environ["THOTH_BACKEND_NAMESPACE"] <NEW_LINE> THOTH_MIDDLETIER_NAMESPACE = os.environ["THOTH_MIDDLETIER_NAMESPACE"] <NEW_LINE> THOTH_AMUN_INSPECTION_NAMESPACE = os.environ["THOTH_AMUN_INSPECTION_NAMESPACE"] <NEW_LINE> CEPH_ACCESS_KEY_ID = os.environ["THOTH_CEPH_KEY_ID"] <NEW_LINE> CEPH_ACCESS_SECRET_KEY = os.environ["THOTH_CEPH_SECRET_KEY"] <NEW_LINE> CEPH_BUCKET_PREFIX = os.environ["THOTH_CEPH_BUCKET_PREFIX"] <NEW_LINE> S3_ENDPOINT_URL = os.environ["THOTH_S3_ENDPOINT_URL"] <NEW_LINE> CEPH_BUCKET = os.environ["THOTH_CEPH_BUCKET"] <NEW_LINE> DEPLOYMENT_NAME = os.environ["THOTH_DEPLOYMENT_NAME"] <NEW_LINE> GITHUB_ACCESS_TOKEN = os.environ["GITHUB_ACCESS_TOKEN"]
Configuration of metrics-exporter.
625990774a966d76dd5f0875
class Meta: <NEW_LINE> <INDENT> model = BountyFulfillment <NEW_LINE> fields = ('fulfiller_address', 'fulfiller_email', 'fulfiller_github_username', 'fulfiller_name', 'fulfillment_id', 'accepted', 'profile', 'created_on', 'accepted_on', 'fulfiller_github_url')
Define the bounty fulfillment serializer metadata.
62599077ad47b63b2c5a91d8
class ProgressBar(WidgetInterface): <NEW_LINE> <INDENT> orientations = { 'left_to_right': gtk.PROGRESS_LEFT_TO_RIGHT, 'right_to_left': gtk.PROGRESS_RIGHT_TO_LEFT, 'bottom_to_top': gtk.PROGRESS_BOTTOM_TO_TOP, 'top_to_bottom': gtk.PROGRESS_TOP_TO_BOTTOM, } <NEW_LINE> def __init__(self, field_name, model_name, attrs=None): <NEW_LINE> <INDENT> super(ProgressBar, self).__init__(field_name, model_name, attrs=attrs) <NEW_LINE> self.widget = gtk.ProgressBar() <NEW_LINE> orientation = self.orientations.get(attrs.get('orientation', 'left_to_right'), gtk.PROGRESS_LEFT_TO_RIGHT) <NEW_LINE> self.widget.set_orientation(orientation) <NEW_LINE> <DEDENT> def display(self, record, field): <NEW_LINE> <INDENT> super(ProgressBar, self).display(record, field) <NEW_LINE> if not field: <NEW_LINE> <INDENT> self.widget.set_text('') <NEW_LINE> self.widget.set_fraction(0.0) <NEW_LINE> return False <NEW_LINE> <DEDENT> value = float(field.get(record) or 0.0) <NEW_LINE> digits = field.digits(record) <NEW_LINE> self.widget.set_text(locale.format('%.*f', (digits[1], value), True)) <NEW_LINE> self.widget.set_fraction(value / 100.0)
Progress Bar
62599077283ffb24f3cf5235
@implementer(IFile) <NEW_LINE> class File(Item): <NEW_LINE> <INDENT> def PUT(self, REQUEST=None, RESPONSE=None): <NEW_LINE> <INDENT> request = REQUEST if REQUEST is not None else self.REQUEST <NEW_LINE> response = RESPONSE if RESPONSE is not None else request.response <NEW_LINE> self.dav__init(request, response) <NEW_LINE> self.dav__simpleifhandler(request, response, refresh=1) <NEW_LINE> infile = request.get('BODYFILE', None) <NEW_LINE> filename = request['PATH_INFO'].split('/')[-1] <NEW_LINE> self.file = NamedBlobFile( data=infile.read(), filename=unicode(filename)) <NEW_LINE> modified(self) <NEW_LINE> return response <NEW_LINE> <DEDENT> def get_size(self): <NEW_LINE> <INDENT> return self.file.size <NEW_LINE> <DEDENT> def content_type(self): <NEW_LINE> <INDENT> return self.file.contentType
Convenience subclass for ``File`` portal type
625990774e4d562566373d8c
class CreateVisitTimeIntervalViewTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = User() <NEW_LINE> self.factory = RequestFactory() <NEW_LINE> <DEDENT> def test_get(self): <NEW_LINE> <INDENT> request = self.factory.get(reverse('register')) <NEW_LINE> request.user = self.user <NEW_LINE> response = register(request) <NEW_LINE> self.assertEqual(HttpResponse.status_code, 200)
Test the snippet create view
625990778a43f66fc4bf3b20
class FSTStateRemaining: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._state_renaming = dict() <NEW_LINE> self._seen_states = set() <NEW_LINE> <DEDENT> def add_state(self, state, idx): <NEW_LINE> <INDENT> if state in self._seen_states: <NEW_LINE> <INDENT> counter = 0 <NEW_LINE> new_state = state + str(counter) <NEW_LINE> while new_state in self._seen_states: <NEW_LINE> <INDENT> counter += 1 <NEW_LINE> new_state = state + str(counter) <NEW_LINE> <DEDENT> self._state_renaming[(state, idx)] = new_state <NEW_LINE> self._seen_states.add(new_state) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._state_renaming[(state, idx)] = state <NEW_LINE> self._seen_states.add(state) <NEW_LINE> <DEDENT> <DEDENT> def add_states(self, states, idx): <NEW_LINE> <INDENT> for state in states: <NEW_LINE> <INDENT> self.add_state(state, idx) <NEW_LINE> <DEDENT> <DEDENT> def get_name(self, state, idx): <NEW_LINE> <INDENT> return self._state_renaming[(state, idx)]
Class for remaining the states in FST
6259907767a9b606de54776a
class ActivityFinalNode(models.Model): <NEW_LINE> <INDENT> __package__ = 'UML.Activities' <NEW_LINE> final_node = models.OneToOneField('FinalNode', on_delete=models.CASCADE, primary_key=True)
An ActivityFinalNode is a FinalNode that terminates the execution of its owning Activity or StructuredActivityNode.
625990774f88993c371f11e6
class MS_LDA(FSCommand): <NEW_LINE> <INDENT> _cmd = 'mri_ms_LDA' <NEW_LINE> input_spec = MS_LDAInputSpec <NEW_LINE> output_spec = MS_LDAOutputSpec <NEW_LINE> def _list_outputs(self): <NEW_LINE> <INDENT> outputs = self._outputs().get() <NEW_LINE> outputs['vol_synth_file'] = os.path.abspath(self.inputs.output_synth) <NEW_LINE> if not isdefined(self.inputs.use_weights) or self.inputs.use_weights is False: <NEW_LINE> <INDENT> outputs['weight_file'] = os.path.abspath(self.inputs.weight_file) <NEW_LINE> <DEDENT> return outputs <NEW_LINE> <DEDENT> def _verify_weights_file_exists(self): <NEW_LINE> <INDENT> if not os.path.exists(os.path.abspath(self.inputs.weight_file)): <NEW_LINE> <INDENT> raise traits.TraitError("MS_LDA: use_weights must accompany an existing weights file") <NEW_LINE> <DEDENT> <DEDENT> def _format_arg(self, name, spec, value): <NEW_LINE> <INDENT> if name is 'use_weights': <NEW_LINE> <INDENT> if self.inputs.use_weights is True: <NEW_LINE> <INDENT> self._verify_weights_file_exists() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> return super(MS_LDA, self)._format_arg(name, spec, value) <NEW_LINE> <DEDENT> def _gen_filename(self, name): <NEW_LINE> <INDENT> pass
Perform LDA reduction on the intensity space of an arbitrary # of FLASH images Examples -------- >>> grey_label = 2 >>> white_label = 3 >>> zero_value = 1 >>> optimalWeights = MS_LDA(lda_labels=[grey_label, white_label], label_file='label.mgz', weight_file='weights.txt', shift=zero_value, synth='synth_out.mgz', conform=True, use_weights=True, images=['FLASH1.mgz', 'FLASH2.mgz', 'FLASH3.mgz']) >>> optimalWeights.cmdline 'mri_ms_LDA -lda 2 3 -label label.mgz -weight weights.txt -shift 0 -synth synth_out.mgz -conform -W FLASH1.mgz FLASH2.mgz FLASH3.mgz'
625990777cff6e4e811b73ca
@pytest.mark.skipif(not IS_LINUX, reason="Irrelevant on non-linux") <NEW_LINE> class TestRepr: <NEW_LINE> <INDENT> def test_repr(self) -> None: <NEW_LINE> <INDENT> repr_str = repr(distro._distro) <NEW_LINE> assert "LinuxDistribution" in repr_str <NEW_LINE> for attr in MODULE_DISTRO.__dict__.keys(): <NEW_LINE> <INDENT> if attr in ("root_dir", "etc_dir", "usr_lib_dir"): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> assert f"{attr}=" in repr_str
Test the __repr__() method.
6259907701c39578d7f143fa
class ReLU(Module, Activation): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> if config.show_calls: <NEW_LINE> <INDENT> print('--- initializing ReLU ---') <NEW_LINE> <DEDENT> self.prev_s = torch.Tensor() <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> if config.show_calls: <NEW_LINE> <INDENT> print(' *Calling ReLU.forward()') <NEW_LINE> <DEDENT> self.prev_s = input <NEW_LINE> return relu(input) <NEW_LINE> <DEDENT> def backward(self, dl_dx): <NEW_LINE> <INDENT> if config.show_calls: <NEW_LINE> <INDENT> print(' *Calling ReLU.backward()') <NEW_LINE> <DEDENT> if config.show_shapes: <NEW_LINE> <INDENT> print(' shape prev_s: ', self.prev_s.shape) <NEW_LINE> print(' shape dl_dx: ', dl_dx.view(-1, 1).shape) <NEW_LINE> <DEDENT> return drelu(self.prev_s)*dl_dx
Doc block!
62599077442bda511e95da1d
class ObjectExistsRequest(CadRequest): <NEW_LINE> <INDENT> def __init__(self, path, storage_name=None, version_id=None): <NEW_LINE> <INDENT> CadRequest.__init__(self) <NEW_LINE> self.path = path <NEW_LINE> self.storage_name = storage_name <NEW_LINE> self.version_id = version_id <NEW_LINE> <DEDENT> def to_http_info(self, config): <NEW_LINE> <INDENT> if self.path is None: <NEW_LINE> <INDENT> raise ValueError("Missing the required parameter `path` when calling `object_exists`") <NEW_LINE> <DEDENT> collection_formats = {} <NEW_LINE> path = '/cad/storage/exist/{path}' <NEW_LINE> path_params = {} <NEW_LINE> if self.path is not None: <NEW_LINE> <INDENT> path_params[self._lowercase_first_letter('path')] = self.path <NEW_LINE> <DEDENT> query_params = [] <NEW_LINE> if self._lowercase_first_letter('storageName') in path: <NEW_LINE> <INDENT> path = path.replace('{' + self._lowercase_first_letter('storageName' + '}'), self.storage_name if self.storage_name is not None else '') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.storage_name is not None: <NEW_LINE> <INDENT> query_params.append((self._lowercase_first_letter('storageName'), self.storage_name)) <NEW_LINE> <DEDENT> <DEDENT> if self._lowercase_first_letter('versionId') in path: <NEW_LINE> <INDENT> path = path.replace('{' + self._lowercase_first_letter('versionId' + '}'), self.version_id if self.version_id is not None else '') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.version_id is not None: <NEW_LINE> <INDENT> query_params.append((self._lowercase_first_letter('versionId'), self.version_id)) <NEW_LINE> <DEDENT> <DEDENT> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = [] <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self._select_header_accept( ['application/json']) <NEW_LINE> header_params['Content-Type'] = 'multipart/form-data' if form_params or local_var_files else self._select_header_content_type( ['application/json']) <NEW_LINE> auth_settings = ['JWT'] <NEW_LINE> return HttpRequest(path, path_params, query_params, header_params, form_params, body_params, local_var_files, collection_formats, auth_settings)
Request model for object_exists operation. Initializes a new instance. :param path File or folder path e.g. '/file.ext' or '/folder' :param storage_name Storage name :param version_id File version ID
625990771b99ca40022901fb
class LimitCpuResou(LimitBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(LimitCpuResou, self).__init__() <NEW_LINE> <DEDENT> def mk_cgroup(self): <NEW_LINE> <INDENT> if self.typelist: <NEW_LINE> <INDENT> for typename in self.typelist: <NEW_LINE> <INDENT> if self.conf[typename]["USE"]=="1": <NEW_LINE> <INDENT> if not os.path.exists(self.conf[typename]["CPU"]["dir_path"]): <NEW_LINE> <INDENT> cmd="mkdir " <NEW_LINE> cmd+=str(self.conf[typename]["CPU"]["dir_path"]) <NEW_LINE> p = self.sub_popen(cmd) <NEW_LINE> self.log(p) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def load_config(self): <NEW_LINE> <INDENT> if self.typelist: <NEW_LINE> <INDENT> for typename in self.typelist: <NEW_LINE> <INDENT> cmd_p="echo " <NEW_LINE> cmd_p+=str(self.conf[typename]["CPU"]["period"]["val"]) <NEW_LINE> cmd_p+=" > " <NEW_LINE> cmd_p+=str(self.conf[typename]["CPU"]["period"]["path"]) <NEW_LINE> cmd_q="echo " <NEW_LINE> cmd_q+=str(self.conf[typename]["CPU"]["quota"]["val"]) <NEW_LINE> cmd_q+=" > " <NEW_LINE> cmd_q+=str(self.conf[typename]["CPU"]["quota"]["path"]) <NEW_LINE> self.sub_popen(cmd_p) <NEW_LINE> self.sub_popen(cmd_q) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_pid_to_cgroup(self): <NEW_LINE> <INDENT> self.get_white_id() <NEW_LINE> if self.typelist: <NEW_LINE> <INDENT> for typename in self.typelist: <NEW_LINE> <INDENT> if self.conf[typename]["CPU"]["USE"]=="1": <NEW_LINE> <INDENT> with open(self.conf[typename]["ID_PATH"],'r') as fd: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> line = fd.readline() <NEW_LINE> line = line.strip('\n') <NEW_LINE> if line: <NEW_LINE> <INDENT> if line in self.whitelist: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd="echo " <NEW_LINE> cmd+=str(line) <NEW_LINE> cmd+=" > " <NEW_LINE> cmd+=self.conf[typename]["CPU"]["task_path"] <NEW_LINE> p=self.sub_popen(cmd) <NEW_LINE> self.log(p) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> break
限制CPU
6259907763b5f9789fe86af0
class CoordinateTransformation(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> this = _osr.new_CoordinateTransformation(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> __swig_destroy__ = _osr.delete_CoordinateTransformation <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def TransformPoint(self, *args): <NEW_LINE> <INDENT> return _osr.CoordinateTransformation_TransformPoint(self, *args) <NEW_LINE> <DEDENT> def TransformPoints(self, *args): <NEW_LINE> <INDENT> return _osr.CoordinateTransformation_TransformPoints(self, *args)
Proxy of C++ OSRCoordinateTransformationShadow class
6259907732920d7e50bc79d3
class InputModule(AbstractInput): <NEW_LINE> <INDENT> def __init__(self, input_dev, testing=False): <NEW_LINE> <INDENT> super(InputModule, self).__init__(input_dev, testing=testing, name=__name__) <NEW_LINE> self.api_url = None <NEW_LINE> self.api_key = None <NEW_LINE> self.city = None <NEW_LINE> if not testing: <NEW_LINE> <INDENT> self.setup_custom_options( INPUT_INFORMATION['custom_options'], input_dev) <NEW_LINE> self.initialize_input() <NEW_LINE> <DEDENT> <DEDENT> def initialize_input(self): <NEW_LINE> <INDENT> if self.api_key and self.city: <NEW_LINE> <INDENT> self.api_url = "http://api.openweathermap.org/data/2.5/weather?appid={key}&units=metric&q={city}".format( key=self.api_key, city=self.city) <NEW_LINE> self.logger.debug("URL: {}".format(self.api_url)) <NEW_LINE> <DEDENT> <DEDENT> def get_measurement(self): <NEW_LINE> <INDENT> if not self.api_url: <NEW_LINE> <INDENT> self.logger.error("API Key and City required") <NEW_LINE> return <NEW_LINE> <DEDENT> self.return_dict = copy.deepcopy(measurements_dict) <NEW_LINE> try: <NEW_LINE> <INDENT> response = requests.get(self.api_url) <NEW_LINE> x = response.json() <NEW_LINE> self.logger.debug("Response: {}".format(x)) <NEW_LINE> if x["cod"] != "404": <NEW_LINE> <INDENT> temperature = x["main"]["temp"] <NEW_LINE> pressure = x["main"]["pressure"] <NEW_LINE> humidity = x["main"]["humidity"] <NEW_LINE> wind_speed = x["wind"]["speed"] <NEW_LINE> wind_deg = x["wind"]["deg"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.error("City Not Found") <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.logger.error("Error acquiring weather information: {}".format(e)) <NEW_LINE> return <NEW_LINE> <DEDENT> self.logger.debug("Temp: {}, Hum: {}, Press: {}, Wind Speed: {}, Wind Direction: {}".format( temperature, humidity, pressure, wind_speed, wind_deg)) <NEW_LINE> if self.is_enabled(0): <NEW_LINE> <INDENT> self.value_set(0, temperature) <NEW_LINE> <DEDENT> if self.is_enabled(1): <NEW_LINE> <INDENT> self.value_set(1, humidity) <NEW_LINE> <DEDENT> if self.is_enabled(2): <NEW_LINE> <INDENT> self.value_set(2, pressure) <NEW_LINE> <DEDENT> if self.is_enabled(0) and self.is_enabled(1) and self.is_enabled(3): <NEW_LINE> <INDENT> self.value_set(3, calculate_dewpoint(temperature, humidity)) <NEW_LINE> <DEDENT> if self.is_enabled(4): <NEW_LINE> <INDENT> self.value_set(4, wind_speed) <NEW_LINE> <DEDENT> if self.is_enabled(5): <NEW_LINE> <INDENT> self.value_set(5, wind_deg) <NEW_LINE> <DEDENT> return self.return_dict
A sensor support class that gets weather for a city
62599077fff4ab517ebcf1a2
class RestorableSqlDatabasesListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[RestorableSqlDatabaseGetResult]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(RestorableSqlDatabasesListResult, self).__init__(**kwargs) <NEW_LINE> self.value = None
The List operation response, that contains the SQL database events and their properties. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: List of SQL database events and their properties. :vartype value: list[~azure.mgmt.cosmosdb.models.RestorableSqlDatabaseGetResult]
62599077ec188e330fdfa232
class rocp(_rocbase): <NEW_LINE> <INDENT> alias = 'ROCP', 'RateOfChangePercentage' <NEW_LINE> outputs = 'rocp' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.o.rocp = self.o.rocp - 1.0
The ROC calculation compares the current price with the price n periods ago, to determine momentum the as the percent change in price. Formula: - rocp = data / data(-period) - 1.0 See: - https://school.stockcharts.com/doku.php?id=technical_indicators:rate_of_change_roc_and_momentum
62599077aad79263cf430144
class RedisStore(Store): <NEW_LINE> <INDENT> def __init__(self, ip="127.0.0.1", port=6379, db=0): <NEW_LINE> <INDENT> self.db = redis.StrictRedis(host=ip, port=port, db=db) <NEW_LINE> self.timeout = web.webapi.config.session_parameters.timeout <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return bool(self.db.exists(SESSION_MARKUP+key)) <NEW_LINE> <DEDENT> except redis.ConnectionError: <NEW_LINE> <INDENT> sys.stderr.write('Error: Can not Connect Redis') <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> v = self.db.get(SESSION_MARKUP+key) <NEW_LINE> if v: <NEW_LINE> <INDENT> self.db.expire(SESSION_MARKUP+key, 600) <NEW_LINE> return self.decode(v) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.db.setex(SESSION_MARKUP+key, 600, self.encode(value)) <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> self.db.delete(SESSION_MARKUP+key) <NEW_LINE> <DEDENT> def cleanup(self, timeout): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def decode(self, session_data): <NEW_LINE> <INDENT> missing_padding = 4 - len(session_data) % 4 <NEW_LINE> if missing_padding: <NEW_LINE> <INDENT> session_data += b'='* missing_padding <NEW_LINE> <DEDENT> pickled = base64.decodestring(session_data) <NEW_LINE> try: <NEW_LINE> <INDENT> return pickle.loads(pickled) <NEW_LINE> <DEDENT> except pickle.UnpicklingError: <NEW_LINE> <INDENT> logging.error('UnpicklingError: '+pickled) <NEW_LINE> return pickle.loads(pickled)
Store for saving a session in redis
62599077627d3e7fe0e08814
class ErrorContainer(Exception): <NEW_LINE> <INDENT> def append(self, error): <NEW_LINE> <INDENT> self.args += (error, ) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.args) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.args) <NEW_LINE> <DEDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> return self.args[i] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "\n".join( ["%s: %s" % (error.__class__.__name__, error) for error in self.args] ) <NEW_LINE> <DEDENT> __repr__ = __str__
A base error class for collecting multiple errors.
62599077379a373c97d9a9af
class NuFluxes(object): <NEW_LINE> <INDENT> Honda2006 = staticmethod(AtmosphericNuFlux("honda2006")) <NEW_LINE> Honda2006H3a = staticmethod(AtmosphericNuFlux("honda2006",knee="gaisserH3a_elbert")) <NEW_LINE> Honda2006H4a = staticmethod(AtmosphericNuFlux("honda2006",knee="gaisserH4a_elbert")) <NEW_LINE> ERS = staticmethod(AtmosphericNuFlux("sarcevic_std")) <NEW_LINE> ERSH3a = staticmethod(AtmosphericNuFlux("sarcevic_std",knee="gaisserH3a_elbert")) <NEW_LINE> ERSH4a = staticmethod(AtmosphericNuFlux("sarcevic_std",knee="gaisserH4a_elbert")) <NEW_LINE> BERSSH3a = staticmethod(AtmosphericNuFlux("BERSS_H3a_central")) <NEW_LINE> BERSSH4a = staticmethod(AtmosphericNuFlux("BERSS_H3p_central")) <NEW_LINE> E2 = staticmethod(PowerLawFlux()) <NEW_LINE> BARTOL = staticmethod(AtmosphericNuFlux("bartol"))
Namespace for neutrino fluxes
6259907723849d37ff852a43
class Purge(BaseView): <NEW_LINE> <INDENT> def update(self): <NEW_LINE> <INDENT> self.purgeLog = [] <NEW_LINE> if super(Purge, self).update(): <NEW_LINE> <INDENT> if 'form.button.Purge' in self.request.form: <NEW_LINE> <INDENT> self.processPurge() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def processPurge(self): <NEW_LINE> <INDENT> urls = self.request.form.get('urls', []) <NEW_LINE> sync = self.request.form.get('synchronous', True) <NEW_LINE> if not urls: <NEW_LINE> <INDENT> self.errors['urls'] = _(u"No URLs or paths entered.") <NEW_LINE> <DEDENT> if self.errors: <NEW_LINE> <INDENT> IStatusMessage(self.request).addStatusMessage(_(u"There were errors."), "error") <NEW_LINE> return <NEW_LINE> <DEDENT> purger = getUtility(IPurger) <NEW_LINE> serverURL = self.request['SERVER_URL'] <NEW_LINE> def purge(url): <NEW_LINE> <INDENT> if sync: <NEW_LINE> <INDENT> status, xcache, xerror = purger.purgeSync(url) <NEW_LINE> log = url <NEW_LINE> if xcache: <NEW_LINE> <INDENT> log += " (X-Cache header: " + xcache + ")" <NEW_LINE> <DEDENT> if xerror: <NEW_LINE> <INDENT> log += " -- " + xerror <NEW_LINE> <DEDENT> self.purgeLog.append(log) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> purger.purgeAsync(url) <NEW_LINE> self.purgeLog.append(url) <NEW_LINE> <DEDENT> <DEDENT> portal_url = getToolByName(self.context, 'portal_url') <NEW_LINE> portal = portal_url.getPortalObject() <NEW_LINE> portalPath = '/'.join(portal.getPhysicalPath()) <NEW_LINE> proxies = self.purgingSettings.cachingProxies <NEW_LINE> for inputURL in urls: <NEW_LINE> <INDENT> if not inputURL.startswith(serverURL): <NEW_LINE> <INDENT> if '://' in inputURL: <NEW_LINE> <INDENT> purge(inputURL) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for newURL in getURLsToPurge(inputURL, proxies): <NEW_LINE> <INDENT> purge(newURL) <NEW_LINE> <DEDENT> <DEDENT> continue <NEW_LINE> <DEDENT> physicalPath = relativePath = None <NEW_LINE> try: <NEW_LINE> <INDENT> physicalPath = self.request.physicalPathFromURL(inputURL) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> purge(inputURL) <NEW_LINE> continue <NEW_LINE> <DEDENT> if not physicalPath: <NEW_LINE> <INDENT> purge(inputURL) <NEW_LINE> continue <NEW_LINE> <DEDENT> relativePath = physicalPath[len(portalPath):] <NEW_LINE> if not relativePath: <NEW_LINE> <INDENT> purge(inputURL) <NEW_LINE> continue <NEW_LINE> <DEDENT> obj = portal.unrestrictedTraverse(relativePath, None) <NEW_LINE> if obj is None: <NEW_LINE> <INDENT> purge(inputURL) <NEW_LINE> continue <NEW_LINE> <DEDENT> for path in getPathsToPurge(obj, self.request): <NEW_LINE> <INDENT> for newURL in getURLsToPurge(path, proxies): <NEW_LINE> <INDENT> purge(newURL)
The purge control panel
6259907766673b3332c31d8b
class ReactComponent(Enum): <NEW_LINE> <INDENT> TEXT_FIELD = 'TextField' <NEW_LINE> JSON_FIELD = 'JsonField' <NEW_LINE> DATE_FIELD = 'DateField' <NEW_LINE> NUMBER_FIELD = 'NumberField' <NEW_LINE> BOOLEAN_FIELD = 'BooleanField' <NEW_LINE> FUNCTION_FIELD = 'FunctionField' <NEW_LINE> REFERENCE_MANY_FIELD = 'ReferenceManyField' <NEW_LINE> PRODUCT_REFERENCE_FIELD = 'ProductReferenceField' <NEW_LINE> STAR_RATING_FIELD = 'StarRatingField' <NEW_LINE> MB_ITEMS_FIELD = 'NbItemsField' <NEW_LINE> TEXT_INPUT = 'TextInput' <NEW_LINE> DATE_INPUT = 'DateInput' <NEW_LINE> SEGMENTS_INPUT = 'SegmentsInput' <NEW_LINE> NULLABLE_BOOLEAN_INPUT = 'NullableBooleanInput' <NEW_LINE> LONG_TEXT_INPUT = 'LongTextInput' <NEW_LINE> JSON_INPUT = 'JsonInput'
Represented React components of `admin-on-rest`.
62599077adb09d7d5dc0bef6
class PlaylistLinkFeed(gdata.data.BatchFeed): <NEW_LINE> <INDENT> entry = [PlaylistLinkEntry]
Describes list of playlists
6259907767a9b606de54776b
class ExtensionAddon(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.AddonName = None <NEW_LINE> self.AddonParam = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.AddonName = params.get("AddonName") <NEW_LINE> self.AddonParam = params.get("AddonParam")
Information of the add-on selected for installation during cluster creation
625990772c8b7c6e89bd5176
class NotSentinelInstance(Exception): <NEW_LINE> <INDENT> pass
Raised when Redis instance is not configured as a sentinel
6259907701c39578d7f143fb
class Taboo(BaseContract): <NEW_LINE> <INDENT> def __init__(self, contract_name, parent=None): <NEW_LINE> <INDENT> super(Taboo, self).__init__(contract_name, self._get_contract_code(), parent) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_contract_code(): <NEW_LINE> <INDENT> return 'vzTaboo' <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_subject_code(): <NEW_LINE> <INDENT> return 'vzTSubj' <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_subject_relation_code(): <NEW_LINE> <INDENT> return 'vzRsDenyRule'
Taboo : Class for Taboos
625990771b99ca40022901fc
class SignatureRequest(Resource): <NEW_LINE> <INDENT> pass
Contains information regarding documents that need to be signed Comprises the following attributes: test_mode (bool): Whether this is a test signature request. Test requests have no legal value. Defaults to 0. signature_request_id (str): The id of the SignatureRequest requester_email_address (str): The email address of the initiator of the SignatureRequest title (str): The title the specified Account uses for the SignatureRequest subject (str): The subject in the email that was initially sent to the signers message (str): The custom message in the email that was initially sent to the signers is_complete (bool): Whether or not the SignatureRequest has been fully executed by all signers has_error (bool): Whether or not an error occurred (either during the creation of the SignatureRequest or during one of the signings) final_copy_uri (DEPRECATED): The relative URI where the PDF copy of the finalized documents can be downloaded. Only present when `is_complete = true`. This will be removed at some point; use the `files_url` instead files_url (str): The URL where a copy of the request's documents can be downloaded signing_url (str): The URL where a signer, after authenticating, can sign the documents details_url (str): The URL where the requester and the signers can view the current status of the SignatureRequest cc_email_addresses (list): A list of email addresses that were CCed on the SignatureRequest. They will receive a copy of the final PDF once all the signers have signed signing_redirect_url (str): The URL you want the signer redirected to after they successfully sign custom_fields (list of dict): An array of Custom Field objects containing the name and type of each custom field name (str): The name of the Custom Field type (str): The type of this Custom Field. Currently, `text` and `checkmark` are the only valid values response_data (list of dict): An array of form field objects containing the name, value, and type of each textbox or checkmark field filled in by the signers api_id (str): The unique ID for this field signature_id (str): The ID of the signature to which this response is linked name (str): The name of the form field value (str): The value of the form field type (str): The type of this form field signatures (list of dict): An array of signature obects, 1 for each signer signature_id (str): Signature identifier signer_email_address (str): The email address of the signer signer_name (str): The name of the signer order (str): If signer order is assigned this is the 0-based index for this signer status_code (str): The current status of the signature. eg: `awaiting_signature`, `signed`, `on_hold` signed_at (str): Time that the document was signed or null last_viewed_at (str): The time that the document was last viewed by this signer or null last_reminded_at (str): The time the last reminder email was sent to the signer or null has_pin (bool): Boolean to indicate whether this signature requires a PIN to access
6259907756b00c62f0fb425f
class AssetEnvBaseInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Name = None <NEW_LINE> self.Type = None <NEW_LINE> self.User = None <NEW_LINE> self.Value = None <NEW_LINE> self.MachineIp = None <NEW_LINE> self.MachineName = None <NEW_LINE> self.OsInfo = None <NEW_LINE> self.Quuid = None <NEW_LINE> self.Uuid = None <NEW_LINE> self.UpdateTime = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Name = params.get("Name") <NEW_LINE> self.Type = params.get("Type") <NEW_LINE> self.User = params.get("User") <NEW_LINE> self.Value = params.get("Value") <NEW_LINE> self.MachineIp = params.get("MachineIp") <NEW_LINE> self.MachineName = params.get("MachineName") <NEW_LINE> self.OsInfo = params.get("OsInfo") <NEW_LINE> self.Quuid = params.get("Quuid") <NEW_LINE> self.Uuid = params.get("Uuid") <NEW_LINE> self.UpdateTime = params.get("UpdateTime") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
资产管理环境变量列表
6259907763b5f9789fe86af2
class MonitorlogApi(object): <NEW_LINE> <INDENT> def __init__(self, api_client=None): <NEW_LINE> <INDENT> config = Configuration() <NEW_LINE> if api_client: <NEW_LINE> <INDENT> self.api_client = api_client <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not config.api_client: <NEW_LINE> <INDENT> config.api_client = ApiClient() <NEW_LINE> <DEDENT> self.api_client = config.api_client <NEW_LINE> <DEDENT> <DEDENT> def get_log_requests_by_http_method(self, httpmethod, **kwargs): <NEW_LINE> <INDENT> all_params = ['httpmethod'] <NEW_LINE> all_params.append('callback') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_log_requests_by_http_method" % key ) <NEW_LINE> <DEDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> if ('httpmethod' not in params) or (params['httpmethod'] is None): <NEW_LINE> <INDENT> raise ValueError("Missing the required parameter `httpmethod` when calling `get_log_requests_by_http_method`") <NEW_LINE> <DEDENT> resource_path = '/monitor/log/{httpmethod}'.replace('{format}', 'json') <NEW_LINE> method = 'GET' <NEW_LINE> path_params = {} <NEW_LINE> if 'httpmethod' in params: <NEW_LINE> <INDENT> path_params['httpmethod'] = params['httpmethod'] <NEW_LINE> <DEDENT> query_params = {} <NEW_LINE> header_params = {} <NEW_LINE> form_params = {} <NEW_LINE> files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client. select_header_accept(['application/json', 'application/xml']) <NEW_LINE> if not header_params['Accept']: <NEW_LINE> <INDENT> del header_params['Accept'] <NEW_LINE> <DEDENT> header_params['Content-Type'] = self.api_client. select_header_content_type([]) <NEW_LINE> auth_settings = [] <NEW_LINE> response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, response_type='list[LogCondRequests]', auth_settings=auth_settings, callback=params.get('callback')) <NEW_LINE> return response
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen
625990774f6381625f19a172
class ThreeLayerConvNet(object): <NEW_LINE> <INDENT> def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0, dtype=np.float32): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.reg = reg <NEW_LINE> self.dtype = dtype <NEW_LINE> b1=np.zeros((1,num_filters)) <NEW_LINE> b2=np.zeros((1,hidden_dim)) <NEW_LINE> b3=np.zeros((1,num_classes)) <NEW_LINE> W1= np.random.randn(num_filters,input_dim[0],filter_size,filter_size)*weight_scale <NEW_LINE> W2= np.random.randn(num_filters*input_dim[1]*input_dim[2]/4,hidden_dim)*weight_scale <NEW_LINE> W3= np.random.randn(hidden_dim,num_classes)*weight_scale <NEW_LINE> self.params['b1']=b1 <NEW_LINE> self.params['b2']=b2 <NEW_LINE> self.params['b3']=b3 <NEW_LINE> self.params['W1']=W1 <NEW_LINE> self.params['W2']=W2 <NEW_LINE> self.params['W3']=W3 <NEW_LINE> for k, v in self.params.iteritems(): <NEW_LINE> <INDENT> self.params[k] = v.astype(dtype) <NEW_LINE> <DEDENT> <DEDENT> def loss(self, X, y=None): <NEW_LINE> <INDENT> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> W3, b3 = self.params['W3'], self.params['b3'] <NEW_LINE> filter_size = W1.shape[2] <NEW_LINE> conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2} <NEW_LINE> pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2} <NEW_LINE> scores = None <NEW_LINE> out, cache_conv = conv_relu_pool_forward(X, W1, b1, conv_param, pool_param) <NEW_LINE> out, cache_full = affine_forward(out, W2, b2) <NEW_LINE> hidden_layer,cache_relu =relu_forward(out) <NEW_LINE> scores,cache=affine_forward(hidden_layer, W3, b3) <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss, grads = 0, {} <NEW_LINE> loss,dscores=softmax_loss(scores,y) <NEW_LINE> loss+=0.5*self.reg*(np.sum(W1*W1)+np.sum(W2*W2)+np.sum(W3*W3)) <NEW_LINE> dhidden2,dW3,db3=affine_backward(dscores, cache) <NEW_LINE> dhidden2=relu_backward(dhidden2, cache_relu) <NEW_LINE> dhidden1,dW2,db2=affine_backward(dhidden2, cache_full) <NEW_LINE> dX, dW1, db1 = conv_relu_pool_backward(dhidden1, cache_conv) <NEW_LINE> dW3 += self.reg * W3 <NEW_LINE> dW2 += self.reg * W2 <NEW_LINE> dW1 += self.reg * W1 <NEW_LINE> grads['b1']=db1 <NEW_LINE> grads['W1']=dW1 <NEW_LINE> grads['b2']=db2 <NEW_LINE> grads['W2']=dW2 <NEW_LINE> grads['b3']=db3 <NEW_LINE> grads['W3']=dW3 <NEW_LINE> return loss, grads
A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C input channels.
62599077be8e80087fbc0a21
class ValueFlow: <NEW_LINE> <INDENT> Id = None <NEW_LINE> values = None <NEW_LINE> class Value: <NEW_LINE> <INDENT> intvalue = None <NEW_LINE> tokvalue = None <NEW_LINE> condition = None <NEW_LINE> def __init__(self, element): <NEW_LINE> <INDENT> self.intvalue = element.get('intvalue') <NEW_LINE> if self.intvalue: <NEW_LINE> <INDENT> self.intvalue = int(self.intvalue) <NEW_LINE> <DEDENT> self.tokvalue = element.get('tokvalue') <NEW_LINE> self.condition = element.get('condition-line') <NEW_LINE> if self.condition: <NEW_LINE> <INDENT> self.condition = int(self.condition) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __init__(self, element): <NEW_LINE> <INDENT> self.Id = element.get('id') <NEW_LINE> self.values = [] <NEW_LINE> for value in element: <NEW_LINE> <INDENT> self.values.append(ValueFlow.Value(value))
ValueFlow::Value class Each possible value has a ValueFlow::Value item. Each ValueFlow::Value either has a intvalue or tokvalue C++ class: http://cppcheck.net/devinfo/doxyoutput/classValueFlow_1_1Value.html Attributes: values Possible values
625990772ae34c7f260aca74
class SenderInitializationError(Exception): <NEW_LINE> <INDENT> pass
Error during sender initialization
62599077a05bb46b3848bdf1
class TankAnt(BodyguardAnt): <NEW_LINE> <INDENT> name = 'Tank' <NEW_LINE> damage = 1 <NEW_LINE> food_cost = 6 <NEW_LINE> armor = 2 <NEW_LINE> container = True <NEW_LINE> implemented = True <NEW_LINE> def action(self, colony): <NEW_LINE> <INDENT> bees = list(self.place.bees) <NEW_LINE> for bee in bees: <NEW_LINE> <INDENT> bee.reduce_armor(self.damage) <NEW_LINE> <DEDENT> if self.ant is not None: <NEW_LINE> <INDENT> self.ant.action(colony)
TankAnt provides both offensive and defensive capabilities.
625990771f5feb6acb164583
class User(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def create(data): <NEW_LINE> <INDENT> hashed=generate_password_hash(data['password']) <NEW_LINE> query = "INSERT INTO users (name,username,email,password,role)" "VALUES('%s','%s', '%s', '%s', '%s')" % ( data['name'],data['username'],data['email'],hashed,data['role']) <NEW_LINE> cur.execute(query) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_admin(data): <NEW_LINE> <INDENT> hashed=generate_password_hash(data['password']) <NEW_LINE> query = "INSERT INTO users (name,username,email,password,role)" "VALUES('%s','%s', '%s', '%s', '%s')" % ( data['name'],data['username'],data['email'],hashed,"admin") <NEW_LINE> cur.execute(query) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def exists(data): <NEW_LINE> <INDENT> if data['email']: <NEW_LINE> <INDENT> query="SELECT * FROM users WHERE email = '%s';" % data['email'] <NEW_LINE> cur.execute(query) <NEW_LINE> return cur.fetchone() <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_by_email(email): <NEW_LINE> <INDENT> if email: <NEW_LINE> <INDENT> query="SELECT * FROM users WHERE email = '%s';" % email <NEW_LINE> cur.execute(query) <NEW_LINE> return cur.fetchone() <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def get_by_id(user_id): <NEW_LINE> <INDENT> if user_id: <NEW_LINE> <INDENT> query="SELECT * FROM users WHERE id = '%s';" % user_id <NEW_LINE> cur.execute(query) <NEW_LINE> return cur.fetchone() <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def get(): <NEW_LINE> <INDENT> query="SELECT * FROM users" <NEW_LINE> cur.execute(query) <NEW_LINE> users=cur.fetchall() <NEW_LINE> for user in users: <NEW_LINE> <INDENT> user.pop("password") <NEW_LINE> <DEDENT> return users
create user
625990775fdd1c0f98e5f90c
class FilterExists(object): <NEW_LINE> <INDENT> def validator(self): <NEW_LINE> <INDENT> from flexget import validator <NEW_LINE> root = validator.factory() <NEW_LINE> root.accept('path') <NEW_LINE> bundle = root.accept('list') <NEW_LINE> bundle.accept('path') <NEW_LINE> return root <NEW_LINE> <DEDENT> def get_config(self, task): <NEW_LINE> <INDENT> config = task.config.get('exists', None) <NEW_LINE> if isinstance(config, basestring): <NEW_LINE> <INDENT> config = [config] <NEW_LINE> <DEDENT> return config <NEW_LINE> <DEDENT> @priority(-1) <NEW_LINE> def on_task_filter(self, task): <NEW_LINE> <INDENT> if not task.accepted: <NEW_LINE> <INDENT> log.debug('No accepted entries, not scanning for existing.') <NEW_LINE> return <NEW_LINE> <DEDENT> log.verbose('Scanning path(s) for existing files.') <NEW_LINE> config = self.get_config(task) <NEW_LINE> for path in config: <NEW_LINE> <INDENT> path = str(os.path.expanduser(path)) <NEW_LINE> if not os.path.exists(path): <NEW_LINE> <INDENT> raise PluginWarning('Path %s does not exist' % path, log) <NEW_LINE> <DEDENT> for root, dirs, files in os.walk(path): <NEW_LINE> <INDENT> dirs = [x.decode('utf-8', 'ignore') for x in dirs] <NEW_LINE> files = [x.decode('utf-8', 'ignore') for x in files] <NEW_LINE> for entry in task.accepted: <NEW_LINE> <INDENT> name = entry['title'] <NEW_LINE> if name in dirs or name in files: <NEW_LINE> <INDENT> log.debug('Found %s in %s' % (name, root)) <NEW_LINE> entry.reject(os.path.join(root, name))
Reject entries that already exist in given path. Example:: exists: /storage/movies/
62599077dc8b845886d54f48
class StartPage(tk.Frame): <NEW_LINE> <INDENT> def __init__(self, parent, controller): <NEW_LINE> <INDENT> root = tk.Frame.__init__(self,parent) <NEW_LINE> label = tk.Label(self, text="Welcome to NYC!", font=("Verdana", 20)) <NEW_LINE> label.pack(pady=100,padx=100) <NEW_LINE> button1 = tk.Button(self, text="Search", height = 2, width = 10, bg='blue', command=lambda: controller.show_frame(Search, 0, 0)) <NEW_LINE> button1.pack(pady=10,padx=10) <NEW_LINE> button2 = tk.Button(self, text="Plan", height = 2, width = 10, bg='red', command=lambda: controller.show_frame(Plan, 0, 0)) <NEW_LINE> button2.pack(pady=10,padx=10) <NEW_LINE> button3 = tk.Button(self, text="Overview", height = 2, width = 10, bg='yellow', command=lambda: controller.show_frame(Overview, 0, 0)) <NEW_LINE> button3.pack(pady=10,padx=10)
This class bulid the Home page of the GUI
6259907755399d3f05627ea1
class BaseScenario(Scenario): <NEW_LINE> <INDENT> objects = GeoInheritanceManager() <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> abstract = False <NEW_LINE> app_label = 'footprint'
BaseScenarios represent an editing of primary or BaseFeature data.
6259907732920d7e50bc79d6
class Sequential(Module): <NEW_LINE> <INDENT> def __init__(self, *modules: Module): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.modules = modules <NEW_LINE> self.input = None <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> self.input = input <NEW_LINE> output = input <NEW_LINE> for module in self.modules: <NEW_LINE> <INDENT> output = module(output) <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> def backward(self, doutput): <NEW_LINE> <INDENT> dsequential = doutput <NEW_LINE> for module in self.modules[::-1]: <NEW_LINE> <INDENT> dsequential = module.backward(dsequential) <NEW_LINE> <DEDENT> return dsequential <NEW_LINE> <DEDENT> @property <NEW_LINE> def param(self): <NEW_LINE> <INDENT> return (module.param for module in self.modules) <NEW_LINE> <DEDENT> def zero_grad(self): <NEW_LINE> <INDENT> for module in self.modules: <NEW_LINE> <INDENT> module.zero_grad()
A sequential model. :param *modules: modules in sequential order
62599077097d151d1a2c2a04
class MM_STATUS(Layer3): <NEW_LINE> <INDENT> constructorList = [ie for ie in Header(5, 49)] <NEW_LINE> def __init__(self, with_options=True, **kwargs): <NEW_LINE> <INDENT> Layer3.__init__(self) <NEW_LINE> self.extend([ Int('Cause', Pt=2, Type='uint8', Dict=Reject_dict)]) <NEW_LINE> self._post_init(with_options, **kwargs)
Net <-> ME Local # content # Cause is 1 byte
6259907760cbc95b06365a34
class T_RotMxInfo(ct.Structure): <NEW_LINE> <INDENT> _fields_ = [("EigenVector", ct.c_int * 3), ("Order", ct.c_int), ("Inverse", ct.c_int), ("RefAxis", ct.c_char), ("DirCode", ct.c_char)]
EigenVector: the rotation axis of the affiliated rotation Matrix Order: one of {1, 2, 3, 4, 6, -1, -2, -3, -4, -6} Inverse: 0 - rotation matrix has a positive turn angle -1 - rotation matrix has a negative turn angle RefAxis: one of {o, x, y, z} Dircode: one of {. = " ' | \ *}
6259907766673b3332c31d8d
class KeyMotorActor(pykka.ThreadingActor): <NEW_LINE> <INDENT> use_daemon_thread = True <NEW_LINE> def __init__(self, hub_actor): <NEW_LINE> <INDENT> super(KeyMotorActor, self).__init__() <NEW_LINE> self.hub_actor = hub_actor <NEW_LINE> <DEDENT> def open(self, callback): <NEW_LINE> <INDENT> self.hub_actor.key_motor_to_angle(KEY_OPEN_ANGLE, 100).get() <NEW_LINE> sleep(1) <NEW_LINE> self.hub_actor.stop_key_motor().get() <NEW_LINE> callback() <NEW_LINE> <DEDENT> def close(self, callback): <NEW_LINE> <INDENT> self.hub_actor.key_motor_to_angle(0, 100).get() <NEW_LINE> sleep(1) <NEW_LINE> self.hub_actor.stop_key_motor().get() <NEW_LINE> callback()
鍵のモーターを扱うアクター
62599077796e427e53850108
class Mpg123(Plugin): <NEW_LINE> <INDENT> height = 1 <NEW_LINE> width = 1 <NEW_LINE> playing = False <NEW_LINE> def pad_down_callback(self, pad): <NEW_LINE> <INDENT> if not self.playing: <NEW_LINE> <INDENT> self.start() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> self.playing = not self.playing <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> call('mpg123', self.get_option('mp3')) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> call('killall', 'mpg123')
Plays mp3's in a subprocess using mpg123. Press button once to start off the mp3, press button again to kill all mpg123's running. Example config: [rickroll] mp3 = /path/to/rick.mp3 plugin = mpg123 position = 0
62599077f9cc0f698b1c5f93
class ContestWebServer(WebService): <NEW_LINE> <INDENT> def __init__(self, shard, contest): <NEW_LINE> <INDENT> logger.initialize(ServiceCoord("ContestWebServer", shard)) <NEW_LINE> self.contest = contest <NEW_LINE> self.notifications = {} <NEW_LINE> parameters = { "login_url": "/", "template_path": pkg_resources.resource_filename("cms.server", "templates/contest"), "static_path": pkg_resources.resource_filename("cms.server", "static"), "cookie_secret": base64.b64encode(config.secret_key), "debug": config.tornado_debug, } <NEW_LINE> parameters["is_proxy_used"] = config.is_proxy_used <NEW_LINE> WebService.__init__( self, config.contest_listen_port[shard], _cws_handlers, parameters, shard=shard, listen_address=config.contest_listen_address[shard]) <NEW_LINE> self.file_cacher = FileCacher(self) <NEW_LINE> self.evaluation_service = self.connect_to( ServiceCoord("EvaluationService", 0)) <NEW_LINE> self.scoring_service = self.connect_to( ServiceCoord("ScoringService", 0)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def authorized_rpc(service, method, arguments): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> NOTIFICATION_ERROR = "error" <NEW_LINE> NOTIFICATION_WARNING = "warning" <NEW_LINE> NOTIFICATION_SUCCESS = "success" <NEW_LINE> def add_notification(self, username, timestamp, subject, text, level): <NEW_LINE> <INDENT> if username not in self.notifications: <NEW_LINE> <INDENT> self.notifications[username] = [] <NEW_LINE> <DEDENT> self.notifications[username].append((timestamp, subject, text, level))
Service that runs the web server serving the contestants.
6259907767a9b606de54776c
class DownloadFactory(CommandFactory): <NEW_LINE> <INDENT> def __init__(self, n_threads=1, memory=4): <NEW_LINE> <INDENT> CommandFactory.__init__(self, args.basedir, n_threads, memory, "dl") <NEW_LINE> <DEDENT> def make_cmd(self, s): <NEW_LINE> <INDENT> cmd = "/usr/bin/Rscript %ssrc/downloadSRA.R %s %s '%s' " % (args.basedir, args.basedir, s.getAccession(), s._breed) <NEW_LINE> commands = [] <NEW_LINE> commands.append(cmd) <NEW_LINE> commands.append("") <NEW_LINE> script_file = s.getFastqFolder()+s.getAccession()+".sh" <NEW_LINE> self.write_script(commands, script_file, s) <NEW_LINE> return("sh %s " % script_file) <NEW_LINE> <DEDENT> def has_output(self, s): <NEW_LINE> <INDENT> return s.hasFastqFiles() or s.hasTrimmedReads() or s.hasMappedReads() or s.hasBamFile() <NEW_LINE> <DEDENT> def has_input(self, s): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def lock_file(self, s): <NEW_LINE> <INDENT> return s.getFastqFolder()+s.getAccession()+"."+self._log_suffix+".lck" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "downloading"
Generate command line calls to download SRA fastq files
625990772c8b7c6e89bd5178
class DocumentReader(Reader): <NEW_LINE> <INDENT> @defer.inlineCallbacks <NEW_LINE> def open(self, url): <NEW_LINE> <INDENT> cache = self.cache() <NEW_LINE> id = self.mangle(url, 'document') <NEW_LINE> d = cache.get(id) <NEW_LINE> if d is None: <NEW_LINE> <INDENT> d = yield self.download(url) <NEW_LINE> cache.put(id, d) <NEW_LINE> <DEDENT> self.plugins.document.parsed(url=url, document=d.root()) <NEW_LINE> defer.returnValue(d) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def download(self, url): <NEW_LINE> <INDENT> store = DocumentStore() <NEW_LINE> fp = store.open(url) <NEW_LINE> if fp is not None: <NEW_LINE> <INDENT> content = fp.read() <NEW_LINE> fp.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> content = yield self.options.transport.open(Request(url)) <NEW_LINE> <DEDENT> ctx = self.plugins.document.loaded(url=url, document=content) <NEW_LINE> content = ctx.document <NEW_LINE> sax = Parser() <NEW_LINE> defer.returnValue(sax.parse(string = content)) <NEW_LINE> <DEDENT> def cache(self): <NEW_LINE> <INDENT> if self.options.cachingpolicy == 0: <NEW_LINE> <INDENT> return self.options.cache <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NoCache()
The XML document reader provides an integration between the SAX L{Parser} and the document cache.
6259907716aa5153ce401e69
class gbdWebsuiteDockWidgetTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.dockwidget = gbdWebsuiteDockWidget(None) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.dockwidget = None <NEW_LINE> <DEDENT> def test_dockwidget_ok(self): <NEW_LINE> <INDENT> pass
Test dockwidget works.
6259907799cbb53fe6832874
class Error(Model): <NEW_LINE> <INDENT> def __init__(self, error_message: str=None, error_code: str=None, error_link: str=None, user_message: str=None): <NEW_LINE> <INDENT> self.swagger_types = { 'error_message': str, 'error_code': str, 'error_link': str, 'user_message': str } <NEW_LINE> self.attribute_map = { 'error_message': 'errorMessage', 'error_code': 'errorCode', 'error_link': 'errorLink', 'user_message': 'userMessage' } <NEW_LINE> self._error_message = error_message <NEW_LINE> self._error_code = error_code <NEW_LINE> self._error_link = error_link <NEW_LINE> self._user_message = user_message <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt) -> 'Error': <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def error_message(self) -> str: <NEW_LINE> <INDENT> return self._error_message <NEW_LINE> <DEDENT> @error_message.setter <NEW_LINE> def error_message(self, error_message: str): <NEW_LINE> <INDENT> if error_message is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `error_message`, must not be `None`") <NEW_LINE> <DEDENT> self._error_message = error_message <NEW_LINE> <DEDENT> @property <NEW_LINE> def error_code(self) -> str: <NEW_LINE> <INDENT> return self._error_code <NEW_LINE> <DEDENT> @error_code.setter <NEW_LINE> def error_code(self, error_code: str): <NEW_LINE> <INDENT> self._error_code = error_code <NEW_LINE> <DEDENT> @property <NEW_LINE> def error_link(self) -> str: <NEW_LINE> <INDENT> return self._error_link <NEW_LINE> <DEDENT> @error_link.setter <NEW_LINE> def error_link(self, error_link: str): <NEW_LINE> <INDENT> self._error_link = error_link <NEW_LINE> <DEDENT> @property <NEW_LINE> def user_message(self) -> str: <NEW_LINE> <INDENT> return self._user_message <NEW_LINE> <DEDENT> @user_message.setter <NEW_LINE> def user_message(self, user_message: str): <NEW_LINE> <INDENT> self._user_message = user_message
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62599077baa26c4b54d50c40
class Celula: <NEW_LINE> <INDENT> def __init__(self, v=0, p=1): <NEW_LINE> <INDENT> self.vertice = int(v) <NEW_LINE> self.peso = int(p) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.vertice == other.vertice
Classe que implementa uma celula de aresta
625990774f6381625f19a173
class TEST23(PMEM2_SOURCE_DEVDAX): <NEW_LINE> <INDENT> test_case = "test_pmem2_src_mcsafe_read_write_invalid_ftype"
test mcsafe read and write operations on source with invalid type on devdax
62599077e1aae11d1e7cf4d7
class CabButton: <NEW_LINE> <INDENT> def __init__(self, pin_no, name): <NEW_LINE> <INDENT> self.pin = Pin(pin_no, Pin.IN, Pin.PULL_UP) <NEW_LINE> self.name = name <NEW_LINE> self.out_button = None <NEW_LINE> self.auto_rate = "N/A" <NEW_LINE> self.active = 1 <NEW_LINE> self.inactive = 0 <NEW_LINE> self.ticks = 0 <NEW_LINE> <DEDENT> def debounce(self): <NEW_LINE> <INDENT> while self.pin.value() == 0: pass <NEW_LINE> utime.sleep_ms(250) <NEW_LINE> <DEDENT> def program(self, out_button, auto_rate): <NEW_LINE> <INDENT> print("Programming %s to %s with %s" % (self.name, out_button.name, auto_rate[0])) <NEW_LINE> self.out_button = out_button <NEW_LINE> self.auto_rate, self.active, self.inactive = auto_rate[0:3] <NEW_LINE> <DEDENT> def fire_if_pressed(self): <NEW_LINE> <INDENT> if self.out_button and self.pin.value() == 0: <NEW_LINE> <INDENT> if self.ticks < self.active: <NEW_LINE> <INDENT> self.out_button.should_fire = True <NEW_LINE> <DEDENT> self.ticks += 1 <NEW_LINE> if self.ticks >= (self.active + self.inactive): <NEW_LINE> <INDENT> self.ticks = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def serialized_state(self): <NEW_LINE> <INDENT> return "%s %s %d %d %s\n" % (self.name, self.out_button.name, self.active, self.inactive, self.auto_rate) <NEW_LINE> <DEDENT> def restore_state(self, line, out_jams): <NEW_LINE> <INDENT> _, out_name, active, inactive, self.auto_rate = line.strip().split() <NEW_LINE> for jam in out_jams: <NEW_LINE> <INDENT> if jam.name == out_name: <NEW_LINE> <INDENT> self.out_button = jam <NEW_LINE> <DEDENT> <DEDENT> self.active = int(active) <NEW_LINE> self.inactive = int(inactive)
Represents a physical button of a cabinet. Connects to cab panel.
625990772c8b7c6e89bd5179
class TestUtil(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls._work_dir = "test_fluiddyn_util_util" <NEW_LINE> if not os.path.exists(cls._work_dir): <NEW_LINE> <INDENT> os.mkdir(cls._work_dir) <NEW_LINE> <DEDENT> os.chdir(cls._work_dir) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> os.chdir("..") <NEW_LINE> rmtree(cls._work_dir) <NEW_LINE> <DEDENT> def test_util(self): <NEW_LINE> <INDENT> util.import_class("fluiddyn.output.figs", "Figures") <NEW_LINE> util.time_as_str(decimal=1) <NEW_LINE> util.is_run_from_ipython() <NEW_LINE> util.is_run_from_jupyter() <NEW_LINE> with stdout_redirected(): <NEW_LINE> <INDENT> util.print_memory_usage("test") <NEW_LINE> util.print_size_in_Mo(np.arange(4)) <NEW_LINE> util.print_size_in_Mo(np.arange(4), string="test") <NEW_LINE> print_fail("") <NEW_LINE> print_warning("") <NEW_LINE> cprint("bar", color="RED") <NEW_LINE> cprint.header("header") <NEW_LINE> cprint.light_blue("light_blue") <NEW_LINE> cprint.light_green("light_green") <NEW_LINE> cprint.light_gray("light_gray") <NEW_LINE> cprint.warning("warning") <NEW_LINE> cprint.fail("fail") <NEW_LINE> cprint.black("black") <NEW_LINE> cprint.red("bar", bold=True) <NEW_LINE> cprint.green("green") <NEW_LINE> cprint.yellow("yellow") <NEW_LINE> cprint.blue("blue") <NEW_LINE> cprint.magenta("magenta") <NEW_LINE> cprint.cyan("cyan") <NEW_LINE> cprint.white("white") <NEW_LINE> cstring("foo", color="GREEN") <NEW_LINE> <DEDENT> with util.print_options(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> util.config_logging() <NEW_LINE> load_user_conf_files() <NEW_LINE> <DEDENT> def test_copy_me(self): <NEW_LINE> <INDENT> util.copy_me_in(os.curdir) <NEW_LINE> <DEDENT> def test_mod_date(self): <NEW_LINE> <INDENT> util.modification_date(os.path.dirname(__file__)) <NEW_LINE> <DEDENT> def test_create_object(self): <NEW_LINE> <INDENT> o = MyObject() <NEW_LINE> o.save("myobject.h5") <NEW_LINE> util.create_object_from_file("object")
Test fluiddyn.util.util module.
625990773539df3088ecdc27
class SerializeReceiver(Receiver): <NEW_LINE> <INDENT> def __init__(self, format): <NEW_LINE> <INDENT> self.format = format <NEW_LINE> <DEDENT> def get_data(self, request, method): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> deserialized_objects = list(serializers.deserialize(self.format, request.raw_post_data)) <NEW_LINE> <DEDENT> except serializers.base.DeserializationError: <NEW_LINE> <INDENT> raise InvalidFormData <NEW_LINE> <DEDENT> if len(deserialized_objects) != 1: <NEW_LINE> <INDENT> raise InvalidFormData <NEW_LINE> <DEDENT> model = deserialized_objects[0].object <NEW_LINE> return model_to_dict(model)
Base class for all data formats possible within Django's serializer framework.
625990775fdd1c0f98e5f90e
class AzLexer(RegexLexer): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> commands = GatherCommands() <NEW_LINE> tokens = { 'root': [ (words( tuple(kid.data for kid in commands.command_tree.children), prefix=r'\b', suffix=r'\b'), Keyword), (words( tuple(commands.get_all_subcommands()), prefix=r'\b', suffix=r'\b'), Keyword.Declaration), (words( tuple(param for param in commands.completable_param + commands.global_param), prefix=r'', suffix=r'\b'), Name.Class), (r'.', Keyword), (r' .', Keyword), ] } <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> tokens = { 'root': [ (r' .', Number), (r'.', Number), ] }
A custom lexer for Azure CLI
62599077627d3e7fe0e08818
class ButtonMixin(object): <NEW_LINE> <INDENT> class Media: <NEW_LINE> <INDENT> js = ('js/admin-button.js',)
Prevent double-clicking button double save
62599077009cb60464d02ecc
class Terminated(BaseModel): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'terminated' <NEW_LINE> <DEDENT> code = CharField(8) <NEW_LINE> name = CharField(32) <NEW_LINE> o_date = CharField() <NEW_LINE> t_date = CharField() <NEW_LINE> insert_date = CharField()
沪深300成分及权重
62599077f9cc0f698b1c5f94
class VolumeTypeExtraSpecs(BASE, ManilaBase): <NEW_LINE> <INDENT> __tablename__ = 'volume_type_extra_specs' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> key = Column(String(255)) <NEW_LINE> value = Column(String(255)) <NEW_LINE> volume_type_id = Column(String(36), ForeignKey('volume_types.id'), nullable=False) <NEW_LINE> volume_type = relationship( VolumeTypes, backref="extra_specs", foreign_keys=volume_type_id, primaryjoin='and_(' 'VolumeTypeExtraSpecs.volume_type_id == VolumeTypes.id,' 'VolumeTypeExtraSpecs.deleted == False)' )
Represents additional specs as key/value pairs for a volume_type.
6259907771ff763f4b5e913c
class NewTypeExpr(Expression): <NEW_LINE> <INDENT> name = None <NEW_LINE> old_type = None <NEW_LINE> info = None <NEW_LINE> def __init__(self, name: str, old_type: 'mypy.types.Type', line: int) -> None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.old_type = old_type <NEW_LINE> <DEDENT> def accept(self, visitor: NodeVisitor[T]) -> T: <NEW_LINE> <INDENT> return visitor.visit_newtype_expr(self)
NewType expression NewType(...).
625990774f88993c371f11e9
class IncomeApiTestCase(NamedModelApiTestCase): <NEW_LINE> <INDENT> factory_class = factories.IncomeModelFactory <NEW_LINE> model_class = models.Income <NEW_LINE> serializer_class = serializers.IncomeSerializer <NEW_LINE> url_detail = "income-detail" <NEW_LINE> url_list = "income-list" <NEW_LINE> name = factories.IncomeModelFactory.name <NEW_LINE> def test_create_income(self): <NEW_LINE> <INDENT> self.verify_create_defaults() <NEW_LINE> <DEDENT> def test_create_income_partial(self): <NEW_LINE> <INDENT> self.verify_create_defaults_partial() <NEW_LINE> <DEDENT> def test_get_income(self): <NEW_LINE> <INDENT> self.verify_get_defaults() <NEW_LINE> <DEDENT> def test_put_income_partial(self): <NEW_LINE> <INDENT> self.verify_put_partial() <NEW_LINE> <DEDENT> def test_delete_income(self): <NEW_LINE> <INDENT> self.verify_delete_default()
Income API unit test class.
6259907744b2445a339b7626
class ExifItem(BaseModel): <NEW_LINE> <INDENT> image = models.ForeignKey(Image, on_delete=models.CASCADE) <NEW_LINE> key = models.CharField(max_length=255) <NEW_LINE> value_str = models.CharField(max_length=65536, null=True) <NEW_LINE> value_int = models.IntegerField(null=True) <NEW_LINE> value_float = models.FloatField(null=True) <NEW_LINE> def get_value(self): <NEW_LINE> <INDENT> if self.value_str: <NEW_LINE> <INDENT> return self.value_str <NEW_LINE> <DEDENT> if self.value_int: <NEW_LINE> <INDENT> return self.value_int <NEW_LINE> <DEDENT> if self.value_float: <NEW_LINE> <INDENT> return self.value_float <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f'ExifItem({self.key})' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'{self.key}'
Piece of exif info of a certain Image
6259907799cbb53fe6832876
class DiredOpenExternalCommand(TextCommand, DiredBaseCommand): <NEW_LINE> <INDENT> def run(self, edit): <NEW_LINE> <INDENT> path = self.path <NEW_LINE> files = self.get_selected(parent=False) <NEW_LINE> fname = join(path, files[0] if files else '') <NEW_LINE> p, f = os.path.split(fname.rstrip(os.sep)) <NEW_LINE> if not exists(fname): <NEW_LINE> <INDENT> return sublime.status_message(u'Directory doesn’t exist “%s”' % path) <NEW_LINE> <DEDENT> if sublime.platform() == 'windows' and path == 'ThisPC\\': <NEW_LINE> <INDENT> if not ST3: <NEW_LINE> <INDENT> fname = fname.encode(locale.getpreferredencoding(False)) <NEW_LINE> <DEDENT> return subprocess.Popen('explorer /select,"%s"' % fname) <NEW_LINE> <DEDENT> if files: <NEW_LINE> <INDENT> self.view.window().run_command("open_dir", {"dir": p, "file": f}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.view.window().run_command("open_dir", {"dir": path})
open dir/file in external file explorer
62599077be8e80087fbc0a25
class UserProfileFeedViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = serializers.ProfileFeedItemSerializer <NEW_LINE> queryset = models.ProfileFeedItem.objects.all() <NEW_LINE> authentication_classes = (TokenAuthentication,) <NEW_LINE> permission_classes = (permissions.UpdateOwnStatus, IsAuthenticated) <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(user_profile=self.request.user)
Handles creating, reading and updating profile feed items
62599077283ffb24f3cf523c
class StdInSocketChannel(ZMQSocketChannel): <NEW_LINE> <INDENT> msg_queue = None <NEW_LINE> def __init__(self, context, session, address): <NEW_LINE> <INDENT> super(StdInSocketChannel, self).__init__(context, session, address) <NEW_LINE> self.ioloop = ioloop.IOLoop() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.socket = self.context.socket(zmq.DEALER) <NEW_LINE> self.socket.setsockopt(zmq.IDENTITY, self.session.bsession) <NEW_LINE> self.socket.connect(self.address) <NEW_LINE> self.stream = zmqstream.ZMQStream(self.socket, self.ioloop) <NEW_LINE> self.stream.on_recv(self._handle_recv) <NEW_LINE> self._run_loop() <NEW_LINE> try: <NEW_LINE> <INDENT> self.socket.close() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.ioloop.stop() <NEW_LINE> super(StdInSocketChannel, self).stop() <NEW_LINE> <DEDENT> def call_handlers(self, msg): <NEW_LINE> <INDENT> raise NotImplementedError('call_handlers must be defined in a subclass.') <NEW_LINE> <DEDENT> def input(self, string): <NEW_LINE> <INDENT> content = dict(value=string) <NEW_LINE> msg = self.session.msg('input_reply', content) <NEW_LINE> self._queue_send(msg)
A reply channel to handle raw_input requests that the kernel makes.
625990773539df3088ecdc29
class TestVARMA(CheckFREDManufacturing): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setup_class(cls): <NEW_LINE> <INDENT> true = results_varmax.fred_varma11.copy() <NEW_LINE> true['predict'] = varmax_results.iloc[1:][['predict_varma11_1', 'predict_varma11_2']] <NEW_LINE> true['dynamic_predict'] = varmax_results.iloc[1:][[ 'dyn_predict_varma11_1', 'dyn_predict_varma11_2']] <NEW_LINE> super(TestVARMA, cls).setup_class( true, order=(1, 1), trend='n', error_cov_type='diagonal') <NEW_LINE> <DEDENT> def test_mle(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @pytest.mark.skip('Known failure: standard errors do not match.') <NEW_LINE> def test_bse_approx(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @pytest.mark.skip('Known failure: standard errors do not match.') <NEW_LINE> def test_bse_oim(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_aic(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_bic(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_predict(self): <NEW_LINE> <INDENT> super(TestVARMA, self).test_predict(end='2009-05-01', atol=1e-4) <NEW_LINE> <DEDENT> def test_dynamic_predict(self): <NEW_LINE> <INDENT> super(TestVARMA, self).test_dynamic_predict(end='2009-05-01', dynamic='2000-01-01') <NEW_LINE> <DEDENT> def test_summary(self): <NEW_LINE> <INDENT> summary = self.results.summary() <NEW_LINE> tables = [str(table) for table in summary.tables] <NEW_LINE> params = self.true['params'] <NEW_LINE> assert re.search(r'Model:.*VARMA\(1,1\)', tables[0]) <NEW_LINE> for i in range(self.model.k_endog): <NEW_LINE> <INDENT> offset_ar = i * self.model.k_endog <NEW_LINE> offset_ma = (self.model.k_endog**2 * self.model.k_ar + i * self.model.k_endog) <NEW_LINE> table = tables[i+2] <NEW_LINE> name = self.model.endog_names[i] <NEW_LINE> assert re.search('Results for equation %s' % name, table) <NEW_LINE> assert len(table.split('\n')) == 9 <NEW_LINE> assert re.search( 'L1.dlncaputil +' + forg(params[offset_ar + 0], prec=4), table) <NEW_LINE> assert re.search( 'L1.dlnhours +' + forg(params[offset_ar + 1], prec=4), table) <NEW_LINE> assert re.search( r'L1.e\(dlncaputil\) +' + forg(params[offset_ma + 0], prec=4), table) <NEW_LINE> assert re.search( r'L1.e\(dlnhours\) +' + forg(params[offset_ma + 1], prec=4), table) <NEW_LINE> <DEDENT> table = tables[-1] <NEW_LINE> assert re.search('Error covariance matrix', table) <NEW_LINE> assert len(table.split('\n')) == 7 <NEW_LINE> params = params[self.model._params_state_cov] <NEW_LINE> names = self.model.param_names[self.model._params_state_cov] <NEW_LINE> for i in range(len(names)): <NEW_LINE> <INDENT> assert re.search('%s +%s' % (names[i], forg(params[i], prec=4)), table)
Test against the sspace VARMA example with some params set to zeros.
625990775fdd1c0f98e5f90f
class WorkerTests(ChannelTestCase): <NEW_LINE> <INDENT> def test_channel_filters(self): <NEW_LINE> <INDENT> worker = Worker(None, only_channels=["yes.*", "maybe.*"]) <NEW_LINE> self.assertEqual( worker.apply_channel_filters(["yes.1", "no.1"]), ["yes.1"], ) <NEW_LINE> self.assertEqual( worker.apply_channel_filters(["yes.1", "no.1", "maybe.2", "yes"]), ["yes.1", "maybe.2"], ) <NEW_LINE> worker = Worker(None, exclude_channels=["no.*", "maybe.*"]) <NEW_LINE> self.assertEqual( worker.apply_channel_filters(["yes.1", "no.1", "maybe.2", "yes"]), ["yes.1", "yes"], ) <NEW_LINE> worker = Worker(None, exclude_channels=["no.*"], only_channels=["yes.*"]) <NEW_LINE> self.assertEqual( worker.apply_channel_filters(["yes.1", "no.1", "maybe.2", "yes"]), ["yes.1"], ) <NEW_LINE> <DEDENT> def test_run_with_consume_later_error(self): <NEW_LINE> <INDENT> def _consumer(message, **kwargs): <NEW_LINE> <INDENT> _consumer._call_count = getattr(_consumer, '_call_count', 0) + 1 <NEW_LINE> if _consumer._call_count == 1: <NEW_LINE> <INDENT> raise ConsumeLater() <NEW_LINE> <DEDENT> <DEDENT> Channel('test').send({'test': 'test'}) <NEW_LINE> channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER] <NEW_LINE> channel_layer.router.add_route(route('test', _consumer)) <NEW_LINE> old_send = channel_layer.send <NEW_LINE> channel_layer.send = mock.Mock(side_effect=old_send) <NEW_LINE> worker = PatchedWorker(channel_layer) <NEW_LINE> worker.termed = 2 <NEW_LINE> worker.run() <NEW_LINE> self.assertEqual(getattr(_consumer, '_call_count', None), 2) <NEW_LINE> self.assertEqual(channel_layer.send.call_count, 1) <NEW_LINE> <DEDENT> def test_normal_run(self): <NEW_LINE> <INDENT> consumer = mock.Mock() <NEW_LINE> Channel('test').send({'test': 'test'}) <NEW_LINE> channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER] <NEW_LINE> channel_layer.router.add_route(route('test', consumer)) <NEW_LINE> old_send = channel_layer.send <NEW_LINE> channel_layer.send = mock.Mock(side_effect=old_send) <NEW_LINE> worker = PatchedWorker(channel_layer) <NEW_LINE> worker.termed = 2 <NEW_LINE> worker.run() <NEW_LINE> self.assertEqual(consumer.call_count, 1) <NEW_LINE> self.assertEqual(channel_layer.send.call_count, 0)
Tests that the router's routing code works correctly.
6259907723849d37ff852a49
class Solution: <NEW_LINE> <INDENT> def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: <NEW_LINE> <INDENT> if root.val == p.val and self.find(root, q): <NEW_LINE> <INDENT> return root <NEW_LINE> <DEDENT> if root.val == q.val and self.find(root, p): <NEW_LINE> <INDENT> return root <NEW_LINE> <DEDENT> if (self.find(root.left, p) and self.find(root.right, q)) or ( self.find(root.left, q) and self.find(root.right, p) ): <NEW_LINE> <INDENT> return root <NEW_LINE> <DEDENT> if self.find(root.left, p) and self.find(root.left, q): <NEW_LINE> <INDENT> return self.lowestCommonAncestor(root.left, p, q) <NEW_LINE> <DEDENT> elif self.find(root.right, p) and self.find(root.right, q): <NEW_LINE> <INDENT> return self.lowestCommonAncestor(root.right, p, q) <NEW_LINE> <DEDENT> <DEDENT> def find(self, root: TreeNode, target: TreeNode )->bool: <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if root.val == target.val: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.find(root.left, target) or self.find(root.right, target)
当两个节点互为父子节点时,最近的公共节点就是父节点本身; 否则,必为一个节点在左子树,一个节点在右子树; 超时
62599077cc0a2c111447c79a
class TotalClashScoreReader(object): <NEW_LINE> <INDENT> def __init__(self, line=False, *args, **kwds): <NEW_LINE> <INDENT> self.readline(line) <NEW_LINE> <DEDENT> def readline(self, line=False): <NEW_LINE> <INDENT> if line: <NEW_LINE> <INDENT> self.clashscore = float(line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.clashscore = None <NEW_LINE> <DEDENT> <DEDENT> def report(self): <NEW_LINE> <INDENT> return "%.2f" % (self.clashscore) <NEW_LINE> <DEDENT> def _extra_report(self): <NEW_LINE> <INDENT> return ''
Reads the single value line produced by "phenix.clashscore verbose=False"
625990773346ee7daa338329
class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('username', 'last_login', 'first_name', 'last_name', 'email')
User name fields required.
62599077091ae356687065cd
class BinaryOperation(Operation): <NEW_LINE> <INDENT> def __init__(self, left: Operation, right: Operation): <NEW_LINE> <INDENT> self._left = left <NEW_LINE> self._right = right <NEW_LINE> <DEDENT> @property <NEW_LINE> def info(self): <NEW_LINE> <INDENT> return '{} {} {}'.format( get_contract_info(self._left), self._operation_name, get_contract_info(self._right) )
Operation combining two operations
625990777b180e01f3e49d2e
class LowerCaseProperty(_DerivedProperty): <NEW_LINE> <INDENT> def __init__(self, property, *args, **kwargs): <NEW_LINE> <INDENT> super(LowerCaseProperty, self).__init__( lambda self: property.__get__(self, type(self)).lower(), *args, **kwargs)
A convenience class for generating lower-cased fields for filtering. Example usage: >>> class Pet(db.Model): ... name = db.StringProperty(required=True) ... name_lower = LowerCaseProperty(name) >>> pet = Pet(name='Fido') >>> pet.name_lower 'fido'
625990775fcc89381b266e23
class WeatherAlert: <NEW_LINE> <INDENT> def __init__(self, alert): <NEW_LINE> <INDENT> self.title = alert.title <NEW_LINE> self.time = pytz.utc.localize(datetime.utcfromtimestamp(alert.time)) <NEW_LINE> try: <NEW_LINE> <INDENT> self.expires = pytz.utc.localize(datetime.utcfromtimestamp(alert.expires)) <NEW_LINE> <DEDENT> except PropertyUnavailable: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.uri = alert.uri <NEW_LINE> self.severity = alert.severity <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '<WeatherAlert: {title} at {time}>'.format(title=self.title, time=self.time) <NEW_LINE> <DEDENT> def expired(self, now=pytz.utc.localize(datetime.utcnow())): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return now > self.expires <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return now > self.time + timedelta(days=3) <NEW_LINE> <DEDENT> <DEDENT> def sha(self): <NEW_LINE> <INDENT> full_alert = self.title + str(self.time) <NEW_LINE> return sha256(full_alert.encode()).hexdigest()
This is for storing weather alerts. The fields are very similar to a ForecastAlert.
6259907756b00c62f0fb4265
class BNMF(NMF): <NEW_LINE> <INDENT> _LAMB_INCREASE_W = 1.1 <NEW_LINE> _LAMB_INCREASE_H = 1.1 <NEW_LINE> def update_h(self): <NEW_LINE> <INDENT> H1 = np.dot(self.W.T, self.data[:,:]) + 3.0*self._lamb_H*(self.H**2) <NEW_LINE> H2 = np.dot(np.dot(self.W.T,self.W), self.H) + 2*self._lamb_H*(self.H**3) + self._lamb_H*self.H + 10**-9 <NEW_LINE> self.H *= H1/H2 <NEW_LINE> self._lamb_W = self._LAMB_INCREASE_W * self._lamb_W <NEW_LINE> self._lamb_H = self._LAMB_INCREASE_H * self._lamb_H <NEW_LINE> <DEDENT> def update_w(self): <NEW_LINE> <INDENT> W1 = np.dot(self.data[:,:], self.H.T) + 3.0*self._lamb_W*(self.W**2) <NEW_LINE> W2 = np.dot(self.W, np.dot(self.H, self.H.T)) + 2.0*self._lamb_W*(self.W**3) + self._lamb_W*self.W + 10**-9 <NEW_LINE> self.W *= W1/W2 <NEW_LINE> <DEDENT> def factorize(self, niter=10, compute_w=True, compute_h=True, show_progress=False, compute_err=True): <NEW_LINE> <INDENT> self._lamb_W = 1.0/niter <NEW_LINE> self._lamb_H = 1.0/niter <NEW_LINE> NMF.factorize(self, niter=niter, compute_w=compute_w, compute_h=compute_h, show_progress=show_progress, compute_err=compute_err)
BNMF(data, data, num_bases=4) Binary Matrix Factorization. Factorize a data matrix into two matrices s.t. F = | data - W*H | is minimal. H and W are restricted to binary values. Parameters ---------- data : array_like, shape (_data_dimension, _num_samples) the input data num_bases: int, optional Number of bases to compute (column rank of W and row rank of H). 4 (default) Attributes ---------- W : "data_dimension x num_bases" matrix of basis vectors H : "num bases x num_samples" matrix of coefficients ferr : frobenius norm (after calling .factorize()) Example ------- Applying BNMF to some rather stupid data set: >>> import numpy as np >>> from bnmf import BNMF >>> data = np.array([[1.0, 0.0, 1.0], [0.0, 1.0, 1.0]]) Use 2 basis vectors -> W shape(data_dimension, 2). >>> bnmf_mdl = BNMF(data, num_bases=2) Set number of iterations to 5 and start computing the factorization. >>> bnmf_mdl.factorize(niter=5) The basis vectors are now stored in bnmf_mdl.W, the coefficients in bnmf_mdl.H. To compute coefficients for an existing set of basis vectors simply copy W to bnmf_mdl.W, and set compute_w to False: >>> data = np.array([[0.0], [1.0]]) >>> W = np.array([[1.0, 0.0], [0.0, 1.0]]) >>> bnmf_mdl = BNMF(data, num_bases=2) >>> bnmf_mdl.W = W >>> bnmf_mdl.factorize(niter=10, compute_w=False) The result is a set of coefficients bnmf_mdl.H, s.t. data = W * bnmf_mdl.H.
62599077167d2b6e312b825b
class UsageError(RuntimeError): <NEW_LINE> <INDENT> pass
Should be raised in case an error happens in the setup rather than the test.
62599077ec188e330fdfa23a
class NACCESSTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_NACCESS_rsa_file(self): <NEW_LINE> <INDENT> with open("PDB/1A8O.rsa") as rsa: <NEW_LINE> <INDENT> naccess = process_rsa_data(rsa) <NEW_LINE> <DEDENT> self.assertEqual(len(naccess), 66) <NEW_LINE> <DEDENT> def test_NACCESS_asa_file(self): <NEW_LINE> <INDENT> with open("PDB/1A8O.asa") as asa: <NEW_LINE> <INDENT> naccess = process_asa_data(asa) <NEW_LINE> <DEDENT> self.assertEqual(len(naccess), 524)
Tests for NACCESS parsing etc which don't need the binary tool. See also test_NACCESS_tool.py for run time testing with the tool.
625990777047854f46340d4d
class Menu(MenuComponent, metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self, name: str, description: str): <NEW_LINE> <INDENT> self.menu_components = [] <NEW_LINE> self.name = name <NEW_LINE> self.description = description <NEW_LINE> <DEDENT> def add(self, menu_component: MenuComponent): <NEW_LINE> <INDENT> self.menu_components.append(menu_component) <NEW_LINE> <DEDENT> def remove(self, menu_component: MenuComponent): <NEW_LINE> <INDENT> self.menu_components.remove(menu_component) <NEW_LINE> <DEDENT> def get_child(self, i: int): <NEW_LINE> <INDENT> return self.menu_components[i] <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_description(self): <NEW_LINE> <INDENT> return self.description <NEW_LINE> <DEDENT> def display(self): <NEW_LINE> <INDENT> print("\n{},{}\n-----------------".format(self.name, self.description)) <NEW_LINE> for menu_component in self.menu_components: <NEW_LINE> <INDENT> menu_component.display() <NEW_LINE> <DEDENT> <DEDENT> def create_iterator(self): <NEW_LINE> <INDENT> return CompositeIterator(iter(self.menu_components))
Menu class
62599077a8370b77170f1d61
class ApresentadoresViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Apresentadores.objects.all() <NEW_LINE> serializer_class = ApresentadoresSerializer
API endpoint that allows groups to be viewed or edited.
6259907792d797404e389825
class ArticlePost(models.Model): <NEW_LINE> <INDENT> author = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> avatar = models.ImageField(upload_to='article/%Y%m%d/', blank=True) <NEW_LINE> column = models.ForeignKey( ArticleColumn, null=True, blank=True, on_delete=models.CASCADE, related_name='article' ) <NEW_LINE> tags = TaggableManager(blank=True) <NEW_LINE> title = models.CharField(max_length=100) <NEW_LINE> body = models.TextField() <NEW_LINE> total_views = models.PositiveIntegerField(default=0) <NEW_LINE> likes = models.PositiveIntegerField(default=0) <NEW_LINE> created = models.DateTimeField(default=timezone.now) <NEW_LINE> updated = models.DateTimeField(auto_now=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('-created',) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('article:article_detail', args=[self.id]) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> article = super(ArticlePost, self).save(*args, **kwargs) <NEW_LINE> if self.avatar and not kwargs.get('update_fields'): <NEW_LINE> <INDENT> image = Image.open(self.avatar) <NEW_LINE> (x, y) = image.size <NEW_LINE> new_x = 400 <NEW_LINE> new_y = int(new_x * (y / x)) <NEW_LINE> resized_image = image.resize((new_x, new_y), Image.ANTIALIAS) <NEW_LINE> resized_image.save(self.avatar.path) <NEW_LINE> <DEDENT> return article <NEW_LINE> <DEDENT> def was_created_recently(self): <NEW_LINE> <INDENT> diff = timezone.now() - self.created <NEW_LINE> if diff.days == 0 and diff.seconds >= 0 and diff.seconds < 60: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
文章的 Model
625990779c8ee82313040e51