INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Start a new site. | def scaffold():
"""Start a new site."""
click.echo("A whole new site? Awesome.")
title = click.prompt("What's the title?")
url = click.prompt("Great. What's url? http://")
# Make sure that title doesn't exist.
click.echo("Got it. Creating %s..." % url) |
Publish the site | def publish():
"""Publish the site"""
try:
build_site(dev_mode=False, clean=True)
click.echo('Deploying the site...')
# call("firebase deploy", shell=True)
call("rsync -avz -e ssh --progress %s/ %s" % (BUILD_DIR, CONFIG["scp_target"],), shell=True)
if "cloudflare" in CONF... |
Schedule all the social media posts. | def promote():
"""Schedule all the social media posts."""
if "BUFFER_ACCESS_TOKEN" not in os.environ:
warn("Missing BUFFER_ACCESS_TOKEN.")
echo("To publish to social medial, you'll need an access token for buffer.")
echo("The simplest way to get one is to create a new app here: https://... |
Returns a list of the branches | def get_branches(self):
"""Returns a list of the branches"""
return [self._sanitize(branch)
for branch in self._git.branch(color="never").splitlines()] |
Returns the currently active branch | def get_current_branch(self):
"""Returns the currently active branch"""
return next((self._sanitize(branch)
for branch in self._git.branch(color="never").splitlines()
if branch.startswith('*')),
None) |
Create a patch between tags | def create_patch(self, from_tag, to_tag):
"""Create a patch between tags"""
return str(self._git.diff('{}..{}'.format(from_tag, to_tag), _tty_out=False)) |
Create a callable that applies func to a value in a sequence. | def one(func, n=0):
"""
Create a callable that applies ``func`` to a value in a sequence.
If the value is not a sequence or is an empty sequence then ``None`` is
returned.
:type func: `callable`
:param func: Callable to be applied to each result.
:type n: `int`
:param n: Index of th... |
Create a callable that applies func to every value in a sequence. | def many(func):
"""
Create a callable that applies ``func`` to every value in a sequence.
If the value is not a sequence then an empty list is returned.
:type func: `callable`
:param func: Callable to be applied to the first result.
"""
def _many(result):
if _isSequenceTypeNotText... |
Parse a value as text. | def Text(value, encoding=None):
"""
Parse a value as text.
:type value: `unicode` or `bytes`
:param value: Text value to parse
:type encoding: `bytes`
:param encoding: Encoding to treat ``bytes`` values as, defaults to
``utf-8``.
:rtype: `unicode`
:return: Parsed text or ``N... |
Parse a value as an integer. | def Integer(value, base=10, encoding=None):
"""
Parse a value as an integer.
:type value: `unicode` or `bytes`
:param value: Text value to parse
:type base: `unicode` or `bytes`
:param base: Base to assume ``value`` is specified in.
:type encoding: `bytes`
:param encoding: Encoding... |
Parse a value as a boolean. | def Boolean(value, true=(u'yes', u'1', u'true'), false=(u'no', u'0', u'false'),
encoding=None):
"""
Parse a value as a boolean.
:type value: `unicode` or `bytes`
:param value: Text value to parse.
:type true: `tuple` of `unicode`
:param true: Values to compare, ignoring case, for... |
Parse a value as a delimited list. | def Delimited(value, parser=Text, delimiter=u',', encoding=None):
"""
Parse a value as a delimited list.
:type value: `unicode` or `bytes`
:param value: Text value to parse.
:type parser: `callable` taking a `unicode` parameter
:param parser: Callable to map over the delimited text values.
... |
Parse a value as a POSIX timestamp in seconds. | def Timestamp(value, _divisor=1., tz=UTC, encoding=None):
"""
Parse a value as a POSIX timestamp in seconds.
:type value: `unicode` or `bytes`
:param value: Text value to parse, which should be the number of seconds
since the epoch.
:type _divisor: `float`
:param _divisor: Number to ... |
Parse query parameters. | def parse(expected, query):
"""
Parse query parameters.
:type expected: `dict` mapping `bytes` to `callable`
:param expected: Mapping of query argument names to argument parsing
callables.
:type query: `dict` mapping `bytes` to `list` of `bytes`
:param query: Mapping of query argumen... |
Put metrics to cloudwatch. Metric shoult be instance or list of instances of CloudWatchMetric | def put(self, metrics):
"""
Put metrics to cloudwatch. Metric shoult be instance or list of
instances of CloudWatchMetric
"""
if type(metrics) == list:
for metric in metrics:
self.c.put_metric_data(**metric)
else:
self.c.put_metric_... |
Render a given resource. | def _renderResource(resource, request):
"""
Render a given resource.
See `IResource.render <twisted:twisted.web.resource.IResource.render>`.
"""
meth = getattr(resource, 'render_' + nativeString(request.method), None)
if meth is None:
try:
allowedMethods = resource.allowedMe... |
Adapt a result to IResource. | def _adaptToResource(self, result):
"""
Adapt a result to `IResource`.
Several adaptions are tried they are, in order: ``None``,
`IRenderable <twisted:twisted.web.iweb.IRenderable>`, `IResource
<twisted:twisted.web.resource.IResource>`, and `URLPath
<twisted:twisted.pyth... |
Handle the result from IResource. render. | def _handleRenderResult(self, request, result):
"""
Handle the result from `IResource.render`.
If the result is a `Deferred` then return `NOT_DONE_YET` and add
a callback to write the result to the request when it arrives.
"""
def _requestFinished(result, cancel):
... |
Negotiate a handler based on the content types acceptable to the client. | def _negotiateHandler(self, request):
"""
Negotiate a handler based on the content types acceptable to the
client.
:rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes`
:return: Pair of a resource and the content type.
"""
accept = _parseAccept(request.re... |
Parse and sort an Accept header. | def _parseAccept(headers):
"""
Parse and sort an ``Accept`` header.
The header is sorted according to the ``q`` parameter for each header value.
@rtype: `OrderedDict` mapping `bytes` to `dict`
@return: Mapping of media types to header parameters.
"""
def sort(value):
return float(v... |
Split an HTTP header whose components are separated with commas. | def _splitHeaders(headers):
"""
Split an HTTP header whose components are separated with commas.
Each component is then split on semicolons and the component arguments
converted into a `dict`.
@return: `list` of 2-`tuple` of `bytes`, `dict`
@return: List of header arguments and mapping of comp... |
Extract an encoding from a Content - Type header. | def contentEncoding(requestHeaders, encoding=None):
"""
Extract an encoding from a ``Content-Type`` header.
@type requestHeaders: `twisted.web.http_headers.Headers`
@param requestHeaders: Request headers.
@type encoding: `bytes`
@param encoding: Default encoding to assume if the ``Content-Ty... |
Create a nil - safe callable decorator. | def maybe(f, default=None):
"""
Create a nil-safe callable decorator.
If the wrapped callable receives ``None`` as its argument, it will return
``None`` immediately.
"""
@wraps(f)
def _maybe(x, *a, **kw):
if x is None:
return default
return f(x, *a, **kw)
ret... |
Get or set Settings. _wrapped | def settings(path=None, with_path=None):
"""
Get or set `Settings._wrapped`
:param str path: a python module file,
if user set it,write config to `Settings._wrapped`
:param str with_path: search path
:return: A instance of `Settings`
"""
if path:
Settings.bind(path, with_pa... |
bind user variable to _wrapped | def bind(mod_path, with_path=None):
"""
bind user variable to `_wrapped`
.. note::
you don't need call this method by yourself.
program will call it in `cliez.parser.parse`
.. expection::
if path is not correct,will cause an `ImportError`
... |
Get the version from version module without importing more than necessary. | def get_version():
"""
Get the version from version module without importing more than
necessary.
"""
version_module_path = os.path.join(
os.path.dirname(__file__), "txspinneret", "_version.py")
# The version module contains a variable called __version__
with open(version_module_path... |
send a transaction immediately. Failed transactions are picked up by the TxBroadcaster | def send(self, use_open_peers=True, queue=True, **kw):
"""
send a transaction immediately. Failed transactions are picked up by the TxBroadcaster
:param ip: specific peer IP to send tx to
:param port: port of specific peer
:param use_open_peers: use Arky's broadcast method
... |
check if a tx is confirmed else resend it. | def check_confirmations_or_resend(self, use_open_peers=False, **kw):
"""
check if a tx is confirmed, else resend it.
:param use_open_peers: select random peers fro api/peers endpoint
"""
if self.confirmations() == 0:
self.send(use_open_peers, **kw) |
Get sub - command list | def command_list():
"""
Get sub-command list
.. note::
Don't use logger handle this function errors.
Because the error should be a code error,not runtime error.
:return: `list` matched sub-parser
"""
from cliez.conf import COMPONENT_ROOT
root = COMPONENT_ROOT
if ro... |
Add class options to argparser options. | def append_arguments(klass, sub_parsers, default_epilog, general_arguments):
"""
Add class options to argparser options.
:param cliez.component.Component klass: subclass of Component
:param Namespace sub_parsers:
:param str default_epilog: default_epilog
:param list general_arguments: global op... |
parser cliez app | def parse(parser, argv=None, settings_key='settings', no_args_func=None):
"""
parser cliez app
:param argparse.ArgumentParser parser: an instance
of argparse.ArgumentParser
:param argv: argument list,default is `sys.argv`
:type argv: list or tuple
:param str settings: settings option n... |
.. deprecated 2. 1:: Don t use this any more. | def include_file(filename, global_vars=None, local_vars=None):
"""
.. deprecated 2.1::
Don't use this any more.
It's not pythonic.
include file like php include.
include is very useful when we need to split large config file
"""
if global_vars is None:
global_vars = s... |
Convert Hump style to underscore | def hump_to_underscore(name):
"""
Convert Hump style to underscore
:param name: Hump Character
:return: str
"""
new_name = ''
pos = 0
for c in name:
if pos == 0:
new_name = c.lower()
elif 65 <= ord(c) <= 90:
new_name += '_' + c.lower()
... |
Fetches fuel prices for all stations. | def get_fuel_prices(self) -> GetFuelPricesResponse:
"""Fetches fuel prices for all stations."""
response = requests.get(
'{}/prices'.format(API_URL_BASE),
headers=self._get_headers(),
timeout=self._timeout,
)
if not response.ok:
raise Fuel... |
Gets the fuel prices for a specific fuel station. | def get_fuel_prices_for_station(
self,
station: int
) -> List[Price]:
"""Gets the fuel prices for a specific fuel station."""
response = requests.get(
'{}/prices/station/{}'.format(API_URL_BASE, station),
headers=self._get_headers(),
timeou... |
Gets all the fuel prices within the specified radius. | def get_fuel_prices_within_radius(
self, latitude: float, longitude: float, radius: int,
fuel_type: str, brands: Optional[List[str]] = None
) -> List[StationPrice]:
"""Gets all the fuel prices within the specified radius."""
if brands is None:
brands = []
... |
Gets the fuel price trends for the given location and fuel types. | def get_fuel_price_trends(self, latitude: float, longitude: float,
fuel_types: List[str]) -> PriceTrends:
"""Gets the fuel price trends for the given location and fuel types."""
response = requests.post(
'{}/prices/trends/'.format(API_URL_BASE),
json... |
Fetches API reference data. | def get_reference_data(
self,
modified_since: Optional[datetime.datetime] = None
) -> GetReferenceDataResponse:
"""
Fetches API reference data.
:param modified_since: The response will be empty if no
changes have been made to the reference data since this
... |
check and get require config: param dict env: user config node: param list keys: check keys.. note:: | def parse_require(self, env, keys, defaults={}):
"""
check and get require config
:param dict env: user config node
:param list keys: check keys
.. note::
option and key name must be same.
:param dict defaults: default value for keys
:return:... |
Called before template is applied. | def pre(self, command, output_dir, vars):
"""
Called before template is applied.
"""
# import pdb;pdb.set_trace()
vars['license_name'] = 'Apache'
vars['year'] = time.strftime('%Y', time.localtime()) |
Match a route parameter. | def Text(name, encoding=None):
"""
Match a route parameter.
`Any` is a synonym for `Text`.
:type name: `bytes`
:param name: Route parameter name.
:type encoding: `bytes`
:param encoding: Default encoding to assume if the ``Content-Type``
header is lacking one.
:return: ``ca... |
Match an integer route parameter. | def Integer(name, base=10, encoding=None):
"""
Match an integer route parameter.
:type name: `bytes`
:param name: Route parameter name.
:type base: `int`
:param base: Base to interpret the value in.
:type encoding: `bytes`
:param encoding: Default encoding to assume if the ``Conten... |
Match a request path against our path components. | def _matchRoute(components, request, segments, partialMatching):
"""
Match a request path against our path components.
The path components are always matched relative to their parent is in the
resource hierarchy, in other words it is only possible to match URIs nested
more deeply than the parent re... |
Decorate a router - producing callable to instead produce a resource. | def routedResource(f, routerAttribute='router'):
"""
Decorate a router-producing callable to instead produce a resource.
This simply produces a new callable that invokes the original callable, and
calls ``resource`` on the ``routerAttribute``.
If the router producer has multiple routers the attrib... |
Create a new Router instance with it s own set of routes for obj. | def _forObject(self, obj):
"""
Create a new `Router` instance, with it's own set of routes, for
``obj``.
"""
router = type(self)()
router._routes = list(self._routes)
router._self = obj
return router |
Add a route handler and matcher to the collection of possible routes. | def _addRoute(self, f, matcher):
"""
Add a route handler and matcher to the collection of possible routes.
"""
self._routes.append((f.func_name, f, matcher)) |
See txspinneret. route. route. | def route(self, *components):
"""
See `txspinneret.route.route`.
This decorator can be stacked with itself to specify multiple routes
with a single handler.
"""
def _factory(f):
self._addRoute(f, route(*components))
return f
return _factor... |
See txspinneret. route. subroute. | def subroute(self, *components):
"""
See `txspinneret.route.subroute`.
This decorator can be stacked with itself to specify multiple routes
with a single handler.
"""
def _factory(f):
self._addRoute(f, subroute(*components))
return f
retur... |
Create a NamedTemporaryFile instance to be passed to atomic_writer | def _tempfile(filename):
"""
Create a NamedTemporaryFile instance to be passed to atomic_writer
"""
return tempfile.NamedTemporaryFile(mode='w',
dir=os.path.dirname(filename),
prefix=os.path.basename(filename),
... |
Open a NamedTemoraryFile handle in a context manager | def atomic_write(filename):
"""
Open a NamedTemoraryFile handle in a context manager
"""
f = _tempfile(os.fsencode(filename))
try:
yield f
finally:
f.close()
# replace the original file with the new temp file (atomic on success)
os.replace(f.name, filename) |
Read entry from JSON file | def get_item(filename, uuid):
"""
Read entry from JSON file
"""
with open(os.fsencode(str(filename)), "r") as f:
data = json.load(f)
results = [i for i in data if i["uuid"] == str(uuid)]
if results:
return results
return None |
Save entry to JSON file | def set_item(filename, item):
"""
Save entry to JSON file
"""
with atomic_write(os.fsencode(str(filename))) as temp_file:
with open(os.fsencode(str(filename))) as products_file:
# load the JSON data into memory
products_data = json.load(products_file)
# check if U... |
Update entry by UUID in the JSON file | def update_item(filename, item, uuid):
"""
Update entry by UUID in the JSON file
"""
with atomic_write(os.fsencode(str(filename))) as temp_file:
with open(os.fsencode(str(filename))) as products_file:
# load the JSON data into memory
products_data = json.load(products_fil... |
.. todo:: | def run(self, options):
"""
.. todo::
check network connection
:param Namespace options: parse result from argparse
:return:
"""
self.logger.debug("debug enabled...")
depends = ['git']
nil_tools = []
self.logger.info("depends list: ... |
: param commit: the commit that all the experiments should have happened or None to include all: type commit: str: param must_contain_results: include only tags that contain results: type must_contain_results: bool: return: all the experiment data: rtype: dict | def experiment_data(self, commit=None, must_contain_results=False):
"""
:param commit: the commit that all the experiments should have happened or None to include all
:type commit: str
:param must_contain_results: include only tags that contain results
:type must_contain_results:... |
Delete an experiment by removing the associated tag.: param experiment_name: the name of the experiment to be deleted: type experiment_name: str: rtype bool: return if deleting succeeded | def delete(self, experiment_name):
"""
Delete an experiment by removing the associated tag.
:param experiment_name: the name of the experiment to be deleted
:type experiment_name: str
:rtype bool
:return if deleting succeeded
"""
if not experiment_name.sta... |
Register your own mode and handle method here. | def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'command':
plugin.command_handle()
else:
plugin.unknown("Unknown actions.") |
Get the number of the shell command. | def command_handle(self):
"""Get the number of the shell command."""
self.__results = self.execute(self.args.command)
self.close()
self.logger.debug("results: {}".format(self.__results))
if not self.__results:
self.unknown("{} return nothing.".format(self.args.comman... |
Execute a shell command. | def execute(self, command, timeout=None):
"""Execute a shell command."""
try:
self.channel = self.ssh.get_transport().open_session()
except paramiko.SSHException as e:
self.unknown("Create channel error: %s" % e)
try:
self.channel.settimeout(self.args.... |
Close and exit the connection. | def close(self):
"""Close and exit the connection."""
try:
self.ssh.close()
self.logger.debug("close connect succeed.")
except paramiko.SSHException as e:
self.unknown("close connect error: %s" % e) |
Simple program that creates an temp S3 link. | def slinky(filename, seconds_available, bucket_name, aws_key, aws_secret):
"""Simple program that creates an temp S3 link."""
if not os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):
print 'Need to set environment variables for AWS access and create a slinky bucket.'
exi... |
Poll self. stdout and return True if it is readable. | def check_readable(self, timeout):
"""
Poll ``self.stdout`` and return True if it is readable.
:param float timeout: seconds to wait I/O
:return: True if readable, else False
:rtype: boolean
"""
rlist, wlist, xlist = select.select([self._stdout], [], [], timeout)... |
Retrieve a list of characters and escape codes where each escape code uses only one index. The indexes will not match up with the indexes in the original string. | def get_indices_list(s: Any) -> List[str]:
""" Retrieve a list of characters and escape codes where each escape
code uses only one index. The indexes will not match up with the
indexes in the original string.
"""
indices = get_indices(s)
return [
indices[i] for i in sorted(indice... |
Strip all color codes from a string. Returns empty string for falsey inputs. | def strip_codes(s: Any) -> str:
""" Strip all color codes from a string.
Returns empty string for "falsey" inputs.
"""
return codepat.sub('', str(s) if (s or (s == 0)) else '') |
Called when builder group collect files Resolves absolute url if relative passed | def init_build(self, asset, builder):
"""
Called when builder group collect files
Resolves absolute url if relative passed
:type asset: static_bundle.builders.Asset
:type builder: static_bundle.builders.StandardBuilder
"""
if not self.abs_path:
rel_pa... |
Add single file or list of files to bundle | def add_file(self, *args):
"""
Add single file or list of files to bundle
:type: file_path: str|unicode
"""
for file_path in args:
self.files.append(FilePath(file_path, self)) |
Add directory or directories list to bundle | def add_directory(self, *args, **kwargs):
"""
Add directory or directories list to bundle
:param exclusions: List of excluded paths
:type path: str|unicode
:type exclusions: list
"""
exc = kwargs.get('exclusions', None)
for path in args:
self... |
Add custom path objects | def add_path_object(self, *args):
"""
Add custom path objects
:type: path_object: static_bundle.paths.AbstractPath
"""
for obj in args:
obj.bundle = self
self.files.append(obj) |
Add prepare handler to bundle | def add_prepare_handler(self, prepare_handlers):
"""
Add prepare handler to bundle
:type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler
"""
if not isinstance(prepare_handlers, static_bundle.BUNDLE_ITERABLE_TYPES):
prepare_handlers = [prepare_handlers... |
Called when builder run collect files in builder group | def prepare(self):
"""
Called when builder run collect files in builder group
:rtype: list[static_bundle.files.StaticFileResult]
"""
result_files = self.collect_files()
chain = self.prepare_handlers_chain
if chain is None:
# default handlers
... |
Register your own mode and handle method here. | def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'filenumber':
plugin.filenumber_handle()
else:
plugin.unknown("Unknown actions.") |
Get the number of files in the folder. | def filenumber_handle(self):
"""Get the number of files in the folder."""
self.__results = []
self.__dirs = []
self.__files = []
self.__ftp = self.connect()
self.__ftp.dir(self.args.path, self.__results.append)
self.logger.debug("dir results: {}".format(self.__res... |
Register the contents as JSON | def register_json(self, data):
"""
Register the contents as JSON
"""
j = json.loads(data)
self.last_data_timestamp = \
datetime.datetime.utcnow().replace(microsecond=0).isoformat()
try:
for v in j:
# prepare the sensor entry con... |
Get the data in text form ( i. e. human readable ) | def get_text(self):
"""
Get the data in text form (i.e. human readable)
"""
t = "==== " + str(self.last_data_timestamp) + " ====\n"
for k in self.data:
t += k + " " + str(self.data[k][self.value_key])
u = ""
if self.unit_key in self.data[k]:
... |
Translate the data with the translation table | def get_translated_data(self):
"""
Translate the data with the translation table
"""
j = {}
for k in self.data:
d = {}
for l in self.data[k]:
d[self.translation_keys[l]] = self.data[k][l]
j[k] = d
return j |
Get the data in JSON form | def get_json(self, prettyprint=False, translate=True):
"""
Get the data in JSON form
"""
j = []
if translate:
d = self.get_translated_data()
else:
d = self.data
for k in d:
j.append(d[k])
if prettyprint:
j = ... |
Get the data as JSON tuples | def get_json_tuples(self, prettyprint=False, translate=True):
"""
Get the data as JSON tuples
"""
j = self.get_json(prettyprint, translate)
if len(j) > 2:
if prettyprint:
j = j[1:-2] + ",\n"
else:
j = j[1:-1] + ","
e... |
Issues a GET request against the API properly formatting the params | def get(self, url, params={}):
"""
Issues a GET request against the API, properly formatting the params
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the paramaters needed
in the request
:returns: a dict parse... |
Issues a POST request against the API allows for multipart data uploads | def post(self, url, params={}, files=None):
"""
Issues a POST request against the API, allows for multipart data uploads
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the parameters needed
in the request
:para... |
Wraps and abstracts content validation and JSON parsing to make sure the user gets the correct response.: param content: The content returned from the web request to be parsed as json: returns: a dict of the json response | def json_parse(self, content):
"""
Wraps and abstracts content validation and JSON parsing
to make sure the user gets the correct response.
:param content: The content returned from the web request to be parsed as json
:returns: a dict of the json response
... |
Go through the env var map transferring the values to this object as attributes. | def load_values(self):
"""
Go through the env var map, transferring the values to this object
as attributes.
:raises: RuntimeError if a required env var isn't defined.
"""
for config_name, evar in self.evar_defs.items():
if evar.is_required and evar.name not... |
Create a temporary directory with input data for the test. The directory contents is copied from a directory with the same name as the module located in the same directory of the test module. | def embed_data(request):
"""
Create a temporary directory with input data for the test.
The directory contents is copied from a directory with the same name as the module located in the same directory of
the test module.
"""
result = _EmbedDataFixture(request)
result.delete_data_dir()
re... |
Returns an absolute filename in the data - directory ( standardized by StandardizePath ). | def get_filename(self, *parts):
'''
Returns an absolute filename in the data-directory (standardized by StandardizePath).
@params parts: list(unicode)
Path parts. Each part is joined to form a path.
:rtype: unicode
:returns:
The full path prefixed with t... |
Compare two files contents. If the files differ show the diff and write a nice HTML diff file into the data directory. | def assert_equal_files(self, obtained_fn, expected_fn, fix_callback=lambda x:x, binary=False, encoding=None):
'''
Compare two files contents. If the files differ, show the diff and write a nice HTML
diff file into the data directory.
Searches for the filenames both inside and outside th... |
Returns a nice side - by - side diff of the given files as a string. | def _generate_html_diff(self, expected_fn, expected_lines, obtained_fn, obtained_lines):
"""
Returns a nice side-by-side diff of the given files, as a string.
"""
import difflib
differ = difflib.HtmlDiff()
return differ.make_file(
fromlines=expected_lines,
... |
Add a peer or multiple peers to the PEERS variable takes a single string or a list. | def add_peer(self, peer):
"""
Add a peer or multiple peers to the PEERS variable, takes a single string or a list.
:param peer(list or string)
"""
if type(peer) == list:
for i in peer:
check_url(i)
self.PEERS.extend(peer)
elif type... |
remove one or multiple peers from PEERS variable | def remove_peer(self, peer):
"""
remove one or multiple peers from PEERS variable
:param peer(list or string):
"""
if type(peer) == list:
for x in peer:
check_url(x)
for i in self.PEERS:
if x in i:
... |
check the status of the network and the peers | def status(self):
"""
check the status of the network and the peers
:return: network_height, peer_status
"""
peer = random.choice(self.PEERS)
formatted_peer = 'http://{}:4001'.format(peer)
peerdata = requests.get(url=formatted_peer + '/api/peers/').json()['peers'... |
broadcasts a transaction to the peerslist using ark - js library | def broadcast_tx(self, address, amount, secret, secondsecret=None, vendorfield=''):
"""broadcasts a transaction to the peerslist using ark-js library"""
peer = random.choice(self.PEERS)
park = Park(
peer,
4001,
constants.ARK_NETHASH,
'1.1.1'
... |
Exposes a given service to this API. | def register(self, service, name=''):
"""
Exposes a given service to this API.
"""
try:
is_model = issubclass(service, orb.Model)
except StandardError:
is_model = False
# expose an ORB table dynamically as a service
if is_model:
... |
Register your own mode and handle method here. | def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'sql':
plugin.sql_handle()
else:
plugin.unknown("Unknown actions.") |
: type input_files: list [ static_bundle. files. StaticFileResult ]: type bundle: static_bundle. bundles. AbstractBundle: rtype: list | def prepare(self, input_files, bundle):
"""
:type input_files: list[static_bundle.files.StaticFileResult]
:type bundle: static_bundle.bundles.AbstractBundle
:rtype: list
"""
out = []
for input_file in input_files:
if input_file.extension == "less" and ... |
Main entry point expects doctopt arg dict as argd. | def main():
""" Main entry point, expects doctopt arg dict as argd. """
global DEBUG
argd = docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT)
DEBUG = argd['--debug']
width = parse_int(argd['--width'] or DEFAULT_WIDTH) or 1
indent = parse_int(argd['--indent'] or (argd['--INDENT'] or 0))
pr... |
Print a message only if DEBUG is truthy. | def debug(*args, **kwargs):
""" Print a message only if DEBUG is truthy. """
if not (DEBUG and args):
return None
# Include parent class name when given.
parent = kwargs.get('parent', None)
with suppress(KeyError):
kwargs.pop('parent')
# Go back more than once when given.
b... |
Parse a string as an integer. Exit with a message on failure. | def parse_int(s):
""" Parse a string as an integer.
Exit with a message on failure.
"""
try:
val = int(s)
except ValueError:
print_err('\nInvalid integer: {}'.format(s))
sys.exit(1)
return val |
If s is a file name read the file and return it s content. Otherwise return the original string. Returns None if the file was opened but errored during reading. | def try_read_file(s):
""" If `s` is a file name, read the file and return it's content.
Otherwise, return the original string.
Returns None if the file was opened, but errored during reading.
"""
try:
with open(s, 'r') as f:
data = f.read()
except FileNotFoundError:
... |
Disconnect and close * Vim *. | def close(self):
"""
Disconnect and close *Vim*.
"""
self._tempfile.close()
self._process.terminate()
if self._process.is_alive():
self._process.kill() |
Send a raw key sequence to * Vim *. | def send_keys(self, keys, wait=True):
"""
Send a raw key sequence to *Vim*.
.. note:: *Vim* style key sequence notation (like ``<Esc>``)
is not recognized.
Use escaped characters (like ``'\033'``) instead.
Example:
>>> import headlessvim
... |
Wait for response until timeout. If timeout is specified to None self. timeout is used. | def wait(self, timeout=None):
"""
Wait for response until timeout.
If timeout is specified to None, ``self.timeout`` is used.
:param float timeout: seconds to wait I/O
"""
if timeout is None:
timeout = self._timeout
while self._process.check_readable(... |
Install * Vim * plugin. | def install_plugin(self, dir, entry_script=None):
"""
Install *Vim* plugin.
:param string dir: the root directory contains *Vim* script
:param string entry_script: path to the initializing script
"""
self.runtimepath.append(dir)
if entry_script is not None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.