INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Distributed process | def _run(self, run_dir):
"""Distributed process"""
# Check to see if the required run_params files exist, if they dont use the tools to generate them
# --------------------------------------------------#
# HERE WE RECREATE OUR RUN_PARAMS OBJECT FROM
# THE RUN FILE WE WROTE TO D... |
For all possible combinations of batchable parameters. create a unique directory to story outputs | def generate_directories(self, overwrite=False):
"""For all possible combinations of 'batchable' parameters. create a unique directory to story outputs
Each directory name is unique and contains the run parameters in the directory name
:param overwrite: If set to True will over write all files... |
Takes lists for parameters and saves them as class properties | def batch_parameters(self, saa, sza, p, x, y, g, s, z):
"""Takes lists for parameters and saves them as class properties
:param saa: <list> Sun Azimuth Angle (deg)
:param sza: <list> Sun Zenith Angle (deg)
:param p: <list> Phytoplankton linear scalling factor
:param x: <list> Sc... |
Loads a text file to a python dictionary using = as the delimiter | def read_param_file_to_dict(file_name):
"""Loads a text file to a python dictionary using '=' as the delimiter
:param file_name: the name and path of the text file
"""
data = loadtxt(file_name, delimiter='=', dtype=scipy.string0)
data_dict = dict(data)
for key in data_di... |
Pull comma separated string values out of a text file and converts them to float list | def string_to_float_list(string_var):
"""Pull comma separated string values out of a text file and converts them to float list"""
try:
return [float(s) for s in string_var.strip('[').strip(']').split(', ')]
except:
return [float(s) for s in string_var.strip('[').strip(']'... |
Reads in a PlanarRad generated report | def read_pr_report(self, filename):
"""Reads in a PlanarRad generated report
Saves the single line reported parameters as a python dictionary
:param filename: The name and path of the PlanarRad generated file
:returns self.data_dictionary: python dictionary with the key and values from... |
Will calcuate the directional AOP ( only sub - surface rrs for now ) if the direction is defined using @ e. g. rrs@32. 0: 45 where <zenith - theta >: <azimuth - phi > | def calc_directional_aop(self, report, parameter, parameter_dir):
"""
Will calcuate the directional AOP (only sub-surface rrs for now) if the direction is defined using @
e.g. rrs@32.0:45 where <zenith-theta>:<azimuth-phi>
:param report: The planarrad report dictionary. should include... |
Collect all of the batch reports and concatenate the results. The report should be: | def write_batch_report(self, input_directory, parameter):
"""
Collect all of the batch reports and concatenate the results. The report should be :
:param input_directory:
:param parameter: This is the parameter in which to report.
"""
# Check to see if there is an @ in... |
This function creates a new file if he doesn t exist already moves it to inputs/ batch_file folder and writes data and comments associated to them. Inputs: saa_values: <list > Sun Azimuth Angle ( deg ) sza_values: <list > Sun Zenith Angle ( deg ) batch_name: Name of the batch file. p_values: <list > Phytoplankton linea... | def write_batch_to_file(self, filename='batch_test_default.txt'):
"""
This function creates a new file if he doesn't exist already, moves it to 'inputs/batch_file' folder
and writes data and comments associated to them.
Inputs: saa_values : <list> Sun Azimuth Angle (deg)
... |
This function will update data that we need to display curves from data_processing from gui_mainLayout Inputs: x_data: An array with wavelengths. y_data: An array with curve s data. num_plot: The line curve to plot. | def update_fields(self, x_data, y_data, num_plot):
"""
This function will update data that we need to display curves, from "data_processing" from "gui_mainLayout"
Inputs : x_data : An array with wavelengths.
y_data : An array with curve's data.
num_plot : The li... |
This function plots results of a file into the canvas. Inputs: flag_curves: A boolean to know with we have to plot all curves or not. ui: The main_Window. | def display_graphic(self, flag_curves, ui):
"""
This function plots results of a file into the canvas.
Inputs : flag_curves : A boolean to know with we have to plot all curves or not.
ui : The main_Window.
"""
ui.graphic_widget.canvas.picture.clear()
x =... |
Takes a list of signals and sets a handler for them | def set_handler(self, signals, handler=signal.SIG_DFL):
""" Takes a list of signals and sets a handler for them """
for sig in signals:
self.log.debug("Creating handler for signal: {0}".format(sig))
signal.signal(sig, handler) |
Pseudo handler placeholder while signal is beind processed | def pseudo_handler(self, signum, frame):
""" Pseudo handler placeholder while signal is beind processed """
self.log.warn("Received sigal {0} but system is already busy processing a previous signal, current frame: {1}".format(signum, str(frame))) |
Default handler a generic callback method for signal processing | def default_handler(self, signum, frame):
""" Default handler, a generic callback method for signal processing"""
self.log.debug("Signal handler called with signal: {0}".format(signum))
# 1. If signal is HUP restart the python process
# 2. If signal is TERM, INT or QUIT we try to cleanup... |
Pause execution execution will resume in X seconds or when the appropriate resume signal is received. Execution will jump to the callback_function the default callback function is the handler method which will run all tasks registered with the reg_on_resume methodi. Returns True if timer expired otherwise returns False | def pause(self, signum, seconds=0, callback_function=None):
"""
Pause execution, execution will resume in X seconds or when the
appropriate resume signal is received. Execution will jump to the
callback_function, the default callback function is the handler
method which will run ... |
Run all abort tasks then all exit tasks then exit with error return status | def abort(self, signum):
""" Run all abort tasks, then all exit tasks, then exit with error
return status"""
self.log.info('Signal handler received abort request')
self._abort(signum)
self._exit(signum)
os._exit(1) |
Run all status tasks then run all tasks in the resume queue | def status(self, signum):
""" Run all status tasks, then run all tasks in the resume queue"""
self.log.debug('Signal handler got status signal')
new_status_callbacks = []
for status_call in self.status_callbacks:
# If callback is non persistent we remove it
try:
... |
Tries to remove a registered event without triggering it | def _unreg_event(self, event_list, event):
""" Tries to remove a registered event without triggering it """
try:
self.log.debug("Removing event {0}({1},{2})".format(event['function'].__name__, event['args'], event['kwargs']))
except AttributeError:
self.log.debug("Removin... |
Register a function/ method to be called on program exit will get executed regardless of successs/ failure of the program running | def reg_on_exit(self, callable_object, *args, **kwargs):
""" Register a function/method to be called on program exit,
will get executed regardless of successs/failure of the program running """
persistent = kwargs.pop('persistent', False)
event = self._create_event(callable_object, 'exit... |
Register a function/ method to be called when execution is aborted | def reg_on_abort(self, callable_object, *args, **kwargs):
""" Register a function/method to be called when execution is aborted"""
persistent = kwargs.pop('persistent', False)
event = self._create_event(callable_object, 'abort', persistent, *args, **kwargs)
self.abort_callbacks.append(ev... |
Register a function/ method to be called when a user or another program asks for an update when status is done it will start running any tasks registered with the reg_on_resume method | def reg_on_status(self, callable_object, *args, **kwargs):
""" Register a function/method to be called when a user or another
program asks for an update, when status is done it will start running
any tasks registered with the reg_on_resume method"""
persistent = kwargs.pop('persistent', ... |
Register a function/ method to be called if the system needs to resume a previously halted or paused execution including status requests. | def reg_on_resume(self, callable_object, *args, **kwargs):
""" Register a function/method to be called if the system needs to
resume a previously halted or paused execution, including status
requests."""
persistent = kwargs.pop('persistent', False)
event = self._create_event(call... |
Fetch time series data from OpenTSDB | def fetch_metric(self, metric, start, end, tags={}, aggregator="sum",
downsample=None, ms_resolution=True):
"""Fetch time series data from OpenTSDB
Parameters:
metric:
A string representing a valid OpenTSDB metric.
tags:
A dict mapping ta... |
Fetch and sort time series data from OpenTSDB | def fetch_sorted_metric(self, *args, **kwargs):
"""Fetch and sort time series data from OpenTSDB
Takes the same parameters as `fetch_metric`, but returns a list of
(timestamp, value) tuples sorted by timestamp.
"""
return sorted(self.fetch_metric(*args, **kwargs).items(),
... |
A pointfree reduce/ left fold function: Applies a function of two arguments cumulatively to the items supplied by the given iterable so as to reduce the iterable to a single value. If an initial value is supplied it is placed before the items from the iterable in the calculation and serves as the default when the itera... | def pfreduce(func, iterable, initial=None):
"""A pointfree reduce / left fold function: Applies a function of two
arguments cumulatively to the items supplied by the given iterable, so
as to reduce the iterable to a single value. If an initial value is
supplied, it is placed before the items from the i... |
Collects and returns a list of values from the given iterable. If the n parameter is not specified collects all values from the iterable. | def pfcollect(iterable, n=None):
"""Collects and returns a list of values from the given iterable. If
the n parameter is not specified, collects all values from the
iterable.
:param iterable: An iterable yielding values for the list
:param n: An optional maximum number of items to collect
:rty... |
Prints an item. | def pfprint(item, end='\n', file=None):
"""Prints an item.
:param item: The item to print
:param end: String to append to the end of printed output
:param file: File to which output is printed
:rtype: None
Example::
>>> from operator import add
>>> fn = pfreduce(add, initial=... |
Prints each item from an iterable. | def pfprint_all(iterable, end='\n', file=None):
"""Prints each item from an iterable.
:param iterable: An iterable yielding values to print
:param end: String to append to the end of printed output
:param file: File to which output is printed
:rtype: None
Example::
>>> @pointfree
... |
Extract function signature default arguments keyword - only arguments and whether or not variable positional or keyword arguments are allowed. This also supports calling unbound instance methods by passing an object instance as the first argument ; however unbound classmethod and staticmethod objects are not callable s... | def __sig_from_func(self, func):
"""Extract function signature, default arguments, keyword-only
arguments, and whether or not variable positional or keyword
arguments are allowed. This also supports calling unbound instance
methods by passing an object instance as the first argument;
... |
Extract function signature from an existing partial instance. | def __sig_from_partial(self, inst):
"""Extract function signature from an existing partial instance."""
self.pargl = list(inst.pargl)
self.kargl = list(inst.kargl)
self.def_argv = inst.def_argv.copy()
self.var_pargs = inst.var_pargs
self.var_kargs = inst.var_kar... |
Makes a new instance of the partial application wrapper based on an existing instance optionally overriding the original s wrapped function and/ or saved arguments. | def make_copy(klass, inst, func=None, argv=None, extra_argv=None, copy_sig=True):
"""Makes a new instance of the partial application wrapper based on
an existing instance, optionally overriding the original's wrapped
function and/or saved arguments.
:param inst: The partial instance we'... |
Calculate new argv and extra_argv values resulting from adding the specified positional and keyword arguments. | def __new_argv(self, *new_pargs, **new_kargs):
"""Calculate new argv and extra_argv values resulting from adding
the specified positional and keyword arguments."""
new_argv = self.argv.copy()
new_extra_argv = list(self.extra_argv)
for v in new_pargs:
arg_name = None... |
We do not support multiple signatures in XPI signing because the client side code makes some pretty reasonable assumptions about a single signature on any given JAR. This function returns True if the file name given is one that we dispose of to prevent multiple signatures. | def ignore_certain_metainf_files(filename):
"""
We do not support multiple signatures in XPI signing because the client
side code makes some pretty reasonable assumptions about a single signature
on any given JAR. This function returns True if the file name given is one
that we dispose of to preven... |
Sort keys for xpi files | def file_key(filename):
'''Sort keys for xpi files
The filenames in a manifest are ordered so that files not in a
directory come before files in any directory, ordered
alphabetically but ignoring case, with a few exceptions
(install.rdf, chrome.manifest, icon.png and icon64.png come at the
begi... |
Read one VLQ - encoded integer value from an input data stream. | def vlq2int(data):
"""Read one VLQ-encoded integer value from an input data stream."""
# The VLQ is little-endian.
byte = ord(data.read(1))
value = byte & 0x7F
shift = 1
while byte & 0x80 != 0:
byte = ord(data.read(1))
value = ((byte & 0x7F) << shift * 7) | value
shift +... |
Read a table structure. | def read_table(data, fields):
"""Read a table structure.
These are used by Blizzard to collect pieces of data together. Each
value is prefixed by two bytes, first denoting (doubled) index and the
second denoting some sort of key -- so far it has always been '09'. The
actual value follows as a Varia... |
Parse the user data header portion of the replay. | def _parse_header(self):
"""Parse the user data header portion of the replay."""
header = OrderedDict()
user_data_header = self.archive.header['user_data_header']['content']
if re.search(r'StarCraft II replay', user_data_header):
user_data_header = StringIO.StringIO(user_data... |
Transform duration into a human - readable form. | def get_duration(self, seconds):
"""Transform duration into a human-readable form."""
duration = ""
minutes, seconds = divmod(seconds, 60)
if minutes >= 60:
hours, minutes = divmod(minutes, 60)
duration = "%sh " % hours
duration += "%sm %ss" % (minutes, se... |
Print a summary of the game details. | def print_details(self):
"""Print a summary of the game details."""
print 'Map ', self.map
print 'Duration ', self.duration
print 'Version ', self.version
print 'Team Player Race Color'
print '-----------------------------------'
for player in s... |
This function gets back data that the user typed. | def data(self):
"""
This function gets back data that the user typed.
"""
self.batch_name_value = self.ui.batch_name_value.text()
self.saa_values = self.ui.saa_values.text()
self.sza_values = self.ui.sza_values.text()
self.p_values = self.ui.p_values.text()
... |
This function once the file found display data s file and the graphic associated. | def search_file_result(self):
"""
This function once the file found, display data's file and the graphic associated.
"""
if self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE:
self.result_file = self.file_dialog.getOpenFileName(caption=str("Open Report File"), director... |
This function checks if there is no problem about values given. If there is a problem with a or some values their label s color is changed to red and call a function to display an error message. If there is no problem their label if it is necessary is changed to grey ( default color ). | def check_values(self):
"""
This function checks if there is no problem about values given.
If there is a problem with a or some values, their label's color is changed to red,
and call a function to display an error message.
If there is no problem, their label, if it is necessary... |
This function calls gui_batch. py with inputs values to write the batch file. | def write_to_file(self):
"""
This function calls "gui_batch.py" with inputs values to write the batch file.
"""
bt = BatchFile(self.batch_name_value, self.p_values, self.x_value, self.y_value, self.g_value, self.s_value,
self.z_value, self.wavelength_values, self.v... |
This function separates data from the file to display curves and will put them in the good arrays. | def data_processing(self):
"""
This function separates data, from the file to display curves, and will put them in the good arrays.
"""
the_file_name = str(self.result_file)
the_file = open(the_file_name, 'r')
lines = the_file.readlines()
# We put all lines in a... |
This function calls the class MplCanvas of gui_matplotlibwidgetFile. py to plot results. Inputs: num_line: The number of cases. wavelength: The wavelengths. data_wanted: The data for wavelengths. information: The array which contains the information of all curves to display. | def display_the_graphic(self, num_line, wavelength, data_wanted, information):
"""
This function calls the class "MplCanvas" of "gui_matplotlibwidgetFile.py" to plot results.
Inputs : num_line : The number of cases.
wavelength : The wavelengths.
data_wanted : Th... |
The following permits to attribute the function display_the_graphic to the slider. Because to make a connection we can not have parameters for the function but display_the_graphic has some. | def display_the_graphic_connection(self):
"""
The following permits to attribute the function "display_the_graphic" to the slider.
Because, to make a connection, we can not have parameters for the function, but "display_the_graphic" has some.
"""
self.display_the_graphic(self.num... |
This function displays information about curves. Inputs ; num_curve ; The index of the curve s line that we have to display. information ; The array which contains the information of all curves to display. | def print_graphic_information(self, num_curve, information):
"""
This function displays information about curves.
Inputs ; num_curve ; The index of the curve's line that we have to display.
information ; The array which contains the information, of all curves to display.
... |
This function scales the slider for curves displayed. Input: The number of cases ( curves ). Return ; The slider value. | def graphic_slider(self, nb_case):
"""
This function scales the slider for curves displayed.
Input : The number of cases (curves).
Return ; The slider value.
"""
"""
The slider range is created each time we call this function. Search to set its range just when it... |
This function displays an error message when a wrong value is typed. | def display_error_message(self):
"""
This function displays an error message when a wrong value is typed.
"""
self.ui.error_label.setScaledContents(True) # Warning image shown.
self.ui.error_text_label.show() # Warning message shown.
self.ui.error_text_label.setStyleShe... |
This function hides the error message when all values are correct. | def hide_error_message(self):
"""
This function hides the error message when all values are correct.
"""
self.ui.error_label.setScaledContents(False) # Warning image hiden.
self.ui.error_text_label.hide() |
This function executes planarRad using the batch file. | def run(self):
"""
This function executes planarRad using the batch file.
"""
"""
Error when planarRad start : /bin/sh: 1: ../planarrad.py: not found
"""
print('Executing planarrad')
# If we are not in the reverse_mode :
if self.ui.tabWidget.curre... |
This function cancels PlanarRad. | def cancel_planarrad(self):
"""
This function cancels PlanarRad.
"""
"""
This function needs to be tested. We don't know if she works.
"""
if (self.is_running == True) & (self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE):
cancel = QtGui.QMes... |
This function quits PlanarRad checking if PlanarRad is running before. | def quit(self):
"""
This function quits PlanarRad, checking if PlanarRad is running before.
"""
"""
Nothing programmed for displaying a message box when the user clicks on the window cross in order to quit.
"""
if self.is_running == True:
warning_pla... |
This function programs the button to save the figure displayed and save it in a png file in the current repository. | def save_figure(self):
"""
This function programs the button to save the figure displayed
and save it in a png file in the current repository.
"""
"""
Increment the name of the figure in order to not erase the previous figure if the user use always this method.
T... |
This function programs the button to save the figure displayed and save it in a png file where you want/ with the name you want thanks to a file dialog. | def save_figure_as(self):
"""
This function programs the button to save the figure displayed
and save it in a png file where you want / with the name you want thanks to a file dialog.
"""
self.file_name = QtGui.QFileDialog.getSaveFileName()
self.file_name = self.file_name... |
The following opens the log file of PlanarRad. | def open_log_file(self):
"""
The following opens the log file of PlanarRad.
"""
"""
TO DO.
"""
# webbrowser.open('https://marrabld.github.io/planarradpy/')
f = open(os.path.expanduser('~/.planarradpy/log/libplanarradpy.log'))
# self.uiLog.textEdit.... |
The following opens the documentation file. | def open_documentation(self):
"""
The following opens the documentation file.
"""
"""
TO DO.
"""
# webbrowser.open('https://marrabld.github.io/planarradpy/')
window = Window()
html = QtCore.QUrl.fromLocalFile(os.path.join(os.getcwd(), './docs/_bui... |
This function does all required actions at the beginning when we run the GUI. | def prerequisite_actions(self):
"""
This function does all required actions at the beginning when we run the GUI.
"""
self.hide_error_message()
self.ui.show_all_curves.setDisabled(True)
self.ui.sens.setDisabled(True)
self.ui.show_grid.setDisabled(True)
p... |
This function intercepts the mouse s right click and its position. | def click(self, event):
"""
This function intercepts the mouse's right click and its position.
"""
if event.button == 3:
if self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE:
self.pos = QtGui.QCursor().pos()
self.graphic_context_menu(se... |
The following gets back coordinates of the mouse on the canvas. | def mouse_move(self, event):
"""
The following gets back coordinates of the mouse on the canvas.
"""
if (self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE):
self.posX = event.xdata
self.posY = event.ydata
self.graphic_target(self.posX, self.po... |
This function will open a context menu on the graphic to save it. Inputs: pos: The position of the mouse cursor. | def graphic_context_menu(self, pos):
"""
This function will open a context menu on the graphic to save it.
Inputs : pos : The position of the mouse cursor.
"""
menu = QtGui.QMenu()
self.actionSave_bis = menu.addAction("Save Figure")
self.actionSave_as_bis = menu.a... |
The following update labels about mouse coordinates. | def graphic_target(self, x, y):
"""
The following update labels about mouse coordinates.
"""
if self.authorized_display == True:
try:
self.display_the_graphic(self.num_line, self.wavelength, self.data_wanted, self.information)
self.ui.mouse_co... |
in order to avoid a complicated bootstrapping we define the genesis_signing_lockset as a lockset with one vote by any validator. | def genesis_signing_lockset(genesis, privkey):
"""
in order to avoid a complicated bootstrapping, we define
the genesis_signing_lockset as a lockset with one vote by any validator.
"""
v = VoteBlock(0, 0, genesis.hash)
v.sign(privkey)
ls = LockSet(num_eligible_votes=1)
ls.add(v)
asse... |
Sign this with a private key | def sign(self, privkey):
"""Sign this with a private key"""
if self.v:
raise InvalidSignature("already signed")
if privkey in (0, '', '\x00' * 32):
raise InvalidSignature("Zero privkey cannot sign")
rawhash = sha3(rlp.encode(self, self.__class__.exclude(['v', 'r'... |
signatures are non deterministic | def hash(self):
"signatures are non deterministic"
if self.sender is None:
raise MissingSignatureError()
class HashSerializable(rlp.Serializable):
fields = [(field, sedes) for field, sedes in self.fields
if field not in ('v', 'r', 's')] + [('_sender... |
compute ( height round ) We might have multiple rounds before we see consensus for a certain height. If everything is good round should always be 0. | def hr(self):
"""compute (height,round)
We might have multiple rounds before we see consensus for a certain height.
If everything is good, round should always be 0.
"""
assert len(self), 'no votes, can not determine height'
h = set([(v.height, v.round) for v in self.votes... |
we ve seen + 2/ 3 of all eligible votes voting for one block. there is a quorum. | def has_quorum(self):
"""
we've seen +2/3 of all eligible votes voting for one block.
there is a quorum.
"""
assert self.is_valid
bhs = self.blockhashes()
if bhs and bhs[0][1] > 2 / 3. * self.num_eligible_votes:
return bhs[0][0] |
less than 1/ 3 of the known votes are on the same block | def has_noquorum(self):
"""
less than 1/3 of the known votes are on the same block
"""
assert self.is_valid
bhs = self.blockhashes()
if not bhs or bhs[0][1] <= 1 / 3. * self.num_eligible_votes:
assert not self.has_quorum_possible
return True |
either invalid or one of quorum noquorum quorumpossible | def check(self):
"either invalid or one of quorum, noquorum, quorumpossible"
if not self.is_valid:
return True
test = (self.has_quorum, self.has_quorum_possible, self.has_noquorum)
assert 1 == len([x for x in test if x is not None])
return True |
Convert the transient block to a: class: ethereum. blocks. Block | def to_block(self, env, parent=None):
"""Convert the transient block to a :class:`ethereum.blocks.Block`"""
return Block(self.header, self.transaction_list, self.uncles, env=env, parent=parent) |
set of validators may change between heights | def validate_votes(self, validators_H, validators_prevH):
"set of validators may change between heights"
assert self.sender
def check(lockset, validators):
if not lockset.num_eligible_votes == len(validators):
raise InvalidProposalError('lockset num_eligible_votes mi... |
set of validators may change between heights | def validate_votes(self, validators_H):
"set of validators may change between heights"
assert self.sender
if not self.round_lockset.num_eligible_votes == len(validators_H):
raise InvalidProposalError('round_lockset num_eligible_votes mismatch')
for v in self.round_lockset:
... |
Standardized Contract API: function transfer ( address _to uint256 _value ) returns ( bool _success ) | def transfer(ctx, _to='address', _value='uint256', returns=STATUS):
""" Standardized Contract API:
function transfer(address _to, uint256 _value) returns (bool _success)
"""
log.DEV('In Fungible.transfer')
if ctx.accounts[ctx.msg_sender] >= _value:
ctx.accounts[ctx.ms... |
Standardized Contract API: function transferFrom ( address _from address _to uint256 _value ) returns ( bool success ) | def transferFrom(ctx, _from='address', _to='address', _value='uint256', returns=STATUS):
""" Standardized Contract API:
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
"""
auth = ctx.allowances[_from][ctx.msg_sender]
if ctx.accounts[_from]... |
Standardized Contract API: function approve ( address _spender uint256 _value ) returns ( bool success ) | def approve(ctx, _spender='address', _value='uint256', returns=STATUS):
""" Standardized Contract API:
function approve(address _spender, uint256 _value) returns (bool success)
"""
ctx.allowances[ctx.msg_sender][_spender] += _value
ctx.Approval(ctx.msg_sender, _spender, _value)
... |
In the IOU fungible the supply is set by Issuer who issue funds. | def issue_funds(ctx, amount='uint256', rtgs_hash='bytes32', returns=STATUS):
"In the IOU fungible the supply is set by Issuer, who issue funds."
# allocate new issue as result of a new cash entry
ctx.accounts[ctx.msg_sender] += amount
ctx.issued_amounts[ctx.msg_sender] += amount
... |
highest lock on height | def last_lock(self):
"highest lock on height"
rs = list(self.rounds)
assert len(rs) < 2 or rs[0] > rs[1] # FIXME REMOVE
for r in self.rounds: # is sorted highest to lowest
if self.rounds[r].lock is not None:
return self.rounds[r].lock |
the last block proposal node voted on | def last_voted_blockproposal(self):
"the last block proposal node voted on"
for r in self.rounds:
if isinstance(self.rounds[r].proposal, BlockProposal):
assert isinstance(self.rounds[r].lock, Vote)
if self.rounds[r].proposal.blockhash == self.rounds[r].lock.bl... |
highest valid lockset on height | def last_valid_lockset(self):
"highest valid lockset on height"
for r in self.rounds:
ls = self.rounds[r].lockset
if ls.is_valid:
return ls
return None |
setup a timeout for waiting for a proposal | def get_timeout(self):
"setup a timeout for waiting for a proposal"
if self.timeout_time is not None or self.proposal:
return
now = self.cm.chainservice.now
round_timeout = ConsensusManager.round_timeout
round_timeout_factor = ConsensusManager.round_timeout_factor
... |
sync the missing blocks between: head highest height with signing lockset | def request(self):
"""
sync the missing blocks between:
head
highest height with signing lockset
we get these locksets by collecting votes on all heights
"""
missing = self.missing
self.cm.log('sync.request', missing=len(missing), requested=len(se... |
called to inform about synced peers | def on_proposal(self, proposal, proto):
"called to inform about synced peers"
assert isinstance(proto, HDCProtocol)
assert isinstance(proposal, Proposal)
if proposal.height >= self.cm.height:
assert proposal.lockset.is_valid
self.last_active_protocol = proto |
Creates a wait_next_block function that will wait timeout seconds ( None = indefinitely ) for a new block to appear. | def wait_next_block_factory(app, timeout=None):
"""Creates a `wait_next_block` function, that
will wait `timeout` seconds (`None` = indefinitely)
for a new block to appear.
:param app: the app-instance the function should work for
:param timeout: timeout in seconds
"""
chain = app.services... |
make privkeys that support coloring see utils. cstr | def mk_privkeys(num):
"make privkeys that support coloring, see utils.cstr"
privkeys = []
assert num <= num_colors
for i in range(num):
j = 0
while True:
k = sha3(str(j))
a = privtoaddr(k)
an = big_endian_to_int(a)
if an % num_colors == i:
... |
bandwidths are inaccurate as we don t account for parallel transfers here | def delay(self, sender, receiver, packet, add_delay=0):
"""
bandwidths are inaccurate, as we don't account for parallel transfers here
"""
bw = min(sender.ul_bandwidth, receiver.dl_bandwidth)
delay = sender.base_latency + receiver.base_latency
delay += len(packet) / bw
... |
deliver on edge of timeout_window | def deliver(self, sender, receiver, packet):
"deliver on edge of timeout_window"
to = ConsensusManager.round_timeout
assert to > 0
print "in slow transport deliver"
super(SlowTransport, self).deliver(sender, receiver, packet, add_delay=to) |
encode args for method: method_id|data | def abi_encode_args(method, args):
"encode args for method: method_id|data"
assert issubclass(method.im_class, NativeABIContract), method.im_class
m_abi = method.im_class._get_method_abi(method)
return zpad(encode_int(m_abi['id']), 4) + abi.encode_abi(m_abi['arg_types'], args) |
create an object which acts as a proxy for the contract on the chain | def chain_nac_proxy(chain, sender, contract_address, value=0):
"create an object which acts as a proxy for the contract on the chain"
klass = registry[contract_address].im_self
assert issubclass(klass, NativeABIContract)
def mk_method(method):
def m(s, *args):
data = abi_encode_args... |
returns class. _on_msg_unsafe use x. im_self to get class | def address_to_native_contract_class(self, address):
"returns class._on_msg_unsafe, use x.im_self to get class"
assert isinstance(address, bytes) and len(address) == 20
assert self.is_instance_address(address)
nca = self.native_contract_address_prefix + address[-4:]
return self.n... |
registers NativeContract classes | def register(self, contract):
"registers NativeContract classes"
assert issubclass(contract, NativeContractBase)
assert len(contract.address) == 20
assert contract.address.startswith(self.native_contract_address_prefix)
if self.native_contracts.get(contract.address) == contract._... |
Consolidate ( potentially hex - encoded ) list of validators into list of binary address representations. | def validators_from_config(validators):
"""Consolidate (potentially hex-encoded) list of validators
into list of binary address representations.
"""
result = []
for validator in validators:
if len(validator) == 40:
validator = validator.decode('hex')
result.append(validat... |
returns True if unknown | def update(self, data):
"returns True if unknown"
if data not in self.filter:
self.filter.append(data)
if len(self.filter) > self.max_items:
self.filter.pop(0)
return True
else:
self.filter.append(self.filter.pop(0))
ret... |
Warning: Locking proposal_lock may block incoming events which are necessary to unlock! I. e. votes/ blocks! Take care! | def add_transaction(self, tx, origin=None, force_broadcast=False):
"""
Warning:
Locking proposal_lock may block incoming events which are necessary to unlock!
I.e. votes / blocks!
Take care!
"""
self.consensus_manager.log(
'add_transaction', blk=self.c... |
receives rlp. decoded serialized | def on_receive_transactions(self, proto, transactions):
"receives rlp.decoded serialized"
log.debug('----------------------------------')
log.debug('remote_transactions_received', count=len(transactions), remote_id=proto)
def _add_txs():
for tx in transactions:
... |
Decondition an image from the VGG16 model. | def img_from_vgg(x):
'''Decondition an image from the VGG16 model.'''
x = x.transpose((1, 2, 0))
x[:, :, 0] += 103.939
x[:, :, 1] += 116.779
x[:, :, 2] += 123.68
x = x[:,:,::-1] # to RGB
return x |
Condition an image for use with the VGG16 model. | def img_to_vgg(x):
'''Condition an image for use with the VGG16 model.'''
x = x[:,:,::-1] # to BGR
x[:, :, 0] -= 103.939
x[:, :, 1] -= 116.779
x[:, :, 2] -= 123.68
x = x.transpose((2, 0, 1))
return x |
Create a function for the response of a layer. | def get_f_layer(self, layer_name):
'''Create a function for the response of a layer.'''
inputs = [self.net_input]
if self.learning_phase is not None:
inputs.append(K.learning_phase())
return K.function(inputs, [self.get_layer_output(layer_name)]) |
Get symbolic output of a layer. | def get_layer_output(self, name):
'''Get symbolic output of a layer.'''
if not name in self._f_layer_outputs:
layer = self.net.get_layer(name)
self._f_layer_outputs[name] = layer.output
return self._f_layer_outputs[name] |
Evaluate layer outputs for x | def get_features(self, x, layers):
'''Evaluate layer outputs for `x`'''
if not layers:
return None
inputs = [self.net.input]
if self.learning_phase is not None:
inputs.append(self.learning_phase)
f = K.function(inputs, [self.get_layer_output(layer_name) fo... |
Creates a new encryption key in the path provided and sets the file permissions. Setting the file permissions currently does not work on Windows platforms because of the differences in how file permissions are read and modified. | def create_key_file(path):
"""
Creates a new encryption key in the path provided and sets the file
permissions. Setting the file permissions currently does not work
on Windows platforms because of the differences in how file
permissions are read and modified.
"""
iv = "{}{}".format(os.urand... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.