INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Execute command on * Vim *... warning:: Do not use redir command if capture is True. It s already enabled for internal use. | def command(self, command, capture=True):
"""
Execute command on *Vim*.
.. warning:: Do not use ``redir`` command if ``capture`` is ``True``.
It's already enabled for internal use.
If ``capture`` argument is set ``False``,
the command execution becomes slightly faster.
... |
Set * Vim * mode to mode. Supported modes: | def set_mode(self, mode):
"""
Set *Vim* mode to ``mode``.
Supported modes:
* ``normal``
* ``insert``
* ``command``
* ``visual``
* ``visual-block``
This method behave as setter-only property.
Example:
>>> import headlessvim
... |
: param size: ( lines columns ) tuple of a screen connected to * Vim *.: type size: ( int int ) | def screen_size(self, size):
"""
:param size: (lines, columns) tuple of a screen connected to *Vim*.
:type size: (int, int)
"""
if self.screen_size != size:
self._screen.resize(*self._swap(size)) |
: return: runtime path of * Vim *: rtype: runtimepath. RuntimePath | def runtimepath(self):
"""
:return: runtime path of *Vim*
:rtype: runtimepath.RuntimePath
"""
if self._runtimepath is None:
self._runtimepath = runtimepath.RuntimePath(self)
return self._runtimepath |
If the file - object is not seekable return ArchiveTemp of the fileobject otherwise return the file - object itself | def make_seekable(fileobj):
"""
If the file-object is not seekable, return ArchiveTemp of the fileobject,
otherwise return the file-object itself
"""
if sys.version_info < (3, 0) and isinstance(fileobj, file):
filename = fileobj.name
fileobj = io.FileIO(fileobj.fileno(), closefd=Fal... |
Setup before_request after_request handlers for tracing. | def init_app(self, app):
"""Setup before_request, after_request handlers for tracing.
"""
app.config.setdefault("TRACY_REQUIRE_CLIENT", False)
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['restpoints'] = self
app.before_request(self._... |
Records the starting time of this reqeust. | def _before(self):
"""Records the starting time of this reqeust.
"""
# Don't trace excluded routes.
if request.path in self.excluded_routes:
request._tracy_exclude = True
return
request._tracy_start_time = monotonic()
client = request.headers.get(... |
Calculates the request duration and adds a transaction ID to the header. | def _after(self, response):
"""Calculates the request duration, and adds a transaction
ID to the header.
"""
# Ignore excluded routes.
if getattr(request, '_tracy_exclude', False):
return response
duration = None
if getattr(request, '_tracy_start_time... |
Close the http/ https connect. | def close(self):
"""Close the http/https connect."""
try:
self.response.close()
self.logger.debug("close connect succeed.")
except Exception as e:
self.unknown("close connect error: %s" % e) |
IMPORTANT: expects path s parent to already be deref () erenced. | def _stat(self, path):
'''IMPORTANT: expects `path`'s parent to already be deref()'erenced.'''
if path not in self.entries:
return OverlayStat(*self.originals['os:stat'](path)[:10], st_overlay=0)
st = self.entries[path].stat
if stat.S_ISLNK(st.st_mode):
return self._stat(self.deref(path))
... |
IMPORTANT: expects path s parent to already be deref () erenced. | def _lstat(self, path):
'''IMPORTANT: expects `path`'s parent to already be deref()'erenced.'''
if path not in self.entries:
return OverlayStat(*self.originals['os:lstat'](path)[:10], st_overlay=0)
return self.entries[path].stat |
IMPORTANT: expects path to already be deref () erenced. | def _exists(self, path):
'''IMPORTANT: expects `path` to already be deref()'erenced.'''
try:
return bool(self._stat(path))
except os.error:
return False |
IMPORTANT: expects path to already be deref () erenced. | def _lexists(self, path):
'''IMPORTANT: expects `path` to already be deref()'erenced.'''
try:
return bool(self._lstat(path))
except os.error:
return False |
overlays os. path. exists () | def fso_exists(self, path):
'overlays os.path.exists()'
try:
return self._exists(self.deref(path))
except os.error:
return False |
overlays os. path. lexists () | def fso_lexists(self, path):
'overlays os.path.lexists()'
try:
return self._lexists(self.deref(path, to_parent=True))
except os.error:
return False |
overlays os. listdir () | def fso_listdir(self, path):
'overlays os.listdir()'
path = self.deref(path)
if not stat.S_ISDIR(self._stat(path).st_mode):
raise OSError(20, 'Not a directory', path)
try:
ret = self.originals['os:listdir'](path)
except Exception:
# assuming that `path` was created within this FSO.... |
overlays os. mkdir () | def fso_mkdir(self, path, mode=None):
'overlays os.mkdir()'
path = self.deref(path, to_parent=True)
if self._lexists(path):
raise OSError(17, 'File exists', path)
self._addentry(OverlayEntry(self, path, stat.S_IFDIR)) |
overlays os. makedirs () | def fso_makedirs(self, path, mode=None):
'overlays os.makedirs()'
path = self.abs(path)
cur = '/'
segments = path.split('/')
for idx, seg in enumerate(segments):
cur = os.path.join(cur, seg)
try:
st = self.fso_stat(cur)
except OSError:
st = None
if st is None:... |
overlays os. rmdir () | def fso_rmdir(self, path):
'overlays os.rmdir()'
st = self.fso_lstat(path)
if not stat.S_ISDIR(st.st_mode):
raise OSError(20, 'Not a directory', path)
if len(self.fso_listdir(path)) > 0:
raise OSError(39, 'Directory not empty', path)
self._addentry(OverlayEntry(self, path, None)) |
overlays os. readlink () | def fso_readlink(self, path):
'overlays os.readlink()'
path = self.deref(path, to_parent=True)
st = self.fso_lstat(path)
if not stat.S_ISLNK(st.st_mode):
raise OSError(22, 'Invalid argument', path)
if st.st_overlay:
return self.entries[path].content
return self.originals['os:readlink... |
overlays os. symlink () | def fso_symlink(self, source, link_name):
'overlays os.symlink()'
path = self.deref(link_name, to_parent=True)
if self._exists(path):
raise OSError(17, 'File exists')
self._addentry(OverlayEntry(self, path, stat.S_IFLNK, source)) |
overlays os. unlink () | def fso_unlink(self, path):
'overlays os.unlink()'
path = self.deref(path, to_parent=True)
if not self._lexists(path):
raise OSError(2, 'No such file or directory', path)
self._addentry(OverlayEntry(self, path, None)) |
overlays os. path. islink () | def fso_islink(self, path):
'overlays os.path.islink()'
try:
return stat.S_ISLNK(self.fso_lstat(path).st_mode)
except OSError:
return False |
overlays shutil. rmtree () | def fso_rmtree(self, path, ignore_errors=False, onerror=None):
'overlays shutil.rmtree()'
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
try:
if self.fso_islink(path):
# symlinks to directories are forbidden, see shuti... |
MWAPIWrapper 控制API请求异常的装饰器 根据requests库定义的异常来控制请求返回的意外情况 | def MWAPIWrapper(func):
"""
MWAPIWrapper 控制API请求异常的装饰器
根据requests库定义的异常来控制请求返回的意外情况
"""
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
try:
result = func(*args, **kwargs)
return result
except ConnectionError:
err_title = '连接错... |
Insert spaces between words until it is wide enough for width. | def expand_words(self, line, width=60):
""" Insert spaces between words until it is wide enough for `width`.
"""
if not line.strip():
return line
# Word index, which word to insert on (cycles between 1->len(words))
wordi = 1
while len(strip_codes(line)) < widt... |
This is a helper method for self. expand_words (). Finds the index of word endings ( default is first word ). The last word doesn t count. If there are no words or there are no spaces in the word it returns - 1. | def find_word_end(text, count=1):
""" This is a helper method for self.expand_words().
Finds the index of word endings (default is first word).
The last word doesn't count.
If there are no words, or there are no spaces in the word, it
returns -1.
This... |
Format a long string into a block of newline seperated text. Arguments: See iter_format_block (). | def format(
self, text=None,
width=60, chars=False, fill=False, newlines=False,
prepend=None, append=None, strip_first=False, strip_last=False,
lstrip=False):
""" Format a long string into a block of newline seperated text.
Arguments:
S... |
Prepend or append text to lines. Yields each line. | def iter_add_text(self, lines, prepend=None, append=None):
""" Prepend or append text to lines. Yields each line. """
if (prepend is None) and (append is None):
yield from lines
else:
# Build up a format string, with optional {prepend}/{append}
fmtpcs = ['{pre... |
Iterator that turns a long string into lines no greater than width in length. It can wrap on spaces or characters. It only does basic blocks. For prepending see iter_format_block (). | def iter_block(
self, text=None,
width=60, chars=False, newlines=False, lstrip=False):
""" Iterator that turns a long string into lines no greater than
'width' in length.
It can wrap on spaces or characters. It only does basic blocks.
For prepending se... |
Format block by splitting on individual characters. | def iter_char_block(self, text=None, width=60, fmtfunc=str):
""" Format block by splitting on individual characters. """
if width < 1:
width = 1
text = (self.text if text is None else text) or ''
text = ' '.join(text.split('\n'))
escapecodes = get_codes(text)
... |
Iterate over lines in a formatted block of text. This iterator allows you to prepend to each line. For basic blocks see iter_block (). | def iter_format_block(
self, text=None,
width=60, chars=False, fill=False, newlines=False,
append=None, prepend=None, strip_first=False, strip_last=False,
lstrip=False):
""" Iterate over lines in a formatted block of text.
This iterator allows you to p... |
Format block by wrapping on spaces. | def iter_space_block(self, text=None, width=60, fmtfunc=str):
""" Format block by wrapping on spaces. """
if width < 1:
width = 1
curline = ''
text = (self.text if text is None else text) or ''
for word in text.split():
possibleline = ' '.join((curline, wo... |
Remove spaces in between words until it is small enough for width. This will always leave at least one space between words so it may not be able to get below width characters. | def squeeze_words(line, width=60):
""" Remove spaces in between words until it is small enough for
`width`.
This will always leave at least one space between words,
so it may not be able to get below `width` characters.
"""
# Start removing spaces to "squeeze"... |
Check IP trough the httpBL API | def check_ip(self, ip):
"""
Check IP trough the httpBL API
:param ip: ipv4 ip address
:return: httpBL results or None if any error is occurred
"""
self._last_result = None
if is_valid_ipv4(ip):
key = None
if self._use_cache:
... |
Check if IP is a threat | def is_threat(self, result=None, harmless_age=None, threat_score=None, threat_type=None):
"""
Check if IP is a threat
:param result: httpBL results; if None, then results from last check_ip() used (optional)
:param harmless_age: harmless age for check if httpBL age is older (optional)
... |
Check if IP is suspicious | def is_suspicious(self, result=None):
"""
Check if IP is suspicious
:param result: httpBL results; if None, then results from last check_ip() used (optional)
:return: True or False
"""
result = result if result is not None else self._last_result
suspicious = Fal... |
Invalidate httpBL cache for IP address | def invalidate_ip(self, ip):
"""
Invalidate httpBL cache for IP address
:param ip: ipv4 IP address
"""
if self._use_cache:
key = self._make_cache_key(ip)
self._cache.delete(key, version=self._cache_version) |
Invalidate httpBL cache | def invalidate_cache(self):
"""
Invalidate httpBL cache
"""
if self._use_cache:
self._cache_version += 1
self._cache.increment('cached_httpbl_{0}_version'.format(self._api_key)) |
Runs the consumer. | def run(self):
"""Runs the consumer."""
self.log.debug('consumer is running...')
self.running = True
while self.running:
self.upload()
self.log.debug('consumer exited.') |
Upload the next batch of items return whether successful. | def upload(self):
"""Upload the next batch of items, return whether successful."""
success = False
batch = self.next()
if len(batch) == 0:
return False
try:
self.request(batch)
success = True
except Exception as e:
self.log... |
Return the next batch of items to upload. | def next(self):
"""Return the next batch of items to upload."""
queue = self.queue
items = []
item = self.next_item()
if item is None:
return items
items.append(item)
while len(items) < self.upload_size and not queue.empty():
item = self.n... |
Get a single item from the queue. | def next_item(self):
"""Get a single item from the queue."""
queue = self.queue
try:
item = queue.get(block=True, timeout=5)
return item
except Exception:
return None |
Attempt to upload the batch and retry before raising an error | def request(self, batch, attempt=0):
"""Attempt to upload the batch and retry before raising an error """
try:
q = self.api.new_queue()
for msg in batch:
q.add(msg['event'], msg['value'], source=msg['source'])
q.submit()
except:
if ... |
Translate camelCase into underscore format. | def _camelcase_to_underscore(url):
"""
Translate camelCase into underscore format.
>>> _camelcase_to_underscore('minutesBetweenSummaries')
'minutes_between_summaries'
"""
def upper2underscore(text):
for char in text:
if char.islower():
yield char
... |
Creates the Trello endpoint tree. | def create_tree(endpoints):
"""
Creates the Trello endpoint tree.
>>> r = {'1': { \
'actions': {'METHODS': {'GET'}}, \
'boards': { \
'members': {'METHODS': {'DELETE'}}}} \
}
>>> r == create_tree([ \
'GET /1/actions/[idA... |
Prints the complete YAML. | def main():
"""
Prints the complete YAML.
"""
ep = requests.get(TRELLO_API_DOC).content
root = html.fromstring(ep)
links = root.xpath('//a[contains(@class, "reference internal")]/@href')
pages = [requests.get(TRELLO_API_DOC + u)
for u in links if u.endswith('index.html')]
... |
Override the default exit in the parser.: param parser:: param _: exit code. Unused because we don t exit: param message: Optional message | def _parser_exit(parser: argparse.ArgumentParser, proc: "DirectoryListProcessor", _=0,
message: Optional[str]=None) -> None:
"""
Override the default exit in the parser.
:param parser:
:param _: exit code. Unused because we don't exit
:param message: Optional message
"""
if... |
Preprocess any arguments that begin with the fromfile prefix char ( s ). This replaces the one in Argparse because it a ) doesn t process - x y correctly and b ) ignores bad files: param argv: raw options list: return: options list with file references replaced | def decode_file_args(self, argv: List[str]) -> List[str]:
"""
Preprocess any arguments that begin with the fromfile prefix char(s).
This replaces the one in Argparse because it
a) doesn't process "-x y" correctly and
b) ignores bad files
:param argv: raw options l... |
Report an error: param ifn: Input file name: param e: Exception to report | def _proc_error(ifn: str, e: Exception) -> None:
""" Report an error
:param ifn: Input file name
:param e: Exception to report
"""
type_, value_, traceback_ = sys.exc_info()
traceback.print_tb(traceback_, file=sys.stderr)
print(file=sys.stderr)
print("****... |
Call the actual processor and intercept anything that goes wrong: param proc: Process to call: param ifn: Input file name to process. If absent typical use is stdin: param ofn: Output file name. If absent typical use is stdout: return: true means process was successful | def _call_proc(self,
proc: Callable[[Optional[str], Optional[str], argparse.Namespace], bool],
ifn: Optional[str],
ofn: Optional[str]) -> bool:
""" Call the actual processor and intercept anything that goes wrong
:param proc: Process to call
... |
Run the directory list processor calling a function per file.: param proc: Process to invoke. Args: input_file_name output_file_name argparse options. Return pass or fail. No return also means pass: param file_filter: Additional filter for testing file names types etc.: param file_filter_2: File filter that includes di... | def run(self,
proc: Callable[[Optional[str], Optional[str], argparse.Namespace], Optional[bool]],
file_filter: Optional[Callable[[str], bool]]=None,
file_filter_2: Optional[Callable[[Optional[str], str, argparse.Namespace], bool]]=None) \
-> Tuple[int, int]:
""" R... |
Construct the output file name from the input file. If a single output file was named and there isn t a directory return the output file.: param dirpath: Directory path to infile: param infile: Name of input file: param outfile_idx: Index into output file list ( for multiple input/ output files ): return: Full name of ... | def _outfile_name(self, dirpath: str, infile: str, outfile_idx: int=0) -> Optional[str]:
""" Construct the output file name from the input file. If a single output file was named and there isn't a
directory, return the output file.
:param dirpath: Directory path to infile
:param infile:... |
Close and exit the connection. | def quit(self):
"""Close and exit the connection."""
try:
self.ftp.quit()
self.logger.debug("quit connect succeed.")
except ftplib.Error as e:
self.unknown("quit connect error: %s" % e) |
Connect by wmi and run wql. | def query(self, wql):
"""Connect by wmi and run wql."""
try:
self.__wql = ['wmic', '-U',
self.args.domain + '\\' + self.args.user + '%' + self.args.password,
'//' + self.args.host,
'--namespace', self.args.namespac... |
Changes the cached value and updates creation time. Args: value: the new cached value. timeout: time to live for the object in milliseconds Returns: None | def set_value(self, value, timeout):
"""
Changes the cached value and updates creation time.
Args:
value: the new cached value.
timeout: time to live for the object in milliseconds
Returns: None
"""
self.value = value
s... |
Wrapper for the other log methods decide which one based on the URL parameter. | def log(self, url=None, credentials=None, do_verify_certificate=True):
"""
Wrapper for the other log methods, decide which one based on the
URL parameter.
"""
if url is None:
url = self.url
if re.match("file://", url):
self.log_file(url)
el... |
Write to a local log file | def log_file(self, url=None):
"""
Write to a local log file
"""
if url is None:
url = self.url
f = re.sub("file://", "", url)
try:
with open(f, "a") as of:
of.write(str(self.store.get_json_tuples(True)))
except IOError as e:... |
Write to a remote host via HTTP POST | def log_post(self, url=None, credentials=None, do_verify_certificate=True):
"""
Write to a remote host via HTTP POST
"""
if url is None:
url = self.url
if credentials is None:
credentials = self.credentials
if do_verify_certificate is None:
... |
Helper method to store username and password | def register_credentials(self, credentials=None, user=None, user_file=None, password=None, password_file=None):
"""
Helper method to store username and password
"""
# lets store all kind of credential data into this dict
if credentials is not None:
self.credentials = ... |
Wrap a generator function so that it returns a list when called. For example: # Define a generator >>> def mygen ( n ):... i = 0... while i < n:... yield i... i + = 1 # This is how it might work >>> generator = mygen ( 5 ) >>> generator. next () 0 >>> generator. next () 1 # Wrap it in generator_to_list and it will beha... | def generator_to_list(function):
"""
Wrap a generator function so that it returns a list when called.
For example:
# Define a generator
>>> def mygen(n):
... i = 0
... while i < n:
... yield i
... i += 1
# This is ... |
Return the next available filename for a particular filename prefix. For example: >>> import os # Make three ( empty ) files in a directory >>> fp0 = open ( file. 0 w ) >>> fp1 = open ( file. 1 w ) >>> fp2 = open ( file. 2 w ) >>> fp0. close () fp1. close () fp2. close () ( None None None ) # Use logrotate to get the n... | def logrotate(filename):
"""
Return the next available filename for a particular filename prefix.
For example:
>>> import os
# Make three (empty) files in a directory
>>> fp0 = open('file.0', 'w')
>>> fp1 = open('file.1', 'w')
>>> fp2 = open('file.2', '... |
Set connection parameters. Call set_connection with no arguments to clear. | def set_connection(host=None, database=None, user=None, password=None):
"""Set connection parameters. Call set_connection with no arguments to clear."""
c.CONNECTION['HOST'] = host
c.CONNECTION['DATABASE'] = database
c.CONNECTION['USER'] = user
c.CONNECTION['PASSWORD'] = password |
Set delegate parameters. Call set_delegate with no arguments to clear. | def set_delegate(address=None, pubkey=None, secret=None):
"""Set delegate parameters. Call set_delegate with no arguments to clear."""
c.DELEGATE['ADDRESS'] = address
c.DELEGATE['PUBKEY'] = pubkey
c.DELEGATE['PASSPHRASE'] = secret |
returns a list of named tuples of all transactions relevant to a specific delegates voters. Flow: finds all voters and unvoters SELECTs all transactions of those voters names all transactions according to the scheme: transaction id amount timestamp recipientId senderId rawasset type fee blockId | def get_transactionlist(delegate_pubkey):
"""returns a list of named tuples of all transactions relevant to a specific delegates voters.
Flow: finds all voters and unvoters, SELECTs all transactions of those voters, names all transactions according to
the scheme: 'transaction', 'id amount timestamp recipien... |
returns a list of named tuples of all transactions relevant to a specific delegates voters. Flow: finds all voters and unvoters SELECTs all transactions of those voters names all transactions according to the scheme: transaction id amount timestamp recipientId senderId rawasset type fee blockId | def get_events(delegate_pubkey):
"""returns a list of named tuples of all transactions relevant to a specific delegates voters.
Flow: finds all voters and unvoters, SELECTs all transactions of those voters, names all transactions according to
the scheme: 'transaction', 'id amount timestamp recipientId sende... |
returns all received transactions between the address and registered delegate accounts ORDER by timestamp ASC. | def payout(address):
"""returns all received transactions between the address and registered delegate accounts
ORDER by timestamp ASC."""
qry = DbCursor().execute_and_fetchall("""
SELECT DISTINCT transactions."id", transactions."amount",
transactions."times... |
Returns a list of namedtuples all votes made by an address { ( +/ - ) pubkeydelegate: timestamp } timestamp DESC | def votes(address):
"""Returns a list of namedtuples all votes made by an address, {(+/-)pubkeydelegate:timestamp}, timestamp DESC"""
qry = DbCursor().execute_and_fetchall("""
SELECT votes."votes", transactions."timestamp"
FROM votes, transactions
WHERE transactions."id"... |
Takes a single address and returns the current balance. | def balance(address):
"""
Takes a single address and returns the current balance.
"""
txhistory = Address.transactions(address)
balance = 0
for i in txhistory:
if i.recipientId == address:
balance += i.amount
if i.senderId == addres... |
returns a list of named tuples x. timestamp x. amount including block rewards | def balance_over_time(address):
"""returns a list of named tuples, x.timestamp, x.amount including block rewards"""
forged_blocks = None
txhistory = Address.transactions(address)
delegates = Delegate.delegates()
for i in delegates:
if address == i.address:
... |
returns a list of named tuples of all delegates. { username: { pubkey: pubkey timestamp: timestamp address: address }} | def delegates():
"""returns a list of named tuples of all delegates.
{username: {'pubkey':pubkey, 'timestamp':timestamp, 'address':address}}"""
qry = DbCursor().execute_and_fetchall("""
SELECT delegates."username", delegates."transactionId", transactions."timestamp", transactions."se... |
Assumes that all send transactions from a delegate are payouts. Use blacklist to remove rewardwallet and other transactions if the address is not a voter. blacklist can contain both addresses and transactionIds | def lastpayout(delegate_address, blacklist=None):
'''
Assumes that all send transactions from a delegate are payouts.
Use blacklist to remove rewardwallet and other transactions if the
address is not a voter. blacklist can contain both addresses and transactionIds'''
if blacklist... |
returns every address that has voted for a delegate. Current voters can be obtained using voters. ORDER BY timestamp ASC | def votes(delegate_pubkey):
"""returns every address that has voted for a delegate.
Current voters can be obtained using voters. ORDER BY timestamp ASC"""
qry = DbCursor().execute_and_fetchall("""
SELECT transactions."recipientId", transactions."timestamp"
FROM ... |
returns a list of named tuples of all blocks forged by a delegate. if delegate_pubkey is not specified set_delegate needs to be called in advance. max_timestamp can be configured to retrieve blocks up to a certain timestamp. | def blocks(delegate_pubkey=None, max_timestamp=None):
"""returns a list of named tuples of all blocks forged by a delegate.
if delegate_pubkey is not specified, set_delegate needs to be called in advance.
max_timestamp can be configured to retrieve blocks up to a certain timestamp."""
i... |
Calculate the true blockweight payout share for a given delegate assuming no exceptions were made for a voter. last_payout is a map of addresses and timestamps: { address: timestamp }. If no argument are given it will start the calculation at the first forged block by the delegate generate a last_payout from transactio... | def share(passphrase=None, last_payout=None, start_block=0, del_pubkey=None, del_address=None):
"""Calculate the true blockweight payout share for a given delegate,
assuming no exceptions were made for a voter. last_payout is a map of addresses and timestamps:
{address: timestamp}. If no argumen... |
Legacy TBW script ( still pretty performant but has some quirky behavior when forging delegates are amongst your voters ) | def dep_trueshare(start_block=0, del_pubkey=None, del_address=None, blacklist=None, share_fees=False, max_weight=float('inf'), raiseError=True):
'''
Legacy TBW script (still pretty performant, but has some quirky behavior when forging delegates are amongst
your voters)
:param int start_... |
Legacy TBW script ( still pretty performant but has some quirky behavior when forging delegates are amongst your voters ) | def trueshare(start_block=0, del_pubkey=None, del_address=None, blacklist=None, share_fees=False,
max_weight=float('inf')):
'''
Legacy TBW script (still pretty performant, but has some quirky behavior when forging delegates are amongst
your voters)
:param int start_blo... |
Adds a source to the factory provided it s type and constructor arguments: param source_class: The class used to instantiate the source: type source_class: type: param constructor_args: Arguments to be passed into the constructor: type constructor_args: Iterable | def add_source(self, source_class, *constructor_args):
"""
Adds a source to the factory provided it's type and constructor arguments
:param source_class: The class used to instantiate the source
:type source_class: type
:param constructor_args: Arguments to be passed into the con... |
Generates instantiated sources from the factory: param limit: the max number of sources to yield: type limit: int: param types_list: filter by types so the constructor can be used to accomidate many types: type types_list: class or list of classes: return: Yields types added by add_source: rtype: generator | def get_sources(self, limit=sys.maxsize, types_list=None):
"""
Generates instantiated sources from the factory
:param limit: the max number of sources to yield
:type limit: int
:param types_list: filter by types so the constructor can be used to accomidate many types
:typ... |
Massages the true and false strings to bool equivalents. | def value_to_bool(config_val, evar):
"""
Massages the 'true' and 'false' strings to bool equivalents.
:param str config_val: The env var value.
:param EnvironmentVariable evar: The EVar object we are validating
a value for.
:rtype: bool
:return: True or False, depending on the value.
... |
If the value is None fail validation. | def validate_is_not_none(config_val, evar):
"""
If the value is ``None``, fail validation.
:param str config_val: The env var value.
:param EnvironmentVariable evar: The EVar object we are validating
a value for.
:raises: ValueError if the config value is None.
"""
if config_val is ... |
Make sure the value evaluates to boolean True. | def validate_is_boolean_true(config_val, evar):
"""
Make sure the value evaluates to boolean True.
:param str config_val: The env var value.
:param EnvironmentVariable evar: The EVar object we are validating
a value for.
:raises: ValueError if the config value evaluates to boolean False.
... |
Convert an evar value into a Python logging level constant. | def value_to_python_log_level(config_val, evar):
"""
Convert an evar value into a Python logging level constant.
:param str config_val: The env var value.
:param EnvironmentVariable evar: The EVar object we are validating
a value for.
:return: A validated string.
:raises: ValueError if ... |
Register a new range type as a PostgreSQL range. | def register_range_type(pgrange, pyrange, conn):
"""
Register a new range type as a PostgreSQL range.
>>> register_range_type("int4range", intrange, conn)
The above will make sure intrange is regarded as an int4range for queries
and that int4ranges will be cast into intrange when fetching rows... |
Acquires the correct error for a given response. | def get_api_error(response):
"""Acquires the correct error for a given response.
:param requests.Response response: HTTP error response
:returns: the appropriate error for a given response
:rtype: APIError
"""
error_class = _status_code_to_class.get(response.status_code, APIError)
return error_class(res... |
Converts the request parameters to Python. | def get_param_values(request, model=None):
"""
Converts the request parameters to Python.
:param request: <pyramid.request.Request> || <dict>
:return: <dict>
"""
if type(request) == dict:
return request
params = get_payload(request)
# support in-place editing formatted reques... |
Extracts ORB context information from the request. | def get_context(request, model=None):
"""
Extracts ORB context information from the request.
:param request: <pyramid.request.Request>
:param model: <orb.Model> || None
:return: {<str> key: <variant> value} values, <orb.Context>
"""
# convert request parameters to python
param_values =... |
Handles real - time updates to the order book. | def _real_time_thread(self):
"""Handles real-time updates to the order book."""
while self.ws_client.connected():
if self.die:
break
if self.pause:
sleep(5)
continue
message = self.ws_client.receive()
if message is None:
break
message_type ... |
Used exclusively as a thread which keeps the WebSocket alive. | def _keep_alive_thread(self):
"""Used exclusively as a thread which keeps the WebSocket alive."""
while True:
with self._lock:
if self.connected():
self._ws.ping()
else:
self.disconnect()
self._thread = None
return
sleep(30) |
Connects and subscribes to the WebSocket Feed. | def connect(self):
"""Connects and subscribes to the WebSocket Feed."""
if not self.connected():
self._ws = create_connection(self.WS_URI)
message = {
'type':self.WS_TYPE,
'product_id':self.WS_PRODUCT_ID
}
self._ws.send(dumps(message))
# There will be only one keep... |
Marks a view function as being exempt from the cached httpbl view protection. | def cached_httpbl_exempt(view_func):
"""
Marks a view function as being exempt from the cached httpbl view protection.
"""
# We could just do view_func.cached_httpbl_exempt = True, but decorators
# are nicer if they don't have side-effects, so we return a new
# function.
def wrapped_view(*ar... |
Hook point for overriding how the CounterPool gets its connection to AWS. | def get_conn(self, aws_access_key=None, aws_secret_key=None):
'''
Hook point for overriding how the CounterPool gets its connection to
AWS.
'''
return boto.connect_dynamodb(
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key,
) |
Hook point for overriding how the CounterPool determines the schema to be used when creating a missing table. | def get_schema(self):
'''
Hook point for overriding how the CounterPool determines the schema
to be used when creating a missing table.
'''
if not self.schema:
raise NotImplementedError(
'You must provide a schema value or override the get_schema metho... |
Hook point for overriding how the CounterPool creates a new table in DynamooDB | def create_table(self):
'''
Hook point for overriding how the CounterPool creates a new table
in DynamooDB
'''
table = self.conn.create_table(
name=self.get_table_name(),
schema=self.get_schema(),
read_units=self.get_read_units(),
w... |
Hook point for overriding how the CounterPool transforms table_name into a boto DynamoDB Table object. | def get_table(self):
'''
Hook point for overriding how the CounterPool transforms table_name
into a boto DynamoDB Table object.
'''
if hasattr(self, '_table'):
table = self._table
else:
try:
table = self.conn.get_table(self.get_tabl... |
Hook point for overriding how the CouterPool creates a DynamoDB item for a given counter when an existing item can t be found. | def create_item(self, hash_key, start=0, extra_attrs=None):
'''
Hook point for overriding how the CouterPool creates a DynamoDB item
for a given counter when an existing item can't be found.
'''
table = self.get_table()
now = datetime.utcnow().replace(microsecond=0).isofo... |
Hook point for overriding how the CouterPool fetches a DynamoDB item for a given counter. | def get_item(self, hash_key, start=0, extra_attrs=None):
'''
Hook point for overriding how the CouterPool fetches a DynamoDB item
for a given counter.
'''
table = self.get_table()
try:
item = table.get_item(hash_key=hash_key)
except DynamoDBKeyNotFoun... |
Gets the DynamoDB item behind a counter and ties it to a Counter instace. | def get_counter(self, name, start=0):
'''
Gets the DynamoDB item behind a counter and ties it to a Counter
instace.
'''
item = self.get_item(hash_key=name, start=start)
counter = Counter(dynamo_item=item, pool=self)
return counter |
Matches this descriptor to another descriptor exactly. Args: descriptor: another descriptor to match this one. Returns: True if descriptors match or False otherwise. | def exact_match(self, descriptor):
"""
Matches this descriptor to another descriptor exactly.
Args:
descriptor: another descriptor to match this one.
Returns: True if descriptors match or False otherwise.
"""
return self._exact_match_field... |
Use an event to build a many - to - one relationship on a class. | def many_to_one(clsname, **kw):
"""Use an event to build a many-to-one relationship on a class.
This makes use of the :meth:`.References._reference_table` method
to generate a full foreign key relationship to the remote table.
"""
@declared_attr
def m2o(cls):
cls._references((cls.__nam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.