INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Parse the command line arguments: return:
def parse_arguments(): """ Parse the command line arguments :return: """ parser = argparse.ArgumentParser() parser.add_argument( "-c", dest="count", default=0, type=int, help="Number of pings to send" ) parser.add_argument( "-i", dest="interval", default=1, type=f...
Create new sketch Params: <int > width <str > path <int > flags <int > seed
def create(self, width=0, depth=0, path=None, flags=0, seed=0): """Create new sketch Params: <int> width <str> path <int> flags <int> seed """ return self.create_method(self, width, depth, path, flags, seed)
Add key - value Params: <str > key <int > key_length Return: <int > key_value
def get(self, key, key_length=0): """Add key-value Params: <str> key <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) return self.get_method(self, key, key_length)
Set value to key - value Params: <str > key <int > value <int > key_length Return: <int > key_value
def set(self, key, value, key_length=0): """Set value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) if self.k: self._...
Add value to key - value Params: <str > key <int > value <int > key_length Return: <int > key_value
def add(self, key, value, key_length=0): """Add value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) val = self.add_method(self, k...
Add value to key - value Params: <str > key <int > value <int > key_length Return: <int > key_value
def inc(self, key, key_length=0): """Add value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) val = self.add_method(self, key, key...
Clear sketch
def clear(self): """Clear sketch""" self.ranking = [] heapq.heapify(self.ranking) self.dq = deque(maxlen=self.k) self.num = 0 return self.clear_method(self)
Shrink sketch Params: <Sketch > src_sketch <int > width <str > path <int > flags
def shrink(self, src, width=0, path=None, flags=0): """Shrink sketch Params: <Sketch> src_sketch <int> width <str> path <int> flags """ self.shrink_method(self, src, width, path, flags)
Merge two sketches Params: <Sketch > sketch <lambda > | <function > lhs_filter <lambda > | <function > rhs_filter
def merge(self, rhs, lhs_filter=None, rhs_filter=None): """Merge two sketches Params: <Sketch> sketch <lambda> | <function> lhs_filter <lambda> | <function> rhs_filter """ if lhs_filter or rhs_filter: get_ = self.get___method se...
Apply filter into all values Params <lambda > | <function > given_filter <bool > only_nonzero
def filter(self, given_filter, apply_zerovalue=False): """Apply filter into all values Params <lambda> | <function> given_filter <bool> only_nonzero """ get_ = self.get___method set_ = self.set___method max_value = self.max_value for table_...
Dump all values Return: <generator > <int > val
def values(self): """Dump all values Return: <generator> <int> val """ table_id = 0 get = self.get___method for cell_id in range(self.width): val = get(self, table_id, cell_id) if val: yield val
Set values from dict Params: <dict <str > <int >> src_dict
def fromdict(self, src_dict, method='set'): """Set values from dict Params: <dict <str> <int>> src_dict """ if method == 'set': _method = self.set_method else: _method = self.add_method if hasattr(src_dict, 'iteritems'): for...
Create new sketch Params: <int > width <int > max_value <str > path <int > flags <int > seed
def create(self, width=0, max_value=0, path=None, flags=0, seed=0): """Create new sketch Params: <int> width <int> max_value <str> path <int> flags <int> seed """ return _madoka.Sketch_create(self, width, max_value, path, flags,...
Increment key - value Params: <str > key <int > key_length Return: <int > key_value
def inc(self, key, key_length=0): """Increment key-value Params: <str> key <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) return _madoka.Sketch_inc(self, key, key_length)
Shrink sketch Params: <Sketch > src_sketch <int > width <int > max_value <lambda > | <function > filter <str > path <int > flags
def shrink(self, src, width=0, max_value=0, filter_method=None, path=None, flags=0): """Shrink sketch Params: <Sketch> src_sketch <int> width <int> max_value <lambda> | <function> filter <str> path <int> flags ...
Try to convert content of README. md into rst format using pypandoc write it into README and return it.
def create_readme_with_long_description(): '''Try to convert content of README.md into rst format using pypandoc, write it into README and return it. If pypandoc cannot be imported write content of README.md unchanged into README and return it. ''' this_dir = os.path.abspath(os.path.dirname(__f...
Install or update OpenSSL from source ( statically linked no shared libs ).
def openssl(version='master', ignore_test_fail=False): ''' Install or update OpenSSL from source (statically linked, no shared libs). Args: version (str): Git tag or branch to install from. Default: 'master' ignore_test_fail: Continue with installation if `make test` fails. ...
Print download statistics for a package.
def stat(package, graph): """Print download statistics for a package. \b Example: pypi stat requests """ client = requests.Session() for name_or_url in package: package = get_package(name_or_url, client) if not package: secho(u'Invalid name or URL: "{name}"'...
Browse to a package s PyPI or project homepage.
def browse(package, homepage): """Browse to a package's PyPI or project homepage.""" p = Package(package) try: if homepage: secho(u'Opening homepage for "{0}"...'.format(package), bold=True) url = p.home_page else: secho(u'Opening PyPI page for "{0}"...'.f...
Search for a pypi package.
def search(query, n_results, web): """Search for a pypi package. \b Examples: \b pypi search requests pypi search 'requests oauth' pypi search requests -n 20 pypi search 'requests toolbelt' --web """ if web: secho(u'Opening search page for "{0}"...'....
Get info about a package or packages.
def info(package, long_description, classifiers, license): """Get info about a package or packages. """ client = requests.Session() for name_or_url in package: package = get_package(name_or_url, client) if not package: secho(u'Invalid name or URL: "{name}"'.format(name=name_o...
Return a bar graph as a string given a dictionary of data.
def bargraph(data, max_key_width=30): """Return a bar graph as a string, given a dictionary of data.""" lines = [] max_length = min(max(len(key) for key in data.keys()), max_key_width) max_val = max(data.values()) max_val_length = max( len(_style_value(val)) for val in data.values())...
Return a dictionary of version: download_count pairs.
def version_downloads(self): """Return a dictionary of version:download_count pairs.""" ret = OrderedDict() for release, info in self.release_info: download_count = sum(file_['downloads'] for file_ in info) ret[release] = download_count return ret
Version with the most downloads.
def max_version(self): """Version with the most downloads. :return: A tuple of the form (version, n_downloads) """ data = self.version_downloads if not data: return None, 0 return max(data.items(), key=lambda item: item[1])
Version with the fewest downloads.
def min_version(self): """Version with the fewest downloads.""" data = self.version_downloads if not data: return (None, 0) return min(data.items(), key=lambda item: item[1])
dx4 dy4 dx2dy2 D = elasprep ( dx dy Te E = 1E11 nu = 0. 25 ) Defines the variables that are required to create the 2D finite difference solution coefficient matrix
def elasprep(self): """ dx4, dy4, dx2dy2, D = elasprep(dx,dy,Te,E=1E11,nu=0.25) Defines the variables that are required to create the 2D finite difference solution coefficient matrix """ if self.Method != 'SAS_NG': self.dx4 = self.dx**4 self.dy4 = self.dy**4 self.dx2...
Selects the boundary conditions E - W is for inside each panel N - S is for the block diagonal matrix ( with fringes ) Then calls the function to build the diagonal matrix
def BC_selector_and_coeff_matrix_creator(self): """ Selects the boundary conditions E-W is for inside each panel N-S is for the block diagonal matrix ("with fringes") Then calls the function to build the diagonal matrix The current method of coefficient matrix construction utilizes longer-range...
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 # ######################################### # W...
Calculates the matrix of coefficients that is later used via sparse matrix solution techniques ( scipy. sparse. linalg. spsolve ) to compute the flexural response to the load. This step need only be performed once and the coefficient matrix can very rapidly compute flexural solutions to any load. This makes this partic...
def get_coeff_values(self): """ Calculates the matrix of coefficients that is later used via sparse matrix solution techniques (scipy.sparse.linalg.spsolve) to compute the flexural response to the load. This step need only be performed once, and the coefficient matrix can very rapidly compute flexur...
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 characteristic...
w = fd_solve () Sparse flexural response calculation. Can be performed by direct factorization with UMFpack ( defuault ) or by an iterative minimum residual technique These are both the fastest of the standard Scipy builtin techniques in their respective classes Requires the coefficient matrix from 2D. coeff_matrix
def fd_solve(self): """ w = fd_solve() Sparse flexural response calculation. Can be performed by direct factorization with UMFpack (defuault) or by an iterative minimum residual technique These are both the fastest of the standard Scipy builtin techniques in their respective classes R...
Install the tools ripit and burnit in order to rip and burn audio cds.
def ripping_of_cds(): '''Install the tools ripit and burnit in order to rip and burn audio cds. More info: http://forums.debian.net/viewtopic.php?f=16&t=36826 ''' # install and configure ripit install_package('ripit') install_file_legacy(path='~/.ripit/config', username=env.user) # install ...
Install and customize the tiling window manager i3.
def i3(): '''Install and customize the tiling window manager i3.''' install_package('i3') install_file_legacy(path='~/.i3/config', username=env.user, repos_dir='repos') # setup: hide the mouse if not in use # in ~/.i3/config: 'exec /home/<USERNAME>/repos/hhpc/hhpc -i 10 &' install_packages(['ma...
Set solarized colors in urxvt tmux and vim.
def solarized(): '''Set solarized colors in urxvt, tmux, and vim. More Infos: * Getting solarized colors right with urxvt, st, tmux and vim: https://bbs.archlinux.org/viewtopic.php?id=164108 * Creating ~/.Xresources: https://wiki.archlinux.org/index.php/Rxvt-unicode#Creating_.7E.2F.Xresour...
Customize vim install package manager pathogen and some vim - packages.
def vim(): '''Customize vim, install package manager pathogen and some vim-packages. pathogen will be installed as a git repo at ~/repos/vim-pathogen and activated in vim by a symbolic link at ~/.vim/autoload/pathogen.vim A ~/.vimrc will be installed which loads the package manager within of vim. ...
Install or update the pyenv python environment.
def pyenv(): '''Install or update the pyenv python environment. Checkout or update the pyenv repo at ~/.pyenv and enable the pyenv. Pyenv wird also als Github-Repo "installiert" unter ~/.pyenv More info: * https://github.com/yyuu/pyenv * https://github.com/yyuu/pyenv/wiki/Common-build-proble...
Install a VirtualBox host system.
def virtualbox_host(): '''Install a VirtualBox host system. More Infos: * overview: https://wiki.ubuntuusers.de/VirtualBox/ * installation: https://wiki.ubuntuusers.de/VirtualBox/Installation/ ''' if query_yes_no(question='Uninstall virtualbox-dkms?', default='yes'): run('sudo apt...
Customize the server ( user authorized_keys... ).
def server_customizations(): '''Customize the server (user, authorized_keys, ...).''' username = env.user env.user = 'root' # create user all_users = run('cut -d: -f1 /etc/passwd').split() if username not in all_users: host = env.host run(flo('adduser {username}')) #...
Install or update latest Pencil version 2 a GUI prototyping tool.
def pencil2(): '''Install or update latest Pencil version 2, a GUI prototyping tool. Tip: For svg exports displayed proper in other programs (eg. inkscape, okular, reveal.js presentations) only use the 'Common Shapes' and 'Desktop - Sketchy GUI' elements. More info: github repo (forked ver...
Install or update latest Pencil version 3 a GUI prototyping tool.
def pencil3(): '''Install or update latest Pencil version 3, a GUI prototyping tool. While it is the newer one and the GUI is more fancy, it is the "more beta" version of pencil. For exmaple, to display a svg export may fail from within a reveal.js presentation. More info: Homepage: http:...
Install custom commands for user root at/ root/ bin/.
def server_prepare_root_bin_dir(): '''Install custom commands for user root at '/root/bin/'.''' commands = ['run_backup'] for command in commands: install_file_legacy(flo('/root/bin/{command}'), sudo=True) sudo(flo('chmod 755 /root/bin/{command}')) if command == 'run_backup': ...
Install and set up powerline - shell prompt.
def powerline_shell(): '''Install and set up powerline-shell prompt. More infos: * https://github.com/banga/powerline-shell * https://github.com/ohnonot/powerline-shell * https://askubuntu.com/questions/283908/how-can-i-install-and-use-powerline-plugin ''' assert env.host == 'localhost',...
Install Telegram desktop client for linux ( x64 ).
def telegram(): '''Install Telegram desktop client for linux (x64). More infos: https://telegram.org https://desktop.telegram.org/ ''' if not exists('~/bin/Telegram', msg='Download and install Telegram:'): run('mkdir -p /tmp/telegram') run('cd /tmp/telegram && wget https:/...
The utililty requires boto3 clients to CloudFormation.
def _init_boto3_clients(self, profile, region): """ The utililty requires boto3 clients to CloudFormation. Args: None Returns: Good or Bad; True or False """ try: session = None if profile and region: sessi...
Determine the drift of the stack.
def determine_drift(self): """ Determine the drift of the stack. Args: None Returns: Good or Bad; True or False """ try: response = self._cloud_formation.detect_stack_drift(StackName=self._stack_name) drift_request_id = re...
Report the drift of the stack.
def _print_drift_report(self): """ Report the drift of the stack. Args: None Returns: Good or Bad; True or False Note: not yet implemented """ try: response = self._cloud_formation.describe_stack_resources(StackName=self._sta...
Looks for settings under DJANGO_HISTORY_SETTINGS supporting dot notation for nested lookups eg. get_setting ( EXCLUDE_CHANGES. fields )
def get_setting(name): """ Looks for settings under DJANGO_HISTORY_SETTINGS, supporting dot notation for nested lookups, eg. get_setting('EXCLUDE_CHANGES.fields') """ dh = getattr(settings, 'DJANGO_HISTORY_SETTINGS', {}) result = None for k in name.split('.'): if dh is None: cont...
Encrypt data
def CryptProtectData( data, description=None, optional_entropy=None, prompt_struct=None, flags=0, ): """ Encrypt data """ data_in = DATA_BLOB(data) entropy = DATA_BLOB(optional_entropy) if optional_entropy else None data_out = DATA_BLOB() res = _CryptProtectData( data_in, description, entropy, None, ...
Returns a tuple of ( description data ) where description is the the description that was passed to the CryptProtectData call and data is the decrypted result.
def CryptUnprotectData( data, optional_entropy=None, prompt_struct=None, flags=0): """ Returns a tuple of (description, data) where description is the the description that was passed to the CryptProtectData call and data is the decrypted result. """ data_in = DATA_BLOB(data) entropy = DATA_BLOB(optional_entropy...
Use this method to set the data for this blob
def set_data(self, data): "Use this method to set the data for this blob" if data is None: self.data_size = 0 self.data = None return self.data_size = len(data) # create a string buffer so that null bytes aren't interpreted # as the end of the string self.data = ctypes.cast(ctypes.create_string_bu...
Get the data for this blob
def get_data(self): "Get the data for this blob" array = ctypes.POINTER(ctypes.c_char * len(self)) return ctypes.cast(self.data, array).contents.raw
Ask a question for input via raw_input () and return their answer.
def query_input(question, default=None, color=default_color): """Ask a question for input via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. The "answer" return value is a str. """ if de...
Check if a ssh - key is created and imported in github. Else exit with return value 1 ( die ).
def git_ssh_or_die(username, key_dir='~/.ssh'): ''' Check if a ssh-key is created and imported in github. Else, exit with return value 1 (die). ''' key_dir_expanded = os.path.expanduser(key_dir) # ssh pub key dictionary pub_keys = [] # check if ~/.ssh exists, if not die if not os.path....
Create a repository for a new fabsetup - task addon.
def new_addon(): '''Create a repository for a new fabsetup-task addon. The repo will contain the fabsetup addon boilerplate. Running this task you have to enter: * your github user account (your pypi account should be the same or similar) * addon name * task name * headline, short descript...
Prints metadata for given location.
def printMetaDataFor(archive, location): """ Prints metadata for given location. :param archive: CombineArchive instance :param location: :return: """ desc = archive.getMetadataForLocation(location) if desc.isEmpty(): print(" no metadata for '{0}'".format(location)) return ...
Prints content of combine archive
def printArchive(fileName): """ Prints content of combine archive :param fileName: path of archive :return: None """ archive = CombineArchive() if archive.initializeFromArchive(fileName) is None: print("Invalid Combine Archive") return None print('*'*80) print('Print ar...
Like cmd. exe s mklink except it will infer directory status of the target.
def mklink(): """ Like cmd.exe's mklink except it will infer directory status of the target. """ from optparse import OptionParser parser = OptionParser(usage="usage: %prog [options] link target") parser.add_option( '-d', '--directory', help="Target is a directory (only necessary if not present)", action="...
If creating a symlink from link to a target determine if target is a directory ( relative to dirname ( link )).
def _is_target_a_directory(link, rel_target): """ If creating a symlink from link to a target, determine if target is a directory (relative to dirname(link)). """ target = os.path.join(os.path.dirname(link), rel_target) return os.path.isdir(target)
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.
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.
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.
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.
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.
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.:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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, ...