code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class DatasetCreate(BaseModel): <NEW_LINE> <INDENT> id: str <NEW_LINE> name: str <NEW_LINE> type: str <NEW_LINE> created_at: Optional[str] <NEW_LINE> description: Optional[str]
Fields information needed for POST
62598fc0a219f33f346c6a38
class MnistNet(nn.Module): <NEW_LINE> <INDENT> def __init__(self, pretrained=False): <NEW_LINE> <INDENT> super(MnistNet, self).__init__() <NEW_LINE> self.conv1 = nn.Conv2d(1, 20, 5, 1) <NEW_LINE> self.conv2 = nn.Conv2d(20, 50, 5, 1) <NEW_LINE> self.fc1 = nn.Linear(4 * 4 * 50, 500) <NEW_LINE> self.fc2 = nn.Linear(500, 10) <NEW_LINE> self.fc2.is_classifier = True <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> state_dict = torch.hub.load_state_dict_from_url( "https://github.com/JJGO/shrinkbench-models/raw/master/mnist/mnistnet.pt" ) <NEW_LINE> self.load_state_dict(state_dict) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = F.relu(self.conv1(x)) <NEW_LINE> x = F.max_pool2d(x, 2, 2) <NEW_LINE> x = F.relu(self.conv2(x)) <NEW_LINE> x = F.max_pool2d(x, 2, 2) <NEW_LINE> x = x.view(-1, 4 * 4 * 50) <NEW_LINE> x = F.relu(self.fc1(x)) <NEW_LINE> x = self.fc2(x) <NEW_LINE> return F.log_softmax(x, dim=1)
Small network designed for Mnist debugging
62598fc056ac1b37e630241e
class SeleniumTestCase(BasicTestCase): <NEW_LINE> <INDENT> driver = None <NEW_LINE> utils = None <NEW_LINE> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> super(SeleniumTestCase, cls).tearDownClass() <NEW_LINE> DriverWrappersPool.close_drivers_and_download_videos(cls.get_subclass_name()) <NEW_LINE> SeleniumTestCase.driver = None <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.driver_wrapper = DriverWrappersPool.get_default_wrapper() <NEW_LINE> if not SeleniumTestCase.driver: <NEW_LINE> <INDENT> if not self.config_files.config_directory: <NEW_LINE> <INDENT> self.config_files.set_config_directory(DriverWrappersPool.get_default_config_directory()) <NEW_LINE> <DEDENT> self.driver_wrapper.configure(True, self.config_files) <NEW_LINE> self.driver_wrapper.connect() <NEW_LINE> <DEDENT> SeleniumTestCase.driver = self.driver_wrapper.driver <NEW_LINE> self.utils = self.driver_wrapper.utils <NEW_LINE> self.reuse_driver = self.driver_wrapper.config.getboolean_optional('Driver', 'reuse_driver') <NEW_LINE> self.utils.set_implicit_wait() <NEW_LINE> super(SeleniumTestCase, self).setUp() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(SeleniumTestCase, self).tearDown() <NEW_LINE> test_name = self.get_subclassmethod_name().replace('.', '_') <NEW_LINE> if not self._test_passed: <NEW_LINE> <INDENT> DriverWrappersPool.capture_screenshots(test_name) <NEW_LINE> <DEDENT> DriverWrappersPool.save_all_webdriver_logs(self.get_subclassmethod_name(), self._test_passed) <NEW_LINE> restart_driver_fail = self.driver_wrapper.config.getboolean_optional('Driver', 'restart_driver_fail') <NEW_LINE> maintain_default = self.reuse_driver and (self._test_passed or not restart_driver_fail) <NEW_LINE> DriverWrappersPool.close_drivers_and_download_videos(test_name, self._test_passed, maintain_default) <NEW_LINE> if not maintain_default: <NEW_LINE> <INDENT> SeleniumTestCase.driver = None <NEW_LINE> <DEDENT> <DEDENT> def assert_screenshot(self, element, filename, threshold=0, exclude_elements=[], driver_wrapper=None, force=False): <NEW_LINE> <INDENT> file_suffix = self.get_method_name() <NEW_LINE> VisualTest(driver_wrapper, force).assert_screenshot(element, filename, file_suffix, threshold, exclude_elements) <NEW_LINE> <DEDENT> def assert_full_screenshot(self, filename, threshold=0, exclude_elements=[], driver_wrapper=None, force=False): <NEW_LINE> <INDENT> file_suffix = self.get_method_name() <NEW_LINE> VisualTest(driver_wrapper, force).assert_screenshot(None, filename, file_suffix, threshold, exclude_elements)
A class whose instances are Selenium test cases. Attributes: driver: webdriver instance utils: test utils instance :type driver: selenium.webdriver.remote.webdriver.WebDriver :type utils: toolium.utils.Utils
62598fc0a05bb46b3848aa9d
class PicsTable(BaseDataBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__('pic') <NEW_LINE> <DEDENT> def has_url(self, pic_url: str) -> bool: <NEW_LINE> <INDENT> row = self.session.query(self.table_name).filter(self.table_name.pic_url == pic_url).first() <NEW_LINE> result = True if row else False <NEW_LINE> return result <NEW_LINE> <DEDENT> def has_girl_name(self, girl_name: str) -> bool: <NEW_LINE> <INDENT> row = self.session.query(self.table_name).filter(self.table_name.girl_name == girl_name).first() <NEW_LINE> result = True if row else False <NEW_LINE> return result
图片信息的一些方法
62598fc066656f66f7d5a624
class UtteranceTarget: <NEW_LINE> <INDENT> action_id: int <NEW_LINE> def __init__(self, action_id): <NEW_LINE> <INDENT> self.action_id = action_id
the DTO-like class storing the training target of a single utterance of a dialog (to feed the GO-bot policy model)
62598fc03346ee7daa337761
class NSNitroNserrHostdown(NSNitroBaseErrors): <NEW_LINE> <INDENT> pass
Nitro error code 320 Host is down
62598fc04527f215b58ea100
class EntryKey(object): <NEW_LINE> <INDENT> def __init__(self, confkey, year, auth=None, dis=""): <NEW_LINE> <INDENT> self.confkey = confkey <NEW_LINE> self.auth = auth <NEW_LINE> self.year = int(year) % 100 <NEW_LINE> self.dis = dis <NEW_LINE> <DEDENT> _str_regexp = re.compile("^([a-zA-Z]+)(?::([a-zA-Z-_']+))?(\d+)(.*)$") <NEW_LINE> @classmethod <NEW_LINE> def from_string(cls, s): <NEW_LINE> <INDENT> r = cls._str_regexp.match(s) <NEW_LINE> if r is None: <NEW_LINE> <INDENT> raise EntryKeyParsingError(s) <NEW_LINE> <DEDENT> (confkey, auth, year, dis) = r.groups() <NEW_LINE> return cls(confkey, year, auth, dis) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.auth == None: <NEW_LINE> <INDENT> return "{0}{1:02d}{2}".format(self.confkey, self.year, self.dis) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "{0}:{1}{2:02d}{3}".format(self.confkey, self.auth, self.year, self.dis) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "EntryKey({0})".format(str(self)) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return str(self).__hash__() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (self.confkey == other.confkey and self.auth == other.auth and self.year == other.year and self.dis == other.dis)
Model an entry key in our bibliographies
62598fc0a8370b77170f0613
class NoType(object): <NEW_LINE> <INDENT> pass
Superclass for ``StrType`` and ``NumType`` classes. This class is the default type of ``Column`` and provides a base class for other data types.
62598fc0aad79263cf42ea07
class RequestCancelledError(StorageProtocolError): <NEW_LINE> <INDENT> pass
The request was cancelled.
62598fc055399d3f05626748
class File(Resource): <NEW_LINE> <INDENT> def __init__(self, name, content=None, **kwargs): <NEW_LINE> <INDENT> super(File, self).__init__('file', name, **kwargs) <NEW_LINE> self.content = content <NEW_LINE> <DEDENT> def dumps(self, inline=False): <NEW_LINE> <INDENT> if inline: <NEW_LINE> <INDENT> if self.content is not None: <NEW_LINE> <INDENT> self['content'] = self.content <NEW_LINE> del self.content <NEW_LINE> <DEDENT> self.type = 'file' <NEW_LINE> del self['source'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.type = 'cookbook_file' <NEW_LINE> <DEDENT> return super(File, self).dumps(inline)
Special Chef file or cookbook_file resource.
62598fc071ff763f4b5e79ae
class CalendarBase(object): <NEW_LINE> <INDENT> parser = NotImplemented <NEW_LINE> def __init__(self, source): <NEW_LINE> <INDENT> self.source = source <NEW_LINE> <DEDENT> def get_date(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> date_obj, period = self.parser.parse(self.source, settings) <NEW_LINE> return {'date_obj': date_obj, 'period': period} <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass
Base setup class for non-Gregorian calendar system. :param source: Date string passed to calendar parser. :type source: str|unicode
62598fc04c3428357761a4ef
class ContainerPropertiesInstanceView(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'restart_count': {'readonly': True}, 'current_state': {'readonly': True}, 'previous_state': {'readonly': True}, 'events': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'restart_count': {'key': 'restartCount', 'type': 'int'}, 'current_state': {'key': 'currentState', 'type': 'ContainerState'}, 'previous_state': {'key': 'previousState', 'type': 'ContainerState'}, 'events': {'key': 'events', 'type': '[Event]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ContainerPropertiesInstanceView, self).__init__(**kwargs) <NEW_LINE> self.restart_count = None <NEW_LINE> self.current_state = None <NEW_LINE> self.previous_state = None <NEW_LINE> self.events = None
The instance view of the container instance. Only valid in response. Variables are only populated by the server, and will be ignored when sending a request. :ivar restart_count: The number of times that the container instance has been restarted. :vartype restart_count: int :ivar current_state: Current container instance state. :vartype current_state: ~azure.mgmt.containerinstance.models.ContainerState :ivar previous_state: Previous container instance state. :vartype previous_state: ~azure.mgmt.containerinstance.models.ContainerState :ivar events: The events of the container instance. :vartype events: list[~azure.mgmt.containerinstance.models.Event]
62598fc04f6381625f1995db
class BashConfigParser(EnvironmentConfiguration): <NEW_LINE> <INDENT> COMMENT_LINE_SIGN = '#' <NEW_LINE> KEY_FIELD = 'key' <NEW_LINE> VALUE_FIELD = 'value' <NEW_LINE> def __init__(self, config_file=None): <NEW_LINE> <INDENT> EnvironmentConfiguration.__init__(self) <NEW_LINE> self.__config_basepath = os.curdir <NEW_LINE> self.__logger = logging.getLogger(self.__class__.__module__) <NEW_LINE> self.__logger.setLevel(logging.WARNING) <NEW_LINE> if config_file != None: <NEW_LINE> <INDENT> self.read(config_file) <NEW_LINE> <DEDENT> <DEDENT> def set_config_basepath(self, basepath): <NEW_LINE> <INDENT> self.__config_basepath = basepath <NEW_LINE> <DEDENT> def get_config_basepath(self): <NEW_LINE> <INDENT> return self.__config_basepath <NEW_LINE> <DEDENT> def add(self, key, value): <NEW_LINE> <INDENT> warnings.warn("use put instead", DeprecationWarning) <NEW_LINE> self.put(key, value) <NEW_LINE> <DEDENT> def __create_csv_reader(self, config_file): <NEW_LINE> <INDENT> return csv.DictReader(config_file, delimiter='=', fieldnames=[self.KEY_FIELD, self.VALUE_FIELD]) <NEW_LINE> <DEDENT> def __open_bash_file(self, config_path): <NEW_LINE> <INDENT> if not os.path.exists(config_path): <NEW_LINE> <INDENT> raise ConfigurationNotFoundWarning("Configuration file %s does not exist" % config_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config_file = open(config_path, "r") <NEW_LINE> return self.__create_csv_reader(config_file) <NEW_LINE> <DEDENT> <DEDENT> def __process_line(self, line, config_rel_to_basepath): <NEW_LINE> <INDENT> if line[self.VALUE_FIELD] != None: <NEW_LINE> <INDENT> self.put(line[self.KEY_FIELD], line[self.VALUE_FIELD]) <NEW_LINE> <DEDENT> elif line[self.KEY_FIELD].startswith('.') or line[self.KEY_FIELD].startswith('source'): <NEW_LINE> <INDENT> pathParts = line[self.KEY_FIELD].rpartition('/') <NEW_LINE> sub_config = pathParts[len(pathParts) - 1] <NEW_LINE> self.read(sub_config) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__logger.debug("Invalid config line in file %s: %s", config_rel_to_basepath, line) <NEW_LINE> <DEDENT> <DEDENT> def __process_lines(self, config_lines, config_rel_to_basepath = None): <NEW_LINE> <INDENT> for line in config_lines: <NEW_LINE> <INDENT> self.__logger.debug("Processing config line %s", line) <NEW_LINE> if not line[self.KEY_FIELD].startswith(self.COMMENT_LINE_SIGN): <NEW_LINE> <INDENT> self.__process_line(line, config_rel_to_basepath) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def read_list(self, config_lines): <NEW_LINE> <INDENT> config_lines = self.__create_csv_reader(config_lines) <NEW_LINE> self.__process_lines(config_lines) <NEW_LINE> <DEDENT> def read(self, config_rel_to_basepath_or_abspath): <NEW_LINE> <INDENT> self.__logger.debug("Processing config file %s", config_rel_to_basepath_or_abspath) <NEW_LINE> if os.path.isabs(config_rel_to_basepath_or_abspath): <NEW_LINE> <INDENT> config_path_rel_to_curdir = config_rel_to_basepath_or_abspath <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config_path_rel_to_curdir = os.path.join(self.__config_basepath, config_rel_to_basepath_or_abspath) <NEW_LINE> <DEDENT> config_lines = self.__open_bash_file(config_path_rel_to_curdir) <NEW_LINE> self.__process_lines(config_lines, config_rel_to_basepath_or_abspath)
Implementation of commons.config_extension_if.Configuration that parses bash-style scripts that contain definitions of shell/environment variables
62598fc0a219f33f346c6a3a
class BrokenTrafficLightMachine(StateMachine): <NEW_LINE> <INDENT> green = State('Green', initial=True) <NEW_LINE> yellow = State('Yellow') <NEW_LINE> blue = State('Blue') <NEW_LINE> cycle = green.to(yellow) | yellow.to(green)
A broken traffic light machine
62598fc05fcc89381b266266
class TeradataTableDataset(Dataset): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, 'linked_service_name': {'required': True}, } <NEW_LINE> _attribute_map = { 'additional_properties': {'key': '', 'type': '{object}'}, 'type': {'key': 'type', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'structure': {'key': 'structure', 'type': 'object'}, 'schema': {'key': 'schema', 'type': 'object'}, 'linked_service_name': {'key': 'linkedServiceName', 'type': 'LinkedServiceReference'}, 'parameters': {'key': 'parameters', 'type': '{ParameterSpecification}'}, 'annotations': {'key': 'annotations', 'type': '[object]'}, 'folder': {'key': 'folder', 'type': 'DatasetFolder'}, 'database': {'key': 'typeProperties.database', 'type': 'object'}, 'table': {'key': 'typeProperties.table', 'type': 'object'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(TeradataTableDataset, self).__init__(**kwargs) <NEW_LINE> self.type = 'TeradataTable' <NEW_LINE> self.database = kwargs.get('database', None) <NEW_LINE> self.table = kwargs.get('table', None)
The Teradata database dataset. All required parameters must be populated in order to send to Azure. :param additional_properties: Unmatched properties from the message are deserialized to this collection. :type additional_properties: dict[str, object] :param type: Required. Type of dataset.Constant filled by server. :type type: str :param description: Dataset description. :type description: str :param structure: Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement. :type structure: object :param schema: Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement. :type schema: object :param linked_service_name: Required. Linked service reference. :type linked_service_name: ~azure.synapse.artifacts.models.LinkedServiceReference :param parameters: Parameters for dataset. :type parameters: dict[str, ~azure.synapse.artifacts.models.ParameterSpecification] :param annotations: List of tags that can be used for describing the Dataset. :type annotations: list[object] :param folder: The folder that this Dataset is in. If not specified, Dataset will appear at the root level. :type folder: ~azure.synapse.artifacts.models.DatasetFolder :param database: The database name of Teradata. Type: string (or Expression with resultType string). :type database: object :param table: The table name of Teradata. Type: string (or Expression with resultType string). :type table: object
62598fc056ac1b37e6302420
class CancelOrStopIntentHandler(AbstractRequestHandler): <NEW_LINE> <INDENT> def can_handle(self, handler_input): <NEW_LINE> <INDENT> return (is_intent_name("AMAZON.CancelIntent")(handler_input) or is_intent_name("AMAZON.StopIntent")(handler_input)) <NEW_LINE> <DEDENT> def handle(self, handler_input): <NEW_LINE> <INDENT> logger.info("In CancelOrStopIntentHandler") <NEW_LINE> data = handler_input.attributes_manager.request_attributes["_"] <NEW_LINE> speech = data[prompts.STOP_MESSAGE] <NEW_LINE> handler_input.response_builder.speak(speech) <NEW_LINE> return handler_input.response_builder.response
Single handler for Cancel and Stop Intent.
62598fc0851cf427c66b84e9
class EncryptionAdapter(Adapter): <NEW_LINE> <INDENT> def _encode(self, obj, context): <NEW_LINE> <INDENT> return Utils.encrypt(json.dumps(obj).encode('utf-8') + b'\x00', context['_']['token']) <NEW_LINE> <DEDENT> def _decode(self, obj, context): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> decrypted = Utils.decrypt(obj, context['_']['token']) <NEW_LINE> decrypted = decrypted.rstrip(b"\x00") <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _LOGGER.debug("Unable to decrypt, returning raw bytes.") <NEW_LINE> return obj <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> jsoned = json.loads(decrypted.decode('utf-8')) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> _LOGGER.error("unable to parse json, was: %s", decrypted) <NEW_LINE> raise <NEW_LINE> <DEDENT> return jsoned
Adapter to handle communication encryption.
62598fc04f88993c371f0623
class VUserGroup(db.Model): <NEW_LINE> <INDENT> name = db.StringProperty()
Описание группы пользователей
62598fc07cff6e4e811b5c57
class CardNotInHandException(RegnancyException): <NEW_LINE> <INDENT> pass
The card can not be accessed, due it is not in the hand of the player
62598fc0dc8b845886d537ee
class PostgresqlSession(Session): <NEW_LINE> <INDENT> pickle_protocol = pickle.HIGHEST_PROTOCOL <NEW_LINE> def __init__(self, id=None, **kwargs): <NEW_LINE> <INDENT> Session.__init__(self, id, **kwargs) <NEW_LINE> self.cursor = self.db.cursor() <NEW_LINE> <DEDENT> def setup(cls, **kwargs): <NEW_LINE> <INDENT> for k, v in kwargs.items(): <NEW_LINE> <INDENT> setattr(cls, k, v) <NEW_LINE> <DEDENT> self.db = self.get_db() <NEW_LINE> <DEDENT> setup = classmethod(setup) <NEW_LINE> def __del__(self): <NEW_LINE> <INDENT> if self.cursor: <NEW_LINE> <INDENT> self.cursor.close() <NEW_LINE> <DEDENT> self.db.commit() <NEW_LINE> <DEDENT> def _exists(self): <NEW_LINE> <INDENT> self.cursor.execute('select data, expiration_time from session ' 'where id=%s', (self.id,)) <NEW_LINE> rows = self.cursor.fetchall() <NEW_LINE> return bool(rows) <NEW_LINE> <DEDENT> def _load(self): <NEW_LINE> <INDENT> self.cursor.execute('select data, expiration_time from session ' 'where id=%s', (self.id,)) <NEW_LINE> rows = self.cursor.fetchall() <NEW_LINE> if not rows: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> pickled_data, expiration_time = rows[0] <NEW_LINE> data = pickle.loads(pickled_data) <NEW_LINE> return data, expiration_time <NEW_LINE> <DEDENT> def _save(self, expiration_time): <NEW_LINE> <INDENT> pickled_data = pickle.dumps(self._data, self.pickle_protocol) <NEW_LINE> self.cursor.execute('update session set data = %s, ' 'expiration_time = %s where id = %s', (pickled_data, expiration_time, self.id)) <NEW_LINE> <DEDENT> def _delete(self): <NEW_LINE> <INDENT> self.cursor.execute('delete from session where id=%s', (self.id,)) <NEW_LINE> <DEDENT> def acquire_lock(self): <NEW_LINE> <INDENT> self.locked = True <NEW_LINE> self.cursor.execute('select id from session where id=%s for update', (self.id,)) <NEW_LINE> <DEDENT> def release_lock(self): <NEW_LINE> <INDENT> self.cursor.close() <NEW_LINE> self.locked = False <NEW_LINE> <DEDENT> def clean_up(self): <NEW_LINE> <INDENT> self.cursor.execute('delete from session where expiration_time < %s', (datetime.datetime.now(),))
Implementation of the PostgreSQL backend for sessions. It assumes a table like this:: create table session ( id varchar(40), data text, expiration_time timestamp ) You must provide your own get_db function.
62598fc023849d37ff8512e7
class WavelengthExplicitFile(ExplicitFile): <NEW_LINE> <INDENT> def get_explicit_axis(self): <NEW_LINE> <INDENT> return self._spectral_indices <NEW_LINE> <DEDENT> def get_secondary_axis(self): <NEW_LINE> <INDENT> return self.observations() <NEW_LINE> <DEDENT> def get_data_row(self, index): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def add_data_row(self, row): <NEW_LINE> <INDENT> if self._timepoints is None: <NEW_LINE> <INDENT> self._timepoints = [] <NEW_LINE> <DEDENT> self._timepoints.append(float(row.pop(0))) <NEW_LINE> if self._spectra is None: <NEW_LINE> <INDENT> self._spectra = [] <NEW_LINE> <DEDENT> self._spectra.append(float(row)) <NEW_LINE> <DEDENT> def get_format_name(self): <NEW_LINE> <INDENT> return DataFileType.wavelength_explicit <NEW_LINE> <DEDENT> def times(self): <NEW_LINE> <INDENT> return self.get_secondary_axis() <NEW_LINE> <DEDENT> def wavelengths(self): <NEW_LINE> <INDENT> return self.get_explicit_axis()
Represents a wavelength explicit file
62598fc097e22403b383b13c
class TestNcase0: <NEW_LINE> <INDENT> def test_ncase1(self): <NEW_LINE> <INDENT> assert ncase0(0, 100, 4, 5, 6, 7) == 4 <NEW_LINE> <DEDENT> def test_ncase2(self): <NEW_LINE> <INDENT> assert ncase0(2, 100, 4, 5, 6, 7) == 6 <NEW_LINE> <DEDENT> def test_ncase3(self): <NEW_LINE> <INDENT> assert ncase0(9, 100, 4, 5, 6, 7) == 100
Выбор по индексу от нуля
62598fc07d847024c075c5f0
class SMSResponse(object): <NEW_LINE> <INDENT> def __init__(self, sms, id, error_code, error_message, success): <NEW_LINE> <INDENT> self.sms = sms <NEW_LINE> self.id = id <NEW_LINE> self.error_code = error_code <NEW_LINE> self.error_message = error_message <NEW_LINE> self.success = success
An wrapper around an SMS reponse
62598fc050812a4eaa620d03
class TestSeekInfo(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return SeekInfo( count = 56, last_indexes = '0', pages = 56, per_page = 56 ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return SeekInfo( ) <NEW_LINE> <DEDENT> <DEDENT> def testSeekInfo(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True)
SeekInfo unit test stubs
62598fc05fc7496912d48395
class FreteBase(BaseModel): <NEW_LINE> <INDENT> nome: str = Field(..., description="Nome do frete.", example="Entrega Ninja") <NEW_LINE> valor_frete: float = Field(..., description="Valor final do frete.", example=12.00) <NEW_LINE> prazo_dias: int = Field(..., description="Prazo final do frete.", example=6)
Modelo base para resposta de frete
62598fc00fa83653e46f5119
class DefaultTransfer(Transfer): <NEW_LINE> <INDENT> def _initialize_transfer(self, in_vec, out_vec): <NEW_LINE> <INDENT> in_inds = self._in_inds <NEW_LINE> out_inds = self._out_inds <NEW_LINE> outs = {} <NEW_LINE> ins = {} <NEW_LINE> for key in in_inds: <NEW_LINE> <INDENT> if len(in_inds[key]) > 0: <NEW_LINE> <INDENT> ins[key] = in_inds[key] <NEW_LINE> outs[key] = out_inds[key] <NEW_LINE> <DEDENT> <DEDENT> self._in_inds = ins <NEW_LINE> self._out_inds = outs <NEW_LINE> <DEDENT> def transfer(self, in_vec, out_vec, mode='fwd'): <NEW_LINE> <INDENT> in_inds = self._in_inds <NEW_LINE> out_inds = self._out_inds <NEW_LINE> if mode == 'fwd': <NEW_LINE> <INDENT> do_complex = in_vec._vector_info._under_complex_step and out_vec._alloc_complex <NEW_LINE> for key in in_inds: <NEW_LINE> <INDENT> in_set_name, out_set_name = key <NEW_LINE> in_vec._data[in_set_name][in_inds[key]] = out_vec._data[out_set_name][out_inds[key]] <NEW_LINE> if do_complex: <NEW_LINE> <INDENT> in_vec._imag_data[in_set_name][in_inds[key]] = out_vec._imag_data[out_set_name][out_inds[key]] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for key in in_inds: <NEW_LINE> <INDENT> in_set_name, out_set_name = key <NEW_LINE> np.add.at( out_vec._data[out_set_name], out_inds[key], in_vec._data[in_set_name][in_inds[key]])
Default NumPy transfer.
62598fc071ff763f4b5e79b0
class Gateway (models.Model): <NEW_LINE> <INDENT> lat = models.FloatField(max_length = 25, null = False) <NEW_LINE> lng = models.FloatField(max_length = 25, null = False) <NEW_LINE> gateway_id = models.IntegerField(null = False) <NEW_LINE> description = models.CharField(max_length = 250, null = True)
A gateway is a connection between a DRT subnet and the rail or BRT network. Basically it is a rail or BRT station. lat : latitute of the gateway lng : longitude of the gateway gateway_id : unidque identifier of the gateway description : (optional) description of the gatway (e.g., Midtown Marta Station)
62598fc0bf627c535bcb16db
class Timer(object): <NEW_LINE> <INDENT> def __init__(self, max_number_seconds): <NEW_LINE> <INDENT> self._start_time = None <NEW_LINE> self.timeout_seconds = max_number_seconds <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self._start_time = time.time() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self._start_time = None <NEW_LINE> <DEDENT> def restart(self): <NEW_LINE> <INDENT> self.start() <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_expired(self): <NEW_LINE> <INDENT> if self._start_time is not None and self.timeout_seconds is not None: <NEW_LINE> <INDENT> if self.time_remaining < 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def timeout_seconds(self): <NEW_LINE> <INDENT> return self._max_number_seconds <NEW_LINE> <DEDENT> @timeout_seconds.setter <NEW_LINE> def timeout_seconds(self, value): <NEW_LINE> <INDENT> self._max_number_seconds = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def time_remaining(self): <NEW_LINE> <INDENT> if self._start_time is None: <NEW_LINE> <INDENT> if self.timeout_seconds is None: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.timeout_seconds <NEW_LINE> <DEDENT> <DEDENT> seconds_elapsed = time.time() - self._start_time <NEW_LINE> return self.timeout_seconds - seconds_elapsed
A generic timer. Implementation of the DICOM Upper Layer's ARTIM timer as per PS3.8 Section 9.1.5. The ARTIM timer is used by the state machine to monitor connection and response timeouts. This class may also be used as a general purpose expiry timer.
62598fc0656771135c4898a4
class TestAuthenticationRequest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testAuthenticationRequest(self): <NEW_LINE> <INDENT> model = swagger_client.models.authentication_request.AuthenticationRequest()
AuthenticationRequest unit test stubs
62598fc0ad47b63b2c5a7a8a
class Feed(Point): <NEW_LINE> <INDENT> _type = R_FEED <NEW_LINE> def get_template(self): <NEW_LINE> <INDENT> return self._client._get_point_data_handler_for(self).get_template() <NEW_LINE> <DEDENT> def share(self, data, mime=None, time=None): <NEW_LINE> <INDENT> evt = self.share_async(data, mime=mime, time=time) <NEW_LINE> self._client._wait_and_except_if_failed(evt) <NEW_LINE> <DEDENT> def share_async(self, data, mime=None, time=None): <NEW_LINE> <INDENT> logger.info("share() [lid=\"%s\",pid=\"%s\"]", self.lid, self.pid) <NEW_LINE> if mime is None and isinstance(data, PointDataObject): <NEW_LINE> <INDENT> data = data.to_dict() <NEW_LINE> <DEDENT> return self._client._request_point_share(self.lid, self.pid, data, mime, time) <NEW_LINE> <DEDENT> def get_recent_info(self): <NEW_LINE> <INDENT> evt = self._client._request_point_recent_info(self._type, self.lid, self.pid) <NEW_LINE> self._client._wait_and_except_if_failed(evt) <NEW_LINE> return evt.payload['recent'] <NEW_LINE> <DEDENT> def set_recent_config(self, max_samples=0): <NEW_LINE> <INDENT> evt = self._client._request_point_recent_config(self._type, self.lid, self.pid, max_samples) <NEW_LINE> self._client._wait_and_except_if_failed(evt) <NEW_LINE> return evt.payload
`Feeds` are advertised when a Thing has data to share. They are for out-going data which will get shared with any remote Things that have followed them. Feeds are one-to-many.
62598fc05166f23b2e243615
class WeatherView(View): <NEW_LINE> <INDENT> def dispatch_request(self): <NEW_LINE> <INDENT> api_key = app.config['OWM_API_KEY'] <NEW_LINE> city_id = app.config['OWM_CITY_ID'] <NEW_LINE> cache_file = app.config['OWM_CACHE_FILE'] <NEW_LINE> weather_data = get_owm_weather(api_key, city_id, cache_file) <NEW_LINE> app.logger.debug('Rendering weather site') <NEW_LINE> pprint.pprint(weather_data) <NEW_LINE> return render_template('weather.html', weather=weather_data, views=app.config['PLUGINS'])
View class for openweathermap data.
62598fc07d43ff248742751f
class PoolHistory(View): <NEW_LINE> <INDENT> def render(self): <NEW_LINE> <INDENT> user = User.by_id(self.session, int(self.request.matchdict['user_id'])) <NEW_LINE> if self.user.has_no_role: <NEW_LINE> <INDENT> if user.id != self.user.id: <NEW_LINE> <INDENT> return HTTPFound(location=route_url('list_request', self.request)) <NEW_LINE> <DEDENT> <DEDENT> if self.user.is_manager: <NEW_LINE> <INDENT> if ((user.id != self.user.id) and (user.manager_id != self.user.id)): <NEW_LINE> <INDENT> return HTTPFound(location=route_url('list_request', self.request)) <NEW_LINE> <DEDENT> <DEDENT> today = datetime.now() <NEW_LINE> year = int(self.request.params.get('year', today.year)) <NEW_LINE> start = datetime(2014, 5, 1) <NEW_LINE> years = [item for item in reversed(range(start.year, today.year + 1))] <NEW_LINE> pool_history = {} <NEW_LINE> pool_history['RTT'] = User.get_rtt_history(self.session, user, year) <NEW_LINE> if today.year > year: <NEW_LINE> <INDENT> if user.country == 'lu': <NEW_LINE> <INDENT> today = datetime(year, 12, 31) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> today = datetime(year, 5, 31) <NEW_LINE> <DEDENT> <DEDENT> history, restant = User.get_cp_history(self.session, user, year, today) <NEW_LINE> vac_class = user.get_cp_class(self.session) <NEW_LINE> cp_history = [] <NEW_LINE> pool_acquis = 0 <NEW_LINE> pool_restant = 0 <NEW_LINE> for idx, entry in enumerate(history): <NEW_LINE> <INDENT> if idx == 0: <NEW_LINE> <INDENT> pool_restant = restant[entry['date']] <NEW_LINE> <DEDENT> if entry['value'] < 0: <NEW_LINE> <INDENT> if user.country == 'lu': <NEW_LINE> <INDENT> pool_restant, pool_acquis = vac_class.consume( taken=entry['value'], restant=pool_restant, acquis=pool_acquis) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _, pool_restant, pool_acquis, _ = vac_class.consume( taken=entry['value'], restant=pool_restant, acquis=pool_acquis, n_1=0, extra=0) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> pool_acquis = pool_acquis + entry['value'] <NEW_LINE> <DEDENT> item = { 'date': entry['date'].strftime('%Y-%m-%d'), 'value': entry['value'], 'restant': pool_restant, 'acquis': pool_acquis, 'flavor': entry.get('flavor', ''), } <NEW_LINE> cp_history.append(item) <NEW_LINE> <DEDENT> pool_history['CP'] = cp_history <NEW_LINE> ret = {'user': user, 'year': year, 'years': years, 'pool_history': pool_history} <NEW_LINE> return ret
Display pool history balance changes for given user
62598fc04f88993c371f0624
class BaseViewlet(grok.Viewlet): <NEW_LINE> <INDENT> grok.baseclass() <NEW_LINE> grok.context(IItem) <NEW_LINE> grok.layer(ISantaTemplatesLayer) <NEW_LINE> grok.require('zope2.View') <NEW_LINE> grok.viewletmanager(SantaTopViewletManager)
Base Viewlet Class.
62598fc0a8370b77170f0616
class CMSPageListResponse(object): <NEW_LINE> <INDENT> def __init__(self, data=None, pagination=None): <NEW_LINE> <INDENT> self.swagger_types = { 'data': 'list[CMSPage]', 'pagination': 'Pagination' } <NEW_LINE> self.attribute_map = { 'data': 'data', 'pagination': 'pagination' } <NEW_LINE> self._data = data <NEW_LINE> self._pagination = pagination <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self._data <NEW_LINE> <DEDENT> @data.setter <NEW_LINE> def data(self, data): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> <DEDENT> @property <NEW_LINE> def pagination(self): <NEW_LINE> <INDENT> return self._pagination <NEW_LINE> <DEDENT> @pagination.setter <NEW_LINE> def pagination(self, pagination): <NEW_LINE> <INDENT> self._pagination = pagination <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fc07cff6e4e811b5c59
class ProjectAPI(APIBase): <NEW_LINE> <INDENT> __class__ = Project <NEW_LINE> reserved_keys = set(['id', 'created', 'updated', 'completed', 'contacted']) <NEW_LINE> def _create_instance_from_request(self, data): <NEW_LINE> <INDENT> inst = super(ProjectAPI, self)._create_instance_from_request(data) <NEW_LINE> default_category = get_categories()[0] <NEW_LINE> inst.category_id = default_category.id <NEW_LINE> return inst <NEW_LINE> <DEDENT> def _update_object(self, obj): <NEW_LINE> <INDENT> if not current_user.is_anonymous(): <NEW_LINE> <INDENT> obj.owner_id = current_user.id <NEW_LINE> <DEDENT> <DEDENT> def _validate_instance(self, project): <NEW_LINE> <INDENT> if project.short_name and is_reserved_name('project', project.short_name): <NEW_LINE> <INDENT> msg = "Project short_name is not valid, as it's used by the system." <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> <DEDENT> def _log_changes(self, old_project, new_project): <NEW_LINE> <INDENT> auditlogger.add_log_entry(old_project, new_project, current_user) <NEW_LINE> <DEDENT> def _forbidden_attributes(self, data): <NEW_LINE> <INDENT> for key in data.keys(): <NEW_LINE> <INDENT> if key in self.reserved_keys: <NEW_LINE> <INDENT> raise BadRequest("Reserved keys in payload")
Class for the domain object Project. It refreshes automatically the cache, and updates the project properly.
62598fc09f28863672818996
class TLBControlCheck(scan.ScannerCheck): <NEW_LINE> <INDENT> def __init__(self, address_space, **kwargs): <NEW_LINE> <INDENT> scan.ScannerCheck.__init__(self, address_space) <NEW_LINE> <DEDENT> def check(self, offset): <NEW_LINE> <INDENT> field_offset, field_size = vmcb_offsets.control_area["TLB_CONTROL"] <NEW_LINE> tlb_control = struct.unpack("<B", self.address_space.read(offset + field_offset, field_size))[0] <NEW_LINE> if not tlb_control & 255: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if not tlb_control ^ 0b1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if not tlb_control ^ 0b11: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return not tlb_control ^ 0b111 <NEW_LINE> <DEDENT> def skip(self, data, offset): <NEW_LINE> <INDENT> return 4096
TLB_CONTROL bits must be: 0x00: Do Nothing 0x01: Flush all TLB Entries 0x03: Flush this guest's TLB entries 0x07: Flush this guest's non-global TLB entries. All other values are reserved.
62598fc092d797404e388c7d
class TrainModel(object): <NEW_LINE> <INDENT> def __init__(self, data, labels, emb_keep, rnn_keep): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.labels = labels <NEW_LINE> self.emb_keep = emb_keep <NEW_LINE> self.rnn_keep = rnn_keep <NEW_LINE> self.global_step <NEW_LINE> self.cell <NEW_LINE> self.predict <NEW_LINE> self.loss <NEW_LINE> self.optimize <NEW_LINE> <DEDENT> @define_scope <NEW_LINE> def cell(self): <NEW_LINE> <INDENT> lstm_cell = [ tf.nn.rnn_cell.DropoutWrapper(tf.nn.rnn_cell.BasicLSTMCell(HIDDEN_SIZE), output_keep_prob=self.rnn_keep) for _ in range(NUM_LAYERS)] <NEW_LINE> cell = tf.nn.rnn_cell.MultiRNNCell(lstm_cell) <NEW_LINE> return cell <NEW_LINE> <DEDENT> @define_scope <NEW_LINE> def predict(self): <NEW_LINE> <INDENT> embedding = tf.get_variable('embedding', shape=[setting.VOCAB_SIZE, HIDDEN_SIZE]) <NEW_LINE> if setting.SHARE_EMD_WITH_SOFTMAX: <NEW_LINE> <INDENT> softmax_weights = tf.transpose(embedding) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> softmax_weights = tf.get_variable('softmaweights', shape=[HIDDEN_SIZE, setting.VOCAB_SIZE]) <NEW_LINE> <DEDENT> softmax_bais = tf.get_variable('softmax_bais', shape=[setting.VOCAB_SIZE]) <NEW_LINE> emb = tf.nn.embedding_lookup(embedding, self.data) <NEW_LINE> emb_dropout = tf.nn.dropout(emb, self.emb_keep) <NEW_LINE> self.init_state = self.cell.zero_state(setting.BATCH_SIZE, dtype=tf.float32) <NEW_LINE> outputs, last_state = tf.nn.dynamic_rnn(self.cell, emb_dropout, scope='d_rnn', dtype=tf.float32, initial_state=self.init_state) <NEW_LINE> outputs = tf.reshape(outputs, [-1, HIDDEN_SIZE]) <NEW_LINE> logits = tf.matmul(outputs, softmax_weights) + softmax_bais <NEW_LINE> return logits <NEW_LINE> <DEDENT> @define_scope <NEW_LINE> def loss(self): <NEW_LINE> <INDENT> outputs_target = tf.reshape(self.labels, [-1]) <NEW_LINE> loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.predict, labels=outputs_target, ) <NEW_LINE> cost = tf.reduce_mean(loss) <NEW_LINE> return cost <NEW_LINE> <DEDENT> @define_scope <NEW_LINE> def global_step(self): <NEW_LINE> <INDENT> global_step = tf.Variable(0, trainable=False) <NEW_LINE> return global_step <NEW_LINE> <DEDENT> @define_scope <NEW_LINE> def optimize(self): <NEW_LINE> <INDENT> learn_rate = tf.train.exponential_decay(setting.LEARN_RATE, self.global_step, setting.LR_DECAY_STEP, setting.LR_DECAY) <NEW_LINE> trainable_variables = tf.trainable_variables() <NEW_LINE> grads, _ = tf.clip_by_global_norm(tf.gradients(self.loss, trainable_variables), setting.MAX_GRAD) <NEW_LINE> optimizer = tf.train.AdamOptimizer(learn_rate) <NEW_LINE> train_op = optimizer.apply_gradients(zip(grads, trainable_variables), self.global_step) <NEW_LINE> return train_op
训练模型
62598fc0fff4ab517ebcda1b
class BlockResponse: <NEW_LINE> <INDENT> VALIDATOR = Draft7Validator( json.loads( ( importlib_resources.files("checkmatelib.resource") / "response_schema.json" ).read_bytes() ) ) <NEW_LINE> def __init__(self, payload): <NEW_LINE> <INDENT> for error in self.VALIDATOR.iter_errors(payload): <NEW_LINE> <INDENT> raise CheckmateException(f"Unparseable response: {error}") <NEW_LINE> <DEDENT> self._payload = payload <NEW_LINE> <DEDENT> @property <NEW_LINE> def presentation_url(self): <NEW_LINE> <INDENT> return self._payload["links"]["html"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def reason_codes(self): <NEW_LINE> <INDENT> return [reason["id"] for reason in self._payload["data"]] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"BlockResponse({repr(self._payload)})"
A response from the Checkmate service with reasons to block.
62598fc0a8370b77170f0617
class FlujoSecuencia(models.Model): <NEW_LINE> <INDENT> actual = models.IntegerField() <NEW_LINE> siguiente = models.IntegerField() <NEW_LINE> proceso = models.ForeignKey(Proceso)
Modelo Flujo Contiene las secuencias de los flujos para cada proceso creado -> Nota Importante: el actual y el siguiente son relacion del objeto Flujo <- Descripcion: - actual: posicion actual del flujo en la secuencia - siguiente: posicion que deberia ir en la secuencia - proceso: proceso que pertenece esta secuencia
62598fc05fc7496912d48396
class Size(IntEnum): <NEW_LINE> <INDENT> TINY = 0 <NEW_LINE> SMALL = 1 <NEW_LINE> MEDIUM = 2 <NEW_LINE> LARGE = 3 <NEW_LINE> HUGE = 4 <NEW_LINE> def __lt__(self, other): <NEW_LINE> <INDENT> if self.__class__ is other.__class__: <NEW_LINE> <INDENT> return self.value < other.value <NEW_LINE> <DEDENT> return NotImplemented <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> if self.__class__ is other.__class__: <NEW_LINE> <INDENT> return self.value <= other.value <NEW_LINE> <DEDENT> return NotImplemented <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> if self.__class__ is other.__class__: <NEW_LINE> <INDENT> return self.value > other.value <NEW_LINE> <DEDENT> return NotImplemented <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> if self.__class__ is other.__class__: <NEW_LINE> <INDENT> return self.value >= other.value <NEW_LINE> <DEDENT> return NotImplemented <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if self.__class__ is other.__class__: <NEW_LINE> <INDENT> return self.value == other.value <NEW_LINE> <DEDENT> return NotImplemented <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if self.__class__ is other.__class__: <NEW_LINE> <INDENT> return self.value != other.value <NEW_LINE> <DEDENT> return NotImplemented
Component Enum detailing Size of an Entity TODO: comparisons will be used for Ramming actions
62598fc05fdd1c0f98e5e1c8
class TestPawnMoves(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.chess_board = ChessBoard() <NEW_LINE> <DEDENT> def test_pawn_can_move_forward(self): <NEW_LINE> <INDENT> self.assertIsNone(self.chess_board[(2, 3)]) <NEW_LINE> ends = list(self.chess_board.valid_moves((1, 3)).keys()) <NEW_LINE> self.assertEqual(ends, [(2, 3), (3, 3)]) <NEW_LINE> <DEDENT> def test_pawn_cant_move_forward_twice_if_not_first_move(self): <NEW_LINE> <INDENT> self.assertIsNone(self.chess_board[(2, 3)]) <NEW_LINE> self.assertIsNone(self.chess_board[(3, 3)]) <NEW_LINE> self.assertIsNone(self.chess_board[(4, 3)]) <NEW_LINE> self.chess_board.move((1, 3), (2, 3)) <NEW_LINE> ends = list(self.chess_board.valid_moves((2, 3)).keys()) <NEW_LINE> self.assertEqual(ends, [(3, 3)]) <NEW_LINE> <DEDENT> def test_white_pawn_promotion(self): <NEW_LINE> <INDENT> promotion_location = (7, 2) <NEW_LINE> self.chess_board[(6, 1)] = self.chess_board[(1, 1)] <NEW_LINE> self.chess_board.move((6, 1), promotion_location) <NEW_LINE> self.assertTrue(self.chess_board[promotion_location].promote_me_daddy) <NEW_LINE> self.chess_board.promote(promotion_location, 'rook') <NEW_LINE> self.assertEqual(self.chess_board[promotion_location].kind, 'rook') <NEW_LINE> <DEDENT> def test_pawn_cant_promote_just_anywhere(self): <NEW_LINE> <INDENT> promotion_location = (2, 1) <NEW_LINE> self.chess_board.move((1, 1), promotion_location) <NEW_LINE> self.assertFalse(self.chess_board[promotion_location].promote_me_daddy) <NEW_LINE> self.chess_board.promote(promotion_location, 'rook') <NEW_LINE> self.assertEqual(self.chess_board[promotion_location].kind, 'pawn')
Chess movement unit tests.
62598fc07047854f4633f60a
class Injector(): <NEW_LINE> <INDENT> mark_id = None <NEW_LINE> only = None <NEW_LINE> def __init__(self, only: dict = None): <NEW_LINE> <INDENT> self.mark_id = 1 <NEW_LINE> self.only = only <NEW_LINE> <DEDENT> def inject(self, result: ParseResult): <NEW_LINE> <INDENT> with open(result.filename) as f: <NEW_LINE> <INDENT> lines = f.readlines() <NEW_LINE> <DEDENT> new_lines = {0: get_perf_include()} <NEW_LINE> print_queue = [] <NEW_LINE> functions = [] <NEW_LINE> try: <NEW_LINE> <INDENT> functions += list(result.d['functions'].items()) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> functions += list(result.d['methods'].items()) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> for _, func in functions: <NEW_LINE> <INDENT> if not func['definition']: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> start = func['start'] <NEW_LINE> end = func['end'] <NEW_LINE> if self.only is not None and len(self.only[str(result.filename)]) > 0: <NEW_LINE> <INDENT> if func['spelling'] not in self.only[str(result.filename)]: <NEW_LINE> <INDENT> present = False <NEW_LINE> for line in self.only[str(result.filename)]: <NEW_LINE> <INDENT> if start < line < end: <NEW_LINE> <INDENT> present = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not present: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if banner in lines[start + 1]: <NEW_LINE> <INDENT> print_queue.append(already_annotated.format(func=func['spelling'], file=result.filename)) <NEW_LINE> continue <NEW_LINE> <DEDENT> print_queue.append(annotating.format(func=func['spelling'], file=result.filename)) <NEW_LINE> new_lines[start + 1] = get_perf_start(self.mark_id) <NEW_LINE> self.mark_id += 1 <NEW_LINE> search = lines[start:end] <NEW_LINE> return_found = False <NEW_LINE> for i, s in enumerate(search): <NEW_LINE> <INDENT> if s.strip().startswith('return'): <NEW_LINE> <INDENT> if start + i in new_lines: <NEW_LINE> <INDENT> print_queue.pop() <NEW_LINE> del new_lines[start + i] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_lines[start + i] = get_perf_end() <NEW_LINE> <DEDENT> return_found = True <NEW_LINE> <DEDENT> <DEDENT> if not return_found: <NEW_LINE> <INDENT> new_lines[end - 1] = get_perf_end() <NEW_LINE> <DEDENT> <DEDENT> for s in print_queue: <NEW_LINE> <INDENT> log.info(s) <NEW_LINE> <DEDENT> new_lines = OrderedDict(sorted(new_lines.items())) <NEW_LINE> new_file = deepcopy(lines) <NEW_LINE> for line_num, text in reversed(new_lines.items()): <NEW_LINE> <INDENT> new_file[line_num:line_num] = text <NEW_LINE> <DEDENT> with open(result.filename, 'w') as f: <NEW_LINE> <INDENT> f.write(''.join(new_file))
Custom class for injecting perfpoint banners into a codebase.
62598fc04a966d76dd5ef10b
class GlobalGrokker(GrokkerBase): <NEW_LINE> <INDENT> def grok(self, name, obj, **kw): <NEW_LINE> <INDENT> raise NotImplementedError
Grokker that groks once per module.
62598fc04428ac0f6e65875a
class DeleteSecurityGroupsRuleRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v1"): <NEW_LINE> <INDENT> super(DeleteSecurityGroupsRuleRequest, self).__init__( '/regions/{regionId}/vpc_securityGroups/{id}/rule', 'DELETE', header, version) <NEW_LINE> self.parameters = parameters
删除安全组规则
62598fc057b8e32f52508239
class StorageExistsRequest(object): <NEW_LINE> <INDENT> def __init__(self, storage_name): <NEW_LINE> <INDENT> self.storage_name = storage_name
Request model for storage_exists operation. :param storage_name Storage name
62598fc04f88993c371f0625
class Column(object): <NEW_LINE> <INDENT> def __init__(self, field_name, read_format=None, primary_key=-1): <NEW_LINE> <INDENT> if not field_name: <NEW_LINE> <INDENT> raise HbaseException("column name must not be null") <NEW_LINE> <DEDENT> if read_format is not None: <NEW_LINE> <INDENT> if not hasattr(read_format,'__call__'): <NEW_LINE> <INDENT> raise HbaseException("'%s' is not a function" % read_format) <NEW_LINE> <DEDENT> <DEDENT> self.field_name = field_name.encode("UTF8") <NEW_LINE> self.read_format = read_format <NEW_LINE> self.primary_key = primary_key <NEW_LINE> <DEDENT> def getValue(self, value): <NEW_LINE> <INDENT> if self.read_format is None: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return self.read_format(value)
hbase column definition class
62598fc056ac1b37e6302424
class Proposal(models.Model): <NEW_LINE> <INDENT> id_num = models.AutoField(primary_key=True) <NEW_LINE> author = models.ForeignKey(Person, related_name="author") <NEW_LINE> title = models.CharField(max_length=70) <NEW_LINE> problem = models.CharField(max_length=300) <NEW_LINE> solution = models.CharField(max_length=300) <NEW_LINE> benefits = models.CharField(max_length=300) <NEW_LINE> upvotes = models.PositiveIntegerField(default=0) <NEW_LINE> downvotes = models.PositiveIntegerField(default=0) <NEW_LINE> views = models.PositiveIntegerField(default=0) <NEW_LINE> timestamp = models.DateTimeField() <NEW_LINE> objects = ProposalManager() <NEW_LINE> def score(self): <NEW_LINE> <INDENT> return self.upvotes - self.downvotes <NEW_LINE> <DEDENT> def total_votes(self): <NEW_LINE> <INDENT> return self.upvotes + self.downvotes <NEW_LINE> <DEDENT> def set_upvotes(self, number): <NEW_LINE> <INDENT> if(number >= 0): <NEW_LINE> <INDENT> self.upvotes = number <NEW_LINE> <DEDENT> <DEDENT> def set_downvotes(self, number): <NEW_LINE> <INDENT> if(number >= 0): <NEW_LINE> <INDENT> self.downvotes = number <NEW_LINE> <DEDENT> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.title
This class represents a suggestion that's started by a Person and voted by other Persons. A proposal is backed up by the author's arguments and other Persons' Opinions.
62598fc08a349b6b43686475
class ServiceVistax86(obj.ProfileModification): <NEW_LINE> <INDENT> before = ['WindowsOverlay', 'WindowsObjectClasses', 'ServiceBase'] <NEW_LINE> conditions = {'os': lambda x: x == 'windows', 'major': lambda x: x == 6, 'minor': lambda x: x < 2, 'memory_model': lambda x: x == '32bit'} <NEW_LINE> def modification(self, profile): <NEW_LINE> <INDENT> profile.merge_overlay({'_SERVICE_RECORD': [ None, { 'PrevEntry': [ 0x0, ['pointer', ['_SERVICE_RECORD']]], 'ServiceName': [ 0x4, ['pointer', ['String', dict(encoding = 'utf16', length = 512)]]], 'DisplayName': [ 0x8, ['pointer', ['String', dict(encoding = 'utf16', length = 512)]]], 'Order': [ 0xC, ['unsigned int']], 'ServiceProcess': [ 0x1C, ['pointer', ['_SERVICE_PROCESS']]], 'DriverName': [ 0x1C, ['pointer', ['String', dict(encoding = 'utf16', length = 256)]]], 'Type' : [ 0x20, ['Flags', {'bitmap': SERVICE_TYPE_FLAGS}]], 'State': [ 0x24, ['Enumeration', dict(target = 'long', choices = SERVICE_STATE_ENUM)]], 'Start' : [ 0x3C, ['Enumeration', dict(target = 'long', choices = SERVICE_START_ENUM)]], }]})
Override the base with vtypes for x86 Vista, 2008, and 7
62598fc03d592f4c4edbb0f4
class SNS_HTTPRequestHandler(BaseHTTPRequestHandler): <NEW_LINE> <INDENT> def do_POST(self): <NEW_LINE> <INDENT> if self.path != self.server.fs.http_listen_path: <NEW_LINE> <INDENT> self.send_response(404) <NEW_LINE> return <NEW_LINE> <DEDENT> content_len = int(self.headers.getheader('content-length')) <NEW_LINE> post_body = self.rfile.read(content_len) <NEW_LINE> message_type = self.headers.getheader('x-amz-sns-message-type') <NEW_LINE> message_content = json.loads(post_body) <NEW_LINE> url = message_content['SigningCertURL'] <NEW_LINE> if not hasattr(self, 'certificate_url') or self.certificate_url != url: <NEW_LINE> <INDENT> logger.debug('downloading certificate') <NEW_LINE> self.certificate_url = url <NEW_LINE> self.certificate = urlopen(url).read() <NEW_LINE> <DEDENT> signature_version = message_content['SignatureVersion'] <NEW_LINE> if signature_version != '1': <NEW_LINE> <INDENT> logger.debug('unknown signature version') <NEW_LINE> self.send_response(404) <NEW_LINE> return <NEW_LINE> <DEDENT> signature = message_content['Signature'] <NEW_LINE> del message_content['SigningCertURL'] <NEW_LINE> del message_content['SignatureVersion'] <NEW_LINE> del message_content['Signature'] <NEW_LINE> if 'UnsubscribeURL' in message_content: <NEW_LINE> <INDENT> del message_content['UnsubscribeURL'] <NEW_LINE> <DEDENT> string_to_sign = '\n'.join(list(itertools.chain.from_iterable( [ (k, message_content[k]) for k in sorted(message_content.keys()) ] ))) + '\n' <NEW_LINE> import M2Crypto <NEW_LINE> cert = M2Crypto.X509.load_cert_string(self.certificate) <NEW_LINE> pub_key = cert.get_pubkey().get_rsa() <NEW_LINE> verify_evp = M2Crypto.EVP.PKey() <NEW_LINE> verify_evp.assign_rsa(pub_key) <NEW_LINE> verify_evp.reset_context(md='sha1') <NEW_LINE> verify_evp.verify_init() <NEW_LINE> verify_evp.verify_update(string_to_sign.encode('ascii')) <NEW_LINE> if verify_evp.verify_final(signature.decode('base64')): <NEW_LINE> <INDENT> self.send_response(200) <NEW_LINE> if message_type== 'Notification': <NEW_LINE> <INDENT> message = message_content['Message'] <NEW_LINE> logger.debug('message = %s' % message) <NEW_LINE> self.server.fs.process_message(message) <NEW_LINE> <DEDENT> elif message_type == 'SubscriptionConfirmation': <NEW_LINE> <INDENT> token = message_content['Token'] <NEW_LINE> response = self.server.fs.sns.confirm_subscription(self.server.fs.sns_topic_arn, token) <NEW_LINE> self.server.fs.http_subscription = response['ConfirmSubscriptionResponse']['ConfirmSubscriptionResult']['SubscriptionArn'] <NEW_LINE> logger.debug('SNS HTTP subscription = %s' % self.server.fs.http_subscription) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug('unknown message type') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug('wrong signature') <NEW_LINE> <DEDENT> self.send_response(404) <NEW_LINE> <DEDENT> def do_GET(self): <NEW_LINE> <INDENT> logger.debug('http get') <NEW_LINE> self.send_response(404) <NEW_LINE> <DEDENT> def do_HEAD(self): <NEW_LINE> <INDENT> logger.debug('http head') <NEW_LINE> self.send_response(404)
HTTP Request Handler to receive SNS notifications via HTTP
62598fc07cff6e4e811b5c5b
class stock_picking_mezzo(orm.Model): <NEW_LINE> <INDENT> _name = "stock.picking.mezzo" <NEW_LINE> _description = "Spedizione mezzo" <NEW_LINE> _columns = { 'name':fields.char('Spedizione mezzo', size=64, readonly=False), 'note': fields.text('Note'), }
Mezzo
62598fc099fddb7c1ca62f08
class Zero(EquationTerm): <NEW_LINE> <INDENT> def __init__(self, operator: Callable = None): <NEW_LINE> <INDENT> super().__init__( sources=set([]), sinks=set([]), operations=OperationsSet([], operator=operator), operator=operator) <NEW_LINE> <DEDENT> def __mul__(self, anext: Category) -> Category: <NEW_LINE> <INDENT> return MediateTerm( sinks=set([]), sources=anext.sources, operations=anext.operations, operator=anext.operator, processed_term=ProcessedTerm(self, CategoryOperations.ARROW, anext)) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return 'O' <NEW_LINE> <DEDENT> def is_identity(self) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def is_zero(self) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def needs_parenthesis_on_print(self) -> bool: <NEW_LINE> <INDENT> return False
>>> I, O, C = from_operator(debug) >>> (C(1) - C(1)) == O True >>> O ==(I) False >>> O ==(O) True >>> O ==(I*I) False >>> O ==(I+I) False >>> O ==(I-I) True >>> O ==(I-O) False >>> O ==(O*I) False >>> O ==(O+I) False >>> O ==(O-I) True >>> O ==(O+O) True
62598fc050812a4eaa620d05
class MainHandler(StaticFileHandler): <NEW_LINE> <INDENT> async def get(self, *args, **kwargs): <NEW_LINE> <INDENT> await super().get('index.html', *args, **kwargs)
为了使用Vue Router的history模式,把所有请求转发到index.html
62598fc05fdd1c0f98e5e1ca
class RMSWriter(object): <NEW_LINE> <INDENT> def __init__(self, output_directory=''): <NEW_LINE> <INDENT> super(RMSWriter, self).__init__() <NEW_LINE> self.output_directory = output_directory <NEW_LINE> make_output_subdirectory(output_directory, 'rms') <NEW_LINE> <DEDENT> def update(self, rmg): <NEW_LINE> <INDENT> solvent_data = None <NEW_LINE> if rmg.solvent: <NEW_LINE> <INDENT> solvent_data = rmg.database.solvation.get_solvent_data(rmg.solvent) <NEW_LINE> <DEDENT> write_yml(rmg.reaction_model.core.species, rmg.reaction_model.core.reactions, solvent=rmg.solvent, solvent_data=solvent_data, path=os.path.join(self.output_directory, 'rms', 'chem{}.rms').format(len(rmg.reaction_model.core.species)))
This class listens to a RMG subject and writes an rms file with the current state of the RMG model, to a rms subfolder. A new instance of the class can be appended to a subject as follows: rmg = ... listener = RMSWriter(outputDirectory) rmg.attach(listener) Whenever the subject calls the .notify() method, the .update() method of the listener will be called. To stop listening to the subject, the class can be detached from its subject: rmg.detach(listener)
62598fc0167d2b6e312b71ae
class FindFriendsService(object): <NEW_LINE> <INDENT> def __init__(self, service_root, session, params): <NEW_LINE> <INDENT> callee = inspect.stack()[2] <NEW_LINE> module = inspect.getmodule(callee[0]) <NEW_LINE> logger = logging.getLogger(module.__name__).getChild('http') <NEW_LINE> self.session = session <NEW_LINE> self.params = params <NEW_LINE> self._service_root = service_root <NEW_LINE> self._friend_endpoint = '%s/fmipservice/client/fmfWeb/initClient' % ( self._service_root, ) <NEW_LINE> self._data = {} <NEW_LINE> <DEDENT> def refresh_data(self): <NEW_LINE> <INDENT> params = dict(self.params) <NEW_LINE> fake_data = json.dumps({ 'clientContext': { 'appVersion': '1.0', 'contextApp': 'com.icloud.web.fmf', 'mapkitAvailable': True, 'productType': 'fmfWeb', 'tileServer': 'Apple', 'userInactivityTimeInMS': 537, 'windowInFocus': False, 'windowVisible': True }, 'dataContext': None, 'serverContext': None }) <NEW_LINE> req = self.session.post(self._friend_endpoint, data=fake_data, params=params) <NEW_LINE> self.response = req.json() <NEW_LINE> return self.response <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> if not self._data: <NEW_LINE> <INDENT> self._data = self.refresh_data() <NEW_LINE> <DEDENT> return self._data <NEW_LINE> <DEDENT> @property <NEW_LINE> def locations(self): <NEW_LINE> <INDENT> return self.data.get('locations') <NEW_LINE> <DEDENT> @property <NEW_LINE> def followers(self): <NEW_LINE> <INDENT> return self.data.get('followers') <NEW_LINE> <DEDENT> @property <NEW_LINE> def friend_fences(self): <NEW_LINE> <INDENT> return self.data.get('friendFencesISet') <NEW_LINE> <DEDENT> @property <NEW_LINE> def my_fences(self): <NEW_LINE> <INDENT> return self.data.get('myFencesISet') <NEW_LINE> <DEDENT> @property <NEW_LINE> def contacts(self): <NEW_LINE> <INDENT> return self.data.get('contactDetails') <NEW_LINE> <DEDENT> @property <NEW_LINE> def details(self): <NEW_LINE> <INDENT> return self.data.get('contactDetails')
The 'Find my Friends' iCloud service This connects to iCloud and returns friend data including the near-realtime latitude and longitude.
62598fc07047854f4633f60c
class NoAuthenticatedUser(Exception): <NEW_LINE> <INDENT> pass
Missing profile
62598fc05fdd1c0f98e5e1cb
class StadtzhdwhdropzoneHarvester(StadtzhHarvester): <NEW_LINE> <INDENT> DATA_PATH = '/usr/lib/ckan/DWH' <NEW_LINE> METADATA_DIR = 'dwh-metadata' <NEW_LINE> def info(self): <NEW_LINE> <INDENT> return { 'name': 'stadtzhdwhdropzone', 'title': 'Stadtzhdwhdropzone', 'description': 'Harvests the Stadtzhdwhdropzone data', 'form_config_interface': 'Text' } <NEW_LINE> <DEDENT> def _import_updated_packages(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def gather_stage(self, harvest_job): <NEW_LINE> <INDENT> log.debug('In StadtzhdwhdropzoneHarvester gather_stage') <NEW_LINE> return self._gather_datasets(harvest_job) <NEW_LINE> <DEDENT> def fetch_stage(self, harvest_object): <NEW_LINE> <INDENT> log.debug('In StadtzhdwhdropzoneHarvester fetch_stage') <NEW_LINE> return self._fetch_datasets(harvest_object) <NEW_LINE> <DEDENT> def import_stage(self, harvest_object): <NEW_LINE> <INDENT> log.debug('In StadtzhdwhdropzoneHarvester import_stage') <NEW_LINE> return self._import_datasets(harvest_object)
The harvester for the Stadt ZH DWH Dropzone
62598fc0442bda511e95c697
class ArbiterLink(SatelliteLink): <NEW_LINE> <INDENT> my_type = 'arbiter' <NEW_LINE> my_name_property = "%s_name" % my_type <NEW_LINE> properties = SatelliteLink.properties.copy() <NEW_LINE> properties.update({ 'type': StringProp(default=u'arbiter', fill_brok=[FULL_STATUS], to_send=True), 'arbiter_name': StringProp(default='', fill_brok=[FULL_STATUS]), 'host_name': StringProp(default=socket.gethostname(), to_send=True), 'port': IntegerProp(default=7770, to_send=True), 'last_master_speak': FloatProp(default=0.0) }) <NEW_LINE> def is_me(self): <NEW_LINE> <INDENT> logger.info("And arbiter is launched with the hostname:%s " "from an arbiter point of view of addr:%s", self.host_name, socket.getfqdn()) <NEW_LINE> return self.host_name == socket.getfqdn() or self.host_name == socket.gethostname() <NEW_LINE> <DEDENT> def do_not_run(self): <NEW_LINE> <INDENT> logger.debug("[%s] do_not_run", self.name) <NEW_LINE> try: <NEW_LINE> <INDENT> self.con.get('_do_not_run') <NEW_LINE> return True <NEW_LINE> <DEDENT> except HTTPClientConnectionException as exp: <NEW_LINE> <INDENT> self.add_failed_check_attempt("Connection error when " "sending do not run: %s" % str(exp)) <NEW_LINE> self.set_dead() <NEW_LINE> <DEDENT> except HTTPClientTimeoutException as exp: <NEW_LINE> <INDENT> self.add_failed_check_attempt("Connection timeout when " "sending do not run: %s" % str(exp)) <NEW_LINE> <DEDENT> except HTTPClientException as exp: <NEW_LINE> <INDENT> self.add_failed_check_attempt("Error when " "sending do not run: %s" % str(exp)) <NEW_LINE> <DEDENT> return False
Class to manage the link to Arbiter daemon. With it, a master arbiter can communicate with a spare Arbiter daemon
62598fc066673b3332c3060b
class UndefinedRegexError(IOBSBaseException): <NEW_LINE> <INDENT> pass
Undefined Regex Error
62598fc0cc40096d6161a2f5
class Graph: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.nodes = {} <NEW_LINE> self.edges = None <NEW_LINE> <DEDENT> def from_edges(self, edge_list: List[Tuple[int, int]]): <NEW_LINE> <INDENT> self.nodes = set(list(chain(*list(zip(*edge_list))))) <NEW_LINE> self.edges = edge_list <NEW_LINE> return self
Class representing a graph
62598fc0283ffb24f3cf3abc
class IScene(model.Schema): <NEW_LINE> <INDENT> pass
Schema for Scene content type.
62598fc07c178a314d78d6d8
class RHAPIRegistrants(RH): <NEW_LINE> <INDENT> @oauth.require_oauth('registrants') <NEW_LINE> def _checkProtection(self): <NEW_LINE> <INDENT> if not self.event.can_manage(request.oauth.user, role='registration'): <NEW_LINE> <INDENT> raise Forbidden() <NEW_LINE> <DEDENT> <DEDENT> def _checkParams(self): <NEW_LINE> <INDENT> self.event = Event.find(id=request.view_args['event_id'], is_deleted=False).first_or_404() <NEW_LINE> <DEDENT> def _process_GET(self): <NEW_LINE> <INDENT> return jsonify(registrants=build_registrations_api_data(self.event))
RESTful registrants API
62598fc0adb09d7d5dc0a7b6
class QuizInterface: <NEW_LINE> <INDENT> def __init__(self, quiz: QuizBrain): <NEW_LINE> <INDENT> self.quiz = quiz <NEW_LINE> self.window = Tk() <NEW_LINE> self.window.title('Quizzler') <NEW_LINE> self.window.config(bg=THEME_COLOR, padx=20, pady=20) <NEW_LINE> self.canvas = Canvas(width=300, height=250, highlightthickness=0) <NEW_LINE> self.question_text = self.canvas.create_text( 150, 125, width=250, text='question goes here', font=('Arial', 20, 'italic') ) <NEW_LINE> self.canvas.grid(column=0, row=1, columnspan=2, pady=20) <NEW_LINE> self.questions_number_label = Label( text=f'No. of questions: {len(self.quiz.question_list)}', font=('Arial', 12, 'normal'), fg='white', bg=THEME_COLOR ) <NEW_LINE> self.questions_number_label.grid(column=0, row=0, padx=20, pady=20) <NEW_LINE> self.score_label = Label( text=f'Score : {0}', font=('Arial', 12, 'normal'), fg='white', bg=THEME_COLOR) <NEW_LINE> self.score_label.grid(column=1, row=0, padx=20, pady=20) <NEW_LINE> self.score_text = None <NEW_LINE> right_image_img = PhotoImage(file='./images/true.png') <NEW_LINE> wrong_image_img = PhotoImage(file='./images/false.png') <NEW_LINE> self.right_button = Button(image=right_image_img, highlightthickness=0, command=self.true_pressed) <NEW_LINE> self.right_button.grid(column=0, row=2) <NEW_LINE> self.wrong_button = Button(image=wrong_image_img, highlightthickness=0, command=self.false_pressed) <NEW_LINE> self.wrong_button.grid(column=1, row=2) <NEW_LINE> self.get_next_question() <NEW_LINE> self.window.mainloop() <NEW_LINE> <DEDENT> def get_next_question(self): <NEW_LINE> <INDENT> self.canvas.config(bg='white') <NEW_LINE> if self.quiz.still_has_questions(): <NEW_LINE> <INDENT> self.score_text = f'Score: {self.quiz.score} / {self.quiz.question_number+1}' <NEW_LINE> self.score_label.config(text=self.score_text) <NEW_LINE> q_text = self.quiz.next_question() <NEW_LINE> self.canvas.itemconfig(self.question_text, text=q_text) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.canvas.itemconfig(self.question_text, text=f'Quiz is finished!\n {self.score_text}') <NEW_LINE> self.right_button.config(state='disabled') <NEW_LINE> self.wrong_button.config(state='disabled') <NEW_LINE> <DEDENT> <DEDENT> def true_pressed(self): <NEW_LINE> <INDENT> is_right = self.quiz.check_answer('True') <NEW_LINE> self.give_feedback(is_right) <NEW_LINE> <DEDENT> def false_pressed(self): <NEW_LINE> <INDENT> is_right = self.quiz.check_answer('False') <NEW_LINE> self.give_feedback(is_right) <NEW_LINE> <DEDENT> def give_feedback(self, is_right): <NEW_LINE> <INDENT> if is_right: <NEW_LINE> <INDENT> self.canvas.config(bg='green') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.canvas.config(bg='red') <NEW_LINE> <DEDENT> self.window.after(1000, self.get_next_question)
will be the class that creates the quiz interface window when an object is created
62598fc063d6d428bbee29eb
@cromlech.content.factored_component <NEW_LINE> @cromlech.content.factory(BakerJoe) <NEW_LINE> @implementer(IBread, ISweet) <NEW_LINE> @name('JoePastry') <NEW_LINE> class Croissant(object): <NEW_LINE> <INDENT> pass
A crusty bread.
62598fc0aad79263cf42ea0e
class ShareItemInternal(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name': {'required': True}, 'properties': {'required': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'Name', 'type': 'str'}, 'snapshot': {'key': 'Snapshot', 'type': 'str'}, 'deleted': {'key': 'Deleted', 'type': 'bool'}, 'version': {'key': 'Version', 'type': 'str'}, 'properties': {'key': 'Properties', 'type': 'SharePropertiesInternal'}, 'metadata': {'key': 'Metadata', 'type': '{str}'}, } <NEW_LINE> _xml_map = { 'name': 'Share' } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ShareItemInternal, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs['name'] <NEW_LINE> self.snapshot = kwargs.get('snapshot', None) <NEW_LINE> self.deleted = kwargs.get('deleted', None) <NEW_LINE> self.version = kwargs.get('version', None) <NEW_LINE> self.properties = kwargs['properties'] <NEW_LINE> self.metadata = kwargs.get('metadata', None)
A listed Azure Storage share item. All required parameters must be populated in order to send to Azure. :ivar name: Required. :vartype name: str :ivar snapshot: :vartype snapshot: str :ivar deleted: :vartype deleted: bool :ivar version: :vartype version: str :ivar properties: Required. Properties of a share. :vartype properties: ~azure.storage.fileshare.models.SharePropertiesInternal :ivar metadata: Dictionary of :code:`<string>`. :vartype metadata: dict[str, str]
62598fc02c8b7c6e89bd39fb
class AWSStorageView(ReportView): <NEW_LINE> <INDENT> permission_classes = [AwsAccessPermission] <NEW_LINE> report = 'storage' <NEW_LINE> provider = 'aws'
Get inventory storage data. @api {get} /cost-management/v1/reports/aws/storage/ Get inventory storage data @apiName getAWSStorageData @apiGroup AWS Report @apiVersion 1.0.0 @apiDescription Get inventory data. @apiHeader {String} token User authorization token. @apiParam (Query Param) {Object} filter The filter to apply to the report. @apiParam (Query Param) {Object} group_by The grouping to apply to the report. @apiParam (Query Param) {Object} order_by The ordering to apply to the report. @apiParam (Query Param) {String} units The units used in the report. @apiParamExample {json} Query Param: ?filter[resolution]=daily&filter[time_scope_value]=-10&order_by[cost]=asc&units=byte @apiSuccess {Object} group_by The grouping to applied to the report. @apiSuccess {Object} filter The filter to applied to the report. @apiSuccess {Object} data The report data. @apiSuccess {Object} total Aggregates statistics for the report range. @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { "group_by": { "account": [ "*" ] }, "filter": { "resolution": "monthly", "time_scope_value": "-1", "time_scope_units": "month" }, "data": [ { "date": "2018-08", "accounts": [ { "account": "0840549025238", "values": [ { "date": "2018-08", "units": "GB-Mo", "account": "0840549025238", "total": 4066.923135971 } ] }, { "account": "3082416796941", "values": [ { "date": "2018-08", "units": "GB-Mo", "account": "3082416796941", "total": 3644.58070225345 } ] }, { "account": "8133889256380", "values": [ { "date": "2018-08", "units": "GB-Mo", "account": "8133889256380", "total": 3584.67567749966 } ] }, { "account": "4783090375826", "values": [ { "date": "2018-08", "units": "GB-Mo", "account": "4783090375826", "total": 3096.66740996526 } ] }, { "account": "2415722664993", "values": [ { "date": "2018-08", "units": "GB-Mo", "account": "2415722664993", "total": 2599.75765963921 } ] } ] } ], "total": { "value": 16992.6045853286, "units": "GB-Mo" } } @apiSuccessExample {text} Success-Response: HTTP/1.1 200 OK account,date,total,units 0840549025238,2018-08,4066.923135971,GB-Mo 3082416796941,2018-08,3644.58070225345,GB-Mo 8133889256380,2018-08,3584.67567749966,GB-Mo 4783090375826,2018-08,3096.66740996526,GB-Mo 2415722664993,2018-08,2599.75765963921,GB-Mo
62598fc03d592f4c4edbb0f6
class Profiler(object): <NEW_LINE> <INDENT> _file_count = count(0) <NEW_LINE> _profiler = None <NEW_LINE> _profiler_owner = None <NEW_LINE> def __init__(self, s3_bucket, s3_prefix, output_local_path, enable_profiling=False): <NEW_LINE> <INDENT> self._enable_profiling = enable_profiling <NEW_LINE> self.s3_bucket = s3_bucket <NEW_LINE> self.s3_prefix = s3_prefix <NEW_LINE> self.output_local_path = output_local_path <NEW_LINE> self.file_count = next(self._file_count) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.start() <NEW_LINE> <DEDENT> def __exit__(self, type_val, value, traceback): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> @property <NEW_LINE> def enable_profiling(self): <NEW_LINE> <INDENT> return self._enable_profiling <NEW_LINE> <DEDENT> @enable_profiling.setter <NEW_LINE> def enable_profiling(self, val): <NEW_LINE> <INDENT> self._enable_profiling = val <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> if self.enable_profiling: <NEW_LINE> <INDENT> if not self._profiler: <NEW_LINE> <INDENT> self._profiler = cProfile.Profile() <NEW_LINE> self._profiler.enable() <NEW_LINE> self._profiler_owner = self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise GenericException('Profiler is in use!') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self._profiler_owner == self: <NEW_LINE> <INDENT> if self._profiler: <NEW_LINE> <INDENT> self._profiler.disable() <NEW_LINE> self._profiler.dump_stats(self.output_local_path) <NEW_LINE> s3_file_name = "{}-{}.txt".format(os.path.splitext(os.path.basename(self.output_local_path))[0], self.file_count) <NEW_LINE> with open(s3_file_name, 'w') as filepointer: <NEW_LINE> <INDENT> pstat_obj = pstats.Stats(self.output_local_path, stream=filepointer) <NEW_LINE> pstat_obj.sort_stats('cumulative') <NEW_LINE> pstat_obj.print_stats() <NEW_LINE> <DEDENT> self._upload_profile_stats_to_s3(s3_file_name) <NEW_LINE> <DEDENT> self._profiler = None <NEW_LINE> self._profiler_owner = None <NEW_LINE> <DEDENT> <DEDENT> def _upload_profile_stats_to_s3(self, s3_file_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> session = boto3.Session() <NEW_LINE> s3_client = session.client('s3', config=get_boto_config()) <NEW_LINE> s3_extra_args = get_s3_kms_extra_args() <NEW_LINE> s3_client.upload_file(Filename=s3_file_name, Bucket=self.s3_bucket, Key=os.path.join(self.s3_prefix, s3_file_name), ExtraArgs=s3_extra_args) <NEW_LINE> <DEDENT> except botocore.exceptions.ClientError as ex: <NEW_LINE> <INDENT> log_and_exit("Unable to upload profiler data: {}, {}".format(self.s3_prefix, ex.response['Error']['Code']), SIMAPP_SIMULATION_WORKER_EXCEPTION, SIMAPP_EVENT_ERROR_CODE_400) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> log_and_exit("Unable to upload profiler data: {}".format(ex), SIMAPP_SIMULATION_WORKER_EXCEPTION, SIMAPP_EVENT_ERROR_CODE_500)
Class to profile the specific code.
62598fc056ac1b37e6302427
class TestUserResolver(NotificationUserScopeResolver): <NEW_LINE> <INDENT> def resolve(self, scope_name, scope_context, instance_context): <NEW_LINE> <INDENT> user_id = scope_context.get('user_id') <NEW_LINE> return [ 'testemail@sdc.com', { 'user_id': user_id, 'email': 'dummy@dummy.com', 'first_name': 'Joe', 'last_name': 'Smith' } ]
UserResolver for test purposes
62598fc097e22403b383b143
@python_2_unicode_compatible <NEW_LINE> class AddressComponent(models.Model, TagSearchable): <NEW_LINE> <INDENT> type = models.CharField(_(u'Component Type'), max_length=50, db_index=True) <NEW_LINE> short_name = models.CharField(_(u'Short Name'), max_length=255, db_index=True) <NEW_LINE> long_name = models.CharField(_(u'Long Name'), max_length=255, db_index=True) <NEW_LINE> tags = TaggableManager(help_text=None, blank=True, verbose_name=_('Tags')) <NEW_LINE> search_fields = [ index.SearchField('short_name'), index.SearchField('long_name'), ] <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> ordering = ('long_name',) <NEW_LINE> unique_together = (('type', 'short_name'), ('type', 'long_name')) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{0}'.format(self.long_name)
Stores an address component record.
62598fc0d8ef3951e32c7f7b
class Status(object): <NEW_LINE> <INDENT> AuthorizationExpired = "authorization_expired" <NEW_LINE> Authorized = "authorized" <NEW_LINE> Authorizing = "authorizing" <NEW_LINE> Failed = "failed" <NEW_LINE> GatewayRejected = "gateway_rejected" <NEW_LINE> ProcessorDeclined = "processor_declined" <NEW_LINE> Settled = "settled" <NEW_LINE> SettlementFailed = "settlement_failed" <NEW_LINE> SubmittedForSettlement = "submitted_for_settlement" <NEW_LINE> Voided = "voided"
Constants representing transaction statuses. Available statuses are: * braintree.Transaction.Status.Authorized * braintree.Transaction.Status.Authorizing * braintree.Transaction.Status.Failed * braintree.Transaction.Status.GatewayRejected * braintree.Transaction.Status.ProcessorDeclined * braintree.Transaction.Status.Settled * braintree.Transaction.Status.SettlementFailed * braintree.Transaction.Status.SubmittedForSettlement * braintree.Transaction.Status.Void
62598fc066673b3332c3060d
class TextAnnotation(enum.Enum): <NEW_LINE> <INDENT> NONE = ('', 'bpe.32000.bin', 'bpe.32000') <NEW_LINE> def __init__(self, identifier, ext, vocab_ext): <NEW_LINE> <INDENT> self.ext = ext <NEW_LINE> self.vocab_ext = vocab_ext <NEW_LINE> self.identifier = identifier <NEW_LINE> <DEDENT> def data_path(self, split, directory, **kwargs): <NEW_LINE> <INDENT> data_ext = self.ext.format(**kwargs) <NEW_LINE> return os.path.join(directory, f'{split}.{data_ext}') <NEW_LINE> <DEDENT> def vocab_path(self, directory, **kwargs): <NEW_LINE> <INDENT> vocab_ext = self.vocab_ext.format(**kwargs) <NEW_LINE> return os.path.join(directory, f'vocab.{vocab_ext}')
An enumeration of text annotation types
62598fc04f6381625f1995df
class TestPBSConfig(TestFunctional): <NEW_LINE> <INDENT> snapdirs = [] <NEW_LINE> snaptars = [] <NEW_LINE> def test_config_for_snapshot(self): <NEW_LINE> <INDENT> pbs_snapshot_path = os.path.join( self.server.pbs_conf["PBS_EXEC"], "sbin", "pbs_snapshot") <NEW_LINE> if not os.path.isfile(pbs_snapshot_path): <NEW_LINE> <INDENT> self.skipTest("pbs_snapshot not found") <NEW_LINE> <DEDENT> pbs_config_path = os.path.join( self.server.pbs_conf["PBS_EXEC"], "unsupported", "pbs_config") <NEW_LINE> if not os.path.isfile(pbs_config_path): <NEW_LINE> <INDENT> self.skipTest("pbs_config not found") <NEW_LINE> <DEDENT> a = {ATTR_rescavail + ".ncpus": 2} <NEW_LINE> self.mom.create_vnodes(attrib=a, num=4, usenatvnode=True) <NEW_LINE> self.server.expect(VNODE, {'state=free': 4}, count=True) <NEW_LINE> a = {'queue_type': 'execution', 'started': 'True', 'enabled': 'True', 'Priority': 200} <NEW_LINE> self.server.manager(MGR_CMD_CREATE, QUEUE, a, id="expressq") <NEW_LINE> a = {"preempt_order": "R"} <NEW_LINE> self.server.manager(MGR_CMD_SET, SCHED, a, id="default") <NEW_LINE> self.scheds["default"].set_sched_config( {"smp_cluster_dist": "round_robin"}) <NEW_LINE> outdir = pwd.getpwnam(self.du.get_current_user()).pw_dir <NEW_LINE> snap_cmd = [pbs_snapshot_path, "-o " + outdir, "--with-sudo"] <NEW_LINE> ret = self.du.run_cmd(cmd=snap_cmd, logerr=False, as_script=True) <NEW_LINE> self.assertEqual(ret["rc"], 0, "pbs_snapshot command failed") <NEW_LINE> snap_out = ret['out'][0] <NEW_LINE> output_tar = snap_out.split(":")[1] <NEW_LINE> output_tar = output_tar.strip() <NEW_LINE> self.assertTrue(os.path.isfile(output_tar), "Error capturing snapshot:\n" + str(ret)) <NEW_LINE> self.snaptars.append(output_tar) <NEW_LINE> tar = tarfile.open(output_tar) <NEW_LINE> tar.extractall(path=outdir) <NEW_LINE> tar.close() <NEW_LINE> snap_dir = output_tar[:-4] <NEW_LINE> self.assertTrue(os.path.isdir(snap_dir)) <NEW_LINE> self.snapdirs.append(snap_dir) <NEW_LINE> TestFunctional.setUp(self) <NEW_LINE> config_cmd = [pbs_config_path, "--snap=" + snap_dir] <NEW_LINE> self.du.run_cmd(cmd=config_cmd, sudo=True, logerr=False) <NEW_LINE> self.server.expect(VNODE, {'state=free': 4}, count=True) <NEW_LINE> self.server.expect(QUEUE, {"Priority": 200}, id="expressq") <NEW_LINE> self.server.expect(SCHED, {"preempt_order": "R"}, id="default") <NEW_LINE> self.scheds["default"].parse_sched_config() <NEW_LINE> self.assertEqual( self.scheds["default"].sched_config["smp_cluster_dist"], "round_robin", "pbs_config didn't load sched_config correctly") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> for snap_dir in self.snapdirs: <NEW_LINE> <INDENT> self.du.rm(path=snap_dir, recursive=True, force=True) <NEW_LINE> <DEDENT> for snap_tar in self.snaptars: <NEW_LINE> <INDENT> self.du.rm(path=snap_tar, force=True)
Test cases for pbs_config tool
62598fc0656771135c4898aa
class UserProfile(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length=256, unique=True, null=False) <NEW_LINE> first_name = models.CharField(max_length=256) <NEW_LINE> last_name = models.CharField(max_length=256) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> objects = UserProfileManager() <NEW_LINE> USERNAME_FIELD = "email" <NEW_LINE> REQUIRED_FIELDS = ["first_name", "last_name"] <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.email <NEW_LINE> <DEDENT> def get_full_name(self): <NEW_LINE> <INDENT> return self.first_name + " " + self.last_name
Represents a user's profile
62598fc056ac1b37e6302428
class ZODBLayer(ZopeComponentLayer): <NEW_LINE> <INDENT> db = None <NEW_LINE> @classmethod <NEW_LINE> def setUp(cls): <NEW_LINE> <INDENT> db = cls.db = ZODB.DB(DemoStorage()) <NEW_LINE> component.getGlobalSiteManager().registerUtility(db, IDatabase) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDown(cls): <NEW_LINE> <INDENT> db = cls.db <NEW_LINE> cls.db = None <NEW_LINE> if db is not None: <NEW_LINE> <INDENT> db.close() <NEW_LINE> reg_db = component.getGlobalSiteManager().queryUtility(IDatabase) <NEW_LINE> if reg_db is db: <NEW_LINE> <INDENT> component.getGlobalSiteManager().unregisterUtility(db, IDatabase) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def testSetUp(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def testTearDown(cls): <NEW_LINE> <INDENT> pass
Test layer that creates a ZODB database using :class:`ZODB.DemoStorage.DemoStorage` and registers it as the no-name :class:`ZODB.interfaces.IDatabase` in the global component registry. It is also available in the :attr:`db` attribute of this object.
62598fc0851cf427c66b84f1
class DerBitString(DerObject): <NEW_LINE> <INDENT> def __init__(self, value=b(''), implicit=None): <NEW_LINE> <INDENT> DerObject.__init__(self, 0x03, b(''), implicit, False) <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def encode(self): <NEW_LINE> <INDENT> self.payload = b('\x00') + self.value <NEW_LINE> return DerObject.encode(self) <NEW_LINE> <DEDENT> def decode(self, derEle): <NEW_LINE> <INDENT> return DerObject.decode(self, derEle) <NEW_LINE> <DEDENT> def _decodeFromStream(self, s): <NEW_LINE> <INDENT> DerObject._decodeFromStream(self, s) <NEW_LINE> if self.payload and bord(self.payload[0])!=0: <NEW_LINE> <INDENT> raise ValueError("Not a valid BIT STRING") <NEW_LINE> <DEDENT> self.value = b('') <NEW_LINE> if self.payload: <NEW_LINE> <INDENT> self.value = self.payload[1:]
Class to model a DER BIT STRING. An example of encoding is: >>> from Crypto.Util.asn1 import DerBitString >>> from binascii import hexlify, unhexlify >>> bs_der = DerBitString(b'\xaa') >>> bs_der.value += b'\xbb' >>> print hexlify(bs_der.encode()) which will show ``040300aabb``, the DER encoding for the bit string ``b'\xAA\xBB'``. For decoding: >>> s = unhexlify(b'040300aabb') >>> try: >>> bs_der = DerBitString() >>> bs_der.decode(s) >>> print hexlify(bs_der.value) >>> except (ValueError, EOFError): >>> print "Not a valid DER OCTET STRING" the output will be ``aabb``.
62598fc0d486a94d0ba2c20c
class CommonPrefix: <NEW_LINE> <INDENT> def __init__ ( self, name = "", bucket = None ): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.bucket = bucket <NEW_LINE> <DEDENT> def __repr__ ( self ): <NEW_LINE> <INDENT> return "<CommonPrefix: \"%s\">" % self.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def short_name ( self ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shortname = self.name [ self.name[:-2].rindex ( "/" ) + 1 : ] <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> shortname = self.name <NEW_LINE> <DEDENT> return shortname
通用前缀 也就是代表目录,只有读取的操作用到,写操作根据名字来分割,自己不用管。 :ivar name: 目录名 :ivar bucket: 目录所属的Bucket对象
62598fc07cff6e4e811b5c5f
class PokemonSimpleListAPIView(ListAPIView): <NEW_LINE> <INDENT> queryset = Pokemon.objects.all() <NEW_LINE> serializer_class = serializers.PokemonSimpleSerializer
Uses generic ListAPIView, but shows only one endpoint for listing
62598fc0e1aae11d1e7ce943
class TestReview(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.rev = Review() <NEW_LINE> cls.rev.user_id = "Adriel and Melissa 123" <NEW_LINE> cls.rev.place_id = "Amy and Victor's room at SF" <NEW_LINE> cls.rev.text = "Team Awesome includes Adekunle" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> del cls.rev <NEW_LINE> try: <NEW_LINE> <INDENT> remove("file.json") <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def test_pep8_style_check(self): <NEW_LINE> <INDENT> style = pep8.StyleGuide(quiet=True) <NEW_LINE> p = style.check_files(['models/review.py']) <NEW_LINE> self.assertEqual(p.total_errors, 0, "pep8 error needs fixing") <NEW_LINE> <DEDENT> def test_Review_dbtable(self): <NEW_LINE> <INDENT> self.assertEqual(self.rev.__tablename__, "reviews") <NEW_LINE> <DEDENT> def test_Review_inheritance(self): <NEW_LINE> <INDENT> self.assertIsInstance(self.rev, BaseModel) <NEW_LINE> <DEDENT> def test_Review_attributes(self): <NEW_LINE> <INDENT> self.assertTrue("place_id" in self.rev.__dir__()) <NEW_LINE> self.assertTrue("user_id" in self.rev.__dir__()) <NEW_LINE> self.assertTrue("text" in self.rev.__dir__()) <NEW_LINE> <DEDENT> @unittest.skipIf(storage == "db", "Testing database storage only") <NEW_LINE> def test_Review_attributes(self): <NEW_LINE> <INDENT> place_id = getattr(self.rev, "place_id") <NEW_LINE> user_id = getattr(self.rev, "user_id") <NEW_LINE> text = getattr(self.rev, "text") <NEW_LINE> self.assertIsInstance(place_id, str) <NEW_LINE> self.assertIsInstance(user_id, str) <NEW_LINE> self.assertIsInstance(text, str)
Testing Review class
62598fc063b5f9789fe853ae
class GeometricConstraints(om.ExplicitComponent): <NEW_LINE> <INDENT> def initialize(self): <NEW_LINE> <INDENT> self.options.declare("nPoints") <NEW_LINE> self.options.declare("diamFlag", default=True) <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> nPoints = self.options["nPoints"] <NEW_LINE> self.add_input("d", np.zeros(nPoints), units="m") <NEW_LINE> self.add_input("t", np.zeros(nPoints - 1), units="m") <NEW_LINE> self.add_output("constr_d_to_t", np.zeros(nPoints - 1)) <NEW_LINE> self.add_output("constr_taper", np.zeros(nPoints - 1)) <NEW_LINE> self.add_output("slope", np.zeros(nPoints - 1)) <NEW_LINE> if nPoints > 2: <NEW_LINE> <INDENT> self.add_output("thickness_slope", np.zeros(nPoints - 2)) <NEW_LINE> <DEDENT> self.declare_partials("*", "*", method="fd", form="central", step=1e-6) <NEW_LINE> <DEDENT> def compute(self, inputs, outputs): <NEW_LINE> <INDENT> d = inputs["d"] <NEW_LINE> t = inputs["t"] <NEW_LINE> diamFlag = self.options["diamFlag"] <NEW_LINE> if not diamFlag: <NEW_LINE> <INDENT> d *= 2.0 <NEW_LINE> <DEDENT> dave, _ = nodal2sectional(d) <NEW_LINE> d_ratio = d[1:] / d[:-1] <NEW_LINE> t_ratio = t[1:] / t[:-1] <NEW_LINE> outputs["constr_d_to_t"] = dave / t <NEW_LINE> outputs["constr_taper"] = np.minimum(d_ratio, 1.0 / d_ratio) <NEW_LINE> outputs["slope"] = d_ratio <NEW_LINE> if self.options["nPoints"] > 2: <NEW_LINE> <INDENT> outputs["thickness_slope"] = t_ratio
Compute the minimum diameter-to-thickness ratio and taper constraints. Parameters ---------- d : numpy array[nPoints], [m] Sectional tower diameters t : numpy array[nPoints-1], [m] Sectional tower wall thicknesses min_d_to_t : float Minimum diameter-to-thickness ratio, dictated by ability to roll steel max_taper : float Maximum taper ratio of tower sections Returns ------- constr_d_to_t : numpy array[n_points-1] Minimum diameter-to-thickness constraint, must be negative to be feasible constr_taper : numpy array[n_points-1] Taper ratio constraint, must be positve to be feasible slope : numpy array[n_points-2] Slope constraint, must be less than 1.0 to be feasible
62598fc0099cdd3c63675500
class ResourceProtector(_ResourceProtector): <NEW_LINE> <INDENT> def __init__(self, app=None, query_client=None, query_token=None, exists_nonce=None): <NEW_LINE> <INDENT> self.query_client = query_client <NEW_LINE> self.query_token = query_token <NEW_LINE> self._exists_nonce = exists_nonce <NEW_LINE> self.app = app <NEW_LINE> if app: <NEW_LINE> <INDENT> self.init_app(app) <NEW_LINE> <DEDENT> <DEDENT> def init_app(self, app, query_client=None, query_token=None, exists_nonce=None): <NEW_LINE> <INDENT> if query_client is not None: <NEW_LINE> <INDENT> self.query_client = query_client <NEW_LINE> <DEDENT> if query_token is not None: <NEW_LINE> <INDENT> self.query_token = query_token <NEW_LINE> <DEDENT> if exists_nonce is not None: <NEW_LINE> <INDENT> self._exists_nonce = exists_nonce <NEW_LINE> <DEDENT> methods = app.config.get('OAUTH1_SUPPORTED_SIGNATURE_METHODS') <NEW_LINE> if methods and isinstance(methods, (list, tuple)): <NEW_LINE> <INDENT> self.SUPPORTED_SIGNATURE_METHODS = methods <NEW_LINE> <DEDENT> self.app = app <NEW_LINE> <DEDENT> def get_client_by_id(self, client_id): <NEW_LINE> <INDENT> return self.query_client(client_id) <NEW_LINE> <DEDENT> def get_token_credential(self, request): <NEW_LINE> <INDENT> return self.query_token(request.client_id, request.token) <NEW_LINE> <DEDENT> def exists_nonce(self, nonce, request): <NEW_LINE> <INDENT> if not self._exists_nonce: <NEW_LINE> <INDENT> raise RuntimeError('"exists_nonce" function is required.') <NEW_LINE> <DEDENT> timestamp = request.timestamp <NEW_LINE> client_id = request.client_id <NEW_LINE> token = request.token <NEW_LINE> return self._exists_nonce(nonce, timestamp, client_id, token) <NEW_LINE> <DEDENT> def acquire_credential(self): <NEW_LINE> <INDENT> req = self.validate_request( _req.method, _req.url, _req.form.to_dict(flat=True), _req.headers ) <NEW_LINE> ctx = _app_ctx_stack.top <NEW_LINE> ctx.authlib_server_oauth1_credential = req.credential <NEW_LINE> return req.credential <NEW_LINE> <DEDENT> def __call__(self, scope=None): <NEW_LINE> <INDENT> def wrapper(f): <NEW_LINE> <INDENT> @functools.wraps(f) <NEW_LINE> def decorated(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.acquire_credential() <NEW_LINE> <DEDENT> except OAuth1Error as error: <NEW_LINE> <INDENT> body = dict(error.get_body()) <NEW_LINE> return Response( json.dumps(body), status=error.status_code, headers=default_json_headers, ) <NEW_LINE> <DEDENT> return f(*args, **kwargs) <NEW_LINE> <DEDENT> return decorated <NEW_LINE> <DEDENT> return wrapper
A protecting method for resource servers. Initialize a resource protector with the query_token method:: from authlib.integrations.flask_oauth1 import ResourceProtector, current_credential from authlib.integrations.flask_oauth1 import create_exists_nonce_func from authlib.integrations.sqla_oauth1 import ( create_query_client_func, create_query_token_func, ) from your_project.models import Token, User, cache # you need to define a ``cache`` instance yourself require_oauth= ResourceProtector( app, query_client=create_query_client_func(db.session, OAuth1Client), query_token=create_query_token_func(db.session, OAuth1Token), exists_nonce=create_exists_nonce_func(cache) ) # or initialize it lazily require_oauth = ResourceProtector() require_oauth.init_app( app, query_client=create_query_client_func(db.session, OAuth1Client), query_token=create_query_token_func(db.session, OAuth1Token), exists_nonce=create_exists_nonce_func(cache) )
62598fc0f9cc0f698b1c53ee
class Donor(BaseModel): <NEW_LINE> <INDENT> donor_name = CharField(primary_key = True, max_length = 30) <NEW_LINE> home_address = CharField(max_length=40) <NEW_LINE> town_and_zip = CharField(max_length = 40)
This class defines Donor person, which maintains details of name, address, town, and zip code
62598fc03317a56b869be66e
class get_count_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None, ire=None, ue=None, te=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.ire = ire <NEW_LINE> self.ue = ue <NEW_LINE> self.te = te <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.success = iprot.readI32() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ire = InvalidRequestException() <NEW_LINE> self.ire.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ue = UnavailableException() <NEW_LINE> self.ue.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 3: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.te = TimedOutException() <NEW_LINE> self.te.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('get_count_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.I32, 0) <NEW_LINE> oprot.writeI32(self.success) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ire is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ire', TType.STRUCT, 1) <NEW_LINE> self.ire.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ue is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ue', TType.STRUCT, 2) <NEW_LINE> self.ue.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.te is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('te', TType.STRUCT, 3) <NEW_LINE> self.te.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success - ire - ue - te
62598fc067a9b606de546208
class KegSessionChunk(_AbstractChunk): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ('session', 'keg') <NEW_LINE> get_latest_by = 'starttime' <NEW_LINE> ordering = ('-starttime',) <NEW_LINE> <DEDENT> objects = managers.SessionManager() <NEW_LINE> site = models.ForeignKey(KegbotSite, related_name='keg_chunks') <NEW_LINE> session = models.ForeignKey(DrinkingSession, related_name='keg_chunks') <NEW_LINE> keg = models.ForeignKey(Keg, related_name='keg_session_chunks', blank=True, null=True) <NEW_LINE> def GetTitle(self): <NEW_LINE> <INDENT> return self.session.GetTitle()
A specific keg's contribution to a session (spans all users).
62598fc07d43ff2487427523
class Model372ServiceRequestEnable(RegisterBase): <NEW_LINE> <INDENT> bit_names = [ "warmup_heater_ramp_done", "valid_reading_control_input", "valid_reading_measurement_input", "alarm", "sensor_overload", "event_summary", "", "sample_heater_ramp_done" ] <NEW_LINE> def __init__(self, warmup_heater_ramp_done, valid_reading_control_input, valid_reading_measurement_input, alarm, sensor_overload, event_summary, sample_heater_ramp_done): <NEW_LINE> <INDENT> self.warmup_heater_ramp_done = warmup_heater_ramp_done <NEW_LINE> self.valid_reading_control_input = valid_reading_control_input <NEW_LINE> self.valid_reading_measurement_input = valid_reading_measurement_input <NEW_LINE> self.alarm = alarm <NEW_LINE> self.sensor_overload = sensor_overload <NEW_LINE> self.event_summary = event_summary <NEW_LINE> self.sample_heater_ramp_done = sample_heater_ramp_done
Class representing the status byte register.
62598fc05fcc89381b26626b
class Eras (object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.run2_common = cms.Modifier() <NEW_LINE> self.run2_25ns_specific = cms.Modifier() <NEW_LINE> self.run2_50ns_specific = cms.Modifier() <NEW_LINE> self.run2_HI_specific = cms.Modifier() <NEW_LINE> self.stage1L1Trigger = cms.Modifier() <NEW_LINE> self.stage2L1Trigger = cms.Modifier() <NEW_LINE> self.fastSim = cms.Modifier() <NEW_LINE> self.Run1 = cms.Modifier() <NEW_LINE> self.Run2_25ns = cms.ModifierChain( self.run2_common, self.run2_25ns_specific, self.stage1L1Trigger ) <NEW_LINE> self.Run2_50ns = cms.ModifierChain( self.run2_common, self.run2_50ns_specific, self.stage1L1Trigger ) <NEW_LINE> self.Run2_HI = cms.ModifierChain( self.run2_common, self.run2_HI_specific, self.stage1L1Trigger ) <NEW_LINE> self.Run2_2016 = cms.ModifierChain( self.run2_common, self.run2_25ns_specific, self.stage2L1Trigger ) <NEW_LINE> self.internalUseEras = [self.run2_common, self.run2_25ns_specific, self.run2_50ns_specific, self.run2_HI_specific, self.stage1L1Trigger, self.fastSim ]
Dummy container for all the cms.Modifier instances that config fragments can use to selectively configure depending on what scenario is active.
62598fc0091ae35668704e63
class JfBranchCfg(schema.SectionCfg): <NEW_LINE> <INDENT> KEYS = [ 'version', 'remote', 'upstream', 'fork', 'lreview', 'review', 'ldebug', 'debug', 'hidden', 'protected', 'tested', 'sync', 'debug_prefix', 'debug_suffix', ] <NEW_LINE> version = schema.Value(schema.IntType, ['version'], default=0) <NEW_LINE> remote = schema.MaybeValue(schema.StrType, ['remote-name']) <NEW_LINE> upstream = schema.Value(schema.StrType, ['upstream'], '') <NEW_LINE> fork = schema.Value(schema.StrType, ['fork'], '') <NEW_LINE> ldebug = schema.MaybeValue(schema.StrType, ['ldebug']) <NEW_LINE> debug = schema.MaybeValue(schema.StrType, ['debug']) <NEW_LINE> lreview = schema.MaybeValue(schema.StrType, ['public']) <NEW_LINE> review = schema.MaybeValue(schema.StrType, ['remote']) <NEW_LINE> debug_prefix = schema.MaybeValue(schema.StrType, ['debug-prefix']) <NEW_LINE> debug_suffix = schema.MaybeValue(schema.StrType, ['debug-suffix']) <NEW_LINE> hidden = schema.Value(schema.BoolType, ['hidden'], default=False) <NEW_LINE> protected = schema.Value(schema.BoolType, ['protected'], default=False) <NEW_LINE> sync = schema.Value(schema.BoolType, ['sync'], default=False) <NEW_LINE> tested = schema.MaybeValue(schema.StrType, ['tested'])
Jflow configuration for a branch.
62598fc0851cf427c66b84f3
class Zoo: <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.zoo_name = name <NEW_LINE> self.animals = set() <NEW_LINE> self.habitats = set() <NEW_LINE> self.visitors = list() <NEW_LINE> self.habitat_population = dict() <NEW_LINE> <DEDENT> def build_habitat(self, habitat): <NEW_LINE> <INDENT> self.habitats.add(habitat) <NEW_LINE> <DEDENT> def sell_family_ticket(self, family): <NEW_LINE> <INDENT> self.visitors.extend(family) <NEW_LINE> <DEDENT> def purchase_animal(self, animal): <NEW_LINE> <INDENT> self.animals.add(animal) <NEW_LINE> <DEDENT> def animal_report(self): <NEW_LINE> <INDENT> for habitat in self.habitats: <NEW_LINE> <INDENT> print(habitat.marketing_name) <NEW_LINE> print("--------------------") <NEW_LINE> for animal in self.animals: <NEW_LINE> <INDENT> if animal.habitat is habitat: <NEW_LINE> <INDENT> print(animal.name + "\n") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def list_animals(self): <NEW_LINE> <INDENT> [print("{} the {}".format(animal.name, animal.type)) for animal in self.animals]
Contains methods for maintaining a Zoo Methods: -------- build_habitat sell_family_ticket purchase_animal
62598fc0aad79263cf42ea12
@Atlas.subcommand("args") <NEW_LINE> class AtlasArgs(cli.Application): <NEW_LINE> <INDENT> target = cli.SwitchAttr( ['-t', '--target'], cli.ExistingFile, help='target image', mandatory=True) <NEW_LINE> fusions = cli.SwitchAttr( ['--fusion'], cli.Set("avg", "wavg", "antsJointFusion", case_sensitive=False), help='Also create predicted labelmap(s) by combining the atlas labelmaps: ' 'avg is naive mathematical average, wavg is weighted average where weights are computed from MI ' 'between the warped atlases and target image, antsJointFusion is local weighted averaging', default='wavg') <NEW_LINE> out = cli.SwitchAttr( ['-o', '--outPrefix'], help='output prefix, output labelmaps are saved as outPrefix-mask.nrrd, outPrefix-cingr.nrrd, ...', mandatory=True) <NEW_LINE> images = cli.SwitchAttr( ['-i', '--images'], help='list of images in quotations, e.g. "img1.nrrd img2.nrrd"', mandatory=True) <NEW_LINE> labels = cli.SwitchAttr( ['-l', '--labels'], help='list of labelmap images in quotations, e.g. "mask1.nrrd mask2.nrrd cingr1.nrrd cingr2.nrrd"', mandatory=True) <NEW_LINE> names = cli.SwitchAttr( '--names', help='list of names for generated labelmaps, e.g. "atlasmask atlascingr"', mandatory=True) <NEW_LINE> threads= cli.SwitchAttr(['-n', '--nproc'], help='number of processes/threads to use (-1 for all available)', default= 8) <NEW_LINE> debug = cli.Flag('-d', help='Debug mode, saves intermediate labelmaps to atlas-debug-<pid> in output directory') <NEW_LINE> def main(self): <NEW_LINE> <INDENT> images = self.images.split() <NEW_LINE> labels = self.labels.split() <NEW_LINE> labelnames = self.names.split() <NEW_LINE> quotient, remainder = divmod(len(labels), len(images)) <NEW_LINE> if remainder != 0: <NEW_LINE> <INDENT> logging.error( 'Wrong number of labelmaps, must be a multiple of number of images (' + str(len(images)) + '). Instead there is a remainder of ' + str(remainder)) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> if quotient != len(labelnames): <NEW_LINE> <INDENT> logging.error( 'Wrong number of names, must match number of labelmap training sets: ' + str(quotient)) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> labelcols = grouper(labels, len(images)) <NEW_LINE> trainingTable= {} <NEW_LINE> trainingTable['image']= images <NEW_LINE> for i, values in enumerate(labelcols): <NEW_LINE> <INDENT> trainingTable[labelnames[i]]= values <NEW_LINE> <DEDENT> trainingTable= pd.DataFrame(trainingTable, columns=['image']+labelnames) <NEW_LINE> self.threads= int(self.threads) <NEW_LINE> if self.threads==-1 or self.threads>N_CPU: <NEW_LINE> <INDENT> self.threads= N_CPU <NEW_LINE> <DEDENT> makeAtlases(self.target, trainingTable, self.out, self.fusions, self.threads, self.debug) <NEW_LINE> logging.info('Made ' + self.out + '-*.nrrd')
Specify training images and labelmaps via commandline arguments.
62598fc060cbc95b0636457a
class TSDBAlreadyExistsError(TSDBError): <NEW_LINE> <INDENT> pass
The TSDB creation request would overwrite an exisiting TSDB.
62598fc03346ee7daa337767
class memoizer(object): <NEW_LINE> <INDENT> def __init__(self, func): <NEW_LINE> <INDENT> self.memo = [[], []] <NEW_LINE> self.func = func <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> key = (args, kwargs) <NEW_LINE> index = None <NEW_LINE> for x in xrange(0, len(self.memo[0])): <NEW_LINE> <INDENT> if self.memo[0][x] == key: <NEW_LINE> <INDENT> index = x <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if index is None: <NEW_LINE> <INDENT> out = self.func(*args, **kwargs) <NEW_LINE> self.memo[0].append(key) <NEW_LINE> self.memo[1].append(out) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out = self.memo[1][index] <NEW_LINE> <DEDENT> return out
A Memoized Function.
62598fc023849d37ff8512f1
class _CommandSectionPlane: <NEW_LINE> <INDENT> def GetResources(self): <NEW_LINE> <INDENT> return {'Pixmap' : 'Arch_SectionPlane', 'Accel': "S, E", 'MenuText': QT_TRANSLATE_NOOP("Arch_SectionPlane","Section Plane"), 'ToolTip': QT_TRANSLATE_NOOP("Arch_SectionPlane","Creates a section plane object, including the selected objects")} <NEW_LINE> <DEDENT> def IsActive(self): <NEW_LINE> <INDENT> return not FreeCAD.ActiveDocument is None <NEW_LINE> <DEDENT> def Activated(self): <NEW_LINE> <INDENT> sel = FreeCADGui.Selection.getSelection() <NEW_LINE> ss = "[" <NEW_LINE> for o in sel: <NEW_LINE> <INDENT> if len(ss) > 1: <NEW_LINE> <INDENT> ss += "," <NEW_LINE> <DEDENT> ss += "FreeCAD.ActiveDocument."+o.Name <NEW_LINE> <DEDENT> ss += "]" <NEW_LINE> FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Section Plane")) <NEW_LINE> FreeCADGui.addModule("Arch") <NEW_LINE> FreeCADGui.doCommand("section = Arch.makeSectionPlane("+ss+")") <NEW_LINE> FreeCADGui.doCommand("section.Placement = FreeCAD.DraftWorkingPlane.getPlacement()") <NEW_LINE> FreeCAD.ActiveDocument.commitTransaction() <NEW_LINE> FreeCAD.ActiveDocument.recompute()
the Arch SectionPlane command definition
62598fc050812a4eaa620d08
class IAF(Neuron): <NEW_LINE> <INDENT> Params = recordclass('params', ('bias','kappa','delta', 'reset')) <NEW_LINE> States = recordclass('states', ('V','I')) <NEW_LINE> initStates = States(V=-65., I=0.0) <NEW_LINE> defaultParams = Params(bias=1.0, kappa=0.01, delta=-60., reset=-70.) <NEW_LINE> @classmethod <NEW_LINE> def ode(cls, states, params=None): <NEW_LINE> <INDENT> params = params or cls.defaultParams <NEW_LINE> gradStates = cls.States(*[0.]*len(cls.States._fields)) <NEW_LINE> gradStates.V = (params.bias+states.I) / params.kappa <NEW_LINE> return gradStates <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def update(cls, dt, states, params=None): <NEW_LINE> <INDENT> params = params or cls.defaultParams <NEW_LINE> newStates = super(IAF, cls).update(dt, states, params) <NEW_LINE> if newStates.V > params.delta: <NEW_LINE> <INDENT> newStates.V = params.reset <NEW_LINE> <DEDENT> return newStates
Integrate-and-Fire Neuron
62598fc07b180e01f3e4916e
class ModelBase: <NEW_LINE> <INDENT> _serialized_names = {} <NEW_LINE> def __init__(self, args): <NEW_LINE> <INDENT> parameter_types = get_type_hints(self.__class__.__init__) <NEW_LINE> field_values = {k: v for k, v in args.items() if k != 'self' and not k.startswith('_')} <NEW_LINE> for k, v in field_values.items(): <NEW_LINE> <INDENT> parameter_type = parameter_types.get(k, None) <NEW_LINE> if parameter_type is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> verify_object_against_type(v, parameter_type) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise TypeError('Argument for {} is not compatible with type "{}". Exception: {}'.format(k, parameter_type, e)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.__dict__.update(field_values) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_struct(cls: Type[T], struct: Mapping) -> T: <NEW_LINE> <INDENT> return parse_object_from_struct_based_on_class_init(cls, struct, serialized_names=cls._serialized_names) <NEW_LINE> <DEDENT> def to_struct(self) -> Mapping: <NEW_LINE> <INDENT> return convert_object_to_struct(self, serialized_names=self._serialized_names) <NEW_LINE> <DEDENT> def _get_field_names(self): <NEW_LINE> <INDENT> return list(inspect.signature(self.__init__).parameters) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ + '(' + ', '.join(param + '=' + repr(getattr(self, param)) for param in self._get_field_names()) + ')' <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__class__ == other.__class__ and {k: getattr(self, k) for k in self._get_field_names()} == {k: getattr(self, k) for k in other._get_field_names()} <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
Base class for types that can be converted to JSON-like dict structures or constructed from such structures. The object fields, their types and default values are taken from the __init__ method arguments. Override the _serialized_names mapping to control the key names of the serialized structures. The derived class objects will have the .from_struct and .to_struct methods for conversion to or from structure. The base class constructor accepts the arguments map, checks the argument types and sets the object field values. Example derived class: class TaskSpec(ModelBase): _serialized_names = { 'component_ref': 'componentRef', 'is_enabled': 'isEnabled', } def __init__(self, component_ref: ComponentReference, arguments: Optional[Mapping[str, ArgumentType]] = None, is_enabled: Optional[Union[ArgumentType, EqualsPredicate, NotEqualsPredicate]] = None, #Optional property with default value ): super().__init__(locals()) #Calling the ModelBase constructor to check the argument types and set the object field values. task_spec = TaskSpec.from_struct("{'componentRef': {...}, 'isEnabled: {'and': {...}}}") # = instance of TaskSpec task_struct = task_spec.to_struct() #= "{'componentRef': {...}, 'isEnabled: {'and': {...}}}"
62598fc0be7bc26dc9251f7b
class MyFavCourseView(LoginRequiredMixin, View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> course_list = [] <NEW_LINE> userfav_ids = UserFavorite.objects.filter(user=request.user, fav_type=1) <NEW_LINE> for userfav_id in userfav_ids: <NEW_LINE> <INDENT> course_id = userfav_id.fav_id <NEW_LINE> org = Course.objects.get(id=course_id) <NEW_LINE> course_list.append(org) <NEW_LINE> <DEDENT> return render(request, 'usercenter-fav-course.html', { 'course_list': course_list })
我的收藏课程
62598fc055399d3f05626754
class Pan(PointEvent): <NEW_LINE> <INDENT> event_name = 'pan' <NEW_LINE> def __init__(self, model, delta_x=None, delta_y=None, direction=None, **kwargs): <NEW_LINE> <INDENT> self.delta_x = delta_x <NEW_LINE> self.delta_y = delta_y <NEW_LINE> self.direction = direction <NEW_LINE> super().__init__(model, **kwargs)
Announce a pan event on a Bokeh plot. Attributes: delta_x (float) : the amount of scroll in the x direction delta_y (float) : the amount of scroll in the y direction direction (float) : the direction of scroll (1 or -1) sx (float) : x-coordinate of the event in *screen* space sy (float) : y-coordinate of the event in *screen* space x (float) : x-coordinate of the event in *data* space y (float) : y-coordinate of the event in *data* space
62598fc0bf627c535bcb16e5
class Melo: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.tracks = [] <NEW_LINE> self.ts_numerator = 4 <NEW_LINE> self.ts_denominator = 4
A list of Track. This class is a lot easier to handle than vanilla MidiFile because Melo uses absolute time and has only note information.
62598fc05fdd1c0f98e5e1d1
class FakeRegisters(Registers): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.registers = [0] * (BANK_SIZE * 2) <NEW_LINE> self.writes = [] <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def write_register(self, reg, value): <NEW_LINE> <INDENT> self.writes.append((reg, value)) <NEW_LINE> if reg in (IOCONA, IOCONB): <NEW_LINE> <INDENT> self.registers[IOCONA] = value <NEW_LINE> self.registers[IOCONB] = value <NEW_LINE> <DEDENT> elif reg == GPIOA: <NEW_LINE> <INDENT> self.registers[OLATA] = value <NEW_LINE> <DEDENT> elif reg == GPIOB: <NEW_LINE> <INDENT> self.registers[OLATB] = value <NEW_LINE> <DEDENT> elif reg not in (INTFA, INTFB, INTCAPA, INTCAPB): <NEW_LINE> <INDENT> self.registers[reg] = value <NEW_LINE> <DEDENT> <DEDENT> def read_register(self, reg): <NEW_LINE> <INDENT> if reg == GPIOA: <NEW_LINE> <INDENT> value = (self.registers[GPIOA] & self.registers[IODIRA]) | (self.registers[OLATA] & ~self.registers[IODIRA]) <NEW_LINE> <DEDENT> elif reg == GPIOB: <NEW_LINE> <INDENT> value = (self.registers[GPIOB] & self.registers[IODIRB]) | (self.registers[OLATB] & ~self.registers[IODIRB]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = self.registers[reg] <NEW_LINE> <DEDENT> if reg in (INTCAPA, GPIOA): <NEW_LINE> <INDENT> self.registers[INTCAPA] = 0 <NEW_LINE> <DEDENT> elif reg in (INTCAPB, GPIOB): <NEW_LINE> <INDENT> self.registers[INTCAPB] = 0 <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def register_value(self, bank, reg): <NEW_LINE> <INDENT> return self.registers[_banked_register(bank, reg)] <NEW_LINE> <DEDENT> def register_bit(self, bank, reg, bit): <NEW_LINE> <INDENT> return (self.register_value(bank, reg) >> bit) & 0x01 <NEW_LINE> <DEDENT> def given_gpio_inputs(self, bank, value): <NEW_LINE> <INDENT> self.given_register_value(bank, GPIO, value) <NEW_LINE> <DEDENT> def given_register_value(self, bank, reg, value): <NEW_LINE> <INDENT> self.registers[_banked_register(bank, reg)] = value <NEW_LINE> <DEDENT> def print_registers(self): <NEW_LINE> <INDENT> for reg, value in zip(count(), self.registers): <NEW_LINE> <INDENT> print(register_names[reg].ljust(8) + " = " + "%02X" % value) <NEW_LINE> <DEDENT> <DEDENT> def print_writes(self): <NEW_LINE> <INDENT> for reg, value in self.writes: <NEW_LINE> <INDENT> print(register_names[reg].ljust(8) + " := " + "%02X" % value) <NEW_LINE> <DEDENT> <DEDENT> def clear_writes(self): <NEW_LINE> <INDENT> self.writes = [] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return type(self).__name__ + "()" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self)
Note - does not simulate effect of the IPOL{A,B} registers.
62598fc03317a56b869be66f
class IContactListing(IViewletManager): <NEW_LINE> <INDENT> pass
Viewlet manager registration for contact view
62598fc0283ffb24f3cf3ac2
class ActivateColors: <NEW_LINE> <INDENT> def __init__(self, enable=True, flavor=None): <NEW_LINE> <INDENT> if enable is True and DEV.current_test(): <NEW_LINE> <INDENT> enable = "testing" <NEW_LINE> <DEDENT> self.enable = enable <NEW_LINE> self.flavor = flavor <NEW_LINE> self.prev = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.prev = ColorManager._activate_colors(self.enable, flavor=self.flavor) <NEW_LINE> <DEDENT> def __exit__(self, *_): <NEW_LINE> <INDENT> ColorManager.backend, ColorManager.bg, ColorManager.fg, ColorManager.style = self.prev
Context manager for temporarily overriding coloring
62598fc0ec188e330fdf8ad2
class TuyaLight(TuyaDevice, LightEntity): <NEW_LINE> <INDENT> def __init__(self, tuya, platform): <NEW_LINE> <INDENT> super().__init__(tuya, platform) <NEW_LINE> self.entity_id = ENTITY_ID_FORMAT.format(tuya.object_id()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def brightness(self): <NEW_LINE> <INDENT> if self._tuya.brightness() is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return int(self._tuya.brightness()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def hs_color(self): <NEW_LINE> <INDENT> return tuple(map(int, self._tuya.hs_color())) <NEW_LINE> <DEDENT> @property <NEW_LINE> def color_temp(self): <NEW_LINE> <INDENT> color_temp = int(self._tuya.color_temp()) <NEW_LINE> if color_temp is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return colorutil.color_temperature_kelvin_to_mired(color_temp) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._tuya.state() <NEW_LINE> <DEDENT> @property <NEW_LINE> def min_mireds(self): <NEW_LINE> <INDENT> return colorutil.color_temperature_kelvin_to_mired(self._tuya.min_color_temp()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def max_mireds(self): <NEW_LINE> <INDENT> return colorutil.color_temperature_kelvin_to_mired(self._tuya.max_color_temp()) <NEW_LINE> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> if ( ATTR_BRIGHTNESS not in kwargs and ATTR_HS_COLOR not in kwargs and ATTR_COLOR_TEMP not in kwargs ): <NEW_LINE> <INDENT> self._tuya.turn_on() <NEW_LINE> <DEDENT> if ATTR_BRIGHTNESS in kwargs: <NEW_LINE> <INDENT> self._tuya.set_brightness(kwargs[ATTR_BRIGHTNESS]) <NEW_LINE> <DEDENT> if ATTR_HS_COLOR in kwargs: <NEW_LINE> <INDENT> self._tuya.set_color(kwargs[ATTR_HS_COLOR]) <NEW_LINE> <DEDENT> if ATTR_COLOR_TEMP in kwargs: <NEW_LINE> <INDENT> color_temp = colorutil.color_temperature_mired_to_kelvin( kwargs[ATTR_COLOR_TEMP] ) <NEW_LINE> self._tuya.set_color_temp(color_temp) <NEW_LINE> <DEDENT> <DEDENT> def turn_off(self, **kwargs): <NEW_LINE> <INDENT> self._tuya.turn_off() <NEW_LINE> <DEDENT> @property <NEW_LINE> def supported_features(self): <NEW_LINE> <INDENT> supports = SUPPORT_BRIGHTNESS <NEW_LINE> if self._tuya.support_color(): <NEW_LINE> <INDENT> supports = supports | SUPPORT_COLOR <NEW_LINE> <DEDENT> if self._tuya.support_color_temp(): <NEW_LINE> <INDENT> supports = supports | SUPPORT_COLOR_TEMP <NEW_LINE> <DEDENT> return supports
Tuya light device.
62598fc0cc40096d6161a2f8
class User(Base): <NEW_LINE> <INDENT> __tablename__ = 'user' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> state = Column(String) <NEW_LINE> first_name = Column(String) <NEW_LINE> last_name = Column(String) <NEW_LINE> name = Column(String) <NEW_LINE> type = Column(String) <NEW_LINE> username = Column(String)
Class which represents the User table in users' states db. This is the original class which is used in DbAdapter, but custom User class could be inherited from this one and passed as user_class parameter in DbAdapter initialization
62598fc05166f23b2e24361f