repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
ethereum/eth-account
eth_account/_utils/structured_data/hashing.py
encode_type
python
def encode_type(primary_type, types): # Getting the dependencies and sorting them alphabetically as per EIP712 deps = get_dependencies(primary_type, types) sorted_deps = (primary_type,) + tuple(sorted(deps)) result = ''.join( [ encode_struct(struct_name, types[struct_name]) ...
The type of a struct is encoded as name ‖ "(" ‖ member₁ ‖ "," ‖ member₂ ‖ "," ‖ … ‖ memberₙ ")" where each member is written as type ‖ " " ‖ name.
train
https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/_utils/structured_data/hashing.py#L72-L87
[ "def get_dependencies(primary_type, types):\n \"\"\"\n Perform DFS to get all the dependencies of the primary_type\n \"\"\"\n deps = set()\n struct_names_yet_to_be_expanded = [primary_type]\n\n while len(struct_names_yet_to_be_expanded) > 0:\n struct_name = struct_names_yet_to_be_expanded.p...
from itertools import ( groupby, ) import json from operator import ( itemgetter, ) from eth_abi import ( encode_abi, is_encodable, ) from eth_abi.grammar import ( parse, ) from eth_utils import ( ValidationError, keccak, to_tuple, toolz, ) from .validation import ( validate_st...
ethereum/eth-account
eth_account/_utils/structured_data/hashing.py
is_valid_abi_type
python
def is_valid_abi_type(type_name): valid_abi_types = {"address", "bool", "bytes", "int", "string", "uint"} is_bytesN = type_name.startswith("bytes") and 1 <= int(type_name[5:]) <= 32 is_intN = ( type_name.startswith("int") and 8 <= int(type_name[3:]) <= 256 and int(type_name[3:]) % 8 ...
This function is used to make sure that the ``type_name`` is a valid ABI Type. Please note that this is a temporary function and should be replaced by the corresponding ABI function, once the following issue has been resolved. https://github.com/ethereum/eth-abi/issues/125
train
https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/_utils/structured_data/hashing.py#L94-L127
null
from itertools import ( groupby, ) import json from operator import ( itemgetter, ) from eth_abi import ( encode_abi, is_encodable, ) from eth_abi.grammar import ( parse, ) from eth_utils import ( ValidationError, keccak, to_tuple, toolz, ) from .validation import ( validate_st...
ethereum/eth-account
eth_account/_utils/structured_data/hashing.py
get_depths_and_dimensions
python
def get_depths_and_dimensions(data, depth): if not isinstance(data, (list, tuple)): # Not checking for Iterable instance, because even Dictionaries and strings # are considered as iterables, but that's not what we want the condition to be. return () yield depth, len(data) for item ...
Yields 2-length tuples of depth and dimension of each element at that depth
train
https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/_utils/structured_data/hashing.py#L137-L150
null
from itertools import ( groupby, ) import json from operator import ( itemgetter, ) from eth_abi import ( encode_abi, is_encodable, ) from eth_abi.grammar import ( parse, ) from eth_utils import ( ValidationError, keccak, to_tuple, toolz, ) from .validation import ( validate_st...
ethereum/eth-account
eth_account/_utils/structured_data/hashing.py
get_array_dimensions
python
def get_array_dimensions(data): depths_and_dimensions = get_depths_and_dimensions(data, 0) # re-form as a dictionary with `depth` as key, and all of the dimensions found at that depth. grouped_by_depth = { depth: tuple(dimension for depth, dimension in group) for depth, group in groupby(dept...
Given an array type data item, check that it is an array and return the dimensions as a tuple. Ex: get_array_dimensions([[1, 2, 3], [4, 5, 6]]) returns (2, 3)
train
https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/_utils/structured_data/hashing.py#L153-L188
null
from itertools import ( groupby, ) import json from operator import ( itemgetter, ) from eth_abi import ( encode_abi, is_encodable, ) from eth_abi.grammar import ( parse, ) from eth_utils import ( ValidationError, keccak, to_tuple, toolz, ) from .validation import ( validate_st...
ethereum/eth-account
eth_account/_utils/signing.py
hash_of_signed_transaction
python
def hash_of_signed_transaction(txn_obj): ''' Regenerate the hash of the signed transaction object. 1. Infer the chain ID from the signature 2. Strip out signature from transaction 3. Annotate the transaction with that ID, if available 4. Take the hash of the serialized, unsigned, chain-aware tr...
Regenerate the hash of the signed transaction object. 1. Infer the chain ID from the signature 2. Strip out signature from transaction 3. Annotate the transaction with that ID, if available 4. Take the hash of the serialized, unsigned, chain-aware transaction Chain ID inference and annotation is a...
train
https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/_utils/signing.py#L96-L117
[ "def strip_signature(txn):\n unsigned_parts = itertools.islice(txn, len(UNSIGNED_TRANSACTION_FIELDS))\n return list(unsigned_parts)\n", "def extract_chain_id(raw_v):\n '''\n Extracts chain ID, according to EIP-155\n @return (chain_id, v)\n '''\n above_id_offset = raw_v - CHAIN_ID_OFFSET\n ...
from cytoolz import ( curry, pipe, ) from eth_utils import ( to_bytes, to_int, to_text, ) from eth_account._utils.structured_data.hashing import ( hash_domain, hash_message, load_and_validate_structured_message, ) from eth_account._utils.transactions import ( ChainAwareUnsignedTrans...
ethereum/eth-account
eth_account/_utils/signing.py
extract_chain_id
python
def extract_chain_id(raw_v): ''' Extracts chain ID, according to EIP-155 @return (chain_id, v) ''' above_id_offset = raw_v - CHAIN_ID_OFFSET if above_id_offset < 0: if raw_v in {0, 1}: return (None, raw_v + V_OFFSET) elif raw_v in {27, 28}: return (None, r...
Extracts chain ID, according to EIP-155 @return (chain_id, v)
train
https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/_utils/signing.py#L120-L135
null
from cytoolz import ( curry, pipe, ) from eth_utils import ( to_bytes, to_int, to_text, ) from eth_account._utils.structured_data.hashing import ( hash_domain, hash_message, load_and_validate_structured_message, ) from eth_account._utils.transactions import ( ChainAwareUnsignedTrans...
evansde77/dockerstache
src/dockerstache/dockerstache.py
run
python
def run(**options): with Dotfile(options) as conf: if conf['context'] is None: msg = "No context file has been provided" LOGGER.error(msg) raise RuntimeError(msg) if not os.path.exists(conf['context_path']): msg = "Context file {} not found".format(con...
_run_ Run the dockerstache process to render templates based on the options provided If extend_context is passed as options it will be used to extend the context with the contents of the dictionary provided via context.update(extend_context)
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/dockerstache.py#L18-L64
null
#!/usr/bin/env python """ _dockerstache_ Main function to invoke dockerstache as a lib call """ import os from .dotfile import Dotfile from .templates import process_templates, process_copies from .context import Context from . import get_logger LOGGER = get_logger()
evansde77/dockerstache
src/dockerstache/templates.py
dir_visitor
python
def dir_visitor(dirname, visitor): visitor(dirname) for obj in os.listdir(dirname): obj_path = os.path.join(dirname, obj) if os.path.isdir(obj_path): dir_visitor(obj_path, visitor)
_dir_visitor_ walk through all files in dirname, find directories and call the callable on them. :param dirname: Name of directory to start visiting, all subdirs will be visited :param visitor: Callable invoked on each dir visited
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/templates.py#L18-L33
[ "def dir_visitor(dirname, visitor):\n \"\"\"\n _dir_visitor_\n\n walk through all files in dirname, find\n directories and call the callable on them.\n\n :param dirname: Name of directory to start visiting,\n all subdirs will be visited\n :param visitor: Callable invoked on each dir visited\n...
#!/usr/bin/env python """ _templates_ Find templates, render templates etc """ import os import functools import pystache import shutil from . import get_logger LOGGER = get_logger() def replicate_directory_tree(input_dir, output_dir): """ _replicate_directory_tree_ clone dir structure under input_d...
evansde77/dockerstache
src/dockerstache/templates.py
replicate_directory_tree
python
def replicate_directory_tree(input_dir, output_dir): def transplant_dir(target, dirname): x = dirname.replace(input_dir, target) if not os.path.exists(x): LOGGER.info('Creating: {}'.format(x)) os.makedirs(x) dir_visitor( input_dir, functools.partial(trans...
_replicate_directory_tree_ clone dir structure under input_dir into output dir All subdirs beneath input_dir will be created under output_dir :param input_dir: path to dir tree to be cloned :param output_dir: path to new dir where dir structure will be created
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/templates.py#L36-L56
[ "def dir_visitor(dirname, visitor):\n \"\"\"\n _dir_visitor_\n\n walk through all files in dirname, find\n directories and call the callable on them.\n\n :param dirname: Name of directory to start visiting,\n all subdirs will be visited\n :param visitor: Callable invoked on each dir visited\n...
#!/usr/bin/env python """ _templates_ Find templates, render templates etc """ import os import functools import pystache import shutil from . import get_logger LOGGER = get_logger() def dir_visitor(dirname, visitor): """ _dir_visitor_ walk through all files in dirname, find directories and call ...
evansde77/dockerstache
src/dockerstache/templates.py
find_templates
python
def find_templates(input_dir): templates = [] def template_finder(result, dirname): for obj in os.listdir(dirname): if obj.endswith('.mustache'): result.append(os.path.join(dirname, obj)) dir_visitor( input_dir, functools.partial(template_finder, templat...
_find_templates_ traverse the input_dir structure and return a list of template files ending with .mustache :param input_dir: Path to start recursive search for mustache templates :returns: List of file paths corresponding to templates
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/templates.py#L59-L81
[ "def dir_visitor(dirname, visitor):\n \"\"\"\n _dir_visitor_\n\n walk through all files in dirname, find\n directories and call the callable on them.\n\n :param dirname: Name of directory to start visiting,\n all subdirs will be visited\n :param visitor: Callable invoked on each dir visited\n...
#!/usr/bin/env python """ _templates_ Find templates, render templates etc """ import os import functools import pystache import shutil from . import get_logger LOGGER = get_logger() def dir_visitor(dirname, visitor): """ _dir_visitor_ walk through all files in dirname, find directories and call ...
evansde77/dockerstache
src/dockerstache/templates.py
find_copies
python
def find_copies(input_dir, exclude_list): copies = [] def copy_finder(copies, dirname): for obj in os.listdir(dirname): pathname = os.path.join(dirname, obj) if os.path.isdir(pathname): continue if obj in exclude_list: continue ...
find files that are not templates and not in the exclude_list for copying from template to image
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/templates.py#L84-L107
[ "def dir_visitor(dirname, visitor):\n \"\"\"\n _dir_visitor_\n\n walk through all files in dirname, find\n directories and call the callable on them.\n\n :param dirname: Name of directory to start visiting,\n all subdirs will be visited\n :param visitor: Callable invoked on each dir visited\n...
#!/usr/bin/env python """ _templates_ Find templates, render templates etc """ import os import functools import pystache import shutil from . import get_logger LOGGER = get_logger() def dir_visitor(dirname, visitor): """ _dir_visitor_ walk through all files in dirname, find directories and call ...
evansde77/dockerstache
src/dockerstache/templates.py
render_template
python
def render_template(template_in, file_out, context): renderer = pystache.Renderer() result = renderer.render_path(template_in, context) with open(file_out, 'w') as handle: LOGGER.info('Rendering: {} to {}'.format(template_in, file_out)) handle.write(result) shutil.copymode(template_in, f...
_render_template_ Render a single template file, using the context provided and write the file out to the location specified #TODO: verify the template is completely rendered, no missing values
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/templates.py#L110-L126
null
#!/usr/bin/env python """ _templates_ Find templates, render templates etc """ import os import functools import pystache import shutil from . import get_logger LOGGER = get_logger() def dir_visitor(dirname, visitor): """ _dir_visitor_ walk through all files in dirname, find directories and call ...
evansde77/dockerstache
src/dockerstache/templates.py
copy_file
python
def copy_file(src, target): LOGGER.info("Copying {} to {}".format(src, target)) shutil.copyfile(src, target) shutil.copymode(src, target)
copy_file copy source to target
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/templates.py#L129-L138
null
#!/usr/bin/env python """ _templates_ Find templates, render templates etc """ import os import functools import pystache import shutil from . import get_logger LOGGER = get_logger() def dir_visitor(dirname, visitor): """ _dir_visitor_ walk through all files in dirname, find directories and call ...
evansde77/dockerstache
src/dockerstache/templates.py
process_templates
python
def process_templates(input_dir, target_dir, context): if not target_dir.endswith('/'): target_dir = "{}/".format(target_dir) if not os.path.exists(target_dir): LOGGER.info('Creating: {}'.format(target_dir)) os.makedirs(target_dir) replicate_directory_tree(input_dir, target_dir) ...
_process_templates_ Given the input dir containing a set of template, clone the structure under that directory into the target dir using the context to process any mustache templates that are encountered
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/templates.py#L141-L161
[ "def replicate_directory_tree(input_dir, output_dir):\n \"\"\"\n _replicate_directory_tree_\n\n clone dir structure under input_dir into output dir\n All subdirs beneath input_dir will be created under\n output_dir\n :param input_dir: path to dir tree to be cloned\n :param output_dir: path to n...
#!/usr/bin/env python """ _templates_ Find templates, render templates etc """ import os import functools import pystache import shutil from . import get_logger LOGGER = get_logger() def dir_visitor(dirname, visitor): """ _dir_visitor_ walk through all files in dirname, find directories and call ...
evansde77/dockerstache
src/dockerstache/templates.py
process_copies
python
def process_copies(input_dir, target_dir, excludes): copies = find_copies(input_dir, excludes) for c in copies: output_file = c.replace(input_dir, target_dir) copy_file(c, output_file)
_process_copies_ Handles files to be copied across, assumes that dir structure has already been replicated
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/templates.py#L164-L175
[ "def copy_file(src, target):\n \"\"\"\n copy_file\n\n copy source to target\n\n \"\"\"\n LOGGER.info(\"Copying {} to {}\".format(src, target))\n shutil.copyfile(src, target)\n shutil.copymode(src, target)\n", "def find_copies(input_dir, exclude_list):\n \"\"\"\n find files that are not ...
#!/usr/bin/env python """ _templates_ Find templates, render templates etc """ import os import functools import pystache import shutil from . import get_logger LOGGER = get_logger() def dir_visitor(dirname, visitor): """ _dir_visitor_ walk through all files in dirname, find directories and call ...
evansde77/dockerstache
setup.py
get_default
python
def get_default(parser, section, option, default): try: result = parser.get(section, option) except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): result = default return result
helper to get config settings with a default if not present
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/setup.py#L16-L22
null
""" _setup.py_ Cirrus template setup.py that reads most of its business from the cirrus.conf file. This lightweight setup.py should be used by projects managed with cirrus. """ import setuptools try: import ConfigParser except ImportError: import configparser as ConfigParser # Build a parser and fetch setu...
evansde77/dockerstache
src/dockerstache/__main__.py
build_parser
python
def build_parser(): parser = argparse.ArgumentParser( description='dockerstache templating util' ) parser.add_argument( '--output', '-o', help='Working directory to render dockerfile and templates', dest='output', default=None ) parser.add_argument( ...
_build_parser_ Set up CLI parser options, parse the CLI options an return the parsed results
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/__main__.py#L17-L65
null
#!/usr/bin/env python """ _dockerstache_ """ import os import sys import argparse from . import get_logger from .dockerstache import run LOGGER = get_logger() def main(): """ _main_ Create a CLI parser and use that to run the template rendering process """ options = build_parser() t...
evansde77/dockerstache
src/dockerstache/__main__.py
main
python
def main(): options = build_parser() try: run(**options) except RuntimeError as ex: msg = ( "An error occurred running dockerstache: {} " "please see logging info above for details" ).format(ex) LOGGER.error(msg) sys.exit(1)
_main_ Create a CLI parser and use that to run the template rendering process
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/__main__.py#L68-L86
[ "def run(**options):\n \"\"\"\n _run_\n\n Run the dockerstache process to render templates\n based on the options provided\n\n If extend_context is passed as options it will be used to\n extend the context with the contents of the dictionary provided\n via context.update(extend_context)\n\n ...
#!/usr/bin/env python """ _dockerstache_ """ import os import sys import argparse from . import get_logger from .dockerstache import run LOGGER = get_logger() def build_parser(): """ _build_parser_ Set up CLI parser options, parse the CLI options an return the parsed results """ parser =...
evansde77/dockerstache
src/dockerstache/__init__.py
setup_logger
python
def setup_logger(): logger = logging.getLogger('dockerstache') logger.setLevel(logging.INFO) handler = logging.StreamHandler(stream=sys.stdout) handler.setLevel(logging.INFO) logger.addHandler(handler) return logger
setup basic logger
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/__init__.py#L31-L40
null
#!/usr/bin/env python """ _dockerstache_ util package for rendering docker files from mustache templates """ import sys import logging import logging.handlers __version__ = "0.0.14" _LOGGER = { "logger": None } def get_logger(): """ _get_logger_ Get package logger instance """ if _LOGGER...
evansde77/dockerstache
src/dockerstache/context.py
Context.load
python
def load(self): if self._defaults_file is not None: if not os.path.exists(self._defaults_file): msg = "Unable to find defaults file: {}".format(self._defaults_file) LOGGER.error(msg) raise RuntimeError(msg) with open(self._defaults_file, 'r...
_load_ Load the defaults file if specified and overlay the json file on top of that
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/context.py#L46-L75
[ "def update(d, u):\n \"\"\"recursive dictionary merge helper\"\"\"\n for k, v in six.iteritems(u):\n if isinstance(v, collections.Mapping):\n r = update(d.get(k, {}), v)\n d[k] = r\n else:\n d[k] = u[k]\n return d\n" ]
class Context(dict): """ _Context_ Util wrapper around a dict to load json files in precedence and build a dictionary for rendering templates """ def __init__(self, jsonfile=None, defaultfile=None): super(Context, self).__init__() self._defaults = {} self._defaults_...
evansde77/dockerstache
src/dockerstache/dotfile.py
execute_command
python
def execute_command(working_dir, cmd, env_dict): proc_env = os.environ.copy() proc_env["PATH"] = "{}:{}:.".format(proc_env["PATH"], working_dir) proc_env.update(env_dict) proc = subprocess.Popen( cmd, cwd=working_dir, env=proc_env, shell=True, stdout=subprocess.PI...
execute_command: run the command provided in the working dir specified adding the env_dict settings to the execution environment :param working_dir: path to directory to execute command also gets added to the PATH :param cmd: Shell command to execute :param env_dict: dictionary of additional...
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/dotfile.py#L19-L53
null
#!/usr/bin/env python """ dotfile Utils for reading the .dockerstache file in a template dir and looking for config/actions found inside it """ import os import six import json import subprocess from . import get_logger LOGGER = get_logger() def absolute_path(p): result = p if not os.path.isabs(p): ...
evansde77/dockerstache
src/dockerstache/dotfile.py
Dotfile.load
python
def load(self): if self.exists(): with open(self.dot_file, 'r') as handle: self.update(json.load(handle)) if self.options['context'] is not None: self['context'] = self.options['context'] else: self.options['context'] = self['context'] ...
read dotfile and populate self opts will override the dotfile settings, make sure everything is synced in both opts and this object
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/dotfile.py#L91-L126
[ "def exists(self):\n \"\"\"check dotfile exists\"\"\"\n return os.path.exists(self.dot_file)\n" ]
class Dotfile(dict): """ object to encapsulate access to the .dockerstache file in a template """ def __init__(self, opts): super(Dotfile, self).__init__() self.options = opts self.template_dir = opts['input'] self.dot_file = os.path.join(self.template_dir, '.dockers...
evansde77/dockerstache
src/dockerstache/dotfile.py
Dotfile.env_dictionary
python
def env_dictionary(self): none_to_str = lambda x: str(x) if x else "" return {"DOCKERSTACHE_{}".format(k.upper()): none_to_str(v) for k, v in six.iteritems(self)}
convert the options to this script into an env var dictionary for pre and post scripts
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/dotfile.py#L152-L158
null
class Dotfile(dict): """ object to encapsulate access to the .dockerstache file in a template """ def __init__(self, opts): super(Dotfile, self).__init__() self.options = opts self.template_dir = opts['input'] self.dot_file = os.path.join(self.template_dir, '.dockers...
evansde77/dockerstache
src/dockerstache/dotfile.py
Dotfile.pre_script
python
def pre_script(self): if self['pre_script'] is None: return LOGGER.info("Executing pre script: {}".format(self['pre_script'])) cmd = self['pre_script'] execute_command(self.abs_input_dir(), cmd, self.env_dictionary()) LOGGER.info("Pre Script completed")
execute the pre script if it is defined
train
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/dotfile.py#L160-L169
[ "def execute_command(working_dir, cmd, env_dict):\n \"\"\"\n execute_command: run the command provided in the working dir\n specified adding the env_dict settings to the\n execution environment\n\n :param working_dir: path to directory to execute command\n also gets added to the PATH\n :para...
class Dotfile(dict): """ object to encapsulate access to the .dockerstache file in a template """ def __init__(self, opts): super(Dotfile, self).__init__() self.options = opts self.template_dir = opts['input'] self.dot_file = os.path.join(self.template_dir, '.dockers...
ScottDuckworth/python-anyvcs
anyvcs/git.py
GitRepo.clone
python
def clone(cls, srcpath, destpath, encoding='utf-8'): cmd = [GIT, 'clone', '--quiet', '--bare', srcpath, destpath] subprocess.check_call(cmd) return cls(destpath, encoding)
Clone an existing repository to a new bare repository.
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/git.py#L59-L63
null
class GitRepo(VCSRepo): """A git repository Valid revisions are anything that git considers as a revision. """ @classmethod @classmethod def create(cls, path, encoding='utf-8'): """Create a new bare repository""" cmd = [GIT, 'init', '--quiet', '--bare', path] subproc...
ScottDuckworth/python-anyvcs
anyvcs/git.py
GitRepo.create
python
def create(cls, path, encoding='utf-8'): cmd = [GIT, 'init', '--quiet', '--bare', path] subprocess.check_call(cmd) return cls(path, encoding)
Create a new bare repository
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/git.py#L66-L70
null
class GitRepo(VCSRepo): """A git repository Valid revisions are anything that git considers as a revision. """ @classmethod def clone(cls, srcpath, destpath, encoding='utf-8'): """Clone an existing repository to a new bare repository.""" cmd = [GIT, 'clone', '--quiet', '--bare', s...
ScottDuckworth/python-anyvcs
anyvcs/common.py
parse_isodate
python
def parse_isodate(datestr): m = isodate_rx.search(datestr) assert m, 'unrecognized date format: ' + datestr year, month, day = m.group('year', 'month', 'day') hour, minute, second, fraction = m.group('hour', 'minute', 'second', 'fraction') tz, tzhh, tzmm = m.group('tz', 'tzhh', 'tzmm') dt = date...
Parse a string that loosely fits ISO 8601 formatted date-time string
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/common.py#L43-L72
null
# Copyright (c) 2013-2014, Clemson University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditio...
ScottDuckworth/python-anyvcs
anyvcs/common.py
VCSRepo.ls
python
def ls( self, rev, path, recursive=False, recursive_dirs=False, directory=False, report=() ): raise NotImplementedError
List directory or file :param rev: The revision to use. :param path: The path to list. May start with a '/' or not. Directories may end with a '/' or not. :param recursive: Recursively list files in subdirectories. :param recursive_dirs: Used when recursive=True, al...
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/common.py#L338-L375
null
class VCSRepo(object): __metaclass__ = ABCMetaDocStringInheritor def __init__(self, path, encoding='utf-8'): """Open an existing repository""" self.path = path self.encoding = encoding @abstractproperty def private_path(self): """Get the path to a directory which can be...
ScottDuckworth/python-anyvcs
anyvcs/common.py
VCSRepo.log
python
def log( self, revrange=None, limit=None, firstparent=False, merges=None, path=None, follow=False ): raise NotImplementedError
Get commit logs :param revrange: Either a single revision or a range of revisions as a 2-element list or tuple. :param int limit: Limit the number of log entries. :param bool firstparent: Only follow the first parent of merges. :param bool merges: True means onl...
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/common.py#L460-L489
null
class VCSRepo(object): __metaclass__ = ABCMetaDocStringInheritor def __init__(self, path, encoding='utf-8'): """Open an existing repository""" self.path = path self.encoding = encoding @abstractproperty def private_path(self): """Get the path to a directory which can be...
ScottDuckworth/python-anyvcs
anyvcs/__init__.py
clone
python
def clone(srcpath, destpath, vcs=None): vcs = vcs or probe(srcpath) cls = _get_repo_class(vcs) return cls.clone(srcpath, destpath)
Clone an existing repository. :param str srcpath: Path to an existing repository :param str destpath: Desired path of new repository :param str vcs: Either ``git``, ``hg``, or ``svn`` :returns VCSRepo: The newly cloned repository If ``vcs`` is not given, then the repository type is discovered from...
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/__init__.py#L32-L46
[ "def probe(path):\n \"\"\"Probe a repository for its type.\n\n :param str path: The path of the repository\n :raises UnknownVCSType: if the repository type couldn't be inferred\n :returns str: either ``git``, ``hg``, or ``svn``\n\n This function employs some heuristics to guess the type of the reposi...
# Copyright (c) 2013-2014, Clemson University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditio...
ScottDuckworth/python-anyvcs
anyvcs/__init__.py
probe
python
def probe(path): import os from .common import UnknownVCSType if os.path.isdir(os.path.join(path, '.git')): return 'git' elif os.path.isdir(os.path.join(path, '.hg')): return 'hg' elif ( os.path.isfile(os.path.join(path, 'config')) and os.path.isdir(os.path.join(path,...
Probe a repository for its type. :param str path: The path of the repository :raises UnknownVCSType: if the repository type couldn't be inferred :returns str: either ``git``, ``hg``, or ``svn`` This function employs some heuristics to guess the type of the repository.
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/__init__.py#L60-L91
null
# Copyright (c) 2013-2014, Clemson University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditio...
ScottDuckworth/python-anyvcs
anyvcs/__init__.py
open
python
def open(path, vcs=None): import os assert os.path.isdir(path), path + ' is not a directory' vcs = vcs or probe(path) cls = _get_repo_class(vcs) return cls(path)
Open an existing repository :param str path: The path of the repository :param vcs: If specified, assume the given repository type to avoid auto-detection. Either ``git``, ``hg``, or ``svn``. :raises UnknownVCSType: if the repository type couldn't be inferred If ``vcs`` is not specifie...
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/__init__.py#L94-L109
[ "def probe(path):\n \"\"\"Probe a repository for its type.\n\n :param str path: The path of the repository\n :raises UnknownVCSType: if the repository type couldn't be inferred\n :returns str: either ``git``, ``hg``, or ``svn``\n\n This function employs some heuristics to guess the type of the reposi...
# Copyright (c) 2013-2014, Clemson University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditio...
ScottDuckworth/python-anyvcs
anyvcs/svn.py
SvnRepo.clone
python
def clone(cls, srcpath, destpath): try: os.makedirs(destpath) except OSError as e: if not e.errno == errno.EEXIST: raise cmd = [SVNADMIN, 'dump', '--quiet', '.'] dump = subprocess.Popen( cmd, cwd=srcpath, stdout=subprocess.PIPE, ...
Copy a main repository to a new location.
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L118-L138
null
class SvnRepo(VCSRepo): """A Subversion repository Unless otherwise specified, valid revisions are: - an integer (ex: 194) - an integer as a string (ex: "194") - a branch or tag name (ex: "HEAD", "trunk", "branches/branch1") - a branch or tag name at a specific revision (ex: "trunk:194") ...
ScottDuckworth/python-anyvcs
anyvcs/svn.py
SvnRepo.create
python
def create(cls, path): try: os.makedirs(path) except OSError as e: if not e.errno == errno.EEXIST: raise cmd = [SVNADMIN, 'create', path] subprocess.check_call(cmd) return cls(path)
Create a new repository
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L141-L150
null
class SvnRepo(VCSRepo): """A Subversion repository Unless otherwise specified, valid revisions are: - an integer (ex: 194) - an integer as a string (ex: "194") - a branch or tag name (ex: "HEAD", "trunk", "branches/branch1") - a branch or tag name at a specific revision (ex: "trunk:194") ...
ScottDuckworth/python-anyvcs
anyvcs/svn.py
SvnRepo.proplist
python
def proplist(self, rev, path=None): rev, prefix = self._maprev(rev) if path is None: return self._proplist(str(rev), None) else: path = type(self).cleanPath(_join(prefix, path)) return self._proplist(str(rev), path)
List Subversion properties of the path
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L193-L200
[ "def _join(*args):\n return '/'.join(arg for arg in args if arg)\n", "def cleanPath(cls, path):\n path = multislash_rx.sub('/', path)\n if not path.startswith('/'):\n path = '/' + path\n return path\n", "def _proplist(self, rev, path):\n cmd = [SVNLOOK, 'proplist', '-r', rev, '.', path or ...
class SvnRepo(VCSRepo): """A Subversion repository Unless otherwise specified, valid revisions are: - an integer (ex: 194) - an integer as a string (ex: "194") - a branch or tag name (ex: "HEAD", "trunk", "branches/branch1") - a branch or tag name at a specific revision (ex: "trunk:194") ...
ScottDuckworth/python-anyvcs
anyvcs/svn.py
SvnRepo.propget
python
def propget(self, prop, rev, path=None): rev, prefix = self._maprev(rev) if path is None: return self._propget(prop, str(rev), None) else: path = type(self).cleanPath(_join(prefix, path)) return self._propget(prop, str(rev), path)
Get Subversion property value of the path
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L206-L213
[ "def _join(*args):\n return '/'.join(arg for arg in args if arg)\n", "def cleanPath(cls, path):\n path = multislash_rx.sub('/', path)\n if not path.startswith('/'):\n path = '/' + path\n return path\n", "def _propget(self, prop, rev, path):\n cmd = [SVNLOOK, 'propget', '-r', rev, '.', prop...
class SvnRepo(VCSRepo): """A Subversion repository Unless otherwise specified, valid revisions are: - an integer (ex: 194) - an integer as a string (ex: "194") - a branch or tag name (ex: "HEAD", "trunk", "branches/branch1") - a branch or tag name at a specific revision (ex: "trunk:194") ...
ScottDuckworth/python-anyvcs
anyvcs/svn.py
SvnRepo.dump
python
def dump( self, stream, progress=None, lower=None, upper=None, incremental=False, deltas=False ): cmd = [SVNADMIN, 'dump', '.'] if progress is None: cmd.append('-q') if lower is not None: cmd.append('-r') if upper is None: c...
Dump the repository to a dumpfile stream. :param stream: A file stream to which the dumpfile is written :param progress: A file stream to which progress is written :param lower: Must be a numeric version number :param upper: Must be a numeric version number See ``svnadmin help ...
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L746-L776
null
class SvnRepo(VCSRepo): """A Subversion repository Unless otherwise specified, valid revisions are: - an integer (ex: 194) - an integer as a string (ex: "194") - a branch or tag name (ex: "HEAD", "trunk", "branches/branch1") - a branch or tag name at a specific revision (ex: "trunk:194") ...
ScottDuckworth/python-anyvcs
anyvcs/svn.py
SvnRepo.load
python
def load( self, stream, progress=None, ignore_uuid=False, force_uuid=False, use_pre_commit_hook=False, use_post_commit_hook=False, parent_dir=None ): cmd = [SVNADMIN, 'load', '.'] if progress is None: cmd.append('-q') if ignore_uuid: cmd.append('--igno...
Load a dumpfile stream into the repository. :param stream: A file stream from which the dumpfile is read :param progress: A file stream to which progress is written See ``svnadmin help load`` for details on the other arguments.
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L778-L811
null
class SvnRepo(VCSRepo): """A Subversion repository Unless otherwise specified, valid revisions are: - an integer (ex: 194) - an integer as a string (ex: "194") - a branch or tag name (ex: "HEAD", "trunk", "branches/branch1") - a branch or tag name at a specific revision (ex: "trunk:194") ...
ScottDuckworth/python-anyvcs
anyvcs/hg.py
HgRepo.clone
python
def clone(cls, srcpath, destpath): # Mercurial will not create intermediate directories for clones. try: os.makedirs(destpath) except OSError as e: if not e.errno == errno.EEXIST: raise cmd = [HG, 'clone', '--quiet', '--noupdate', srcpath, destpath...
Clone an existing repository to a new bare repository.
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/hg.py#L66-L76
null
class HgRepo(VCSRepo): """A Mercurial repository Valid revisions are anything that Mercurial considers as a revision. """ @classmethod @classmethod def create(cls, path): """Create a new repository""" cmd = [HG, 'init', path] subprocess.check_call(cmd) return...
ScottDuckworth/python-anyvcs
anyvcs/hg.py
HgRepo.create
python
def create(cls, path): cmd = [HG, 'init', path] subprocess.check_call(cmd) return cls(path)
Create a new repository
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/hg.py#L79-L83
null
class HgRepo(VCSRepo): """A Mercurial repository Valid revisions are anything that Mercurial considers as a revision. """ @classmethod def clone(cls, srcpath, destpath): """Clone an existing repository to a new bare repository.""" # Mercurial will not create intermediate directori...
ScottDuckworth/python-anyvcs
anyvcs/hg.py
HgRepo.private_path
python
def private_path(self): path = os.path.join(self.path, '.hg', '.private') try: os.mkdir(path) except OSError as e: if e.errno != errno.EEXIST: raise return path
Get the path to a directory which can be used to store arbitrary data This directory should not conflict with any of the repository internals. The directory should be created if it does not already exist.
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/hg.py#L86-L99
null
class HgRepo(VCSRepo): """A Mercurial repository Valid revisions are anything that Mercurial considers as a revision. """ @classmethod def clone(cls, srcpath, destpath): """Clone an existing repository to a new bare repository.""" # Mercurial will not create intermediate directori...
ScottDuckworth/python-anyvcs
anyvcs/hg.py
HgRepo.bookmarks
python
def bookmarks(self): cmd = [HG, 'bookmarks'] output = self._command(cmd).decode(self.encoding, 'replace') if output.startswith('no bookmarks set'): return [] results = [] for line in output.splitlines(): m = bookmarks_rx.match(line) assert m, '...
Get list of bookmarks
train
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/hg.py#L330-L341
[ "def _command(self, cmd, input=None, **kwargs):\n kwargs.setdefault('cwd', self.path)\n return command(cmd, **kwargs)\n" ]
class HgRepo(VCSRepo): """A Mercurial repository Valid revisions are anything that Mercurial considers as a revision. """ @classmethod def clone(cls, srcpath, destpath): """Clone an existing repository to a new bare repository.""" # Mercurial will not create intermediate directori...
brews/snakebacon
snakebacon/agedepth.py
AgeDepthModel.fit
python
def fit(self): self._mcmcfit = self.mcmcsetup.run() self._mcmcfit.burnin(self.burnin) dmin = min(self._mcmcfit.depth_segments) dmax = max(self._mcmcfit.depth_segments) self._thick = (dmax - dmin) / len(self.mcmcfit.depth_segments) self._depth = np.arange(dmin, dmax + 0.00...
Fit MCMC AgeDepthModel
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/agedepth.py#L64-L72
[ "def run(self):\n self.validate()\n return McmcResults(self)\n", "def burnin(self, n):\n \"\"\"Remove the earliest n ensemble members from the MCMC output\"\"\"\n self.sediment_rate = self.sediment_rate[:, n:]\n self.headage = self.headage[n:]\n self.sediment_memory = self.sediment_memory[n:]\n ...
class AgeDepthModel: def __init__(self, coredates, *, mcmc_kws, hold=False, burnin=200): self.burnin = int(burnin) self.mcmcsetup = McmcSetup(coredates, **mcmc_kws) self._mcmcfit = None self._thick = None self._depth = None self._age_ensemble = None if not hol...
brews/snakebacon
snakebacon/agedepth.py
AgeDepthModel.date
python
def date(self, proxy, how='median', n=500): assert how in ['median', 'ensemble'] ens_members = self.mcmcfit.n_members() if how == 'ensemble': select_idx = np.random.choice(range(ens_members), size=n, replace=True) out = [] for d in proxy.data.depth.values: ...
Date a proxy record Parameters ---------- proxy : ProxyRecord how : str How to perform the dating. 'median' returns the average of the MCMC ensemble. 'ensemble' returns a 'n' randomly selected members of the MCMC ensemble. Default is 'median'. n : int ...
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/agedepth.py#L74-L102
[ "def agedepth(self, d):\n \"\"\"Get calendar age for a depth\n\n Parameters\n ----------\n d : float\n Sediment depth (in cm).\n\n Returns\n -------\n Numeric giving true age at given depth.\n \"\"\"\n # TODO(brews): Function cannot handle hiatus\n # See lines 77 - 100 of hist2....
class AgeDepthModel: def __init__(self, coredates, *, mcmc_kws, hold=False, burnin=200): self.burnin = int(burnin) self.mcmcsetup = McmcSetup(coredates, **mcmc_kws) self._mcmcfit = None self._thick = None self._depth = None self._age_ensemble = None if not hol...
brews/snakebacon
snakebacon/agedepth.py
AgeDepthModel.plot
python
def plot(self, agebins=50, p=(2.5, 97.5), ax=None): if ax is None: ax = plt.gca() ax.hist2d(np.repeat(self.depth, self.age_ensemble.shape[1]), self.age_ensemble.flatten(), (len(self.depth), agebins), cmin=1) ax.step(self.depth, self.age_median(), where='mid', color...
Age-depth plot
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/agedepth.py#L104-L116
[ "def age_median(self):\n return np.median(self.age_ensemble, axis=1)\n", "def age_percentile(self, p):\n return np.percentile(self.age_ensemble, q=p, axis=1)\n" ]
class AgeDepthModel: def __init__(self, coredates, *, mcmc_kws, hold=False, burnin=200): self.burnin = int(burnin) self.mcmcsetup = McmcSetup(coredates, **mcmc_kws) self._mcmcfit = None self._thick = None self._depth = None self._age_ensemble = None if not hol...
brews/snakebacon
snakebacon/agedepth.py
AgeDepthModel.agedepth
python
def agedepth(self, d): # TODO(brews): Function cannot handle hiatus # See lines 77 - 100 of hist2.cpp x = self.mcmcfit.sediment_rate theta0 = self.mcmcfit.headage # Age abscissa (in yrs). If array, dimension should be iterations or realizations of the sediment deltac = self.thi...
Get calendar age for a depth Parameters ---------- d : float Sediment depth (in cm). Returns ------- Numeric giving true age at given depth.
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/agedepth.py#L118-L149
null
class AgeDepthModel: def __init__(self, coredates, *, mcmc_kws, hold=False, burnin=200): self.burnin = int(burnin) self.mcmcsetup = McmcSetup(coredates, **mcmc_kws) self._mcmcfit = None self._thick = None self._depth = None self._age_ensemble = None if not hol...
brews/snakebacon
snakebacon/agedepth.py
AgeDepthModel.plot_prior_dates
python
def plot_prior_dates(self, dwidth=30, ax=None): if ax is None: ax = plt.gca() depth, probs = self.prior_dates() pat = [] for i, d in enumerate(depth): p = probs[i] z = np.array([p[:, 0], dwidth * p[:, 1] / np.sum(p[:, 1])]) # Normalize z =...
Plot prior chronology dates in age-depth plot
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/agedepth.py#L154-L176
[ "def prior_dates(self):\n return self.mcmcsetup.prior_dates()\n" ]
class AgeDepthModel: def __init__(self, coredates, *, mcmc_kws, hold=False, burnin=200): self.burnin = int(burnin) self.mcmcsetup = McmcSetup(coredates, **mcmc_kws) self._mcmcfit = None self._thick = None self._depth = None self._age_ensemble = None if not hol...
brews/snakebacon
snakebacon/agedepth.py
AgeDepthModel.plot_sediment_rate
python
def plot_sediment_rate(self, ax=None): if ax is None: ax = plt.gca() y_prior, x_prior = self.prior_sediment_rate() ax.plot(x_prior, y_prior, label='Prior') y_posterior = self.mcmcfit.sediment_rate density = scipy.stats.gaussian_kde(y_posterior.flat) density....
Plot sediment accumulation rate prior and posterior distributions
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/agedepth.py#L181-L205
[ "def prior_sediment_rate(self):\n return self.mcmcsetup.prior_sediment_rate()\n" ]
class AgeDepthModel: def __init__(self, coredates, *, mcmc_kws, hold=False, burnin=200): self.burnin = int(burnin) self.mcmcsetup = McmcSetup(coredates, **mcmc_kws) self._mcmcfit = None self._thick = None self._depth = None self._age_ensemble = None if not hol...
brews/snakebacon
snakebacon/agedepth.py
AgeDepthModel.plot_sediment_memory
python
def plot_sediment_memory(self, ax=None): if ax is None: ax = plt.gca() y_prior, x_prior = self.prior_sediment_memory() ax.plot(x_prior, y_prior, label='Prior') y_posterior = self.mcmcfit.sediment_memory density = scipy.stats.gaussian_kde(y_posterior ** (1/self.thick...
Plot sediment memory prior and posterior distributions
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/agedepth.py#L210-L234
[ "def prior_sediment_memory(self):\n return self.mcmcsetup.prior_sediment_memory()\n" ]
class AgeDepthModel: def __init__(self, coredates, *, mcmc_kws, hold=False, burnin=200): self.burnin = int(burnin) self.mcmcsetup = McmcSetup(coredates, **mcmc_kws) self._mcmcfit = None self._thick = None self._depth = None self._age_ensemble = None if not hol...
brews/snakebacon
snakebacon/records.py
read_14c
python
def read_14c(fl): indata = pd.read_csv(fl, index_col=None, skiprows=11, header=None, names=['calbp', 'c14age', 'error', 'delta14c', 'sigma']) outcurve = CalibCurve(calbp=indata['calbp'], c14age=indata['c14age'], error=indata['error'], ...
Create CalibCurve instance from Bacon curve file
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/records.py#L14-L24
null
import logging import matplotlib.pylab as plt import numpy as np import pandas as pd import scipy.stats as stats from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon log = logging.getLogger(__name__) def read_chron(fl): """Create ChronRecord instance from Bacon file ""...
brews/snakebacon
snakebacon/records.py
read_chron
python
def read_chron(fl): indata = pd.read_csv(fl, sep=r'\s*\,\s*', index_col=None, engine='python') outcore = ChronRecord(age=indata['age'], error=indata['error'], depth=indata['depth'], labid=indata['labID']) return outcore
Create ChronRecord instance from Bacon file
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/records.py#L27-L35
null
import logging import matplotlib.pylab as plt import numpy as np import pandas as pd import scipy.stats as stats from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon log = logging.getLogger(__name__) def read_14c(fl): """Create CalibCurve instance from Bacon curve file ...
brews/snakebacon
snakebacon/records.py
read_proxy
python
def read_proxy(fl): outcore = ProxyRecord(data=pd.read_csv(fl, sep=r'\s*\,\s*', index_col=None, engine='python')) return outcore
Read a file to create a proxy record instance
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/records.py#L38-L42
null
import logging import matplotlib.pylab as plt import numpy as np import pandas as pd import scipy.stats as stats from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon log = logging.getLogger(__name__) def read_14c(fl): """Create CalibCurve instance from Bacon curve file ...
brews/snakebacon
snakebacon/records.py
DatedProxyRecord.to_pandas
python
def to_pandas(self): agedepthdf = pd.DataFrame(self.age, index=self.data.depth) agedepthdf.columns = list(range(self.n_members())) out = (agedepthdf.join(self.data.set_index('depth')) .reset_index() .melt(id_vars=self.data.columns.values, var_name='mciter', value_na...
Convert record to pandas.DataFrame
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/records.py#L89-L99
[ "def n_members(self):\n \"\"\"Get number of MCMC ensemble members in calendar age estimates\"\"\"\n try:\n n = len(self.age[0])\n except TypeError:\n n = 1\n return n\n" ]
class DatedProxyRecord(ProxyRecord): def __init__(self, data, age): """Create a dated proxy record instance Parameters ---------- data : DataFrame Pandas dataframe containing columns with proxy sample measurements. Must also have 'depth' column. age : iterable ...
brews/snakebacon
snakebacon/mcmc.py
McmcResults.burnin
python
def burnin(self, n): self.sediment_rate = self.sediment_rate[:, n:] self.headage = self.headage[n:] self.sediment_memory = self.sediment_memory[n:] self.objective = self.objective[n:]
Remove the earliest n ensemble members from the MCMC output
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/mcmc.py#L54-L59
null
class McmcResults: def __init__(self, setup): mcmcout = setup.mcmcbackend.runmcmc(core_labid=setup.coredates.labid, core_age=setup.coredates.age, core_error=setup.coredates.error, ...
brews/snakebacon
snakebacon/mcmcbackends/__init__.py
Bacon.prior_dates
python
def prior_dates(*args, **kwargs): try: chron = args[0] except IndexError: chron = kwargs['coredates'] d_r = np.array(kwargs['d_r']) d_std = np.array(kwargs['d_std']) t_a = np.array(kwargs['t_a']) t_b = np.array(kwargs['t_b']) try: ...
Get the prior distribution of calibrated radiocarbon dates
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/mcmcbackends/__init__.py#L11-L49
[ "def fetch_calibcurve(curvename):\n \"\"\"Get CalibCurve from name string\"\"\"\n f = available_curves[curvename]\n return f()\n", "def calibrate_dates(chron, calib_curve, d_r, d_std, cutoff=0.0001, normal_distr=False, t_a=[3], t_b=[4]):\n \"\"\"Get density of calendar dates for chron date segment in ...
class Bacon: def runmcmc(*args, **kwargs): return run_baconmcmc(*args, **kwargs) def prior_sediment_rate(*args, **kwargs): """Get the prior density of sediment rates Returns ------- y : ndarray Array giving the density. x : ndarray Arra...
brews/snakebacon
snakebacon/mcmcbackends/__init__.py
Bacon.prior_sediment_rate
python
def prior_sediment_rate(*args, **kwargs): # PlotAccPrior @ Bacon.R ln 113 -> ln 1097-1115 # alpha = acc_shape, beta = acc_shape / acc_mean # TODO(brews): Check that these stats are correctly translated to scipy.stats distribs. acc_mean = kwargs['acc_mean'] acc_shape = kwargs['acc...
Get the prior density of sediment rates Returns ------- y : ndarray Array giving the density. x : ndarray Array of sediment accumulation values (yr/cm) over which the density was evaluated.
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/mcmcbackends/__init__.py#L52-L70
null
class Bacon: def runmcmc(*args, **kwargs): return run_baconmcmc(*args, **kwargs) def prior_dates(*args, **kwargs): """Get the prior distribution of calibrated radiocarbon dates""" try: chron = args[0] except IndexError: chron = kwargs['coredates'] ...
brews/snakebacon
snakebacon/mcmcbackends/__init__.py
Bacon.prior_sediment_memory
python
def prior_sediment_memory(*args, **kwargs): # "plot the prior for the memory (= accumulation rate varibility between neighbouring depths)" # PlotMemPrior @ Bacon.R ln 114 -> ln 1119 - 1141 # w_a = mem_strength * mem_mean, w_b = mem_strength * (1 - mem_mean) # TODO(brews): Check that thes...
Get the prior density of sediment memory Returns ------- y : ndarray Array giving the density. x : ndarray Array of Memory (ratio) values over which the density was evaluated.
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/mcmcbackends/__init__.py#L73-L92
null
class Bacon: def runmcmc(*args, **kwargs): return run_baconmcmc(*args, **kwargs) def prior_dates(*args, **kwargs): """Get the prior distribution of calibrated radiocarbon dates""" try: chron = args[0] except IndexError: chron = kwargs['coredates'] ...
brews/snakebacon
snakebacon/mcmcbackends/bacon/utils.py
d_cal
python
def d_cal(calibcurve, rcmean, w2, cutoff=0.0001, normal_distr=False, t_a=3, t_b=4): assert t_b - 1 == t_a if normal_distr: # TODO(brews): Test this. Line 946 of Bacon.R. std = np.sqrt(calibcurve.error ** 2 + w2) dens = stats.norm(loc=rcmean, scale=std).pdf(calibcurve.c14age) else: ...
Get calendar date probabilities Parameters ---------- calibcurve : CalibCurve Calibration curve. rcmean : scalar Reservoir-adjusted age. w2 : scalar r'$w^2_j(\theta)$' from pg 461 & 463 of Blaauw and Christen 2011. cutoff : scalar, optional Unknown. normal_di...
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/mcmcbackends/bacon/utils.py#L5-L49
null
import numpy as np import scipy.stats as stats def calibrate_dates(chron, calib_curve, d_r, d_std, cutoff=0.0001, normal_distr=False, t_a=[3], t_b=[4]): """Get density of calendar dates for chron date segment in core Parameters ---------- chron : DatedProxy-like calib_curve : CalibCurve or list ...
brews/snakebacon
snakebacon/mcmcbackends/bacon/utils.py
calibrate_dates
python
def calibrate_dates(chron, calib_curve, d_r, d_std, cutoff=0.0001, normal_distr=False, t_a=[3], t_b=[4]): # Python version of .bacon.calib() on line 908 in Bacon.R # .bacon.calib - line 908 # rcmean = 4128; w2 = 4225; t_a=3; t_b=4 # test = d_cal(cc = calib_curve.rename(columns = {0:'a', 1:'b', 2:'c'})...
Get density of calendar dates for chron date segment in core Parameters ---------- chron : DatedProxy-like calib_curve : CalibCurve or list of CalibCurves d_r : scalar or ndarray Carbon reservoir offset. d_std : scalar or ndarray Carbon reservoir offset error standard deviation....
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/mcmcbackends/bacon/utils.py#L52-L123
[ "def d_cal(calibcurve, rcmean, w2, cutoff=0.0001, normal_distr=False, t_a=3, t_b=4):\n \"\"\"Get calendar date probabilities\n\n Parameters\n ----------\n calibcurve : CalibCurve\n Calibration curve.\n rcmean : scalar\n Reservoir-adjusted age.\n w2 : scalar\n r'$w^2_j(\\theta)...
import numpy as np import scipy.stats as stats def d_cal(calibcurve, rcmean, w2, cutoff=0.0001, normal_distr=False, t_a=3, t_b=4): """Get calendar date probabilities Parameters ---------- calibcurve : CalibCurve Calibration curve. rcmean : scalar Reservoir-adjusted age. w2 : s...
brews/snakebacon
snakebacon/utils.py
suggest_accumulation_rate
python
def suggest_accumulation_rate(chron): # Follow's Bacon's method @ Bacon.R ln 30 - 44 # Suggested round vals. sugg = np.tile([1, 2, 5], (4, 1)) * np.reshape(np.repeat([0.1, 1.0, 10, 100], 3), (4, 3)) # Get ballpark accumulation rates, uncalibrated dates. ballpacc = stats.linregress(x=chron.depth, y=c...
From core age-depth data, suggest mean accumulation rate (cm/y)
train
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/utils.py#L5-L15
null
import numpy as np import scipy.stats as stats
greenape/mktheapidocs
mktheapidocs/mkapi.py
get_line
python
def get_line(thing): try: return inspect.getsourcelines(thing)[1] except TypeError: # Might be a property return inspect.getsourcelines(thing.fget)[1] except Exception as e: # print(thing) raise e
Get the line number for something. Parameters ---------- thing : function, class, module Returns ------- int Line number in the source file
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L6-L25
null
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def _sort_modules(mods): """ Always sort `index` or `README` as first filename in list. """ def compare(x, y): x = x[1] y = y[1...
greenape/mktheapidocs
mktheapidocs/mkapi.py
_sort_modules
python
def _sort_modules(mods): def compare(x, y): x = x[1] y = y[1] if x == y: return 0 if y.stem == "__init__.py": return 1 if x.stem == "__init__.py" or x < y: return -1 return 1 return sorted(mods, key=cmp_to_key(compare))
Always sort `index` or `README` as first filename in list.
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L28-L42
null
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
refs_section
python
def refs_section(doc): lines = [] if "References" in doc and len(doc["References"]) > 0: # print("Found refs") for ref in doc["References"]: # print(ref) ref_num = re.findall("\[([0-9]+)\]", ref)[0] # print(ref_num) ref_body = " ".join(ref.split(" ...
Generate a References section. Parameters ---------- doc : dict Dictionary produced by numpydoc Returns ------- list of str Markdown for references section
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L231-L256
null
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
examples_section
python
def examples_section(doc, header_level): lines = [] if "Examples" in doc and len(doc["Examples"]) > 0: lines.append(f"{'#'*(header_level+1)} Examples \n") egs = "\n".join(doc["Examples"]) lines += mangle_examples(doc["Examples"]) return lines
Generate markdown for Examples section. Parameters ---------- doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples section
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L259-L280
[ "def mangle_examples(examples):\n was_in_python = False\n in_python = False\n lines = []\n for line in examples:\n if line.startswith(\">>>\"):\n in_python = True\n if line == \"\":\n in_python = False\n if not in_python and was_in_python:\n lines.ap...
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
returns_section
python
def returns_section(thing, doc, header_level): lines = [] return_type = None try: return_type = thing.__annotations__["return"] except AttributeError: try: return_type = thing.fget.__annotations__["return"] except: pass except KeyError: pass ...
Generate markdown for Returns section. Parameters ---------- thing : function Function to produce returns for doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples section
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L283-L357
[ "def mangle_types(types):\n default = re.findall(\"default .+\", types)\n mangled = []\n try:\n if len(default):\n default = re.sub(\"default (.+)\", r\"default ``\\1``\", default[0])\n mangled.append(default)\n types = re.sub(\"default .+\", \"\", types)\n curlie...
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
summary
python
def summary(doc): lines = [] if "Summary" in doc and len(doc["Summary"]) > 0: lines.append(fix_footnotes(" ".join(doc["Summary"]))) lines.append("\n") if "Extended Summary" in doc and len(doc["Extended Summary"]) > 0: lines.append(fix_footnotes(" ".join(doc["Extended Summary"]))) ...
Generate markdown for summary section. Parameters ---------- doc : dict Output from numpydoc Returns ------- list of str Markdown strings
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L360-L381
[ "def fix_footnotes(s):\n return re.subn(\"\\[([0-9]+)\\]_\", r\"[^\\1]\", s)[0]\n" ]
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
params_section
python
def params_section(thing, doc, header_level): lines = [] class_doc = doc["Parameters"] return type_list( inspect.signature(thing), class_doc, "#" * (header_level + 1) + " Parameters\n\n", )
Generate markdown for Parameters section. Parameters ---------- thing : functuon Function to produce parameters from doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples secti...
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L384-L409
[ "def type_list(signature, doc, header):\n \"\"\"\n Construct a list of types, preferring type annotations to\n docstrings if they are available.\n\n Parameters\n ----------\n signature : Signature\n Signature of thing\n doc : list of tuple\n Numpydoc's type list section\n\n Ret...
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
get_source_link
python
def get_source_link(thing, source_location): try: lineno = get_line(thing) try: owner_module = inspect.getmodule(thing) assert owner_module is not None except (TypeError, AssertionError): owner_module = inspect.getmodule(thing.fget) thing_file = "...
Get a link to the line number a module/class/function is defined at. Parameters ---------- thing : function or class Thing to get the link for source_location : str GitHub url of the source code Returns ------- str String with link to the file & line number, or empt...
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L429-L472
[ "def escape(string):\n \"\"\"\n Escape underscores in markdown.\n\n Parameters\n ----------\n string : str\n String to escape\n\n Returns\n -------\n str\n The string, with `_`s escaped with backslashes\n \"\"\"\n return string.replace(\"_\", \"\\\\_\")\n", "def get_lin...
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
get_signature
python
def get_signature(name, thing): if inspect.ismodule(thing): return "" if isinstance(thing, property): func_sig = name else: try: sig = inspect.signature(thing) except TypeError: sig = inspect.signature(thing.fget) except ValueError: ...
Get the signature for a function or class, formatted nicely if possible. Parameters ---------- name : str Name of the thing, used as the first part of the signature thing : class or function Thing to get the signature of
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L475-L503
null
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
_get_names
python
def _get_names(names, types): if types == "": try: names, types = names.split(":") except: pass return names.split(","), types
Get names, bearing in mind that there might be no name, no type, and that the `:` separator might be wrongly used.
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L506-L516
null
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
string_annotation
python
def string_annotation(typ, default): try: type_string = ( f"`{typ.__name__}`" if typ.__module__ == "builtins" else f"`{typ.__module__}.{typ.__name__}`" ) except AttributeError: type_string = f"`{str(typ)}`" if default is None: type_string =...
Construct a string representation of a type annotation. Parameters ---------- typ : type Type to turn into a string default : any Default value (if any) of the type Returns ------- str String version of the type annotation
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L519-L549
null
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
type_list
python
def type_list(signature, doc, header): lines = [] docced = set() lines.append(header) try: for names, types, description in doc: names, types = _get_names(names, types) unannotated = [] for name in names: docced.add(name) try: ...
Construct a list of types, preferring type annotations to docstrings if they are available. Parameters ---------- signature : Signature Signature of thing doc : list of tuple Numpydoc's type list section Returns ------- list of str Markdown formatted type list
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L552-L612
[ "def mangle_types(types):\n default = re.findall(\"default .+\", types)\n mangled = []\n try:\n if len(default):\n default = re.sub(\"default (.+)\", r\"default ``\\1``\", default[0])\n mangled.append(default)\n types = re.sub(\"default .+\", \"\", types)\n curlie...
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
_split_props
python
def _split_props(thing, doc): props = inspect.getmembers(thing, lambda o: isinstance(o, property)) ps = [] docs = [ (*_get_names(names, types), names, types, desc) for names, types, desc in doc ] for prop_name, prop in props: in_doc = [d for d in enumerate(docs) if prop_name in d[0]]...
Separate properties from other kinds of member.
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L615-L632
null
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
attributes_section
python
def attributes_section(thing, doc, header_level): # Get Attributes if not inspect.isclass(thing): return [] props, class_doc = _split_props(thing, doc["Attributes"]) tl = type_list(inspect.signature(thing), class_doc, "\n### Attributes\n\n") if len(tl) == 0 and len(props) > 0: tl.a...
Generate an attributes section for classes. Prefers type annotations, if they are present. Parameters ---------- thing : class Class to document doc : dict Numpydoc output header_level : int Number of `#`s to use for header Returns ------- list of str ...
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L635-L666
[ "def type_list(signature, doc, header):\n \"\"\"\n Construct a list of types, preferring type annotations to\n docstrings if they are available.\n\n Parameters\n ----------\n signature : Signature\n Signature of thing\n doc : list of tuple\n Numpydoc's type list section\n\n Ret...
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
enum_doc
python
def enum_doc(name, enum, header_level, source_location): lines = [f"{'#'*header_level} Enum **{name}**\n\n"] lines.append(f"```python\n{name}\n```\n") lines.append(get_source_link(enum, source_location)) try: doc = NumpyDocString(inspect.getdoc(thing))._parsed_data lines += summary(doc)...
Generate markdown for an enum Parameters ---------- name : str Name of the thing being documented enum : EnumMeta Enum to document header_level : int Heading level source_location : str URL of repo containing source code
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L669-L695
[ "def summary(doc):\n \"\"\"\n Generate markdown for summary section.\n\n Parameters\n ----------\n doc : dict\n Output from numpydoc\n\n Returns\n -------\n list of str\n Markdown strings\n \"\"\"\n lines = []\n if \"Summary\" in doc and len(doc[\"Summary\"]) > 0:\n ...
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
to_doc
python
def to_doc(name, thing, header_level, source_location): if type(thing) is enum.EnumMeta: return enum_doc(name, thing, header_level, source_location) if inspect.isclass(thing): header = f"{'#'*header_level} Class **{name}**\n\n" else: header = f"{'#'*header_level} {name}\n\n" lin...
Generate markdown for a class or function Parameters ---------- name : str Name of the thing being documented thing : class or function Class or function to document header_level : int Heading level source_location : str URL of repo containing source code
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L698-L738
[ "def summary(doc):\n \"\"\"\n Generate markdown for summary section.\n\n Parameters\n ----------\n doc : dict\n Output from numpydoc\n\n Returns\n -------\n list of str\n Markdown strings\n \"\"\"\n lines = []\n if \"Summary\" in doc and len(doc[\"Summary\"]) > 0:\n ...
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/mkapi.py
doc_module
python
def doc_module(module_name, module, output_dir, source_location, leaf): path = pathlib.Path(output_dir).joinpath(*module.__name__.split(".")) available_classes = get_available_classes(module) deffed_classes = get_classes(module) deffed_funcs = get_funcs(module) deffed_enums = get_enums(module) a...
Document a module Parameters ---------- module_name : str module : module output_dir : str source_location : str leaf : bool
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/mkapi.py#L741-L789
[ "def get_classes(module):\n return set(\n [\n x\n for x in inspect.getmembers(module, inspect.isclass)\n if (not x[0].startswith(\"_\"))\n and x[1].__module__ == module.__name__\n and not type(x[1]) is enum.EnumMeta\n ]\n )\n", "def get_en...
import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns --...
greenape/mktheapidocs
mktheapidocs/plugin.py
PyDocFile._get_stem
python
def _get_stem(self): filename = os.path.basename(self.src_path) stem, ext = os.path.splitext(filename) return "index" if stem in ("index", "README", "__init__") else stem
Return the name of the file without it's extension.
train
https://github.com/greenape/mktheapidocs/blob/a45e8b43ddd80ed360fe1e98d4f73dc11c4e7bf7/mktheapidocs/plugin.py#L21-L25
null
class PyDocFile(mkdocs.structure.files.File): def __init__(self, path, src_dir, dest_dir, use_directory_urls, parent): self.parent = parent super().__init__(path, src_dir, dest_dir, use_directory_urls) self.abs_src_path = self.parent def is_documentation_page(self): return True ...
thetarkus/django-semanticui-forms
semanticuiforms/templatetags/semanticui.py
render_form
python
def render_form(form, exclude=None, **kwargs): """Render an entire form with Semantic UI wrappers for each field Args: form (form): Django Form exclude (string): exclude fields by name, separated by commas kwargs (dict): other attributes will be passed to fields Returns: string: HTML of Django F...
Render an entire form with Semantic UI wrappers for each field Args: form (form): Django Form exclude (string): exclude fields by name, separated by commas kwargs (dict): other attributes will be passed to fields Returns: string: HTML of Django Form fields with Semantic UI wrappers
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/templatetags/semanticui.py#L153-L174
null
from django import template from django.utils.html import format_html, escape from django.utils.safestring import mark_safe from ..wrappers import * from ..utils import pad from ..fields import FIELDS register = template.Library() class Field(): """ Semantic UI Form Field. """ def __init__(self, field, **kwarg...
thetarkus/django-semanticui-forms
semanticuiforms/templatetags/semanticui.py
render_layout_form
python
def render_layout_form(form, layout=None, **kwargs): """Render an entire form with Semantic UI wrappers for each field with a layout provided in the template or in the form class Args: form (form): Django Form layout (tuple): layout design kwargs (dict): other attributes will be passed to fields ...
Render an entire form with Semantic UI wrappers for each field with a layout provided in the template or in the form class Args: form (form): Django Form layout (tuple): layout design kwargs (dict): other attributes will be passed to fields Returns: string: HTML of Django Form fields with Semant...
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/templatetags/semanticui.py#L178-L214
null
from django import template from django.utils.html import format_html, escape from django.utils.safestring import mark_safe from ..wrappers import * from ..utils import pad from ..fields import FIELDS register = template.Library() class Field(): """ Semantic UI Form Field. """ def __init__(self, field, **kwarg...
thetarkus/django-semanticui-forms
semanticuiforms/templatetags/semanticui.py
Field.set_input
python
def set_input(self): """Returns form input field of Field. """ name = self.attrs.get("_override", self.widget.__class__.__name__) self.values["field"] = str(FIELDS.get(name, FIELDS.get(None))(self.field, self.attrs))
Returns form input field of Field.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/templatetags/semanticui.py#L36-L40
null
class Field(): """ Semantic UI Form Field. """ def __init__(self, field, **kwargs): """Initializer for Field class. Args: field (BoundField): Form field **kwargs (dict): Field attributes """ # Kwargs will always be additional attributes self.attrs = kwargs self.attrs.update(field.field.widget.att...
thetarkus/django-semanticui-forms
semanticuiforms/templatetags/semanticui.py
Field.set_label
python
def set_label(self): """Set label markup. """ if not self.field.label or self.attrs.get("_no_label"): return self.values["label"] = format_html( LABEL_TEMPLATE, self.field.html_name, mark_safe(self.field.label) )
Set label markup.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/templatetags/semanticui.py#L43-L51
null
class Field(): """ Semantic UI Form Field. """ def __init__(self, field, **kwargs): """Initializer for Field class. Args: field (BoundField): Form field **kwargs (dict): Field attributes """ # Kwargs will always be additional attributes self.attrs = kwargs self.attrs.update(field.field.widget.att...
thetarkus/django-semanticui-forms
semanticuiforms/templatetags/semanticui.py
Field.set_help
python
def set_help(self): """Set help text markup. """ if not (self.field.help_text and self.attrs.get("_help")): return self.values["help"] = HELP_TEMPLATE.format(self.field.help_text)
Set help text markup.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/templatetags/semanticui.py#L54-L60
null
class Field(): """ Semantic UI Form Field. """ def __init__(self, field, **kwargs): """Initializer for Field class. Args: field (BoundField): Form field **kwargs (dict): Field attributes """ # Kwargs will always be additional attributes self.attrs = kwargs self.attrs.update(field.field.widget.att...
thetarkus/django-semanticui-forms
semanticuiforms/templatetags/semanticui.py
Field.set_errors
python
def set_errors(self): """Set errors markup. """ if not self.field.errors or self.attrs.get("_no_errors"): return self.values["class"].append("error") for error in self.field.errors: self.values["errors"] += ERROR_WRAPPER % {"message": error}
Set errors markup.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/templatetags/semanticui.py#L63-L72
null
class Field(): """ Semantic UI Form Field. """ def __init__(self, field, **kwargs): """Initializer for Field class. Args: field (BoundField): Form field **kwargs (dict): Field attributes """ # Kwargs will always be additional attributes self.attrs = kwargs self.attrs.update(field.field.widget.att...
thetarkus/django-semanticui-forms
semanticuiforms/templatetags/semanticui.py
Field.set_icon
python
def set_icon(self): """Wrap current field with icon wrapper. This setter must be the last setter called. """ if not self.attrs.get("_icon"): return if "Date" in self.field.field.__class__.__name__: return self.values["field"] = INPUT_WRAPPER % { "field": self.values["field"], "help...
Wrap current field with icon wrapper. This setter must be the last setter called.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/templatetags/semanticui.py#L75-L90
[ "def pad(value):\n\t\"\"\"\n\tAdd one space padding around value if value is valid.\n\n\tArgs:\n\t\tvalue (string): Value\n\n\tReturns:\n\t\tstring: Value with padding if value was valid else one space\n\t\"\"\"\n\treturn \" %s \" % value if value else \" \"\n" ]
class Field(): """ Semantic UI Form Field. """ def __init__(self, field, **kwargs): """Initializer for Field class. Args: field (BoundField): Form field **kwargs (dict): Field attributes """ # Kwargs will always be additional attributes self.attrs = kwargs self.attrs.update(field.field.widget.att...
thetarkus/django-semanticui-forms
semanticuiforms/templatetags/semanticui.py
Field.set_classes
python
def set_classes(self): """Set field properties and custom classes. """ # Custom field classes on field wrapper if self.attrs.get("_field_class"): self.values["class"].append(escape(self.attrs.get("_field_class"))) # Inline class if self.attrs.get("_inline"): self.values["class"].append("inli...
Set field properties and custom classes.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/templatetags/semanticui.py#L93-L112
null
class Field(): """ Semantic UI Form Field. """ def __init__(self, field, **kwargs): """Initializer for Field class. Args: field (BoundField): Form field **kwargs (dict): Field attributes """ # Kwargs will always be additional attributes self.attrs = kwargs self.attrs.update(field.field.widget.att...
thetarkus/django-semanticui-forms
semanticuiforms/templatetags/semanticui.py
Field.render
python
def render(self): """Render field as HTML. """ self.widget.attrs = { k: v for k, v in self.attrs.items() if k[0] != "_" } self.set_input() if not self.attrs.get("_no_wrapper"): self.set_label() self.set_help() self.set_errors() self.set_classes() self.set_icon() # Must be th...
Render field as HTML.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/templatetags/semanticui.py#L115-L133
[ "def pad(value):\n\t\"\"\"\n\tAdd one space padding around value if value is valid.\n\n\tArgs:\n\t\tvalue (string): Value\n\n\tReturns:\n\t\tstring: Value with padding if value was valid else one space\n\t\"\"\"\n\treturn \" %s \" % value if value else \" \"\n", "def set_input(self):\n\t\"\"\"Returns form input f...
class Field(): """ Semantic UI Form Field. """ def __init__(self, field, **kwargs): """Initializer for Field class. Args: field (BoundField): Form field **kwargs (dict): Field attributes """ # Kwargs will always be additional attributes self.attrs = kwargs self.attrs.update(field.field.widget.att...
thetarkus/django-semanticui-forms
example/app/apps.py
ExampleAppConfig.ready
python
def ready(self): from .models import Friend # Requires migrations, not necessary try: Friend.objects.get_or_create(first_name="Michael", last_name="1", age=22) Friend.objects.get_or_create(first_name="Joe", last_name="2", age=21) Friend.objects.get_or_create(first_name="Bill", last_name="3", age=20) e...
Create test friends for displaying.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/example/app/apps.py#L12-L24
null
class ExampleAppConfig(AppConfig): """ App config for the Example App. """ name = "app"
thetarkus/django-semanticui-forms
semanticuiforms/fields.py
render_booleanfield
python
def render_booleanfield(field, attrs): attrs.setdefault("_no_label", True) # No normal label for booleanfields attrs.setdefault("_inline", True) # Checkbox should be inline field.field.widget.attrs["style"] = "display:hidden" # Hidden field return wrappers.CHECKBOX_WRAPPER % { "style": pad(attrs.get("_style",...
Render BooleanField with label next to instead of above.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/fields.py#L33-L47
[ "def pad(value):\n\t\"\"\"\n\tAdd one space padding around value if value is valid.\n\n\tArgs:\n\t\tvalue (string): Value\n\n\tReturns:\n\t\tstring: Value with padding if value was valid else one space\n\t\"\"\"\n\treturn \" %s \" % value if value else \" \"\n" ]
from django.utils.html import format_html, format_html_join, escape from django.utils.safestring import mark_safe from django.forms.utils import flatatt from . import wrappers from .utils import pad, get_choices, get_placeholder_text def render_charfield(field, attrs): """ Render the generic CharField. """ retur...
thetarkus/django-semanticui-forms
semanticuiforms/fields.py
render_choicefield
python
def render_choicefield(field, attrs, choices=None): # Allow custom choice list, but if no custom choice list then wrap all # choices into the `wrappers.CHOICE_TEMPLATE` if not choices: choices = format_html_join("", wrappers.CHOICE_TEMPLATE, get_choices(field)) # Accessing the widget attrs directly saves them fo...
Render ChoiceField as 'div' dropdown rather than select for more customization.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/fields.py#L50-L71
[ "def pad(value):\n\t\"\"\"\n\tAdd one space padding around value if value is valid.\n\n\tArgs:\n\t\tvalue (string): Value\n\n\tReturns:\n\t\tstring: Value with padding if value was valid else one space\n\t\"\"\"\n\treturn \" %s \" % value if value else \" \"\n", "def get_choices(field):\n\t\"\"\"\n\tFind choices ...
from django.utils.html import format_html, format_html_join, escape from django.utils.safestring import mark_safe from django.forms.utils import flatatt from . import wrappers from .utils import pad, get_choices, get_placeholder_text def render_charfield(field, attrs): """ Render the generic CharField. """ retur...
thetarkus/django-semanticui-forms
semanticuiforms/fields.py
render_iconchoicefield
python
def render_iconchoicefield(field, attrs): choices = "" # Loop over every choice to manipulate for choice in field.field._choices: value = choice[1].split("|") # Value|Icon # Each choice is formatted with the choice value being split with # the "|" as the delimeter. First element is the value, the second #...
Render a ChoiceField with icon support; where the value is split by a pipe (|): first element being the value, last element is the icon.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/fields.py#L74-L96
[ "def render_choicefield(field, attrs, choices=None):\n\t\"\"\"\n\tRender ChoiceField as 'div' dropdown rather than select for more\n\tcustomization.\n\t\"\"\"\n\t# Allow custom choice list, but if no custom choice list then wrap all\n\t# choices into the `wrappers.CHOICE_TEMPLATE`\n\tif not choices:\n\t\tchoices = ...
from django.utils.html import format_html, format_html_join, escape from django.utils.safestring import mark_safe from django.forms.utils import flatatt from . import wrappers from .utils import pad, get_choices, get_placeholder_text def render_charfield(field, attrs): """ Render the generic CharField. """ retur...
thetarkus/django-semanticui-forms
semanticuiforms/fields.py
render_countryfield
python
def render_countryfield(field, attrs): choices = ((k, k.lower(), v) for k, v in field.field._choices[1:]) # Render a `ChoiceField` with all countries return render_choicefield( field, attrs, format_html_join("", wrappers.COUNTRY_TEMPLATE, choices) )
Render a custom ChoiceField specific for CountryFields.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/fields.py#L99-L109
[ "def render_choicefield(field, attrs, choices=None):\n\t\"\"\"\n\tRender ChoiceField as 'div' dropdown rather than select for more\n\tcustomization.\n\t\"\"\"\n\t# Allow custom choice list, but if no custom choice list then wrap all\n\t# choices into the `wrappers.CHOICE_TEMPLATE`\n\tif not choices:\n\t\tchoices = ...
from django.utils.html import format_html, format_html_join, escape from django.utils.safestring import mark_safe from django.forms.utils import flatatt from . import wrappers from .utils import pad, get_choices, get_placeholder_text def render_charfield(field, attrs): """ Render the generic CharField. """ retur...
thetarkus/django-semanticui-forms
semanticuiforms/fields.py
render_multiplechoicefield
python
def render_multiplechoicefield(field, attrs, choices=None): choices = format_html_join("", wrappers.CHOICE_TEMPLATE, get_choices(field)) return wrappers.MULTIPLE_DROPDOWN_WRAPPER % { "name": field.html_name, "field": field, "choices": choices, "placeholder": attrs.get("placeholder") or get_placeholder_text(),...
MultipleChoiceField uses its own field, but also uses a queryset.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/fields.py#L112-L124
[ "def pad(value):\n\t\"\"\"\n\tAdd one space padding around value if value is valid.\n\n\tArgs:\n\t\tvalue (string): Value\n\n\tReturns:\n\t\tstring: Value with padding if value was valid else one space\n\t\"\"\"\n\treturn \" %s \" % value if value else \" \"\n", "def get_choices(field):\n\t\"\"\"\n\tFind choices ...
from django.utils.html import format_html, format_html_join, escape from django.utils.safestring import mark_safe from django.forms.utils import flatatt from . import wrappers from .utils import pad, get_choices, get_placeholder_text def render_charfield(field, attrs): """ Render the generic CharField. """ retur...
thetarkus/django-semanticui-forms
semanticuiforms/fields.py
render_datefield
python
def render_datefield(field, attrs, style="date"): return wrappers.CALENDAR_WRAPPER % { "field": field, "style": pad(style), "align": pad(attrs.get("_align", "")), "icon": format_html(wrappers.ICON_TEMPLATE, attrs.get("_icon")), }
DateField that uses wrappers.CALENDAR_WRAPPER.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/fields.py#L127-L136
[ "def pad(value):\n\t\"\"\"\n\tAdd one space padding around value if value is valid.\n\n\tArgs:\n\t\tvalue (string): Value\n\n\tReturns:\n\t\tstring: Value with padding if value was valid else one space\n\t\"\"\"\n\treturn \" %s \" % value if value else \" \"\n" ]
from django.utils.html import format_html, format_html_join, escape from django.utils.safestring import mark_safe from django.forms.utils import flatatt from . import wrappers from .utils import pad, get_choices, get_placeholder_text def render_charfield(field, attrs): """ Render the generic CharField. """ retur...
thetarkus/django-semanticui-forms
semanticuiforms/fields.py
render_filefield
python
def render_filefield(field, attrs): field.field.widget.attrs["style"] = "display:none" if not "_no_label" in attrs: attrs["_no_label"] = True return wrappers.FILE_WRAPPER % { "field": field, "id": "id_" + field.name, "style": pad(attrs.get("_style", "")), "text": escape(attrs.get("_text", "Select File"))...
Render a typical File Field.
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/fields.py#L153-L168
[ "def pad(value):\n\t\"\"\"\n\tAdd one space padding around value if value is valid.\n\n\tArgs:\n\t\tvalue (string): Value\n\n\tReturns:\n\t\tstring: Value with padding if value was valid else one space\n\t\"\"\"\n\treturn \" %s \" % value if value else \" \"\n" ]
from django.utils.html import format_html, format_html_join, escape from django.utils.safestring import mark_safe from django.forms.utils import flatatt from . import wrappers from .utils import pad, get_choices, get_placeholder_text def render_charfield(field, attrs): """ Render the generic CharField. """ retur...
thetarkus/django-semanticui-forms
semanticuiforms/utils.py
get_choices
python
def get_choices(field): """ Find choices of a field, whether it has choices or has a queryset. Args: field (BoundField): Django form boundfield Returns: list: List of choices """ empty_label = getattr(field.field, "empty_label", False) needs_empty_value = False choices = [] # Data is the choices if ha...
Find choices of a field, whether it has choices or has a queryset. Args: field (BoundField): Django form boundfield Returns: list: List of choices
train
https://github.com/thetarkus/django-semanticui-forms/blob/9664c6f01621568c3fa39b36439178586649eafe/semanticuiforms/utils.py#L25-L66
null
from django.db.models.fields import BLANK_CHOICE_DASH from django.conf import settings def pad(value): """ Add one space padding around value if value is valid. Args: value (string): Value Returns: string: Value with padding if value was valid else one space """ return " %s " % value if value else " " d...
astropy/pyregion
pyregion/wcs_converter.py
_generate_arg_types
python
def _generate_arg_types(coordlist_length, shape_name): from .ds9_region_parser import ds9_shape_defs from .ds9_attr_parser import ds9_shape_in_comment_defs if shape_name in ds9_shape_defs: shape_def = ds9_shape_defs[shape_name] else: shape_def = ds9_shape_in_comment_defs[shape_name] ...
Find coordinate types based on shape name and coordlist length This function returns a list of coordinate types based on which coordinates can be repeated for a given type of shap Parameters ---------- coordlist_length : int The number of coordinates or arguments used to define the shape. ...
train
https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/wcs_converter.py#L13-L55
null
import copy from astropy.coordinates import SkyCoord from astropy.wcs import WCS from astropy.wcs.utils import proj_plane_pixel_area, proj_plane_pixel_scales import numpy as np from .wcs_helper import _estimate_angle from .region_numbers import CoordOdd, Distance, Angle from .parser_helper import Shape, CoordCommand f...
astropy/pyregion
pyregion/wcs_converter.py
convert_to_imagecoord
python
def convert_to_imagecoord(shape, header): arg_types = _generate_arg_types(len(shape.coord_list), shape.name) new_coordlist = [] is_even_distance = True coord_list_iter = iter(zip(shape.coord_list, arg_types)) new_wcs = WCS(header) pixel_scales = proj_plane_pixel_scales(new_wcs) for coordi...
Convert the coordlist of `shape` to image coordinates Parameters ---------- shape : `pyregion.parser_helper.Shape` The `Shape` to convert coordinates header : `~astropy.io.fits.Header` Specifies what WCS transformations to use. Returns ------- new_coordlist : list ...
train
https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/wcs_converter.py#L58-L115
[ "def _generate_arg_types(coordlist_length, shape_name):\n \"\"\"Find coordinate types based on shape name and coordlist length\n\n This function returns a list of coordinate types based on which\n coordinates can be repeated for a given type of shap\n\n Parameters\n ----------\n coordlist_length :...
import copy from astropy.coordinates import SkyCoord from astropy.wcs import WCS from astropy.wcs.utils import proj_plane_pixel_area, proj_plane_pixel_scales import numpy as np from .wcs_helper import _estimate_angle from .region_numbers import CoordOdd, Distance, Angle from .parser_helper import Shape, CoordCommand f...
astropy/pyregion
pyregion/region_to_filter.py
as_region_filter
python
def as_region_filter(shape_list, origin=1): filter_list = [] for shape in shape_list: if shape.name == "composite": continue if shape.name == "polygon": xy = np.array(shape.coord_list) - origin f = region_filter.Polygon(xy[::2], xy[1::2]) elif shap...
Often, the regions files implicitly assume the lower-left corner of the image as a coordinate (1,1). However, the python convetion is that the array index starts from 0. By default (origin = 1), coordinates of the returned mpl artists have coordinate shifted by (1, 1). If you do not want this shift, use...
train
https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/region_to_filter.py#L6-L117
null
import numpy as np import pyregion._region_filter as region_filter import warnings
astropy/pyregion
pyregion/core.py
parse
python
def parse(region_string): rp = RegionParser() ss = rp.parse(region_string) sss1 = rp.convert_attr(ss) sss2 = _check_wcs(sss1) shape_list, comment_list = rp.filter_shape2(sss2) return ShapeList(shape_list, comment_list=comment_list)
Parse DS9 region string into a ShapeList. Parameters ---------- region_string : str Region string Returns ------- shapes : `ShapeList` List of `~pyregion.Shape`
train
https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/core.py#L223-L242
[ "def check_wcs(l):\n default_coord = \"physical\"\n\n for l1, c1 in l:\n if isinstance(l1, CoordCommand):\n default_coord = l1.text.lower()\n continue\n if isinstance(l1, Shape):\n if default_coord == \"galactic\":\n is_wcs, coord_list = check_wcs_...
from itertools import cycle from .ds9_region_parser import RegionParser from .wcs_converter import check_wcs as _check_wcs _builtin_open = open class ShapeList(list): """A list of `~pyregion.Shape` objects. Parameters ---------- shape_list : list List of `pyregion.Shape` objects comment...