repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
PyAr/fades
fades/envbuilder.py
_FadesEnvBuilder.create_env
def create_env(self, interpreter, is_current, options): """Create the virtualenv and return its info.""" if is_current: # apply pyvenv options pyvenv_options = options['pyvenv_options'] if "--system-site-packages" in pyvenv_options: self.system_site_pa...
python
def create_env(self, interpreter, is_current, options): """Create the virtualenv and return its info.""" if is_current: # apply pyvenv options pyvenv_options = options['pyvenv_options'] if "--system-site-packages" in pyvenv_options: self.system_site_pa...
[ "def", "create_env", "(", "self", ",", "interpreter", ",", "is_current", ",", "options", ")", ":", "if", "is_current", ":", "pyvenv_options", "=", "options", "[", "'pyvenv_options'", "]", "if", "\"--system-site-packages\"", "in", "pyvenv_options", ":", "self", "...
Create the virtualenv and return its info.
[ "Create", "the", "virtualenv", "and", "return", "its", "info", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/envbuilder.py#L95-L117
train
PyAr/fades
fades/envbuilder.py
UsageManager.store_usage_stat
def store_usage_stat(self, venv_data, cache): """Log an usage record for venv_data.""" with open(self.stat_file_path, 'at') as f: self._write_venv_usage(f, venv_data)
python
def store_usage_stat(self, venv_data, cache): """Log an usage record for venv_data.""" with open(self.stat_file_path, 'at') as f: self._write_venv_usage(f, venv_data)
[ "def", "store_usage_stat", "(", "self", ",", "venv_data", ",", "cache", ")", ":", "with", "open", "(", "self", ".", "stat_file_path", ",", "'at'", ")", "as", "f", ":", "self", ".", "_write_venv_usage", "(", "f", ",", "venv_data", ")" ]
Log an usage record for venv_data.
[ "Log", "an", "usage", "record", "for", "venv_data", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/envbuilder.py#L192-L195
train
PyAr/fades
fades/envbuilder.py
UsageManager.clean_unused_venvs
def clean_unused_venvs(self, max_days_to_keep): """Compact usage stats and remove venvs. This method loads the complete file usage in memory, for every venv compact all records in one (the lastest), updates this info for every env deleted and, finally, write the entire file to disk. ...
python
def clean_unused_venvs(self, max_days_to_keep): """Compact usage stats and remove venvs. This method loads the complete file usage in memory, for every venv compact all records in one (the lastest), updates this info for every env deleted and, finally, write the entire file to disk. ...
[ "def", "clean_unused_venvs", "(", "self", ",", "max_days_to_keep", ")", ":", "with", "filelock", "(", "self", ".", "stat_file_lock", ")", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "venvs_dict", "=", "self", ".", "_get_compacted_dict_usage_from_file",...
Compact usage stats and remove venvs. This method loads the complete file usage in memory, for every venv compact all records in one (the lastest), updates this info for every env deleted and, finally, write the entire file to disk. If something failed during this steps, usage file rem...
[ "Compact", "usage", "stats", "and", "remove", "venvs", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/envbuilder.py#L214-L242
train
PyAr/fades
fades/helpers.py
logged_exec
def logged_exec(cmd): """Execute a command, redirecting the output to the log.""" logger = logging.getLogger('fades.exec') logger.debug("Executing external command: %r", cmd) p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) stdout = [] ...
python
def logged_exec(cmd): """Execute a command, redirecting the output to the log.""" logger = logging.getLogger('fades.exec') logger.debug("Executing external command: %r", cmd) p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) stdout = [] ...
[ "def", "logged_exec", "(", "cmd", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'fades.exec'", ")", "logger", ".", "debug", "(", "\"Executing external command: %r\"", ",", "cmd", ")", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "st...
Execute a command, redirecting the output to the log.
[ "Execute", "a", "command", "redirecting", "the", "output", "to", "the", "log", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L72-L86
train
PyAr/fades
fades/helpers.py
_get_specific_dir
def _get_specific_dir(dir_type): """Get a specific directory, using some XDG base, with sensible default.""" if SNAP_BASEDIR_NAME in os.environ: logger.debug("Getting base dir information from SNAP_BASEDIR_NAME env var.") direct = os.path.join(os.environ[SNAP_BASEDIR_NAME], dir_type) else: ...
python
def _get_specific_dir(dir_type): """Get a specific directory, using some XDG base, with sensible default.""" if SNAP_BASEDIR_NAME in os.environ: logger.debug("Getting base dir information from SNAP_BASEDIR_NAME env var.") direct = os.path.join(os.environ[SNAP_BASEDIR_NAME], dir_type) else: ...
[ "def", "_get_specific_dir", "(", "dir_type", ")", ":", "if", "SNAP_BASEDIR_NAME", "in", "os", ".", "environ", ":", "logger", ".", "debug", "(", "\"Getting base dir information from SNAP_BASEDIR_NAME env var.\"", ")", "direct", "=", "os", ".", "path", ".", "join", ...
Get a specific directory, using some XDG base, with sensible default.
[ "Get", "a", "specific", "directory", "using", "some", "XDG", "base", "with", "sensible", "default", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L94-L113
train
PyAr/fades
fades/helpers.py
_get_interpreter_info
def _get_interpreter_info(interpreter=None): """Return the interpreter's full path using pythonX.Y format.""" if interpreter is None: # If interpreter is None by default returns the current interpreter data. major, minor = sys.version_info[:2] executable = sys.executable else: ...
python
def _get_interpreter_info(interpreter=None): """Return the interpreter's full path using pythonX.Y format.""" if interpreter is None: # If interpreter is None by default returns the current interpreter data. major, minor = sys.version_info[:2] executable = sys.executable else: ...
[ "def", "_get_interpreter_info", "(", "interpreter", "=", "None", ")", ":", "if", "interpreter", "is", "None", ":", "major", ",", "minor", "=", "sys", ".", "version_info", "[", ":", "2", "]", "executable", "=", "sys", ".", "executable", "else", ":", "args...
Return the interpreter's full path using pythonX.Y format.
[ "Return", "the", "interpreter", "s", "full", "path", "using", "pythonX", ".", "Y", "format", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L126-L146
train
PyAr/fades
fades/helpers.py
get_interpreter_version
def get_interpreter_version(requested_interpreter): """Return a 'sanitized' interpreter and indicates if it is the current one.""" logger.debug('Getting interpreter version for: %s', requested_interpreter) current_interpreter = _get_interpreter_info() logger.debug('Current interpreter is %s', current_in...
python
def get_interpreter_version(requested_interpreter): """Return a 'sanitized' interpreter and indicates if it is the current one.""" logger.debug('Getting interpreter version for: %s', requested_interpreter) current_interpreter = _get_interpreter_info() logger.debug('Current interpreter is %s', current_in...
[ "def", "get_interpreter_version", "(", "requested_interpreter", ")", ":", "logger", ".", "debug", "(", "'Getting interpreter version for: %s'", ",", "requested_interpreter", ")", "current_interpreter", "=", "_get_interpreter_info", "(", ")", "logger", ".", "debug", "(", ...
Return a 'sanitized' interpreter and indicates if it is the current one.
[ "Return", "a", "sanitized", "interpreter", "and", "indicates", "if", "it", "is", "the", "current", "one", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L149-L161
train
PyAr/fades
fades/helpers.py
check_pypi_updates
def check_pypi_updates(dependencies): """Return a list of dependencies to upgrade.""" dependencies_up_to_date = [] for dependency in dependencies.get('pypi', []): # get latest version from PyPI api try: latest_version = get_latest_version_number(dependency.project_name) e...
python
def check_pypi_updates(dependencies): """Return a list of dependencies to upgrade.""" dependencies_up_to_date = [] for dependency in dependencies.get('pypi', []): # get latest version from PyPI api try: latest_version = get_latest_version_number(dependency.project_name) e...
[ "def", "check_pypi_updates", "(", "dependencies", ")", ":", "dependencies_up_to_date", "=", "[", "]", "for", "dependency", "in", "dependencies", ".", "get", "(", "'pypi'", ",", "[", "]", ")", ":", "try", ":", "latest_version", "=", "get_latest_version_number", ...
Return a list of dependencies to upgrade.
[ "Return", "a", "list", "of", "dependencies", "to", "upgrade", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L180-L214
train
PyAr/fades
fades/helpers.py
_pypi_head_package
def _pypi_head_package(dependency): """Hit pypi with a http HEAD to check if pkg_name exists.""" if dependency.specs: _, version = dependency.specs[0] url = BASE_PYPI_URL_WITH_VERSION.format(name=dependency.project_name, version=version) else: url = BASE_PYPI_URL.format(name=dependen...
python
def _pypi_head_package(dependency): """Hit pypi with a http HEAD to check if pkg_name exists.""" if dependency.specs: _, version = dependency.specs[0] url = BASE_PYPI_URL_WITH_VERSION.format(name=dependency.project_name, version=version) else: url = BASE_PYPI_URL.format(name=dependen...
[ "def", "_pypi_head_package", "(", "dependency", ")", ":", "if", "dependency", ".", "specs", ":", "_", ",", "version", "=", "dependency", ".", "specs", "[", "0", "]", "url", "=", "BASE_PYPI_URL_WITH_VERSION", ".", "format", "(", "name", "=", "dependency", "...
Hit pypi with a http HEAD to check if pkg_name exists.
[ "Hit", "pypi", "with", "a", "http", "HEAD", "to", "check", "if", "pkg_name", "exists", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L217-L242
train
PyAr/fades
fades/helpers.py
check_pypi_exists
def check_pypi_exists(dependencies): """Check if the indicated dependencies actually exists in pypi.""" for dependency in dependencies.get('pypi', []): logger.debug("Checking if %r exists in PyPI", dependency) try: exists = _pypi_head_package(dependency) except Exception as e...
python
def check_pypi_exists(dependencies): """Check if the indicated dependencies actually exists in pypi.""" for dependency in dependencies.get('pypi', []): logger.debug("Checking if %r exists in PyPI", dependency) try: exists = _pypi_head_package(dependency) except Exception as e...
[ "def", "check_pypi_exists", "(", "dependencies", ")", ":", "for", "dependency", "in", "dependencies", ".", "get", "(", "'pypi'", ",", "[", "]", ")", ":", "logger", ".", "debug", "(", "\"Checking if %r exists in PyPI\"", ",", "dependency", ")", "try", ":", "e...
Check if the indicated dependencies actually exists in pypi.
[ "Check", "if", "the", "indicated", "dependencies", "actually", "exists", "in", "pypi", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L245-L258
train
PyAr/fades
fades/helpers.py
download_remote_script
def download_remote_script(url): """Download the content of a remote script to a local temp file.""" temp_fh = tempfile.NamedTemporaryFile('wt', encoding='utf8', suffix=".py", delete=False) downloader = _ScriptDownloader(url) logger.info( "Downloading remote script from %r using (%r downloader) ...
python
def download_remote_script(url): """Download the content of a remote script to a local temp file.""" temp_fh = tempfile.NamedTemporaryFile('wt', encoding='utf8', suffix=".py", delete=False) downloader = _ScriptDownloader(url) logger.info( "Downloading remote script from %r using (%r downloader) ...
[ "def", "download_remote_script", "(", "url", ")", ":", "temp_fh", "=", "tempfile", ".", "NamedTemporaryFile", "(", "'wt'", ",", "encoding", "=", "'utf8'", ",", "suffix", "=", "\".py\"", ",", "delete", "=", "False", ")", "downloader", "=", "_ScriptDownloader", ...
Download the content of a remote script to a local temp file.
[ "Download", "the", "content", "of", "a", "remote", "script", "to", "a", "local", "temp", "file", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L334-L345
train
PyAr/fades
fades/helpers.py
ExecutionError.dump_to_log
def dump_to_log(self, logger): """Send the cmd info and collected stdout to logger.""" logger.error("Execution ended in %s for cmd %s", self._retcode, self._cmd) for line in self._collected_stdout: logger.error(STDOUT_LOG_PREFIX + line)
python
def dump_to_log(self, logger): """Send the cmd info and collected stdout to logger.""" logger.error("Execution ended in %s for cmd %s", self._retcode, self._cmd) for line in self._collected_stdout: logger.error(STDOUT_LOG_PREFIX + line)
[ "def", "dump_to_log", "(", "self", ",", "logger", ")", ":", "logger", ".", "error", "(", "\"Execution ended in %s for cmd %s\"", ",", "self", ".", "_retcode", ",", "self", ".", "_cmd", ")", "for", "line", "in", "self", ".", "_collected_stdout", ":", "logger"...
Send the cmd info and collected stdout to logger.
[ "Send", "the", "cmd", "info", "and", "collected", "stdout", "to", "logger", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L65-L69
train
PyAr/fades
fades/helpers.py
_ScriptDownloader._decide
def _decide(self): """Find out which method should be applied to download that URL.""" netloc = parse.urlparse(self.url).netloc name = self.NETLOCS.get(netloc, 'raw') return name
python
def _decide(self): """Find out which method should be applied to download that URL.""" netloc = parse.urlparse(self.url).netloc name = self.NETLOCS.get(netloc, 'raw') return name
[ "def", "_decide", "(", "self", ")", ":", "netloc", "=", "parse", ".", "urlparse", "(", "self", ".", "url", ")", ".", "netloc", "name", "=", "self", ".", "NETLOCS", ".", "get", "(", "netloc", ",", "'raw'", ")", "return", "name" ]
Find out which method should be applied to download that URL.
[ "Find", "out", "which", "method", "should", "be", "applied", "to", "download", "that", "URL", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L287-L291
train
PyAr/fades
fades/helpers.py
_ScriptDownloader.get
def get(self): """Get the script content from the URL using the decided downloader.""" method_name = "_download_" + self.name method = getattr(self, method_name) return method()
python
def get(self): """Get the script content from the URL using the decided downloader.""" method_name = "_download_" + self.name method = getattr(self, method_name) return method()
[ "def", "get", "(", "self", ")", ":", "method_name", "=", "\"_download_\"", "+", "self", ".", "name", "method", "=", "getattr", "(", "self", ",", "method_name", ")", "return", "method", "(", ")" ]
Get the script content from the URL using the decided downloader.
[ "Get", "the", "script", "content", "from", "the", "URL", "using", "the", "decided", "downloader", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L293-L297
train
PyAr/fades
fades/helpers.py
_ScriptDownloader._download_raw
def _download_raw(self, url=None): """Download content from URL directly.""" if url is None: url = self.url req = request.Request(url, headers=self.HEADERS_PLAIN) return request.urlopen(req).read().decode("utf8")
python
def _download_raw(self, url=None): """Download content from URL directly.""" if url is None: url = self.url req = request.Request(url, headers=self.HEADERS_PLAIN) return request.urlopen(req).read().decode("utf8")
[ "def", "_download_raw", "(", "self", ",", "url", "=", "None", ")", ":", "if", "url", "is", "None", ":", "url", "=", "self", ".", "url", "req", "=", "request", ".", "Request", "(", "url", ",", "headers", "=", "self", ".", "HEADERS_PLAIN", ")", "retu...
Download content from URL directly.
[ "Download", "content", "from", "URL", "directly", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L299-L304
train
PyAr/fades
fades/helpers.py
_ScriptDownloader._download_linkode
def _download_linkode(self): """Download content from Linkode pastebin.""" # build the API url linkode_id = self.url.split("/")[-1] if linkode_id.startswith("#"): linkode_id = linkode_id[1:] url = "https://linkode.org/api/1/linkodes/" + linkode_id req = reque...
python
def _download_linkode(self): """Download content from Linkode pastebin.""" # build the API url linkode_id = self.url.split("/")[-1] if linkode_id.startswith("#"): linkode_id = linkode_id[1:] url = "https://linkode.org/api/1/linkodes/" + linkode_id req = reque...
[ "def", "_download_linkode", "(", "self", ")", ":", "linkode_id", "=", "self", ".", "url", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "if", "linkode_id", ".", "startswith", "(", "\"#\"", ")", ":", "linkode_id", "=", "linkode_id", "[", "1", "...
Download content from Linkode pastebin.
[ "Download", "content", "from", "Linkode", "pastebin", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L306-L319
train
PyAr/fades
fades/helpers.py
_ScriptDownloader._download_pastebin
def _download_pastebin(self): """Download content from Pastebin itself.""" paste_id = self.url.split("/")[-1] url = "https://pastebin.com/raw/" + paste_id return self._download_raw(url)
python
def _download_pastebin(self): """Download content from Pastebin itself.""" paste_id = self.url.split("/")[-1] url = "https://pastebin.com/raw/" + paste_id return self._download_raw(url)
[ "def", "_download_pastebin", "(", "self", ")", ":", "paste_id", "=", "self", ".", "url", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "url", "=", "\"https://pastebin.com/raw/\"", "+", "paste_id", "return", "self", ".", "_download_raw", "(", "url", ...
Download content from Pastebin itself.
[ "Download", "content", "from", "Pastebin", "itself", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L321-L325
train
PyAr/fades
fades/helpers.py
_ScriptDownloader._download_gist
def _download_gist(self): """Download content from github's pastebin.""" parts = parse.urlparse(self.url) url = "https://gist.github.com" + parts.path + "/raw" return self._download_raw(url)
python
def _download_gist(self): """Download content from github's pastebin.""" parts = parse.urlparse(self.url) url = "https://gist.github.com" + parts.path + "/raw" return self._download_raw(url)
[ "def", "_download_gist", "(", "self", ")", ":", "parts", "=", "parse", ".", "urlparse", "(", "self", ".", "url", ")", "url", "=", "\"https://gist.github.com\"", "+", "parts", ".", "path", "+", "\"/raw\"", "return", "self", ".", "_download_raw", "(", "url",...
Download content from github's pastebin.
[ "Download", "content", "from", "github", "s", "pastebin", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/helpers.py#L327-L331
train
PyAr/fades
setup.py
get_version
def get_version(): """Retrieves package version from the file.""" with open('fades/_version.py') as fh: m = re.search("\(([^']*)\)", fh.read()) if m is None: raise ValueError("Unrecognized version in 'fades/_version.py'") return m.groups()[0].replace(', ', '.')
python
def get_version(): """Retrieves package version from the file.""" with open('fades/_version.py') as fh: m = re.search("\(([^']*)\)", fh.read()) if m is None: raise ValueError("Unrecognized version in 'fades/_version.py'") return m.groups()[0].replace(', ', '.')
[ "def", "get_version", "(", ")", ":", "with", "open", "(", "'fades/_version.py'", ")", "as", "fh", ":", "m", "=", "re", ".", "search", "(", "\"\\(([^']*)\\)\"", ",", "fh", ".", "read", "(", ")", ")", "if", "m", "is", "None", ":", "raise", "ValueError"...
Retrieves package version from the file.
[ "Retrieves", "package", "version", "from", "the", "file", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/setup.py#L53-L59
train
PyAr/fades
setup.py
CustomInstall.initialize_options
def initialize_options(self): """Run parent initialization and then fix the scripts var.""" install.initialize_options(self) # leave the proper script according to the platform script = SCRIPT_WIN if sys.platform == "win32" else SCRIPT_REST self.distribution.scripts = [script]
python
def initialize_options(self): """Run parent initialization and then fix the scripts var.""" install.initialize_options(self) # leave the proper script according to the platform script = SCRIPT_WIN if sys.platform == "win32" else SCRIPT_REST self.distribution.scripts = [script]
[ "def", "initialize_options", "(", "self", ")", ":", "install", ".", "initialize_options", "(", "self", ")", "script", "=", "SCRIPT_WIN", "if", "sys", ".", "platform", "==", "\"win32\"", "else", "SCRIPT_REST", "self", ".", "distribution", ".", "scripts", "=", ...
Run parent initialization and then fix the scripts var.
[ "Run", "parent", "initialization", "and", "then", "fix", "the", "scripts", "var", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/setup.py#L70-L76
train
PyAr/fades
setup.py
CustomInstall.run
def run(self): """Run parent install, and then save the man file.""" install.run(self) # man directory if self._custom_man_dir is not None: if not os.path.exists(self._custom_man_dir): os.makedirs(self._custom_man_dir) shutil.copy("man/fades.1", s...
python
def run(self): """Run parent install, and then save the man file.""" install.run(self) # man directory if self._custom_man_dir is not None: if not os.path.exists(self._custom_man_dir): os.makedirs(self._custom_man_dir) shutil.copy("man/fades.1", s...
[ "def", "run", "(", "self", ")", ":", "install", ".", "run", "(", "self", ")", "if", "self", ".", "_custom_man_dir", "is", "not", "None", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_custom_man_dir", ")", ":", "os", ".", ...
Run parent install, and then save the man file.
[ "Run", "parent", "install", "and", "then", "save", "the", "man", "file", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/setup.py#L78-L86
train
PyAr/fades
setup.py
CustomInstall.finalize_options
def finalize_options(self): """Alter the installation path.""" install.finalize_options(self) if self.prefix is None: # no place for man page (like in a 'snap') man_dir = None else: man_dir = os.path.join(self.prefix, "share", "man", "man1") ...
python
def finalize_options(self): """Alter the installation path.""" install.finalize_options(self) if self.prefix is None: # no place for man page (like in a 'snap') man_dir = None else: man_dir = os.path.join(self.prefix, "share", "man", "man1") ...
[ "def", "finalize_options", "(", "self", ")", ":", "install", ".", "finalize_options", "(", "self", ")", "if", "self", ".", "prefix", "is", "None", ":", "man_dir", "=", "None", "else", ":", "man_dir", "=", "os", ".", "path", ".", "join", "(", "self", ...
Alter the installation path.
[ "Alter", "the", "installation", "path", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/setup.py#L88-L101
train
PyAr/fades
fades/file_options.py
options_from_file
def options_from_file(args): """Get a argparse.Namespace and return it updated with options from config files. Config files will be parsed with priority equal to his order in CONFIG_FILES. """ logger.debug("updating options from config files") updated_from_file = [] for config_file in CONFIG_FI...
python
def options_from_file(args): """Get a argparse.Namespace and return it updated with options from config files. Config files will be parsed with priority equal to his order in CONFIG_FILES. """ logger.debug("updating options from config files") updated_from_file = [] for config_file in CONFIG_FI...
[ "def", "options_from_file", "(", "args", ")", ":", "logger", ".", "debug", "(", "\"updating options from config files\"", ")", "updated_from_file", "=", "[", "]", "for", "config_file", "in", "CONFIG_FILES", ":", "logger", ".", "debug", "(", "\"updating from: %s\"", ...
Get a argparse.Namespace and return it updated with options from config files. Config files will be parsed with priority equal to his order in CONFIG_FILES.
[ "Get", "a", "argparse", ".", "Namespace", "and", "return", "it", "updated", "with", "options", "from", "config", "files", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/file_options.py#L33-L66
train
PyAr/fades
fades/cache.py
VEnvsCache._venv_match
def _venv_match(self, installed, requirements): """Return True if what is installed satisfies the requirements. This method has multiple exit-points, but only for False (because if *anything* is not satisified, the venv is no good). Only after all was checked, and it didn't exit, the ve...
python
def _venv_match(self, installed, requirements): """Return True if what is installed satisfies the requirements. This method has multiple exit-points, but only for False (because if *anything* is not satisified, the venv is no good). Only after all was checked, and it didn't exit, the ve...
[ "def", "_venv_match", "(", "self", ",", "installed", ",", "requirements", ")", ":", "if", "not", "requirements", ":", "return", "None", "if", "installed", "else", "[", "]", "satisfying_deps", "=", "[", "]", "for", "repo", ",", "req_deps", "in", "requiremen...
Return True if what is installed satisfies the requirements. This method has multiple exit-points, but only for False (because if *anything* is not satisified, the venv is no good). Only after all was checked, and it didn't exit, the venv is ok so return True.
[ "Return", "True", "if", "what", "is", "installed", "satisfies", "the", "requirements", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L44-L84
train
PyAr/fades
fades/cache.py
VEnvsCache._match_by_uuid
def _match_by_uuid(self, current_venvs, uuid): """Select a venv matching exactly by uuid.""" for venv_str in current_venvs: venv = json.loads(venv_str) env_path = venv.get('metadata', {}).get('env_path') _, env_uuid = os.path.split(env_path) if env_uuid ==...
python
def _match_by_uuid(self, current_venvs, uuid): """Select a venv matching exactly by uuid.""" for venv_str in current_venvs: venv = json.loads(venv_str) env_path = venv.get('metadata', {}).get('env_path') _, env_uuid = os.path.split(env_path) if env_uuid ==...
[ "def", "_match_by_uuid", "(", "self", ",", "current_venvs", ",", "uuid", ")", ":", "for", "venv_str", "in", "current_venvs", ":", "venv", "=", "json", ".", "loads", "(", "venv_str", ")", "env_path", "=", "venv", ".", "get", "(", "'metadata'", ",", "{", ...
Select a venv matching exactly by uuid.
[ "Select", "a", "venv", "matching", "exactly", "by", "uuid", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L86-L93
train
PyAr/fades
fades/cache.py
VEnvsCache._select_better_fit
def _select_better_fit(self, matching_venvs): """Receive a list of matching venvs, and decide which one is the best fit.""" # keep the venvs in a separate array, to pick up the winner, and the (sorted, to compare # each dependency with its equivalent) in other structure to later compare ...
python
def _select_better_fit(self, matching_venvs): """Receive a list of matching venvs, and decide which one is the best fit.""" # keep the venvs in a separate array, to pick up the winner, and the (sorted, to compare # each dependency with its equivalent) in other structure to later compare ...
[ "def", "_select_better_fit", "(", "self", ",", "matching_venvs", ")", ":", "venvs", "=", "[", "]", "to_compare", "=", "[", "]", "for", "matching", ",", "venv", "in", "matching_venvs", ":", "to_compare", ".", "append", "(", "sorted", "(", "matching", ",", ...
Receive a list of matching venvs, and decide which one is the best fit.
[ "Receive", "a", "list", "of", "matching", "venvs", "and", "decide", "which", "one", "is", "the", "best", "fit", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L95-L123
train
PyAr/fades
fades/cache.py
VEnvsCache._match_by_requirements
def _match_by_requirements(self, current_venvs, requirements, interpreter, options): """Select a venv matching interpreter and options, complying with requirements. Several venvs can be found in this case, will return the better fit. """ matching_venvs = [] for venv_str in curre...
python
def _match_by_requirements(self, current_venvs, requirements, interpreter, options): """Select a venv matching interpreter and options, complying with requirements. Several venvs can be found in this case, will return the better fit. """ matching_venvs = [] for venv_str in curre...
[ "def", "_match_by_requirements", "(", "self", ",", "current_venvs", ",", "requirements", ",", "interpreter", ",", "options", ")", ":", "matching_venvs", "=", "[", "]", "for", "venv_str", "in", "current_venvs", ":", "venv", "=", "json", ".", "loads", "(", "ve...
Select a venv matching interpreter and options, complying with requirements. Several venvs can be found in this case, will return the better fit.
[ "Select", "a", "venv", "matching", "interpreter", "and", "options", "complying", "with", "requirements", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L125-L146
train
PyAr/fades
fades/cache.py
VEnvsCache._select
def _select(self, current_venvs, requirements=None, interpreter='', uuid='', options=None): """Select which venv satisfy the received requirements.""" if uuid: logger.debug("Searching a venv by uuid: %s", uuid) venv = self._match_by_uuid(current_venvs, uuid) else: ...
python
def _select(self, current_venvs, requirements=None, interpreter='', uuid='', options=None): """Select which venv satisfy the received requirements.""" if uuid: logger.debug("Searching a venv by uuid: %s", uuid) venv = self._match_by_uuid(current_venvs, uuid) else: ...
[ "def", "_select", "(", "self", ",", "current_venvs", ",", "requirements", "=", "None", ",", "interpreter", "=", "''", ",", "uuid", "=", "''", ",", "options", "=", "None", ")", ":", "if", "uuid", ":", "logger", ".", "debug", "(", "\"Searching a venv by uu...
Select which venv satisfy the received requirements.
[ "Select", "which", "venv", "satisfy", "the", "received", "requirements", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L148-L163
train
PyAr/fades
fades/cache.py
VEnvsCache.get_venv
def get_venv(self, requirements=None, interpreter='', uuid='', options=None): """Find a venv that serves these requirements, if any.""" lines = self._read_cache() return self._select(lines, requirements, interpreter, uuid=uuid, options=options)
python
def get_venv(self, requirements=None, interpreter='', uuid='', options=None): """Find a venv that serves these requirements, if any.""" lines = self._read_cache() return self._select(lines, requirements, interpreter, uuid=uuid, options=options)
[ "def", "get_venv", "(", "self", ",", "requirements", "=", "None", ",", "interpreter", "=", "''", ",", "uuid", "=", "''", ",", "options", "=", "None", ")", ":", "lines", "=", "self", ".", "_read_cache", "(", ")", "return", "self", ".", "_select", "(",...
Find a venv that serves these requirements, if any.
[ "Find", "a", "venv", "that", "serves", "these", "requirements", "if", "any", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L165-L168
train
PyAr/fades
fades/cache.py
VEnvsCache.store
def store(self, installed_stuff, metadata, interpreter, options): """Store the virtualenv metadata for the indicated installed_stuff.""" new_content = { 'timestamp': int(time.mktime(time.localtime())), 'installed': installed_stuff, 'metadata': metadata, 'i...
python
def store(self, installed_stuff, metadata, interpreter, options): """Store the virtualenv metadata for the indicated installed_stuff.""" new_content = { 'timestamp': int(time.mktime(time.localtime())), 'installed': installed_stuff, 'metadata': metadata, 'i...
[ "def", "store", "(", "self", ",", "installed_stuff", ",", "metadata", ",", "interpreter", ",", "options", ")", ":", "new_content", "=", "{", "'timestamp'", ":", "int", "(", "time", ".", "mktime", "(", "time", ".", "localtime", "(", ")", ")", ")", ",", ...
Store the virtualenv metadata for the indicated installed_stuff.
[ "Store", "the", "virtualenv", "metadata", "for", "the", "indicated", "installed_stuff", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L175-L187
train
PyAr/fades
fades/cache.py
VEnvsCache.remove
def remove(self, env_path): """Remove metadata for a given virtualenv from cache.""" with filelock(self.lockpath): cache = self._read_cache() logger.debug("Removing virtualenv from cache: %s" % env_path) lines = [ line for line in cache ...
python
def remove(self, env_path): """Remove metadata for a given virtualenv from cache.""" with filelock(self.lockpath): cache = self._read_cache() logger.debug("Removing virtualenv from cache: %s" % env_path) lines = [ line for line in cache ...
[ "def", "remove", "(", "self", ",", "env_path", ")", ":", "with", "filelock", "(", "self", ".", "lockpath", ")", ":", "cache", "=", "self", ".", "_read_cache", "(", ")", "logger", ".", "debug", "(", "\"Removing virtualenv from cache: %s\"", "%", "env_path", ...
Remove metadata for a given virtualenv from cache.
[ "Remove", "metadata", "for", "a", "given", "virtualenv", "from", "cache", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L189-L198
train
PyAr/fades
fades/cache.py
VEnvsCache._read_cache
def _read_cache(self): """Read virtualenv metadata from cache.""" if os.path.exists(self.filepath): with open(self.filepath, 'rt', encoding='utf8') as fh: lines = [x.strip() for x in fh] else: logger.debug("Index not found, starting empty") lin...
python
def _read_cache(self): """Read virtualenv metadata from cache.""" if os.path.exists(self.filepath): with open(self.filepath, 'rt', encoding='utf8') as fh: lines = [x.strip() for x in fh] else: logger.debug("Index not found, starting empty") lin...
[ "def", "_read_cache", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "filepath", ")", ":", "with", "open", "(", "self", ".", "filepath", ",", "'rt'", ",", "encoding", "=", "'utf8'", ")", "as", "fh", ":", "lines", ...
Read virtualenv metadata from cache.
[ "Read", "virtualenv", "metadata", "from", "cache", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L200-L208
train
PyAr/fades
fades/cache.py
VEnvsCache._write_cache
def _write_cache(self, lines, append=False): """Write virtualenv metadata to cache.""" mode = 'at' if append else 'wt' with open(self.filepath, mode, encoding='utf8') as fh: fh.writelines(line + '\n' for line in lines)
python
def _write_cache(self, lines, append=False): """Write virtualenv metadata to cache.""" mode = 'at' if append else 'wt' with open(self.filepath, mode, encoding='utf8') as fh: fh.writelines(line + '\n' for line in lines)
[ "def", "_write_cache", "(", "self", ",", "lines", ",", "append", "=", "False", ")", ":", "mode", "=", "'at'", "if", "append", "else", "'wt'", "with", "open", "(", "self", ".", "filepath", ",", "mode", ",", "encoding", "=", "'utf8'", ")", "as", "fh", ...
Write virtualenv metadata to cache.
[ "Write", "virtualenv", "metadata", "to", "cache", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/cache.py#L210-L214
train
PyAr/fades
fades/pipmanager.py
PipManager.install
def install(self, dependency): """Install a new dependency.""" if not self.pip_installed: logger.info("Need to install a dependency with pip, but no builtin, " "doing it manually (just wait a little, all should go well)") self._brute_force_install_pip() ...
python
def install(self, dependency): """Install a new dependency.""" if not self.pip_installed: logger.info("Need to install a dependency with pip, but no builtin, " "doing it manually (just wait a little, all should go well)") self._brute_force_install_pip() ...
[ "def", "install", "(", "self", ",", "dependency", ")", ":", "if", "not", "self", ".", "pip_installed", ":", "logger", ".", "info", "(", "\"Need to install a dependency with pip, but no builtin, \"", "\"doing it manually (just wait a little, all should go well)\"", ")", "sel...
Install a new dependency.
[ "Install", "a", "new", "dependency", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/pipmanager.py#L50-L75
train
PyAr/fades
fades/pipmanager.py
PipManager.get_version
def get_version(self, dependency): """Return the installed version parsing the output of 'pip show'.""" logger.debug("getting installed version for %s", dependency) stdout = helpers.logged_exec([self.pip_exe, "show", str(dependency)]) version = [line for line in stdout if line.startswith...
python
def get_version(self, dependency): """Return the installed version parsing the output of 'pip show'.""" logger.debug("getting installed version for %s", dependency) stdout = helpers.logged_exec([self.pip_exe, "show", str(dependency)]) version = [line for line in stdout if line.startswith...
[ "def", "get_version", "(", "self", ",", "dependency", ")", ":", "logger", ".", "debug", "(", "\"getting installed version for %s\"", ",", "dependency", ")", "stdout", "=", "helpers", ".", "logged_exec", "(", "[", "self", ".", "pip_exe", ",", "\"show\"", ",", ...
Return the installed version parsing the output of 'pip show'.
[ "Return", "the", "installed", "version", "parsing", "the", "output", "of", "pip", "show", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/pipmanager.py#L77-L89
train
PyAr/fades
fades/pipmanager.py
PipManager._brute_force_install_pip
def _brute_force_install_pip(self): """A brute force install of pip itself.""" if os.path.exists(self.pip_installer_fname): logger.debug("Using pip installer from %r", self.pip_installer_fname) else: logger.debug( "Installer for pip not found in %r, downlo...
python
def _brute_force_install_pip(self): """A brute force install of pip itself.""" if os.path.exists(self.pip_installer_fname): logger.debug("Using pip installer from %r", self.pip_installer_fname) else: logger.debug( "Installer for pip not found in %r, downlo...
[ "def", "_brute_force_install_pip", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "pip_installer_fname", ")", ":", "logger", ".", "debug", "(", "\"Using pip installer from %r\"", ",", "self", ".", "pip_installer_fname", ")", "...
A brute force install of pip itself.
[ "A", "brute", "force", "install", "of", "pip", "itself", "." ]
e5ea457b09b105f321d4f81772f25e8695159604
https://github.com/PyAr/fades/blob/e5ea457b09b105f321d4f81772f25e8695159604/fades/pipmanager.py#L98-L110
train
albertyw/csv-ical
csv_ical/convert.py
Convert._generate_configs_from_default
def _generate_configs_from_default(self, overrides=None): # type: (Dict[str, int]) -> Dict[str, int] """ Generate configs by inheriting from defaults """ config = DEFAULT_CONFIG.copy() if not overrides: overrides = {} for k, v in overrides.items(): config[...
python
def _generate_configs_from_default(self, overrides=None): # type: (Dict[str, int]) -> Dict[str, int] """ Generate configs by inheriting from defaults """ config = DEFAULT_CONFIG.copy() if not overrides: overrides = {} for k, v in overrides.items(): config[...
[ "def", "_generate_configs_from_default", "(", "self", ",", "overrides", "=", "None", ")", ":", "config", "=", "DEFAULT_CONFIG", ".", "copy", "(", ")", "if", "not", "overrides", ":", "overrides", "=", "{", "}", "for", "k", ",", "v", "in", "overrides", "."...
Generate configs by inheriting from defaults
[ "Generate", "configs", "by", "inheriting", "from", "defaults" ]
cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed
https://github.com/albertyw/csv-ical/blob/cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed/csv_ical/convert.py#L29-L37
train
albertyw/csv-ical
csv_ical/convert.py
Convert.read_ical
def read_ical(self, ical_file_location): # type: (str) -> Calendar """ Read the ical file """ with open(ical_file_location, 'r') as ical_file: data = ical_file.read() self.cal = Calendar.from_ical(data) return self.cal
python
def read_ical(self, ical_file_location): # type: (str) -> Calendar """ Read the ical file """ with open(ical_file_location, 'r') as ical_file: data = ical_file.read() self.cal = Calendar.from_ical(data) return self.cal
[ "def", "read_ical", "(", "self", ",", "ical_file_location", ")", ":", "with", "open", "(", "ical_file_location", ",", "'r'", ")", "as", "ical_file", ":", "data", "=", "ical_file", ".", "read", "(", ")", "self", ".", "cal", "=", "Calendar", ".", "from_ica...
Read the ical file
[ "Read", "the", "ical", "file" ]
cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed
https://github.com/albertyw/csv-ical/blob/cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed/csv_ical/convert.py#L39-L44
train
albertyw/csv-ical
csv_ical/convert.py
Convert.read_csv
def read_csv(self, csv_location, csv_configs=None): # type: (str, Dict[str, int]) -> List[List[str]] """ Read the csv file """ csv_configs = self._generate_configs_from_default(csv_configs) with open(csv_location, 'r') as csv_file: csv_reader = csv.reader(csv_file) ...
python
def read_csv(self, csv_location, csv_configs=None): # type: (str, Dict[str, int]) -> List[List[str]] """ Read the csv file """ csv_configs = self._generate_configs_from_default(csv_configs) with open(csv_location, 'r') as csv_file: csv_reader = csv.reader(csv_file) ...
[ "def", "read_csv", "(", "self", ",", "csv_location", ",", "csv_configs", "=", "None", ")", ":", "csv_configs", "=", "self", ".", "_generate_configs_from_default", "(", "csv_configs", ")", "with", "open", "(", "csv_location", ",", "'r'", ")", "as", "csv_file", ...
Read the csv file
[ "Read", "the", "csv", "file" ]
cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed
https://github.com/albertyw/csv-ical/blob/cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed/csv_ical/convert.py#L46-L54
train
albertyw/csv-ical
csv_ical/convert.py
Convert.make_ical
def make_ical(self, csv_configs=None): # type: (Dict[str, int]) -> Calendar """ Make iCal entries """ csv_configs = self._generate_configs_from_default(csv_configs) self.cal = Calendar() for row in self.csv_data: event = Event() event.add('summary', row[cs...
python
def make_ical(self, csv_configs=None): # type: (Dict[str, int]) -> Calendar """ Make iCal entries """ csv_configs = self._generate_configs_from_default(csv_configs) self.cal = Calendar() for row in self.csv_data: event = Event() event.add('summary', row[cs...
[ "def", "make_ical", "(", "self", ",", "csv_configs", "=", "None", ")", ":", "csv_configs", "=", "self", ".", "_generate_configs_from_default", "(", "csv_configs", ")", "self", ".", "cal", "=", "Calendar", "(", ")", "for", "row", "in", "self", ".", "csv_dat...
Make iCal entries
[ "Make", "iCal", "entries" ]
cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed
https://github.com/albertyw/csv-ical/blob/cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed/csv_ical/convert.py#L56-L69
train
albertyw/csv-ical
csv_ical/convert.py
Convert.save_ical
def save_ical(self, ical_location): # type: (str) -> None """ Save the calendar instance to a file """ data = self.cal.to_ical() with open(ical_location, 'w') as ical_file: ical_file.write(data.decode('utf-8'))
python
def save_ical(self, ical_location): # type: (str) -> None """ Save the calendar instance to a file """ data = self.cal.to_ical() with open(ical_location, 'w') as ical_file: ical_file.write(data.decode('utf-8'))
[ "def", "save_ical", "(", "self", ",", "ical_location", ")", ":", "data", "=", "self", ".", "cal", ".", "to_ical", "(", ")", "with", "open", "(", "ical_location", ",", "'w'", ")", "as", "ical_file", ":", "ical_file", ".", "write", "(", "data", ".", "d...
Save the calendar instance to a file
[ "Save", "the", "calendar", "instance", "to", "a", "file" ]
cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed
https://github.com/albertyw/csv-ical/blob/cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed/csv_ical/convert.py#L86-L90
train
albertyw/csv-ical
csv_ical/convert.py
Convert.save_csv
def save_csv(self, csv_location): # type: (str) -> None """ Save the csv to a file """ with open(csv_location, 'w') as csv_handle: writer = csv.writer(csv_handle) for row in self.csv_data: writer.writerow(row)
python
def save_csv(self, csv_location): # type: (str) -> None """ Save the csv to a file """ with open(csv_location, 'w') as csv_handle: writer = csv.writer(csv_handle) for row in self.csv_data: writer.writerow(row)
[ "def", "save_csv", "(", "self", ",", "csv_location", ")", ":", "with", "open", "(", "csv_location", ",", "'w'", ")", "as", "csv_handle", ":", "writer", "=", "csv", ".", "writer", "(", "csv_handle", ")", "for", "row", "in", "self", ".", "csv_data", ":",...
Save the csv to a file
[ "Save", "the", "csv", "to", "a", "file" ]
cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed
https://github.com/albertyw/csv-ical/blob/cdb55a226cd0cb6cc214d896a6cea41a5b92c9ed/csv_ical/convert.py#L92-L97
train
planetarypy/planetaryimage
planetaryimage/image.py
PlanetaryImage.open
def open(cls, filename): """ Read an image file from disk Parameters ---------- filename : string Name of file to read as an image file. This file may be gzip (``.gz``) or bzip2 (``.bz2``) compressed. """ if filename.endswith('.gz'): ...
python
def open(cls, filename): """ Read an image file from disk Parameters ---------- filename : string Name of file to read as an image file. This file may be gzip (``.gz``) or bzip2 (``.bz2``) compressed. """ if filename.endswith('.gz'): ...
[ "def", "open", "(", "cls", ",", "filename", ")", ":", "if", "filename", ".", "endswith", "(", "'.gz'", ")", ":", "fp", "=", "gzip", ".", "open", "(", "filename", ",", "'rb'", ")", "try", ":", "return", "cls", "(", "fp", ",", "filename", ",", "com...
Read an image file from disk Parameters ---------- filename : string Name of file to read as an image file. This file may be gzip (``.gz``) or bzip2 (``.bz2``) compressed.
[ "Read", "an", "image", "file", "from", "disk" ]
ee9aef4746ff7a003b1457565acb13f5f1db0375
https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/image.py#L69-L92
train
planetarypy/planetaryimage
planetaryimage/image.py
PlanetaryImage.image
def image(self): """An Image like array of ``self.data`` convenient for image processing tasks * 2D array for single band, grayscale image data * 3D array for three band, RGB image data Enables working with ``self.data`` as if it were a PIL image. See https://planetaryimage.re...
python
def image(self): """An Image like array of ``self.data`` convenient for image processing tasks * 2D array for single band, grayscale image data * 3D array for three band, RGB image data Enables working with ``self.data`` as if it were a PIL image. See https://planetaryimage.re...
[ "def", "image", "(", "self", ")", ":", "if", "self", ".", "bands", "==", "1", ":", "return", "self", ".", "data", ".", "squeeze", "(", ")", "elif", "self", ".", "bands", "==", "3", ":", "return", "numpy", ".", "dstack", "(", "self", ".", "data", ...
An Image like array of ``self.data`` convenient for image processing tasks * 2D array for single band, grayscale image data * 3D array for three band, RGB image data Enables working with ``self.data`` as if it were a PIL image. See https://planetaryimage.readthedocs.io/en/latest/usage...
[ "An", "Image", "like", "array", "of", "self", ".", "data", "convenient", "for", "image", "processing", "tasks" ]
ee9aef4746ff7a003b1457565acb13f5f1db0375
https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/image.py#L131-L146
train
planetarypy/planetaryimage
planetaryimage/cubefile.py
CubeFile.apply_numpy_specials
def apply_numpy_specials(self, copy=True): """Convert isis special pixel values to numpy special pixel values. ======= ======= Isis Numpy ======= ======= Null nan Lrs -inf Lis -inf His inf ...
python
def apply_numpy_specials(self, copy=True): """Convert isis special pixel values to numpy special pixel values. ======= ======= Isis Numpy ======= ======= Null nan Lrs -inf Lis -inf His inf ...
[ "def", "apply_numpy_specials", "(", "self", ",", "copy", "=", "True", ")", ":", "if", "copy", ":", "data", "=", "self", ".", "data", ".", "astype", "(", "numpy", ".", "float64", ")", "elif", "self", ".", "data", ".", "dtype", "!=", "numpy", ".", "f...
Convert isis special pixel values to numpy special pixel values. ======= ======= Isis Numpy ======= ======= Null nan Lrs -inf Lis -inf His inf Hrs inf ======= ======= Par...
[ "Convert", "isis", "special", "pixel", "values", "to", "numpy", "special", "pixel", "values", "." ]
ee9aef4746ff7a003b1457565acb13f5f1db0375
https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/cubefile.py#L161-L199
train
planetarypy/planetaryimage
planetaryimage/pds3image.py
Pointer.parse
def parse(cls, value, record_bytes): """Parses the pointer label. Parameters ---------- pointer_data Supported values for `pointer_data` are:: ^PTR = nnn ^PTR = nnn <BYTES> ^PTR = "filename" ^PTR = ("filename")...
python
def parse(cls, value, record_bytes): """Parses the pointer label. Parameters ---------- pointer_data Supported values for `pointer_data` are:: ^PTR = nnn ^PTR = nnn <BYTES> ^PTR = "filename" ^PTR = ("filename")...
[ "def", "parse", "(", "cls", ",", "value", ",", "record_bytes", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "cls", "(", "value", ",", "0", ")", "if", "isinstance", "(", "value", ",", "list", ")", ...
Parses the pointer label. Parameters ---------- pointer_data Supported values for `pointer_data` are:: ^PTR = nnn ^PTR = nnn <BYTES> ^PTR = "filename" ^PTR = ("filename") ^PTR = ("filename", nnn) ...
[ "Parses", "the", "pointer", "label", "." ]
ee9aef4746ff7a003b1457565acb13f5f1db0375
https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/pds3image.py#L24-L58
train
planetarypy/planetaryimage
planetaryimage/pds3image.py
PDS3Image._save
def _save(self, file_to_write, overwrite): """Save PDS3Image object as PDS3 file. Parameters ---------- filename: Set filename for the pds image to be saved. Overwrite: Use this keyword to save image with same filename. Usage: image.save('temp.IMG', overwrite=True) ...
python
def _save(self, file_to_write, overwrite): """Save PDS3Image object as PDS3 file. Parameters ---------- filename: Set filename for the pds image to be saved. Overwrite: Use this keyword to save image with same filename. Usage: image.save('temp.IMG', overwrite=True) ...
[ "def", "_save", "(", "self", ",", "file_to_write", ",", "overwrite", ")", ":", "if", "overwrite", ":", "file_to_write", "=", "self", ".", "filename", "elif", "os", ".", "path", ".", "isfile", "(", "file_to_write", ")", ":", "msg", "=", "'File '", "+", ...
Save PDS3Image object as PDS3 file. Parameters ---------- filename: Set filename for the pds image to be saved. Overwrite: Use this keyword to save image with same filename. Usage: image.save('temp.IMG', overwrite=True)
[ "Save", "PDS3Image", "object", "as", "PDS3", "file", "." ]
ee9aef4746ff7a003b1457565acb13f5f1db0375
https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/pds3image.py#L129-L181
train
planetarypy/planetaryimage
planetaryimage/pds3image.py
PDS3Image._create_label
def _create_label(self, array): """Create sample PDS3 label for NumPy Array. It is called by 'image.py' to create PDS3Image object from Numpy Array. Returns ------- PVLModule label for the given NumPy array. Usage: self.label = _create_label(array) """ ...
python
def _create_label(self, array): """Create sample PDS3 label for NumPy Array. It is called by 'image.py' to create PDS3Image object from Numpy Array. Returns ------- PVLModule label for the given NumPy array. Usage: self.label = _create_label(array) """ ...
[ "def", "_create_label", "(", "self", ",", "array", ")", ":", "if", "len", "(", "array", ".", "shape", ")", "==", "3", ":", "bands", "=", "array", ".", "shape", "[", "0", "]", "lines", "=", "array", ".", "shape", "[", "1", "]", "line_samples", "="...
Create sample PDS3 label for NumPy Array. It is called by 'image.py' to create PDS3Image object from Numpy Array. Returns ------- PVLModule label for the given NumPy array. Usage: self.label = _create_label(array)
[ "Create", "sample", "PDS3", "label", "for", "NumPy", "Array", ".", "It", "is", "called", "by", "image", ".", "py", "to", "create", "PDS3Image", "object", "from", "Numpy", "Array", "." ]
ee9aef4746ff7a003b1457565acb13f5f1db0375
https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/pds3image.py#L183-L222
train
planetarypy/planetaryimage
planetaryimage/pds3image.py
PDS3Image._update_label
def _update_label(self, label, array): """Update PDS3 label for NumPy Array. It is called by '_create_label' to update label values such as, - ^IMAGE, RECORD_BYTES - STANDARD_DEVIATION - MAXIMUM, MINIMUM - MEDIAN, MEAN Returns ------- Upda...
python
def _update_label(self, label, array): """Update PDS3 label for NumPy Array. It is called by '_create_label' to update label values such as, - ^IMAGE, RECORD_BYTES - STANDARD_DEVIATION - MAXIMUM, MINIMUM - MEDIAN, MEAN Returns ------- Upda...
[ "def", "_update_label", "(", "self", ",", "label", ",", "array", ")", ":", "maximum", "=", "float", "(", "numpy", ".", "max", "(", "array", ")", ")", "mean", "=", "float", "(", "numpy", ".", "mean", "(", "array", ")", ")", "median", "=", "float", ...
Update PDS3 label for NumPy Array. It is called by '_create_label' to update label values such as, - ^IMAGE, RECORD_BYTES - STANDARD_DEVIATION - MAXIMUM, MINIMUM - MEDIAN, MEAN Returns ------- Update label module for the NumPy array. Usag...
[ "Update", "PDS3", "label", "for", "NumPy", "Array", ".", "It", "is", "called", "by", "_create_label", "to", "update", "label", "values", "such", "as", "-", "^IMAGE", "RECORD_BYTES", "-", "STANDARD_DEVIATION", "-", "MAXIMUM", "MINIMUM", "-", "MEDIAN", "MEAN" ]
ee9aef4746ff7a003b1457565acb13f5f1db0375
https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/pds3image.py#L224-L259
train
web-push-libs/encrypted-content-encoding
python/http_ece/__init__.py
iv
def iv(base, counter): """Generate an initialization vector. """ if (counter >> 64) != 0: raise ECEException(u"Counter too big") (mask,) = struct.unpack("!Q", base[4:]) return base[:4] + struct.pack("!Q", counter ^ mask)
python
def iv(base, counter): """Generate an initialization vector. """ if (counter >> 64) != 0: raise ECEException(u"Counter too big") (mask,) = struct.unpack("!Q", base[4:]) return base[:4] + struct.pack("!Q", counter ^ mask)
[ "def", "iv", "(", "base", ",", "counter", ")", ":", "if", "(", "counter", ">>", "64", ")", "!=", "0", ":", "raise", "ECEException", "(", "u\"Counter too big\"", ")", "(", "mask", ",", ")", "=", "struct", ".", "unpack", "(", "\"!Q\"", ",", "base", "...
Generate an initialization vector.
[ "Generate", "an", "initialization", "vector", "." ]
849aebea751752e17fc84a64ce1bbf65dc994e6c
https://github.com/web-push-libs/encrypted-content-encoding/blob/849aebea751752e17fc84a64ce1bbf65dc994e6c/python/http_ece/__init__.py#L164-L171
train
web-push-libs/encrypted-content-encoding
python/http_ece/__init__.py
encrypt
def encrypt(content, salt=None, key=None, private_key=None, dh=None, auth_secret=None, keyid=None, keylabel="P-256", rs=4096, version="aes128gcm"): """ Encrypt a data block :param content: block of data to encrypt :type content: str :param salt: Encryption salt ...
python
def encrypt(content, salt=None, key=None, private_key=None, dh=None, auth_secret=None, keyid=None, keylabel="P-256", rs=4096, version="aes128gcm"): """ Encrypt a data block :param content: block of data to encrypt :type content: str :param salt: Encryption salt ...
[ "def", "encrypt", "(", "content", ",", "salt", "=", "None", ",", "key", "=", "None", ",", "private_key", "=", "None", ",", "dh", "=", "None", ",", "auth_secret", "=", "None", ",", "keyid", "=", "None", ",", "keylabel", "=", "\"P-256\"", ",", "rs", ...
Encrypt a data block :param content: block of data to encrypt :type content: str :param salt: Encryption salt :type salt: str :param key: Encryption key data :type key: str :param private_key: DH private key :type key: object :param keyid: Internal key identifier for private key inf...
[ "Encrypt", "a", "data", "block" ]
849aebea751752e17fc84a64ce1bbf65dc994e6c
https://github.com/web-push-libs/encrypted-content-encoding/blob/849aebea751752e17fc84a64ce1bbf65dc994e6c/python/http_ece/__init__.py#L297-L405
train
varlink/python
varlink/error.py
VarlinkError.parameters
def parameters(self, namespaced=False): """returns the exception varlink error parameters""" if namespaced: return json.loads(json.dumps(self.args[0]['parameters']), object_hook=lambda d: SimpleNamespace(**d)) else: return self.args[0].get('parameters')
python
def parameters(self, namespaced=False): """returns the exception varlink error parameters""" if namespaced: return json.loads(json.dumps(self.args[0]['parameters']), object_hook=lambda d: SimpleNamespace(**d)) else: return self.args[0].get('parameters')
[ "def", "parameters", "(", "self", ",", "namespaced", "=", "False", ")", ":", "if", "namespaced", ":", "return", "json", ".", "loads", "(", "json", ".", "dumps", "(", "self", ".", "args", "[", "0", "]", "[", "'parameters'", "]", ")", ",", "object_hook...
returns the exception varlink error parameters
[ "returns", "the", "exception", "varlink", "error", "parameters" ]
b021a29dd9def06b03416d20e8b37be39c3edd33
https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/error.py#L66-L71
train
varlink/python
varlink/server.py
Service.handle
def handle(self, message, _server=None, _request=None): """This generator function handles any incoming message. Write any returned bytes to the output stream. >>> for outgoing_message in service.handle(incoming_message): >>> connection.write(outgoing_message) """ ...
python
def handle(self, message, _server=None, _request=None): """This generator function handles any incoming message. Write any returned bytes to the output stream. >>> for outgoing_message in service.handle(incoming_message): >>> connection.write(outgoing_message) """ ...
[ "def", "handle", "(", "self", ",", "message", ",", "_server", "=", "None", ",", "_request", "=", "None", ")", ":", "if", "not", "message", ":", "return", "if", "message", "[", "-", "1", "]", "==", "0", ":", "message", "=", "message", "[", ":", "-...
This generator function handles any incoming message. Write any returned bytes to the output stream. >>> for outgoing_message in service.handle(incoming_message): >>> connection.write(outgoing_message)
[ "This", "generator", "function", "handles", "any", "incoming", "message", "." ]
b021a29dd9def06b03416d20e8b37be39c3edd33
https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/server.py#L227-L252
train
varlink/python
varlink/server.py
Server.server_close
def server_close(self): """Called to clean-up the server. May be overridden. """ if self.remove_file: try: os.remove(self.remove_file) except: pass self.socket.close()
python
def server_close(self): """Called to clean-up the server. May be overridden. """ if self.remove_file: try: os.remove(self.remove_file) except: pass self.socket.close()
[ "def", "server_close", "(", "self", ")", ":", "if", "self", ".", "remove_file", ":", "try", ":", "os", ".", "remove", "(", "self", ".", "remove_file", ")", "except", ":", "pass", "self", ".", "socket", ".", "close", "(", ")" ]
Called to clean-up the server. May be overridden.
[ "Called", "to", "clean", "-", "up", "the", "server", "." ]
b021a29dd9def06b03416d20e8b37be39c3edd33
https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/server.py#L473-L484
train
varlink/python
varlink/client.py
Client.open
def open(self, interface_name, namespaced=False, connection=None): """Open a new connection and get a client interface handle with the varlink methods installed. :param interface_name: an interface name, which the service this client object is connected to, provides. ...
python
def open(self, interface_name, namespaced=False, connection=None): """Open a new connection and get a client interface handle with the varlink methods installed. :param interface_name: an interface name, which the service this client object is connected to, provides. ...
[ "def", "open", "(", "self", ",", "interface_name", ",", "namespaced", "=", "False", ",", "connection", "=", "None", ")", ":", "if", "not", "connection", ":", "connection", "=", "self", ".", "open_connection", "(", ")", "if", "interface_name", "not", "in", ...
Open a new connection and get a client interface handle with the varlink methods installed. :param interface_name: an interface name, which the service this client object is connected to, provides. :param namespaced: If arguments and return values are instances of SimpleN...
[ "Open", "a", "new", "connection", "and", "get", "a", "client", "interface", "handle", "with", "the", "varlink", "methods", "installed", "." ]
b021a29dd9def06b03416d20e8b37be39c3edd33
https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/client.py#L585-L606
train
varlink/python
varlink/client.py
Client.get_interfaces
def get_interfaces(self, socket_connection=None): """Returns the a list of Interface objects the service implements.""" if not socket_connection: socket_connection = self.open_connection() close_socket = True else: close_socket = False # noinspection ...
python
def get_interfaces(self, socket_connection=None): """Returns the a list of Interface objects the service implements.""" if not socket_connection: socket_connection = self.open_connection() close_socket = True else: close_socket = False # noinspection ...
[ "def", "get_interfaces", "(", "self", ",", "socket_connection", "=", "None", ")", ":", "if", "not", "socket_connection", ":", "socket_connection", "=", "self", ".", "open_connection", "(", ")", "close_socket", "=", "True", "else", ":", "close_socket", "=", "Fa...
Returns the a list of Interface objects the service implements.
[ "Returns", "the", "a", "list", "of", "Interface", "objects", "the", "service", "implements", "." ]
b021a29dd9def06b03416d20e8b37be39c3edd33
https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/client.py#L615-L630
train
varlink/python
varlink/client.py
Client.add_interface
def add_interface(self, interface): """Manually add or overwrite an interface definition from an Interface object. :param interface: an Interface() object """ if not isinstance(interface, Interface): raise TypeError self._interfaces[interface.name] = interface
python
def add_interface(self, interface): """Manually add or overwrite an interface definition from an Interface object. :param interface: an Interface() object """ if not isinstance(interface, Interface): raise TypeError self._interfaces[interface.name] = interface
[ "def", "add_interface", "(", "self", ",", "interface", ")", ":", "if", "not", "isinstance", "(", "interface", ",", "Interface", ")", ":", "raise", "TypeError", "self", ".", "_interfaces", "[", "interface", ".", "name", "]", "=", "interface" ]
Manually add or overwrite an interface definition from an Interface object. :param interface: an Interface() object
[ "Manually", "add", "or", "overwrite", "an", "interface", "definition", "from", "an", "Interface", "object", "." ]
b021a29dd9def06b03416d20e8b37be39c3edd33
https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/client.py#L650-L659
train
SINGROUP/SOAPLite
utilities/batchSoapPy.py
create
def create(atoms_list,N, L, cutoff = 0, all_atomtypes=[]): """Takes a trajectory xyz file and writes soap features """ myAlphas, myBetas = genBasis.getBasisFunc(cutoff, N) # get information about feature length n_datapoints = len(atoms_list) atoms = atoms_list[0] x = get_lastatom_soap(atoms,...
python
def create(atoms_list,N, L, cutoff = 0, all_atomtypes=[]): """Takes a trajectory xyz file and writes soap features """ myAlphas, myBetas = genBasis.getBasisFunc(cutoff, N) # get information about feature length n_datapoints = len(atoms_list) atoms = atoms_list[0] x = get_lastatom_soap(atoms,...
[ "def", "create", "(", "atoms_list", ",", "N", ",", "L", ",", "cutoff", "=", "0", ",", "all_atomtypes", "=", "[", "]", ")", ":", "myAlphas", ",", "myBetas", "=", "genBasis", ".", "getBasisFunc", "(", "cutoff", ",", "N", ")", "n_datapoints", "=", "len"...
Takes a trajectory xyz file and writes soap features
[ "Takes", "a", "trajectory", "xyz", "file", "and", "writes", "soap", "features" ]
80e27cc8d5b4c887011542c5a799583bfc6ff643
https://github.com/SINGROUP/SOAPLite/blob/80e27cc8d5b4c887011542c5a799583bfc6ff643/utilities/batchSoapPy.py#L21-L44
train
SINGROUP/SOAPLite
soaplite/getBasis.py
getPoly
def getPoly(rCut, nMax): """Used to calculate discrete vectors for the polynomial basis functions. Args: rCut(float): Radial cutoff nMax(int): Number of polynomial radial functions """ rCutVeryHard = rCut+5.0 rx = 0.5*rCutVeryHard*(x + 1) basisFunctions = [] for i in range(...
python
def getPoly(rCut, nMax): """Used to calculate discrete vectors for the polynomial basis functions. Args: rCut(float): Radial cutoff nMax(int): Number of polynomial radial functions """ rCutVeryHard = rCut+5.0 rx = 0.5*rCutVeryHard*(x + 1) basisFunctions = [] for i in range(...
[ "def", "getPoly", "(", "rCut", ",", "nMax", ")", ":", "rCutVeryHard", "=", "rCut", "+", "5.0", "rx", "=", "0.5", "*", "rCutVeryHard", "*", "(", "x", "+", "1", ")", "basisFunctions", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "nMax",...
Used to calculate discrete vectors for the polynomial basis functions. Args: rCut(float): Radial cutoff nMax(int): Number of polynomial radial functions
[ "Used", "to", "calculate", "discrete", "vectors", "for", "the", "polynomial", "basis", "functions", "." ]
80e27cc8d5b4c887011542c5a799583bfc6ff643
https://github.com/SINGROUP/SOAPLite/blob/80e27cc8d5b4c887011542c5a799583bfc6ff643/soaplite/getBasis.py#L303-L342
train
SINGROUP/SOAPLite
soaplite/core.py
_format_ase2clusgeo
def _format_ase2clusgeo(obj, all_atomtypes=None): """ Takes an ase Atoms object and returns numpy arrays and integers which are read by the internal clusgeo. Apos is currently a flattened out numpy array Args: obj(): all_atomtypes(): sort(): """ #atoms metadata total...
python
def _format_ase2clusgeo(obj, all_atomtypes=None): """ Takes an ase Atoms object and returns numpy arrays and integers which are read by the internal clusgeo. Apos is currently a flattened out numpy array Args: obj(): all_atomtypes(): sort(): """ #atoms metadata total...
[ "def", "_format_ase2clusgeo", "(", "obj", ",", "all_atomtypes", "=", "None", ")", ":", "totalAN", "=", "len", "(", "obj", ")", "if", "all_atomtypes", "is", "not", "None", ":", "atomtype_set", "=", "set", "(", "all_atomtypes", ")", "else", ":", "atomtype_se...
Takes an ase Atoms object and returns numpy arrays and integers which are read by the internal clusgeo. Apos is currently a flattened out numpy array Args: obj(): all_atomtypes(): sort():
[ "Takes", "an", "ase", "Atoms", "object", "and", "returns", "numpy", "arrays", "and", "integers", "which", "are", "read", "by", "the", "internal", "clusgeo", ".", "Apos", "is", "currently", "a", "flattened", "out", "numpy", "array" ]
80e27cc8d5b4c887011542c5a799583bfc6ff643
https://github.com/SINGROUP/SOAPLite/blob/80e27cc8d5b4c887011542c5a799583bfc6ff643/soaplite/core.py#L11-L44
train
SINGROUP/SOAPLite
soaplite/core.py
get_soap_structure
def get_soap_structure(obj, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0): """Get the RBF basis SOAP output for atoms in a finite structure. Args: obj(ase.Atoms): Atomic structure for which the SOAP output is calculated. alp: Alphas bet: Be...
python
def get_soap_structure(obj, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0): """Get the RBF basis SOAP output for atoms in a finite structure. Args: obj(ase.Atoms): Atomic structure for which the SOAP output is calculated. alp: Alphas bet: Be...
[ "def", "get_soap_structure", "(", "obj", ",", "alp", ",", "bet", ",", "rCut", "=", "5.0", ",", "nMax", "=", "5", ",", "Lmax", "=", "5", ",", "crossOver", "=", "True", ",", "all_atomtypes", "=", "None", ",", "eta", "=", "1.0", ")", ":", "Hpos", "=...
Get the RBF basis SOAP output for atoms in a finite structure. Args: obj(ase.Atoms): Atomic structure for which the SOAP output is calculated. alp: Alphas bet: Betas rCut: Radial cutoff. nMax: Maximum nmber of radial basis functions Lmax: Maximum spherica...
[ "Get", "the", "RBF", "basis", "SOAP", "output", "for", "atoms", "in", "a", "finite", "structure", "." ]
80e27cc8d5b4c887011542c5a799583bfc6ff643
https://github.com/SINGROUP/SOAPLite/blob/80e27cc8d5b4c887011542c5a799583bfc6ff643/soaplite/core.py#L172-L195
train
SINGROUP/SOAPLite
soaplite/core.py
get_periodic_soap_locals
def get_periodic_soap_locals(obj, Hpos, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0): """Get the RBF basis SOAP output for the given position in a periodic system. Args: obj(ase.Atoms): Atomic structure for which the SOAP output is calculated. alp...
python
def get_periodic_soap_locals(obj, Hpos, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0): """Get the RBF basis SOAP output for the given position in a periodic system. Args: obj(ase.Atoms): Atomic structure for which the SOAP output is calculated. alp...
[ "def", "get_periodic_soap_locals", "(", "obj", ",", "Hpos", ",", "alp", ",", "bet", ",", "rCut", "=", "5.0", ",", "nMax", "=", "5", ",", "Lmax", "=", "5", ",", "crossOver", "=", "True", ",", "all_atomtypes", "=", "None", ",", "eta", "=", "1.0", ")"...
Get the RBF basis SOAP output for the given position in a periodic system. Args: obj(ase.Atoms): Atomic structure for which the SOAP output is calculated. alp: Alphas bet: Betas rCut: Radial cutoff. nMax: Maximum nmber of radial basis functions Lmax: Maxi...
[ "Get", "the", "RBF", "basis", "SOAP", "output", "for", "the", "given", "position", "in", "a", "periodic", "system", "." ]
80e27cc8d5b4c887011542c5a799583bfc6ff643
https://github.com/SINGROUP/SOAPLite/blob/80e27cc8d5b4c887011542c5a799583bfc6ff643/soaplite/core.py#L198-L221
train
adrn/gala
gala/dynamics/orbit.py
Orbit.orbit_gen
def orbit_gen(self): """ Generator for iterating over each orbit. """ if self.norbits == 1: yield self else: for i in range(self.norbits): yield self[:, i]
python
def orbit_gen(self): """ Generator for iterating over each orbit. """ if self.norbits == 1: yield self else: for i in range(self.norbits): yield self[:, i]
[ "def", "orbit_gen", "(", "self", ")", ":", "if", "self", ".", "norbits", "==", "1", ":", "yield", "self", "else", ":", "for", "i", "in", "range", "(", "self", ".", "norbits", ")", ":", "yield", "self", "[", ":", ",", "i", "]" ]
Generator for iterating over each orbit.
[ "Generator", "for", "iterating", "over", "each", "orbit", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L294-L303
train
adrn/gala
gala/dynamics/orbit.py
Orbit.zmax
def zmax(self, return_times=False, func=np.mean, interp_kwargs=None, minimize_kwargs=None, approximate=False): """ Estimate the maximum ``z`` height of the orbit by identifying local maxima in the absolute value of the ``z`` position and interpolating between ti...
python
def zmax(self, return_times=False, func=np.mean, interp_kwargs=None, minimize_kwargs=None, approximate=False): """ Estimate the maximum ``z`` height of the orbit by identifying local maxima in the absolute value of the ``z`` position and interpolating between ti...
[ "def", "zmax", "(", "self", ",", "return_times", "=", "False", ",", "func", "=", "np", ".", "mean", ",", "interp_kwargs", "=", "None", ",", "minimize_kwargs", "=", "None", ",", "approximate", "=", "False", ")", ":", "if", "return_times", "and", "func", ...
Estimate the maximum ``z`` height of the orbit by identifying local maxima in the absolute value of the ``z`` position and interpolating between timesteps near the maxima. By default, this returns the mean of all local maxima. To get, e.g., the largest ``z`` excursion, pass in ``func=np...
[ "Estimate", "the", "maximum", "z", "height", "of", "the", "orbit", "by", "identifying", "local", "maxima", "in", "the", "absolute", "value", "of", "the", "z", "position", "and", "interpolating", "between", "timesteps", "near", "the", "maxima", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L550-L612
train
adrn/gala
gala/dynamics/orbit.py
Orbit.eccentricity
def eccentricity(self, **kw): r""" Returns the eccentricity computed from the mean apocenter and mean pericenter. .. math:: e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}} Parameters ---------- **kw Any keyword arguments ...
python
def eccentricity(self, **kw): r""" Returns the eccentricity computed from the mean apocenter and mean pericenter. .. math:: e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}} Parameters ---------- **kw Any keyword arguments ...
[ "def", "eccentricity", "(", "self", ",", "**", "kw", ")", ":", "r", "ra", "=", "self", ".", "apocenter", "(", "**", "kw", ")", "rp", "=", "self", ".", "pericenter", "(", "**", "kw", ")", "return", "(", "ra", "-", "rp", ")", "/", "(", "ra", "+...
r""" Returns the eccentricity computed from the mean apocenter and mean pericenter. .. math:: e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}} Parameters ---------- **kw Any keyword arguments passed to ``apocenter()`` and ...
[ "r", "Returns", "the", "eccentricity", "computed", "from", "the", "mean", "apocenter", "and", "mean", "pericenter", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L614-L637
train
adrn/gala
gala/dynamics/orbit.py
Orbit.estimate_period
def estimate_period(self, radial=True): """ Estimate the period of the orbit. By default, computes the radial period. If ``radial==False``, this returns period estimates for each dimension of the orbit. Parameters ---------- radial : bool (optional) W...
python
def estimate_period(self, radial=True): """ Estimate the period of the orbit. By default, computes the radial period. If ``radial==False``, this returns period estimates for each dimension of the orbit. Parameters ---------- radial : bool (optional) W...
[ "def", "estimate_period", "(", "self", ",", "radial", "=", "True", ")", ":", "if", "self", ".", "t", "is", "None", ":", "raise", "ValueError", "(", "\"To compute the period, a time array is needed.\"", "\" Specify a time array when creating this object.\"", ")", "if", ...
Estimate the period of the orbit. By default, computes the radial period. If ``radial==False``, this returns period estimates for each dimension of the orbit. Parameters ---------- radial : bool (optional) What period to estimate. If ``True``, estimates the radial ...
[ "Estimate", "the", "period", "of", "the", "orbit", ".", "By", "default", "computes", "the", "radial", "period", ".", "If", "radial", "==", "False", "this", "returns", "period", "estimates", "for", "each", "dimension", "of", "the", "orbit", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L639-L675
train
adrn/gala
gala/dynamics/orbit.py
Orbit.circulation
def circulation(self): """ Determine which axes the Orbit circulates around by checking whether there is a change of sign of the angular momentum about an axis. Returns a 2D array with ``ndim`` integers per orbit point. If a box orbit, all integers will be 0. A 1 indicates ...
python
def circulation(self): """ Determine which axes the Orbit circulates around by checking whether there is a change of sign of the angular momentum about an axis. Returns a 2D array with ``ndim`` integers per orbit point. If a box orbit, all integers will be 0. A 1 indicates ...
[ "def", "circulation", "(", "self", ")", ":", "L", "=", "self", ".", "angular_momentum", "(", ")", "if", "L", ".", "ndim", "==", "2", ":", "single_orbit", "=", "True", "L", "=", "L", "[", "...", ",", "None", "]", "else", ":", "single_orbit", "=", ...
Determine which axes the Orbit circulates around by checking whether there is a change of sign of the angular momentum about an axis. Returns a 2D array with ``ndim`` integers per orbit point. If a box orbit, all integers will be 0. A 1 indicates circulation about the corresponding axis....
[ "Determine", "which", "axes", "the", "Orbit", "circulates", "around", "by", "checking", "whether", "there", "is", "a", "change", "of", "sign", "of", "the", "angular", "momentum", "about", "an", "axis", ".", "Returns", "a", "2D", "array", "with", "ndim", "i...
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L680-L731
train
adrn/gala
gala/dynamics/orbit.py
Orbit.align_circulation_with_z
def align_circulation_with_z(self, circulation=None): """ If the input orbit is a tube orbit, this function aligns the circulation axis with the z axis and returns a copy. Parameters ---------- circulation : array_like (optional) Array of bits that specify th...
python
def align_circulation_with_z(self, circulation=None): """ If the input orbit is a tube orbit, this function aligns the circulation axis with the z axis and returns a copy. Parameters ---------- circulation : array_like (optional) Array of bits that specify th...
[ "def", "align_circulation_with_z", "(", "self", ",", "circulation", "=", "None", ")", ":", "if", "circulation", "is", "None", ":", "circulation", "=", "self", ".", "circulation", "(", ")", "circulation", "=", "atleast_2d", "(", "circulation", ",", "insert_axis...
If the input orbit is a tube orbit, this function aligns the circulation axis with the z axis and returns a copy. Parameters ---------- circulation : array_like (optional) Array of bits that specify the axis about which the orbit circulates. If not provided, will...
[ "If", "the", "input", "orbit", "is", "a", "tube", "orbit", "this", "function", "aligns", "the", "circulation", "axis", "with", "the", "z", "axis", "and", "returns", "a", "copy", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L733-L800
train
adrn/gala
gala/coordinates/greatcircle.py
greatcircle_to_greatcircle
def greatcircle_to_greatcircle(from_greatcircle_coord, to_greatcircle_frame): """Transform between two greatcircle frames.""" # This transform goes through the parent frames on each side. # from_frame -> from_frame.origin -> to_frame.origin -> to_frame intermediate_from =...
python
def greatcircle_to_greatcircle(from_greatcircle_coord, to_greatcircle_frame): """Transform between two greatcircle frames.""" # This transform goes through the parent frames on each side. # from_frame -> from_frame.origin -> to_frame.origin -> to_frame intermediate_from =...
[ "def", "greatcircle_to_greatcircle", "(", "from_greatcircle_coord", ",", "to_greatcircle_frame", ")", ":", "intermediate_from", "=", "from_greatcircle_coord", ".", "transform_to", "(", "from_greatcircle_coord", ".", "pole", ")", "intermediate_to", "=", "intermediate_from", ...
Transform between two greatcircle frames.
[ "Transform", "between", "two", "greatcircle", "frames", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/greatcircle.py#L21-L31
train
adrn/gala
gala/coordinates/greatcircle.py
reference_to_greatcircle
def reference_to_greatcircle(reference_frame, greatcircle_frame): """Convert a reference coordinate to a great circle frame.""" # Define rotation matrices along the position angle vector, and # relative to the origin. pole = greatcircle_frame.pole.transform_to(coord.ICRS) ra0 = greatcircle_frame.ra...
python
def reference_to_greatcircle(reference_frame, greatcircle_frame): """Convert a reference coordinate to a great circle frame.""" # Define rotation matrices along the position angle vector, and # relative to the origin. pole = greatcircle_frame.pole.transform_to(coord.ICRS) ra0 = greatcircle_frame.ra...
[ "def", "reference_to_greatcircle", "(", "reference_frame", ",", "greatcircle_frame", ")", ":", "pole", "=", "greatcircle_frame", ".", "pole", ".", "transform_to", "(", "coord", ".", "ICRS", ")", "ra0", "=", "greatcircle_frame", ".", "ra0", "center", "=", "greatc...
Convert a reference coordinate to a great circle frame.
[ "Convert", "a", "reference", "coordinate", "to", "a", "great", "circle", "frame", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/greatcircle.py#L34-L70
train
adrn/gala
gala/coordinates/greatcircle.py
pole_from_endpoints
def pole_from_endpoints(coord1, coord2): """Compute the pole from a great circle that connects the two specified coordinates. This assumes a right-handed rule from coord1 to coord2: the pole is the north pole under that assumption. Parameters ---------- coord1 : `~astropy.coordinates.SkyCo...
python
def pole_from_endpoints(coord1, coord2): """Compute the pole from a great circle that connects the two specified coordinates. This assumes a right-handed rule from coord1 to coord2: the pole is the north pole under that assumption. Parameters ---------- coord1 : `~astropy.coordinates.SkyCo...
[ "def", "pole_from_endpoints", "(", "coord1", ",", "coord2", ")", ":", "c1", "=", "coord1", ".", "cartesian", "/", "coord1", ".", "cartesian", ".", "norm", "(", ")", "coord2", "=", "coord2", ".", "transform_to", "(", "coord1", ".", "frame", ")", "c2", "...
Compute the pole from a great circle that connects the two specified coordinates. This assumes a right-handed rule from coord1 to coord2: the pole is the north pole under that assumption. Parameters ---------- coord1 : `~astropy.coordinates.SkyCoord` Coordinate of one point on a great ...
[ "Compute", "the", "pole", "from", "a", "great", "circle", "that", "connects", "the", "two", "specified", "coordinates", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/greatcircle.py#L270-L296
train
adrn/gala
gala/coordinates/greatcircle.py
sph_midpoint
def sph_midpoint(coord1, coord2): """Compute the midpoint between two points on the sphere. Parameters ---------- coord1 : `~astropy.coordinates.SkyCoord` Coordinate of one point on a great circle. coord2 : `~astropy.coordinates.SkyCoord` Coordinate of the other point on a great cir...
python
def sph_midpoint(coord1, coord2): """Compute the midpoint between two points on the sphere. Parameters ---------- coord1 : `~astropy.coordinates.SkyCoord` Coordinate of one point on a great circle. coord2 : `~astropy.coordinates.SkyCoord` Coordinate of the other point on a great cir...
[ "def", "sph_midpoint", "(", "coord1", ",", "coord2", ")", ":", "c1", "=", "coord1", ".", "cartesian", "/", "coord1", ".", "cartesian", ".", "norm", "(", ")", "coord2", "=", "coord2", ".", "transform_to", "(", "coord1", ".", "frame", ")", "c2", "=", "...
Compute the midpoint between two points on the sphere. Parameters ---------- coord1 : `~astropy.coordinates.SkyCoord` Coordinate of one point on a great circle. coord2 : `~astropy.coordinates.SkyCoord` Coordinate of the other point on a great circle. Returns ------- midpt :...
[ "Compute", "the", "midpoint", "between", "two", "points", "on", "the", "sphere", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/greatcircle.py#L299-L322
train
adrn/gala
gala/coordinates/pm_cov_transform.py
get_uv_tan
def get_uv_tan(c): """Get tangent plane basis vectors on the unit sphere at the given spherical coordinates. """ l = c.spherical.lon b = c.spherical.lat p = np.array([-np.sin(l), np.cos(l), np.zeros_like(l.value)]).T q = np.array([-np.cos(l)*np.sin(b), -np.sin(l)*np.sin(b), np.cos(b)]).T ...
python
def get_uv_tan(c): """Get tangent plane basis vectors on the unit sphere at the given spherical coordinates. """ l = c.spherical.lon b = c.spherical.lat p = np.array([-np.sin(l), np.cos(l), np.zeros_like(l.value)]).T q = np.array([-np.cos(l)*np.sin(b), -np.sin(l)*np.sin(b), np.cos(b)]).T ...
[ "def", "get_uv_tan", "(", "c", ")", ":", "l", "=", "c", ".", "spherical", ".", "lon", "b", "=", "c", ".", "spherical", ".", "lat", "p", "=", "np", ".", "array", "(", "[", "-", "np", ".", "sin", "(", "l", ")", ",", "np", ".", "cos", "(", "...
Get tangent plane basis vectors on the unit sphere at the given spherical coordinates.
[ "Get", "tangent", "plane", "basis", "vectors", "on", "the", "unit", "sphere", "at", "the", "given", "spherical", "coordinates", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/pm_cov_transform.py#L8-L18
train
adrn/gala
gala/coordinates/pm_cov_transform.py
transform_pm_cov
def transform_pm_cov(c, cov, to_frame): """Transform a proper motion covariance matrix to a new frame. Parameters ---------- c : `~astropy.coordinates.SkyCoord` The sky coordinates of the sources in the initial coordinate frame. cov : array_like The covariance matrix of the proper m...
python
def transform_pm_cov(c, cov, to_frame): """Transform a proper motion covariance matrix to a new frame. Parameters ---------- c : `~astropy.coordinates.SkyCoord` The sky coordinates of the sources in the initial coordinate frame. cov : array_like The covariance matrix of the proper m...
[ "def", "transform_pm_cov", "(", "c", ",", "cov", ",", "to_frame", ")", ":", "if", "c", ".", "isscalar", "and", "cov", ".", "shape", "!=", "(", "2", ",", "2", ")", ":", "raise", "ValueError", "(", "'If input coordinate object is a scalar coordinate, '", "'the...
Transform a proper motion covariance matrix to a new frame. Parameters ---------- c : `~astropy.coordinates.SkyCoord` The sky coordinates of the sources in the initial coordinate frame. cov : array_like The covariance matrix of the proper motions. Must have same length as the in...
[ "Transform", "a", "proper", "motion", "covariance", "matrix", "to", "a", "new", "frame", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/pm_cov_transform.py#L62-L121
train
adrn/gala
gala/potential/frame/builtin/transformations.py
rodrigues_axis_angle_rotate
def rodrigues_axis_angle_rotate(x, vec, theta): """ Rotated the input vector or set of vectors `x` around the axis `vec` by the angle `theta`. Parameters ---------- x : array_like The vector or array of vectors to transform. Must have shape """ x = np.array(x).T vec = np.a...
python
def rodrigues_axis_angle_rotate(x, vec, theta): """ Rotated the input vector or set of vectors `x` around the axis `vec` by the angle `theta`. Parameters ---------- x : array_like The vector or array of vectors to transform. Must have shape """ x = np.array(x).T vec = np.a...
[ "def", "rodrigues_axis_angle_rotate", "(", "x", ",", "vec", ",", "theta", ")", ":", "x", "=", "np", ".", "array", "(", "x", ")", ".", "T", "vec", "=", "np", ".", "array", "(", "vec", ")", ".", "T", "theta", "=", "np", ".", "array", "(", "theta"...
Rotated the input vector or set of vectors `x` around the axis `vec` by the angle `theta`. Parameters ---------- x : array_like The vector or array of vectors to transform. Must have shape
[ "Rotated", "the", "input", "vector", "or", "set", "of", "vectors", "x", "around", "the", "axis", "vec", "by", "the", "angle", "theta", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L10-L29
train
adrn/gala
gala/potential/frame/builtin/transformations.py
z_angle_rotate
def z_angle_rotate(xy, theta): """ Rotated the input vector or set of vectors `xy` by the angle `theta`. Parameters ---------- xy : array_like The vector or array of vectors to transform. Must have shape """ xy = np.array(xy).T theta = np.array(theta).T out = np.zeros_lik...
python
def z_angle_rotate(xy, theta): """ Rotated the input vector or set of vectors `xy` by the angle `theta`. Parameters ---------- xy : array_like The vector or array of vectors to transform. Must have shape """ xy = np.array(xy).T theta = np.array(theta).T out = np.zeros_lik...
[ "def", "z_angle_rotate", "(", "xy", ",", "theta", ")", ":", "xy", "=", "np", ".", "array", "(", "xy", ")", ".", "T", "theta", "=", "np", ".", "array", "(", "theta", ")", ".", "T", "out", "=", "np", ".", "zeros_like", "(", "xy", ")", "out", "[...
Rotated the input vector or set of vectors `xy` by the angle `theta`. Parameters ---------- xy : array_like The vector or array of vectors to transform. Must have shape
[ "Rotated", "the", "input", "vector", "or", "set", "of", "vectors", "xy", "by", "the", "angle", "theta", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L31-L49
train
adrn/gala
gala/potential/frame/builtin/transformations.py
static_to_constantrotating
def static_to_constantrotating(frame_i, frame_r, w, t=None): """ Transform from an inertial static frame to a rotating frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynam...
python
def static_to_constantrotating(frame_i, frame_r, w, t=None): """ Transform from an inertial static frame to a rotating frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynam...
[ "def", "static_to_constantrotating", "(", "frame_i", ",", "frame_r", ",", "w", ",", "t", "=", "None", ")", ":", "return", "_constantrotating_static_helper", "(", "frame_r", "=", "frame_r", ",", "frame_i", "=", "frame_i", ",", "w", "=", "w", ",", "t", "=", ...
Transform from an inertial static frame to a rotating frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit` t : quantity_like (optional) Required if input coo...
[ "Transform", "from", "an", "inertial", "static", "frame", "to", "a", "rotating", "frame", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L100-L120
train
adrn/gala
gala/potential/frame/builtin/transformations.py
constantrotating_to_static
def constantrotating_to_static(frame_r, frame_i, w, t=None): """ Transform from a constantly rotating frame to a static, inertial frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `...
python
def constantrotating_to_static(frame_r, frame_i, w, t=None): """ Transform from a constantly rotating frame to a static, inertial frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `...
[ "def", "constantrotating_to_static", "(", "frame_r", ",", "frame_i", ",", "w", ",", "t", "=", "None", ")", ":", "return", "_constantrotating_static_helper", "(", "frame_r", "=", "frame_r", ",", "frame_i", "=", "frame_i", ",", "w", "=", "w", ",", "t", "=", ...
Transform from a constantly rotating frame to a static, inertial frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit` t : quantity_like (optional) Required i...
[ "Transform", "from", "a", "constantly", "rotating", "frame", "to", "a", "static", "inertial", "frame", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L122-L142
train
adrn/gala
gala/potential/potential/io.py
to_dict
def to_dict(potential): """ Turn a potential object into a dictionary that fully specifies the state of the object. Parameters ---------- potential : :class:`~gala.potential.PotentialBase` The instantiated :class:`~gala.potential.PotentialBase` object. """ from .. import potent...
python
def to_dict(potential): """ Turn a potential object into a dictionary that fully specifies the state of the object. Parameters ---------- potential : :class:`~gala.potential.PotentialBase` The instantiated :class:`~gala.potential.PotentialBase` object. """ from .. import potent...
[ "def", "to_dict", "(", "potential", ")", ":", "from", ".", ".", "import", "potential", "as", "gp", "if", "isinstance", "(", "potential", ",", "gp", ".", "CompositePotential", ")", ":", "d", "=", "dict", "(", ")", "d", "[", "'class'", "]", "=", "poten...
Turn a potential object into a dictionary that fully specifies the state of the object. Parameters ---------- potential : :class:`~gala.potential.PotentialBase` The instantiated :class:`~gala.potential.PotentialBase` object.
[ "Turn", "a", "potential", "object", "into", "a", "dictionary", "that", "fully", "specifies", "the", "state", "of", "the", "object", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/io.py#L148-L179
train
adrn/gala
gala/integrate/core.py
Integrator._prepare_ws
def _prepare_ws(self, w0, mmap, n_steps): """ Decide how to make the return array. If mmap is False, this returns a full array of zeros, but with the correct shape as the output. If mmap is True, return a pointer to a memory-mapped array. The latter is particularly useful for int...
python
def _prepare_ws(self, w0, mmap, n_steps): """ Decide how to make the return array. If mmap is False, this returns a full array of zeros, but with the correct shape as the output. If mmap is True, return a pointer to a memory-mapped array. The latter is particularly useful for int...
[ "def", "_prepare_ws", "(", "self", ",", "w0", ",", "mmap", ",", "n_steps", ")", ":", "from", ".", ".", "dynamics", "import", "PhaseSpacePosition", "if", "not", "isinstance", "(", "w0", ",", "PhaseSpacePosition", ")", ":", "w0", "=", "PhaseSpacePosition", "...
Decide how to make the return array. If mmap is False, this returns a full array of zeros, but with the correct shape as the output. If mmap is True, return a pointer to a memory-mapped array. The latter is particularly useful for integrating a large number of orbits or integrating a lar...
[ "Decide", "how", "to", "make", "the", "return", "array", ".", "If", "mmap", "is", "False", "this", "returns", "a", "full", "array", "of", "zeros", "but", "with", "the", "correct", "shape", "as", "the", "output", ".", "If", "mmap", "is", "True", "return...
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/integrate/core.py#L44-L78
train
adrn/gala
gala/dynamics/nonlinear.py
fast_lyapunov_max
def fast_lyapunov_max(w0, hamiltonian, dt, n_steps, d0=1e-5, n_steps_per_pullback=10, noffset_orbits=2, t1=0., atol=1E-10, rtol=1E-10, nmax=0, return_orbit=True): """ Compute the maximum Lyapunov exponent using a C-implemented estimator that uses the DOPRI853 inte...
python
def fast_lyapunov_max(w0, hamiltonian, dt, n_steps, d0=1e-5, n_steps_per_pullback=10, noffset_orbits=2, t1=0., atol=1E-10, rtol=1E-10, nmax=0, return_orbit=True): """ Compute the maximum Lyapunov exponent using a C-implemented estimator that uses the DOPRI853 inte...
[ "def", "fast_lyapunov_max", "(", "w0", ",", "hamiltonian", ",", "dt", ",", "n_steps", ",", "d0", "=", "1e-5", ",", "n_steps_per_pullback", "=", "10", ",", "noffset_orbits", "=", "2", ",", "t1", "=", "0.", ",", "atol", "=", "1E-10", ",", "rtol", "=", ...
Compute the maximum Lyapunov exponent using a C-implemented estimator that uses the DOPRI853 integrator. Parameters ---------- w0 : `~gala.dynamics.PhaseSpacePosition`, array_like Initial conditions. hamiltonian : `~gala.potential.Hamiltonian` dt : numeric Timestep. n_steps ...
[ "Compute", "the", "maximum", "Lyapunov", "exponent", "using", "a", "C", "-", "implemented", "estimator", "that", "uses", "the", "DOPRI853", "integrator", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/nonlinear.py#L12-L95
train
adrn/gala
gala/dynamics/nonlinear.py
surface_of_section
def surface_of_section(orbit, plane_ix, interpolate=False): """ Generate and return a surface of section from the given orbit. .. warning:: This is an experimental function and the API may change. Parameters ---------- orbit : `~gala.dynamics.Orbit` plane_ix : int Integer ...
python
def surface_of_section(orbit, plane_ix, interpolate=False): """ Generate and return a surface of section from the given orbit. .. warning:: This is an experimental function and the API may change. Parameters ---------- orbit : `~gala.dynamics.Orbit` plane_ix : int Integer ...
[ "def", "surface_of_section", "(", "orbit", ",", "plane_ix", ",", "interpolate", "=", "False", ")", ":", "w", "=", "orbit", ".", "w", "(", ")", "if", "w", ".", "ndim", "==", "2", ":", "w", "=", "w", "[", "...", ",", "None", "]", "ndim", ",", "nt...
Generate and return a surface of section from the given orbit. .. warning:: This is an experimental function and the API may change. Parameters ---------- orbit : `~gala.dynamics.Orbit` plane_ix : int Integer that represents the coordinate to record crossings in. For examp...
[ "Generate", "and", "return", "a", "surface", "of", "section", "from", "the", "given", "orbit", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/nonlinear.py#L207-L263
train
adrn/gala
gala/potential/potential/core.py
PotentialBase._remove_units
def _remove_units(self, x): """ Always returns an array. If a Quantity is passed in, it converts to the units associated with this object and returns the value. """ if hasattr(x, 'unit'): x = x.decompose(self.units).value else: x = np.array(x) ...
python
def _remove_units(self, x): """ Always returns an array. If a Quantity is passed in, it converts to the units associated with this object and returns the value. """ if hasattr(x, 'unit'): x = x.decompose(self.units).value else: x = np.array(x) ...
[ "def", "_remove_units", "(", "self", ",", "x", ")", ":", "if", "hasattr", "(", "x", ",", "'unit'", ")", ":", "x", "=", "x", ".", "decompose", "(", "self", ".", "units", ")", ".", "value", "else", ":", "x", "=", "np", ".", "array", "(", "x", "...
Always returns an array. If a Quantity is passed in, it converts to the units associated with this object and returns the value.
[ "Always", "returns", "an", "array", ".", "If", "a", "Quantity", "is", "passed", "in", "it", "converts", "to", "the", "units", "associated", "with", "this", "object", "and", "returns", "the", "value", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/core.py#L96-L107
train
adrn/gala
gala/potential/potential/core.py
PotentialBase.mass_enclosed
def mass_enclosed(self, q, t=0.): """ Estimate the mass enclosed within the given position by assuming the potential is spherical. Parameters ---------- q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like Position(s) to estimate the...
python
def mass_enclosed(self, q, t=0.): """ Estimate the mass enclosed within the given position by assuming the potential is spherical. Parameters ---------- q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like Position(s) to estimate the...
[ "def", "mass_enclosed", "(", "self", ",", "q", ",", "t", "=", "0.", ")", ":", "q", "=", "self", ".", "_remove_units_prepare_shape", "(", "q", ")", "orig_shape", ",", "q", "=", "self", ".", "_get_c_valid_arr", "(", "q", ")", "t", "=", "self", ".", "...
Estimate the mass enclosed within the given position by assuming the potential is spherical. Parameters ---------- q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like Position(s) to estimate the enclossed mass. Returns ------- ...
[ "Estimate", "the", "mass", "enclosed", "within", "the", "given", "position", "by", "assuming", "the", "potential", "is", "spherical", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/core.py#L246-L291
train
adrn/gala
gala/potential/potential/core.py
PotentialBase.circular_velocity
def circular_velocity(self, q, t=0.): """ Estimate the circular velocity at the given position assuming the potential is spherical. Parameters ---------- q : array_like, numeric Position(s) to estimate the circular velocity. Returns ------- ...
python
def circular_velocity(self, q, t=0.): """ Estimate the circular velocity at the given position assuming the potential is spherical. Parameters ---------- q : array_like, numeric Position(s) to estimate the circular velocity. Returns ------- ...
[ "def", "circular_velocity", "(", "self", ",", "q", ",", "t", "=", "0.", ")", ":", "q", "=", "self", ".", "_remove_units_prepare_shape", "(", "q", ")", "r", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "q", "**", "2", ",", "axis", "=", "0...
Estimate the circular velocity at the given position assuming the potential is spherical. Parameters ---------- q : array_like, numeric Position(s) to estimate the circular velocity. Returns ------- vcirc : `~astropy.units.Quantity` Circu...
[ "Estimate", "the", "circular", "velocity", "at", "the", "given", "position", "assuming", "the", "potential", "is", "spherical", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/core.py#L293-L318
train
adrn/gala
gala/potential/potential/util.py
format_doc
def format_doc(*args, **kwargs): """ Replaces the docstring of the decorated object and then formats it. Modeled after astropy.utils.decorators.format_doc """ def set_docstring(obj): # None means: use the objects __doc__ doc = obj.__doc__ # Delete documentation in this case...
python
def format_doc(*args, **kwargs): """ Replaces the docstring of the decorated object and then formats it. Modeled after astropy.utils.decorators.format_doc """ def set_docstring(obj): # None means: use the objects __doc__ doc = obj.__doc__ # Delete documentation in this case...
[ "def", "format_doc", "(", "*", "args", ",", "**", "kwargs", ")", ":", "def", "set_docstring", "(", "obj", ")", ":", "doc", "=", "obj", ".", "__doc__", "obj", ".", "__doc__", "=", "None", "kwargs", "[", "'__doc__'", "]", "=", "obj", ".", "__doc__", ...
Replaces the docstring of the decorated object and then formats it. Modeled after astropy.utils.decorators.format_doc
[ "Replaces", "the", "docstring", "of", "the", "decorated", "object", "and", "then", "formats", "it", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/util.py#L165-L184
train
adrn/gala
gala/io.py
quantity_to_hdf5
def quantity_to_hdf5(f, key, q): """ Turn an Astropy Quantity object into something we can write out to an HDF5 file. Parameters ---------- f : :class:`h5py.File`, :class:`h5py.Group`, :class:`h5py.DataSet` key : str The name. q : float, `astropy.units.Quantity` The quan...
python
def quantity_to_hdf5(f, key, q): """ Turn an Astropy Quantity object into something we can write out to an HDF5 file. Parameters ---------- f : :class:`h5py.File`, :class:`h5py.Group`, :class:`h5py.DataSet` key : str The name. q : float, `astropy.units.Quantity` The quan...
[ "def", "quantity_to_hdf5", "(", "f", ",", "key", ",", "q", ")", ":", "if", "hasattr", "(", "q", ",", "'unit'", ")", ":", "f", "[", "key", "]", "=", "q", ".", "value", "f", "[", "key", "]", ".", "attrs", "[", "'unit'", "]", "=", "str", "(", ...
Turn an Astropy Quantity object into something we can write out to an HDF5 file. Parameters ---------- f : :class:`h5py.File`, :class:`h5py.Group`, :class:`h5py.DataSet` key : str The name. q : float, `astropy.units.Quantity` The quantity.
[ "Turn", "an", "Astropy", "Quantity", "object", "into", "something", "we", "can", "write", "out", "to", "an", "HDF5", "file", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/io.py#L27-L48
train
adrn/gala
gala/units.py
UnitSystem.get_constant
def get_constant(self, name): """ Retrieve a constant with specified name in this unit system. Parameters ---------- name : str The name of the constant, e.g., G. Returns ------- const : float The value of the constant represented...
python
def get_constant(self, name): """ Retrieve a constant with specified name in this unit system. Parameters ---------- name : str The name of the constant, e.g., G. Returns ------- const : float The value of the constant represented...
[ "def", "get_constant", "(", "self", ",", "name", ")", ":", "try", ":", "c", "=", "getattr", "(", "const", ",", "name", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", "\"Constant name '{}' doesn't exist in astropy.constants\"", ".", "format", "...
Retrieve a constant with specified name in this unit system. Parameters ---------- name : str The name of the constant, e.g., G. Returns ------- const : float The value of the constant represented in this unit system. Examples --...
[ "Retrieve", "a", "constant", "with", "specified", "name", "in", "this", "unit", "system", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/units.py#L160-L187
train
adrn/gala
gala/util.py
atleast_2d
def atleast_2d(*arys, **kwargs): """ View inputs as arrays with at least two dimensions. Parameters ---------- arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are pre...
python
def atleast_2d(*arys, **kwargs): """ View inputs as arrays with at least two dimensions. Parameters ---------- arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are pre...
[ "def", "atleast_2d", "(", "*", "arys", ",", "**", "kwargs", ")", ":", "insert_axis", "=", "kwargs", ".", "pop", "(", "'insert_axis'", ",", "0", ")", "slc", "=", "[", "slice", "(", "None", ")", "]", "*", "2", "slc", "[", "insert_axis", "]", "=", "...
View inputs as arrays with at least two dimensions. Parameters ---------- arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved. insert_axis : int (optional) ...
[ "View", "inputs", "as", "arrays", "with", "at", "least", "two", "dimensions", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/util.py#L113-L170
train
adrn/gala
gala/coordinates/quaternion.py
Quaternion.from_v_theta
def from_v_theta(cls, v, theta): """ Create a quaternion from unit vector v and rotation angle theta. Returns ------- q : :class:`gala.coordinates.Quaternion` A ``Quaternion`` instance. """ theta = np.asarray(theta) v = np.asarray(v) ...
python
def from_v_theta(cls, v, theta): """ Create a quaternion from unit vector v and rotation angle theta. Returns ------- q : :class:`gala.coordinates.Quaternion` A ``Quaternion`` instance. """ theta = np.asarray(theta) v = np.asarray(v) ...
[ "def", "from_v_theta", "(", "cls", ",", "v", ",", "theta", ")", ":", "theta", "=", "np", ".", "asarray", "(", "theta", ")", "v", "=", "np", ".", "asarray", "(", "v", ")", "s", "=", "np", ".", "sin", "(", "0.5", "*", "theta", ")", "c", "=", ...
Create a quaternion from unit vector v and rotation angle theta. Returns ------- q : :class:`gala.coordinates.Quaternion` A ``Quaternion`` instance.
[ "Create", "a", "quaternion", "from", "unit", "vector", "v", "and", "rotation", "angle", "theta", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/quaternion.py#L27-L45
train
adrn/gala
gala/coordinates/quaternion.py
Quaternion.random
def random(cls): """ Randomly sample a Quaternion from a distribution uniform in 3D rotation angles. https://www-preview.ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf Returns ------- q : :class:`gala.coordinates.Quaternion` ...
python
def random(cls): """ Randomly sample a Quaternion from a distribution uniform in 3D rotation angles. https://www-preview.ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf Returns ------- q : :class:`gala.coordinates.Quaternion` ...
[ "def", "random", "(", "cls", ")", ":", "s", "=", "np", ".", "random", ".", "uniform", "(", ")", "s1", "=", "np", ".", "sqrt", "(", "1", "-", "s", ")", "s2", "=", "np", ".", "sqrt", "(", "s", ")", "t1", "=", "np", ".", "random", ".", "unif...
Randomly sample a Quaternion from a distribution uniform in 3D rotation angles. https://www-preview.ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf Returns ------- q : :class:`gala.coordinates.Quaternion` A randomly sampled ``Quaternion`` ins...
[ "Randomly", "sample", "a", "Quaternion", "from", "a", "distribution", "uniform", "in", "3D", "rotation", "angles", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/quaternion.py#L112-L137
train
adrn/gala
gala/integrate/pyintegrators/leapfrog.py
LeapfrogIntegrator.step
def step(self, t, x_im1, v_im1_2, dt): """ Step forward the positions and velocities by the given timestep. Parameters ---------- dt : numeric The timestep to move forward. """ x_i = x_im1 + v_im1_2 * dt F_i = self.F(t, np.vstack((x_i, v_im1_...
python
def step(self, t, x_im1, v_im1_2, dt): """ Step forward the positions and velocities by the given timestep. Parameters ---------- dt : numeric The timestep to move forward. """ x_i = x_im1 + v_im1_2 * dt F_i = self.F(t, np.vstack((x_i, v_im1_...
[ "def", "step", "(", "self", ",", "t", ",", "x_im1", ",", "v_im1_2", ",", "dt", ")", ":", "x_i", "=", "x_im1", "+", "v_im1_2", "*", "dt", "F_i", "=", "self", ".", "F", "(", "t", ",", "np", ".", "vstack", "(", "(", "x_i", ",", "v_im1_2", ")", ...
Step forward the positions and velocities by the given timestep. Parameters ---------- dt : numeric The timestep to move forward.
[ "Step", "forward", "the", "positions", "and", "velocities", "by", "the", "given", "timestep", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/integrate/pyintegrators/leapfrog.py#L93-L110
train
adrn/gala
gala/dynamics/actionangle.py
fit_isochrone
def fit_isochrone(orbit, m0=2E11, b0=1., minimize_kwargs=None): r""" Fit the toy Isochrone potential to the sum of the energy residuals relative to the mean energy by minimizing the function .. math:: f(m,b) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm iso}(x_i\,|\,m,b) - <E>)^2 TODO: This shou...
python
def fit_isochrone(orbit, m0=2E11, b0=1., minimize_kwargs=None): r""" Fit the toy Isochrone potential to the sum of the energy residuals relative to the mean energy by minimizing the function .. math:: f(m,b) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm iso}(x_i\,|\,m,b) - <E>)^2 TODO: This shou...
[ "def", "fit_isochrone", "(", "orbit", ",", "m0", "=", "2E11", ",", "b0", "=", "1.", ",", "minimize_kwargs", "=", "None", ")", ":", "r", "pot", "=", "orbit", ".", "hamiltonian", ".", "potential", "if", "pot", "is", "None", ":", "raise", "ValueError", ...
r""" Fit the toy Isochrone potential to the sum of the energy residuals relative to the mean energy by minimizing the function .. math:: f(m,b) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm iso}(x_i\,|\,m,b) - <E>)^2 TODO: This should fail if the Hamiltonian associated with the orbit has a...
[ "r", "Fit", "the", "toy", "Isochrone", "potential", "to", "the", "sum", "of", "the", "energy", "residuals", "relative", "to", "the", "mean", "energy", "by", "minimizing", "the", "function" ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/actionangle.py#L78-L140
train
adrn/gala
gala/dynamics/actionangle.py
fit_harmonic_oscillator
def fit_harmonic_oscillator(orbit, omega0=[1., 1, 1], minimize_kwargs=None): r""" Fit the toy harmonic oscillator potential to the sum of the energy residuals relative to the mean energy by minimizing the function .. math:: f(\boldsymbol{\omega}) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm sho}(x_i...
python
def fit_harmonic_oscillator(orbit, omega0=[1., 1, 1], minimize_kwargs=None): r""" Fit the toy harmonic oscillator potential to the sum of the energy residuals relative to the mean energy by minimizing the function .. math:: f(\boldsymbol{\omega}) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm sho}(x_i...
[ "def", "fit_harmonic_oscillator", "(", "orbit", ",", "omega0", "=", "[", "1.", ",", "1", ",", "1", "]", ",", "minimize_kwargs", "=", "None", ")", ":", "r", "omega0", "=", "np", ".", "atleast_1d", "(", "omega0", ")", "pot", "=", "orbit", ".", "hamilto...
r""" Fit the toy harmonic oscillator potential to the sum of the energy residuals relative to the mean energy by minimizing the function .. math:: f(\boldsymbol{\omega}) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm sho}(x_i\,|\,\boldsymbol{\omega}) - <E>)^2 TODO: This should fail if the Hamiltonian...
[ "r", "Fit", "the", "toy", "harmonic", "oscillator", "potential", "to", "the", "sum", "of", "the", "energy", "residuals", "relative", "to", "the", "mean", "energy", "by", "minimizing", "the", "function" ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/actionangle.py#L142-L194
train
adrn/gala
gala/dynamics/actionangle.py
check_angle_sampling
def check_angle_sampling(nvecs, angles): """ Returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n. Parameters ---------- nvecs ...
python
def check_angle_sampling(nvecs, angles): """ Returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n. Parameters ---------- nvecs ...
[ "def", "check_angle_sampling", "(", "nvecs", ",", "angles", ")", ":", "failed_nvecs", "=", "[", "]", "failures", "=", "[", "]", "for", "i", ",", "vec", "in", "enumerate", "(", "nvecs", ")", ":", "X", "=", "(", "angles", "*", "vec", "[", ":", ",", ...
Returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n. Parameters ---------- nvecs : array_like Array of integer vectors. an...
[ "Returns", "a", "list", "of", "the", "index", "of", "elements", "of", "n", "which", "do", "not", "have", "adequate", "toy", "angle", "coverage", ".", "The", "criterion", "is", "that", "we", "must", "have", "at", "least", "one", "sample", "in", "each", ...
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/actionangle.py#L237-L283
train
adrn/gala
gala/dynamics/actionangle.py
find_actions
def find_actions(orbit, N_max, force_harmonic_oscillator=False, toy_potential=None): r""" Find approximate actions and angles for samples of a phase-space orbit. Uses toy potentials with known, analytic action-angle transformations to approximate the true coordinates as a Fourier sum. This code is ...
python
def find_actions(orbit, N_max, force_harmonic_oscillator=False, toy_potential=None): r""" Find approximate actions and angles for samples of a phase-space orbit. Uses toy potentials with known, analytic action-angle transformations to approximate the true coordinates as a Fourier sum. This code is ...
[ "def", "find_actions", "(", "orbit", ",", "N_max", ",", "force_harmonic_oscillator", "=", "False", ",", "toy_potential", "=", "None", ")", ":", "r", "if", "orbit", ".", "norbits", "==", "1", ":", "return", "_single_orbit_find_actions", "(", "orbit", ",", "N_...
r""" Find approximate actions and angles for samples of a phase-space orbit. Uses toy potentials with known, analytic action-angle transformations to approximate the true coordinates as a Fourier sum. This code is adapted from Jason Sanders' `genfunc <https://github.com/jlsanders/genfunc>`_ Pa...
[ "r", "Find", "approximate", "actions", "and", "angles", "for", "samples", "of", "a", "phase", "-", "space", "orbit", ".", "Uses", "toy", "potentials", "with", "known", "analytic", "action", "-", "angle", "transformations", "to", "approximate", "the", "true", ...
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/actionangle.py#L539-L591
train
adrn/gala
gala/dynamics/_genfunc/toy_potentials.py
angact_ho
def angact_ho(x,omega): """ Calculate angle and action variable in sho potential with parameter omega """ action = (x[3:]**2+(omega*x[:3])**2)/(2.*omega) angle = np.array([np.arctan(-x[3+i]/omega[i]/x[i]) if x[i]!=0. else -np.sign(x[3+i])*np.pi/2. for i in range(3)]) for i in range(3): if(x[...
python
def angact_ho(x,omega): """ Calculate angle and action variable in sho potential with parameter omega """ action = (x[3:]**2+(omega*x[:3])**2)/(2.*omega) angle = np.array([np.arctan(-x[3+i]/omega[i]/x[i]) if x[i]!=0. else -np.sign(x[3+i])*np.pi/2. for i in range(3)]) for i in range(3): if(x[...
[ "def", "angact_ho", "(", "x", ",", "omega", ")", ":", "action", "=", "(", "x", "[", "3", ":", "]", "**", "2", "+", "(", "omega", "*", "x", "[", ":", "3", "]", ")", "**", "2", ")", "/", "(", "2.", "*", "omega", ")", "angle", "=", "np", "...
Calculate angle and action variable in sho potential with parameter omega
[ "Calculate", "angle", "and", "action", "variable", "in", "sho", "potential", "with", "parameter", "omega" ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/_genfunc/toy_potentials.py#L18-L26
train
adrn/gala
gala/dynamics/util.py
peak_to_peak_period
def peak_to_peak_period(t, f, amplitude_threshold=1E-2): """ Estimate the period of the input time series by measuring the average peak-to-peak time. Parameters ---------- t : array_like Time grid aligned with the input time series. f : array_like A periodic time series. ...
python
def peak_to_peak_period(t, f, amplitude_threshold=1E-2): """ Estimate the period of the input time series by measuring the average peak-to-peak time. Parameters ---------- t : array_like Time grid aligned with the input time series. f : array_like A periodic time series. ...
[ "def", "peak_to_peak_period", "(", "t", ",", "f", ",", "amplitude_threshold", "=", "1E-2", ")", ":", "if", "hasattr", "(", "t", ",", "'unit'", ")", ":", "t_unit", "=", "t", ".", "unit", "t", "=", "t", ".", "value", "else", ":", "t_unit", "=", "u", ...
Estimate the period of the input time series by measuring the average peak-to-peak time. Parameters ---------- t : array_like Time grid aligned with the input time series. f : array_like A periodic time series. amplitude_threshold : numeric (optional) A tolerance paramet...
[ "Estimate", "the", "period", "of", "the", "input", "time", "series", "by", "measuring", "the", "average", "peak", "-", "to", "-", "peak", "time", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/util.py#L17-L68
train
adrn/gala
gala/dynamics/util.py
estimate_dt_n_steps
def estimate_dt_n_steps(w0, hamiltonian, n_periods, n_steps_per_period, dE_threshold=1E-9, func=np.nanmax, **integrate_kwargs): """ Estimate the timestep and number of steps to integrate an orbit for given its initial conditions and a potential object. Pa...
python
def estimate_dt_n_steps(w0, hamiltonian, n_periods, n_steps_per_period, dE_threshold=1E-9, func=np.nanmax, **integrate_kwargs): """ Estimate the timestep and number of steps to integrate an orbit for given its initial conditions and a potential object. Pa...
[ "def", "estimate_dt_n_steps", "(", "w0", ",", "hamiltonian", ",", "n_periods", ",", "n_steps_per_period", ",", "dE_threshold", "=", "1E-9", ",", "func", "=", "np", ".", "nanmax", ",", "**", "integrate_kwargs", ")", ":", "if", "not", "isinstance", "(", "w0", ...
Estimate the timestep and number of steps to integrate an orbit for given its initial conditions and a potential object. Parameters ---------- w0 : `~gala.dynamics.PhaseSpacePosition`, array_like Initial conditions. potential : :class:`~gala.potential.PotentialBase` The potential to...
[ "Estimate", "the", "timestep", "and", "number", "of", "steps", "to", "integrate", "an", "orbit", "for", "given", "its", "initial", "conditions", "and", "a", "potential", "object", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/util.py#L94-L169
train
adrn/gala
gala/coordinates/reflex.py
reflex_correct
def reflex_correct(coords, galactocentric_frame=None): """Correct the input Astropy coordinate object for solar reflex motion. The input coordinate instance must have distance and radial velocity information. If the radial velocity is not known, fill the Parameters ---------- coords : `~astropy.co...
python
def reflex_correct(coords, galactocentric_frame=None): """Correct the input Astropy coordinate object for solar reflex motion. The input coordinate instance must have distance and radial velocity information. If the radial velocity is not known, fill the Parameters ---------- coords : `~astropy.co...
[ "def", "reflex_correct", "(", "coords", ",", "galactocentric_frame", "=", "None", ")", ":", "c", "=", "coord", ".", "SkyCoord", "(", "coords", ")", "if", "galactocentric_frame", "is", "None", ":", "galactocentric_frame", "=", "coord", ".", "Galactocentric", "(...
Correct the input Astropy coordinate object for solar reflex motion. The input coordinate instance must have distance and radial velocity information. If the radial velocity is not known, fill the Parameters ---------- coords : `~astropy.coordinates.SkyCoord` The Astropy coordinate object with...
[ "Correct", "the", "input", "Astropy", "coordinate", "object", "for", "solar", "reflex", "motion", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/reflex.py#L5-L40
train