INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Apply standard deviation filter to remove anomalous values.
def noise_despike(sig, win=3, nlim=24., maxiter=4): """ Apply standard deviation filter to remove anomalous values. Parameters ---------- win : int The window used to calculate rolling statistics. nlim : float The number of standard deviations above the rolling mean abov...
Apply exponential decay filter to remove physically impossible data based on instrumental washout.
def expdecay_despike(sig, expdecay_coef, tstep, maxiter=3): """ Apply exponential decay filter to remove physically impossible data based on instrumental washout. The filter is re-applied until no more points are removed, or maxiter is reached. Parameters ---------- exponent : float Ex...
** f ** must return the same stack type as ** self. value ** has. Iterates over the effects sequences the inner instance successively to the top and joins with the outer instance. Example: List ( Right ( Just ( 1 ))) = > List ( Right ( Just ( List ( Right ( Just ( 5 )))))) = > List ( List ( Right ( Just ( Right ( Just ...
def _flat_map(self, f: Callable): ''' **f** must return the same stack type as **self.value** has. Iterates over the effects, sequences the inner instance successively to the top and joins with the outer instance. Example: List(Right(Just(1))) => List(Right(Just(List(Right(Just(5...
Add filter.
def add(self, name, filt, info='', params=(), setn=None): """ Add filter. Parameters ---------- name : str filter name filt : array_like boolean filter array info : str informative description of the filter params : tup...
Remove filter.
def remove(self, name=None, setn=None): """ Remove filter. Parameters ---------- name : str name of the filter to remove setn : int or True int: number of set to remove True: remove all filters in set that 'name' belongs to Re...
Clear all filters.
def clear(self): """ Clear all filters. """ self.components = {} self.info = {} self.params = {} self.switches = {} self.keys = {} self.index = {} self.sets = {} self.maxset = -1 self.n = 0 for a in self.analytes: ...
Remove unused filters.
def clean(self): """ Remove unused filters. """ for f in sorted(self.components.keys()): unused = not any(self.switches[a][f] for a in self.analytes) if unused: self.remove(f)
Turn on specified filter ( s ) for specified analyte ( s ).
def on(self, analyte=None, filt=None): """ Turn on specified filter(s) for specified analyte(s). Parameters ---------- analyte : optional, str or array_like Name or list of names of analytes. Defaults to all analytes. filt : optional. int, str or ...
Make filter for specified analyte ( s ).
def make(self, analyte): """ Make filter for specified analyte(s). Filter specified in filt.switches. Parameters ---------- analyte : str or array_like Name or list of names of analytes. Returns ------- array_like boolean...
Identify a filter by fuzzy string matching.
def fuzzmatch(self, fuzzkey, multi=False): """ Identify a filter by fuzzy string matching. Partial ('fuzzy') matching performed by `fuzzywuzzy.fuzzy.ratio` Parameters ---------- fuzzkey : str A string that partially matches one filter name more than the othe...
Make filter from logical expression.
def make_fromkey(self, key): """ Make filter from logical expression. Takes a logical expression as an input, and returns a filter. Used for advanced filtering, where combinations of nested and/or filters are desired. Filter names must exactly match the names listed by print(fil...
Make logical expressions describing the filter ( s ) for specified analyte ( s ).
def make_keydict(self, analyte=None): """ Make logical expressions describing the filter(s) for specified analyte(s). Parameters ---------- analyte : optional, str or array_like Name or list of names of analytes. Defaults to all analytes. Returns...
Flexible access to specific filter using any key format.
def grab_filt(self, filt, analyte=None): """ Flexible access to specific filter using any key format. Parameters ---------- f : str, dict or bool either logical filter expression, dict of expressions, or a boolean analyte : str name of...
Extract filter components for specific analyte ( s ).
def get_components(self, key, analyte=None): """ Extract filter components for specific analyte(s). Parameters ---------- key : str string present in one or more filter names. e.g. 'Al27' will return all filters with 'Al27' in their names. ...
Get info for all filters.
def get_info(self): """ Get info for all filters. """ out = '' for k in sorted(self.components.keys()): out += '{:s}: {:s}'.format(k, self.info[k]) + '\n' return(out)
Load data_file described by a dataformat dict.
def read_data(data_file, dataformat, name_mode): """ Load data_file described by a dataformat dict. Parameters ---------- data_file : str Path to data file, including extension. dataformat : dict A dataformat dict, see example below. name_mode : str How to identyfy s...
Function for plotting Test User and LAtools data comparison.
def residual_plots(df, rep_stats=None, els=['Mg', 'Sr', 'Al', 'Mn', 'Fe', 'Cu', 'Zn', 'B']): """ Function for plotting Test User and LAtools data comparison. Parameters ---------- df : pandas.DataFrame A dataframe containing reference ('X/Ca_r'), test user ('X/Ca_t') and LAtools ('...
Compute comparison stats for test and LAtools data. Population - level similarity assessed by a Kolmogorov - Smirnov test. Individual similarity assessed by a pairwise Wilcoxon signed rank test. Trends in residuals assessed by regression analysis where significance of the slope and intercept is determined by t - tests ...
def comparison_stats(df, els=None): """ Compute comparison stats for test and LAtools data. Population-level similarity assessed by a Kolmogorov-Smirnov test. Individual similarity assessed by a pairwise Wilcoxon signed rank test. Trends in residuals assessed by regression analysis, w...
Function for logging method calls and parameters
def _log(func): """ Function for logging method calls and parameters """ @wraps(func) def wrapper(self, *args, **kwargs): a = func(self, *args, **kwargs) self.log.append(func.__name__ + ' :: args={} kwargs={}'.format(args, kwargs)) return a return wrapper
Write and analysis log to a file.
def write_logfile(log, header, file_name): """ Write and analysis log to a file. Parameters ---------- log : list latools.analyse analysis log header : list File header lines. file_name : str Destination file. If no file extension specified, uses '.lalog' ...
Reads an latools analysis. log file and returns dicts of arguments.
def read_logfile(log_file): """ Reads an latools analysis.log file, and returns dicts of arguments. Parameters ---------- log_file : str Path to an analysis.log file produced by latools. Returns ------- runargs, paths : tuple Two dictionaries. runargs contains all t...
Compresses the target directory and saves it to../ name. zip
def zipdir(directory, name=None, delete=False): """ Compresses the target directory, and saves it to ../name.zip Parameters ---------- directory : str Path to the directory you want to compress. Compressed file will be saved at directory/../name.zip name : str (default=None) ...
Extract contents of zip file into subfolder in parent directory. Parameters ---------- zip_file: str Path to zip file Returns ------- str: folder where the zip was extracted
def extract_zipdir(zip_file): """ Extract contents of zip file into subfolder in parent directory. Parameters ---------- zip_file : str Path to zip file Returns ------- str : folder where the zip was extracted """ if not os.path.exists(zip_file): rai...
Decorator that will try to login and redo an action before failing.
def autologin(function, timeout=TIMEOUT): """Decorator that will try to login and redo an action before failing.""" @wraps(function) async def wrapper(self, *args, **kwargs): """Wrap a function with timeout.""" try: async with async_timeout.timeout(timeout): retur...
Example of printing the inbox.
async def get_information(): """Example of printing the inbox.""" jar = aiohttp.CookieJar(unsafe=True) websession = aiohttp.ClientSession(cookie_jar=jar) modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession) await modem.login(password=sys.argv[2]) result = await modem.informa...
Example of sending a message.
async def send_message(): """Example of sending a message.""" jar = aiohttp.CookieJar(unsafe=True) websession = aiohttp.ClientSession(cookie_jar=jar) modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession) await modem.login(password=sys.argv[2]) await modem.sms(phone=sys.argv[3...
Example of printing the current upstream.
async def get_information(): """Example of printing the current upstream.""" jar = aiohttp.CookieJar(unsafe=True) websession = aiohttp.ClientSession(cookie_jar=jar) try: modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession) await modem.login(password=sys.argv[2]) ...
Example of printing the current upstream.
async def set_failover_mode(mode): """Example of printing the current upstream.""" jar = aiohttp.CookieJar(unsafe=True) websession = aiohttp.ClientSession(cookie_jar=jar) try: modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession) await modem.login(password=sys.argv[2])...
Parse a file - like object or string.
def parse(file_or_string): """Parse a file-like object or string. Args: file_or_string (file, str): File-like object or string. Returns: ParseResults: instance of pyparsing parse results. """ from mysqlparse.grammar.sql_file import sql_file_syntax if hasattr(file_or_string, 'r...
Return the link to the Jupyter nbviewer for the given notebook url
def nbviewer_link(url): """Return the link to the Jupyter nbviewer for the given notebook url""" if six.PY2: from urlparse import urlparse as urlsplit else: from urllib.parse import urlsplit info = urlsplit(url) domain = info.netloc url_type = 'github' if domain == 'github.com' e...
The string for creating the thumbnail of this example
def thumbnail_div(self): """The string for creating the thumbnail of this example""" return self.THUMBNAIL_TEMPLATE.format( snippet=self.get_description()[1], thumbnail=self.thumb_file, ref_name=self.reference)
The string for creating a code example for the gallery
def code_div(self): """The string for creating a code example for the gallery""" code_example = self.code_example if code_example is None: return None return self.CODE_TEMPLATE.format( snippet=self.get_description()[1], code=code_example, ref_name=self...
The code example out of the notebook metadata
def code_example(self): """The code example out of the notebook metadata""" if self._code_example is not None: return self._code_example return getattr(self.nb.metadata, 'code_example', None)
The supplementary files of this notebook
def supplementary_files(self): """The supplementary files of this notebook""" if self._supplementary_files is not None: return self._supplementary_files return getattr(self.nb.metadata, 'supplementary_files', None)
The supplementary files of this notebook
def other_supplementary_files(self): """The supplementary files of this notebook""" if self._other_supplementary_files is not None: return self._other_supplementary_files return getattr(self.nb.metadata, 'other_supplementary_files', None)
The url on jupyter nbviewer for this notebook or None if unknown
def url(self): """The url on jupyter nbviewer for this notebook or None if unknown""" if self._url is not None: url = self._url else: url = getattr(self.nb.metadata, 'url', None) if url is not None: return nbviewer_link(url)
get the output file with the specified ending
def get_out_file(self, ending='rst'): """get the output file with the specified `ending`""" return os.path.splitext(self.outfile)[0] + os.path.extsep + ending
Process the notebook and create all the pictures and files
def process_notebook(self, disable_warnings=True): """Process the notebook and create all the pictures and files This method runs the notebook using the :mod:`nbconvert` and :mod:`nbformat` modules. It creates the :attr:`outfile` notebook, a python and a rst file""" infile = sel...
Create the rst file from the notebook node
def create_rst(self, nb, in_dir, odir): """Create the rst file from the notebook node""" raw_rst, resources = nbconvert.export_by_name('rst', nb) # remove ipython magics rst_content = '' i0 = 0 m = None # HACK: we insert the bokeh style sheets here as well, since ...
Create the python script from the notebook node
def create_py(self, nb, force=False): """Create the python script from the notebook node""" # Although we would love to simply use ``nbconvert.export_python(nb)`` # this causes troubles in other cells processed by the ipython # directive. Instead of getting something like ``Out [5]:``, w...
Create the rst string to download supplementary data
def data_download(self, files): """Create the rst string to download supplementary data""" if len(files) > 1: return self.DATA_DOWNLOAD % ( ('\n\n' + ' '*8) + ('\n' + ' '*8).join( '* :download:`%s`' % f for f in files)) return self.DATA_DOWNLOAD % ...
Create the thumbnail for html output
def create_thumb(self): """Create the thumbnail for html output""" thumbnail_figure = self.copy_thumbnail_figure() if thumbnail_figure is not None: if isinstance(thumbnail_figure, six.string_types): pic = thumbnail_figure else: pic = self.p...
Get summary and description of this notebook
def get_description(self): """Get summary and description of this notebook""" def split_header(s, get_header=True): s = s.lstrip().rstrip() parts = s.splitlines() if parts[0].startswith('#'): if get_header: header = re.sub('#+\s*', ...
Scales an image with the same aspect ratio centered in an image with a given max_width and max_height if in_fname == out_fname the image can only be scaled down
def scale_image(self, in_fname, out_fname, max_width, max_height): """Scales an image with the same aspect ratio centered in an image with a given max_width and max_height if in_fname == out_fname the image can only be scaled down """ # local import to avoid testing depende...
Save the thumbnail image
def save_thumbnail(self, image_path): """Save the thumbnail image""" thumb_dir = os.path.join(os.path.dirname(image_path), 'thumb') create_dirs(thumb_dir) thumb_file = os.path.join(thumb_dir, '%s_thumb.png' % self.reference) if os.path.exists(im...
The integer of the thumbnail figure
def copy_thumbnail_figure(self): """The integer of the thumbnail figure""" ret = None if self._thumbnail_figure is not None: if not isstring(self._thumbnail_figure): ret = self._thumbnail_figure else: ret = osp.join(osp.dirname(self.outfile...
Create the rst files from the input directories in the: attr: in_dir attribute
def process_directories(self): """Create the rst files from the input directories in the :attr:`in_dir` attribute""" for i, (base_dir, target_dir, paths) in enumerate(zip( self.in_dir, self.out_dir, map(os.walk, self.in_dir))): self._in_dir_count = i self....
Method to recursivly process the notebooks in the base_dir
def recursive_processing(self, base_dir, target_dir, it): """Method to recursivly process the notebooks in the `base_dir` Parameters ---------- base_dir: str Path to the base example directory (see the `examples_dir` parameter for the :class:`Gallery` class) ...
Class method to create a: class: Gallery instance from the configuration of a sphinx application
def from_sphinx(cls, app): """Class method to create a :class:`Gallery` instance from the configuration of a sphinx application""" app.config.html_static_path.append(os.path.join( os.path.dirname(__file__), '_static')) config = app.config.example_gallery_config inser...
Return the url corresponding to the given notebook file
def get_url(self, nbfile): """Return the url corresponding to the given notebook file Parameters ---------- nbfile: str The path of the notebook relative to the corresponding :attr:``in_dir`` Returns ------- str or None The ur...
command execution
def handle(self, *args, **options): """ command execution """ assume_yes = options.get('assume_yes', False) default_language = options.get('default_language', None) # set manual transaction management transaction.commit_unless_managed() transaction.enter_transaction_mana...
get only db changes fields
def get_db_change_languages(self, field_name, db_table_fields): """ get only db changes fields """ for lang_code, lang_name in get_languages(): if get_real_fieldname(field_name, lang_code) not in db_table_fields: yield lang_code for db_table_field in db_table_fields: ...
returns SQL needed for sync schema for a new translatable field
def get_sync_sql(self, field_name, db_change_langs, model, db_table_fields): """ returns SQL needed for sync schema for a new translatable field """ qn = connection.ops.quote_name style = no_style() sql_output = [] db_table = model._meta.db_table was_translatable_before =...
returns all translatable fields in a model ( including superclasses ones )
def get_all_translatable_fields(model, model_trans_fields=None, column_in_current_table=False): """ returns all translatable fields in a model (including superclasses ones) """ if model_trans_fields is None: model_trans_fields = set() model_trans_fields.update(set(getattr(model._meta, 'translatable_...
When accessing to the name of the field itself the value in the current language will be returned. Unless it s set the value in the default language will be returned.
def default_value(field): ''' When accessing to the name of the field itself, the value in the current language will be returned. Unless it's set, the value in the default language will be returned. ''' def default_value_func(self): attname = lambda x: get_real_fieldname(field, x) ...
Post processors are functions that receive file objects performs necessary operations and return the results as file objects.
def process(thumbnail_file, size, **kwargs): """ Post processors are functions that receive file objects, performs necessary operations and return the results as file objects. """ from . import conf size_dict = conf.SIZES[size] for processor in size_dict['POST_PROCESSORS']: processo...
A post processing function to optimize file size. Accepts commands to optimize JPG PNG and GIF images as arguments. Example:
def optimize(thumbnail_file, jpg_command=None, png_command=None, gif_command=None): """ A post processing function to optimize file size. Accepts commands to optimize JPG, PNG and GIF images as arguments. Example: THUMBNAILS = { # Other options... 'POST_PROCESSORS': [ ...
Return an attribute from a dotted path name ( e. g. path. to. func ). Copied from nvie s rq https:// github. com/ nvie/ rq/ blob/ master/ rq/ utils. py
def import_attribute(name): """ Return an attribute from a dotted path name (e.g. "path.to.func"). Copied from nvie's rq https://github.com/nvie/rq/blob/master/rq/utils.py """ if hasattr(name, '__call__'): return name module_name, attribute = name.rsplit('.', 1) module = importlib.im...
Returns a dictionary that contains the imported processors and kwargs. For example passing in:
def parse_processors(processor_definition): """ Returns a dictionary that contains the imported processors and kwargs. For example, passing in: processors = [ {'processor': 'thumbnails.processors.resize', 'width': 10, 'height': 10}, {'processor': 'thumbnails.processors.crop', 'width': 1...
Process an image through its defined processors params: file: filename or file - like object params: size: string for size defined in settings return a ContentFile
def process(file, size): """ Process an image through its defined processors params :file: filename or file-like object params :size: string for size defined in settings return a ContentFile """ from . import conf # open image in piccaso raw_image = images.from_file(file) # run ...
Process the source image through the defined processors.
def pre_save(self, model_instance, add): """ Process the source image through the defined processors. """ file = getattr(model_instance, self.attname) if file and not file._committed: image_file = file if self.resize_source_to: file.seek(0...
Populate self. _thumbnails.
def _refresh_cache(self): """Populate self._thumbnails.""" self._thumbnails = {} metadatas = self.metadata_backend.get_thumbnails(self.source_image.name) for metadata in metadatas: self._thumbnails[metadata.size] = Thumbnail(metadata=metadata, storage=self.storage)
Return all thumbnails in a dict format.
def all(self): """ Return all thumbnails in a dict format. """ if self._thumbnails is not None: return self._thumbnails self._refresh_cache() return self._thumbnails
Returns a Thumbnail instance. First check whether thumbnail is already cached. If it doesn t: 1. Try to fetch the thumbnail 2. Create thumbnail if it s not present 3. Cache the thumbnail for future use
def get(self, size, create=True): """ Returns a Thumbnail instance. First check whether thumbnail is already cached. If it doesn't: 1. Try to fetch the thumbnail 2. Create thumbnail if it's not present 3. Cache the thumbnail for future use """ if self._thu...
Creates and return a thumbnail of a given size.
def create(self, size): """ Creates and return a thumbnail of a given size. """ thumbnail = images.create(self.source_image.name, size, self.metadata_backend, self.storage) return thumbnail
Deletes a thumbnail of a given size
def delete(self, size): """ Deletes a thumbnail of a given size """ images.delete(self.source_image.name, size, self.metadata_backend, self.storage) del(self._thumbnails[size])
Creates a thumbnail file and its relevant metadata. Returns a Thumbnail instance.
def create(source_name, size, metadata_backend=None, storage_backend=None): """ Creates a thumbnail file and its relevant metadata. Returns a Thumbnail instance. """ if storage_backend is None: storage_backend = backends.storage.get_backend() if metadata_backend is None: metadat...
Returns a Thumbnail instance or None if thumbnail does not yet exist.
def get(source_name, size, metadata_backend=None, storage_backend=None): """ Returns a Thumbnail instance, or None if thumbnail does not yet exist. """ if storage_backend is None: storage_backend = backends.storage.get_backend() if metadata_backend is None: metadata_backend = backend...
Deletes a thumbnail file and its relevant metadata.
def delete(source_name, size, metadata_backend=None, storage_backend=None): """ Deletes a thumbnail file and its relevant metadata. """ if storage_backend is None: storage_backend = backends.storage.get_backend() if metadata_backend is None: metadata_backend = backends.metadata.get_b...
Simulate an incoming message
def received(self, src, body): """ Simulate an incoming message :type src: str :param src: Message source :type boby: str | unicode :param body: Message body :rtype: IncomingMessage """ # Create the message self._msgid += 1 ...
Register a virtual subscriber which receives messages to the matching number.
def subscribe(self, number, callback): """ Register a virtual subscriber which receives messages to the matching number. :type number: str :param number: Subscriber phone number :type callback: callable :param callback: A callback(OutgoingMessage) which handles t...
Get the set of states. Mostly used for pretty printing
def states(self): """ Get the set of states. Mostly used for pretty printing :rtype: set :returns: Set of 'accepted', 'delivered', 'expired', 'error' """ ret = set() if self.accepted: ret.add('accepted') if self.delivered: ret.add(...
Register a provider on the gateway
def add_provider(self, name, Provider, **config): """ Register a provider on the gateway The first provider defined becomes the default one: used in case the routing function has no better idea. :type name: str :param name: Provider name that will be used to uniquely identi...
Send a message object
def send(self, message): """ Send a message object :type message: data.OutgoingMessage :param message: The message to send :rtype: data.OutgoingMessage :returns: The sent message with populated fields :raises AssertionError: wrong provider name encoun...
Get a Flask blueprint for the named provider that handles incoming messages & status reports
def receiver_blueprint_for(self, name): """ Get a Flask blueprint for the named provider that handles incoming messages & status reports Note: this requires Flask microframework. :rtype: flask.blueprints.Blueprint :returns: Flask Blueprint, fully functional :rai...
Get Flask blueprints for every provider that supports it
def receiver_blueprints(self): """ Get Flask blueprints for every provider that supports it Note: this requires Flask microframework. :rtype: dict :returns: A dict { provider-name: Blueprint } """ blueprints = {} for name in self._providers: ...
Register all provider receivers on the provided Flask application under/ { prefix }/ provider - name
def receiver_blueprints_register(self, app, prefix='/'): """ Register all provider receivers on the provided Flask application under '/{prefix}/provider-name' Note: this requires Flask microframework. :type app: flask.Flask :param app: Flask app to register the blueprints o...
Incoming message callback
def _receive_message(self, message): """ Incoming message callback Calls Gateway.onReceive event hook Providers are required to: * Cast phone numbers to digits-only * Support both ASCII and Unicode messages * Populate `message.msgid` and `message.met...
Incoming status callback
def _receive_status(self, status): """ Incoming status callback Calls Gateway.onStatus event hook Providers are required to: * Cast phone numbers to digits-only * Use proper MessageStatus subclasses * Populate `status.msgid` and `status.meta` fields ...
Incoming message handler: forwarded by ForwardServerProvider
def im(): """ Incoming message handler: forwarded by ForwardServerProvider """ req = jsonex_loads(request.get_data()) message = g.provider._receive_message(req['message']) return {'message': message}
Incoming status handler: forwarded by ForwardServerProvider
def status(): """ Incoming status handler: forwarded by ForwardServerProvider """ req = jsonex_loads(request.get_data()) status = g.provider._receive_status(req['status']) return {'status': status}
Unserialize with JsonEx: rtype: dict
def jsonex_loads(s): """ Unserialize with JsonEx :rtype: dict """ return json.loads(s.decode('utf-8'), cls=JsonExDecoder, classes=classes, exceptions=exceptions)
View wrapper for JsonEx responses. Catches exceptions as well
def jsonex_api(f): """ View wrapper for JsonEx responses. Catches exceptions as well """ @wraps(f) def wrapper(*args, **kwargs): # Call, catch exceptions try: code, res = 200, f(*args, **kwargs) except HTTPException as e: code, res = e.code, {'error': e} ...
Parse authentication data from the URL and put it in the headers dict. With caching behavior: param url: URL: type url: str: return: ( URL without authentication info headers dict ): rtype: str dict
def _parse_authentication(url): """ Parse authentication data from the URL and put it in the `headers` dict. With caching behavior :param url: URL :type url: str :return: (URL without authentication info, headers dict) :rtype: str, dict """ u = url h = {} # New headers # Cache? ...
Make a request with JsonEx: param url: URL: type url: str: param data: Data to POST: type data: dict: return: Response: rtype: dict: raises exc. ConnectionError: Connection error: raises exc. ServerError: Remote server error ( unknown ): raises exc. ProviderError: any errors reported by the remote
def jsonex_request(url, data, headers=None): """ Make a request with JsonEx :param url: URL :type url: str :param data: Data to POST :type data: dict :return: Response :rtype: dict :raises exc.ConnectionError: Connection error :raises exc.ServerError: Remote server error (unknown) ...
Send a message by forwarding it to the server: param message: Message: type message: smsframework. data. OutgoingMessage: rtype: smsframework. data. OutgoingMessage: raise Exception: any exception reported by the other side: raise urllib2. URLError: Connection error
def send(self, message): """ Send a message by forwarding it to the server :param message: Message :type message: smsframework.data.OutgoingMessage :rtype: smsframework.data.OutgoingMessage :raise Exception: any exception reported by the other side :raise urllib2.URLError...
Forward an object to client: type client: str: type obj: smsframework. data. IncomingMessage|smsframework. data. MessageStatus: rtype: smsframework. data. IncomingMessage|smsframework. data. MessageStatus: raise Exception: any exception reported by the other side
def _forward_object_to_client(self, client, obj): """ Forward an object to client :type client: str :type obj: smsframework.data.IncomingMessage|smsframework.data.MessageStatus :rtype: smsframework.data.IncomingMessage|smsframework.data.MessageStatus :raise Exception: any excepti...
Forward an object to clients.
def forward(self, obj): """ Forward an object to clients. :param obj: The object to be forwarded :type obj: smsframework.data.IncomingMessage|smsframework.data.MessageStatus :raises Exception: if any of the clients failed """ assert isinstance(obj, (IncomingMessage, Mess...
Returns a dictionnary of dictionnary that contains critical information about the transport and protocol behavior such as: * amount of received frames * amount of badly delimited frames * amount of correctly delimited but still corrupted frames * etc
def stats(self): """ Returns a dictionnary of dictionnary that contains critical information about the transport and protocol behavior, such as: * amount of received frames * amount of badly delimited frames * amount of correctly delimited but still corrupted frames * etc """ d = dic...
Get balance of address for erc20_address: param address: owner address: param erc20_address: erc20 token address: return: balance
def get_balance(self, address: str, erc20_address: str) -> int: """ Get balance of address for `erc20_address` :param address: owner address :param erc20_address: erc20 token address :return: balance """ return get_erc20_contract(self.w3, erc20_address).functions....
Get erc20 information ( name symbol and decimals ): param erc20_address:: return: Erc20_Info
def get_info(self, erc20_address: str) -> Erc20_Info: """ Get erc20 information (`name`, `symbol` and `decimals`) :param erc20_address: :return: Erc20_Info """ # We use the `example erc20` as the `erc20 interface` doesn't have `name`, `symbol` nor `decimals` erc20...
Get events for erc20 transfers. At least one of from_address to_address or token_address must be defined An example of event: { args: { from: 0x1Ce67Ea59377A163D47DFFc9BaAB99423BE6EcF1 to: 0xaE9E15896fd32E59C7d89ce7a95a9352D6ebD70E value: 15000000000000000 } event: Transfer logIndex: 42 transactionIndex: 60 transaction...
def get_transfer_history(self, from_block: int, to_block: Optional[int] = None, from_address: Optional[str] = None, to_address: Optional[str] = None, token_address: Optional[str] = None) -> List[Dict[str, any]]: """ Get events for erc20 transfers...
Send tokens to address: param to:: param amount:: param erc20_address:: param private_key:: return: tx_hash
def send_tokens(self, to: str, amount: int, erc20_address: str, private_key: str) -> bytes: """ Send tokens to address :param to: :param amount: :param erc20_address: :param private_key: :return: tx_hash """ erc20 = get_erc20_contract(self.w3, erc2...
: param from_block: Quantity or Tag - ( optional ) From this block. 0 is not working it needs to be > = 1: param to_block: Quantity or Tag - ( optional ) To this block.: param from_address: Array - ( optional ) Sent from these addresses.: param to_address: Address - ( optional ) Sent to these addresses.: param after: Q...
def trace_filter(self, from_block: int = 1, to_block: Optional[int] = None, from_address: Optional[List[str]] = None, to_address: Optional[List[str]] = None, after: Optional[int] = None, count: Optional[int] = None) -> List[Dict[str, any]]: """ :param from_block...
Get web3 provider for slow queries. Default HTTPProvider timeouts after 10 seconds: param provider: Configured Web3 provider: param timeout: Timeout to configure for internal requests ( default is 10 ): return: A new web3 provider with the slow_provider_timeout
def get_slow_provider(self, timeout: int): """ Get web3 provider for slow queries. Default `HTTPProvider` timeouts after 10 seconds :param provider: Configured Web3 provider :param timeout: Timeout to configure for internal requests (default is 10) :return: A new web3 provider wi...
Send a tx using an unlocked public key in the node or a private key. Both public_key and private_key cannot be None: param tx:: param private_key:: param public_key:: param retry: Retry if a problem with nonce is found: param block_identifier:: return: tx hash
def send_unsigned_transaction(self, tx: Dict[str, any], private_key: Optional[str] = None, public_key: Optional[str] = None, retry: bool = False, block_identifier: Optional[str] = None) -> bytes: """ Send a tx using an unlocked public k...
Send ether using configured account: param to: to: param gas_price: gas_price: param value: value ( wei ): param gas: gas defaults to 22000: param retry: Retry if a problem is found: param block_identifier: None default pending not confirmed txs: return: tx_hash
def send_eth_to(self, private_key: str, to: str, gas_price: int, value: int, gas: int=22000, retry: bool = False, block_identifier=None, max_eth_to_send: int = 0) -> bytes: """ Send ether using configured account :param to: to :param gas_price: gas_price :para...
Check tx hash and make sure it has the confirmations required: param w3: Web3 instance: param tx_hash: Hash of the tx: param confirmations: Minimum number of confirmations required: return: True if tx was mined with the number of confirmations required False otherwise
def check_tx_with_confirmations(self, tx_hash: str, confirmations: int) -> bool: """ Check tx hash and make sure it has the confirmations required :param w3: Web3 instance :param tx_hash: Hash of the tx :param confirmations: Minimum number of confirmations required :retur...
: return: checksum encoded address starting by 0x for example 0x568c93675A8dEb121700A6FAdDdfE7DFAb66Ae4A: rtype: str
def get_signing_address(hash: Union[bytes, str], v: int, r: int, s: int) -> str: """ :return: checksum encoded address starting by 0x, for example `0x568c93675A8dEb121700A6FAdDdfE7DFAb66Ae4A` :rtype: str """ encoded_64_address = ecrecover_to_pub(hash, v, r, s) address_byt...
Generates an address for a contract created using CREATE2.: param from_: The address which is creating this new address ( need to be 20 bytes ): param salt: A salt ( 32 bytes ): param init_code: A init code of the contract being created: return: Address of the new contract
def generate_address_2(from_: Union[str, bytes], salt: Union[str, bytes], init_code: [str, bytes]) -> str: """ Generates an address for a contract created using CREATE2. :param from_: The address which is creating this new address (need to be 20 bytes) :param salt: A salt (32 bytes) :param init_code...