text stringlengths 81 112k |
|---|
Merge arguments and rc_settings.
def compute_settings(args, rc_settings):
"""
Merge arguments and rc_settings.
"""
settings = {}
for key, value in args.items():
if key in ['reverse', 'opposite']:
settings[key] = value ^ rc_settings.get(key, False)
else:
setti... |
Output the millipede
def millipede(size, comment=None, reverse=False, template='default', position=0, opposite=False):
"""
Output the millipede
"""
padding_offsets = [2, 1, 0, 1, 2, 3, 4, 4, 3]
padding_suite_length = len(padding_offsets)
head_padding_extra_offset = 2
if opposite:
p... |
Send `message` as `name` to `url`.
You can specify extra variables in `http_data`
def api_post(message, url, name, http_data=None, auth=None):
""" Send `message` as `name` to `url`.
You can specify extra variables in `http_data`
"""
try:
import requests
except ImportError:
print... |
Entry point
def main():
"""
Entry point
"""
rc_settings = read_rcfile()
parser = ArgumentParser(description='Millipede generator')
parser.add_argument('-s', '--size',
type=int,
nargs="?",
help='the size of the millipede')
... |
Read package long description from README file
def read_long_description(readme_file):
""" Read package long description from README file """
try:
import pypandoc
except (ImportError, OSError) as exception:
print('No pypandoc or pandoc: %s' % (exception,))
if sys.version_info.major ... |
Return the content of the specified file as a string.
This function also supports loading resources from packages.
def content_from_path(path, encoding='utf-8'):
"""Return the content of the specified file as a string.
This function also supports loading resources from packages.
"""
if not os.pat... |
Execute the method with args
def execute(self, method, args, ref):
""" Execute the method with args """
response = {'result': None, 'error': None, 'ref': ref}
fun = self.methods.get(method)
if not fun:
response['error'] = 'Method `{}` not found'.format(method)
else:... |
Register function on this service
def register(self, name, fun, description=None):
""" Register function on this service """
self.methods[name] = fun
self.descriptions[name] = description |
Parse client request
def parse(cls, payload):
""" Parse client request """
try:
method, args, ref = payload
except Exception as exception:
raise RequestParseError(exception)
else:
return method, args, ref |
Receive data from socket and process request
def process(self):
""" Receive data from socket and process request """
response = None
try:
payload = self.receive()
method, args, ref = self.parse(payload)
response = self.execute(method, args, ref)
ex... |
Build the payload to be sent to a `Responder`
def build_payload(cls, method, args):
""" Build the payload to be sent to a `Responder` """
ref = str(uuid.uuid4())
return (method, args, ref) |
Make a call to a `Responder` and return the result
def call(self, method, *args):
""" Make a call to a `Responder` and return the result """
payload = self.build_payload(method, args)
logging.debug('* Client will send payload: {}'.format(payload))
self.send(payload)
res = self... |
Read the json file located at `filepath`
If `filecontent` is specified, its content will be json decoded
and loaded instead.
Usage:
config.load(filepath=None, filecontent=None):
Provide either a filepath or a json string
def load(filepath=None, filecontent=None):
""" Read the json fil... |
Runs the checks and exits.
To extend this tool, use this function and set do_exit to False
to get returned the status code.
def run_main(args: argparse.Namespace, do_exit=True) -> None:
"""Runs the checks and exits.
To extend this tool, use this function and set do_exit to False
to get returned t... |
Main entry point for console commands.
def main() -> None:
"""Main entry point for console commands."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--json",
help="output in JSON format",
action="store_true",
default=False)
parser.add_argument(
"--con... |
Set up and return Session object that is set up with retrying. Requires either global user agent to be set or
appropriate user agent parameter(s) to be completed.
Args:
user_agent (Optional[str]): User agent string. HDXPythonUtilities/X.X.X- is prefixed.
user_agent_config_yaml (Optional[str]): ... |
Connect to server
Returns:
None
def connect(self):
# type: () -> None
"""
Connect to server
Returns:
None
"""
if self.connection_type.lower() == 'ssl':
self.server = smtplib.SMTP_SSL(host=self.host, port=self.port, local_hos... |
Send email
Args:
recipients (List[str]): Email recipient
subject (str): Email subject
text_body (str): Plain text email body
html_body (Optional[str]): HTML email body
sender (Optional[str]): Email sender. Defaults to global sender.
**kwar... |
Gets SQLAlchemy session given url. Your tables must inherit
from Base in hdx.utilities.database.
Args:
db_url (str): SQLAlchemy url
Returns:
sqlalchemy.orm.session.Session: SQLAlchemy session
def get_session(db_url):
# type: (str) -> Session
"""Gets SQL... |
Gets PostgreSQL database connection parameters from SQLAlchemy url
Args:
db_url (str): SQLAlchemy url
Returns:
Dict[str,Any]: Dictionary of database connection parameters
def get_params_from_sqlalchemy_url(db_url):
# type: (str) -> Dict[str,Any]
"""Gets Postgre... |
Gets SQLAlchemy url from database connection parameters
Args:
database (Optional[str]): Database name
host (Optional[str]): Host where database is located
port (Union[int, str, None]): Database port
username (Optional[str]): Username to log into database
... |
Waits for PostgreSQL database to be up
Args:
database (Optional[str]): Database name
host (Optional[str]): Host where database is located
port (Union[int, str, None]): Database port
username (Optional[str]): Username to log into database
password (Opt... |
return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint])
def get_unset_cache(self):
"""return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint])
"""
caches = []
if self._cached_api_global_response is None:
caches.append('glo... |
This function gets as arguments an array of dicts through the dicts_objects parameter,
then it'll return the dicts that have a value value_of_filter of the key field_to_filter.
def dicts_filter(dicts_object, field_to_filter, value_of_filter):
"""This function gets as arguments an array of dicts through the ... |
Get filename from url and join to provided folder or temporary folder if no folder supplied, ensuring uniqueness
Args:
url (str): URL to download
folder (Optional[str]): Folder to download it to. Defaults to None (temporary folder).
filename (Optional[str]): Filename to use ... |
Get full url including any additional parameters
Args:
url (str): URL for which to get full url
Returns:
str: Full url including any additional parameters
def get_full_url(self, url):
# type: (str) -> str
"""Get full url including any additional parameters
... |
Get full url for GET request including parameters
Args:
url (str): URL to download
parameters (Optional[Dict]): Parameters to pass. Defaults to None.
Returns:
str: Full url
def get_url_for_get(url, parameters=None):
# type: (str, Optional[Dict]) -> str
... |
Get full url for POST request and all parameters including any in the url
Args:
url (str): URL to download
parameters (Optional[Dict]): Parameters to pass. Defaults to None.
Returns:
Tuple[str, Dict]: (Full url, parameters)
def get_url_params_for_post(url, paramete... |
Setup download from provided url returning the response
Args:
url (str): URL to download
stream (bool): Whether to stream download. Defaults to True.
post (bool): Whether to use POST instead of GET. Defaults to False.
parameters (Optional[Dict]): Parameters to pa... |
Stream file from url and hash it using MD5. Must call setup method first.
Args:
url (str): URL to download
Returns:
str: MD5 hash of file
def hash_stream(self, url):
# type: (str) -> str
"""Stream file from url and hash it using MD5. Must call setup method firs... |
Stream file from url and store in provided folder or temporary folder if no folder supplied.
Must call setup method first.
Args:
url (str): URL to download
filename (Optional[str]): Filename to use for downloaded file. Defaults to None (derive from the url).
folder (... |
Download file from url and store in provided folder or temporary folder if no folder supplied
Args:
url (str): URL to download
folder (Optional[str]): Folder to download it to. Defaults to None.
filename (Optional[str]): Filename to use for downloaded file. Defaults to None ... |
Download url
Args:
url (str): URL to download
post (bool): Whether to use POST instead of GET. Defaults to False.
parameters (Optional[Dict]): Parameters to pass. Defaults to None.
timeout (Optional[float]): Timeout for connecting to URL. Defaults to None (no tim... |
Get Tabulator stream.
Args:
url (str): URL to download
**kwargs:
headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers
file_type (Optional[str]): Type of file. Defaults to inferring.
delimiter (Optional[str... |
Get iterator for reading rows from tabular data. Each row is returned as a dictionary.
Args:
url (str): URL to download
dict_rows (bool): Return dict (requires headers parameter) or list for each row. Defaults to False (list).
**kwargs:
headers (Union[int, List[i... |
Download 2 column csv from url and return a dictionary of keys (first column) and values (second column)
Args:
url (str): URL to download
**kwargs:
headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers
file_type (Optio... |
Download multicolumn csv from url and return dictionary where keys are first column and values are
dictionaries with keys from column headers and values from columns beneath
Args:
url (str): URL to download
headers (Union[int, List[int], List[str]]): Number of row(s) containing ... |
Wizard to create the user-level configuration file.
def setup(ctx, force):
"""Wizard to create the user-level configuration file."""
if os.path.exists(USER_CONFIG) and not force:
click.secho(
'An existing configuration file was found at "{}".\n'
.format(USER_CONFIG),
... |
Wizard to create a project-level configuration file.
def init(ctx, force):
"""Wizard to create a project-level configuration file."""
if os.path.exists(PROJECT_CONFIG) and not force:
click.secho(
'An existing configuration file was found at "{}".\n'
.format(PROJECT_CONFIG),
... |
Forget saved passwords for the web services.
def logout(lancet, service):
"""Forget saved passwords for the web services."""
if service:
services = [service]
else:
services = ['tracker', 'harvest']
for service in services:
url = lancet.config.get(service, 'url')
key = '... |
List all currently configured services.
def _services(lancet):
"""List all currently configured services."""
def get_services(config):
for s in config.sections():
if config.has_option(s, 'url'):
if config.has_option(s, 'username'):
yield s
for s in g... |
: param string 'ticker', it's 'ticker' if we want info about coins,
'global' for global market's info.
: param string 'coin_name', specify the name of the coin, if None,
we'll retrieve info about all available coins.
def send_request(self, endpoint='ticker', coin_name=None, **kwargs... |
return json response from APIs converted into python list
: param string 'data_type', if it's None it'll return the avaliable cache,
if we've both global and ticker data, the function will return 'ticker' data,
in that case, data_type should be assigned with 'ticker' or 'global'
def ... |
Convert a given language identifier into an ISO 639 Part 2 code, such
as "eng" or "deu". This will accept language codes in the two- or three-
letter format, and some language names. If the given string cannot be
converted, ``None`` will be returned.
def iso_639_alpha3(code):
"""Convert a given languag... |
Parse all the language codes in a given list into ISO 639 Part 2 codes
and optionally expand them with synonyms (i.e. other names for the same
language).
def list_to_alpha3(languages, synonyms=True):
"""Parse all the language codes in a given list into ISO 639 Part 2 codes
and optionally expand them wi... |
Create a new pull request for this issue.
def pull_request(ctx, base_branch, open_pr, stop_timer):
"""Create a new pull request for this issue."""
lancet = ctx.obj
review_status = lancet.config.get("tracker", "review_status")
remote_name = lancet.config.get("repository", "remote_name")
if not bas... |
Checkout the branch for the given issue.
It is an error if the branch does no exist yet.
def checkout(lancet, force, issue):
"""
Checkout the branch for the given issue.
It is an error if the branch does no exist yet.
"""
issue = get_issue(lancet, issue)
# Get the working branch
bran... |
Get BeautifulSoup object for a url. Requires either global user agent to be set or appropriate user agent
parameter(s) to be completed.
Args:
url (str): url to read
downloader (Download): Download object. Defaults to creating a Download object with given user agent values.
user_agent (O... |
Extract HTML table as list of dictionaries
Args:
tabletag (Tag): BeautifulSoup tag
Returns:
str: Text of tag stripped of leading and trailing whitespace and newlines and with   replaced with space
def extract_table(tabletag):
# type: (Tag) -> List[Dict]
"""
Extract HTML table ... |
Wraps function-based callable_obj into a `Route` instance, else
proxies a `bottle_neck.handlers.BaseHandler` subclass instance.
Args:
uri (str): The uri relative path.
methods (tuple): A tuple of valid method strings.
callable_obj (instance): The callable object.
... |
Register the route object to a `bottle.Bottle` app instance.
Args:
app (instance):
Returns:
Route instance (for chaining purposes)
def register_app(self, app):
"""Register the route object to a `bottle.Bottle` app instance.
Args:
app (instance):
... |
Register a handler callable to a specific route.
Args:
entrypoint (str): The uri relative path.
methods (tuple): A tuple of valid method strings.
callable_obj (callable): The callable object.
Returns:
The Router instance (for chaining purposes).
... |
Mounts all registered routes to a bottle.py application instance.
Args:
app (instance): A `bottle.Bottle()` application instance.
Returns:
The Router instance (for chaining purposes).
def mount(self, app=None):
"""Mounts all registered routes to a bottle.py application... |
setup logger
@param log_level: debug/info/warning/error/critical
@param log_file: log file path
@param logger_name: the name of logger, default is 'root' if not specify
def setup_logger(log_level, log_file=None, logger_name=None):
"""setup logger
@param log_... |
log with different level
def _tolog(self,level):
""" log with different level """
def wrapper(msg):
if self.log_colors:
color = self.log_colors[level.upper()]
getattr(self.logger, level.lower())(coloring("- {}".format(msg), color))
else:
... |
Returns a class method from bottle.HTTPError.status_line attribute.
Useful for patching `bottle.HTTPError` for web services.
Args:
status_line (str): bottle.HTTPError.status_line text.
msg: The message data for response.
Returns:
Class method based on statu... |
Shortcut API for HTTP 201 `Created` response.
Args:
data (object): Response key/value data.
Returns:
WSResponse Instance.
def created(cls, data=None):
"""Shortcut API for HTTP 201 `Created` response.
Args:
data (object): Response key/value data.
... |
Shortcut API for HTTP 304 `Not Modified` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
def not_modified(cls, errors=None):
"""Shortcut API for HTTP 304 `Not Modified` response.
Args:
errors (list): Response k... |
Shortcut API for HTTP 400 `Bad Request` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
def bad_request(cls, errors=None):
"""Shortcut API for HTTP 400 `Bad Request` response.
Args:
errors (list): Response key/... |
Shortcut API for HTTP 401 `Unauthorized` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
def unauthorized(cls, errors=None):
"""Shortcut API for HTTP 401 `Unauthorized` response.
Args:
errors (list): Response k... |
Shortcut API for HTTP 403 `Forbidden` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
def forbidden(cls, errors=None):
"""Shortcut API for HTTP 403 `Forbidden` response.
Args:
errors (list): Response key/value ... |
Shortcut API for HTTP 404 `Not found` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
def not_found(cls, errors=None):
"""Shortcut API for HTTP 404 `Not found` response.
Args:
errors (list): Response key/value ... |
Shortcut API for HTTP 405 `Method not allowed` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
def method_not_allowed(cls, errors=None):
"""Shortcut API for HTTP 405 `Method not allowed` response.
Args:
errors ... |
Shortcut API for HTTP 501 `Not Implemented` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
def not_implemented(cls, errors=None):
"""Shortcut API for HTTP 501 `Not Implemented` response.
Args:
errors (list): R... |
Shortcut API for HTTP 503 `Service Unavailable` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
def service_unavailable(cls, errors=None):
"""Shortcut API for HTTP 503 `Service Unavailable` response.
Args:
erro... |
Short cut for JSON response service data.
Returns:
Dict that implements JSON interface.
def to_json(self):
"""Short cut for JSON response service data.
Returns:
Dict that implements JSON interface.
"""
web_resp = collections.OrderedDict()
web_... |
Setup logging configuration
Args:
**kwargs: See below
logging_config_dict (dict): Logging configuration dictionary OR
logging_config_json (str): Path to JSON Logging configuration OR
logging_config_yaml (str): Path to YAML Logging configuration. Defaults to internal logging_configur... |
A helper method for `self.search` that returns a generator rather than a list.
def _search_generator(self, item: Any, reverse: bool = False) -> Generator[Any, None, None]:
"""A helper method for `self.search` that returns a generator rather than a list."""
results = 0
for _, x in self.enumerate... |
A helper method for `self.search` that returns a generator rather than a list.
def _search_generator(self, item: Any) -> Generator[Any, None, None]:
"""A helper method for `self.search` that returns a generator rather than a list."""
results = 0
for x in self.enumerate(item):
yield ... |
A helper method for `self.search` that returns a generator rather than a list.
def _search_generator(self, item: Any) -> Generator[Tuple[Any, Any], None, None]:
"""A helper method for `self.search` that returns a generator rather than a list."""
results = 0
for key, value in self.enumerate(item... |
Asks a question yes no style
def ask_bool(question: str, default: bool = True) -> bool:
"""Asks a question yes no style"""
default_q = "Y/n" if default else "y/N"
answer = input("{0} [{1}]: ".format(question, default_q))
lower = answer.lower()
if not lower:
return default
return lower =... |
Asks for a number in a question
def ask_int(question: str, default: int = None) -> int:
"""Asks for a number in a question"""
default_q = " [default: {0}]: ".format(
default) if default is not None else ""
answer = input("{0} [{1}]: ".format(question, default_q))
if not answer:
if defa... |
Asks for a path
def ask_path(question: str, default: str = None) -> str:
"""Asks for a path"""
default_q = " [default: {0}]: ".format(
default) if default is not None else ""
answer = input("{0} [{1}]: ".format(question, default_q))
if answer == "":
return default
if os.path.isdir... |
Asks for a comma seperated list of strings
def ask_list(question: str, default: list = None) -> list:
"""Asks for a comma seperated list of strings"""
default_q = " [default: {0}]: ".format(
",".join(default)) if default is not None else ""
answer = input("{0} [{1}]: ".format(question, default_q))
... |
Asks for a simple string
def ask_str(question: str, default: str = None):
"""Asks for a simple string"""
default_q = " [default: {0}]: ".format(
default) if default is not None else ""
answer = input("{0} [{1}]: ".format(question, default_q))
if answer == "":
return default
return ... |
Lets the user enter the tools he want to use
def get_tools(self) -> list:
"""Lets the user enter the tools he want to use"""
tools = "flake8,pylint,vulture,pyroma,isort,yapf,safety,dodgy,pytest,pypi".split(
",")
print("Available tools: {0}".format(",".join(tools)))
answer = ... |
The main function for generating the config file
def main(self) -> None:
"""The main function for generating the config file"""
path = ask_path("where should the config be stored?", ".snekrc")
conf = configobj.ConfigObj()
tools = self.get_tools()
for tool in tools:
... |
Compute pagination info for collection filtering.
Args:
limit (int): Collection filter limit.
offset (int): Collection filter offset.
record_count (int): Collection filter total record count.
base_uri (str): Collection filter base uri (without limit, offset)
page_nav_tpl (st... |
JSON serializer that accepts datetime & date
def serialize(obj):
"""JSON serializer that accepts datetime & date"""
from datetime import datetime, date, time
if isinstance(obj, date) and not isinstance(obj, datetime):
obj = datetime.combine(obj, time.min)
if isinstance(obj, datetime):
r... |
Check whether the status code of the response equals expected_status and
raise an APIError otherwise.
@param url: The url of the response (for error messages).
Defaults to response.url
@param json: if True, return r.json(), otherwise return r.text
def check(response, expected_status=200, ur... |
Get the authentication info for the current user, from
1) a ~/.amcatauth file, which should be a csv file
containing host, username, password entries
2) the AMCAT_USER (or USER) and AMCAT_PASSWORD environment variables
def _get_auth(self, user=None, password=None):
"""
Get the... |
Make an HTTP request to the given relative URL with the host,
user, and password information. Returns the deserialized json
if successful, and raises an exception otherwise
def request(self, url, method="get", format="json", data=None,
expected_status=None, headers=None, use_xpost=True,... |
Get all pages at url, yielding individual results
:param url: the url to fetch
:param page: start from this page
:param page_size: results per page
:param yield_pages: yield whole pages rather than individual results
:param filters: additional filters
:return: a generator... |
Scroll through the resource at url and yield the individual results
:param url: url to scroll through
:param page_size: results per page
:param yield_pages: yield whole pages rather than individual results
:param filters: Additional filters
:return: a generator of objects (dicts)... |
Get the AmCAT status page
def get_status(self):
"""Get the AmCAT status page"""
url = URL.status.format(**locals())
return self.get_request(url) |
Conduct an aggregate query
def aggregate(self, **filters):
"""Conduct an aggregate query"""
url = URL.aggregate.format(**locals())
return self.get_pages(url, **filters) |
List the articlesets in a project
def list_sets(self, project, **filters):
"""List the articlesets in a project"""
url = URL.articlesets.format(**locals())
return self.get_pages(url, **filters) |
List the articlesets in a project
def get_set(self, project, articleset, **filters):
"""List the articlesets in a project"""
url = URL.articleset.format(**locals())
return self.request(url, **filters) |
List the articles in a set
def list_articles(self, project, articleset, page=1, **filters):
"""List the articles in a set"""
url = URL.article.format(**locals())
return self.get_pages(url, page=page, **filters) |
Create a new article set. Provide the needed arguments using
post_data or with key-value pairs
def create_set(self, project, json_data=None, **options):
"""
Create a new article set. Provide the needed arguments using
post_data or with key-value pairs
"""
url = URL.artic... |
Create one or more articles in the set. Provide the needed arguments
using the json_data or with key-value pairs
@param json_data: A dictionary or list of dictionaries. Each dict
can contain a 'children' attribute which
is another list of dictionaries.... |
Return authentication signature of encoded bytes
def sign(self, encoded):
""" Return authentication signature of encoded bytes """
signature = self._hmac.copy()
signature.update(encoded)
return signature.hexdigest().encode('utf-8') |
Split into signature and message
def split(self, encoded):
""" Split into signature and message """
maxlen = len(encoded) - self.sig_size
message = encoded[:maxlen]
signature = encoded[-self.sig_size:]
return message, signature |
Validate integrity of encoded bytes
def auth(self, encoded):
""" Validate integrity of encoded bytes """
message, signature = self.split(encoded)
computed = self.sign(message)
if not hmac.compare_digest(signature, computed):
raise AuthenticatorInvalidSignature |
A memorization decorator for class properties.
It implements the above `classproperty` decorator, with
the difference that the function result is computed and attached
to class as direct attribute. (Lazy loading and caching.)
def cached_classproperty(fun):
"""A memorization decorator for class prope... |
Plugin Method decorator.
Signs a web handler function with the plugins to be applied as attributes.
Args:
plugin_names (list): A list of plugin callable names
Returns:
A wrapped handler callable.
Examples:
>>> @plugin_method('json', 'bill')
... def method():
..... |
Custom handler routing decorator.
Signs a web handler callable with the http method as attribute.
Args:
method_name (str): HTTP method name (i.e GET, POST)
extra_part (bool): Indicates if wrapped callable name should be a part
of the actual endpoint.
Returns:
... |
Create a new issue on the issue tracker.
def issue_add(lancet, assign, add_to_sprint, summary):
"""
Create a new issue on the issue tracker.
"""
summary = " ".join(summary)
issue = create_issue(
lancet,
summary,
# project_id=project_id,
add_to_active_sprint=add_to_sp... |
DRY helper. If the specified attribute of the user differs from the
specified value, it will be updated.
def _maybe_update(self, user, attribute, new_value):
"""
DRY helper. If the specified attribute of the user differs from the
specified value, it will be updated.
"""
... |
DRY helper.
Requiring the user to specify both username and email will help catch
certain issues, for example if the expected username has already been
taken by someone else.
def _check_email_match(self, user, email):
"""
DRY helper.
Requiring the user to specify both ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.