_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q56600
select_dict
train
def select_dict(conn, query: str, params=None, name=None, itersize=5000): """Return a select statement's results as dictionary. Parameters ---------- conn : database connection query : select query string params : query parameters. name : server side cursor name. defaults to client side. ...
python
{ "resource": "" }
q56601
select_each
train
def select_each(conn, query: str, parameter_groups, name=None): """Run select query for each parameter set in single transaction.""" with conn: with conn.cursor(name=name) as cursor: for parameters in parameter_groups: cursor.execute(query, parameters) yield ...
python
{ "resource": "" }
q56602
query_columns
train
def query_columns(conn, query, name=None): """Lightweight query to retrieve column list of select query. Notes ----- Strongly urged to specify a cursor name for performance. """ with conn.cursor(name) as cursor: cursor.itersize = 1 cursor.execute(query) cursor.fetchmany...
python
{ "resource": "" }
q56603
ReferenceCodingSequenceKey.from_variant_and_transcript
train
def from_variant_and_transcript( cls, variant, transcript, context_size): """ Extracts the reference sequence around a variant locus on a particular transcript and determines the reading frame at the start of that sequence context. ...
python
{ "resource": "" }
q56604
create_readme_with_long_description
train
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...
python
{ "resource": "" }
q56605
stat
train
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}"'...
python
{ "resource": "" }
q56606
browse
train
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...
python
{ "resource": "" }
q56607
search
train
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}"...'....
python
{ "resource": "" }
q56608
info
train
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...
python
{ "resource": "" }
q56609
bargraph
train
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())...
python
{ "resource": "" }
q56610
Package.max_version
train
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])
python
{ "resource": "" }
q56611
Package.min_version
train
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])
python
{ "resource": "" }
q56612
ripping_of_cds
train
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 ...
python
{ "resource": "" }
q56613
i3
train
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...
python
{ "resource": "" }
q56614
solarized
train
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...
python
{ "resource": "" }
q56615
vim
train
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. ...
python
{ "resource": "" }
q56616
pyenv
train
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...
python
{ "resource": "" }
q56617
virtualbox_host
train
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...
python
{ "resource": "" }
q56618
pencil2
train
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...
python
{ "resource": "" }
q56619
pencil3
train
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:...
python
{ "resource": "" }
q56620
powerline_shell
train
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',...
python
{ "resource": "" }
q56621
DriftTool._init_boto3_clients
train
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...
python
{ "resource": "" }
q56622
DriftTool.determine_drift
train
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...
python
{ "resource": "" }
q56623
DriftTool._print_drift_report
train
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...
python
{ "resource": "" }
q56624
DATA_BLOB.set_data
train
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...
python
{ "resource": "" }
q56625
DATA_BLOB.get_data
train
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
python
{ "resource": "" }
q56626
printMetaDataFor
train
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 ...
python
{ "resource": "" }
q56627
printArchive
train
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...
python
{ "resource": "" }
q56628
mklink
train
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="...
python
{ "resource": "" }
q56629
is_reparse_point
train
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) )
python
{ "resource": "" }
q56630
is_symlink
train
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....
python
{ "resource": "" }
q56631
get_final_path
train
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...
python
{ "resource": "" }
q56632
join
train
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...
python
{ "resource": "" }
q56633
resolve_path
train
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...
python
{ "resource": "" }
q56634
trace_symlink_target
train
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...
python
{ "resource": "" }
q56635
patch_os_module
train
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
python
{ "resource": "" }
q56636
task
train
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, ...
python
{ "resource": "" }
q56637
subtask
train
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...
python
{ "resource": "" }
q56638
_is_sudoer
train
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...
python
{ "resource": "" }
q56639
install_packages
train
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...
python
{ "resource": "" }
q56640
checkup_git_repos_legacy
train
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: ...
python
{ "resource": "" }
q56641
checkup_git_repo_legacy
train
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 =...
python
{ "resource": "" }
q56642
install_file_legacy
train
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' ...
python
{ "resource": "" }
q56643
install_user_command_legacy
train
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...
python
{ "resource": "" }
q56644
_line_2_pair
train
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('"'...
python
{ "resource": "" }
q56645
extract_minors_from_setup_py
train
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...
python
{ "resource": "" }
q56646
vim_janus
train
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...
python
{ "resource": "" }
q56647
scan
train
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...
python
{ "resource": "" }
q56648
ping
train
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...
python
{ "resource": "" }
q56649
delete
train
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[...
python
{ "resource": "" }
q56650
list
train
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_...
python
{ "resource": "" }
q56651
drift
train
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, ...
python
{ "resource": "" }
q56652
start_upsert
train
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(...
python
{ "resource": "" }
q56653
read_config_info
train
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...
python
{ "resource": "" }
q56654
StackTool.print_stack_info
train
def print_stack_info(self): ''' List resources from the given stack Args: None Returns: A dictionary filled resources or None if things went sideways ''' try: rest_api_id = None deployment_found = False respon...
python
{ "resource": "" }
q56655
StackTool.print_stack_events
train
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 ...
python
{ "resource": "" }
q56656
trac
train
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...
python
{ "resource": "" }
q56657
Wallabag.query
train
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 ...
python
{ "resource": "" }
q56658
revealjs
train
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...
python
{ "resource": "" }
q56659
tweak_css
train
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', ...
python
{ "resource": "" }
q56660
decktape
train
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...
python
{ "resource": "" }
q56661
revealjs_template
train
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...
python
{ "resource": "" }
q56662
F1D.spatialDomainNoGrid
train
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 ...
python
{ "resource": "" }
q56663
F1D.build_diagonals
train
def build_diagonals(self): """ Builds the diagonals for the coefficient array """ ########################################################## # INCORPORATE BOUNDARY CONDITIONS INTO COEFFICIENT ARRAY # ########################################################## # Roll to keep the pro...
python
{ "resource": "" }
q56664
createArchiveExample
train
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...
python
{ "resource": "" }
q56665
calc_deviation
train
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...
python
{ "resource": "" }
q56666
StatsList.append
train
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: ...
python
{ "resource": "" }
q56667
pipeline
train
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)
python
{ "resource": "" }
q56668
RegisteredEnvironment.add
train
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_...
python
{ "resource": "" }
q56669
Info.current
train
def current(class_): "Windows Platform SDK GetTimeZoneInformation" tzi = class_() kernel32 = ctypes.windll.kernel32 getter = kernel32.GetTimeZoneInformation getter = getattr(kernel32, 'GetDynamicTimeZoneInformation', getter) code = getter(ctypes.byref(tzi)) return code, tzi
python
{ "resource": "" }
q56670
Info.dynamic_info
train
def dynamic_info(self): "Return a map that for a given year will return the correct Info" if self.key_name: dyn_key = self.get_key().subkey('Dynamic DST') del dyn_key['FirstEntry'] del dyn_key['LastEntry'] years = map(int, dyn_key.keys()) values = map(Info, dyn_key.values()) # create a range mappi...
python
{ "resource": "" }
q56671
Info._locate_day
train
def _locate_day(year, cutoff): """ Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION structure or call to GetTimeZoneInformation and interprets it based on the given year to identify the actual day. This method is necessary because the SYSTEMTIME structure refers to a day by its ...
python
{ "resource": "" }
q56672
redirect
train
def redirect(pattern, to, permanent=True, locale_prefix=True, anchor=None, name=None, query=None, vary=None, cache_timeout=12, decorators=None, re_flags=None, to_args=None, to_kwargs=None, prepend_locale=True, merge_query=False): """ Return a url matcher suited for urlpatterns. pa...
python
{ "resource": "" }
q56673
AllocatedTable.__get_table_size
train
def __get_table_size(self): """ Retrieve the size of the buffer needed by calling the method with a null pointer and length of zero. This should trigger an insufficient buffer error and return the size needed for the buffer. """ length = ctypes.wintypes.DWORD() res = self.method(None, length, False) i...
python
{ "resource": "" }
q56674
AllocatedTable.get_table
train
def get_table(self): """ Get the table """ buffer_length = self.__get_table_size() returned_buffer_length = ctypes.wintypes.DWORD(buffer_length) buffer = ctypes.create_string_buffer(buffer_length) pointer_type = ctypes.POINTER(self.structure) table_p = ctypes.cast(buffer, pointer_type) res = self.meth...
python
{ "resource": "" }
q56675
AllocatedTable.entries
train
def entries(self): """ Using the table structure, return the array of entries based on the table size. """ table = self.get_table() entries_array = self.row_structure * table.num_entries pointer_type = ctypes.POINTER(entries_array) return ctypes.cast(table.entries, pointer_type).contents
python
{ "resource": "" }
q56676
owncloud
train
def owncloud(): '''Set up owncloud. Package 'owncloud' pulls package 'mysql' which asks for a password. ''' hostname = re.sub(r'^[^@]+@', '', env.host) # without username if any sitename = query_input( question='\nEnter site-name of Your Owncloud web service', ...
python
{ "resource": "" }
q56677
doctree_read_handler
train
def doctree_read_handler(app, doctree): """ Add 'orphan' to metadata for partials :type app: sphinx.application.Sphinx :type doctree: docutils.nodes.document """ # noinspection PyProtectedMember docname = sys._getframe(2).f_locals['docname'] if docname.startswith('_partial'): ap...
python
{ "resource": "" }
q56678
autodoc_skip_member_handler
train
def autodoc_skip_member_handler(app, what, name, obj, skip, options): """ Skip un parseable functions. :type app: sphinx.application.Sphinx :param str what: the type of the object which the docstring belongs to (one of "module", "class", "exception", "function", "method", "attribute") :para...
python
{ "resource": "" }
q56679
Plotting.surfplot
train
def surfplot(self, z, titletext): """ Plot if you want to - for troubleshooting - 1 figure """ if self.latlon: plt.imshow(z, extent=(0, self.dx*z.shape[0], self.dy*z.shape[1], 0)) #,interpolation='nearest' plt.xlabel('longitude [deg E]', fontsize=12, fontweight='bold') plt.ylabel('lati...
python
{ "resource": "" }
q56680
Plotting.twoSurfplots
train
def twoSurfplots(self): """ Plot multiple subplot figure for 2D array """ # Could more elegantly just call surfplot twice # And also could include xyzinterp as an option inside surfplot. # Noted here in case anyone wants to take that on in the future... plt.subplot(211) plt.title('Load ...
python
{ "resource": "" }
q56681
Flexure.outputDeflections
train
def outputDeflections(self): """ Outputs a grid of deflections if an output directory is defined in the configuration file If the filename given in the configuration file ends in ".npy", then a binary numpy grid will be exported. Otherwise, an ASCII grid will be exported. """ ...
python
{ "resource": "" }
q56682
Flexure.TeArraySizeCheck
train
def TeArraySizeCheck(self): """ Checks that Te and q0 array sizes are compatible For finite difference solution. """ # Only if they are both defined and are arrays # Both being arrays is a possible bug in this check routine that I have # intentionally introduced if type(self.Te) == np.n...
python
{ "resource": "" }
q56683
Flexure.FD
train
def FD(self): """ Set-up for the finite difference solution method """ if self.Verbose: print("Finite Difference Solution Technique") # Used to check for coeff_matrix here, but now doing so in self.bc_check() # called by f1d and f2d at the start # # Define a stress-based qs = q0 ...
python
{ "resource": "" }
q56684
Flexure.SAS
train
def SAS(self): """ Set-up for the rectangularly-gridded superposition of analytical solutions method for solving flexure """ if self.x is None: self.x = np.arange(self.dx/2., self.dx * self.qs.shape[0], self.dx) if self.filename: # Define the (scalar) elastic thickness self.Te...
python
{ "resource": "" }
q56685
Flexure.SAS_NG
train
def SAS_NG(self): """ Set-up for the ungridded superposition of analytical solutions method for solving flexure """ if self.filename: # Define the (scalar) elastic thickness self.Te = self.configGet("float", "input", "ElasticThickness") # See if it wants to be run in lat/lon ...
python
{ "resource": "" }
q56686
_c3_mro
train
def _c3_mro(cls, abcs=None): """Computes the method resolution order using extended C3 linearization. If no *abcs* are given, the algorithm works exactly like the built-in C3 linearization used for method resolution. If given, *abcs* is a list of abstract base classes that should be inserted into ...
python
{ "resource": "" }
q56687
singledispatch
train
def singledispatch(function): # noqa """Single-dispatch generic function decorator. Transforms a function into a generic function, which can have different behaviours depending upon the type of its first argument. The decorated function acts as the default implementation, and additional implementa...
python
{ "resource": "" }
q56688
Runner._parse_args
train
def _parse_args(self, args): """Parses any supplied command-line args and provides help text. """ parser = ArgumentParser(description="Runs pylint recursively on a directory") parser.add_argument( "-v", "--verbose", dest="verbose", action="store_...
python
{ "resource": "" }
q56689
Runner._parse_ignores
train
def _parse_ignores(self): """ Parse the ignores setting from the pylintrc file if available. """ error_message = ( colorama.Fore.RED + "{} does not appear to be a valid pylintrc file".format(self.rcfile) + colorama.Fore.RESET ) if not os.path.isfile(...
python
{ "resource": "" }
q56690
Runner.run
train
def run(self, output=None, error=None): """ Runs pylint on all python files in the current directory """ pylint_output = output if output is not None else sys.stdout pylint_error = error if error is not None else sys.stderr savedout, savederr = sys.__stdout__, sys.__stderr__ sys...
python
{ "resource": "" }
q56691
strict
train
def strict(*types): """Decorator, type check production rule output""" def decorate(func): @wraps(func) def wrapper(self, p): func(self, p) if not isinstance(p[0], types): raise YAMLStrictTypeError(p[0], types, func) wrapper.co_firstlineno = func...
python
{ "resource": "" }
q56692
find_column
train
def find_column(t): """Get cursor position, based on previous newline""" pos = t.lexer.lexpos data = t.lexer.lexdata last_cr = data.rfind('\n', 0, pos) if last_cr < 0: last_cr = -1 column = pos - last_cr return column
python
{ "resource": "" }
q56693
no_sleep
train
def no_sleep(): """ Context that prevents the computer from going to sleep. """ mode = power.ES.continuous | power.ES.system_required handle_nonzero_success(power.SetThreadExecutionState(mode)) try: yield finally: handle_nonzero_success(power.SetThreadExecutionState(power.ES.continuous))
python
{ "resource": "" }
q56694
selfoss
train
def selfoss(reset_password=False): '''Install, update and set up selfoss. This selfoss installation uses sqlite (selfoss-default), php5-fpm and nginx. The connection is https-only and secured by a letsencrypt certificate. This certificate must be created separately with task setup.server_letsencrypt....
python
{ "resource": "" }
q56695
get_cache_path
train
def get_cache_path(filename): """ get file path """ cwd = os.path.dirname(os.path.realpath(__file__)) return os.path.join(cwd, filename)
python
{ "resource": "" }
q56696
get_process_token
train
def get_process_token(): """ Get the current process token """ token = wintypes.HANDLE() res = process.OpenProcessToken( process.GetCurrentProcess(), process.TOKEN_ALL_ACCESS, token) if not res > 0: raise RuntimeError("Couldn't get process token") return token
python
{ "resource": "" }
q56697
get_symlink_luid
train
def get_symlink_luid(): """ Get the LUID for the SeCreateSymbolicLinkPrivilege """ symlink_luid = privilege.LUID() res = privilege.LookupPrivilegeValue( None, "SeCreateSymbolicLinkPrivilege", symlink_luid) if not res > 0: raise RuntimeError("Couldn't lookup privilege value") return symlink_luid
python
{ "resource": "" }
q56698
get_privilege_information
train
def get_privilege_information(): """ Get all privileges associated with the current process. """ # first call with zero length to determine what size buffer we need return_length = wintypes.DWORD() params = [ get_process_token(), privilege.TOKEN_INFORMATION_CLASS.TokenPrivileges, None, 0, return_length...
python
{ "resource": "" }
q56699
enable_symlink_privilege
train
def enable_symlink_privilege(): """ Try to assign the symlink privilege to the current process token. Return True if the assignment is successful. """ # create a space in memory for a TOKEN_PRIVILEGES structure # with one element size = ctypes.sizeof(privilege.TOKEN_PRIVILEGES) size += ctypes.sizeof(privilege....
python
{ "resource": "" }