Search is not available for this dataset
text stringlengths 75 104k |
|---|
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) |
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]
... |
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... |
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] |
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) |
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] |
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... |
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 |
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... |
def add_answer(self, inp, record):
"""Adds an answer"""
if not record.suppressed_by(inp):
self.add_answer_at_time(record, 0) |
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... |
def write_byte(self, value):
"""Writes a single byte to the packet"""
format = '!B'
self.data.append(struct.pack(format, value))
self.size += 1 |
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 |
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 |
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 |
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) |
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... |
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) |
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... |
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)
... |
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) |
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... |
def remove(self, entry):
"""Removes an entry"""
try:
list = self.cache[entry.key]
list.remove(entry)
except:
pass |
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 |
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) |
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 [] |
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:... |
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 |
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 |
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 |
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:
... |
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 ... |
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() |
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() |
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):
... |
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,... |
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) |
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... |
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... |
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):
... |
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... |
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() |
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... |
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 =... |
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... |
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()
... |
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... |
def get_record_rdd_from_json_files(self,
json_files: List[str],
data_processor: DataProcessor = SimpleJsonDataProcessor(),
spark_session: Optional['SparkSession'] = None) -> 'RDD':
"""
Re... |
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... |
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... |
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... |
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 =... |
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 |
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... |
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... |
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) |
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.
"""
... |
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... |
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... |
def _persist(self) -> None:
"""
Persists the current data group
"""
if self._store:
self._store.save(self._key, self._snapshot) |
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 ... |
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) |
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... |
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... |
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_... |
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... |
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.
... |
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... |
def global_add(self, key: str, value: Any) -> None:
"""
Adds a key and value to the global dictionary
"""
self.global_context[key] = value |
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... |
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... |
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... |
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... |
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 `... |
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... |
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
... |
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... |
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 |
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... |
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
--------... |
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... |
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
-------
... |
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... |
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
... |
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... |
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) |
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... |
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:
... |
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 ... |
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... |
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}'
... |
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 |
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) |
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 |
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 |
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) |
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 |
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
... |
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
... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.