sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def write(self, out): """Used in constructing an outgoing packet""" out.write_short(self.priority) out.write_short(self.weight) out.write_short(self.port) out.write_name(self.server)
Used in constructing an outgoing packet
entailment
def read_header(self): """Reads header portion of packet""" format = '!HHHHHH' length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length self.id = info[0] self.flags = info[1] ...
Reads header portion of packet
entailment
def read_questions(self): """Reads questions section of packet""" format = '!HH' length = struct.calcsize(format) for i in range(0, self.num_questions): name = self.read_name() info = struct.unpack(format, self.data[self.offset:self.offset + le...
Reads questions section of packet
entailment
def read_int(self): """Reads an integer from the packet""" format = '!I' length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length return info[0]
Reads an integer from the packet
entailment
def read_character_string(self): """Reads a character string from the packet""" length = ord(self.data[self.offset]) self.offset += 1 return self.read_string(length)
Reads a character string from the packet
entailment
def read_string(self, len): """Reads a string of a given length from the packet""" format = '!' + str(len) + 's' length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length return info[0]
Reads a string of a given length from the packet
entailment
def read_others(self): """Reads the answers, authorities and additionals section of the packet""" format = '!HHiH' length = struct.calcsize(format) n = self.num_answers + self.num_authorities + self.num_additionals for i in range(0, n): domain = self.read_name...
Reads the answers, authorities and additionals section of the packet
entailment
def read_utf(self, offset, len): """Reads a UTF-8 string of a given length from the packet""" try: result = self.data[offset:offset + len].decode('utf-8') except UnicodeDecodeError: result = str('') return result
Reads a UTF-8 string of a given length from the packet
entailment
def read_name(self): """Reads a domain name from the packet""" result = '' off = self.offset next = -1 first = off while 1: len = ord(self.data[off]) off += 1 if len == 0: break t = len & 0xC0 if...
Reads a domain name from the packet
entailment
def add_answer(self, inp, record): """Adds an answer""" if not record.suppressed_by(inp): self.add_answer_at_time(record, 0)
Adds an answer
entailment
def add_answer_at_time(self, record, now): """Adds an answer if if does not expire by a certain time""" if record is not None: if now == 0 or not record.is_expired(now): self.answers.append((record, now)) if record.rrsig is not None: self.a...
Adds an answer if if does not expire by a certain time
entailment
def write_byte(self, value): """Writes a single byte to the packet""" format = '!B' self.data.append(struct.pack(format, value)) self.size += 1
Writes a single byte to the packet
entailment
def insert_short(self, index, value): """Inserts an unsigned short in a certain position in the packet""" format = '!H' self.data.insert(index, struct.pack(format, value)) self.size += 2
Inserts an unsigned short in a certain position in the packet
entailment
def write_int(self, value): """Writes an unsigned integer to the packet""" format = '!I' self.data.append(struct.pack(format, int(value))) self.size += 4
Writes an unsigned integer to the packet
entailment
def write_string(self, value, length): """Writes a string to the packet""" format = '!' + str(length) + 's' self.data.append(struct.pack(format, value)) self.size += length
Writes a string to the packet
entailment
def write_utf(self, s): """Writes a UTF-8 string of a given length to the packet""" utfstr = s.encode('utf-8') length = len(utfstr) if length > 64: raise NamePartTooLongException self.write_byte(length) self.write_string(utfstr, length)
Writes a UTF-8 string of a given length to the packet
entailment
def write_name(self, name): """Writes a domain name to the packet""" try: # Find existing instance of this name in packet # index = self.names[name] except KeyError: # No record of this name already, so write it # out as normal, record...
Writes a domain name to the packet
entailment
def write_question(self, question): """Writes a question to the packet""" self.write_name(question.name) self.write_short(question.type) self.write_short(question.clazz)
Writes a question to the packet
entailment
def write_record(self, record, now): """Writes a record (answer, authoritative answer, additional) to the packet""" self.write_name(record.name) self.write_short(record.type) if record.unique and self.multicast: self.write_short(record.clazz | _CLASS_UNIQUE) e...
Writes a record (answer, authoritative answer, additional) to the packet
entailment
def packet(self): """Returns a string containing the packet's bytes No further parts should be added to the packet once this is done.""" if not self.finished: self.finished = 1 for question in self.questions: self.write_question(question) ...
Returns a string containing the packet's bytes No further parts should be added to the packet once this is done.
entailment
def add(self, entry): """Adds an entry""" if self.get(entry) is not None: return try: list = self.cache[entry.key] except: list = self.cache[entry.key] = [] list.append(entry)
Adds an entry
entailment
def sign(self, entry, signer=None): """Adds and sign an entry""" if (self.get(entry) is not None): return if (entry.rrsig is None) and (self.private is not None): entry.rrsig = DNSSignatureS(entry.name, _TYPE_RRSIG, _CLASS_IN, entry, self.private, sign...
Adds and sign an entry
entailment
def remove(self, entry): """Removes an entry""" try: list = self.cache[entry.key] list.remove(entry) except: pass
Removes an entry
entailment
def get(self, entry): """Gets an entry by key. Will return None if there is no matching entry.""" try: list = self.cache[entry.key] return list[list.index(entry)] except: return None
Gets an entry by key. Will return None if there is no matching entry.
entailment
def get_by_details(self, name, type, clazz): """Gets an entry by details. Will return None if there is no matching entry.""" entry = DNSEntry(name, type, clazz) return self.get(entry)
Gets an entry by details. Will return None if there is no matching entry.
entailment
def entries(self): """Returns a list of all entries""" def add(x, y): return x + y try: return reduce(add, list(self.cache.values())) except: return []
Returns a list of all entries
entailment
def update_record(self, zeroconf, now, record): """Callback invoked by Zeroconf when new information arrives. Updates information required by browser in the Zeroconf cache.""" if record.type == _TYPE_PTR and record.name == self.type: expired = record.is_expired(now) try:...
Callback invoked by Zeroconf when new information arrives. Updates information required by browser in the Zeroconf cache.
entailment
def set_properties(self, properties): """Sets properties and text of this info from a dictionary""" if isinstance(properties, dict): self.properties = properties self.sync_properties() else: self.text = properties
Sets properties and text of this info from a dictionary
entailment
def set_text(self, text): """Sets properties and text given a text field""" self.text = text try: self.properties = text_to_dict(text) except: traceback.print_exc() self.properties = None
Sets properties and text given a text field
entailment
def get_name(self): """Name accessor""" if self.type is not None and self.name.endswith("." + self.type): return self.name[:len(self.name) - len(self.type) - 1] return self.name
Name accessor
entailment
def update_record(self, zeroconf, now, record): """Updates service information from a DNS record""" if record is not None and not record.is_expired(now): if record.type == _TYPE_A: if record.name == self.name: if not record.address in self.address: ...
Updates service information from a DNS record
entailment
def request(self, zeroconf, timeout): """Returns true if the service could be discovered on the network, and updates this object with details discovered. """ now = current_time_millis() delay = _LISTENER_TIME next = now + delay last = now + timeout result ...
Returns true if the service could be discovered on the network, and updates this object with details discovered.
entailment
def wait(self, timeout): """Calling thread waits for a given number of milliseconds or until notified.""" self.condition.acquire() self.condition.wait(timeout // 1000) self.condition.release()
Calling thread waits for a given number of milliseconds or until notified.
entailment
def notify_all(self): """Notifies all waiting threads""" self.condition.acquire() # python 3.x try: self.condition.notify_all() except: self.condition.notifyAll() self.condition.release()
Notifies all waiting threads
entailment
def get_service_info(self, type, name, timeout=3000): """Returns network's service information for a particular name and type, or None if no service matches by the timeout, which defaults to 3 seconds.""" info = ServiceInfo(type, name) if info.request(self, timeout): ...
Returns network's service information for a particular name and type, or None if no service matches by the timeout, which defaults to 3 seconds.
entailment
def add_serviceListener(self, type, listener): """Adds a listener for a particular service type. This object will then have its update_record method called when information arrives for that type.""" self.remove_service_listener(listener) self.browsers.append(ServiceBrowser(self,...
Adds a listener for a particular service type. This object will then have its update_record method called when information arrives for that type.
entailment
def remove_service_listener(self, listener): """Removes a listener from the set that is currently listening.""" for browser in self.browsers: if browser.listener == listener: browser.cancel() del(browser)
Removes a listener from the set that is currently listening.
entailment
def register_service(self, info): """Registers service information to the network with a default TTL of 60 seconds. Zeroconf will then respond to requests for information for that service. The name of the service may be changed if needed to make it unique on the network.""" sel...
Registers service information to the network with a default TTL of 60 seconds. Zeroconf will then respond to requests for information for that service. The name of the service may be changed if needed to make it unique on the network.
entailment
def unregister_service(self, info): """Unregister a service.""" try: del(self.services[info.name.lower()]) except: pass now = current_time_millis() next_time = now i = 0 while i < 3: if now < next_time: self.wait...
Unregister a service.
entailment
def check_service(self, info): """Checks the network for a unique service name, modifying the ServiceInfo passed in if it is not unique.""" now = current_time_millis() next_time = now i = 0 while i < 3: for record in self.cache.entries_with_name(info.type): ...
Checks the network for a unique service name, modifying the ServiceInfo passed in if it is not unique.
entailment
def add_listener(self, listener, question): """Adds a listener for a given question. The listener will have its update_record method called when information is available to answer the question.""" now = current_time_millis() self.listeners.append(listener) if question is...
Adds a listener for a given question. The listener will have its update_record method called when information is available to answer the question.
entailment
def update_record(self, now, rec): """Used to notify listeners of new information that has updated a record.""" for listener in self.listeners: listener.update_record(self, now, rec) self.notify_all()
Used to notify listeners of new information that has updated a record.
entailment
def handle_response(self, msg, address): """Deal with incoming response packets. All answers are held in the cache, and listeners are notified.""" now = current_time_millis() sigs = [] precache = [] for record in msg.answers: if isinstance(record, DNSSignat...
Deal with incoming response packets. All answers are held in the cache, and listeners are notified.
entailment
def handle_query(self, msg, addr, port, orig): """ Deal with incoming query packets. Provides a response if possible. msg - message to process addr - dst addr port - dst port orig - originating address (for adaptive records) """ out =...
Deal with incoming query packets. Provides a response if possible. msg - message to process addr - dst addr port - dst port orig - originating address (for adaptive records)
entailment
def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT): """Sends an outgoing packet.""" # This is a quick test to see if we can parse the packets we generate #temp = DNSIncoming(out.packet()) for i in self.intf.values(): try: return i.sendto(out.packet(), 0, (a...
Sends an outgoing packet.
entailment
def close(self): """Ends the background threads, and prevent this instance from servicing further queries.""" if globals()['_GLOBAL_DONE'] == 0: globals()['_GLOBAL_DONE'] = 1 self.notify_all() self.engine.notify() self.unregister_all_services() ...
Ends the background threads, and prevent this instance from servicing further queries.
entailment
def execute(self, identity_records: 'RDD', old_state_rdd: Optional['RDD'] = None) -> 'RDD': """ Executes Blurr BTS with the given records. old_state_rdd can be provided to load an older state from a previous run. :param identity_records: RDD of the form Tuple[Identity, List[TimeAndRecor...
Executes Blurr BTS with the given records. old_state_rdd can be provided to load an older state from a previous run. :param identity_records: RDD of the form Tuple[Identity, List[TimeAndRecord]] :param old_state_rdd: A previous streaming BTS state RDD as Tuple[Identity, Streaming BTS ...
entailment
def get_record_rdd_from_json_files(self, json_files: List[str], data_processor: DataProcessor = SimpleJsonDataProcessor(), spark_session: Optional['SparkSession'] = None) -> 'RDD': """ Re...
Reads the data from the given json_files path and converts them into the `Record`s format for processing. `data_processor` is used to process the per event data in those files to convert them into `Record`. :param json_files: List of json file paths. Regular Spark path wildcards are accepted. ...
entailment
def get_record_rdd_from_rdd( self, rdd: 'RDD', data_processor: DataProcessor = SimpleDictionaryDataProcessor(), ) -> 'RDD': """ Converts a RDD of raw events into the `Record`s format for processing. `data_processor` is used to process the per row data to c...
Converts a RDD of raw events into the `Record`s format for processing. `data_processor` is used to process the per row data to convert them into `Record`. :param rdd: RDD containing the raw events. :param data_processor: `DataProcessor` to process each row in the given `rdd`. :return: R...
entailment
def write_output_file(self, path: str, per_identity_data: 'RDD', spark_session: Optional['SparkSession'] = None) -> None: """ Basic helper function to persist data to disk. If window BTS was provided then the window B...
Basic helper function to persist data to disk. If window BTS was provided then the window BTS output to written in csv format, otherwise, the streaming BTS output is written in JSON format to the `path` provided :param path: Path where the output should be written. :param per_identity_...
entailment
def print_output(self, per_identity_data: 'RDD') -> None: """ Basic helper function to write data to stdout. If window BTS was provided then the window BTS output is written, otherwise, the streaming BTS output is written to stdout. WARNING - For large datasets this will be extremely sl...
Basic helper function to write data to stdout. If window BTS was provided then the window BTS output is written, otherwise, the streaming BTS output is written to stdout. WARNING - For large datasets this will be extremely slow. :param per_identity_data: Output of the `execute()` call.
entailment
def find_executable(executable, path=None): """ As distutils.spawn.find_executable, but on Windows, look up every extension declared in PATHEXT instead of just `.exe` """ if sys.platform != 'win32': return distutils.spawn.find_executable(executable, path) if path is None: path =...
As distutils.spawn.find_executable, but on Windows, look up every extension declared in PATHEXT instead of just `.exe`
entailment
def create_environment_dict(overrides): """ Create and return a copy of os.environ with the specified overrides """ result = os.environ.copy() result.update(overrides or {}) return result
Create and return a copy of os.environ with the specified overrides
entailment
def get(self, server): """ Retrieve credentials for `server`. If no credentials are found, a `StoreError` will be raised. """ if not isinstance(server, six.binary_type): server = server.encode('utf-8') data = self._execute('get', server) result = json.load...
Retrieve credentials for `server`. If no credentials are found, a `StoreError` will be raised.
entailment
def store(self, server, username, secret): """ Store credentials for `server`. Raises a `StoreError` if an error occurs. """ data_input = json.dumps({ 'ServerURL': server, 'Username': username, 'Secret': secret }).encode('utf-8') re...
Store credentials for `server`. Raises a `StoreError` if an error occurs.
entailment
def erase(self, server): """ Erase credentials for `server`. Raises a `StoreError` if an error occurs. """ if not isinstance(server, six.binary_type): server = server.encode('utf-8') self._execute('erase', server)
Erase credentials for `server`. Raises a `StoreError` if an error occurs.
entailment
def get_identity(self, record: Record) -> str: """ Evaluates and returns the identity as specified in the schema. :param record: Record which is used to determine the identity. :return: The evaluated identity :raises: IdentityError if identity cannot be determined. """ ...
Evaluates and returns the identity as specified in the schema. :param record: Record which is used to determine the identity. :return: The evaluated identity :raises: IdentityError if identity cannot be determined.
entailment
def run_evaluate(self, record: Record): """ Evaluates and updates data in the StreamingTransformer. :param record: The 'source' record used for the update. :raises: IdentityError if identity is different from the one used during initialization. """ record_identity...
Evaluates and updates data in the StreamingTransformer. :param record: The 'source' record used for the update. :raises: IdentityError if identity is different from the one used during initialization.
entailment
def extend_schema_spec(self) -> None: """ Injects the identity field """ super().extend_schema_spec() identity_field = { 'Name': '_identity', 'Type': BtsType.STRING, 'Value': 'identity', ATTRIBUTE_INTERNAL: True } if self.ATTRIBUT...
Injects the identity field
entailment
def _persist(self) -> None: """ Persists the current data group """ if self._store: self._store.save(self._key, self._snapshot)
Persists the current data group
entailment
def add_schema_spec(self, spec: Dict[str, Any], fully_qualified_parent_name: str = None) -> Optional[str]: """ Add a schema dictionary to the schema loader. The given schema is stored against fully_qualified_parent_name + ITEM_SEPARATOR('.') + schema.name. :param ...
Add a schema dictionary to the schema loader. The given schema is stored against fully_qualified_parent_name + ITEM_SEPARATOR('.') + schema.name. :param spec: Schema specification. :param fully_qualified_parent_name: Full qualified name of the parent. If None is passed then the schema is...
entailment
def add_errors(self, *errors: Union[BaseSchemaError, SchemaErrorCollection]) -> None: """ Adds errors to the error store for the schema """ for error in errors: self._error_cache.add(error)
Adds errors to the error store for the schema
entailment
def get_schema_object(self, fully_qualified_name: str) -> 'BaseSchema': """ Used to generate a schema object from the given fully_qualified_name. :param fully_qualified_name: The fully qualified name of the object needed. :return: An initialized schema object """ if full...
Used to generate a schema object from the given fully_qualified_name. :param fully_qualified_name: The fully qualified name of the object needed. :return: An initialized schema object
entailment
def get_store(self, fully_qualified_name: str) -> Optional['Store']: """ Used to generate a store object from the given fully_qualified_name. :param fully_qualified_name: The fully qualified name of the store object needed. :return: An initialized store object """ if ful...
Used to generate a store object from the given fully_qualified_name. :param fully_qualified_name: The fully qualified name of the store object needed. :return: An initialized store object
entailment
def get_nested_schema_object(self, fully_qualified_parent_name: str, nested_item_name: str) -> Optional['BaseSchema']: """ Used to generate a schema object from the given fully_qualified_parent_name and the nested_item_name. :param fully_qualified_parent_...
Used to generate a schema object from the given fully_qualified_parent_name and the nested_item_name. :param fully_qualified_parent_name: The fully qualified name of the parent. :param nested_item_name: The nested item name. :return: An initialized schema object of the nested item.
entailment
def get_fully_qualified_name(fully_qualified_parent_name: str, nested_item_name: str) -> str: """ Returns the fully qualified name by combining the fully_qualified_parent_name and nested_item_name. :param fully_qualified_parent_name: The fully qualified name of the parent. :param...
Returns the fully qualified name by combining the fully_qualified_parent_name and nested_item_name. :param fully_qualified_parent_name: The fully qualified name of the parent. :param nested_item_name: The nested item name. :return: The fully qualified name of the nested item.
entailment
def get_schema_spec(self, fully_qualified_name: str) -> Dict[str, Any]: """ Used to retrieve the specifications of the schema from the given fully_qualified_name of schema. :param fully_qualified_name: The fully qualified name of the schema needed. :return: Schema dictionary. ...
Used to retrieve the specifications of the schema from the given fully_qualified_name of schema. :param fully_qualified_name: The fully qualified name of the schema needed. :return: Schema dictionary.
entailment
def get_schema_specs_of_type(self, *schema_types: Type) -> Dict[str, Dict[str, Any]]: """ Returns a list of fully qualified names and schema dictionary tuples for the schema types provided. :param schema_types: Schema types. :return: List of fully qualified names and schema dicti...
Returns a list of fully qualified names and schema dictionary tuples for the schema types provided. :param schema_types: Schema types. :return: List of fully qualified names and schema dictionary tuples.
entailment
def global_add(self, key: str, value: Any) -> None: """ Adds a key and value to the global dictionary """ self.global_context[key] = value
Adds a key and value to the global dictionary
entailment
def merge(self, evaluation_context: 'EvaluationContext') -> None: """ Merges the provided evaluation context to the current evaluation context. :param evaluation_context: Evaluation context to merge. """ self.global_context.merge(evaluation_context.global_context) self.lo...
Merges the provided evaluation context to the current evaluation context. :param evaluation_context: Evaluation context to merge.
entailment
def evaluate(self, evaluation_context: EvaluationContext) -> Any: """ Evaluates the expression with the context provided. If the execution results in failure, an ExpressionEvaluationException encapsulating the underlying exception is raised. :param evaluation_context: Global and...
Evaluates the expression with the context provided. If the execution results in failure, an ExpressionEvaluationException encapsulating the underlying exception is raised. :param evaluation_context: Global and local context dictionary to be passed for evaluation
entailment
def _copy_files(source, target): """ Copy all the files in source directory to target. Ignores subdirectories. """ source_files = listdir(source) if not exists(target): makedirs(target) for filename in source_files: full_filename = join(source, filename) if isfile(fu...
Copy all the files in source directory to target. Ignores subdirectories.
entailment
def create_copy(self): """ Initialises a temporary directory structure and copy of MAGICC configuration files and binary. """ if self.executable is None or not isfile(self.executable): raise FileNotFoundError( "Could not find MAGICC{} executable: {}".f...
Initialises a temporary directory structure and copy of MAGICC configuration files and binary.
entailment
def run(self, scenario=None, only=None, **kwargs): """ Run MAGICC and parse the output. As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its parameters into ``out/PARAMETERS.OUT`` and they will then be read into ``output.metadata["parameters"]`` where `...
Run MAGICC and parse the output. As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its parameters into ``out/PARAMETERS.OUT`` and they will then be read into ``output.metadata["parameters"]`` where ``output`` is the returned object. Parameters ---------...
entailment
def check_config(self): """Check that our MAGICC ``.CFG`` files are set to safely work with PYMAGICC For further detail about why this is required, please see :ref:`MAGICC flags`. Raises ------ ValueError If we are not certain that the config written by PYMAGICC wil...
Check that our MAGICC ``.CFG`` files are set to safely work with PYMAGICC For further detail about why this is required, please see :ref:`MAGICC flags`. Raises ------ ValueError If we are not certain that the config written by PYMAGICC will overwrite all other c...
entailment
def write(self, mdata, name): """Write an input file to disk Parameters ---------- mdata : :obj:`pymagicc.io.MAGICCData` A MAGICCData instance with the data to write name : str The name of the file to write. The file will be written to the MAGICC ...
Write an input file to disk Parameters ---------- mdata : :obj:`pymagicc.io.MAGICCData` A MAGICCData instance with the data to write name : str The name of the file to write. The file will be written to the MAGICC instance's run directory i.e. ``self...
entailment
def read_parameters(self): """ Read a parameters.out file Returns ------- dict A dictionary containing all the configuration used by MAGICC """ param_fname = join(self.out_dir, "PARAMETERS.OUT") if not exists(param_fname): raise F...
Read a parameters.out file Returns ------- dict A dictionary containing all the configuration used by MAGICC
entailment
def remove_temp_copy(self): """ Removes a temporary copy of the MAGICC version shipped with Pymagicc. """ if self.is_temp and self.root_dir is not None: shutil.rmtree(self.root_dir) self.root_dir = None
Removes a temporary copy of the MAGICC version shipped with Pymagicc.
entailment
def set_config( self, filename="MAGTUNE_PYMAGICC.CFG", top_level_key="nml_allcfgs", **kwargs ): """ Create a configuration file for MAGICC. Writes a fortran namelist in run_dir. Parameters ---------- filename : str Name of configuration file to w...
Create a configuration file for MAGICC. Writes a fortran namelist in run_dir. Parameters ---------- filename : str Name of configuration file to write top_level_key : str Name of namelist to be written in the configuration file kwar...
entailment
def update_config( self, filename="MAGTUNE_PYMAGICC.CFG", top_level_key="nml_allcfgs", **kwargs ): """Updates a configuration file for MAGICC Updates the contents of a fortran namelist in the run directory, creating a new namelist if none exists. Parameters --------...
Updates a configuration file for MAGICC Updates the contents of a fortran namelist in the run directory, creating a new namelist if none exists. Parameters ---------- filename : str Name of configuration file to write top_level_key : str Name of...
entailment
def set_zero_config(self): """Set config such that radiative forcing and temperature output will be zero This method is intended as a convenience only, it does not handle everything in an obvious way. Adjusting the parameter settings still requires great care and may behave unepexctedly...
Set config such that radiative forcing and temperature output will be zero This method is intended as a convenience only, it does not handle everything in an obvious way. Adjusting the parameter settings still requires great care and may behave unepexctedly.
entailment
def set_years(self, startyear=1765, endyear=2100): """ Set the start and end dates of the simulations. Parameters ---------- startyear : int Start year of the simulation endyear : int End year of the simulation Returns ------- ...
Set the start and end dates of the simulations. Parameters ---------- startyear : int Start year of the simulation endyear : int End year of the simulation Returns ------- dict The contents of the namelist
entailment
def set_output_variables(self, write_ascii=True, write_binary=False, **kwargs): """Set the output configuration, minimising output as much as possible There are a number of configuration parameters which control which variables are written to file and in which format. Limiting the variables tha...
Set the output configuration, minimising output as much as possible There are a number of configuration parameters which control which variables are written to file and in which format. Limiting the variables that are written to file can greatly speed up the running of MAGICC. By default, ...
entailment
def diagnose_tcr_ecs(self, **kwargs): """Diagnose TCR and ECS The transient climate response (TCR), is the global-mean temperature response at time at which atmopsheric |CO2| concentrations double in a scenario where atmospheric |CO2| concentrations are increased at 1% per year from ...
Diagnose TCR and ECS The transient climate response (TCR), is the global-mean temperature response at time at which atmopsheric |CO2| concentrations double in a scenario where atmospheric |CO2| concentrations are increased at 1% per year from pre-industrial levels. The equilibr...
entailment
def set_emission_scenario_setup(self, scenario, config_dict): """Set the emissions flags correctly. Parameters ---------- scenario : :obj:`pymagicc.io.MAGICCData` Scenario to run. config_dict : dict Dictionary with current input configurations which is t...
Set the emissions flags correctly. Parameters ---------- scenario : :obj:`pymagicc.io.MAGICCData` Scenario to run. config_dict : dict Dictionary with current input configurations which is to be validated and updated where necessary. Returns ...
entailment
def contains(value: Union[str, 'Type']) -> bool: """ Checks if a type is defined """ if isinstance(value, str): return any(value.lower() == i.value for i in Type) return any(value == i for i in Type)
Checks if a type is defined
entailment
def xml_replace(filename, **replacements): """Read the content of an XML template file (XMLT), apply the given `replacements` to its substitution markers, and write the result into an XML file with the same name but ending with `xml` instead of `xmlt`. First, we write an XMLT file, containing a regula...
Read the content of an XML template file (XMLT), apply the given `replacements` to its substitution markers, and write the result into an XML file with the same name but ending with `xml` instead of `xmlt`. First, we write an XMLT file, containing a regular HTML comment, a readily defined element `e1`...
entailment
def _calcidxs(func): """Return the required indexes based on the given lambda function and the |Timegrids| object handled by module |pub|. Raise a |RuntimeError| if the latter is not available. """ timegrids = hydpy.pub.get('timegrids') if timegrids is None: ...
Return the required indexes based on the given lambda function and the |Timegrids| object handled by module |pub|. Raise a |RuntimeError| if the latter is not available.
entailment
def dayofyear(self): """Day of the year index (the first of January = 0...). For reasons of consistency between leap years and non-leap years, assuming a daily time step, index 59 is always associated with the 29th of February. Hence, it is missing in non-leap years: >>> from ...
Day of the year index (the first of January = 0...). For reasons of consistency between leap years and non-leap years, assuming a daily time step, index 59 is always associated with the 29th of February. Hence, it is missing in non-leap years: >>> from hydpy import pub >>> fro...
entailment
def timeofyear(self): """Time of the year index (first simulation step of each year = 0...). The property |Indexer.timeofyear| is best explained through comparing it with property |Indexer.dayofyear|: Let us reconsider one of the examples of the documentation on property |Index...
Time of the year index (first simulation step of each year = 0...). The property |Indexer.timeofyear| is best explained through comparing it with property |Indexer.dayofyear|: Let us reconsider one of the examples of the documentation on property |Indexer.dayofyear|: >>> from ...
entailment
def set_doc(self, doc: str): """Assign the given docstring to the property instance and, if possible, to the `__test__` dictionary of the module of its owner class.""" self.__doc__ = doc if hasattr(self, 'module'): ref = f'{self.objtype.__name__}.{self.name}' ...
Assign the given docstring to the property instance and, if possible, to the `__test__` dictionary of the module of its owner class.
entailment
def getter_(self, fget) -> 'BaseProperty': """Add the given getter function and its docstring to the property and return it.""" self.fget = fget self.set_doc(fget.__doc__) return self
Add the given getter function and its docstring to the property and return it.
entailment
def isready(self, obj) -> bool: """Return |True| or |False| to indicate if the protected property is ready for the given object. If the object is unknow, |ProtectedProperty| returns |False|.""" return vars(obj).get(self.name, False)
Return |True| or |False| to indicate if the protected property is ready for the given object. If the object is unknow, |ProtectedProperty| returns |False|.
entailment
def allready(self, obj) -> bool: """Return |True| or |False| to indicate whether all protected properties are ready or not.""" for prop in self.__properties: if not prop.isready(obj): return False return True
Return |True| or |False| to indicate whether all protected properties are ready or not.
entailment
def call_fget(self, obj) -> Any: """Return the predefined custom value when available, otherwise, the value defined by the getter function.""" custom = vars(obj).get(self.name) if custom is None: return self.fget(obj) return custom
Return the predefined custom value when available, otherwise, the value defined by the getter function.
entailment
def call_fset(self, obj, value) -> None: """Store the given custom value and call the setter function.""" vars(obj)[self.name] = self.fset(obj, value)
Store the given custom value and call the setter function.
entailment
def call_fdel(self, obj) -> None: """Remove the predefined custom value and call the delete function.""" self.fdel(obj) try: del vars(obj)[self.name] except KeyError: pass
Remove the predefined custom value and call the delete function.
entailment
def trim(self, lower=None, upper=None): """Trim upper values in accordance with :math:`RelWB \\leq RelWZ`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(3) >>> lnk(ACKER) >>> relwb.values = 0.5 >>> relwz(0.2, 0.5, 0.8) >>> relwz ...
Trim upper values in accordance with :math:`RelWB \\leq RelWZ`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(3) >>> lnk(ACKER) >>> relwb.values = 0.5 >>> relwz(0.2, 0.5, 0.8) >>> relwz relwz(0.5, 0.5, 0.8)
entailment
def trim(self, lower=None, upper=None): """Trim upper values in accordance with :math:`RelWB \\leq RelWZ`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(3) >>> lnk(ACKER) >>> relwz.values = 0.5 >>> relwb(0.2, 0.5, 0.8) >>> relwb ...
Trim upper values in accordance with :math:`RelWB \\leq RelWZ`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(3) >>> lnk(ACKER) >>> relwz.values = 0.5 >>> relwb(0.2, 0.5, 0.8) >>> relwb relwb(0.2, 0.5, 0.5)
entailment
def trim(self, lower=None, upper=None): """Trim upper values in accordance with :math:`EQI1 \\leq EQB`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqi1.value = 2.0 >>> eqb(1.0) >>> eqb eqb(2.0) >>> eqb(2.0) >>> eqb eq...
Trim upper values in accordance with :math:`EQI1 \\leq EQB`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqi1.value = 2.0 >>> eqb(1.0) >>> eqb eqb(2.0) >>> eqb(2.0) >>> eqb eqb(2.0) >>> eqb(3.0) >>> eqb ...
entailment