INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
An implementation of os.symlink for Windows (Vista and greater)
def symlink(target, link, target_is_directory=False): """ An implementation of os.symlink for Windows (Vista and greater) """ target_is_directory = ( target_is_directory or _is_target_a_directory(link, target) ) # normalize the target (MS symlinks don't respect forward slashes) target = os.path.normpath(targ...
Determine if the given path is a reparse point. Return False if the file does not exist or the file attributes cannot be determined.
def is_reparse_point(path): """ Determine if the given path is a reparse point. Return False if the file does not exist or the file attributes cannot be determined. """ res = api.GetFileAttributes(path) return ( res != api.INVALID_FILE_ATTRIBUTES and bool(res & api.FILE_ATTRIBUTE_REPARSE_POINT) )
r""" Paths have a max length of api.MAX_PATH characters (260). If a target path is longer than that, it needs to be made absolute and prepended with \\?\ in order to work with API calls. See http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx for details.
def _patch_path(path): r""" Paths have a max length of api.MAX_PATH characters (260). If a target path is longer than that, it needs to be made absolute and prepended with \\?\ in order to work with API calls. See http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx for details. """ if path.starts...
Assuming path is a reparse point, determine if it's a symlink.
def is_symlink(path): """ Assuming path is a reparse point, determine if it's a symlink. """ path = _patch_path(path) try: return _is_symlink(next(find_files(path))) # comment below workaround for PyCQA/pyflakes#376 except WindowsError as orig_error: # noqa: F841 tmpl = "Error accessing {path}: {orig_error....
r""" A pythonic wrapper around the FindFirstFile/FindNextFile win32 api. >>> root_files = tuple(find_files(r'c:\*')) >>> len(root_files) > 1 True >>> root_files[0].filename == root_files[1].filename False This test might fail on a non-standard installation >>> 'Windows' in (fd.filename for fd in root_files) ...
def find_files(spec): r""" A pythonic wrapper around the FindFirstFile/FindNextFile win32 api. >>> root_files = tuple(find_files(r'c:\*')) >>> len(root_files) > 1 True >>> root_files[0].filename == root_files[1].filename False This test might fail on a non-standard installation >>> 'Windows' in (fd.filename ...
r""" For a given path, determine the ultimate location of that path. Useful for resolving symlink targets. This functions wraps the GetFinalPathNameByHandle from the Windows SDK. Note, this function fails if a handle cannot be obtained (such as for C:\Pagefile.sys on a stock windows system). Consider using trac...
def get_final_path(path): r""" For a given path, determine the ultimate location of that path. Useful for resolving symlink targets. This functions wraps the GetFinalPathNameByHandle from the Windows SDK. Note, this function fails if a handle cannot be obtained (such as for C:\Pagefile.sys on a stock windows sy...
r""" Wrapper around os.path.join that works with Windows drive letters. >>> join('d:\\foo', '\\bar') 'd:\\bar'
def join(*paths): r""" Wrapper around os.path.join that works with Windows drive letters. >>> join('d:\\foo', '\\bar') 'd:\\bar' """ paths_with_drives = map(os.path.splitdrive, paths) drives, paths = zip(*paths_with_drives) # the drive we care about is the last one in the list drive = next(filter(None, revers...
r""" Find a path from start to target where target is relative to start. >>> tmp = str(getfixture('tmpdir_as_cwd')) >>> findpath('d:\\') 'd:\\' >>> findpath('d:\\', tmp) 'd:\\' >>> findpath('\\bar', 'd:\\') 'd:\\bar' >>> findpath('\\bar', 'd:\\foo') # fails with '\\bar' 'd:\\bar' >>> findpath('bar', 'd...
def resolve_path(target, start=os.path.curdir): r""" Find a path from start to target where target is relative to start. >>> tmp = str(getfixture('tmpdir_as_cwd')) >>> findpath('d:\\') 'd:\\' >>> findpath('d:\\', tmp) 'd:\\' >>> findpath('\\bar', 'd:\\') 'd:\\bar' >>> findpath('\\bar', 'd:\\foo') # fails...
Given a file that is known to be a symlink, trace it to its ultimate target. Raises TargetNotPresent when the target cannot be determined. Raises ValueError when the specified link is not a symlink.
def trace_symlink_target(link): """ Given a file that is known to be a symlink, trace it to its ultimate target. Raises TargetNotPresent when the target cannot be determined. Raises ValueError when the specified link is not a symlink. """ if not is_symlink(link): raise ValueError("link must point to a symlin...
readlink(link) -> target Return a string representing the path to which the symbolic link points.
def readlink(link): """ readlink(link) -> target Return a string representing the path to which the symbolic link points. """ handle = api.CreateFile( link, 0, 0, None, api.OPEN_EXISTING, api.FILE_FLAG_OPEN_REPARSE_POINT | api.FILE_FLAG_BACKUP_SEMANTICS, None, ) if handle == api.INVALID_HANDLE_VAL...
jaraco.windows provides the os.symlink and os.readlink functions. Monkey-patch the os module to include them if not present.
def patch_os_module(): """ jaraco.windows provides the os.symlink and os.readlink functions. Monkey-patch the os module to include them if not present. """ if not hasattr(os, 'symlink'): os.symlink = symlink os.path.islink = islink if not hasattr(os, 'readlink'): os.readlink = readlink
%prog [start-path] Search the specified path (defaults to the current directory) for symlinks, printing the source and target on each line.
def find_symlinks_cmd(): """ %prog [start-path] Search the specified path (defaults to the current directory) for symlinks, printing the source and target on each line. """ from optparse import OptionParser from textwrap import dedent parser = OptionParser(usage=dedent(find_symlinks_cmd.__doc__).strip()) optio...
Set file attributes. e.g.: SetFileAttributes('C:\\foo', 'hidden') Each attr must be either a numeric value, a constant defined in jaraco.windows.filesystem.api, or one of the nice names defined in this function.
def SetFileAttributes(filepath, *attrs): """ Set file attributes. e.g.: SetFileAttributes('C:\\foo', 'hidden') Each attr must be either a numeric value, a constant defined in jaraco.windows.filesystem.api, or one of the nice names defined in this function. """ nice_names = collections.defaultdict( lambda k...
Decorator: prompt user for value of env.host_string with default to 'localhost' when env.host_string is empty. Modification of decorator function fabric.network.needs_host
def suggest_localhost(func): '''Decorator: prompt user for value of env.host_string with default to 'localhost' when env.host_string is empty. Modification of decorator function fabric.network.needs_host ''' from fabric.network import handle_prompt_abort, to_dict @wraps(func) def host_prom...
Decorator, ensures that fabsetup-custom exists and it is a git repo.
def needs_repo_fabsetup_custom(func): '''Decorator, ensures that fabsetup-custom exists and it is a git repo.''' from fabric.api import local @wraps(func) def wrapper(*args, **kwargs): if not os.path.exists(FABSETUP_CUSTOM_DIR): msg = '''\ Git repository ~/.fabsetup-custom with conf...
Decorator: ensure that packages are installed on host given by fabric argument `-H` (local or remote).
def needs_packages(*packages): '''Decorator: ensure that packages are installed on host given by fabric argument `-H` (local or remote). ''' def real_decorator(func): @wraps(func) def wrapper(*args, **kwargs): non_installed = _non_installed(packages) if non_insta...
Composition of decorator functions for inherent self-documentation on task execution. On execution, each task prints out its name and its first docstring line.
def task(func, *args, **kwargs): '''Composition of decorator functions for inherent self-documentation on task execution. On execution, each task prints out its name and its first docstring line. ''' prefix = '\n# ' tail = '\n' return fabric.api.task( print_full_name(color=magenta, ...
Decorator which prints out the name of the decorated function on execution.
def subtask(*args, **kwargs): '''Decorator which prints out the name of the decorated function on execution. ''' depth = kwargs.get('depth', 2) prefix = kwargs.get('prefix', '\n' + '#' * depth + ' ') tail = kwargs.get('tail', '\n') doc1 = kwargs.get('doc1', False) color = kwargs.get('col...
Return True if current user is a sudoer, else False. Should be called non-eager if sudo is wanted only.
def _is_sudoer(what_for=''): '''Return True if current user is a sudoer, else False. Should be called non-eager if sudo is wanted only. ''' if env.get('nosudo', None) is None: if what_for: print(yellow(what_for)) with quiet(): # possible outputs: # e...
Try to install .deb packages given by list. Return True, if packages could be installed or are installed already, or if they cannot be installed but the user gives feedback to continue. Else return False.
def install_packages(packages, what_for='for a complete setup to work properly'): '''Try to install .deb packages given by list. Return True, if packages could be installed or are installed already, or if they cannot be installed but the user gives feedback to continue. Else retur...
Checkout or update git repos. repos must be a list of dicts each with an url and optional with a name value.
def checkup_git_repos_legacy(repos, base_dir='~/repos', verbose=False, prefix='', postfix=''): '''Checkout or update git repos. repos must be a list of dicts each with an url and optional with a name value. ''' run(flo('mkdir -p {base_dir}')) for repo in repos: ...
Checkout or update a git repo.
def checkup_git_repo_legacy(url, name=None, base_dir='~/repos', verbose=False, prefix='', postfix=''): '''Checkout or update a git repo.''' if not name: match = re.match(r'.*/(.+)\.git', url) assert match, flo("Unable to extract repo name from '{url}'") name =...
Install file with path on the host target. The from file is the first of this list which exists: * custom file * custom file.template * common file * common file.template
def install_file_legacy(path, sudo=False, from_path=None, **substitutions): '''Install file with path on the host target. The from file is the first of this list which exists: * custom file * custom file.template * common file * common file.template ''' # source paths 'from_custom' ...
Install command executable file into users bin dir. If a custom executable exists it would be installed instead of the "normal" one. The executable also could exist as a <command>.template file.
def install_user_command_legacy(command, **substitutions): '''Install command executable file into users bin dir. If a custom executable exists it would be installed instead of the "normal" one. The executable also could exist as a <command>.template file. ''' path = flo('~/bin/{command}') ins...
Return 2-Tuple (from_custom, from_default) for a given path. Example: >>> FABSETUP_CUSTOM_DIR = '/home/theno/.fabsetup-custom' >>> >>> # path is an abpath ... >>> addon_package = AddonPackage(module_dir='/home/theno/' ... '.fabsetup-addo...
def _determine_froms(addon_package, path): '''Return 2-Tuple (from_custom, from_default) for a given path. Example: >>> FABSETUP_CUSTOM_DIR = '/home/theno/.fabsetup-custom' >>> >>> # path is an abpath ... >>> addon_package = AddonPackage(module_dir='/home/theno/' ...
Search in file 'filename' for a line starting with 'prefix' and replace the line by 'new_line'. If a line starting with 'prefix' not exists 'new_line' will be appended. If the file not exists, it will be created. Return False if new_line was appended, else True (i.e. if the prefix was found within...
def update_or_append_line(filename, prefix, new_line, keep_backup=True, append=True): '''Search in file 'filename' for a line starting with 'prefix' and replace the line by 'new_line'. If a line starting with 'prefix' not exists 'new_line' will be appended. If the file not exi...
Comment line out by putting a comment sign in front of the line. If the file does not contain the line, the files content will not be changed (but the file will be touched in every case).
def comment_out_line(filename, line, comment='#'): '''Comment line out by putting a comment sign in front of the line. If the file does not contain the line, the files content will not be changed (but the file will be touched in every case). ''' return comment_out_local(filename, line, comment, ...
Remove the comment of an commented out line and make the line "active". If such an commented out line not exists it would be appended.
def uncomment_or_update_or_append_line(filename, prefix, new_line, comment='#', keep_backup=True): '''Remove the comment of an commented out line and make the line "active". If such an commented out line not exists it would be appended. ''' return uua_local(filena...
Return bash variable declaration as name-value pair. Name as lower case str. Value itself only without surrounding '"' (if any). For example, _line_2_pair('NAME="Ubuntu"') will return ('name', 'Ubuntu')
def _line_2_pair(line): '''Return bash variable declaration as name-value pair. Name as lower case str. Value itself only without surrounding '"' (if any). For example, _line_2_pair('NAME="Ubuntu"') will return ('name', 'Ubuntu') ''' key, val = line.split('=') return key.lower(), val.strip('"'...
Return variable content of file '/etc/os-release' as dict. Return-example (in case of an Ubuntu 16.04): { 'name': 'Ubuntu', 'version': '16.04.1 LTS (Xenial Xerus)', 'version_id': '16.04', ... }
def _fetch_os_release_infos(): '''Return variable content of file '/etc/os-release' as dict. Return-example (in case of an Ubuntu 16.04): { 'name': 'Ubuntu', 'version': '16.04.1 LTS (Xenial Xerus)', 'version_id': '16.04', ... } ''' os_rele...
Return True if OS name in /etc/lsb-release of host given by fabric param `-H` is the same as given by argument, False else. If arg version_id is not None only return True if it is the same as in /etc/lsb-release, too. Args: name: 'Debian GNU/Linux', 'Ubuntu' version_id(None or str): No...
def is_os(name, version_id=None): '''Return True if OS name in /etc/lsb-release of host given by fabric param `-H` is the same as given by argument, False else. If arg version_id is not None only return True if it is the same as in /etc/lsb-release, too. Args: name: 'Debian GNU/Linux', 'Ub...
Return the Common Name (cn) from the Distinguished Name (dn) of the certificate which contains the `domain` in its Subject Alternativ Name (san) list. Needs repo ~/.fabsetup-custom. Return None if no certificate is configured with `domain` in SAN.
def dn_cn_of_certificate_with_san(domain): '''Return the Common Name (cn) from the Distinguished Name (dn) of the certificate which contains the `domain` in its Subject Alternativ Name (san) list. Needs repo ~/.fabsetup-custom. Return None if no certificate is configured with `domain` in SAN. ...
Extract supported python minor versions from setup.py and return them as a list of str. Return example: ['2.6', '2.7', '3.3', '3.4', '3.5', '3.6']
def extract_minors_from_setup_py(filename_setup_py): '''Extract supported python minor versions from setup.py and return them as a list of str. Return example: ['2.6', '2.7', '3.3', '3.4', '3.5', '3.6'] ''' # eg: minors_str = '2.6\n2.7\n3.3\n3.4\n3.5\n3.6' minors_str = fabric.api.local...
Return highest minor of a list of stable (semantic) versions. Example: >>> python_versions = [ ... '2.6.9', '2.7.14', '3.3.7', '3.4.8', '3.5.5', '3.6.4'] >>> highest_minor(python_versions) '3.6'
def highest_minor(python_versions): '''Return highest minor of a list of stable (semantic) versions. Example: >>> python_versions = [ ... '2.6.9', '2.7.14', '3.3.7', '3.4.8', '3.5.5', '3.6.4'] >>> highest_minor(python_versions) '3.6' ''' highest = python_versions[-1...
Install or update Janus, a distribution of addons and mappings for vim. More info: https://github.com/carlhuda/janus Customization: https://github.com/carlhuda/janus/wiki/Customization Args: uninstall: If not None, Uninstall janus and restore old vim config
def vim_janus(uninstall=None): '''Install or update Janus, a distribution of addons and mappings for vim. More info: https://github.com/carlhuda/janus Customization: https://github.com/carlhuda/janus/wiki/Customization Args: uninstall: If not None, Uninstall janus and restore old vim c...
Remove all janus files and dirs and (try to) restore previous vim config.
def uninstall_janus(): '''Remove all janus files and dirs and (try to) restore previous vim config. ''' if exists('~/.vim/janus'): run('rm -rf ~/.vim', msg='delete janus repo dir') with warn_only(): run('rm -rf ~/.janus', msg='delete ~/.janus dir') run('bash -c "rm ~/...
Scan a network port Parameters ---------- host : str Host or ip address to scan port : int, optional Port to scan, default=80 url : str, optional URL to perform get request to on the host and port specified https : bool, optional Perform ssl connection on the ...
def scan(host, port=80, url=None, https=False, timeout=1, max_size=65535): """ Scan a network port Parameters ---------- host : str Host or ip address to scan port : int, optional Port to scan, default=80 url : str, optional URL to perform get request to on the hos...
Ping a host Parameters ---------- host: str The host or ip address to ping port: int, optional The port to ping, default=80 url: str, optional URL to ping, will do a host/port ping if not provided https: bool, optional Connect via ssl, default=False timeo...
def ping(host, port=80, url=None, https=False, timeout=1, max_size=65535, sequence=0): """ Ping a host Parameters ---------- host: str The host or ip address to ping port: int, optional The port to ping, default=80 url: str, optional URL to ping, will do a host/por...
The main reason we have arrived here. This is the entry-point for the utility to create/update a CloudFormation stack.
def upsert(version, stack, ini, dryrun, yaml, no_poll, work_directory): """ The main reason we have arrived here. This is the entry-point for the utility to create/update a CloudFormation stack. """ ini_data = read_config_info(ini) if 'environment' not in ini_data: print('[environment] s...
Delete the given CloudFormation stack.
def delete(stack, region, profile): """ Delete the given CloudFormation stack. """ ini_data = {} environment = {} environment['stack_name'] = stack if region: environment['region'] = region else: environment['region'] = find_myself() if profile: environment[...
List all the CloudFormation stacks in the given region.
def list(region, profile): """ List all the CloudFormation stacks in the given region. """ ini_data = {} environment = {} if region: environment['region'] = region else: environment['region'] = find_myself() if profile: environment['profile'] = profile ini_...
Produce a CloudFormation drift report for the given stack.
def drift(stack, region, profile): """ Produce a CloudFormation drift report for the given stack. """ logging.debug('finding drift - stack: {}'.format(stack)) logging.debug('region: {}'.format(region)) logging.debug('profile: {}'.format(profile)) tool = DriftTool( Stack=stack, ...
Helper function to facilitate upsert. Args: ini_date - the dictionary of info to run upsert Exit: 0 - good 1 - bad
def start_upsert(ini_data): """ Helper function to facilitate upsert. Args: ini_date - the dictionary of info to run upsert Exit: 0 - good 1 - bad """ stack_driver = CloudStackUtility(ini_data) poll_stack = not ini_data.get('no_poll', False) if stack_driver.upsert(...
Read the INI file Args: ini_file - path to the file Returns: A dictionary of stuff from the INI file Exits: 1 - if problems are encountered
def read_config_info(ini_file): """ Read the INI file Args: ini_file - path to the file Returns: A dictionary of stuff from the INI file Exits: 1 - if problems are encountered """ try: config = RawConfigParser() config.optionxform = lambda option: o...
List events from the given stack Args: None Returns: None
def print_stack_events(self): ''' List events from the given stack Args: None Returns: None ''' first_token = '7be7981bd6287dd8112305e8f3822a6f' keep_going = True next_token = first_token current_request_token = None ...
Set up or update a trac project. This trac installation uses python2, git, sqlite (trac-default), gunicorn, and nginx. The connection is https-only and secured by a letsencrypt certificate. This certificate must be created separately with task setup.server_letsencrypt. This task installes or upd...
def trac(): '''Set up or update a trac project. This trac installation uses python2, git, sqlite (trac-default), gunicorn, and nginx. The connection is https-only and secured by a letsencrypt certificate. This certificate must be created separately with task setup.server_letsencrypt. This ta...
Do a query to the System API :param path: url to the API :param method: the kind of query to do :param params: a dict with all the necessary things to query the API :return json data
async def query(self, path, method='get', **params): """ Do a query to the System API :param path: url to the API :param method: the kind of query to do :param params: a dict with all the necessary things to query the API :return json data """ if ...
get the json data response :param responses: the json response :return the json data without 'root' node
async def handle_json_response(responses): """ get the json data response :param responses: the json response :return the json data without 'root' node """ json_data = {} if responses.status != 200: err_msg = HttpProcessingError(code=responses.status, ...
get the value of a parm :param what: string parm :param type_attr: type of parm :param value_attr: :param kwargs: :return: value of the parm
def __get_attr(what, type_attr, value_attr, **kwargs): """ get the value of a parm :param what: string parm :param type_attr: type of parm :param value_attr: :param kwargs: :return: value of the parm """ if what in kwargs: value = int(k...
GET /api/entries.{_format} Retrieve all entries. It could be filtered by many options. :param kwargs: can contain one of the following filters archive: '0' or '1', default '0' filter by archived status. starred: '0' or '1', default '0' filter by starred status. sor...
async def get_entries(self, **kwargs): """ GET /api/entries.{_format} Retrieve all entries. It could be filtered by many options. :param kwargs: can contain one of the following filters archive: '0' or '1', default '0' filter by archived status. starred: '0' or...
POST /api/entries.{_format} Create an entry :param url: the url of the note to store :param title: Optional, we'll get the title from the page. :param tags: tag1,tag2,tag3 a comma-separated list of tags. :param starred entry already starred :param archive entry already ...
async def post_entries(self, url, title='', tags='', starred=0, archive=0, content='', language='', published_at='', authors='', public=1, original_url=''): """ POST /api/entries.{_format} Create an entry :param url: the url of the note to store :para...
GET /api/entries/{entry}.{_format} Retrieve a single entry :param entry: \w+ an integer The Entry ID :return data related to the ext
async def get_entry(self, entry): """ GET /api/entries/{entry}.{_format} Retrieve a single entry :param entry: \w+ an integer The Entry ID :return data related to the ext """ params = {'access_token': self.token} url = '/api/entries/{entry}.{ext}'.format...
PATCH /api/entries/{entry}.{_format} Change several properties of an entry :param entry: the entry to 'patch' / update :param kwargs: can contain one of the following title: string tags: a list of tags tag1,tag2,tag3 archive: '0' or '1', default '0' archive...
async def patch_entries(self, entry, **kwargs): """ PATCH /api/entries/{entry}.{_format} Change several properties of an entry :param entry: the entry to 'patch' / update :param kwargs: can contain one of the following title: string tags: a list of tags ...
DELETE /api/entries/{entry}.{_format} Delete permanently an entry :param entry: \w+ an integer The Entry ID :return result
async def delete_entries(self, entry): """ DELETE /api/entries/{entry}.{_format} Delete permanently an entry :param entry: \w+ an integer The Entry ID :return result """ params = {'Authorization': 'Bearer {}'.format(self.token)} path = '/api/entries/{en...
GET /api/entries/exists.{_format} Check if an entry exist by url. :param url string true An url Url to check if it exists :param urls string false An array of urls (?urls[]=http...&urls[]=http...) Urls (as an array) to check if it exists :return result
async def entries_exists(self, url, urls=''): """ GET /api/entries/exists.{_format} Check if an entry exist by url. :param url string true An url Url to check if it exists :param urls string false An array of urls (?urls[]=http...&urls[]=http...) Urls (as an array...
POST /api/entries/{entry}/tags.{_format} Add one or more tags to an entry :param entry: \w+ an integer The Entry ID :param tags: list of tags (urlencoded) :return result
async def post_entry_tags(self, entry, tags): """ POST /api/entries/{entry}/tags.{_format} Add one or more tags to an entry :param entry: \w+ an integer The Entry ID :param tags: list of tags (urlencoded) :return result """ params = {'access_token': self...
DELETE /api/entries/{entry}/tags/{tag}.{_format} Permanently remove one tag for an entry :param entry: \w+ an integer The Entry ID :param tag: string The Tag :return data related to the ext
async def delete_entry_tag(self, entry, tag): """ DELETE /api/entries/{entry}/tags/{tag}.{_format} Permanently remove one tag for an entry :param entry: \w+ an integer The Entry ID :param tag: string The Tag :return data related to the ext """ params = {...
GET /api/tags.{_format} Retrieve all tags :return data related to the ext
async def get_tags(self): """ GET /api/tags.{_format} Retrieve all tags :return data related to the ext """ params = {'access_token': self.token} path = '/api/tags.{ext}'.format(ext=self.format) return await self.query(path, "get", **params)
DELETE /api/tags/{tag}.{_format} Permanently remove one tag from every entry :param tag: string The Tag :return data related to the ext
async def delete_tag(self, tag): """ DELETE /api/tags/{tag}.{_format} Permanently remove one tag from every entry :param tag: string The Tag :return data related to the ext """ path = '/api/tags/{tag}.{ext}'.format(tag=tag, ext=self.format) params = {'ac...
PUT /api/annotations/{annotation}.{_format} Updates an annotation. :param annotation \w+ string The annotation ID Will returns annotation for this entry :return data related to the ext
async def put_annotations(self, annotation): """ PUT /api/annotations/{annotation}.{_format} Updates an annotation. :param annotation \w+ string The annotation ID Will returns annotation for this entry :return data related to the ext """ params = {'a...
POST /api/annotations/{entry}.{_format} Creates a new annotation. :param entry \w+ integer The entry ID :return
async def post_annotations(self, entry, **kwargs): """ POST /api/annotations/{entry}.{_format} Creates a new annotation. :param entry \w+ integer The entry ID :return """ params = dict({'access_token': self.token, 'ranges': [], ...
GET /api/version.{_format} Retrieve version number :return data related to the ext
async def version(self): """ GET /api/version.{_format} Retrieve version number :return data related to the ext """ params = {'access_token': self.token} url = '/api/version.{ext}'.format(ext=self.format) return await self.query(url, "get", **params)
POST /oauth/v2/token Get a new token :param host: host of the service :param params: will contain : params = {"grant_type": "password", "client_id": "a string", "client_secret": "a string", "username": "a login", ...
async def get_token(cls, host, **params): """ POST /oauth/v2/token Get a new token :param host: host of the service :param params: will contain : params = {"grant_type": "password", "client_id": "a string", "client_secret": "a string...
Set up or update a reveals.js presentation with slides written in markdown. Several reveal.js plugins will be set up, too. More info: Demo: https://theno.github.io/revealjs_template http://lab.hakim.se/reveal-js/ https://github.com/hakimel/reveal.js plugins: https://github.com/...
def revealjs(basedir=None, title=None, subtitle=None, description=None, github_user=None, github_repo=None): '''Set up or update a reveals.js presentation with slides written in markdown. Several reveal.js plugins will be set up, too. More info: Demo: https://theno.github.io/revealjs_te...
Comment out some css settings.
def tweak_css(repo_dir): '''Comment out some css settings.''' print_msg("* don't capitalize titles (no uppercase headings)") files = [ 'beige.css', 'black.css', 'blood.css', 'league.css', 'moon.css', 'night.css', 'serif.css', 'simple.css', 'sky.css', 'solarized.css', 'white.css', ...
More info: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ https://developer.github.com/v3/repos/#create https://stackoverflow.com/a/10325316
def _create_github_remote_repo(basedir): '''More info: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ https://developer.github.com/v3/repos/#create https://stackoverflow.com/a/10325316 ''' github_user = _lazy('github_user') github_repo = _...
Install DeckTape. DeckTape is a "high-quality PDF exporter for HTML5 presentation frameworks". It can be used to create PDFs from reveal.js presentations. More info: https://github.com/astefanutti/decktape https://github.com/hakimel/reveal.js/issues/1252#issuecomment-198270915
def decktape(): '''Install DeckTape. DeckTape is a "high-quality PDF exporter for HTML5 presentation frameworks". It can be used to create PDFs from reveal.js presentations. More info: https://github.com/astefanutti/decktape https://github.com/hakimel/reveal.js/issues/1252#issuecomment-19...
Create or update the template presentation demo using task `revealjs`.
def revealjs_template(): '''Create or update the template presentation demo using task `revealjs`. ''' from config import basedir, github_user, github_repo run(flo('rm -f {basedir}/index.html')) run(flo('rm -f {basedir}/slides.md')) run(flo('rm -f {basedir}/README.md')) run(flo('rm -rf {bas...
Superposition of analytical solutions without a gridded domain
def spatialDomainNoGrid(self): """ Superposition of analytical solutions without a gridded domain """ self.w = np.zeros(self.xw.shape) if self.Debug: print("w = ") print(self.w.shape) for i in range(len(self.q)): # More efficient if we have created some 0-load ...
dx4, D = elasprepFD(dx,Te,E=1E11,nu=0.25) Defines the variables (except for the subset flexural rigidity) that are needed to run "coeff_matrix_1d"
def elasprepFD(self): """ dx4, D = elasprepFD(dx,Te,E=1E11,nu=0.25) Defines the variables (except for the subset flexural rigidity) that are needed to run "coeff_matrix_1d" """ self.dx4 = self.dx**4 self.D = self.E*self.Te**3/(12*(1-self.nu**2))
Utility function to help implement boundary conditions by specifying them for and applying them to the elastic thickness grid
def BC_Rigidity(self): """ Utility function to help implement boundary conditions by specifying them for and applying them to the elastic thickness grid """ ######################################### # FLEXURAL RIGIDITY BOUNDARY CONDITIONS # #########################################...
Builds the diagonals for the coefficient array
def build_diagonals(self): """ Builds the diagonals for the coefficient array """ ########################################################## # INCORPORATE BOUNDARY CONDITIONS INTO COEFFICIENT ARRAY # ########################################################## # Roll to keep the pro...
Periodic boundary conditions: wraparound to the other side.
def BC_Periodic(self): """ Periodic boundary conditions: wraparound to the other side. """ if self.BC_E == 'Periodic' and self.BC_W == 'Periodic': # If both boundaries are periodic, we are good to go (and self-consistent) pass # It is just a shift in the coeff. matrix creation. el...
0Displacement0Slope boundary condition for 0 deflection. This requires that nothing be done to the edges of the solution array, because the lack of the off-grid terms implies that they go to 0 Here we just turn the cells outside the array into nan, to ensure that we are not accidentally including ...
def BC_0Displacement0Slope(self): """ 0Displacement0Slope boundary condition for 0 deflection. This requires that nothing be done to the edges of the solution array, because the lack of the off-grid terms implies that they go to 0 Here we just turn the cells outside the array into nan, to ensu...
This boundary condition is esentially a Neumann 0-gradient boundary condition with that 0-gradient state extended over a longer part of the grid such that the third derivative also equals 0. This boundary condition has more of a geometric meaning than a physical meaning. It produces a state...
def BC_0Slope0Shear(self): i=0 """ This boundary condition is esentially a Neumann 0-gradient boundary condition with that 0-gradient state extended over a longer part of the grid such that the third derivative also equals 0. This boundary condition has more of a geometric meaning ...
Mirrors qs across the boundary on either the west (left) or east (right) side, depending on the selections. This can, for example, produce a scenario in which you are observing a mountain range up to the range crest (or, more correctly, the halfway point across the mountain range).
def BC_Mirror(self): """ Mirrors qs across the boundary on either the west (left) or east (right) side, depending on the selections. This can, for example, produce a scenario in which you are observing a mountain range up to the range crest (or, more correctly, the halfway point a...
Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure (this code), grids are padded out to one maximum flexural wavelength, but in any case, the flexural wavelength is a good characteristic distance for any truncation limit
def calc_max_flexural_wavelength(self): """ Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure (this code), grids are padded out to one maximum flexural wavelength, but in any case, the flexural wavelength is a good character...
w = fd_solve() where coeff is the sparse coefficient matrix output from function coeff_matrix and qs is the array of loads (stresses) Sparse solver for one-dimensional flexure of an elastic plate
def fd_solve(self): """ w = fd_solve() where coeff is the sparse coefficient matrix output from function coeff_matrix and qs is the array of loads (stresses) Sparse solver for one-dimensional flexure of an elastic plate """ if self.Debug: print("qs", self.qs.shape) ...
A model's save() never gets called on ManyToManyField changes, m2m_changed-signal is sent. sender = dynamically generated model in m2m-table instance = parent related_instance = instance being m2m'ed
def m2m_changed_handler(sender, *args, **kwargs): """ A model's save() never gets called on ManyToManyField changes, m2m_changed-signal is sent. sender = dynamically generated model in m2m-table instance = parent related_instance = instance being m2m'ed """ action = kwargs['action'] inst...
Return a > b. Computed by @total_ordering from (not a < b) and (a != b).
def _gt_from_lt(self, other): """Return a > b. Computed by @total_ordering from (not a < b) and (a != b).""" op_result = self.__lt__(other) if op_result is NotImplemented: return NotImplemented return not op_result and self != other
Return a <= b. Computed by @total_ordering from (a < b) or (a == b).
def _le_from_lt(self, other): """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" op_result = self.__lt__(other) return op_result or self == other
Return a >= b. Computed by @total_ordering from (not a < b).
def _ge_from_lt(self, other): """Return a >= b. Computed by @total_ordering from (not a < b).""" op_result = self.__lt__(other) if op_result is NotImplemented: return NotImplemented return not op_result
Return a >= b. Computed by @total_ordering from (not a <= b) or (a == b).
def _ge_from_le(self, other): """Return a >= b. Computed by @total_ordering from (not a <= b) or (a == b).""" op_result = self.__le__(other) if op_result is NotImplemented: return NotImplemented return not op_result or self == other
Return a < b. Computed by @total_ordering from (a <= b) and (a != b).
def _lt_from_le(self, other): """Return a < b. Computed by @total_ordering from (a <= b) and (a != b).""" op_result = self.__le__(other) if op_result is NotImplemented: return NotImplemented return op_result and self != other
Return a > b. Computed by @total_ordering from (not a <= b).
def _gt_from_le(self, other): """Return a > b. Computed by @total_ordering from (not a <= b).""" op_result = self.__le__(other) if op_result is NotImplemented: return NotImplemented return not op_result
Return a < b. Computed by @total_ordering from (not a > b) and (a != b).
def _lt_from_gt(self, other): """Return a < b. Computed by @total_ordering from (not a > b) and (a != b).""" op_result = self.__gt__(other) if op_result is NotImplemented: return NotImplemented return not op_result and self != other
Return a >= b. Computed by @total_ordering from (a > b) or (a == b).
def _ge_from_gt(self, other): """Return a >= b. Computed by @total_ordering from (a > b) or (a == b).""" op_result = self.__gt__(other) return op_result or self == other
Return a <= b. Computed by @total_ordering from (not a > b).
def _le_from_gt(self, other): """Return a <= b. Computed by @total_ordering from (not a > b).""" op_result = self.__gt__(other) if op_result is NotImplemented: return NotImplemented return not op_result
Return a <= b. Computed by @total_ordering from (not a >= b) or (a == b).
def _le_from_ge(self, other): """Return a <= b. Computed by @total_ordering from (not a >= b) or (a == b).""" op_result = self.__ge__(other) if op_result is NotImplemented: return NotImplemented return not op_result or self == other
Return a > b. Computed by @total_ordering from (a >= b) and (a != b).
def _gt_from_ge(self, other): """Return a > b. Computed by @total_ordering from (a >= b) and (a != b).""" op_result = self.__ge__(other) if op_result is NotImplemented: return NotImplemented return op_result and self != other
Return a < b. Computed by @total_ordering from (not a >= b).
def _lt_from_ge(self, other): """Return a < b. Computed by @total_ordering from (not a >= b).""" op_result = self.__ge__(other) if op_result is NotImplemented: return NotImplemented return not op_result
Class decorator that fills in missing ordering methods
def total_ordering(cls): """Class decorator that fills in missing ordering methods""" convert = { # :off '__lt__': [('__gt__', _gt_from_lt), ('__le__', _le_from_lt), ('__ge__', _ge_from_lt)], '__le__': [('__ge__', _ge_from_le), ('__lt__',...
Creates Combine Archive containing the given file. :param fileName: file to include in the archive :return: None
def createArchiveExample(fileName): """ Creates Combine Archive containing the given file. :param fileName: file to include in the archive :return: None """ print('*' * 80) print('Create archive') print('*' * 80) archive = CombineArchive() archive.addFile( fileName, # file...
Delete temporary files not under version control.
def clean(): '''Delete temporary files not under version control.''' basedir = dirname(__file__) print(cyan('delete temp files and dirs for packaging')) local(flo( 'rm -rf ' '{basedir}/.eggs/ ' '{basedir}/fabsetup.egg-info/ ' '{basedir}/dist ' '{basedir}/REA...
Build package and upload to pypi.
def pypi(): '''Build package and upload to pypi.''' if not query_yes_no('version updated in ' '`fabsetup/_version.py`?'): print('abort') else: print(cyan('\n## clean-up\n')) execute(clean) basedir = dirname(__file__) # latest_pythons = _deter...
Calculate the standard deviation of a list of values @param values: list(float) @param average: @return:
def calc_deviation(values, average): """ Calculate the standard deviation of a list of values @param values: list(float) @param average: @return: """ size = len(values) if size < 2: return 0 calc_sum = 0.0 for number in range(0, size): calc_sum += math.sqrt((valu...
Append a value to the stats list Parameters ---------- value : float The value to add
def append(self, value): """ Append a value to the stats list Parameters ---------- value : float The value to add """ self.count += 1 if self.count == 1: self.old_m = self.new_m = value self.old_s = 0 else: ...
Chain results from a list of functions. Inverted reduce. :param (function) steps: List of function callbacks :param initial: Starting value for pipeline.
def pipeline(steps, initial=None): """ Chain results from a list of functions. Inverted reduce. :param (function) steps: List of function callbacks :param initial: Starting value for pipeline. """ def apply(result, step): return step(result) return reduce(apply, steps, initial)
%prog [<name>=[value]] To show all environment variables, call with no parameters: %prog To Add/Modify/Delete environment variable: %prog <name>=[value] If <name> is PATH or PATHEXT, %prog will by default append the value using a semicolon as a separator. Use -r to disable this behavior or -a to force it for...
def enver(*args): """ %prog [<name>=[value]] To show all environment variables, call with no parameters: %prog To Add/Modify/Delete environment variable: %prog <name>=[value] If <name> is PATH or PATHEXT, %prog will by default append the value using a semicolon as a separator. Use -r to disable this behavio...
Add a value to a delimited variable, but only when the value isn't already present.
def add(class_, name, value, sep=';'): """ Add a value to a delimited variable, but only when the value isn't already present. """ values = class_.get_values_list(name, sep) if value in values: return new_value = sep.join(values + [value]) winreg.SetValueEx( class_.key, name, 0, winreg.REG_EXPAND_...