INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns a dictionary for storage. | def _store(self):
"""Returns a dictionary for storage.
Every element in the dictionary except for 'explored_data' is a pickle dump.
Reusage of objects is identified over the object id, i.e. python's built-in id function.
'explored_data' contains the references to the objects to be abl... |
Reconstructs objects from the pickle dumps in load_dict. | def _load(self, load_dict):
"""Reconstructs objects from the pickle dumps in `load_dict`.
The 'explored_data' entry in `load_dict` is used to reconstruct
the exploration range in the correct order.
Sets the `v_protocol` property to the protocol used to store 'data'.
"""
... |
Translates integer indices into the appropriate names | def f_translate_key(self, key):
"""Translates integer indices into the appropriate names"""
if isinstance(key, int):
if key == 0:
key = self.v_name
else:
key = self.v_name + '_%d' % key
return key |
Summarizes data handled by the result as a string. | def f_val_to_str(self):
"""Summarizes data handled by the result as a string.
Calls `__repr__` on all handled data. Data is NOT ordered.
Truncates the string if it is longer than
:const:`pypetconstants.HDF5_STRCOL_MAX_VALUE_LENGTH`
:return: string
"""
resstrl... |
Returns all handled data as a dictionary. | def f_to_dict(self, copy=True):
"""Returns all handled data as a dictionary.
:param copy:
Whether the original dictionary or a shallow copy is returned.
:return: Data dictionary
"""
if copy:
return self._data.copy()
else:
return sel... |
Method to put data into the result. | def f_set(self, *args, **kwargs):
""" Method to put data into the result.
:param args:
The first positional argument is stored with the name of the result.
Following arguments are stored with `name_X` where `X` is the position
of the argument.
:param kwargs... |
Returns items handled by the result. | def f_get(self, *args):
"""Returns items handled by the result.
If only a single name is given, a single data item is returned. If several names are
given, a list is returned. For integer inputs the result returns `resultname_X`.
If the result contains only a single entry you can ca... |
Sets a single data item of the result. | def f_set_single(self, name, item):
"""Sets a single data item of the result.
Raises TypeError if the type of the outer data structure is not understood.
Note that the type check is shallow. For example, if the data item is a list,
the individual list elements are NOT checked whether th... |
Removes * args from the result | def f_remove(self, *args):
"""Removes `*args` from the result"""
for arg in args:
arg = self.f_translate_key(arg)
if arg in self._data:
del self._data[arg]
else:
raise AttributeError('Your result `%s` does not contain %s.' % (self.name_... |
Supports everything of parent class and csr csc bsr and dia sparse matrices. | def _supports(self, item):
"""Supports everything of parent class and csr, csc, bsr, and dia sparse matrices."""
if SparseParameter._is_supported_matrix(item):
return True
else:
return super(SparseResult, self)._supports(item) |
Returns a storage dictionary understood by the storage service. | def _store(self):
"""Returns a storage dictionary understood by the storage service.
Sparse matrices are extracted similar to the :class:`~pypet.parameter.SparseParameter` and
marked with the identifier `__spsp__`.
"""
store_dict = {}
for key in self._data:
... |
Loads data from load_dict | def _load(self, load_dict):
"""Loads data from `load_dict`
Reconstruction of sparse matrices similar to the :class:`~pypet.parameter.SparseParameter`.
"""
for key in list(load_dict.keys()):
# We delete keys over time:
if key in load_dict:
if Spar... |
Adds a single data item to the pickle result. | def f_set_single(self, name, item):
"""Adds a single data item to the pickle result.
Note that it is NOT checked if the item can be pickled!
"""
if self.v_stored:
self._logger.debug('You are changing an already stored result. If '
'you not... |
Returns a dictionary containing pickle dumps | def _store(self):
"""Returns a dictionary containing pickle dumps"""
store_dict = {}
for key, val in self._data.items():
store_dict[key] = pickle.dumps(val, protocol=self.v_protocol)
store_dict[PickleResult.PROTOCOL] = self.v_protocol
return store_dict |
Reconstructs all items from the pickle dumps in load_dict. | def _load(self, load_dict):
"""Reconstructs all items from the pickle dumps in `load_dict`.
Sets the `v_protocol` property to the protocol of the first reconstructed item.
"""
try:
self.v_protocol = load_dict.pop(PickleParameter.PROTOCOL)
except KeyError:
... |
Simply merge all trajectories in the working directory | def main():
"""Simply merge all trajectories in the working directory"""
folder = os.getcwd()
print('Merging all files')
merge_all_in_folder(folder,
delete_other_files=True, # We will only keep one trajectory
dynamic_imports=FunctionParameter,
... |
Uploads a file | def upload_file(filename, session):
""" Uploads a file """
print('Uploading file %s' % filename)
outfilesource = os.path.join(os.getcwd(), filename)
outfiletarget = 'sftp://' + ADDRESS + WORKING_DIR
out = saga.filesystem.File(outfilesource, session=session, flags=OVERWRITE)
out.copy(outfiletarge... |
Downloads a file | def download_file(filename, session):
""" Downloads a file """
print('Downloading file %s' % filename)
infilesource = os.path.join('sftp://' + ADDRESS + WORKING_DIR,
filename)
infiletarget = os.path.join(os.getcwd(), filename)
incoming = saga.filesystem.File(infileso... |
Creates and returns a new SAGA session | def create_session():
""" Creates and returns a new SAGA session """
ctx = saga.Context("UserPass")
ctx.user_id = USER
ctx.user_pass = PASSWORD
session = saga.Session()
session.add_context(ctx)
return session |
Merges all trajectories found in the working directory | def merge_trajectories(session):
""" Merges all trajectories found in the working directory """
jd = saga.job.Description()
jd.executable = 'python'
jd.arguments = ['merge_trajs.py']
jd.output = "mysagajob_merge.stdout"
jd.error = "mysagajob_merge.stderr"
jd.wo... |
Starts all jobs and runs the_task. py in batches. | def start_jobs(session):
""" Starts all jobs and runs `the_task.py` in batches. """
js = saga.job.Service('ssh://' + ADDRESS, session=session)
batches = range(3)
jobs = []
for batch in batches:
print('Starting batch %d' % batch)
jd = saga.job.Description()
jd.executable ... |
Sophisticated simulation of multiplication | def multiply(traj):
"""Sophisticated simulation of multiplication"""
z=traj.x*traj.y
traj.f_add_result('z',z=z, comment='I am the product of two reals!') |
Main function to protect the * entry point * of the program. | def main():
"""Main function to protect the *entry point* of the program.
If you want to use multiprocessing with SCOOP you need to wrap your
main code creating an environment into a function. Otherwise
the newly started child processes will re-execute the code and throw
errors (also see http://sco... |
Runs a simulation of a model neuron. | def run_neuron(traj):
"""Runs a simulation of a model neuron.
:param traj:
Container with all parameters.
:return:
An estimate of the firing rate of the neuron
"""
# Extract all parameters from `traj`
V_init = traj.par.neuron.V_init
I = traj.par.neuron.I
tau_V = tra... |
Postprocessing sorts computed firing rates into a table | def neuron_postproc(traj, result_list):
"""Postprocessing, sorts computed firing rates into a table
:param traj:
Container for results and parameters
:param result_list:
List of tuples, where first entry is the run index and second is the actual
result of the corresponding run.
... |
Adds all parameters to traj | def add_parameters(traj):
"""Adds all parameters to `traj`"""
print('Adding Parameters')
traj.f_add_parameter('neuron.V_init', 0.0,
comment='The initial condition for the '
'membrane potential')
traj.f_add_parameter('neuron.I', 0.0,
... |
Explores different values of I and tau_ref. | def add_exploration(traj):
"""Explores different values of `I` and `tau_ref`."""
print('Adding exploration of I and tau_ref')
explore_dict = {'neuron.I': np.arange(0, 1.01, 0.01).tolist(),
'neuron.tau_ref': [5.0, 7.5, 10.0]}
explore_dict = cartesian_product(explore_dict, ('neuron.... |
Runs a network before the actual experiment. | def execute_network_pre_run(self, traj, network, network_dict, component_list, analyser_list):
"""Runs a network before the actual experiment.
Called by a :class:`~pypet.brian2.network.NetworkManager`.
Similar to :func:`~pypet.brian2.network.NetworkRunner.run_network`.
Subruns and thei... |
Runs a network in an experimental run. | def execute_network_run(self, traj, network, network_dict, component_list, analyser_list):
"""Runs a network in an experimental run.
Called by a :class:`~pypet.brian2.network.NetworkManager`.
A network run is divided into several subruns which are defined as
:class:`~pypet.brian2.param... |
Extracts subruns from the trajectory. | def _extract_subruns(self, traj, pre_run=False):
"""Extracts subruns from the trajectory.
:param traj: Trajectory container
:param pre_run: Boolean whether current run is regular or a pre-run
:raises: RuntimeError if orders are duplicates or even missing
"""
if pre_ru... |
Generic execute_network_run function handles experimental runs as well as pre - runs. | def _execute_network_run(self, traj, network, network_dict, component_list,
analyser_list, pre_run=False):
"""Generic `execute_network_run` function, handles experimental runs as well as pre-runs.
See also :func:`~pypet.brian2.network.NetworkRunner.execute_network_run` and
... |
Adds parameters for a network simulation. | def add_parameters(self, traj):
"""Adds parameters for a network simulation.
Calls :func:`~pypet.brian2.network.NetworkComponent.add_parameters` for all components,
analyser, and the network runner (in this order).
:param traj: Trajectory container
"""
self._logger.in... |
Pre - builds network components. | def pre_build(self, traj):
"""Pre-builds network components.
Calls :func:`~pypet.brian2.network.NetworkComponent.pre_build` for all components,
analysers, and the network runner.
`pre_build` is not automatically called but either needs to be executed manually
by the user, eithe... |
Pre - builds network components. | def build(self, traj):
"""Pre-builds network components.
Calls :func:`~pypet.brian2.network.NetworkComponent.build` for all components,
analysers and the network runner.
`build` does not need to be called by the user. If `~pypet.brian2.network.run_network`
is passed to an :clas... |
Starts a network run before the individual run. | def pre_run_network(self, traj):
"""Starts a network run before the individual run.
Useful if a network needs an initial run that can be shared by all individual
experimental runs during parameter exploration.
Needs to be called by the user. If `pre_run_network` is started by the user,... |
Top - level simulation function pass this to the environment | def run_network(self, traj):
"""Top-level simulation function, pass this to the environment
Performs an individual network run during parameter exploration.
`run_network` does not need to be called by the user. If this
method (not this one of the NetworkManager)
is passed to an... |
Starts a single run carried out by a NetworkRunner. | def _run_network(self, traj):
"""Starts a single run carried out by a NetworkRunner.
Called from the public function :func:`~pypet.brian2.network.NetworkManger.run_network`.
:param traj: Trajectory container
"""
self.build(traj)
self._pretty_print_explored_parameters(... |
Function to create generic filenames based on what has been explored | def make_filename(traj):
""" Function to create generic filenames based on what has been explored """
explored_parameters = traj.f_get_explored_parameters()
filename = ''
for param in explored_parameters.values():
short_name = param.v_name
val = param.f_get()
filename += '%s_%s__... |
Simple wrapper function for compatibility with * pypet *. | def wrap_automaton(traj):
""" Simple wrapper function for compatibility with *pypet*.
We will call the original simulation functions with data extracted from ``traj``.
The resulting automaton patterns wil also be stored into the trajectory.
:param traj: Trajectory container for data
"""
# Ma... |
Main * boilerplate * function to start simulation | def main():
""" Main *boilerplate* function to start simulation """
# Now let's make use of logging
logger = logging.getLogger()
# Create folders for data and plots
folder = os.path.join(os.getcwd(), 'experiments', 'ca_patterns_pypet')
if not os.path.isdir(folder):
os.makedirs(folder)
... |
Returns next element from chain. | def next(self):
"""Returns next element from chain.
More precisely, it returns the next element of the
foremost iterator. If this iterator is empty it moves iteratively
along the chain of available iterators to pick the new foremost one.
Raises StopIteration if there are no ele... |
Merges all files in a given folder. | def merge_all_in_folder(folder, ext='.hdf5',
dynamic_imports=None,
storage_service=None,
force=False,
ignore_data=(),
move_data=False,
delete_other_files=False,
... |
Handler of SIGINT | def _handle_sigint(self, signum, frame):
"""Handler of SIGINT
Does nothing if SIGINT is encountered once but raises a KeyboardInterrupt in case it
is encountered twice.
immediatly.
"""
if self.hit:
prompt = 'Exiting immediately!'
raise KeyboardIn... |
Small configuration file management function | def config_from_file(filename, config=None):
''' Small configuration file management function'''
if config:
# We're writing configuration
try:
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(config))
except IOError as error:
logger.except... |
Method to request a PIN from ecobee for authorization | def request_pin(self):
''' Method to request a PIN from ecobee for authorization '''
url = 'https://api.ecobee.com/authorize'
params = {'response_type': 'ecobeePin',
'client_id': self.api_key, 'scope': 'smartWrite'}
try:
request = requests.get(url, params=pa... |
Method to request API tokens from ecobee | def request_tokens(self):
''' Method to request API tokens from ecobee '''
url = 'https://api.ecobee.com/token'
params = {'grant_type': 'ecobeePin', 'code': self.authorization_code,
'client_id': self.api_key}
try:
request = requests.post(url, params=params)
... |
Method to refresh API tokens from ecobee | def refresh_tokens(self):
''' Method to refresh API tokens from ecobee '''
url = 'https://api.ecobee.com/token'
params = {'grant_type': 'refresh_token',
'refresh_token': self.refresh_token,
'client_id': self.api_key}
request = requests.post(url, params... |
Set self. thermostats to a json list of thermostats from ecobee | def get_thermostats(self):
''' Set self.thermostats to a json list of thermostats from ecobee '''
url = 'https://api.ecobee.com/1/thermostat'
header = {'Content-Type': 'application/json;charset=UTF-8',
'Authorization': 'Bearer ' + self.access_token}
params = {'json': ('... |
Write api tokens to a file | def write_tokens_to_file(self):
''' Write api tokens to a file '''
config = dict()
config['API_KEY'] = self.api_key
config['ACCESS_TOKEN'] = self.access_token
config['REFRESH_TOKEN'] = self.refresh_token
config['AUTHORIZATION_CODE'] = self.authorization_code
if se... |
possible hvac modes are auto auxHeatOnly cool heat off | def set_hvac_mode(self, index, hvac_mode):
''' possible hvac modes are auto, auxHeatOnly, cool, heat, off '''
body = {"selection": {"selectionType": "thermostats",
"selectionMatch": self.thermostats[index]['identifier']},
"thermostat": {
... |
The minimum time in minutes to run the fan each hour. Value from 1 to 60 | def set_fan_min_on_time(self, index, fan_min_on_time):
''' The minimum time, in minutes, to run the fan each hour. Value from 1 to 60 '''
body = {"selection": {"selectionType": "thermostats",
"selectionMatch": self.thermostats[index]['identifier']},
"therm... |
Set fan mode. Values: auto minontime on | def set_fan_mode(self, index, fan_mode, cool_temp, heat_temp, hold_type="nextTransition"):
''' Set fan mode. Values: auto, minontime, on '''
body = {"selection": {
"selectionType": "thermostats",
"selectionMatch": self.thermostats[index]['identifier']},
... |
Set a hold | def set_hold_temp(self, index, cool_temp, heat_temp,
hold_type="nextTransition"):
''' Set a hold '''
body = {"selection": {
"selectionType": "thermostats",
"selectionMatch": self.thermostats[index]['identifier']},
"functions":... |
Set a climate hold - ie away home sleep | def set_climate_hold(self, index, climate, hold_type="nextTransition"):
''' Set a climate hold - ie away, home, sleep '''
body = {"selection": {
"selectionType": "thermostats",
"selectionMatch": self.thermostats[index]['identifier']},
"functions": ... |
Delete the vacation with name vacation | def delete_vacation(self, index, vacation):
''' Delete the vacation with name vacation '''
body = {"selection": {
"selectionType": "thermostats",
"selectionMatch": self.thermostats[index]['identifier']},
"functions": [{"type": "deleteVacation", "pa... |
Resume currently scheduled program | def resume_program(self, index, resume_all=False):
''' Resume currently scheduled program '''
body = {"selection": {
"selectionType": "thermostats",
"selectionMatch": self.thermostats[index]['identifier']},
"functions": [{"type": "resumeProgram", "... |
Send a message to the thermostat | def send_message(self, index, message="Hello from python-ecobee!"):
''' Send a message to the thermostat '''
body = {"selection": {
"selectionType": "thermostats",
"selectionMatch": self.thermostats[index]['identifier']},
"functions": [{"type": "se... |
Set humidity level | def set_humidity(self, index, humidity):
''' Set humidity level'''
body = {"selection": {"selectionType": "thermostats",
"selectionMatch": self.thermostats[index]['identifier']},
"thermostat": {
"settings": {
... |
Enable/ disable Alexa mic ( only for Ecobee 4 ) Values: True False | def set_mic_mode(self, index, mic_enabled):
'''Enable/disable Alexa mic (only for Ecobee 4)
Values: True, False
'''
body = {
'selection': {
'selectionType': 'thermostats',
'selectionMatch': self.thermostats[index]['identifier']},
... |
Enable/ disable Smart Home/ Away and Follow Me modes Values: True False | def set_occupancy_modes(self, index, auto_away=None, follow_me=None):
'''Enable/disable Smart Home/Away and Follow Me modes
Values: True, False
'''
body = {
'selection': {
'selectionType': 'thermostats',
'selectionMatch': self.thermost... |
Enable/ disable daylight savings Values: True False | def set_dst_mode(self, index, dst):
'''Enable/disable daylight savings
Values: True, False
'''
body = {
'selection': {
'selectionType': 'thermostats',
'selectionMatch': self.thermostats[index]['identifier']},
'thermostat': ... |
. | def future_dt_str(dt, td):
"""."""
if isinstance(td, str):
td = float(td)
td = timedelta(seconds=td)
future_dt = dt + td
return future_dt.strftime(DT_PRINT_FORMAT) |
Generate the delay in seconds in which the DISCOVER will be sent. | def gen_delay_selecting():
"""Generate the delay in seconds in which the DISCOVER will be sent.
[:rfc:`2131#section-4.4.1`]::
The client SHOULD wait a random time between one and ten seconds to
desynchronize the use of DHCP at startup.
"""
delay = float(random.randint(0, MAX_DELAY_SEL... |
Generate the time in seconds in which DHCPDISCOVER wil be retransmited. | def gen_timeout_resend(attempts):
"""Generate the time in seconds in which DHCPDISCOVER wil be retransmited.
[:rfc:`2131#section-3.1`]::
might retransmit the
DHCPREQUEST message four times, for a total delay of 60 seconds
[:rfc:`2131#section-4.1`]::
For example, in a 10Mb/sec Eth... |
Generate time in seconds to retransmit DHCPREQUEST. | def gen_timeout_request_renew(lease):
"""Generate time in seconds to retransmit DHCPREQUEST.
[:rfc:`2131#section-4..4.5`]::
In both RENEWING and REBINDING states,
if the client receives no response to its DHCPREQUEST
message, the client SHOULD wait one-half of the remaining
tim... |
. | def gen_timeout_request_rebind(lease):
"""."""
time_left = (lease.lease_time - lease.rebinding_time) * RENEW_PERC
if time_left < 60:
time_left = 60
logger.debug('Next request on rebinding will happen on %s',
future_dt_str(nowutc(), time_left))
return time_left |
Generate RENEWING time. | def gen_renewing_time(lease_time, elapsed=0):
"""Generate RENEWING time.
[:rfc:`2131#section-4.4.5`]::
T1
defaults to (0.5 * duration_of_lease). T2 defaults to (0.875 *
duration_of_lease). Times T1 and T2 SHOULD be chosen with some
random "fuzz" around a fixed value, to avoid... |
. | def gen_rebinding_time(lease_time, elapsed=0):
"""."""
rebinding_time = int(lease_time) * REBIND_PERC - elapsed
# FIXME:90 [:rfc:`2131#section-4.4.5`]: the chosen "fuzz" could fingerprint
# the implementation
# NOTE: here using same "fuzz" as systemd?
range_fuzz = int(lease_time) - rebinding_tim... |
Return the self object attributes not inherited as dict. | def dict_self(self):
"""Return the self object attributes not inherited as dict."""
return {k: v for k, v in self.__dict__.items() if k in FSM_ATTRS} |
Reset object attributes when state is INIT. | def reset(self, iface=None, client_mac=None, xid=None, scriptfile=None):
"""Reset object attributes when state is INIT."""
logger.debug('Reseting attributes.')
if iface is None:
iface = conf.iface
if client_mac is None:
# scapy for python 3 returns byte, not tuple... |
Workaround to get timeout in the ATMT. timeout class method. | def get_timeout(self, state, function):
"""Workaround to get timeout in the ATMT.timeout class method."""
state = STATES2NAMES[state]
for timeout_fn_t in self.timeout[state]:
# access the function name
if timeout_fn_t[1] is not None and \
timeout_fn_t[1].at... |
Workaround to change timeout values in the ATMT. timeout class method. | def set_timeout(self, state, function, newtimeout):
"""
Workaround to change timeout values in the ATMT.timeout class method.
self.timeout format is::
{'STATE': [
(TIMEOUT0, <function foo>),
(TIMEOUT1, <function bar>)),
(None, None)
... |
Send discover. | def send_discover(self):
"""Send discover."""
assert self.client
assert self.current_state == STATE_INIT or \
self.current_state == STATE_SELECTING
pkt = self.client.gen_discover()
sendp(pkt)
# FIXME:20 check that this is correct,: all or only discover?
... |
Select an offer from the offers received. | def select_offer(self):
"""Select an offer from the offers received.
[:rfc:`2131#section-4.2`]::
DHCP clients are free to use any strategy in selecting a DHCP
server among those from which the client receives a DHCPOFFER.
[:rfc:`2131#section-4.4.1`]::
The ... |
Send request. | def send_request(self):
"""Send request.
[:rfc:`2131#section-3.1`]::
a client retransmitting as described in section 4.1 might retransmit
the DHCPREQUEST message four times, for a total delay of 60 seconds
.. todo::
- The maximum number of retransmitted REQUESTs is... |
Set renewal rebinding times. | def set_timers(self):
"""Set renewal, rebinding times."""
logger.debug('setting timeouts')
self.set_timeout(self.current_state,
self.renewing_time_expires,
self.client.lease.renewal_time)
self.set_timeout(self.current_state,
... |
Process a received ACK packet. | def process_received_ack(self, pkt):
"""Process a received ACK packet.
Not specifiyed in [:rfc:`7844`].
Probe the offered IP in [:rfc:`2131#section-2.2.`]::
the allocating
server SHOULD probe the reused address before allocating the
address, e.g., with an IC... |
Process a received NAK packet. | def process_received_nak(self, pkt):
"""Process a received NAK packet."""
if isnak(pkt):
logger.info('DHCPNAK of %s from %s',
self.client.client_ip, self.client.server_ip)
return True
return False |
INIT state. | def INIT(self):
"""INIT state.
[:rfc:`2131#section-4.4.1`]::
The client SHOULD wait a random time between one and ten
seconds to desynchronize the use of DHCP at startup
.. todo::
- The initial delay is implemented, but probably is not in other
... |
BOUND state. | def BOUND(self):
"""BOUND state."""
logger.debug('In state: BOUND')
logger.info('(%s) state changed %s -> bound', self.client.iface,
STATES2NAMES[self.current_state])
self.current_state = STATE_BOUND
self.client.lease.info_lease()
if self.script is not... |
RENEWING state. | def RENEWING(self):
"""RENEWING state."""
logger.debug('In state: RENEWING')
self.current_state = STATE_RENEWING
if self.script is not None:
self.script.script_init(self.client.lease, self.current_state)
self.script.script_go()
else:
set_net(se... |
REBINDING state. | def REBINDING(self):
"""REBINDING state."""
logger.debug('In state: REBINDING')
self.current_state = STATE_REBINDING
if self.script is not None:
self.script.script_init(self.client.lease, self.current_state)
self.script.script_go()
else:
set_ne... |
END state. | def END(self):
"""END state."""
logger.debug('In state: END')
self.current_state = STATE_END
if self.script is not None:
self.script.script_init(self.client.lease, self.current_state)
self.script.script_go()
else:
set_net(self.client.lease)
... |
ERROR state. | def ERROR(self):
"""ERROR state."""
logger.debug('In state: ERROR')
self.current_state = STATE_ERROR
if self.script is not None:
self.script.script_init(self.client.lease, self.current_state)
self.script.script_go()
set_net(self.client.lease)
raise... |
Timeout of selecting on SELECTING state. | def timeout_selecting(self):
"""Timeout of selecting on SELECTING state.
Not specifiyed in [:rfc:`7844`].
See comments in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_request`.
"""
logger.debug('C2.1: T In %s, timeout receiving response to select.',
self.current_st... |
Timeout requesting in REQUESTING state. | def timeout_requesting(self):
"""Timeout requesting in REQUESTING state.
Not specifiyed in [:rfc:`7844`]
[:rfc:`2131#section-3.1`]::
might retransmit the
DHCPREQUEST message four times, for a total delay of 60 seconds
"""
logger.debug("C3.2: T. In %s, ... |
Timeout of renewing on RENEWING state. | def timeout_request_renewing(self):
"""Timeout of renewing on RENEWING state.
Same comments as in
:func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`.
"""
logger.debug("C5.2:T In %s, timeout receiving response to request.",
self.current_state)
if self.... |
Timeout of request rebinding on REBINDING state. | def timeout_request_rebinding(self):
"""Timeout of request rebinding on REBINDING state.
Same comments as in
:func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`.
"""
logger.debug("C6.2:T In %s, timeout receiving response to request.",
self.current_state)
... |
Receive offer on SELECTING state. | def receive_offer(self, pkt):
"""Receive offer on SELECTING state."""
logger.debug("C2. Received OFFER?, in SELECTING state.")
if isoffer(pkt):
logger.debug("C2: T, OFFER received")
self.offers.append(pkt)
if len(self.offers) >= MAX_OFFERS_COLLECTED:
... |
Receive ACK in REQUESTING state. | def receive_ack_requesting(self, pkt):
"""Receive ACK in REQUESTING state."""
logger.debug("C3. Received ACK?, in REQUESTING state.")
if self.process_received_ack(pkt):
logger.debug("C3: T. Received ACK, in REQUESTING state, "
"raise BOUND.")
rais... |
Receive NAK in REQUESTING state. | def receive_nak_requesting(self, pkt):
"""Receive NAK in REQUESTING state."""
logger.debug("C3.1. Received NAK?, in REQUESTING state.")
if self.process_received_nak(pkt):
logger.debug("C3.1: T. Received NAK, in REQUESTING state, "
"raise INIT.")
r... |
Receive ACK in RENEWING state. | def receive_ack_renewing(self, pkt):
"""Receive ACK in RENEWING state."""
logger.debug("C3. Received ACK?, in RENEWING state.")
if self.process_received_ack(pkt):
logger.debug("C3: T. Received ACK, in RENEWING state, "
"raise BOUND.")
raise self.B... |
Receive NAK in RENEWING state. | def receive_nak_renewing(self, pkt):
"""Receive NAK in RENEWING state."""
logger.debug("C3.1. Received NAK?, in RENEWING state.")
if self.process_received_nak(pkt):
logger.debug("C3.1: T. Received NAK, in RENEWING state, "
" raise INIT.")
raise se... |
Receive ACK in REBINDING state. | def receive_ack_rebinding(self, pkt):
"""Receive ACK in REBINDING state."""
logger.debug("C3. Received ACK?, in REBINDING state.")
if self.process_received_ack(pkt):
logger.debug("C3: T. Received ACK, in REBINDING state, "
"raise BOUND.")
raise se... |
Receive NAK in REBINDING state. | def receive_nak_rebinding(self, pkt):
"""Receive NAK in REBINDING state."""
logger.debug("C3.1. Received NAK?, in RENEWING state.")
if self.process_received_nak(pkt):
logger.debug("C3.1: T. Received NAK, in RENEWING state, "
"raise INIT.")
raise s... |
Action on renewing on RENEWING state. | def on_renewing(self):
"""Action on renewing on RENEWING state.
Not recording lease, but restarting timers.
"""
self.client.lease.sanitize_net_values()
self.client.lease.set_times(self.time_sent_request)
self.set_timers() |
. | def isoffer(packet):
"""."""
if DHCP in packet and (DHCPTypes.get(packet[DHCP].options[0][1]) ==
'offer' or packet[DHCP].options[0][1] == "offer"):
logger.debug('Packet is Offer.')
return True
return False |
Assign a value remove if it s None | def set(self, name, value):
""" Assign a value, remove if it's None """
clone = self._clone()
if django.VERSION[0] <= 1 and django.VERSION[1] <= 4:
value = value or None
clone._qsl = [(q, v) for (q, v) in self._qsl if q != name]
if value is not None:
clone... |
Append a value to multiple value parameter. | def add(self, name, value):
""" Append a value to multiple value parameter. """
clone = self._clone()
clone._qsl = [p for p in self._qsl
if not(p[0] == name and p[1] == value)]
clone._qsl.append((name, value,))
return clone |
Remove a value from multiple value parameter. | def remove(self, name, value):
""" Remove a value from multiple value parameter. """
clone = self._clone()
clone._qsl = [qb for qb in self._qsl if qb != (name, str(value))]
return clone |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.