sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def filter_module(module, filter_type): """ filter functions or variables from import module @params module: imported module filter_type: "function" or "variable" """ filter_type = ModuleUtils.is_function if filter_type == "function" else ModuleUtils.is_vari...
filter functions or variables from import module @params module: imported module filter_type: "function" or "variable"
entailment
def search_conf_item(start_path, item_type, item_name): """ search expected function or variable recursive upward @param start_path: search start path item_type: "function" or "variable" item_name: function name or variable name e.g. search_...
search expected function or variable recursive upward @param start_path: search start path item_type: "function" or "variable" item_name: function name or variable name e.g. search_conf_item('C:/Users/RockFeng/Desktop/s/preference.py','function','tes...
entailment
def find_data_files(source,target,patterns,isiter=False): """Locates the specified data-files and returns the matches; filesystem tree for setup's data_files in setup.py Usage: data_files = find_data_files(r"C:\Python27\Lib\site-packages\numpy\core","numpy/core",["*....
Locates the specified data-files and returns the matches; filesystem tree for setup's data_files in setup.py Usage: data_files = find_data_files(r"C:\Python27\Lib\site-packages\numpy\core","numpy/core",["*.dll","*.pyd"]) data_files = find_data_files(r"d:\auto...
entailment
def convert_to_order_dict(map_list): """ convert mapping in list to ordered dict @param (list) map_list [ {"a": 1}, {"b": 2} ] @return (OrderDict) OrderDict({ "a": 1, "b": 2 ...
convert mapping in list to ordered dict @param (list) map_list [ {"a": 1}, {"b": 2} ] @return (OrderDict) OrderDict({ "a": 1, "b": 2 })
entailment
def get_value_from_cfg(cfg_file): ''' initial the configuration with file that you specify Sample usage: config = get_value_from_cfg() return: return a dict -->config[section][option] such as config["twsm"]["dut_ip"] ...
initial the configuration with file that you specify Sample usage: config = get_value_from_cfg() return: return a dict -->config[section][option] such as config["twsm"]["dut_ip"]
entailment
def get_exception_error(): ''' Get the exception info Sample usage: try: raise Exception("asdfsdfsdf") except: print common.get_exception_error() Return: return the exception infomation. ''' error_messa...
Get the exception info Sample usage: try: raise Exception("asdfsdfsdf") except: print common.get_exception_error() Return: return the exception infomation.
entailment
def echo(transferred, toBeTransferred, suffix=''): ''' usage: for i in range(101): ProgressBarUtils.echo(i,100) ''' bar_len = 60 rate = transferred/float(toBeTransferred) filled_len = int(round(bar_len * rate)) ...
usage: for i in range(101): ProgressBarUtils.echo(i,100)
entailment
def echo_size(self, transferred=1, status=None): '''Sample usage: f=lambda x,y:x+y ldata = range(10) toBeTransferred = reduce(f,range(10)) progress = ProgressBarUtils("refresh", toBeTransferred=toBeTransferred, unit="KB", chunk_siz...
Sample usage: f=lambda x,y:x+y ldata = range(10) toBeTransferred = reduce(f,range(10)) progress = ProgressBarUtils("refresh", toBeTransferred=toBeTransferred, unit="KB", chunk_size=1.0, run_status="ๆญฃๅœจไธ‹่ฝฝ", fin_status="ไธ‹่ฝฝๅฎŒๆˆ") imp...
entailment
def echo_percent(self,transferred=1, status=None): '''Sample usage: f=lambda x,y:x+y ldata = range(10) toBeTransferred = reduce(f,range(10)) import time progress = ProgressBarUtils("viewbar", toBeTransferred=toBeTransferred, run_sta...
Sample usage: f=lambda x,y:x+y ldata = range(10) toBeTransferred = reduce(f,range(10)) import time progress = ProgressBarUtils("viewbar", toBeTransferred=toBeTransferred, run_status="ๆญฃๅœจไธ‹่ฝฝ", fin_status="ไธ‹่ฝฝๅฎŒๆˆ") for i in ldata:...
entailment
def start_service(addr, n): """ Start a service """ s = Service(addr) s.register('add', lambda x, y: x + y) started = time.time() for _ in range(n): s.process() duration = time.time() - started time.sleep(0.1) print('Service stats:') util.print_stats(n, duration) return
Start a service
entailment
def bench(client, n): """ Benchmark n requests """ pairs = [(x, x + 1) for x in range(n)] started = time.time() for pair in pairs: res, err = client.call('add', *pair) # assert err is None duration = time.time() - started print('Client stats:') util.print_stats(n, duration)
Benchmark n requests
entailment
def start_service(addr, n): """ Start a service """ s = Subscriber(addr) s.socket.set_string_option(nanomsg.SUB, nanomsg.SUB_SUBSCRIBE, 'test') started = time.time() for _ in range(n): msg = s.socket.recv() s.socket.close() duration = time.time() - started print('Raw SUB servi...
Start a service
entailment
def shell_escape(s): r"""Given bl"a, returns "bl\\"a". """ if isinstance(s, PosixPath): s = unicode_(s) elif isinstance(s, bytes): s = s.decode('utf-8') if not s or any(c not in safe_shell_chars for c in s): return '"%s"' % (s.replace('\\', '\\\\') ....
r"""Given bl"a, returns "bl\\"a".
entailment
def projects(lancet, query): """List Harvest projects, optionally filtered with a regexp.""" projects = lancet.timer.projects() if query: regexp = re.compile(query, flags=re.IGNORECASE) def match(project): match = regexp.search(project['name']) if match is None: ...
List Harvest projects, optionally filtered with a regexp.
entailment
def tasks(lancet, project_id): """List Harvest tasks for the given project ID.""" for task in lancet.timer.tasks(project_id): click.echo('{:>9d} {} {}'.format( task['id'], click.style('โ€ฃ', fg='yellow'), task['name']))
List Harvest tasks for the given project ID.
entailment
def get_long_description(): """ Retrieve the long description from DESCRIPTION.rst """ here = os.path.abspath(os.path.dirname(__file__)) with copen(os.path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as description: return description.read()
Retrieve the long description from DESCRIPTION.rst
entailment
def flatten(nested_list: list) -> list: """Flattens a list, ignore all the lambdas.""" return list(sorted(filter(lambda y: y is not None, list(map(lambda x: (nested_list.extend(x) # noqa: T484 if isinstance(x, list) else x), ...
Flattens a list, ignore all the lambdas.
entailment
def get_py_files(dir_name: str) -> list: """Get all .py files.""" return flatten([ x for x in [["{0}/{1}".format(path, f) for f in files if f.endswith(".py")] for path, _, files in os.walk(dir_name) if not path.startswith("./build")] if x ])
Get all .py files.
entailment
def exit(self) -> None: """Raise SystemExit with correct status code and output logs.""" total = sum(len(logs) for logs in self.logs.values()) if self.json: self.logs['total'] = total print(json.dumps(self.logs, indent=self.indent)) else: for name, lo...
Raise SystemExit with correct status code and output logs.
entailment
def run_linter(self, linter) -> None: """Run a checker class""" self.current = linter.name if (linter.name not in self.parser["all"].as_list("linters") or linter.base_pyversion > sys.version_info): # noqa: W503 return if any(x not in self.installed for x in...
Run a checker class
entailment
def read_rcfile(): """ Try to read a rcfile from a list of paths """ files = [ '{}/.millipederc'.format(os.environ.get('HOME')), '/usr/local/etc/millipederc', '/etc/millipederc', ] for filepath in files: if os.path.isfile(filepath): with open(filepath)...
Try to read a rcfile from a list of paths
entailment
def parse_rcfile(rcfile): """ Parses rcfile Invalid lines are ignored with a warning """ def parse_bool(value): """Parse boolean string""" value = value.lower() if value in ['yes', 'true']: return True elif value in ['no', 'false']: return Fal...
Parses rcfile Invalid lines are ignored with a warning
entailment
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: settings[key] = value or rc_settings.ge...
Merge arguments and rc_settings.
entailment
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: padding_offsets.reverse...
Output the millipede
entailment
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('requests is required to do api post.', file=sys.stderr) sys.exit(1) data...
Send `message` as `name` to `url`. You can specify extra variables in `http_data`
entailment
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') parser.add...
Entry point
entailment
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 == 3: handle = open(readme_file, enc...
Read package long description from README file
entailment
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.path.isabs(path) and ':' in path: package, path = path.split(':', 1) content = resource_string(package, path...
Return the content of the specified file as a string. This function also supports loading resources from packages.
entailment
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: try: ...
Execute the method with args
entailment
def register(self, name, fun, description=None): """ Register function on this service """ self.methods[name] = fun self.descriptions[name] = description
Register function on this service
entailment
def parse(cls, payload): """ Parse client request """ try: method, args, ref = payload except Exception as exception: raise RequestParseError(exception) else: return method, args, ref
Parse client request
entailment
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) except AuthenticateError as exception: ...
Receive data from socket and process request
entailment
def build_payload(cls, method, args): """ Build the payload to be sent to a `Responder` """ ref = str(uuid.uuid4()) return (method, args, ref)
Build the payload to be sent to a `Responder`
entailment
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.receive() assert payload[2] == res['ref'] ...
Make a call to a `Responder` and return the result
entailment
def load(filepath=None, filecontent=None): """ 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 """ conf =...
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
entailment
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 the status code. """ if args.init: generate() return None # exit after generate instead of starting to lint ...
Runs the checks and exits. To extend this tool, use this function and set do_exit to False to get returned the status code.
entailment
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( "--config-file", help="Select config file to u...
Main entry point for console commands.
entailment
def get_session(user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> requests.Session """Set up and return Session object that is set up with retrying. Requires either global user agent to be set or appropriate user ag...
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]): ...
entailment
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_hostname=self.local_hostname, ...
Connect to server Returns: None
entailment
def send(self, recipients, subject, text_body, html_body=None, sender=None, **kwargs): # type: (List[str], str, str, Optional[str], Optional[str], Any) -> None """ Send email Args: recipients (List[str]): Email recipient subject (str): Email subject t...
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...
entailment
def get_session(db_url): # type: (str) -> Session """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 "...
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
entailment
def get_params_from_sqlalchemy_url(db_url): # type: (str) -> Dict[str,Any] """Gets PostgreSQL database connection parameters from SQLAlchemy url Args: db_url (str): SQLAlchemy url Returns: Dict[str,Any]: Dictionary of database connection parameters """ ...
Gets PostgreSQL database connection parameters from SQLAlchemy url Args: db_url (str): SQLAlchemy url Returns: Dict[str,Any]: Dictionary of database connection parameters
entailment
def get_sqlalchemy_url(database=None, host=None, port=None, username=None, password=None, driver='postgres'): # type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str], str) -> str """Gets SQLAlchemy url from database connection parameters Args: data...
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 ...
entailment
def wait_for_postgres(database, host, port, username, password): # type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str]) -> None """Waits for PostgreSQL database to be up Args: database (Optional[str]): Database name host (Optional[str...
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...
entailment
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('global') if self._cached_api_ticker_response is None: caches.append...
return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint])
entailment
def dicts_filter(dicts_object, field_to_filter, value_of_filter): """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. """ lambda_query = lambda value: value[field_to_filter]...
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.
entailment
def get_path_for_url(url, folder=None, filename=None, overwrite=False): # type: (str, Optional[str], Optional[str], bool) -> str """Get filename from url and join to provided folder or temporary folder if no folder supplied, ensuring uniqueness Args: url (str): URL to download ...
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 ...
entailment
def get_full_url(self, url): # type: (str) -> str """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 """ request = Request('GET', url) ...
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
entailment
def get_url_for_get(url, parameters=None): # type: (str, Optional[Dict]) -> str """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: Ful...
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
entailment
def get_url_params_for_post(url, parameters=None): # type: (str, Optional[Dict]) -> Tuple[str, Dict] """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...
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)
entailment
def setup(self, url, stream=True, post=False, parameters=None, timeout=None): # type: (str, bool, bool, Optional[Dict], Optional[float]) -> requests.Response """Setup download from provided url returning the response Args: url (str): URL to download stream (bool): Whethe...
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...
entailment
def hash_stream(self, url): # type: (str) -> str """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 """ md5hash = hashlib.md5() try: fo...
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
entailment
def stream_file(self, url, folder=None, filename=None, overwrite=False): # type: (str, Optional[str], Optional[str], bool) -> str """Stream file from url and store in provided folder or temporary folder if no folder supplied. Must call setup method first. Args: url (str): UR...
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 (...
entailment
def download_file(self, url, folder=None, filename=None, overwrite=False, post=False, parameters=None, timeout=None): # type: (str, Optional[str], Optional[str], bool, bool, Optional[Dict], Optional[float]) -> str """Download file from url and store in provided folder or temporary ...
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 ...
entailment
def download(self, url, post=False, parameters=None, timeout=None): # type: (str, bool, Optional[Dict], Optional[float]) -> requests.Response """Download url Args: url (str): URL to download post (bool): Whether to use POST instead of GET. Defaults to False. ...
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...
entailment
def get_tabular_stream(self, url, **kwargs): # type: (str, Any) -> tabulator.Stream """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 ...
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...
entailment
def get_tabular_rows(self, url, dict_rows=False, **kwargs): # type: (str, bool, Any) -> Iterator[Dict] """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 heade...
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...
entailment
def download_tabular_key_value(self, url, **kwargs): # type: (str, Any) -> Dict """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...
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...
entailment
def download_tabular_rows_as_dicts(self, url, headers=1, keycolumn=1, **kwargs): # type: (str, Union[int, List[int], List[str]], int, Any) -> Dict[Dict] """Download multicolumn csv from url and return dictionary where keys are first column and values are dictionaries with keys from column header...
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 ...
entailment
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), fg='red', bold=True ) click.secho( ...
Wizard to create the user-level configuration file.
entailment
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), fg='red', bold=True ) click.se...
Wizard to create a project-level configuration file.
entailment
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 = 'lancet+{}'.format(url) username = lanc...
Forget saved passwords for the web services.
entailment
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 get_services(lancet.config): click...
List all currently configured services.
entailment
def send_request(self, endpoint='ticker', coin_name=None, **kwargs): """: 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 avai...
: 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.
entailment
def get_response(self, data_type=None): """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...
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'
entailment
def iso_639_alpha3(code): """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. """ code = norma...
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.
entailment
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 with synonyms (i.e. other names for the same language).""" codes = set([]) for language in ensure_list(languages): code = iso_639_alpha3(language...
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).
entailment
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 base_branch: base_branch = lancet.conf...
Create a new pull request for this issue.
entailment
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 branch = get_branch(lancet, issue, create=force) with taskstatus("Checking out working branch"...
Checkout the branch for the given issue. It is an error if the branch does no exist yet.
entailment
def get_soup(url, downloader=None, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (str, Download, Optional[str], Optional[str], Optional[str], Any) -> BeautifulSoup """ Get BeautifulSoup object for a url. Requires either global user agent to be set or appropriate us...
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...
entailment
def extract_table(tabletag): # type: (Tag) -> List[Dict] """ 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 &nbsp replaced with space """ theadta...
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 &nbsp replaced with space
entailment
def wrap_callable(cls, uri, methods, callable_obj): """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 string...
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. ...
entailment
def register_app(self, app): """Register the route object to a `bottle.Bottle` app instance. Args: app (instance): Returns: Route instance (for chaining purposes) """ app.route(self.uri, methods=self.methods)(self.callable_obj) return self
Register the route object to a `bottle.Bottle` app instance. Args: app (instance): Returns: Route instance (for chaining purposes)
entailment
def register_handler(self, callable_obj, entrypoint, methods=('GET',)): """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. ...
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). ...
entailment
def mount(self, app=None): """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). """ for endpoint in self._routes: ...
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).
entailment
def setup_logger(log_level, log_file=None, logger_name=None): """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 """ applogger = AppL...
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
entailment
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: getattr(self...
log with different level
entailment
def from_status(cls, status_line, msg=None): """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 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...
entailment
def created(cls, data=None): """Shortcut API for HTTP 201 `Created` response. Args: data (object): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/j...
Shortcut API for HTTP 201 `Created` response. Args: data (object): Response key/value data. Returns: WSResponse Instance.
entailment
def not_modified(cls, errors=None): """Shortcut API for HTTP 304 `Not Modified` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'a...
Shortcut API for HTTP 304 `Not Modified` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
entailment
def bad_request(cls, errors=None): """Shortcut API for HTTP 400 `Bad Request` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'app...
Shortcut API for HTTP 400 `Bad Request` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
entailment
def unauthorized(cls, errors=None): """Shortcut API for HTTP 401 `Unauthorized` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'a...
Shortcut API for HTTP 401 `Unauthorized` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
entailment
def forbidden(cls, errors=None): """Shortcut API for HTTP 403 `Forbidden` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'applica...
Shortcut API for HTTP 403 `Forbidden` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
entailment
def not_found(cls, errors=None): """Shortcut API for HTTP 404 `Not found` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'applica...
Shortcut API for HTTP 404 `Not found` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
entailment
def method_not_allowed(cls, errors=None): """Shortcut API for HTTP 405 `Method not allowed` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.conte...
Shortcut API for HTTP 405 `Method not allowed` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
entailment
def not_implemented(cls, errors=None): """Shortcut API for HTTP 501 `Not Implemented` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_typ...
Shortcut API for HTTP 501 `Not Implemented` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
entailment
def service_unavailable(cls, errors=None): """Shortcut API for HTTP 503 `Service Unavailable` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.con...
Shortcut API for HTTP 503 `Service Unavailable` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
entailment
def to_json(self): """Short cut for JSON response service data. Returns: Dict that implements JSON interface. """ web_resp = collections.OrderedDict() web_resp['status_code'] = self.status_code web_resp['status_text'] = dict(HTTP_CODES).get(self.status_code...
Short cut for JSON response service data. Returns: Dict that implements JSON interface.
entailment
def setup_logging(**kwargs): # type: (Any) -> None """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 YAM...
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...
entailment
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(item, reverse=reverse): yield x results += 1 if...
A helper method for `self.search` that returns a generator rather than a list.
entailment
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 x results += 1 if results == 0: raise SearchErro...
A helper method for `self.search` that returns a generator rather than a list.
entailment
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): yield key, value results += 1 if results == 0...
A helper method for `self.search` that returns a generator rather than a list.
entailment
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 == "y"
Asks a question yes no style
entailment
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 default is None: print("N...
Asks for a number in a question
entailment
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(answer): ...
Asks for a path
entailment
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)) if answer == "": return default...
Asks for a comma seperated list of strings
entailment
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 answer
Asks for a simple string
entailment
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 = ask_list("What tools would you like to use?", ...
Lets the user enter the tools he want to use
entailment
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: conf[tool] = getattr(self, tool)() # pylint: dis...
The main function for generating the config file
entailment
def paginator(limit, offset, record_count, base_uri, page_nav_tpl='&limit={}&offset={}'): """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. ...
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...
entailment