Search is not available for this dataset
text stringlengths 75 104k |
|---|
def __complete_refers(self, value: str) -> Iterable[str]:
"""Return an iterable of possible completions matching the given
prefix from the list of referred Vars."""
return map(
lambda entry: f"{entry[0].name}",
filter(
Namespace.__completion_matcher(value)... |
def complete(self, text: str) -> Iterable[str]:
"""Return an iterable of possible completions for the given text in
this namespace."""
assert not text.startswith(":")
if "/" in text:
prefix, suffix = text.split("/", maxsplit=1)
results = itertools.chain(
... |
def args(self) -> Tuple:
"""Return the arguments for a trampolined function. If the function
that is being trampolined has varargs, unroll the final argument if
it is a sequence."""
if not self._has_varargs:
return self._args
try:
final = self._args[-1]
... |
def list(members, meta=None) -> List: # pylint:disable=redefined-builtin
"""Creates a new list."""
return List( # pylint: disable=abstract-class-instantiated
plist(iterable=members), meta=meta
) |
def l(*members, meta=None) -> List:
"""Creates a new list from members."""
return List( # pylint: disable=abstract-class-instantiated
plist(iterable=members), meta=meta
) |
def change_style(style, representer):
"""
This function is used to format the key value as a multi-line string maintaining the line breaks
"""
def new_representer(dumper, data):
scalar = representer(dumper, data)
scalar.style = style
return scalar
return new_representer |
def get_public_key(platform, service, purpose, key_use, version, public_key, keys_folder):
'''
Loads a public key from the file system and adds it to a dict of keys
:param keys: A dict of keys
:param platform the platform the key is for
:param service the service the key is for
:param key_use wh... |
def get_private_key(platform, service, purpose, key_use, version, private_key, keys_folder):
'''
Loads a private key from the file system and adds it to a dict of keys
:param keys: A dict of keys
:param platform the platform the key is for
:param service the service the key is for
:param key_use... |
def decrypt_with_key(encrypted_token, key):
"""
Decrypts JWE token with supplied key
:param encrypted_token:
:param key: A (:class:`jwcrypto.jwk.JWK`) decryption key or a password
:returns: The payload of the decrypted token
"""
try:
jwe_token = jwe.JW... |
def decrypt(token, key_store, key_purpose, leeway=120):
"""This decrypts the provided jwe token, then decodes resulting jwt token and returns
the payload.
:param str token: The jwe token.
:param key_store: The key store.
:param str key_purpose: Context for the key.
:param int leeway: Extra allo... |
def encrypt(json, key_store, key_purpose):
"""This encrypts the supplied json and returns a jwe token.
:param str json: The json to be encrypted.
:param key_store: The key store.
:param str key_purpose: Context for the key.
:return: A jwe token.
"""
jwt_key = key_store.get_key_for_purpose_... |
def get_key_for_purpose_and_type(self, purpose, key_type):
"""
Gets a list of keys that match the purpose and key_type, and returns the first key in that list
Note, if there are many keys that match the criteria, the one you get back will be random from that list
:returns: A key object t... |
def get_default_args(func):
"""
returns a dictionary of arg_name:default_values for the input function
"""
args, _, _, defaults, *rest = inspect.getfullargspec(func)
return dict(zip(reversed(args), reversed(defaults))) |
def map_arguments_to_objects(kwargs, objects, object_key, object_tuple_key, argument_key, result_value, default_result):
"""
:param kwargs: kwargs used to call the multiget function
:param objects: objects returned from the inner function
:param object_key: field or set of fields that map to the kwargs ... |
def delete(self, *args):
"""Remove the key from the request cache and from memcache."""
cache = get_cache()
key = self.get_cache_key(*args)
if key in cache:
del cache[key] |
def multiget_cached(object_key, argument_key=None, default_result=None,
result_fields=None, join_table_name=None, coerce_args_to_strings=False):
"""
:param object_key: the names of the attributes on the result object that are meant to match the function parameters
:param argument_key: th... |
def get_dot_target_name(version=None, module=None):
"""Returns the current version/module in -dot- notation which is used by `target:` parameters."""
version = version or get_current_version_name()
module = module or get_current_module_name()
return '-dot-'.join((version, module)) |
def get_dot_target_name_safe(version=None, module=None):
"""
Returns the current version/module in -dot- notation which is used by `target:` parameters.
If there is no current version or module then None is returned.
"""
version = version or get_current_version_name_safe()
module = module or get_current_mod... |
def _get_os_environ_dict(keys):
"""Return a dictionary of key/values from os.environ."""
return {k: os.environ.get(k, _UNDEFINED) for k in keys} |
def name(obj) -> str:
"""This helper function attempts to resolve the dot-colon import path for a given object.
Specifically searches for classes and methods, it should be able to find nearly anything at either the module
level or nested one level deep. Uses ``__qualname__`` if available.
"""
if not isroutine... |
def to_python(self):
"""Deconstruct the ``Constraint`` instance to a tuple.
Returns:
tuple: The deconstructed ``Constraint``.
"""
return (
self.selector,
COMPARISON_MAP.get(self.comparison, self.comparison),
self.argument
) |
async def connect(self):
"""Connect to LASAF through a CAM-socket."""
self.reader, self.writer = await asyncio.open_connection(
self.host, self.port, loop=self.loop)
self.welcome_msg = await self.reader.read(self.buffer_size) |
async def send(self, commands):
"""Send commands to LASAF through CAM-socket.
Parameters
----------
commands : list of tuples or bytes string
Commands as a list of tuples or a bytes string. cam.prefix is
allways prepended before sending.
Returns
... |
async def receive(self):
"""Receive message from socket interface as list of OrderedDict."""
try:
incomming = await self.reader.read(self.buffer_size)
except OSError:
return []
return _parse_receive(incomming) |
async def wait_for(self, cmd, value=None, timeout=60):
"""Hang until command is received.
If value is supplied, it will hang until ``cmd:value`` is received.
Parameters
----------
cmd : string
Command to wait for in bytestring from microscope CAM interface. If
... |
def close(self):
"""Close stream."""
if self.writer.can_write_eof():
self.writer.write_eof()
self.writer.close() |
def lazyload(reference: str, *args, **kw):
"""Lazily load and cache an object reference upon dereferencing.
Assign the result of calling this function with either an object reference passed in positionally:
class MyClass:
debug = lazyload('logging:debug')
Or the attribute path to traverse (using `marrow.p... |
def iter_parse(fiql_str):
"""Iterate through the FIQL string. Yield a tuple containing the
following FIQL components for each iteration:
- preamble: Any operator or opening/closing paranthesis preceding a
constraint or at the very end of the FIQL string.
- selector: The selector portion of ... |
def parse_str_to_expression(fiql_str):
"""Parse a FIQL formatted string into an ``Expression``.
Args:
fiql_str (string): The FIQL formatted string we want to parse.
Returns:
Expression: An ``Expression`` object representing the parsed FIQL
string.
Raises:
FiqlFormatExc... |
def encode_model(obj):
"""Encode objects like ndb.Model which have a `.to_dict()` method."""
obj_dict = obj.to_dict()
for key, val in obj_dict.iteritems():
if isinstance(val, types.StringType):
try:
unicode(val)
except UnicodeDecodeError:
# Encode binary strings (blobs) to base64.
... |
def dump(ndb_model, fp, **kwargs):
"""Custom json dump using the custom encoder above."""
for chunk in NdbEncoder(**kwargs).iterencode(ndb_model):
fp.write(chunk) |
def object_hook_handler(self, val):
"""Handles decoding of nested date strings."""
return {k: self.decode_date(v) for k, v in val.iteritems()} |
def decode_date(self, val):
"""Tries to decode strings that look like dates into datetime objects."""
if isinstance(val, basestring) and val.count('-') == 2 and len(val) > 9:
try:
dt = dateutil.parser.parse(val)
# Check for UTC.
if val.endswith(('+00:00', '-00:00', 'Z')):
... |
def decode(self, val):
"""Override of the default decode method that also uses decode_date."""
# First try the date decoder.
new_val = self.decode_date(val)
if val != new_val:
return new_val
# Fall back to the default decoder.
return json.JSONDecoder.decode(self, val) |
def default(self, obj):
"""Overriding the default JSONEncoder.default for NDB support."""
obj_type = type(obj)
# NDB Models return a repr to calls from type().
if obj_type not in self._ndb_type_encoding:
if hasattr(obj, '__metaclass__'):
obj_type = obj.__metaclass__
else:
# T... |
def traverse(obj, target:str, default=nodefault, executable:bool=False, separator:str='.', protect:bool=True):
"""Traverse down an object, using getattr or getitem.
If ``executable`` is ``True`` any executable function encountered will be, with no arguments. Traversal will
continue on the result of that call. You... |
def load(target:str, namespace:str=None, default=nodefault, executable:bool=False, separators:Sequence[str]=('.', ':'),
protect:bool=True):
"""This helper function loads an object identified by a dotted-notation string.
For example::
# Load class Foo from example.objects
load('example.objects:Foo')
# L... |
def run():
"""Run client."""
cam = CAM()
print(cam.welcome_msg)
print(cam.send(b'/cmd:deletelist'))
sleep(0.1)
print(cam.receive())
print(cam.send(b'/cmd:deletelist'))
sleep(0.1)
print(cam.wait_for(cmd='cmd', timeout=0.1))
cam.close() |
def validate_version():
"""Validate version before release."""
import leicacam
version_string = leicacam.__version__
versions = version_string.split('.', 3)
try:
for ver in versions:
int(ver)
except ValueError:
print(
'Only integers are allowed in release ... |
def generate():
"""Generate changelog."""
old_dir = os.getcwd()
proj_dir = os.path.join(os.path.dirname(__file__), os.pardir)
os.chdir(proj_dir)
version = validate_version()
if not version:
os.chdir(old_dir)
return
print('Generating changelog for version {}'.format(version))
... |
def strongly_connected_components(graph: Graph) -> List:
"""Find the strongly connected components in a graph using Tarjan's algorithm.
The `graph` argument should be a dictionary mapping node names to sequences of successor nodes.
"""
assert check_argument_types()
result = []
stack = []
low = {}
def vi... |
def robust_topological_sort(graph: Graph) -> list:
"""Identify strongly connected components then perform a topological sort of those components."""
assert check_argument_types()
components = strongly_connected_components(graph)
node_component = {}
for component in components:
for node in component:
nod... |
def set_parent(self, parent):
"""Set parent ``Expression`` for this object.
Args:
parent (Expression): The ``Expression`` which contains this object.
Raises:
FiqlObjectException: Parent must be of type ``Expression``.
"""
if not isinstance(parent, Expres... |
def get_parent(self):
"""Get the parent ``Expression`` for this object.
Returns:
Expression: The ``Expression`` which contains this object.
Raises:
FiqlObjectException: Parent is ``None``.
"""
if not isinstance(self.parent, Expression):
raise... |
def add_operator(self, operator):
"""Add an ``Operator`` to the ``Expression``.
The ``Operator`` may result in a new ``Expression`` if an ``Operator``
already exists and is of a different precedence.
There are three possibilities when adding an ``Operator`` to an
``Expression``... |
def add_element(self, element):
"""Add an element of type ``Operator``, ``Constraint``, or
``Expression`` to the ``Expression``.
Args:
element: ``Constraint``, ``Expression``, or ``Operator``.
Returns:
Expression: ``self``
Raises:
FiqlObject... |
def op_and(self, *elements):
"""Update the ``Expression`` by joining the specified additional
``elements`` using an "AND" ``Operator``
Args:
*elements (BaseExpression): The ``Expression`` and/or
``Constraint`` elements which the "AND" ``Operator`` applies
... |
def op_or(self, *elements):
"""Update the ``Expression`` by joining the specified additional
``elements`` using an "OR" ``Operator``
Args:
*elements (BaseExpression): The ``Expression`` and/or
``Constraint`` elements which the "OR" ``Operator`` applies
... |
def to_python(self):
"""Deconstruct the ``Expression`` instance to a list or tuple
(If ``Expression`` contains only one ``Constraint``).
Returns:
list or tuple: The deconstructed ``Expression``.
"""
if len(self.elements) == 0:
return None
if len(s... |
async def run(loop):
"""Run client."""
cam = AsyncCAM(loop=loop)
await cam.connect()
print(cam.welcome_msg)
await cam.send(b'/cmd:deletelist')
print(await cam.receive())
await cam.send(b'/cmd:deletelist')
print(await cam.wait_for(cmd='cmd', timeout=0.1))
await cam.send(b'/cmd:deletel... |
def logger(function):
"""Decorate passed in function and log message to module logger."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
"""Wrap function."""
sep = kwargs.get('sep', ' ')
end = kwargs.get('end', '') # do not add newline by default
out = sep.join([re... |
def _parse_receive(incomming):
"""Parse received response.
Parameters
----------
incomming : bytes string
Incomming bytes from socket server.
Returns
-------
list of OrderedDict
Received message as a list of OrderedDict.
"""
debug(b'< ' + incomming)
# remove te... |
def tuples_as_bytes(cmds):
"""Format list of tuples to CAM message with format /key:val.
Parameters
----------
cmds : list of tuples
List of commands as tuples.
Returns
-------
bytes
Sequence of /key:val.
Example
-------
::
>>> tuples_as_bytes([('cmd',... |
def tuples_as_dict(_list):
"""Translate a list of tuples to OrderedDict with key and val as strings.
Parameters
----------
_list : list of tuples
Returns
-------
collections.OrderedDict
Example
-------
::
>>> tuples_as_dict([('cmd', 'val'), ('cmd2', 'val2')])
... |
def bytes_as_dict(msg):
"""Parse CAM message to OrderedDict based on format /key:val.
Parameters
----------
msg : bytes
Sequence of /key:val.
Returns
-------
collections.OrderedDict
With /key:val => dict[key] = val.
"""
# decode bytes, assume '/' in start
cmd_s... |
def check_messages(msgs, cmd, value=None):
"""Check if specific message is present.
Parameters
----------
cmd : string
Command to check for in bytestring from microscope CAM interface. If
``value`` is falsey, value of received command does not matter.
value : string
Check if... |
def _prepare_send(self, commands):
"""Prepare message to be sent.
Parameters
----------
commands : list of tuples or bytes string
Commands as a list of tuples or a bytes string. cam.prefix is
allways prepended before sending.
Returns
-------
... |
def connect(self):
"""Connect to LASAF through a CAM-socket."""
self.socket = socket.socket()
self.socket.connect((self.host, self.port))
self.socket.settimeout(False) # non-blocking
sleep(self.delay) # wait for response
self.welcome_msg = self.socket.recv(
... |
def flush(self):
"""Flush incomming socket messages."""
debug('flushing incomming socket messages')
try:
while True:
msg = self.socket.recv(self.buffer_size)
debug(b'< ' + msg)
except socket.error:
pass |
def send(self, commands):
"""Send commands to LASAF through CAM-socket.
Parameters
----------
commands : list of tuples or bytes string
Commands as a list of tuples or a bytes string. cam.prefix is
allways prepended before sending.
Returns
------... |
def receive(self):
"""Receive message from socket interface as list of OrderedDict."""
try:
incomming = self.socket.recv(self.buffer_size)
except socket.error:
return []
return _parse_receive(incomming) |
def wait_for(self, cmd, value=None, timeout=60):
"""Hang until command is received.
If value is supplied, it will hang until ``cmd:value`` is received.
Parameters
----------
cmd : string
Command to wait for in bytestring from microscope CAM interface. If
... |
def enable(self, slide=0, wellx=1, welly=1, fieldx=1, fieldy=1):
"""Enable a given scan field."""
# pylint: disable=too-many-arguments
cmd = [
('cmd', 'enable'),
('slide', str(slide)),
('wellx', str(wellx)),
('welly', str(welly)),
('fie... |
def save_template(self, filename="{ScanningTemplate}leicacam.xml"):
"""Save scanning template to filename."""
cmd = [
('sys', '0'),
('cmd', 'save'),
('fil', str(filename))
]
self.send(cmd)
return self.wait_for(*cmd[0]) |
def load_template(self, filename="{ScanningTemplate}leicacam.xml"):
"""Load scanning template from filename.
Template needs to exist in database, otherwise it will not load.
Parameters
----------
filename : str
Filename to template to load. Filename may contain path... |
def get_information(self, about='stage'):
"""Get information about given keyword. Defaults to stage."""
cmd = [
('cmd', 'getinfo'),
('dev', str(about))
]
self.send(cmd)
return self.wait_for(*cmd[1]) |
def incfile(fname, fpointer, lrange="1,6-", sdir=None):
r"""
Include a Python source file in a docstring formatted in reStructuredText.
:param fname: File name, relative to environment variable
:bash:`${TRACER_DIR}`
:type fname: string
:param fpointer: Output function pointer. N... |
def locate_package_json():
"""
Find and return the location of package.json.
"""
directory = settings.SYSTEMJS_PACKAGE_JSON_DIR
if not directory:
raise ImproperlyConfigured(
"Could not locate 'package.json'. Set SYSTEMJS_PACKAGE_JSON_DIR "
"to the directory that holds... |
def parse_package_json():
"""
Extract the JSPM configuration from package.json.
"""
with open(locate_package_json()) as pjson:
data = json.loads(pjson.read())
return data |
def find_systemjs_location():
"""
Figure out where `jspm_packages/system.js` will be put by JSPM.
"""
location = os.path.abspath(os.path.dirname(locate_package_json()))
conf = parse_package_json()
if 'jspm' in conf:
conf = conf['jspm']
try:
conf = conf['directories']
ex... |
def _handle_api_error_with_json(http_exc, jsondata, response):
"""Handle YOURLS API errors.
requests' raise_for_status doesn't show the user the YOURLS json response,
so we parse that here and raise nicer exceptions.
"""
if 'code' in jsondata and 'message' in jsondata:
code = jsondata['code... |
def _validate_yourls_response(response, data):
"""Validate response from YOURLS server."""
try:
response.raise_for_status()
except HTTPError as http_exc:
# Collect full HTTPError information so we can reraise later if required.
http_error_info = sys.exc_info()
# We will rera... |
def _homogenize_waves(wave_a, wave_b):
"""
Generate combined independent variable vector.
The combination is from two waveforms and the (possibly interpolated)
dependent variable vectors of these two waveforms
"""
indep_vector = _get_indep_vector(wave_a, wave_b)
dep_vector_a = _interp_dep_v... |
def _interp_dep_vector(wave, indep_vector):
"""Create new dependent variable vector."""
dep_vector_is_int = wave.dep_vector.dtype.name.startswith("int")
dep_vector_is_complex = wave.dep_vector.dtype.name.startswith("complex")
if (wave.interp, wave.indep_scale) == ("CONTINUOUS", "LOG"):
wave_inte... |
def _get_indep_vector(wave_a, wave_b):
"""Create new independent variable vector."""
exobj = pexdoc.exh.addex(RuntimeError, "Independent variable ranges do not overlap")
min_bound = max(np.min(wave_a.indep_vector), np.min(wave_b.indep_vector))
max_bound = min(np.max(wave_a.indep_vector), np.max(wave_b.i... |
def _verify_compatibility(wave_a, wave_b, check_dep_units=True):
"""Verify that two waveforms can be combined with various mathematical functions."""
exobj = pexdoc.exh.addex(RuntimeError, "Waveforms are not compatible")
ctuple = (
bool(wave_a.indep_scale != wave_b.indep_scale),
bool(wave_a.... |
def load_systemjs_manifest(self):
"""
Load the existing systemjs manifest and remove any entries that no longer
exist on the storage.
"""
# backup the original name
_manifest_name = self.manifest_name
# load the custom bundle manifest
self.manifest_name =... |
def trace_pars(mname):
"""Define trace parameters."""
pickle_fname = os.path.join(os.path.dirname(__file__), "{0}.pkl".format(mname))
ddir = os.path.dirname(os.path.dirname(__file__))
moddb_fname = os.path.join(ddir, "moddb.json")
in_callables_fname = moddb_fname if os.path.exists(moddb_fname) else ... |
def run_trace(
mname,
fname,
module_prefix,
callable_names,
no_print,
module_exclude=None,
callable_exclude=None,
debug=False,
):
"""Run module tracing."""
# pylint: disable=R0913
module_exclude = [] if module_exclude is None else module_exclude
callable_exclude = [] if c... |
def shorten(self, url, keyword=None, title=None):
"""Shorten URL with optional keyword and title.
Parameters:
url: URL to shorten.
keyword: Optionally choose keyword for short URL, otherwise automatic.
title: Optionally choose title, otherwise taken from web page.
... |
def expand(self, short):
"""Expand short URL or keyword to long URL.
Parameters:
short: Short URL (``http://example.com/abc``) or keyword (abc).
:return: Expanded/long URL, e.g.
``https://www.youtube.com/watch?v=dQw4w9WgXcQ``
Raises:
~yourls.ex... |
def url_stats(self, short):
"""Get stats for short URL or keyword.
Parameters:
short: Short URL (http://example.com/abc) or keyword (abc).
Returns:
ShortenedURL: Shortened URL and associated data.
Raises:
~yourls.exceptions.YOURLSHTTPError: HTTP err... |
def stats(self, filter, limit, start=None):
"""Get stats about links.
Parameters:
filter: 'top', 'bottom', 'rand', or 'last'.
limit: Number of links to return from filter.
start: Optional start number.
Returns:
Tuple containing list of ShortenedU... |
def db_stats(self):
"""Get database statistics.
Returns:
DBStats: Total clicks and links statistics.
Raises:
requests.exceptions.HTTPError: Generic HTTP Error
"""
data = dict(action='db-stats')
jsondata = self._api_request(params=data)
s... |
def ste(command, nindent, mdir, fpointer):
r"""
Echo terminal output.
Print STDOUT resulting from a given Bash shell command (relative to the
package :code:`pypkg` directory) formatted in reStructuredText
:param command: Bash shell command, relative to
:bash:`${PMISC_DIR}/pypkg... |
def term_echo(command, nindent=0, env=None, fpointer=None, cols=60):
"""
Print STDOUT resulting from a Bash shell command formatted in reStructuredText.
:param command: Bash shell command
:type command: string
:param nindent: Indentation level
:type nindent: integer
:param env: Environm... |
def log(self, msg, level=2):
"""
Small log helper
"""
if self.verbosity >= level:
self.stdout.write(msg) |
def cached(method) -> property:
"""alternative to reify and property decorators. caches the value when it's
generated. It cashes it as instance._name_of_the_property.
"""
name = "_" + method.__name__
@property
def wrapper(self):
try:
return getattr(self, name)
except... |
def chunkiter(iterable, chunksize):
"""break an iterable into chunks and yield those chunks as lists
until there's nothing left to yeild.
"""
iterator = iter(iterable)
for chunk in iter(lambda: list(itertools.islice(iterator, chunksize)), []):
yield chunk |
def chunkprocess(func):
"""take a function that taks an iterable as the first argument.
return a wrapper that will break an iterable into chunks using
chunkiter and run each chunk in function, yielding the value of each
function call as an iterator.
"""
@functools.wraps(func)
def wrapper(it... |
def flatten(iterable, map2iter=None):
"""recursively flatten nested objects"""
if map2iter and isinstance(iterable):
iterable = map2iter(iterable)
for item in iterable:
if isinstance(item, str) or not isinstance(item, abc.Iterable):
yield item
else:
yield fro... |
def deepupdate(
mapping: abc.MutableMapping, other: abc.Mapping, listextend=False
):
"""update one dictionary from another recursively. Only individual
values will be overwritten--not entire branches of nested
dictionaries.
"""
def inner(other, previouskeys):
"""previouskeys is a tuple ... |
def quietinterrupt(msg=None):
"""add a handler for SIGINT that optionally prints a given message.
For stopping scripts without having to see the stacktrace.
"""
def handler():
if msg:
print(msg, file=sys.stderr)
sys.exit(1)
signal.signal(signal.SIGINT, handler) |
def printtsv(table, sep="\t", file=sys.stdout):
"""stupidly print an iterable of iterables in TSV format"""
for record in table:
print(*record, sep=sep, file=file) |
def mkdummy(name, **attrs):
"""Make a placeholder object that uses its own name for its repr"""
return type(
name, (), dict(__repr__=(lambda self: "<%s>" % name), **attrs)
)() |
def pipe(value, *functions, funcs=None):
"""pipe(value, f, g, h) == h(g(f(value)))"""
if funcs:
functions = funcs
for function in functions:
value = function(value)
return value |
def pipeline(*functions, funcs=None):
"""like pipe, but curried:
pipline(f, g, h)(*args, **kwargs) == h(g(f(*args, **kwargs)))
"""
if funcs:
functions = funcs
head, *tail = functions
return lambda *args, **kwargs: pipe(head(*args, **kwargs), funcs=tail) |
def human_readable(self, decimal=False):
"""returns the size of size as a tuple of:
(number, single-letter-unit)
If the decimal flag is set to true, units 1000 is used as the
divisor, rather than 1024.
"""
divisor = 1000 if decimal else 1024
number = int(sel... |
def from_str(cls, human_readable_str, decimal=False, bits=False):
"""attempt to parse a size in bytes from a human-readable string."""
divisor = 1000 if decimal else 1024
num = []
c = ""
for c in human_readable_str:
if c not in cls.digits:
break
... |
def cli(ctx, apiurl, signature, username, password):
"""Command line interface for YOURLS.
Configuration parameters can be passed as switches or stored in .yourls or
~/.yourls.
If your YOURLS server requires authentication, please provide one of the
following:
\b
• apiurl and signature
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.