code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class UniversalFuzzyScale(FuzzyScale): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._name = 'FuzzyScale' <NEW_LINE> self._levels = [{'name': 'Min', 'fSet': FuzzySet(membershipFunction=MFunction('hyperbolic', **{'a': 8, 'b': 20, 'c': 0}), supportSet=(0., 0.23), linguisticName='Min')}, {'name': 'Low', 'fSet': FuzzySet(membershipFunction=MFunction('bell', **{'a': 0.17, 'b': 0.23, 'c': 0.34}), supportSet=(0.17, 0.4), linguisticName='Low')}, {'name': 'Med', 'fSet': FuzzySet(membershipFunction=MFunction('bell', **{'a': 0.34, 'b': 0.4, 'c': 0.6}), supportSet=(0.34, 0.66), linguisticName='Med')}, {'name': 'High', 'fSet': FuzzySet(membershipFunction=MFunction('bell', **{'a': 0.6, 'b': 0.66, 'c': 0.77}), supportSet=(0.6, 0.83), linguisticName='High')}, {'name': 'Max', 'fSet': FuzzySet(membershipFunction=MFunction('parabolic', **{'a': 0.77, 'b': 0.95}), supportSet=(0.77, 1.), linguisticName='Max')}] <NEW_LINE> self._levelsNames = self._GetLevelsNames() <NEW_LINE> self._levelsNamesUpper = self._GetLevelsNamesUpper() <NEW_LINE> <DEDENT> @property <NEW_LINE> def levels(self): <NEW_LINE> <INDENT> return self._levels <NEW_LINE> <DEDENT> @property <NEW_LINE> def levelsNames(self): <NEW_LINE> <INDENT> return self._levelsNames <NEW_LINE> <DEDENT> @property <NEW_LINE> def levelsNamesUpper(self): <NEW_LINE> <INDENT> return self._levelsNamesUpper
Iniversal fuzzy scale S_f = {Min, Low, Med, High, Max}. Example view: FuzzyScale = {Min, Low, Med, High, Max} Min = <Hyperbolic(x, {"a": 8, "b": 20, "c": 0}), [0.0, 0.23]> Low = <Bell(x, {"a": 0.17, "b": 0.23, "c": 0.34}), [0.17, 0.4]> Med = <Bell(x, {"a": 0.34, "b": 0.4, "c": 0.6}), [0.34, 0.66]> High = <Bell(x, {"a": 0.6, "b": 0.66, "c": 0.77}), [0.6, 0.83]> Max = <Parabolic(x, {"a": 0.77, "b": 0.95}), [0.77, 1.0]>
62598ff7627d3e7fe0e077e5
class CargaBD_b006(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.enabled = True <NEW_LINE> self.checked = False <NEW_LINE> <DEDENT> def onClick(self): <NEW_LINE> <INDENT> pythonaddins.GPToolDialog(r'\\192.168.201.115\cpv2017\SegmentacionRural_Procesamiento\TBX\ToolbarSegmRuralV3.tbx', 'CargarInfo')
Implementation for CargaBD_b006.button (Button)
62598ff74c3428357761abee
class OligoSampleLookup(SampleLookupBase): <NEW_LINE> <INDENT> model = M.OligoSample <NEW_LINE> search_fields = ('container__displayId__startswith', 'displayId__startswith', 'oligo__displayId__startswith')
For selectable auto-completion field in Sequencing form
62598ff74c3428357761abf0
class EditDistance(_StringDistance): <NEW_LINE> <INDENT> def _distance(self, s1, s2, same): <NEW_LINE> <INDENT> return _levenshtein_like_or_border_cases(s1, s2, same, _levenshtein)
<dl> <dt>'EditDistance[$a$, $b$]' <dd>returns the Levenshtein distance of $a$ and $b$, which is defined as the minimum number of insertions, deletions and substitutions on the constituents of $a$ and $b$ needed to transform one into the other. </dl> >> EditDistance["kitten", "kitchen"] = 2 >> EditDistance["abc", "ac"] = 1 >> EditDistance["abc", "acb"] = 2 >> EditDistance["azbc", "abxyc"] = 3 The IgnoreCase option makes EditDistance ignore the case of letters: >> EditDistance["time", "Thyme"] = 3 >> EditDistance["time", "Thyme", IgnoreCase -> True] = 2 EditDistance also works on lists: >> EditDistance[{1, E, 2, Pi}, {1, E, Pi, 2}] = 2
62598ff7627d3e7fe0e077eb
class MoveFolderRequest(object): <NEW_LINE> <INDENT> def __init__(self, src_path, dest_path, src_storage_name=None, dest_storage_name=None): <NEW_LINE> <INDENT> self.src_path = src_path <NEW_LINE> self.dest_path = dest_path <NEW_LINE> self.src_storage_name = src_storage_name <NEW_LINE> self.dest_storage_name = dest_storage_name
Request model for move_folder operation. :param src_path Folder path to move e.g. '/folder' :param dest_path Destination folder path to move to e.g '/dst' :param src_storage_name Source storage name :param dest_storage_name Destination storage name
62598ff7ad47b63b2c5a819a
class CheckerError(CheckerException): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(CheckerStatus.FAILED)
Internal error in checker.
62598ff726238365f5fad4a8
class ParseError(Error): <NEW_LINE> <INDENT> _MESSAGE = "Parse error in %(filename)r, line %(lineno)s" <NEW_LINE> def __init__(self, filename, lineno): <NEW_LINE> <INDENT> Error.__init__(self, filename, lineno) <NEW_LINE> self.filename = filename <NEW_LINE> self.lineno = lineno <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._MESSAGE % {'filename': self.filename, 'lineno': self.lineno}
Parse error :CVariables: - `_MESSAGE`: The message format string :IVariables: - `filename`: The name of the file where the error occured - `lineno`: The line number of the error :Types: - `_MESSAGE`: ``str`` - `filename`: ``basestring`` - `lineno`: ``int``
62598ff70a366e3fb87dd33e
class TableSpaceAddTestCase(BaseTestGenerator): <NEW_LINE> <INDENT> scenarios = [ ('Check Tablespace Node', dict(url='/browser/tablespace/obj/')) ] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.tablespace_name = '' <NEW_LINE> if not self.server['tablespace_path'] or self.server['tablespace_path'] is None: <NEW_LINE> <INDENT> message = "Tablespace add test case. Tablespace path" " not configured for server: %s" % self.server['name'] <NEW_LINE> self.skipTest(message) <NEW_LINE> <DEDENT> <DEDENT> def runTest(self): <NEW_LINE> <INDENT> server_id = parent_node_dict["server"][-1]["server_id"] <NEW_LINE> server_response = server_utils.connect_server(self, server_id) <NEW_LINE> if not server_response['data']['connected']: <NEW_LINE> <INDENT> raise Exception("Unable to connect server to get tablespace.") <NEW_LINE> <DEDENT> db_owner = server_response['data']['user']['name'] <NEW_LINE> table_space_path = self.server['tablespace_path'] <NEW_LINE> data = tablespace_utils.get_tablespace_data( table_space_path, db_owner) <NEW_LINE> self.tablespace_name = data['name'] <NEW_LINE> response = self.tester.post( self.url + str(utils.SERVER_GROUP) + '/' + str(server_id) + '/', data=json.dumps(data), content_type='html/json') <NEW_LINE> self.assertEquals(response.status_code, 200) <NEW_LINE> response_data = json.loads(response.data.decode('utf-8')) <NEW_LINE> tablespace_id = response_data['node']['_id'] <NEW_LINE> tablespace_dict = {"tablespace_id": tablespace_id, "tablespace_name": self.tablespace_name, "server_id": server_id} <NEW_LINE> utils.write_node_info("tsid", tablespace_dict) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> connection = utils.get_db_connection(self.server['db'], self.server['username'], self.server['db_password'], self.server['host'], self.server['port'], self.server['sslmode']) <NEW_LINE> tablespace_utils.delete_tablespace(connection, self.tablespace_name)
This class will add tablespace node under server
62598ff7c4546d3d9def772c
class ListMeasurementProtocolSecretsResponse(proto.Message): <NEW_LINE> <INDENT> @property <NEW_LINE> def raw_page(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> measurement_protocol_secrets = proto.RepeatedField( proto.MESSAGE, number=1, message=resources.MeasurementProtocolSecret, ) <NEW_LINE> next_page_token = proto.Field( proto.STRING, number=2, )
Response message for ListMeasurementProtocolSecret RPC Attributes: measurement_protocol_secrets (Sequence[google.analytics.admin_v1alpha.types.MeasurementProtocolSecret]): A list of secrets for the parent stream specified in the request. next_page_token (str): A token, which can be sent as ``page_token`` to retrieve the next page. If this field is omitted, there are no subsequent pages.
62598ff74c3428357761abf6
class Thunk(LambdaProcedure): <NEW_LINE> <INDENT> def get_actual_value(self): <NEW_LINE> <INDENT> value, env = self.apply(nil, self.env) <NEW_LINE> return scheme_eval(value, self.env)
A by-name value that is to be called as a parameterless function when its value is fetched to be used.
62598ff7c4546d3d9def772d
class BindingState(): <NEW_LINE> <INDENT> def __init__(self, is_64): <NEW_LINE> <INDENT> self.index = 0 <NEW_LINE> self.done = False <NEW_LINE> self.lib_ord = 0 <NEW_LINE> self.sym_name = "" <NEW_LINE> self.sym_flags = 0 <NEW_LINE> self.binding_type = 0 <NEW_LINE> self.addend = 0 <NEW_LINE> self.segment_index = 0 <NEW_LINE> self.address = 0 <NEW_LINE> self.seg_end_address = 0 <NEW_LINE> self.wraparound = 2 ** 64 <NEW_LINE> self.sizeof_intptr_t = 8 if is_64 else 4 <NEW_LINE> self.bind_handler = None <NEW_LINE> <DEDENT> def add_address_ov(self, address, addend): <NEW_LINE> <INDENT> tmp = address + addend <NEW_LINE> if tmp > self.wraparound: <NEW_LINE> <INDENT> tmp -= self.wraparound <NEW_LINE> <DEDENT> self.address = tmp <NEW_LINE> <DEDENT> def check_address_bounds(self): <NEW_LINE> <INDENT> if self.address >= self.seg_end_address: <NEW_LINE> <INDENT> l.error("index %d: address >= seg_end_address (%#x >= %#x)", self.index, self.address, self.seg_end_address) <NEW_LINE> raise CLEInvalidBinaryError()
State object
62598ff7ad47b63b2c5a81a0
class RemoteEcont(object): <NEW_LINE> <INDENT> def __init__(self, service_url, parcel_url, username, password, transfer_class): <NEW_LINE> <INDENT> self._service_url = service_url <NEW_LINE> self._parcel_url = parcel_url <NEW_LINE> self._username = username <NEW_LINE> self._password = password <NEW_LINE> self._transfer_class = transfer_class <NEW_LINE> <DEDENT> def access_clients(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def account_roles(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def cancel_shipment(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def check_cd_agreement(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def cities(self, cities, updated_time): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def cities_quarters(self, cities, updated_time): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def cities_regions(self, cities, updated_time): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def cities_streets(self, cities, updated_time): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def cities_zones(self, cities, updated_time): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def client_info(self, ein, egn, _id): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def countries(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def delivery_days(self, delivery_days): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def offices(self, updated_time): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def post_boxes(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def profile(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def registration_request(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def shipments(self, sender_city, receiver_city, _id, full_tracking='ON'): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def shipping(self, loadings, system): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def tariff_courier(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def tariff_post(self): <NEW_LINE> <INDENT> raise NotImplementedError
Simple interface for communication with Econt services.
62598ff7627d3e7fe0e077f1
class YubiKeyCapabilities(object): <NEW_LINE> <INDENT> model = 'Unknown' <NEW_LINE> version = (0, 0, 0,) <NEW_LINE> version_num = 0x0 <NEW_LINE> default_answer = True <NEW_LINE> def __init__(self, model = None, version = None, default_answer = None): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> if default_answer is not None: <NEW_LINE> <INDENT> self.default_answer = default_answer <NEW_LINE> <DEDENT> if version is not None: <NEW_LINE> <INDENT> self.version = version <NEW_LINE> (major, minor, build,) = version <NEW_LINE> self.version_num = (major << 24) | (minor << 16) | build <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s instance at %s: Device %s %s (default: %s)>' % ( self.__class__.__name__, hex(id(self)), self.model, self.version, self.default_answer, ) <NEW_LINE> <DEDENT> def have_yubico_OTP(self): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_OATH(self, mode): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_challenge_response(self, mode): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_serial_number(self): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_ticket_flag(self, flag): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_config_flag(self, flag): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_extended_flag(self, flag): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_extended_scan_code_mode(self): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_shifted_1_mode(self): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_nfc_ndef(self, slot=1): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_configuration_slot(self): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_device_config(self): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_usb_mode(self, mode): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_scanmap(self): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_capabilities(self): <NEW_LINE> <INDENT> return self.default_answer <NEW_LINE> <DEDENT> def have_capability(self, capability): <NEW_LINE> <INDENT> return self.default_answer
Class expressing the functionality of a YubiKey. This base class should be the superset of all sub-classes. In this base class, we lie and say 'yes' to all capabilities. If the base class is used (such as when creating a YubiKeyConfig() before getting a YubiKey()), errors must be handled at runtime (or later, when the user is unable to use the YubiKey).
62598ff70a366e3fb87dd342
class ReSTFormatter(Formatter): <NEW_LINE> <INDENT> def escape(self, text): <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> def title(self, text): <NEW_LINE> <INDENT> self.print(text) <NEW_LINE> self.print('=' * len(text)) <NEW_LINE> self.print() <NEW_LINE> <DEDENT> def begin_module_section(self, modname): <NEW_LINE> <INDENT> self.print(modname) <NEW_LINE> self.print('-' * len(modname)) <NEW_LINE> self.print() <NEW_LINE> <DEDENT> def end_module_section(self): <NEW_LINE> <INDENT> self.print() <NEW_LINE> <DEDENT> def write_supported_item(self, modname, itemname, typename, explained, sources, alias): <NEW_LINE> <INDENT> self.print('.. function:: {}.{}'.format(modname, itemname)) <NEW_LINE> self.print() <NEW_LINE> if alias: <NEW_LINE> <INDENT> self.print(" Alias to: ``{}``".format(alias)) <NEW_LINE> <DEDENT> self.print() <NEW_LINE> for tcls, source in sources.items(): <NEW_LINE> <INDENT> if source: <NEW_LINE> <INDENT> impl = source['name'] <NEW_LINE> sig = source['sig'] <NEW_LINE> filename = source['filename'] <NEW_LINE> lines = source['lines'] <NEW_LINE> source_link = github_url.format( commit=commit, path=filename, firstline=lines[0], lastline=lines[1], ) <NEW_LINE> self.print( " - defined by ``{}{}`` at `{}:{}-{} <{}>`_".format( impl, sig, filename, lines[0], lines[1], source_link, ), ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.print(" - defined by ``{}``".format(str(tcls))) <NEW_LINE> <DEDENT> <DEDENT> self.print() <NEW_LINE> <DEDENT> def write_unsupported_item(self, modname, itemname): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def write_statistic(self, stat): <NEW_LINE> <INDENT> if stat.supported == 0: <NEW_LINE> <INDENT> self.print("This module is not supported.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = "Not showing {} unsupported functions." <NEW_LINE> self.print(msg.format(stat.unsupported)) <NEW_LINE> self.print() <NEW_LINE> self.print(stat.describe()) <NEW_LINE> <DEDENT> self.print()
Formatter that output ReSTructured text format for Sphinx docs.
62598ff7627d3e7fe0e077f3
class Decodable(Struct): <NEW_LINE> <INDENT> _decode_map: typing.List[ typing.Tuple[ typing.Dict[str, typing.Any], typing.Type['Decodable'] ] ] = [] <NEW_LINE> def __init_subclass__(cls, **kwargs: typing.Any): <NEW_LINE> <INDENT> super().__init_subclass__(**kwargs) <NEW_LINE> if cls._initial: <NEW_LINE> <INDENT> cls._decode_map.append((cls._initial, cls)) <NEW_LINE> cls._decode_map = [] <NEW_LINE> <DEDENT> <DEDENT> def decode(self: DerivedDecodable) -> DerivedDecodable: <NEW_LINE> <INDENT> dmap = self._decode_map <NEW_LINE> ret_tp = type(self) <NEW_LINE> while True: <NEW_LINE> <INDENT> for cond, child_tp in reversed(dmap): <NEW_LINE> <INDENT> if all(getattr(self, k) == v for k, v in cond.items()): <NEW_LINE> <INDENT> dmap = child_tp._decode_map <NEW_LINE> ret_tp = typing.cast(typing.Type[DerivedDecodable], child_tp) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return self if ret_tp is type(self) else ret_tp(ref=self.buffer)
Decoding facility added Struct
62598ff70a366e3fb87dd346
class DPT(Polio): <NEW_LINE> <INDENT> max_doses = 5
Diphtheria,Pertussis and Whooping Cough vaccine
62598ff7187af65679d2a0a3
class ParticipantsPasswordsPDF(PDFView): <NEW_LINE> <INDENT> permission_required = 'participant.can_manage_participant' <NEW_LINE> filename = ugettext_lazy("Participant-access-data") <NEW_LINE> top_space = 0 <NEW_LINE> def build_document(self, pdf_document, story): <NEW_LINE> <INDENT> pdf_document.build(story) <NEW_LINE> <DEDENT> def append_to_pdf(self, pdf): <NEW_LINE> <INDENT> participants_passwords_to_pdf(pdf)
Generate the access data welcome paper for all participants as PDF.
62598ff7ad47b63b2c5a81a8
class UriStyleGenerator(SimpleGenerator): <NEW_LINE> <INDENT> def __init__(self, uris, headers, loop_limit=0, http_ver='1.1'): <NEW_LINE> <INDENT> self.ammo_number = 0 <NEW_LINE> self.loop_limit = loop_limit <NEW_LINE> self.uri_count = len(uris) <NEW_LINE> self.missiles = cycle([(HttpAmmo(uri, headers, http_ver).to_s(), None) for uri in uris]) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for m in self.missiles: <NEW_LINE> <INDENT> self.ammo_number += 1 <NEW_LINE> if self.loop_limit and self.loop_count() > self.loop_limit: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield m <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def loop_count(self): <NEW_LINE> <INDENT> return self.ammo_number / self.uri_count
Generates GET ammo based on given URI list
62598ff7627d3e7fe0e077f9
class TestSettingsManager(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._original_settings = {} <NEW_LINE> <DEDENT> def set(self, **kwargs): <NEW_LINE> <INDENT> for k,v in kwargs.iteritems(): <NEW_LINE> <INDENT> self._original_settings.setdefault(k, getattr(settings, k, NO_SETTING)) <NEW_LINE> setattr(settings, k, v) <NEW_LINE> <DEDENT> if 'INSTALLED_APPS' in kwargs: <NEW_LINE> <INDENT> self.syncdb() <NEW_LINE> <DEDENT> <DEDENT> def syncdb(self): <NEW_LINE> <INDENT> loading.cache.loaded = False <NEW_LINE> call_command('syncdb', migrate=False, verbosity=0) <NEW_LINE> <DEDENT> def revert(self): <NEW_LINE> <INDENT> for k,v in self._original_settings.iteritems(): <NEW_LINE> <INDENT> if v == NO_SETTING: <NEW_LINE> <INDENT> delattr(settings, k) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(settings, k, v) <NEW_LINE> <DEDENT> <DEDENT> if 'INSTALLED_APPS' in self._original_settings: <NEW_LINE> <INDENT> self.syncdb() <NEW_LINE> <DEDENT> self._original_settings = {}
A class which can modify some Django settings temporarily for a test and then revert them to their original values later. Automatically handles resyncing the DB if INSTALLED_APPS is modified.
62598ff73cc13d1c6d4660a6
class State(BaseModel): <NEW_LINE> <INDENT> name = ""
Represents a state
62598ff70a366e3fb87dd34c
class ContextualInternalServerError(InternalServerError): <NEW_LINE> <INDENT> def __init__(self, *a, **kw): <NEW_LINE> <INDENT> self.request = kw.get('request') <NEW_LINE> self.hide_internal_frames = kw.pop('hide_internal_frames', True) <NEW_LINE> super(ContextualInternalServerError, self).__init__(*a, **kw) <NEW_LINE> <DEDENT> def to_dict(self, *a, **kw): <NEW_LINE> <INDENT> ret = super(ContextualInternalServerError, self).to_dict(*a, **kw) <NEW_LINE> del ret['exc_info'] <NEW_LINE> exc_info = getattr(self, 'exc_info', None) <NEW_LINE> if not exc_info: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> exc_tb = exc_info.tb_info.to_dict() <NEW_LINE> for i, frame in enumerate(exc_tb['frames']): <NEW_LINE> <INDENT> if self.hide_internal_frames: <NEW_LINE> <INDENT> if not frame['line'] and frame['module_path'] == '<string>': <NEW_LINE> <INDENT> frame['is_hidden'] = True <NEW_LINE> <DEDENT> elif frame['module_name'] == 'clastic.sinter' and frame['func_name'] == 'inject': <NEW_LINE> <INDENT> frame['is_hidden'] = True <NEW_LINE> <DEDENT> <DEDENT> frame['id'] = i <NEW_LINE> pre_start_lineno = glom(frame, T['pre_lines'][0]['lineno'], default=1) <NEW_LINE> frame['pre_start_lineno'] = pre_start_lineno <NEW_LINE> frame['post_start_lineno'] = frame['lineno'] + 1 <NEW_LINE> <DEDENT> last_frame = glom(exc_tb, T['frames'][-1], default=None) <NEW_LINE> eid = {'is_email': False, 'clastic_version': _version.__version__, 'exc_type': exc_info.exc_type, 'exc_value': exc_info.exc_msg, 'exc_tb': exc_tb, 'last_frame': last_frame, 'exc_tb_str': str(exc_info.tb_info), 'server_time': str(datetime.datetime.now()), 'server_time_utc': str(datetime.datetime.utcnow()), 'python': {'executable': sys.executable, 'version': sys.version.replace('\n', ' '), 'path': sys.path}} <NEW_LINE> request = self.request <NEW_LINE> if request: <NEW_LINE> <INDENT> eid['req'] = {'path': request.path, 'full_url': request.url, 'method': request.method, 'abs_path': request.path, 'url_params': request.args, 'cookies': request.cookies, 'headers': request.headers, 'files': request.files} <NEW_LINE> <DEDENT> ret.update(eid) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def to_html(self, *a, **kw): <NEW_LINE> <INDENT> render_ctx = self.to_dict() <NEW_LINE> return CONTEXTUAL_ENV.render('500.html', render_ctx)
An Internal Server Error with a full contextual view of the exception, mostly for development (non-production) purposes. # NOTE: The dict returned by to_dict is not JSON-encodable with the default encoder. It relies on the ClasticJSONEncoder currently used in the InternalServerError class.
62598ff8627d3e7fe0e077fb
class _DispycosJob_(object): <NEW_LINE> <INDENT> __slots__ = ('request', 'client', 'name', 'where', 'cpu', 'code', 'args', 'kwargs', 'done') <NEW_LINE> def __init__(self, request, client, name, where, cpu, code, args=None, kwargs=None): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> self.client = client <NEW_LINE> self.name = name <NEW_LINE> self.where = where <NEW_LINE> self.cpu = cpu <NEW_LINE> self.code = code <NEW_LINE> self.args = pycos.serialize(args) <NEW_LINE> self.kwargs = pycos.serialize(kwargs) <NEW_LINE> self.done = None
Internal use only.
62598ff8187af65679d2a0a5
class ProgressBar(Widget): <NEW_LINE> <INDENT> pass
Tk no prograss bar support
62598ff84c3428357761ac04
class GwDbValidatorsPattern(GwSqlPattern, GwValidatorsPattern): <NEW_LINE> <INDENT> def __init__(self, app, **kwargs): <NEW_LINE> <INDENT> super(GwDbValidatorsPattern, self).__init__(app, **kwargs) <NEW_LINE> self.app = app <NEW_LINE> self.validators.db = DbValidatorsPlugin(self) <NEW_LINE> if not hasattr(self.app.validators, "db"): <NEW_LINE> <INDENT> self.app.validators.db = DbValidatorsApplication(self.app)
Allows the validation of database model requests. Builds automatically hashes of table rows/model instances and validates these hashes, if a request is made on these rows.
62598ff8187af65679d2a0a6
class Reals(DeclarativeBase): <NEW_LINE> <INDENT> __tablename__ = 'reals' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> title = Column('title', String) <NEW_LINE> link = Column('link', String, nullable=True)
SQLAlchemy Reals Model
62598ff80a366e3fb87dd350
class CouponStatus(object): <NEW_LINE> <INDENT> NEW = 1 <NEW_LINE> CANCELLED = 2 <NEW_LINE> _VALUES_TO_NAMES = { 1: "NEW", 2: "CANCELLED", } <NEW_LINE> _NAMES_TO_VALUES = { "NEW": 1, "CANCELLED": 2, }
CouponStatus Перечисление статусов талончика на прием к врачу
62598ff80a366e3fb87dd352
class VolumeRenderingSpecialEffectsTest(ScriptedLoadableModuleTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> slicer.mrmlScene.Clear(0) <NEW_LINE> <DEDENT> def runTest(self): <NEW_LINE> <INDENT> self.setUp() <NEW_LINE> self.test_VolumeRenderingSpecialEffects1() <NEW_LINE> <DEDENT> def test_VolumeRenderingSpecialEffects1(self): <NEW_LINE> <INDENT> self.delayDisplay("Starting the test") <NEW_LINE> import SampleData <NEW_LINE> volumeNode = SampleData.downloadFromURL( nodeNames='MRHead', fileNames='MR-Head.nrrd', uris='https://github.com/Slicer/SlicerTestingData/releases/download/MD5/39b01631b7b38232a220007230624c8e', checksums='MD5:39b01631b7b38232a220007230624c8e')[0] <NEW_LINE> self.delayDisplay('Finished with download and loading') <NEW_LINE> markupsNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLMarkupsFiducialNode") <NEW_LINE> markupsNode.CreateDefaultDisplayNodes() <NEW_LINE> parameterNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLScriptedModuleNode") <NEW_LINE> parameterNode.SetModuleName("VolumeRenderingSpecialEffects") <NEW_LINE> parameterNode.SetAttribute("ModuleName", "VolumeRenderingSpecialEffects") <NEW_LINE> parameterNode.SetNodeReferenceID("InputVolume", volumeNode.GetID()) <NEW_LINE> parameterNode.SetNodeReferenceID("InputMarkups", markupsNode.GetID()) <NEW_LINE> parameterNode.SetParameter("Radius", "60.0") <NEW_LINE> parameterNode.SetParameter("Mode", "None") <NEW_LINE> self.delayDisplay('No special effect') <NEW_LINE> logic = VolumeRenderingSpecialEffectsLogic() <NEW_LINE> logic.setParameterNode(parameterNode) <NEW_LINE> self.delayDisplay('Sphere crop') <NEW_LINE> markupsNode.AddControlPointWorld(vtk.vtkVector3d(-3,67,45)) <NEW_LINE> parameterNode.SetParameter("Mode", "SphereCrop") <NEW_LINE> self.delayDisplay('Wedge crop') <NEW_LINE> markupsNode.RemoveAllControlPoints() <NEW_LINE> markupsNode.AddControlPointWorld(vtk.vtkVector3d(1,30,-20)) <NEW_LINE> markupsNode.AddControlPointWorld(vtk.vtkVector3d(30,97,20)) <NEW_LINE> parameterNode.SetParameter("Mode", "WedgeCrop") <NEW_LINE> self.delayDisplay('Test passed')
This is the test case for your scripted module. Uses ScriptedLoadableModuleTest base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
62598ff8ad47b63b2c5a81b2
class ICollectiveJqxgridPagesLayer(IDefaultBrowserLayer): <NEW_LINE> <INDENT> pass
Marker interface that defines a browser layer.
62598ff8c4546d3d9def7736
class RegistrationForm(forms.Form): <NEW_LINE> <INDENT> username = forms.CharField(max_length=30, widget=forms.TextInput(attrs=attrs_reqd), label=_(u'Username')) <NEW_LINE> email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_reqd, maxlength=75) ), label=_(u'Your Email Address')) <NEW_LINE> password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_reqd), label=_(u'Password')) <NEW_LINE> password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_reqd), label=_(u'Password (again)')) <NEW_LINE> def clean_username(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(username__exact=self.cleaned_data['username']) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> return self.cleaned_data['username'] <NEW_LINE> <DEDENT> raise forms.ValidationError(_(u'This username is already taken. Please choose another.')) <NEW_LINE> <DEDENT> def clean_password2(self): <NEW_LINE> <INDENT> if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: <NEW_LINE> <INDENT> if self.cleaned_data['password1'] == self.cleaned_data['password2']: <NEW_LINE> <INDENT> return self.cleaned_data['password2'] <NEW_LINE> <DEDENT> raise forms.ValidationError(_(u'You must type the same password each time')) <NEW_LINE> <DEDENT> <DEDENT> def save(self, profile_callback=None): <NEW_LINE> <INDENT> new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], profile_callback=profile_callback) <NEW_LINE> barf <NEW_LINE> return new_user
Form for registering a new user account. Validates that the request username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should either preserve the base ``save()`` or implement a ``save()`` which accepts the ``profile_callback`` keyword argument and passes it through to ``RegistrationProfile.objects.create_inactive_user()``.
62598ff826238365f5fad4c0
class UseCaseParams(EmbeddedDocument): <NEW_LINE> <INDENT> key = StringField() <NEW_LINE> value = StringField() <NEW_LINE> description = StringField()
请求参数
62598ff8ad47b63b2c5a81b4
class AudioPauseCb(ctypes.c_void_p): <NEW_LINE> <INDENT> pass
Callback prototype for audio pause. ote The pause callback is never called if the audio is already paused. \param data data pointer as passed to L{libvlc_audio_set_callbacks}() [IN] \param pts time stamp of the pause request (should be elapsed already)
62598ff815fb5d323ce7f6a5
class CustomUserManager(BaseUserManager): <NEW_LINE> <INDENT> def create_user(self, email, password=None, **kwargs): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError('Email field is required') <NEW_LINE> <DEDENT> email = self.normalize_email(email) <NEW_LINE> user = self.model(email=email, **kwargs) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_superuser(self, email, password, **extra_fields): <NEW_LINE> <INDENT> extra_fields.setdefault('is_staff', True) <NEW_LINE> extra_fields.setdefault('is_superuser', True) <NEW_LINE> extra_fields.setdefault('is_active', True) <NEW_LINE> return self.create_user(email, password, **extra_fields)
Overriding BaseUserManager in order to allow users to register and authenticate by using email instead of username.
62598ff8c4546d3d9def7737
class MinHeap(): <NEW_LINE> <INDENT> def __init__(self, items = None): <NEW_LINE> <INDENT> if not items: <NEW_LINE> <INDENT> self.heap = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.heap = items[:] <NEW_LINE> <DEDENT> heapq.heapify(self.heap) <NEW_LINE> <DEDENT> def push(self, item): <NEW_LINE> <INDENT> heapq.heappush(self.heap, item) <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> return heapq.heappop(self.heap) <NEW_LINE> <DEDENT> def get(self, num): <NEW_LINE> <INDENT> return self.heap[num] <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return len(self.heap) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.heap)
A minimum heap. This is kind of cheating since I use the built-in heap implementation
62598ff80a366e3fb87dd356
class FacebookManager(models.Manager): <NEW_LINE> <INDENT> def create_facebook_profile( self, facebook_id, first_name, last_name, birthday, relationship, hometown, current_city, facebook_email, gender, profile_picture_url, friends_count, link, age_range, last_updated, auth_token, devices ): <NEW_LINE> <INDENT> facebook_profile = self.create( facebook_id=facebook_id, first_name=first_name, last_name=last_name, birthday=birthday, relationship=relationship, hometown=hometown, current_city=current_city, facebook_email=facebook_email, gender=gender, profile_picture_url=profile_picture_url, friends_count=friends_count, link=link, age_range=age_range, last_updated=last_updated, auth_token=auth_token, devices=devices ) <NEW_LINE> return facebook_profile
Manager for the FacebookProfile Model
62598ff8ad47b63b2c5a81b6
class RelayExtraInfoDescriptor(ExtraInfoDescriptor): <NEW_LINE> <INDENT> TYPE_ANNOTATION_NAME = 'extra-info' <NEW_LINE> ATTRIBUTES = dict(ExtraInfoDescriptor.ATTRIBUTES, **{ 'ed25519_certificate': (None, _parse_identity_ed25519_line), 'ed25519_signature': (None, _parse_router_sig_ed25519_line), 'signature': (None, _parse_router_signature_line), }) <NEW_LINE> PARSER_FOR_LINE = dict(ExtraInfoDescriptor.PARSER_FOR_LINE, **{ 'identity-ed25519': _parse_identity_ed25519_line, 'router-sig-ed25519': _parse_router_sig_ed25519_line, 'router-signature': _parse_router_signature_line, }) <NEW_LINE> @classmethod <NEW_LINE> def content(cls, attr = None, exclude = (), sign = False, signing_key = None): <NEW_LINE> <INDENT> base_header = ( ('extra-info', '%s %s' % (_random_nickname(), _random_fingerprint())), ('published', _random_date()), ) <NEW_LINE> if signing_key: <NEW_LINE> <INDENT> sign = True <NEW_LINE> <DEDENT> if sign: <NEW_LINE> <INDENT> if attr and 'router-signature' in attr: <NEW_LINE> <INDENT> raise ValueError('Cannot sign the descriptor if a router-signature has been provided') <NEW_LINE> <DEDENT> if signing_key is None: <NEW_LINE> <INDENT> signing_key = create_signing_key() <NEW_LINE> <DEDENT> content = _descriptor_content(attr, exclude, base_header) + b'\nrouter-signature\n' <NEW_LINE> return _append_router_signature(content, signing_key.private) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return _descriptor_content(attr, exclude, base_header, ( ('router-signature', _random_crypto_blob('SIGNATURE')), )) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def create(cls, attr = None, exclude = (), validate = True, sign = False, signing_key = None): <NEW_LINE> <INDENT> return cls(cls.content(attr, exclude, sign, signing_key), validate = validate) <NEW_LINE> <DEDENT> @lru_cache() <NEW_LINE> def digest(self, hash_type = DigestHash.SHA1, encoding = DigestEncoding.HEX): <NEW_LINE> <INDENT> if hash_type == DigestHash.SHA1: <NEW_LINE> <INDENT> content = self._content_range(end = '\nrouter-signature\n') <NEW_LINE> return stem.descriptor._encode_digest(hashlib.sha1(content), encoding) <NEW_LINE> <DEDENT> elif hash_type == DigestHash.SHA256: <NEW_LINE> <INDENT> return stem.descriptor._encode_digest(hashlib.sha256(self.get_bytes()), encoding) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError('Extrainfo descriptor digests are only available in sha1 and sha256, not %s' % hash_type)
Relay extra-info descriptor, constructed from data such as that provided by 'GETINFO extra-info/digest/\*', cached descriptors, and metrics (`specification <https://gitweb.torproject.org/torspec.git/tree/dir-spec.txt>`_). :var ed25519_certificate str: base64 encoded ed25519 certificate :var ed25519_signature str: signature of this document using ed25519 :var str signature: **\*** signature for this extrainfo descriptor **\*** attribute is required when we're parsed with validation .. versionchanged:: 1.5.0 Added the ed25519_certificate and ed25519_signature attributes.
62598ff8c4546d3d9def7738
class Sensor(object): <NEW_LINE> <INDENT> def __init__(self, channel=0, volts=2.0): <NEW_LINE> <INDENT> self.channel = channel <NEW_LINE> self.volts = volts <NEW_LINE> self.spi = spidev.SpiDev() <NEW_LINE> self.spi.open(0, 0) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.spi.close() <NEW_LINE> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> r = self.spi.xfer2([1, 8 + self.channel << 4, 0]) <NEW_LINE> return ((r[1] & 3) << 8) + r[2] <NEW_LINE> <DEDENT> def get_readings(self): <NEW_LINE> <INDENT> value = self.get_value() <NEW_LINE> volts = (value * self.volts) / 1024 <NEW_LINE> direction = (volts - 0.389) / 16 * 360 if volts > 0 else 0 <NEW_LINE> return SensorDirection(direction=max(0, min(direction * 10, 360)))
Sensor for Wind Direction. 0-360 degrees 0.4v = 0 degrees north 16 directions Specification: http://chinaplccenter.com/support/pdf/Sensor/QS-FX-en.pdf
62598ff8627d3e7fe0e07808
class Loc(object): <NEW_LINE> <INDENT> def __init__(self, filename, line, col=None): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.line = line <NEW_LINE> self.col = col <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_function_id(cls, func_id): <NEW_LINE> <INDENT> return cls(func_id.filename, func_id.firstlineno) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Loc(filename=%s, line=%s, col=%s)" % (self.filename, self.line, self.col) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.col is not None: <NEW_LINE> <INDENT> return "%s (%s:%s)" % (self.filename, self.line, self.col) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "%s (%s)" % (self.filename, self.line) <NEW_LINE> <DEDENT> <DEDENT> def strformat(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> path = os.path.relpath(self.filename) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> path = os.path.abspath(self.filename) <NEW_LINE> <DEDENT> return 'File "%s", line %d' % (path, self.line) <NEW_LINE> <DEDENT> def with_lineno(self, line, col=None): <NEW_LINE> <INDENT> return type(self)(self.filename, line, col)
Source location
62598ff826238365f5fad4c4
class Movie(): <NEW_LINE> <INDENT> def __init__(self, movie_title, movie_storyline, poster_image, release_date, starring, trailer_youtube): <NEW_LINE> <INDENT> self.title = movie_title <NEW_LINE> self.storyline = movie_storyline <NEW_LINE> self.poster_image_url = poster_image <NEW_LINE> self.release_date = release_date <NEW_LINE> self.starring = starring <NEW_LINE> self.trailer_youtube_url = trailer_youtube <NEW_LINE> <DEDENT> def show_trailer(self): <NEW_LINE> <INDENT> webbrowser.open(self.trailer_youtube_url)
Create a class Movie with title, storyline, image, release date, cast, and youtube trailer attributes
62598ff815fb5d323ce7f6a9
class TestKeyedItem(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 testKeyedItem(self): <NEW_LINE> <INDENT> pass
KeyedItem unit test stubs
62598ff84c3428357761ac10
class OverrideWaffleFlagTests(TestCase): <NEW_LINE> <INDENT> NAMESPACE_NAME = "test_namespace" <NEW_LINE> FLAG_NAME = "test_flag" <NEW_LINE> NAMESPACED_FLAG_NAME = NAMESPACE_NAME + "." + FLAG_NAME <NEW_LINE> TEST_COURSE_KEY = CourseKey.from_string("edX/DemoX/Demo_Course") <NEW_LINE> TEST_NAMESPACE = WaffleFlagNamespace(NAMESPACE_NAME) <NEW_LINE> TEST_COURSE_FLAG = CourseWaffleFlag(TEST_NAMESPACE, FLAG_NAME) <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(OverrideWaffleFlagTests, self).setUp() <NEW_LINE> request = RequestFactory().request() <NEW_LINE> self.addCleanup(crum.set_current_request, None) <NEW_LINE> crum.set_current_request(request) <NEW_LINE> RequestCache.clear_all_namespaces() <NEW_LINE> <DEDENT> @override_waffle_flag(TEST_COURSE_FLAG, True) <NEW_LINE> def assert_decorator_activates_flag(self): <NEW_LINE> <INDENT> assert self.TEST_COURSE_FLAG.is_enabled(self.TEST_COURSE_KEY) <NEW_LINE> <DEDENT> def test_override_waffle_flag_pre_cached(self): <NEW_LINE> <INDENT> assert not self.TEST_COURSE_FLAG.is_enabled(self.TEST_COURSE_KEY) <NEW_LINE> flag_cache = self.TEST_COURSE_FLAG.waffle_namespace._cached_flags <NEW_LINE> assert self.NAMESPACED_FLAG_NAME in flag_cache <NEW_LINE> self.assert_decorator_activates_flag() <NEW_LINE> assert self.NAMESPACED_FLAG_NAME in flag_cache <NEW_LINE> assert not self.TEST_COURSE_FLAG.is_enabled(self.TEST_COURSE_KEY) <NEW_LINE> <DEDENT> def test_override_waffle_flag_not_pre_cached(self): <NEW_LINE> <INDENT> flag_cache = self.TEST_COURSE_FLAG.waffle_namespace._cached_flags <NEW_LINE> assert self.NAMESPACED_FLAG_NAME not in flag_cache <NEW_LINE> self.assert_decorator_activates_flag() <NEW_LINE> assert self.NAMESPACED_FLAG_NAME not in flag_cache <NEW_LINE> <DEDENT> def test_override_waffle_flag_as_context_manager(self): <NEW_LINE> <INDENT> assert not self.TEST_COURSE_FLAG.is_enabled(self.TEST_COURSE_KEY) <NEW_LINE> with override_waffle_flag(self.TEST_COURSE_FLAG, True): <NEW_LINE> <INDENT> assert self.TEST_COURSE_FLAG.is_enabled(self.TEST_COURSE_KEY) <NEW_LINE> <DEDENT> assert not self.TEST_COURSE_FLAG.is_enabled(self.TEST_COURSE_KEY)
Tests for the override_waffle_flag decorator/context manager.
62598ff8ad47b63b2c5a81ba
class Containers(ResourceCollection): <NEW_LINE> <INDENT> resource_class = Container
Containers collection API methods.
62598ff8c4546d3d9def773a
class ComputeGlobalForwardingRulesListRequest(messages.Message): <NEW_LINE> <INDENT> filter = messages.StringField(1) <NEW_LINE> maxResults = messages.IntegerField(2, variant=messages.Variant.UINT32, default=500) <NEW_LINE> pageToken = messages.StringField(3) <NEW_LINE> project = messages.StringField(4, required=True)
A ComputeGlobalForwardingRulesListRequest object. Fields: filter: Optional. Filter expression for filtering listed resources. maxResults: Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. pageToken: Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. project: Name of the project scoping this request.
62598ff8c4546d3d9def773b
class PinentryTests(unittest.SynchronousTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.pinentry = _impl.Pinentry(name="pinentry") <NEW_LINE> <DEDENT> def test_argvRaisesWhenNotFound(self): <NEW_LINE> <INDENT> self.assertRaises( _impl.PinentryNotFound, self.pinentry.argv, _which=lambda arg: [], ) <NEW_LINE> <DEDENT> def test_argvReturnsListWhenFoundWithDefaultArgumentFactory(self): <NEW_LINE> <INDENT> path = ["/path/to/pinentry"] <NEW_LINE> self.assertEqual(self.pinentry.argv(_which=lambda arg: path), path) <NEW_LINE> <DEDENT> def test_argvReturnsListWhenFoundWithCustomArgumentFactory(self): <NEW_LINE> <INDENT> def argumentFactory(): <NEW_LINE> <INDENT> return ["a", "b"] <NEW_LINE> <DEDENT> path = "/path/to/pin/entry" <NEW_LINE> def which(arg): <NEW_LINE> <INDENT> return [path, "ignored"] <NEW_LINE> <DEDENT> pinentry = _impl.Pinentry( name="pinentry", argumentFactory=argumentFactory ) <NEW_LINE> self.assertEqual( pinentry.argv(_which=which), [path] + argumentFactory(), )
Tests for L{_impl.Pinentry}.
62598ff8187af65679d2a0ae
class modelParams(object): <NEW_LINE> <INDENT> def __init__(self, learn_rate = 0.001, replay_size = 32, max_memory = 2000, num_epochs = 2, hidden_size = 16): <NEW_LINE> <INDENT> self.learn_rate = float(learn_rate) <NEW_LINE> self.replay_size = int(replay_size) <NEW_LINE> self.max_memory = int(max_memory) <NEW_LINE> self.num_epochs = int(num_epochs) <NEW_LINE> self.hidden_size = int(hidden_size)
Parameters of the model
62598ff8c4546d3d9def773d
class DiminishedSeventhSimultaneityPrevalence(featuresModule.FeatureExtractor): <NEW_LINE> <INDENT> id = 'CS10' <NEW_LINE> def __init__(self, dataOrStream=None, *arguments, **keywords): <NEW_LINE> <INDENT> featuresModule.FeatureExtractor.__init__(self, dataOrStream=dataOrStream, *arguments, **keywords) <NEW_LINE> self.name = 'Diminished Seventh Simultaneity Prevalence' <NEW_LINE> self.description = 'Percentage of all simultaneities that are diminished seventh chords.' <NEW_LINE> self.dimensions = 1 <NEW_LINE> self.discrete = False <NEW_LINE> <DEDENT> def _process(self): <NEW_LINE> <INDENT> total = len(self.data['chordify.getElementsByClass.Chord']) <NEW_LINE> histo = self.data['chordifyTypesHistogram'] <NEW_LINE> part = histo['isDiminishedSeventh'] <NEW_LINE> self._feature.vector[0] = part / float(total)
Percentage of all simultaneities that are diminished seventh chords. >>> s = corpus.parse('bwv66.6') >>> fe = features.native.DiminishedSeventhSimultaneityPrevalence(s) >>> fe.extract().vector [0.0]
62598ff8627d3e7fe0e07812
class ClaimProjectsForm(forms.Form): <NEW_LINE> <INDENT> def __init__(self, slug, *args, **kwargs): <NEW_LINE> <INDENT> super(ClaimProjectsForm, self).__init__(*args, **kwargs) <NEW_LINE> course = Course.objects.get(slug=slug) <NEW_LINE> course_projects = course.projects.all() <NEW_LINE> if len(course_projects) > 1: <NEW_LINE> <INDENT> self.fields['all_projects'].choices = course_projects <NEW_LINE> self.fields['all_projects'].widget = forms.SelectMultiple <NEW_LINE> <DEDENT> <DEDENT> all_projects = forms.ChoiceField( label="All Projects", required=False ) <NEW_LINE> claimed_projects = forms.ChoiceField( label="Claimed Projects", required=False ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Course <NEW_LINE> fields = ['all_projects', 'claimed_projects']
Form used for TA's to select their projects
62598ff83cc13d1c6d4660be
@ut.skip("external dataset option not supported") <NEW_LINE> class TestExternal(BaseDataset): <NEW_LINE> <INDENT> def test_contents(self): <NEW_LINE> <INDENT> shape = (6, 100) <NEW_LINE> testdata = np.random.random(shape) <NEW_LINE> ext_file = self.mktemp() <NEW_LINE> external = [(ext_file, 0, h5f.UNLIMITED)] <NEW_LINE> dset = self.f.create_dataset('foo', shape, dtype=testdata.dtype, external=external) <NEW_LINE> dset[...] = testdata <NEW_LINE> assert dset.external is not None <NEW_LINE> with open(ext_file, 'rb') as fid: <NEW_LINE> <INDENT> contents = fid.read() <NEW_LINE> <DEDENT> assert contents == testdata.tobytes() <NEW_LINE> <DEDENT> def test_name_str(self): <NEW_LINE> <INDENT> self.f.create_dataset('foo', (6, 100), external=self.mktemp()) <NEW_LINE> <DEDENT> def test_name_path(self): <NEW_LINE> <INDENT> self.f.create_dataset('foo', (6, 100), external=pathlib.Path(self.mktemp())) <NEW_LINE> <DEDENT> def test_iter_multi(self): <NEW_LINE> <INDENT> ext_file = self.mktemp() <NEW_LINE> N = 100 <NEW_LINE> external = iter((ext_file, x * 1000, 1000) for x in range(N)) <NEW_LINE> dset = self.f.create_dataset('poo', (6, 100), external=external) <NEW_LINE> assert len(dset.external) == N <NEW_LINE> <DEDENT> def test_invalid(self): <NEW_LINE> <INDENT> shape = (6, 100) <NEW_LINE> ext_file = self.mktemp() <NEW_LINE> for exc_type, external in [ (TypeError, [ext_file]), (TypeError, [ext_file, 0]), (TypeError, [ext_file, 0, h5f.UNLIMITED]), (ValueError, [(ext_file,)]), (ValueError, [(ext_file, 0)]), (ValueError, [(ext_file, 0, h5f.UNLIMITED, 0)]), (TypeError, [(ext_file, 0, "h5f.UNLIMITED")]), ]: <NEW_LINE> <INDENT> with self.assertRaises(exc_type): <NEW_LINE> <INDENT> self.f.create_dataset('foo', shape, external=external)
Feature: Datasets with the external storage property TBD: external option not supported in HSDS. Use external link instead
62598ff8ad47b63b2c5a81c2
class OrgDetailCourse(View): <NEW_LINE> <INDENT> def get(self, request, org_id): <NEW_LINE> <INDENT> current_page = 'course' <NEW_LINE> detail_org = get_object_or_404(CourseOrg, pk=int(org_id)) <NEW_LINE> all_course = detail_org.course_set.all() <NEW_LINE> has_fav = False <NEW_LINE> if request.user.is_authenticated: <NEW_LINE> <INDENT> if UserFavorite.objects.filter(user=request.user, fav_id=int(detail_org.pk), fav_type=2): <NEW_LINE> <INDENT> has_fav = True <NEW_LINE> <DEDENT> <DEDENT> return render(request, 'org-detail-course.html',{ "all_course": all_course, "detail_org": detail_org, "current_page": current_page, "has_fav": has_fav, })
课程机构课程
62598ff8187af65679d2a0b1
class TestPlotMultiCctfs(unittest.TestCase): <NEW_LINE> <INDENT> def test_plot_multi_cctfs(self): <NEW_LINE> <INDENT> figure, axes = plot_multi_cctfs(["ITU-R BT.709", "sRGB"]) <NEW_LINE> self.assertIsInstance(figure, Figure) <NEW_LINE> self.assertIsInstance(axes, Axes)
Define :func:`colour.plotting.models.plot_multi_cctfs` definition unit tests methods.
62598ff8ad47b63b2c5a81c4
class Square(): <NEW_LINE> <INDENT> def __init__(self, size=0): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> <DEDENT> def area(self): <NEW_LINE> <INDENT> return self.__size ** 2 <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self.__size <NEW_LINE> <DEDENT> @size.setter <NEW_LINE> def size(self, value): <NEW_LINE> <INDENT> if not isinstance(value, int) and not isinstance(value, float): <NEW_LINE> <INDENT> raise TypeError("size must be an number") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("size must be >= 0") <NEW_LINE> <DEDENT> self.__size = value <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.area() == other.area() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return self.area() != other.area() <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return self.area() > other.area() <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.area() < other.area() <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> return self.area() >= other.area() <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return self.area() <= other.area()
A square class.
62598ff80a366e3fb87dd365
class TestSchoolUser(TestCase): <NEW_LINE> <INDENT> token = None <NEW_LINE> ip_addr = None <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.token, self.ip_addr = Initialization.start_session(self) <NEW_LINE> Initialization.register(self, 'testuser', 'Test666', '11011011011') <NEW_LINE> Initialization.login(self, 'testuser', 'Test666') <NEW_LINE> Initialization.promote_user(self, 4) <NEW_LINE> Initialization.create_theme(self, 0, '计算机科学与技术', '贵系', '2099-10-30 00:00:00.000000') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> Initialization.disconnect(self) <NEW_LINE> <DEDENT> def test0001(self): <NEW_LINE> <INDENT> response = self.client.post('/school/theme/create', { 'token' : self.token, 'school_id' : 0, 'theme_name' : '测试帖子', 'theme_description' : '测试帖子', 'theme_deadline' : '2019-10-30 00:00:00.000000' }) <NEW_LINE> data = analyse_response(response) <NEW_LINE> self.assertEqual(data.get('status'), 1)
Test Program User
62598ff8c4546d3d9def773f
class MailTemplate(SimpleLogingInformations, Base): <NEW_LINE> <INDENT> name = Column('name', Unicode(255, collation='utf8_unicode_ci'), nullable=False) <NEW_LINE> body = Column('body', UnicodeText(collation='utf8_unicode_ci'), nullable=False) <NEW_LINE> subject = Column('subject', Unicode(255, collation='utf8_unicode_ci'), nullable=False) <NEW_LINE> def to_dict(self, complete=True, inflated=False): <NEW_LINE> <INDENT> if complete: <NEW_LINE> <INDENT> return {'identifier': self.convert_value(self.uuid), 'name': self.convert_value(self.name), 'body': self.convert_value(self.body), 'subject': self.convert_value(self.subject)} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return {'identifier': self.convert_value(self.uuid), 'name': self.convert_value(self.name)} <NEW_LINE> <DEDENT> <DEDENT> def populate(self, json): <NEW_LINE> <INDENT> self.name = json.get('name', None) <NEW_LINE> self.body = json.get('body', None) <NEW_LINE> self.subject = json.get('subject', None) <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> ObjectValidator.validateAlNum(self, 'name', withSpaces=True, minLength=3, withSymbols=True) <NEW_LINE> ObjectValidator.validateAlNum(self, 'body', withNonPrintableCharacters=True, withSpaces=True, minLength=3, withSymbols=True) <NEW_LINE> ObjectValidator.validateAlNum(self, 'subject', withSpaces=True, minLength=3, withSymbols=True) <NEW_LINE> return ObjectValidator.isObjectValid(self)
This is a container class for the Mails table.
62598ff8627d3e7fe0e0781a
class MatchCondition(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'match_variables': {'required': True}, 'operator': {'required': True}, 'match_values': {'required': True}, } <NEW_LINE> _attribute_map = { 'match_variables': {'key': 'matchVariables', 'type': '[MatchVariable]'}, 'operator': {'key': 'operator', 'type': 'str'}, 'negation_conditon': {'key': 'negationConditon', 'type': 'bool'}, 'match_values': {'key': 'matchValues', 'type': '[str]'}, 'transforms': {'key': 'transforms', 'type': '[str]'}, } <NEW_LINE> def __init__( self, *, match_variables: List["MatchVariable"], operator: Union[str, "WebApplicationFirewallOperator"], match_values: List[str], negation_conditon: Optional[bool] = None, transforms: Optional[List[Union[str, "WebApplicationFirewallTransform"]]] = None, **kwargs ): <NEW_LINE> <INDENT> super(MatchCondition, self).__init__(**kwargs) <NEW_LINE> self.match_variables = match_variables <NEW_LINE> self.operator = operator <NEW_LINE> self.negation_conditon = negation_conditon <NEW_LINE> self.match_values = match_values <NEW_LINE> self.transforms = transforms
Define match conditions. All required parameters must be populated in order to send to Azure. :param match_variables: Required. List of match variables. :type match_variables: list[~azure.mgmt.network.v2019_09_01.models.MatchVariable] :param operator: Required. Describes operator to be matched. Possible values include: "IPMatch", "Equal", "Contains", "LessThan", "GreaterThan", "LessThanOrEqual", "GreaterThanOrEqual", "BeginsWith", "EndsWith", "Regex", "GeoMatch". :type operator: str or ~azure.mgmt.network.v2019_09_01.models.WebApplicationFirewallOperator :param negation_conditon: Describes if this is negate condition or not. :type negation_conditon: bool :param match_values: Required. Match value. :type match_values: list[str] :param transforms: List of transforms. :type transforms: list[str or ~azure.mgmt.network.v2019_09_01.models.WebApplicationFirewallTransform]
62598ff84c3428357761ac21
class DistrictManipulator(ManipulatorBase[District]): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def getCacheKeysAndQueries( cls, affected_refs: TAffectedReferences ) -> List[get_affected_queries.TCacheKeyAndQuery]: <NEW_LINE> <INDENT> return get_affected_queries.district_updated(affected_refs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def updateMerge( cls, new_model: District, old_model: District, auto_union: bool = True ) -> District: <NEW_LINE> <INDENT> cls._update_attrs(new_model, old_model, auto_union) <NEW_LINE> return old_model
Handles District database writes
62598ff8ad47b63b2c5a81ca
class BusInfoOnRoad(BaseDataRequest): <NEW_LINE> <INDENT> def __init__(self, line_name, from_station): <NEW_LINE> <INDENT> BaseDataRequest.__init__(self, 'GetBusListOnRoad') <NEW_LINE> self.set_param({ 'lineName': line_name, 'fromStation': from_station })
获取指定线路路上巴士的信息
62598ff80a366e3fb87dd36b
class UploadDefaultTranscriptHandlerTests(VideoXBlockTestBase): <NEW_LINE> <INDENT> @patch('video_xblock.video_xblock.create_reference_name') <NEW_LINE> def test_upload_handler_default_transcript_not_in_vtt_case(self, create_reference_name_mock): <NEW_LINE> <INDENT> request_body = """{"label": "test_label","lang": "test_lang","source": "test_source","url": "test_url"}""" <NEW_LINE> assert_data = json.loads(request_body) <NEW_LINE> test_media_id = 'test_video_id' <NEW_LINE> test_subs_text = 'test_subs_text' <NEW_LINE> test_reference = 'test_reference' <NEW_LINE> test_file_name = 'test_file_name' <NEW_LINE> test_external_url = 'test_external_url' <NEW_LINE> request_mock = arrange_request_mock(request_body) <NEW_LINE> create_reference_name_mock.return_value = test_reference <NEW_LINE> with patch.object(self.xblock, 'get_player') as get_player_mock, patch.object(self.xblock, 'convert_caps_to_vtt') as convert_caps_mock, patch.object(self.xblock, 'create_transcript_file') as create_transcript_file_mock: <NEW_LINE> <INDENT> get_player_mock.return_value = player_mock = Mock() <NEW_LINE> convert_caps_mock.return_value = prepared_subs_mock = Mock() <NEW_LINE> create_transcript_file_mock.return_value = (test_file_name, test_external_url) <NEW_LINE> player_mock.media_id.return_value = test_media_id <NEW_LINE> player_mock.download_default_transcript.return_value = test_subs_text <NEW_LINE> type(player_mock).default_transcripts_in_vtt = PropertyMock(return_value=False) <NEW_LINE> response = self.xblock.upload_default_transcript_handler(request_mock) <NEW_LINE> player_mock.download_default_transcript.assert_called_with( assert_data['url'], assert_data['lang'] ) <NEW_LINE> create_reference_name_mock.assert_called_with(assert_data['label'], test_media_id, assert_data['source']) <NEW_LINE> player_mock.download_default_transcript.assert_called_with( assert_data['url'], assert_data['lang'] ) <NEW_LINE> convert_caps_mock.assert_called_with(caps=test_subs_text) <NEW_LINE> create_transcript_file_mock.assert_called_with(trans_str=prepared_subs_mock, reference_name=test_reference) <NEW_LINE> self.assertEqual( response.body, bytes(json.dumps({ 'success_message': 'Successfully uploaded "test_file_name".', 'lang': assert_data['lang'], 'url': test_external_url, 'label': assert_data['label'], 'source': assert_data['source'], }), 'utf-8') )
Test cases for `VideoXBlock.upload_default_transcript_handler`.
62598ff815fb5d323ce7f6bb
class Topic(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=100) <NEW_LINE> date_added = models.DateTimeField(auto_now_add=True) <NEW_LINE> owner = models.ForeignKey(User) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title
Basic model for a Topic Return: title (str): The title of the topic.
62598ff94c3428357761ac23
class Configure(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read_config(self, conf_name, section, option): <NEW_LINE> <INDENT> value = "" <NEW_LINE> try: <NEW_LINE> <INDENT> cf = configparser.ConfigParser() <NEW_LINE> cf.read(conf_name) <NEW_LINE> value = cf.get(section, option) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> def write_config(self, conf_name, value): <NEW_LINE> <INDENT> fp = open(conf_name, 'w') <NEW_LINE> cf = configparser.ConfigParser() <NEW_LINE> for (k, v) in value.items(): <NEW_LINE> <INDENT> cf.add_section(str(k)) <NEW_LINE> for (e, a) in v.items(): <NEW_LINE> <INDENT> cf.set(str(k), str(e), str(a)) <NEW_LINE> <DEDENT> <DEDENT> cf.write(fp) <NEW_LINE> fp.close()
读取配置文件
62598ff93cc13d1c6d4660ca
class SigningKey(Key): <NEW_LINE> <INDENT> def sign(self, data): <NEW_LINE> <INDENT> if not self.has_private(): <NEW_LINE> <INDENT> raise TypeError('Private key not available in this object') <NEW_LINE> <DEDENT> return self._sign(data) <NEW_LINE> <DEDENT> def verify(self, data, sig): <NEW_LINE> <INDENT> return self._verify(data, sig)
Base class for signing keys.
62598ff926238365f5fad4da
class ListZoneOperationsResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None) <NEW_LINE> <DEDENT> def get_NewAccessToken(self): <NEW_LINE> <INDENT> return self._output.get('NewAccessToken', None)
A ResultSet with methods tailored to the values returned by the ListZoneOperations Choreo. The ResultSet object is used to retrieve the results of a Choreo execution.
62598ff9c4546d3d9def7745
class Peaklist(object): <NEW_LINE> <INDENT> def __init__(self, infn): <NEW_LINE> <INDENT> with open(infn, "r") as infile: <NEW_LINE> <INDENT> self.firstline = infile.readline().split("\012")[0] <NEW_LINE> self.axislabels = infile.readline().split("\012")[0] <NEW_LINE> self.dataset = infile.readline().split("\012")[0] <NEW_LINE> self.sw = infile.readline().split("\012")[0] <NEW_LINE> self.sf = infile.readline().split("\012")[0] <NEW_LINE> self.datalabels = infile.readline().split("\012")[0] <NEW_LINE> self.data = [line.split("\012")[0] for line in infile] <NEW_LINE> <DEDENT> <DEDENT> def residue_dict(self, index): <NEW_LINE> <INDENT> maxres = -1 <NEW_LINE> minres = -1 <NEW_LINE> self.dict = {} <NEW_LINE> for i in range(len(self.data)): <NEW_LINE> <INDENT> line = self.data[i] <NEW_LINE> ind = XpkEntry(line, self.datalabels).fields[index + ".L"] <NEW_LINE> key = ind.split(".")[0] <NEW_LINE> res = int(key) <NEW_LINE> if maxres == -1: <NEW_LINE> <INDENT> maxres = res <NEW_LINE> <DEDENT> if minres == -1: <NEW_LINE> <INDENT> minres = res <NEW_LINE> <DEDENT> maxres = max([maxres, res]) <NEW_LINE> minres = min([minres, res]) <NEW_LINE> if str(res) in self.dict: <NEW_LINE> <INDENT> templst = self.dict[str(res)] <NEW_LINE> templst.append(line) <NEW_LINE> self.dict[str(res)] = templst <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.dict[str(res)] = [line] <NEW_LINE> <DEDENT> <DEDENT> self.dict["maxres"] = maxres <NEW_LINE> self.dict["minres"] = minres <NEW_LINE> return self.dict <NEW_LINE> <DEDENT> def write_header(self, outfn): <NEW_LINE> <INDENT> with open(outfn, "w") as outfile: <NEW_LINE> <INDENT> outfile.write(self.firstline) <NEW_LINE> outfile.write("\012") <NEW_LINE> outfile.write(self.axislabels) <NEW_LINE> outfile.write("\012") <NEW_LINE> outfile.write(self.dataset) <NEW_LINE> outfile.write("\012") <NEW_LINE> outfile.write(self.sw) <NEW_LINE> outfile.write("\012") <NEW_LINE> outfile.write(self.sf) <NEW_LINE> outfile.write("\012") <NEW_LINE> outfile.write(self.datalabels) <NEW_LINE> outfile.write("\012")
Provide access to header lines and data from a nmrview xpk file. Header file lines and file data are available as attributes. Parameters ---------- infn : str The input nmrview filename. Attributes ---------- firstline : str The first line in the header. axislabels : str The axis labels. dataset : str The label of the dataset. sw : str The sw coordinates. sf : str The sf coordinates. datalabels : str The labels of the entries. data : list File data after header lines. Examples -------- >>> from Bio.NMR.xpktools import Peaklist >>> peaklist = Peaklist('../Doc/examples/nmr/noed.xpk') >>> peaklist.firstline 'label dataset sw sf ' >>> peaklist.dataset 'test.nv' >>> peaklist.sf '{599.8230 } { 60.7860 } { 60.7860 }' >>> peaklist.datalabels ' H1.L H1.P H1.W H1.B H1.E H1.J 15N2.L 15N2.P 15N2.W 15N2.B 15N2.E 15N2.J N15.L N15.P N15.W N15.B N15.E N15.J vol int stat '
62598ff9ad47b63b2c5a81d2
class Student(): <NEW_LINE> <INDENT> def __init__(self, first_name, last_name, age): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return(self.__dict__)
class that defines studen
62598ff9c4546d3d9def7747
class User(Interface): <NEW_LINE> <INDENT> score = 1 <NEW_LINE> display_score = 2020 <NEW_LINE> @classmethod <NEW_LINE> def to_python(cls, data, **kwargs): <NEW_LINE> <INDENT> data = data.copy() <NEW_LINE> for key in ("id", "email", "username", "ip_address", "name", "geo", "data"): <NEW_LINE> <INDENT> data.setdefault(key, None) <NEW_LINE> <DEDENT> if data["geo"] is not None: <NEW_LINE> <INDENT> data["geo"] = Geo.to_python_subpath(data, ["geo"], **kwargs) <NEW_LINE> <DEDENT> return super().to_python(data, **kwargs) <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return prune_empty_keys( { "id": self.id, "email": self.email, "username": self.username, "ip_address": self.ip_address, "name": self.name, "geo": self.geo.to_json() if self.geo is not None else None, "data": self.data or None, } ) <NEW_LINE> <DEDENT> def get_api_context(self, is_public=False, platform=None): <NEW_LINE> <INDENT> return { "id": self.id, "email": self.email, "username": self.username, "ip_address": self.ip_address, "name": self.name, "data": self.data, } <NEW_LINE> <DEDENT> def get_api_meta(self, meta, is_public=False, platform=None): <NEW_LINE> <INDENT> return { "": meta.get(""), "id": meta.get("id"), "email": meta.get("email"), "username": meta.get("username"), "ip_address": meta.get("ip_address"), "name": meta.get("name"), "data": meta.get("data"), } <NEW_LINE> <DEDENT> def get_display_name(self): <NEW_LINE> <INDENT> return self.email or self.username <NEW_LINE> <DEDENT> def get_label(self): <NEW_LINE> <INDENT> return self.name or self.email or self.username or self.id or self.ip_address <NEW_LINE> <DEDENT> def to_email_html(self, event, **kwargs): <NEW_LINE> <INDENT> context = { "user_id": self.id, "user_email": self.email, "user_username": self.username, "user_ip_address": self.ip_address, "user_data": self.data, "user": self, } <NEW_LINE> return render_to_string("sentry/partial/interfaces/user_email.html", context)
An interface which describes the authenticated User for a request. You should provide **at least** either an `id` (a unique identifier for an authenticated user) or `ip_address` (their IP address). All other attributes are optional. >>> { >>> "id": "unique_id", >>> "username": "my_user", >>> "email": "foo@example.com" >>> "ip_address": "127.0.0.1", >>> "optional": "value" >>> }
62598ff9ad47b63b2c5a81d4
class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): <NEW_LINE> <INDENT> allow_reuse_address = True <NEW_LINE> _send_traceback_header = False <NEW_LINE> def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True): <NEW_LINE> <INDENT> self.logRequests = logRequests <NEW_LINE> SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) <NEW_LINE> socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) <NEW_LINE> if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'): <NEW_LINE> <INDENT> flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD) <NEW_LINE> flags |= fcntl.FD_CLOEXEC <NEW_LINE> fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
Simple XML-RPC server. Simple XML-RPC server that allows functions and a single instance to be installed to handle requests. The default implementation attempts to dispatch XML-RPC calls to the functions or instance installed in the server. Override the _dispatch method inherited from SimpleXMLRPCDispatcher to change this behavior.
62598ff94c3428357761ac2b
class GAN(nn.Module, ABC): <NEW_LINE> <INDENT> def __init__(self, res): <NEW_LINE> <INDENT> super(GAN, self).__init__() <NEW_LINE> self._res = res <NEW_LINE> <DEDENT> def most_parameters(self, recurse=True, excluded_params: list = []): <NEW_LINE> <INDENT> for name, params in self.named_parameters(recurse=recurse): <NEW_LINE> <INDENT> if name not in excluded_params: <NEW_LINE> <INDENT> yield params <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def res(self): <NEW_LINE> <INDENT> return self._res <NEW_LINE> <DEDENT> @res.setter <NEW_LINE> def res(self, new_res): <NEW_LINE> <INDENT> message = f'GAN().res cannot be changed, as {self.__class__.__name__} only permits one resolution: {self._res}.' <NEW_LINE> raise AttributeError(message) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def forward(self, x): <NEW_LINE> <INDENT> raise NotImplementedError( 'Can only call `forward` on valid subclasses.' )
Base GANs architechture for ResNet
62598ff93cc13d1c6d4660d3
class PropertyViewFilterSet(FilterSet): <NEW_LINE> <INDENT> address_line_1 = CharFilter(name="state__address_line_1", lookup_expr='contains') <NEW_LINE> analysis_state = CharFilter(method='analysis_state_filter') <NEW_LINE> identifier = CharFilter(method='identifier_filter') <NEW_LINE> cycle_start = DateFilter(name='cycle__start', lookup_expr='lte') <NEW_LINE> cycle_end = DateFilter(name='cycle__end', lookup_expr='gte') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = PropertyView <NEW_LINE> fields = ['identifier', 'address_line_1', 'cycle', 'property', 'cycle_start', 'cycle_end', 'analysis_state'] <NEW_LINE> <DEDENT> def identifier_filter(self, queryset, name, value): <NEW_LINE> <INDENT> address_line_1 = Q(state__address_line_1__icontains=value) <NEW_LINE> jurisdiction_property_id = Q(state__jurisdiction_property_id__icontains=value) <NEW_LINE> custom_id_1 = Q(state__custom_id_1__icontains=value) <NEW_LINE> pm_property_id = Q(state__pm_property_id__icontains=value) <NEW_LINE> ubid = Q(state__ubid__icontains=value) <NEW_LINE> query = ( address_line_1 | jurisdiction_property_id | custom_id_1 | pm_property_id | ubid ) <NEW_LINE> return queryset.filter(query).order_by('-state__id') <NEW_LINE> <DEDENT> def analysis_state_filter(self, queryset, name, value): <NEW_LINE> <INDENT> state_id = None <NEW_LINE> for state in PropertyState.ANALYSIS_STATE_TYPES: <NEW_LINE> <INDENT> if state[1].upper() == value.upper(): <NEW_LINE> <INDENT> state_id = state[0] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if state_id is not None: <NEW_LINE> <INDENT> return queryset.filter(Q(state__analysis_state__exact=state_id)).order_by('-state__id') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return queryset.order_by('-state__id')
Advanced filtering for PropertyView sets version 2.1.
62598ff90a366e3fb87dd377
class InvalidSwitchToTargetException(Exception): <NEW_LINE> <INDENT> def __init__(self, msg=None): <NEW_LINE> <INDENT> Exception.__init__(self, msg)
The frame or window target to be switched doesn't exist.
62598ff915fb5d323ce7f6c7
class ajax_error_wrapper(object): <NEW_LINE> <INDENT> def __init__(self, f): <NEW_LINE> <INDENT> self.f = f <NEW_LINE> <DEDENT> def __call__(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if request.method != 'POST': <NEW_LINE> <INDENT> return ajax_error('POST method must be used.') <NEW_LINE> <DEDENT> if not request.user.is_authenticated(): <NEW_LINE> <INDENT> return ajax_error('You must be logged in to do that') <NEW_LINE> <DEDENT> value = self.f(request) <NEW_LINE> return value <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> traceback.print_exc() <NEW_LINE> return ajax_error('Error: %s' % exc)
Used as decorator to trap/display errors in the ajax calls
62598ff94c3428357761ac2f
class SPFTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def _make_dummy_suspect(self, senderdomain, clientip, helo='foo.example.com'): <NEW_LINE> <INDENT> s = Suspect('sender@%s' % senderdomain, 'recipient@example.com', '/dev/null') <NEW_LINE> s.clientinfo = (helo, unicode(clientip), 'ptr.example.com') <NEW_LINE> return s <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.candidate = SPFPlugin(None) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testSPF(self): <NEW_LINE> <INDENT> suspect = self._make_dummy_suspect('gmail.com', '1.2.3.4') <NEW_LINE> self.candidate.examine(suspect) <NEW_LINE> self.assertEquals(suspect.get_tag('SPF.status'), 'softfail') <NEW_LINE> suspect = self._make_dummy_suspect('gmail.com', '216.239.32.22') <NEW_LINE> self.candidate.examine(suspect) <NEW_LINE> self.assertEquals(suspect.get_tag('SPF.status'), 'pass') <NEW_LINE> suspect = self._make_dummy_suspect('fuglu.org', '1.2.3.4') <NEW_LINE> self.candidate.examine(suspect) <NEW_LINE> self.assertEquals(suspect.get_tag('SPF.status'), 'none')
SPF Check Tests
62598ff915fb5d323ce7f6c9
class GalaxyLogin(object): <NEW_LINE> <INDENT> GITHUB_AUTH = 'https://api.github.com/authorizations' <NEW_LINE> def __init__(self, galaxy, github_token=None): <NEW_LINE> <INDENT> self.galaxy = galaxy <NEW_LINE> self.github_username = None <NEW_LINE> self.github_password = None <NEW_LINE> if github_token is None: <NEW_LINE> <INDENT> self.get_credentials() <NEW_LINE> <DEDENT> <DEDENT> def get_credentials(self): <NEW_LINE> <INDENT> display.display(u'\n\n' + "We need your " + stringc("GitHub login", 'bright cyan') + " to identify you.", screen_only=True) <NEW_LINE> display.display("This information will " + stringc("not be sent to Galaxy", 'bright cyan') + ", only to " + stringc("api.github.com.", "yellow"), screen_only=True) <NEW_LINE> display.display("The password will not be displayed." + u'\n\n', screen_only=True) <NEW_LINE> display.display("Use " + stringc("--github-token", 'yellow') + " if you do not want to enter your password." + u'\n\n', screen_only=True) <NEW_LINE> try: <NEW_LINE> <INDENT> self.github_username = input("GitHub Username: ") <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.github_password = getpass.getpass("Password for %s: " % self.github_username) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if not self.github_username or not self.github_password: <NEW_LINE> <INDENT> raise AnsibleError("Invalid GitHub credentials. Username and password are required.") <NEW_LINE> <DEDENT> <DEDENT> def remove_github_token(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tokens = json.load(open_url(self.GITHUB_AUTH, url_username=self.github_username, url_password=self.github_password, force_basic_auth=True,)) <NEW_LINE> <DEDENT> except HTTPError as e: <NEW_LINE> <INDENT> res = json.load(e) <NEW_LINE> raise AnsibleError(res['message']) <NEW_LINE> <DEDENT> for token in tokens: <NEW_LINE> <INDENT> if token['note'] == 'ansible-galaxy login': <NEW_LINE> <INDENT> display.vvvvv('removing token: %s' % token['token_last_eight']) <NEW_LINE> try: <NEW_LINE> <INDENT> open_url('https://api.github.com/authorizations/%d' % token['id'], url_username=self.github_username, url_password=self.github_password, method='DELETE', force_basic_auth=True) <NEW_LINE> <DEDENT> except HTTPError as e: <NEW_LINE> <INDENT> res = json.load(e) <NEW_LINE> raise AnsibleError(res['message']) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def create_github_token(self): <NEW_LINE> <INDENT> self.remove_github_token() <NEW_LINE> args = json.dumps({"scopes": ["public_repo"], "note": "ansible-galaxy login"}) <NEW_LINE> try: <NEW_LINE> <INDENT> data = json.load(open_url(self.GITHUB_AUTH, url_username=self.github_username, url_password=self.github_password, force_basic_auth=True, data=args)) <NEW_LINE> <DEDENT> except HTTPError as e: <NEW_LINE> <INDENT> res = json.load(e) <NEW_LINE> raise AnsibleError(res['message']) <NEW_LINE> <DEDENT> return data['token']
Class to handle authenticating user with Galaxy API prior to performing CUD operations
62598ff9ad47b63b2c5a81da
class FlowTimeout(base_tests.SimpleDataPlane): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> logging.info("Running Flow_Timeout test ") <NEW_LINE> of_ports = config["port_map"].keys() <NEW_LINE> of_ports.sort() <NEW_LINE> self.assertTrue(len(of_ports) > 1, "Not enough ports for test") <NEW_LINE> rc = delete_all_flows(self.controller) <NEW_LINE> self.assertEqual(rc, 0, "Failed to delete all flows") <NEW_LINE> logging.info("Inserting flow entry with hard_timeout set and send_flow_removed_message flag not set") <NEW_LINE> logging.info("Expecting the flow entry to delete, but no flow removed message") <NEW_LINE> pkt = simple_tcp_packet() <NEW_LINE> match3 = parse.packet_to_flow_match(pkt) <NEW_LINE> self.assertTrue(match3 is not None, "Could not generate flow match from pkt") <NEW_LINE> match3.wildcards = ofp.OFPFW_ALL-ofp.OFPFW_IN_PORT <NEW_LINE> match3.in_port = of_ports[0] <NEW_LINE> msg3 = message.flow_mod() <NEW_LINE> msg3.out_port = of_ports[2] <NEW_LINE> msg3.command = ofp.OFPFC_ADD <NEW_LINE> msg3.cookie = random.randint(0,9007199254740992) <NEW_LINE> msg3.buffer_id = 0xffffffff <NEW_LINE> msg3.hard_timeout = 1 <NEW_LINE> msg3.buffer_id = 0xffffffff <NEW_LINE> msg3.match = match3 <NEW_LINE> act3 = action.action_output() <NEW_LINE> act3.port = of_ports[1] <NEW_LINE> self.assertTrue(msg3.actions.add(act3), "could not add action") <NEW_LINE> rv = self.controller.message_send(msg3) <NEW_LINE> self.assertTrue(rv != -1, "Error installing flow mod") <NEW_LINE> self.assertEqual(do_barrier(self.controller), 0, "Barrier failed") <NEW_LINE> (response, pkt) = self.controller.poll(exp_msg=ofp.OFPT_FLOW_REMOVED, timeout=3) <NEW_LINE> self.assertTrue(response is None, 'Recieved flow removed message ') <NEW_LINE> verify_tablestats(self,expect_active=0)
Verify that Flow removed messages are generated as expected Flow removed messages being generated when flag is set, is already tested in the above tests So here, we test the vice-versa condition
62598ff926238365f5fad4e6
class ExpressRouteCircuitAuthorization(SubResource): <NEW_LINE> <INDENT> _validation = { 'etag': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'}, 'authorization_use_status': {'key': 'properties.authorizationUseStatus', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, authorization_key: Optional[str] = None, authorization_use_status: Optional[Union[str, "AuthorizationUseStatus"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ExpressRouteCircuitAuthorization, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.etag = None <NEW_LINE> self.type = None <NEW_LINE> self.authorization_key = authorization_key <NEW_LINE> self.authorization_use_status = authorization_use_status <NEW_LINE> self.provisioning_state = None
Authorization in an ExpressRouteCircuit resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Type of the resource. :vartype type: str :param authorization_key: The authorization key. :type authorization_key: str :param authorization_use_status: The authorization use status. Possible values include: "Available", "InUse". :type authorization_use_status: str or ~azure.mgmt.network.v2020_07_01.models.AuthorizationUseStatus :ivar provisioning_state: The provisioning state of the authorization resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed". :vartype provisioning_state: str or ~azure.mgmt.network.v2020_07_01.models.ProvisioningState
62598ff94c3428357761ac33
class UpdateModelMixinWithNone(object): <NEW_LINE> <INDENT> def update(self, request, *args, **kwargs): <NEW_LINE> <INDENT> serializer = self.get_serializer(self.kwargs, data=request.data, partial=False) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> return Response(serializer.save()) <NEW_LINE> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save()
Update a model instance. do not return data to response
62598ff93cc13d1c6d4660da
class PurgeUrlsCacheRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Urls = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Urls = params.get("Urls")
PurgeUrlsCache请求参数结构体
62598ff9627d3e7fe0e0782e
class dotdict(dict): <NEW_LINE> <INDENT> __getattr__ = dict.get <NEW_LINE> __setattr__ = dict.__setitem__ <NEW_LINE> __delattr__ = dict.__delitem__ <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> for key, value in dict(*args, **kwargs).items(): <NEW_LINE> <INDENT> if hasattr(value, 'keys'): value = dotdict(value) <NEW_LINE> self[key] = value
``dotdict`` wrapper class to allow dot-operator access to ``dict`` values. See: https://stackoverflow.com/a/23689767 And: https://stackoverflow.com/a/13520518
62598ff94c3428357761ac37
class Level(object): <NEW_LINE> <INDENT> wall_list = None <NEW_LINE> num_list = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.wall_list = pygame.sprite.Group() <NEW_LINE> self.num_list = pygame.sprite.Group() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.wall_list.update() <NEW_LINE> self.num_list.update() <NEW_LINE> <DEDENT> def draw(self, screen): <NEW_LINE> <INDENT> screen.fill(constants.BLACK) <NEW_LINE> self.wall_list.draw(screen) <NEW_LINE> self.num_list.draw(screen)
Each level has a set of walls, nos. and enemies
62598ff9c4546d3d9def774e
class View(Model): <NEW_LINE> <INDENT> _inherit = 'ir.ui.view' <NEW_LINE> def render(self, cr, uid, id_or_xml_id, values=None, engine='ir.qweb', context=None): <NEW_LINE> <INDENT> if values is None: <NEW_LINE> <INDENT> values = dict() <NEW_LINE> <DEDENT> if 'website' not in values: <NEW_LINE> <INDENT> w_obj = self.pool.get('website') <NEW_LINE> if w_obj: <NEW_LINE> <INDENT> current_website = w_obj.get_current_website( cr, uid, context=context) <NEW_LINE> if current_website: <NEW_LINE> <INDENT> values['website'] = current_website <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return super(View, self).render(cr, uid, id_or_xml_id, values, engine, context)
View class.
62598ff94c3428357761ac39
class SGSEmbedding(SGSBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(derivatives=EmbeddingDerivatives(), params=["weight"])
SGS extension for Embedding.
62598ff915fb5d323ce7f6d5
class HStoreDict(UnicodeMixin, dict): <NEW_LINE> <INDENT> def __init__(self, value=None, field=None, instance=None, connection=None, **params): <NEW_LINE> <INDENT> if isinstance(value, six.string_types): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = json.loads(value) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> raise exceptions.HStoreDictException( 'HStoreDict accepts only valid json formatted strings.', json_error_message=force_text(e) ) <NEW_LINE> <DEDENT> <DEDENT> elif value is None: <NEW_LINE> <INDENT> value = {} <NEW_LINE> <DEDENT> if not isinstance(value, dict): <NEW_LINE> <INDENT> raise exceptions.HStoreDictException( 'HStoreDict accepts only dictionary objects, None and json formatted string representations of json objects' ) <NEW_LINE> <DEDENT> for key, val in value.items(): <NEW_LINE> <INDENT> value[key] = self.ensure_acceptable_value(val) <NEW_LINE> <DEDENT> super(HStoreDict, self).__init__(value, **params) <NEW_LINE> self.field = field <NEW_LINE> self.instance = instance <NEW_LINE> self.connection = connection <NEW_LINE> <DEDENT> def __setitem__(self, *args, **kwargs): <NEW_LINE> <INDENT> args = (args[0], self.ensure_acceptable_value(args[1])) <NEW_LINE> super(HStoreDict, self).__setitem__(*args, **kwargs) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> if self: <NEW_LINE> <INDENT> return force_text(json.dumps(self)) <NEW_LINE> <DEDENT> return u'' <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> if self.connection: <NEW_LINE> <INDENT> d = dict(self.__dict__) <NEW_LINE> d['connection'] = None <NEW_LINE> return d <NEW_LINE> <DEDENT> return self.__dict__ <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> return self.__class__(self, self.field, self.connection) <NEW_LINE> <DEDENT> def update(self, *args, **kwargs): <NEW_LINE> <INDENT> for key, value in dict(*args, **kwargs).iteritems(): <NEW_LINE> <INDENT> self[key] = value <NEW_LINE> <DEDENT> <DEDENT> def ensure_acceptable_value(self, value): <NEW_LINE> <INDENT> if isinstance(value, bool): <NEW_LINE> <INDENT> return force_text(value).lower() <NEW_LINE> <DEDENT> elif isinstance(value, int) or isinstance(value, float): <NEW_LINE> <INDENT> return force_text(value) <NEW_LINE> <DEDENT> elif isinstance(value, list) or isinstance(value, dict): <NEW_LINE> <INDENT> return force_text(json.dumps(value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> def prepare(self, connection): <NEW_LINE> <INDENT> self.connection = connection <NEW_LINE> <DEDENT> def remove(self, keys): <NEW_LINE> <INDENT> queryset = self.instance._base_manager.get_query_set() <NEW_LINE> queryset.filter(pk=self.instance.pk).hremove(self.field.name, keys)
A dictionary subclass which implements hstore support.
62598ff94c3428357761ac3b
class Observables(entities.EntityList): <NEW_LINE> <INDENT> _binding = core_binding <NEW_LINE> _binding_class = _binding.ObservablesType <NEW_LINE> _namespace = 'http://cybox.mitre.org/cybox-2' <NEW_LINE> cybox_major_version = fields.TypedField("cybox_major_version") <NEW_LINE> cybox_minor_version = fields.TypedField("cybox_minor_version") <NEW_LINE> cybox_update_version = fields.TypedField("cybox_update_version") <NEW_LINE> observable_package_source = fields.TypedField("Observable_Package_Source", MeasureSource) <NEW_LINE> observables = fields.TypedField("Observable", Observable, multiple=True, key_name="observables") <NEW_LINE> pools = fields.TypedField("Pools", type_="cybox.core.pool.Pools") <NEW_LINE> def __init__(self, observables=None): <NEW_LINE> <INDENT> super(Observables, self).__init__(observables) <NEW_LINE> self.cybox_major_version = "2" <NEW_LINE> self.cybox_minor_version = "1" <NEW_LINE> self.cybox_update_version = "0" <NEW_LINE> <DEDENT> def add(self, object_): <NEW_LINE> <INDENT> from cybox.core.pool import Pools <NEW_LINE> if not object_: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif isinstance(object_, MeasureSource): <NEW_LINE> <INDENT> self.observable_package_source = object_ <NEW_LINE> return <NEW_LINE> <DEDENT> elif isinstance(object_, Pools): <NEW_LINE> <INDENT> self.pools = object_ <NEW_LINE> return <NEW_LINE> <DEDENT> elif not isinstance(object_, Observable): <NEW_LINE> <INDENT> object_ = Observable(object_) <NEW_LINE> <DEDENT> self.observables.append(object_)
The root CybOX Observables object.
62598ff926238365f5fad4f0
class ILayer(Interface): <NEW_LINE> <INDENT> pass
A layer specific to this product. Is registered using browserlayer.xml
62598ff9c4546d3d9def7751
class PipelinesResponse(object): <NEW_LINE> <INDENT> swagger_types = { 'items': 'list[Pipeline]', 'links': 'Links', 'meta': 'Meta' } <NEW_LINE> attribute_map = { 'items': 'items', 'links': 'links', 'meta': 'meta' } <NEW_LINE> def __init__(self, items=None, links=None, meta=None): <NEW_LINE> <INDENT> self._items = None <NEW_LINE> self._links = None <NEW_LINE> self._meta = None <NEW_LINE> self.discriminator = None <NEW_LINE> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> if links is not None: <NEW_LINE> <INDENT> self.links = links <NEW_LINE> <DEDENT> if meta is not None: <NEW_LINE> <INDENT> self.meta = meta <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def items(self): <NEW_LINE> <INDENT> return self._items <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items(self, items): <NEW_LINE> <INDENT> self._items = items <NEW_LINE> <DEDENT> @property <NEW_LINE> def links(self): <NEW_LINE> <INDENT> return self._links <NEW_LINE> <DEDENT> @links.setter <NEW_LINE> def links(self, links): <NEW_LINE> <INDENT> self._links = links <NEW_LINE> <DEDENT> @property <NEW_LINE> def meta(self): <NEW_LINE> <INDENT> return self._meta <NEW_LINE> <DEDENT> @meta.setter <NEW_LINE> def meta(self, meta): <NEW_LINE> <INDENT> self._meta = meta <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.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> if issubclass(PipelinesResponse, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PipelinesResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598ff90a366e3fb87dd38a
class ExtensionPreferences: <NEW_LINE> <INDENT> manifest = None <NEW_LINE> @classmethod <NEW_LINE> @lru_cache(maxsize=1000) <NEW_LINE> def create_instance(cls, ext_id): <NEW_LINE> <INDENT> return cls(ext_id, ExtensionManifest.open(ext_id)) <NEW_LINE> <DEDENT> def __init__(self, ext_id: str, manifest: ExtensionManifest, ext_preferences_dir: str = EXT_PREFERENCES_DIR): <NEW_LINE> <INDENT> self.db_path = os.path.join(ext_preferences_dir, '%s.db' % ext_id) <NEW_LINE> self.db = KeyValueDb[str, str](self.db_path) <NEW_LINE> self.manifest = manifest <NEW_LINE> self._db_is_open = False <NEW_LINE> <DEDENT> def get_items(self, type: str = None) -> PreferenceItems: <NEW_LINE> <INDENT> self._open_db() <NEW_LINE> items = [] <NEW_LINE> for p in self.manifest.get_preferences(): <NEW_LINE> <INDENT> if type and type != p['type']: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> default_value = p.get('default_value', '') <NEW_LINE> items.append({ 'id': p['id'], 'type': p['type'], 'name': p.get('name', ''), 'description': p.get('description', ''), 'options': p.get('options', []), 'default_value': default_value, 'user_value': self.db.find(p['id']) or '', 'value': self.db.find(p['id']) or default_value }) <NEW_LINE> <DEDENT> return items <NEW_LINE> <DEDENT> def get_dict(self) -> Dict[str, str]: <NEW_LINE> <INDENT> items = {} <NEW_LINE> for i in self.get_items(): <NEW_LINE> <INDENT> items[i['id']] = i['value'] <NEW_LINE> <DEDENT> return items <NEW_LINE> <DEDENT> def get(self, id: str) -> Optional[PreferenceItem]: <NEW_LINE> <INDENT> for i in self.get_items(): <NEW_LINE> <INDENT> if i['id'] == id: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def get_active_keywords(self) -> List[str]: <NEW_LINE> <INDENT> return [p['value'] for p in self.get_items(type='keyword') if p['value']] <NEW_LINE> <DEDENT> def set(self, id: str, value: str): <NEW_LINE> <INDENT> self.db.put(id, value) <NEW_LINE> self.db.commit() <NEW_LINE> <DEDENT> def _open_db(self): <NEW_LINE> <INDENT> if not self._db_is_open: <NEW_LINE> <INDENT> self.db.open() <NEW_LINE> self._db_is_open = True
Manages extension preferences. Stores them in pickled file in cache directory
62598ff9c4546d3d9def7753
class ProcessProtocol(protocol.ProcessProtocol): <NEW_LINE> <INDENT> def __init__(self, processName, processHandler): <NEW_LINE> <INDENT> self.processName = processName <NEW_LINE> self.processHandler = processHandler <NEW_LINE> self.stdOut = [] <NEW_LINE> self.errOut = [] <NEW_LINE> <DEDENT> def outReceived(self, data): <NEW_LINE> <INDENT> self.stdOut.append(data) <NEW_LINE> <DEDENT> def errReceived(self, data): <NEW_LINE> <INDENT> self.errOut.append(data) <NEW_LINE> <DEDENT> def processEnded(self, status): <NEW_LINE> <INDENT> if status.value.exitCode == 0: <NEW_LINE> <INDENT> self.processHandler.processCompleted(self.processName) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.processHandler.processFailed(self.processName) <NEW_LINE> <DEDENT> <DEDENT> def kill(self): <NEW_LINE> <INDENT> self.transport.signalProcess('KILL')
@summary: Protocol class for job processes
62598ff93cc13d1c6d4660e9
class Tiles: <NEW_LINE> <INDENT> def __init__(self, size, covered_colour=(255,255,255), uncovered_colour=(125,125,125), text_colour=(0,38,255), transparency=255, font = None): <NEW_LINE> <INDENT> self.font = font <NEW_LINE> self.size = size <NEW_LINE> if font == None: <NEW_LINE> <INDENT> pygame.font.init() <NEW_LINE> self.font = pygame.font.SysFont("monospace", int(self.size*0.75), bold=True) <NEW_LINE> <DEDENT> self.covered_colour = covered_colour <NEW_LINE> self.size = size <NEW_LINE> self.uncovered_colour = uncovered_colour <NEW_LINE> self.text_colour = text_colour <NEW_LINE> self.base = pygame.Surface((size,size), SRCALPHA, 32).convert_alpha() <NEW_LINE> self.base.set_alpha(transparency) <NEW_LINE> self.covered_base = self.base.copy() <NEW_LINE> self.covered_base.fill(self.covered_colour) <NEW_LINE> self.uncovered_base = self.base.copy() <NEW_LINE> self.uncovered_base.fill(uncovered_colour) <NEW_LINE> self.array = [] <NEW_LINE> for i in range(12): <NEW_LINE> <INDENT> self.array.append(self.uncovered_base.copy()) <NEW_LINE> <DEDENT> <DEDENT> def create(self): <NEW_LINE> <INDENT> for i in range(9): <NEW_LINE> <INDENT> number = self.font.render(str(i), False, self.text_colour) <NEW_LINE> self.array[i].blit(number, (self.size//4,self.size//8)) <NEW_LINE> <DEDENT> flag = self.font.render("F", False, self.text_colour) <NEW_LINE> self.array[9] = self.covered_base.copy() <NEW_LINE> self.array[9].blit(flag,(self.size//4, self.size//8)) <NEW_LINE> mine = self.font.render("M", False, (255,0,0)) <NEW_LINE> self.array[10] = self.covered_base.copy() <NEW_LINE> self.array[10].blit(mine,(self.size//4, self.size//8)) <NEW_LINE> self.array[11] = self.covered_base.copy() <NEW_LINE> <DEDENT> def get(self, type): <NEW_LINE> <INDENT> return self.array[type]
This class provides squares to blit onto the main pygame surface; there is an initial. type is an int from 0-11 where type: 0-8 correspond to tiles with numbers 0-8 on them 9 is a flagged tiles 10 is a mine 11 is an covered tile size is the dimensions of each tile in pixels covoured_colour is the colour of the coloured tiles as an RGB tuple uncovoured_colour is the colour of the uncoloured tiles as an RGB tuple text_tolour: RGB tuple for the text colour transparency: integer from 0-255 repreenting transparency of the tiles font: pygame font object
62598ffa0a366e3fb87dd394
class Actor(models.Model): <NEW_LINE> <INDENT> name = models.CharField(verbose_name="Имя", max_length=100) <NEW_LINE> age = models.PositiveSmallIntegerField(verbose_name="Возраст", default=0) <NEW_LINE> description = models.TextField(verbose_name="Описание") <NEW_LINE> image = models.ImageField(verbose_name="Изображение", upload_to="actors/") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse("actor_detail", kwargs={"slug": self.name}) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "Актёры и режиссёры" <NEW_LINE> verbose_name_plural = "Актёры и режиссёры"
Актёры и режессёры
62598ffa627d3e7fe0e07846
@logger.init('gui', 'DEBUG') <NEW_LINE> class SpreadsheetSettings(QtGui.QTabWidget): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> super(SpreadsheetSettings, self).__init__(parent) <NEW_LINE> self.addTab(ReportPane(self), "Reports") <NEW_LINE> self.addTab(ColumnPane(self), "Columns") <NEW_LINE> self.addTab(ModificationPane(self), "Modifications") <NEW_LINE> self.addTab(OtherPane(self), "Miscellanious")
Definitions for spreadsheet settings
62598ffa0a366e3fb87dd398
class ConversionMap(object): <NEW_LINE> <INDENT> def __init__(self, recursive, nocompile_decorators, partial_types): <NEW_LINE> <INDENT> self.recursive = recursive <NEW_LINE> self.nocompile_decorators = nocompile_decorators <NEW_LINE> self.partial_types = partial_types if partial_types else () <NEW_LINE> self.dependency_cache = {} <NEW_LINE> self.name_map = {} <NEW_LINE> <DEDENT> def new_namer(self, global_symbols): <NEW_LINE> <INDENT> return naming.Namer(global_symbols, self.recursive, self.name_map, self.partial_types) <NEW_LINE> <DEDENT> def update_name_map(self, namer): <NEW_LINE> <INDENT> for o, name in namer.renamed_calls.items(): <NEW_LINE> <INDENT> if o in self.name_map: <NEW_LINE> <INDENT> if self.name_map[o] != name: <NEW_LINE> <INDENT> raise ValueError( 'Calls to %s were converted using multiple names (%s). This is ' 'possible when an object with one of these names already ' 'existed. To fix, avoid using any of these names.') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.name_map[o] = name <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_to_cache(self, original_object, converted_ast): <NEW_LINE> <INDENT> self.dependency_cache[original_object] = converted_ast
ConversionMaps keep track of converting function hierarchies. Attributes: recursive: Whether to recusrively convert any functions that the decorator function may call. nocompile_decorators: tuple of decorator functions that toggle compilation off. dependency_cache: dict[object]: ast; maps original objects to their converted AST name_map: dict[string]: string; maps original objects to the name of their converted counterparts
62598ffaad47b63b2c5a81fa
class Arbol: <NEW_LINE> <INDENT> def __init__(self, contenido): <NEW_LINE> <INDENT> self.contenido = contenido <NEW_LINE> self.enlaces = [] <NEW_LINE> <DEDENT> def setenlaces(self, enlaces): <NEW_LINE> <INDENT> for enlace in enlaces: <NEW_LINE> <INDENT> if not isinstance(enlace, Arbol): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> <DEDENT> self.enlaces = enlaces
Un arbol n-ario. Sirve para representar la jerarquia de categorias de operaciones
62598ffac4546d3d9def775a
class AssignName(mixins.NoChildrenMixin, LookupMixIn, mixins.ParentAssignTypeMixin, NodeNG): <NEW_LINE> <INDENT> _other_fields = ('name',) <NEW_LINE> def __init__(self, name=None, lineno=None, col_offset=None, parent=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> super(AssignName, self).__init__(lineno, col_offset, parent)
Variation of :class:`ast.Assign` representing assignment to a name. An :class:`AssignName` is the name of something that is assigned to. This includes variables defined in a function signature or in a loop. >>> node = astroid.extract_node('variable = range(10)') >>> node <Assign l.1 at 0x7effe1db8550> >>> list(node.get_children()) [<AssignName.variable l.1 at 0x7effe1db8748>, <Call l.1 at 0x7effe1db8630>] >>> list(node.get_children())[0].as_string() 'variable'
62598ffaad47b63b2c5a81fc
class GetPseudoIPv4SettingRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v1"): <NEW_LINE> <INDENT> super(GetPseudoIPv4SettingRequest, self).__init__( '/zones/{zone_identifier}/settings$$pseudo_ipv4', 'GET', header, version) <NEW_LINE> self.parameters = parameters
获取Pseudo IPv4(IPv6到IPv4的转换服务)的设置
62598ffaad47b63b2c5a8200
class AclsFun(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def acls_auth(auth='sys'): <NEW_LINE> <INDENT> acls_info = acls(auth,debug = False) <NEW_LINE> return acls_info <NEW_LINE> <DEDENT> @click.group() <NEW_LINE> def Acls(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @click.command() <NEW_LINE> @click.option('--describe',default = None, help = "Detail of specific keypair") <NEW_LINE> def list(describe): <NEW_LINE> <INDENT> acls_info = AclsFun.acls_auth() <NEW_LINE> if not isNone(describe): <NEW_LINE> <INDENT> table_layout(' Acls Info ',acls_info.queryById(describe)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pp(show_list = acls_info.list()) <NEW_LINE> <DEDENT> <DEDENT> Acls.add_command(list)
Funciton for Acls CLI
62598ffa187af65679d2a0d0
class ln_access_to_workplace_from_residences(Variable): <NEW_LINE> <INDENT> gc_ln_access_to_workplace_from_residences = "gc_ln_access_to_workplace_from_residences" <NEW_LINE> hh_grid_id = "grid_id" <NEW_LINE> def dependencies(self): <NEW_LINE> <INDENT> return [attribute_label("gridcell", self.gc_ln_access_to_workplace_from_residences), attribute_label("household", self.hh_grid_id) ] <NEW_LINE> <DEDENT> def compute(self, dataset_pool): <NEW_LINE> <INDENT> return self.get_dataset().get_2d_dataset_attribute('gc_ln_access_to_workplace_from_residences')
(SUM(Jobs(i) * exp(logsum_DDD(i to this_zone)), for i=zone_1...zone_n), for the income type (DDD) of this house) / number_of_DDD_types Although, the above fomula is really calculated in zones and passed through gridcell to household.
62598ffa3cc13d1c6d4660ff
class GemSet: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.gems = {} <NEW_LINE> <DEDENT> def add(self, gem, count): <NEW_LINE> <INDENT> new_count = self.gems.get(gem, 0) + count <NEW_LINE> assert new_count >= 0 <NEW_LINE> self.gems[gem] = new_count <NEW_LINE> <DEDENT> def get(self, gem): <NEW_LINE> <INDENT> return self.gems.get(gem, 0) <NEW_LINE> <DEDENT> def __setitem__(self, gem, count): <NEW_LINE> <INDENT> assert count >= 0 <NEW_LINE> self.gems[gem] = count <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return self.gems.items() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = '' <NEW_LINE> for gem in GEMS: <NEW_LINE> <INDENT> if gem in self.gems: <NEW_LINE> <INDENT> count = self.get(gem) <NEW_LINE> if count > 0: <NEW_LINE> <INDENT> s += gem + str(count) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return s <NEW_LINE> <DEDENT> def shortage(self, price): <NEW_LINE> <INDENT> shortage = GemSet() <NEW_LINE> for gem, count in price.items(): <NEW_LINE> <INDENT> assert gem is not GOLD_GEM <NEW_LINE> diff = count - self.get(gem) <NEW_LINE> if diff > 0: <NEW_LINE> <INDENT> shortage.add(gem, diff) <NEW_LINE> <DEDENT> <DEDENT> return shortage <NEW_LINE> <DEDENT> def count(self): <NEW_LINE> <INDENT> total = 0 <NEW_LINE> for _, count in self.items(): <NEW_LINE> <INDENT> total += count <NEW_LINE> <DEDENT> return total
Set of gems with count (or price) each
62598ffa4c3428357761ac59
class Client: <NEW_LINE> <INDENT> def __init__(self, name, company, email, position, uid=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.company = company <NEW_LINE> self.email = email <NEW_LINE> self.position = position <NEW_LINE> self.uid = uid or uuid.uuid4() <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return vars(self) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def schema(): <NEW_LINE> <INDENT> return ['name', 'company', 'email', 'position', 'uid']
docstring for Client
62598ffa15fb5d323ce7f6f6
@admin.register(Person) <NEW_LINE> class PersonAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('name', 'email', 'responsible_for_lab') <NEW_LINE> search_fields = ('name', 'email', 'responsible_for_lab__name') <NEW_LINE> ordering = ('name', )
ModelAdmin for Person model
62598ffa187af65679d2a0d3
class IssueConfig(AppConfig): <NEW_LINE> <INDENT> name = 'issue'
config for Issue
62598ffaad47b63b2c5a8208
class Galaxy(object): <NEW_LINE> <INDENT> def __init__(self, options): <NEW_LINE> <INDENT> self.options = options <NEW_LINE> roles_path = getattr(self.options, 'roles_path', []) <NEW_LINE> self.roles_paths = roles_path <NEW_LINE> self.roles = {} <NEW_LINE> this_dir, this_filename = os.path.split(__file__) <NEW_LINE> self.DATA_PATH = os.path.join(this_dir, "data") <NEW_LINE> self._default_readme = None <NEW_LINE> self._default_meta = None <NEW_LINE> self._default_test = None <NEW_LINE> self._default_travis = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_readme(self): <NEW_LINE> <INDENT> if self._default_readme is None: <NEW_LINE> <INDENT> self._default_readme = self._str_from_data_file('readme') <NEW_LINE> <DEDENT> return self._default_readme <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_meta(self): <NEW_LINE> <INDENT> if self._default_meta is None: <NEW_LINE> <INDENT> self._default_meta = self._str_from_data_file('metadata_template.j2') <NEW_LINE> <DEDENT> return self._default_meta <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_test(self): <NEW_LINE> <INDENT> if self._default_test is None: <NEW_LINE> <INDENT> self._default_test = self._str_from_data_file('test_playbook.j2') <NEW_LINE> <DEDENT> return self._default_test <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_travis(self): <NEW_LINE> <INDENT> if self._default_travis is None: <NEW_LINE> <INDENT> self._default_travis = self._str_from_data_file('travis.j2') <NEW_LINE> <DEDENT> return self._default_travis <NEW_LINE> <DEDENT> def add_role(self, role): <NEW_LINE> <INDENT> self.roles[role.name] = role <NEW_LINE> <DEDENT> def remove_role(self, role_name): <NEW_LINE> <INDENT> del self.roles[role_name] <NEW_LINE> <DEDENT> def _str_from_data_file(self, filename): <NEW_LINE> <INDENT> myfile = os.path.join(self.DATA_PATH, filename) <NEW_LINE> try: <NEW_LINE> <INDENT> return open(myfile).read() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise AnsibleError("Could not open %s: %s" % (filename, str(e)))
Keeps global galaxy info
62598ffa4c3428357761ac5f
class BaseViewTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(BaseViewTests, self).setUp() <NEW_LINE> self._real_render_to_response = shortcuts.render_to_response <NEW_LINE> shortcuts.render_to_response = fake_render_to_response <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(BaseViewTests, self).tearDown() <NEW_LINE> shortcuts.render_to_response = self._real_render_to_response <NEW_LINE> <DEDENT> def assertRedirectsNoFollow(self, response, expected_url): <NEW_LINE> <INDENT> self.assertEqual(response._headers['location'], ('Location', settings.TESTSERVER + expected_url)) <NEW_LINE> self.assertEqual(response.status_code, 302)
Base class for view based unit tests.
62598ffaad47b63b2c5a820a
class FileManager: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read_file(filename): <NEW_LINE> <INDENT> file = open(filename, 'r') <NEW_LINE> lines = file.readlines() <NEW_LINE> file.close() <NEW_LINE> return lines <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_dir(filename): <NEW_LINE> <INDENT> os.mkdir(filename) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def open_file(filename): <NEW_LINE> <INDENT> return open(filename, 'wb') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def angle_view(ant_name_image): <NEW_LINE> <INDENT> if "dorsal" in ant_name_image: <NEW_LINE> <INDENT> return "dorsal" <NEW_LINE> <DEDENT> elif "head" in ant_name_image: <NEW_LINE> <INDENT> return "head" <NEW_LINE> <DEDENT> elif "profile" in ant_name_image: <NEW_LINE> <INDENT> return "profile" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "error" <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def find_next_number(filename, name_species, view_angle): <NEW_LINE> <INDENT> find = False <NEW_LINE> i = 0 <NEW_LINE> while not find: <NEW_LINE> <INDENT> if path.exists(filename + "/" + name_species + "/" + view_angle + "/" + str(i) + ".jpg"): <NEW_LINE> <INDENT> i = +1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def dir_exist(filename): <NEW_LINE> <INDENT> return path.isdir(filename)
This class allows to manage the files part of the part with some static method. Cette classe permet de gérer les fichiers du projet avec quelques methodes statique. Author: Kierian Tirlemont
62598ffa0a366e3fb87dd3aa