repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
lepture/flask-weixin
flask_weixin.py
Weixin.parse
def parse(self, content): """Parse xml body sent by weixin. :param content: A text of xml body. """ raw = {} try: root = etree.fromstring(content) except SyntaxError as e: raise ValueError(*e.args) for child in root: raw[chil...
python
def parse(self, content): """Parse xml body sent by weixin. :param content: A text of xml body. """ raw = {} try: root = etree.fromstring(content) except SyntaxError as e: raise ValueError(*e.args) for child in root: raw[chil...
[ "def", "parse", "(", "self", ",", "content", ")", ":", "raw", "=", "{", "}", "try", ":", "root", "=", "etree", ".", "fromstring", "(", "content", ")", "except", "SyntaxError", "as", "e", ":", "raise", "ValueError", "(", "*", "e", ".", "args", ")", ...
Parse xml body sent by weixin. :param content: A text of xml body.
[ "Parse", "xml", "body", "sent", "by", "weixin", "." ]
abf0b507d41b9780257507aa78fc0817fdc75719
https://github.com/lepture/flask-weixin/blob/abf0b507d41b9780257507aa78fc0817fdc75719/flask_weixin.py#L108-L133
train
lepture/flask-weixin
flask_weixin.py
Weixin.reply
def reply(self, username, type='text', sender=None, **kwargs): """Create the reply text for weixin. The reply varies per reply type. The acceptable types are `text`, `music`, `news`, `image`, `voice`, `video`. Each type accepts different parameters, but they share some common parameters...
python
def reply(self, username, type='text', sender=None, **kwargs): """Create the reply text for weixin. The reply varies per reply type. The acceptable types are `text`, `music`, `news`, `image`, `voice`, `video`. Each type accepts different parameters, but they share some common parameters...
[ "def", "reply", "(", "self", ",", "username", ",", "type", "=", "'text'", ",", "sender", "=", "None", ",", "*", "*", "kwargs", ")", ":", "sender", "=", "sender", "or", "self", ".", "sender", "if", "not", "sender", ":", "raise", "RuntimeError", "(", ...
Create the reply text for weixin. The reply varies per reply type. The acceptable types are `text`, `music`, `news`, `image`, `voice`, `video`. Each type accepts different parameters, but they share some common parameters: * username: the receiver's username * type: the...
[ "Create", "the", "reply", "text", "for", "weixin", "." ]
abf0b507d41b9780257507aa78fc0817fdc75719
https://github.com/lepture/flask-weixin/blob/abf0b507d41b9780257507aa78fc0817fdc75719/flask_weixin.py#L187-L258
train
lepture/flask-weixin
flask_weixin.py
Weixin.register
def register(self, key=None, func=None, **kwargs): """Register a command helper function. You can register the function:: def print_help(**kwargs): username = kwargs.get('sender') sender = kwargs.get('receiver') return weixin.reply( ...
python
def register(self, key=None, func=None, **kwargs): """Register a command helper function. You can register the function:: def print_help(**kwargs): username = kwargs.get('sender') sender = kwargs.get('receiver') return weixin.reply( ...
[ "def", "register", "(", "self", ",", "key", "=", "None", ",", "func", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "func", ":", "if", "key", "is", "None", ":", "limitation", "=", "frozenset", "(", "kwargs", ".", "items", "(", ")", ")", ...
Register a command helper function. You can register the function:: def print_help(**kwargs): username = kwargs.get('sender') sender = kwargs.get('receiver') return weixin.reply( username, sender=sender, content='text reply' ...
[ "Register", "a", "command", "helper", "function", "." ]
abf0b507d41b9780257507aa78fc0817fdc75719
https://github.com/lepture/flask-weixin/blob/abf0b507d41b9780257507aa78fc0817fdc75719/flask_weixin.py#L260-L292
train
lepture/flask-weixin
flask_weixin.py
Weixin.view_func
def view_func(self): """Default view function for Flask app. This is a simple implementation for view func, you can add it to your Flask app:: weixin = Weixin(app) app.add_url_rule('/', view_func=weixin.view_func) """ if request is None: rais...
python
def view_func(self): """Default view function for Flask app. This is a simple implementation for view func, you can add it to your Flask app:: weixin = Weixin(app) app.add_url_rule('/', view_func=weixin.view_func) """ if request is None: rais...
[ "def", "view_func", "(", "self", ")", ":", "if", "request", "is", "None", ":", "raise", "RuntimeError", "(", "'view_func need Flask be installed'", ")", "signature", "=", "request", ".", "args", ".", "get", "(", "'signature'", ")", "timestamp", "=", "request",...
Default view function for Flask app. This is a simple implementation for view func, you can add it to your Flask app:: weixin = Weixin(app) app.add_url_rule('/', view_func=weixin.view_func)
[ "Default", "view", "function", "for", "Flask", "app", "." ]
abf0b507d41b9780257507aa78fc0817fdc75719
https://github.com/lepture/flask-weixin/blob/abf0b507d41b9780257507aa78fc0817fdc75719/flask_weixin.py#L313-L369
train
cuducos/getgist
getgist/__main__.py
run_getgist
def run_getgist(filename, user, **kwargs): """Passes user inputs to GetGist() and calls get()""" assume_yes = kwargs.get("yes_to_all") getgist = GetGist(user=user, filename=filename, assume_yes=assume_yes) getgist.get()
python
def run_getgist(filename, user, **kwargs): """Passes user inputs to GetGist() and calls get()""" assume_yes = kwargs.get("yes_to_all") getgist = GetGist(user=user, filename=filename, assume_yes=assume_yes) getgist.get()
[ "def", "run_getgist", "(", "filename", ",", "user", ",", "*", "*", "kwargs", ")", ":", "assume_yes", "=", "kwargs", ".", "get", "(", "\"yes_to_all\"", ")", "getgist", "=", "GetGist", "(", "user", "=", "user", ",", "filename", "=", "filename", ",", "ass...
Passes user inputs to GetGist() and calls get()
[ "Passes", "user", "inputs", "to", "GetGist", "()", "and", "calls", "get", "()" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__main__.py#L107-L111
train
cuducos/getgist
getgist/__main__.py
run_getmy
def run_getmy(filename, **kwargs): """Shortcut for run_getgist() reading username from env var""" assume_yes = kwargs.get("yes_to_all") user = getenv("GETGIST_USER") getgist = GetGist(user=user, filename=filename, assume_yes=assume_yes) getgist.get()
python
def run_getmy(filename, **kwargs): """Shortcut for run_getgist() reading username from env var""" assume_yes = kwargs.get("yes_to_all") user = getenv("GETGIST_USER") getgist = GetGist(user=user, filename=filename, assume_yes=assume_yes) getgist.get()
[ "def", "run_getmy", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "assume_yes", "=", "kwargs", ".", "get", "(", "\"yes_to_all\"", ")", "user", "=", "getenv", "(", "\"GETGIST_USER\"", ")", "getgist", "=", "GetGist", "(", "user", "=", "user", ",", ...
Shortcut for run_getgist() reading username from env var
[ "Shortcut", "for", "run_getgist", "()", "reading", "username", "from", "env", "var" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__main__.py#L117-L122
train
cuducos/getgist
getgist/__main__.py
run_putgist
def run_putgist(filename, user, **kwargs): """Passes user inputs to GetGist() and calls put()""" assume_yes = kwargs.get("yes_to_all") private = kwargs.get("private") getgist = GetGist( user=user, filename=filename, assume_yes=assume_yes, create_private=private, a...
python
def run_putgist(filename, user, **kwargs): """Passes user inputs to GetGist() and calls put()""" assume_yes = kwargs.get("yes_to_all") private = kwargs.get("private") getgist = GetGist( user=user, filename=filename, assume_yes=assume_yes, create_private=private, a...
[ "def", "run_putgist", "(", "filename", ",", "user", ",", "*", "*", "kwargs", ")", ":", "assume_yes", "=", "kwargs", ".", "get", "(", "\"yes_to_all\"", ")", "private", "=", "kwargs", ".", "get", "(", "\"private\"", ")", "getgist", "=", "GetGist", "(", "...
Passes user inputs to GetGist() and calls put()
[ "Passes", "user", "inputs", "to", "GetGist", "()", "and", "calls", "put", "()" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__main__.py#L130-L141
train
cuducos/getgist
getgist/__main__.py
GetGist.get
def get(self): """Reads the remote file from Gist and save it locally""" if self.gist: content = self.github.read_gist_file(self.gist) self.local.save(content)
python
def get(self): """Reads the remote file from Gist and save it locally""" if self.gist: content = self.github.read_gist_file(self.gist) self.local.save(content)
[ "def", "get", "(", "self", ")", ":", "if", "self", ".", "gist", ":", "content", "=", "self", ".", "github", ".", "read_gist_file", "(", "self", ".", "gist", ")", "self", ".", "local", ".", "save", "(", "content", ")" ]
Reads the remote file from Gist and save it locally
[ "Reads", "the", "remote", "file", "from", "Gist", "and", "save", "it", "locally" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__main__.py#L88-L92
train
cuducos/getgist
getgist/__main__.py
GetGist.put
def put(self): """ Reads local file & update the remote gist (or create a new one)""" content = self.local.read() if self.gist: self.github.update(self.gist, content) else: self.github.create(content, public=self.public)
python
def put(self): """ Reads local file & update the remote gist (or create a new one)""" content = self.local.read() if self.gist: self.github.update(self.gist, content) else: self.github.create(content, public=self.public)
[ "def", "put", "(", "self", ")", ":", "content", "=", "self", ".", "local", ".", "read", "(", ")", "if", "self", ".", "gist", ":", "self", ".", "github", ".", "update", "(", "self", ".", "gist", ",", "content", ")", "else", ":", "self", ".", "gi...
Reads local file & update the remote gist (or create a new one)
[ "Reads", "local", "file", "&", "update", "the", "remote", "gist", "(", "or", "create", "a", "new", "one", ")" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__main__.py#L94-L100
train
cuducos/getgist
getgist/github.py
oauth_only
def oauth_only(function): """Decorator to restrict some GitHubTools methods to run only with OAuth""" def check_for_oauth(self, *args, **kwargs): """ Returns False if GitHubTools instance is not authenticated, or return the decorated fucntion if it is. """ if not self.is...
python
def oauth_only(function): """Decorator to restrict some GitHubTools methods to run only with OAuth""" def check_for_oauth(self, *args, **kwargs): """ Returns False if GitHubTools instance is not authenticated, or return the decorated fucntion if it is. """ if not self.is...
[ "def", "oauth_only", "(", "function", ")", ":", "def", "check_for_oauth", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Returns False if GitHubTools instance is not authenticated, or return\n the decorated fucntion if it is.\n ...
Decorator to restrict some GitHubTools methods to run only with OAuth
[ "Decorator", "to", "restrict", "some", "GitHubTools", "methods", "to", "run", "only", "with", "OAuth" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L11-L25
train
cuducos/getgist
getgist/github.py
GitHubTools.add_oauth_header
def add_oauth_header(self): """ Validate token and add the proper header for further requests. :return: (None) """ # abort if no token oauth_token = self._get_token() if not oauth_token: return # add oauth header & reach the api self.h...
python
def add_oauth_header(self): """ Validate token and add the proper header for further requests. :return: (None) """ # abort if no token oauth_token = self._get_token() if not oauth_token: return # add oauth header & reach the api self.h...
[ "def", "add_oauth_header", "(", "self", ")", ":", "# abort if no token", "oauth_token", "=", "self", ".", "_get_token", "(", ")", "if", "not", "oauth_token", ":", "return", "# add oauth header & reach the api", "self", ".", "headers", "[", "\"Authorization\"", "]", ...
Validate token and add the proper header for further requests. :return: (None)
[ "Validate", "token", "and", "add", "the", "proper", "header", "for", "further", "requests", ".", ":", "return", ":", "(", "None", ")" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L56-L79
train
cuducos/getgist
getgist/github.py
GitHubTools.get_gists
def get_gists(self): """ List generator containing gist relevant information such as id, description, filenames and raw URL (dict). """ # fetch all gists if self.is_authenticated: url = self._api_url("gists") else: url = self._api_url("user...
python
def get_gists(self): """ List generator containing gist relevant information such as id, description, filenames and raw URL (dict). """ # fetch all gists if self.is_authenticated: url = self._api_url("gists") else: url = self._api_url("user...
[ "def", "get_gists", "(", "self", ")", ":", "# fetch all gists", "if", "self", ".", "is_authenticated", ":", "url", "=", "self", ".", "_api_url", "(", "\"gists\"", ")", "else", ":", "url", "=", "self", ".", "_api_url", "(", "\"users\"", ",", "self", ".", ...
List generator containing gist relevant information such as id, description, filenames and raw URL (dict).
[ "List", "generator", "containing", "gist", "relevant", "information", "such", "as", "id", "description", "filenames", "and", "raw", "URL", "(", "dict", ")", "." ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L81-L107
train
cuducos/getgist
getgist/github.py
GitHubTools.select_gist
def select_gist(self, allow_none=False): """ Given the requested filename, it selects the proper gist; if more than one gist is found with the given filename, user is asked to choose. :allow_none: (bool) for `getgist` it should raise error if no gist is found, but setting this ar...
python
def select_gist(self, allow_none=False): """ Given the requested filename, it selects the proper gist; if more than one gist is found with the given filename, user is asked to choose. :allow_none: (bool) for `getgist` it should raise error if no gist is found, but setting this ar...
[ "def", "select_gist", "(", "self", ",", "allow_none", "=", "False", ")", ":", "# pick up all macthing gists", "matches", "=", "list", "(", ")", "for", "gist", "in", "self", ".", "get_gists", "(", ")", ":", "for", "gist_file", "in", "gist", ".", "get", "(...
Given the requested filename, it selects the proper gist; if more than one gist is found with the given filename, user is asked to choose. :allow_none: (bool) for `getgist` it should raise error if no gist is found, but setting this argument to True avoid this error, which is useful when...
[ "Given", "the", "requested", "filename", "it", "selects", "the", "proper", "gist", ";", "if", "more", "than", "one", "gist", "is", "found", "with", "the", "given", "filename", "user", "is", "asked", "to", "choose", ".", ":", "allow_none", ":", "(", "bool...
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L109-L141
train
cuducos/getgist
getgist/github.py
GitHubTools.read_gist_file
def read_gist_file(self, gist): """ Returns the contents of file hosted inside a gist at GitHub. :param gist: (dict) gist parsed by GitHubTools._parse() :return: (bytes) content of a gist loaded from GitHub """ url = False files = gist.get("files") for gis...
python
def read_gist_file(self, gist): """ Returns the contents of file hosted inside a gist at GitHub. :param gist: (dict) gist parsed by GitHubTools._parse() :return: (bytes) content of a gist loaded from GitHub """ url = False files = gist.get("files") for gis...
[ "def", "read_gist_file", "(", "self", ",", "gist", ")", ":", "url", "=", "False", "files", "=", "gist", ".", "get", "(", "\"files\"", ")", "for", "gist_file", "in", "files", ":", "if", "gist_file", ".", "get", "(", "\"filename\"", ")", "==", "self", ...
Returns the contents of file hosted inside a gist at GitHub. :param gist: (dict) gist parsed by GitHubTools._parse() :return: (bytes) content of a gist loaded from GitHub
[ "Returns", "the", "contents", "of", "file", "hosted", "inside", "a", "gist", "at", "GitHub", ".", ":", "param", "gist", ":", "(", "dict", ")", "gist", "parsed", "by", "GitHubTools", ".", "_parse", "()", ":", "return", ":", "(", "bytes", ")", "content",...
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L143-L158
train
cuducos/getgist
getgist/github.py
GitHubTools.update
def update(self, gist, content): """ Updates the contents of file hosted inside a gist at GitHub. :param gist: (dict) gist parsed by GitHubTools._parse_gist() :param content: (str or bytes) to be written :return: (bool) indicatind the success or failure of the update """ ...
python
def update(self, gist, content): """ Updates the contents of file hosted inside a gist at GitHub. :param gist: (dict) gist parsed by GitHubTools._parse_gist() :param content: (str or bytes) to be written :return: (bool) indicatind the success or failure of the update """ ...
[ "def", "update", "(", "self", ",", "gist", ",", "content", ")", ":", "# abort if content is False", "if", "content", "is", "False", ":", "return", "False", "# request", "url", "=", "self", ".", "_api_url", "(", "\"gists\"", ",", "gist", ".", "get", "(", ...
Updates the contents of file hosted inside a gist at GitHub. :param gist: (dict) gist parsed by GitHubTools._parse_gist() :param content: (str or bytes) to be written :return: (bool) indicatind the success or failure of the update
[ "Updates", "the", "contents", "of", "file", "hosted", "inside", "a", "gist", "at", "GitHub", ".", ":", "param", "gist", ":", "(", "dict", ")", "gist", "parsed", "by", "GitHubTools", ".", "_parse_gist", "()", ":", "param", "content", ":", "(", "str", "o...
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L161-L187
train
cuducos/getgist
getgist/github.py
GitHubTools.create
def create(self, content, **kwargs): """ Create a new gist. :param gist: (dict) gist parsed by GitHubTools._parse() :param content: (str or bytes) to be written :param public: (bool) defines if the gist is public or private :return: (bool) indicatind the success or failur...
python
def create(self, content, **kwargs): """ Create a new gist. :param gist: (dict) gist parsed by GitHubTools._parse() :param content: (str or bytes) to be written :param public: (bool) defines if the gist is public or private :return: (bool) indicatind the success or failur...
[ "def", "create", "(", "self", ",", "content", ",", "*", "*", "kwargs", ")", ":", "# abort if content is False", "if", "content", "is", "False", ":", "return", "False", "# set new gist", "public", "=", "bool", "(", "kwargs", ".", "get", "(", "\"public\"", "...
Create a new gist. :param gist: (dict) gist parsed by GitHubTools._parse() :param content: (str or bytes) to be written :param public: (bool) defines if the gist is public or private :return: (bool) indicatind the success or failure of the creation
[ "Create", "a", "new", "gist", ".", ":", "param", "gist", ":", "(", "dict", ")", "gist", "parsed", "by", "GitHubTools", ".", "_parse", "()", ":", "param", "content", ":", "(", "str", "or", "bytes", ")", "to", "be", "written", ":", "param", "public", ...
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L190-L227
train
cuducos/getgist
getgist/github.py
GitHubTools._ask_which_gist
def _ask_which_gist(self, matches): """ Asks user which gist to use in case of more than one gist matching the instance filename. :param matches: (list) of dictioaries generated within select_gists() :return: (dict) of the selected gist """ # ask user which gist t...
python
def _ask_which_gist(self, matches): """ Asks user which gist to use in case of more than one gist matching the instance filename. :param matches: (list) of dictioaries generated within select_gists() :return: (dict) of the selected gist """ # ask user which gist t...
[ "def", "_ask_which_gist", "(", "self", ",", "matches", ")", ":", "# ask user which gist to use", "self", ".", "hey", "(", "\"Use {} from which gist?\"", ".", "format", "(", "self", ".", "filename", ")", ")", "for", "count", ",", "gist", "in", "enumerate", "(",...
Asks user which gist to use in case of more than one gist matching the instance filename. :param matches: (list) of dictioaries generated within select_gists() :return: (dict) of the selected gist
[ "Asks", "user", "which", "gist", "to", "use", "in", "case", "of", "more", "than", "one", "gist", "matching", "the", "instance", "filename", ".", ":", "param", "matches", ":", "(", "list", ")", "of", "dictioaries", "generated", "within", "select_gists", "()...
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L229-L251
train
cuducos/getgist
getgist/github.py
GitHubTools._parse_gist
def _parse_gist(gist): """Receive a gist (dict) and parse it to GetGist""" # parse files files = list() file_names = sorted(filename for filename in gist["files"].keys()) for name in file_names: files.append( dict(filename=name, raw_url=gist["files"][...
python
def _parse_gist(gist): """Receive a gist (dict) and parse it to GetGist""" # parse files files = list() file_names = sorted(filename for filename in gist["files"].keys()) for name in file_names: files.append( dict(filename=name, raw_url=gist["files"][...
[ "def", "_parse_gist", "(", "gist", ")", ":", "# parse files", "files", "=", "list", "(", ")", "file_names", "=", "sorted", "(", "filename", "for", "filename", "in", "gist", "[", "\"files\"", "]", ".", "keys", "(", ")", ")", "for", "name", "in", "file_n...
Receive a gist (dict) and parse it to GetGist
[ "Receive", "a", "gist", "(", "dict", ")", "and", "parse", "it", "to", "GetGist" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L258-L280
train
cuducos/getgist
getgist/__init__.py
GetGistCommons.indent
def indent(self, message): """ Sets the indent for standardized output :param message: (str) :return: (str) """ indent = self.indent_char * self.indent_size return indent + message
python
def indent(self, message): """ Sets the indent for standardized output :param message: (str) :return: (str) """ indent = self.indent_char * self.indent_size return indent + message
[ "def", "indent", "(", "self", ",", "message", ")", ":", "indent", "=", "self", ".", "indent_char", "*", "self", ".", "indent_size", "return", "indent", "+", "message" ]
Sets the indent for standardized output :param message: (str) :return: (str)
[ "Sets", "the", "indent", "for", "standardized", "output", ":", "param", "message", ":", "(", "str", ")", ":", "return", ":", "(", "str", ")" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__init__.py#L12-L19
train
cuducos/getgist
getgist/__init__.py
GetGistCommons.output
def output(self, message, color=None): """ A helper to used like print() or click's secho() tunneling all the outputs to sys.stdout or sys.stderr :param message: (str) :param color: (str) check click.secho() documentation :return: (None) prints to sys.stdout or sys.stderr...
python
def output(self, message, color=None): """ A helper to used like print() or click's secho() tunneling all the outputs to sys.stdout or sys.stderr :param message: (str) :param color: (str) check click.secho() documentation :return: (None) prints to sys.stdout or sys.stderr...
[ "def", "output", "(", "self", ",", "message", ",", "color", "=", "None", ")", ":", "output_to", "=", "stderr", "if", "color", "==", "\"red\"", "else", "stdout", "secho", "(", "self", ".", "indent", "(", "message", ")", ",", "fg", "=", "color", ",", ...
A helper to used like print() or click's secho() tunneling all the outputs to sys.stdout or sys.stderr :param message: (str) :param color: (str) check click.secho() documentation :return: (None) prints to sys.stdout or sys.stderr
[ "A", "helper", "to", "used", "like", "print", "()", "or", "click", "s", "secho", "()", "tunneling", "all", "the", "outputs", "to", "sys", ".", "stdout", "or", "sys", ".", "stderr", ":", "param", "message", ":", "(", "str", ")", ":", "param", "color",...
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__init__.py#L21-L30
train
cuducos/getgist
getgist/request.py
GetGistRequests.get
def get(self, url, params=None, **kwargs): """Encapsulte requests.get to use this class instance header""" return requests.get(url, params=params, headers=self.add_headers(**kwargs))
python
def get(self, url, params=None, **kwargs): """Encapsulte requests.get to use this class instance header""" return requests.get(url, params=params, headers=self.add_headers(**kwargs))
[ "def", "get", "(", "self", ",", "url", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "requests", ".", "get", "(", "url", ",", "params", "=", "params", ",", "headers", "=", "self", ".", "add_headers", "(", "*", "*", "kwa...
Encapsulte requests.get to use this class instance header
[ "Encapsulte", "requests", ".", "get", "to", "use", "this", "class", "instance", "header" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/request.py#L26-L28
train
cuducos/getgist
getgist/request.py
GetGistRequests.patch
def patch(self, url, data=None, **kwargs): """Encapsulte requests.patch to use this class instance header""" return requests.patch(url, data=data, headers=self.add_headers(**kwargs))
python
def patch(self, url, data=None, **kwargs): """Encapsulte requests.patch to use this class instance header""" return requests.patch(url, data=data, headers=self.add_headers(**kwargs))
[ "def", "patch", "(", "self", ",", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "requests", ".", "patch", "(", "url", ",", "data", "=", "data", ",", "headers", "=", "self", ".", "add_headers", "(", "*", "*", "kwarg...
Encapsulte requests.patch to use this class instance header
[ "Encapsulte", "requests", ".", "patch", "to", "use", "this", "class", "instance", "header" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/request.py#L30-L32
train
cuducos/getgist
getgist/request.py
GetGistRequests.post
def post(self, url, data=None, **kwargs): """Encapsulte requests.post to use this class instance header""" return requests.post(url, data=data, headers=self.add_headers(**kwargs))
python
def post(self, url, data=None, **kwargs): """Encapsulte requests.post to use this class instance header""" return requests.post(url, data=data, headers=self.add_headers(**kwargs))
[ "def", "post", "(", "self", ",", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "requests", ".", "post", "(", "url", ",", "data", "=", "data", ",", "headers", "=", "self", ".", "add_headers", "(", "*", "*", "kwargs"...
Encapsulte requests.post to use this class instance header
[ "Encapsulte", "requests", ".", "post", "to", "use", "this", "class", "instance", "header" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/request.py#L34-L36
train
cuducos/getgist
getgist/local.py
LocalTools.save
def save(self, content): """ Save any given content to the instance file. :param content: (str or bytes) :return: (None) """ # backup existing file if needed if os.path.exists(self.file_path) and not self.assume_yes: message = "Overwrite existing {}? (...
python
def save(self, content): """ Save any given content to the instance file. :param content: (str or bytes) :return: (None) """ # backup existing file if needed if os.path.exists(self.file_path) and not self.assume_yes: message = "Overwrite existing {}? (...
[ "def", "save", "(", "self", ",", "content", ")", ":", "# backup existing file if needed", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "file_path", ")", "and", "not", "self", ".", "assume_yes", ":", "message", "=", "\"Overwrite existing {}? (y/n) ...
Save any given content to the instance file. :param content: (str or bytes) :return: (None)
[ "Save", "any", "given", "content", "to", "the", "instance", "file", ".", ":", "param", "content", ":", "(", "str", "or", "bytes", ")", ":", "return", ":", "(", "None", ")" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/local.py#L23-L41
train
cuducos/getgist
getgist/local.py
LocalTools.backup
def backup(self): """Backups files with the same name of the instance filename""" count = 0 name = "{}.bkp".format(self.filename) backup = os.path.join(self.cwd, name) while os.path.exists(backup): count += 1 name = "{}.bkp{}".format(self.filename, count) ...
python
def backup(self): """Backups files with the same name of the instance filename""" count = 0 name = "{}.bkp".format(self.filename) backup = os.path.join(self.cwd, name) while os.path.exists(backup): count += 1 name = "{}.bkp{}".format(self.filename, count) ...
[ "def", "backup", "(", "self", ")", ":", "count", "=", "0", "name", "=", "\"{}.bkp\"", ".", "format", "(", "self", ".", "filename", ")", "backup", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cwd", ",", "name", ")", "while", "os", ".", ...
Backups files with the same name of the instance filename
[ "Backups", "files", "with", "the", "same", "name", "of", "the", "instance", "filename" ]
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/local.py#L43-L53
train
cuducos/getgist
getgist/local.py
LocalTools.read
def read(self, file_path=None): """ Read the contents of a file. :param filename: (str) path to a file in the local file system :return: (str) contents of the file, or (False) if not found/not file """ if not file_path: file_path = self.file_path # ab...
python
def read(self, file_path=None): """ Read the contents of a file. :param filename: (str) path to a file in the local file system :return: (str) contents of the file, or (False) if not found/not file """ if not file_path: file_path = self.file_path # ab...
[ "def", "read", "(", "self", ",", "file_path", "=", "None", ")", ":", "if", "not", "file_path", ":", "file_path", "=", "self", ".", "file_path", "# abort if the file path does not exist", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ...
Read the contents of a file. :param filename: (str) path to a file in the local file system :return: (str) contents of the file, or (False) if not found/not file
[ "Read", "the", "contents", "of", "a", "file", ".", ":", "param", "filename", ":", "(", "str", ")", "path", "to", "a", "file", "in", "the", "local", "file", "system", ":", "return", ":", "(", "str", ")", "contents", "of", "the", "file", "or", "(", ...
c70a0a9353eca43360b82c759d1e1514ec265d3b
https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/local.py#L55-L75
train
thautwarm/EBNFParser
Python/Ruikowa/ObjectRegex/Tokenizer.py
char_matcher
def char_matcher(mode): """ a faster way for characters to generate token strings cache """ def f_raw(inp_str, pos): return mode if inp_str[pos] is mode else None def f_collection(inp_str, pos): ch = inp_str[pos] for each in mode: if ch is each: ...
python
def char_matcher(mode): """ a faster way for characters to generate token strings cache """ def f_raw(inp_str, pos): return mode if inp_str[pos] is mode else None def f_collection(inp_str, pos): ch = inp_str[pos] for each in mode: if ch is each: ...
[ "def", "char_matcher", "(", "mode", ")", ":", "def", "f_raw", "(", "inp_str", ",", "pos", ")", ":", "return", "mode", "if", "inp_str", "[", "pos", "]", "is", "mode", "else", "None", "def", "f_collection", "(", "inp_str", ",", "pos", ")", ":", "ch", ...
a faster way for characters to generate token strings cache
[ "a", "faster", "way", "for", "characters", "to", "generate", "token", "strings", "cache" ]
101a92c4f408f9e6ce7b55aacb39cded9394521d
https://github.com/thautwarm/EBNFParser/blob/101a92c4f408f9e6ce7b55aacb39cded9394521d/Python/Ruikowa/ObjectRegex/Tokenizer.py#L159-L181
train
thautwarm/EBNFParser
Python/Ruikowa/ObjectRegex/Tokenizer.py
str_matcher
def str_matcher(mode): """ generate token strings' cache """ def f_raw(inp_str, pos): return unique_literal_cache_pool[mode] if inp_str.startswith(mode, pos) else None def f_collection(inp_str, pos): for each in mode: if inp_str.startswith(each, pos): ...
python
def str_matcher(mode): """ generate token strings' cache """ def f_raw(inp_str, pos): return unique_literal_cache_pool[mode] if inp_str.startswith(mode, pos) else None def f_collection(inp_str, pos): for each in mode: if inp_str.startswith(each, pos): ...
[ "def", "str_matcher", "(", "mode", ")", ":", "def", "f_raw", "(", "inp_str", ",", "pos", ")", ":", "return", "unique_literal_cache_pool", "[", "mode", "]", "if", "inp_str", ".", "startswith", "(", "mode", ",", "pos", ")", "else", "None", "def", "f_collec...
generate token strings' cache
[ "generate", "token", "strings", "cache" ]
101a92c4f408f9e6ce7b55aacb39cded9394521d
https://github.com/thautwarm/EBNFParser/blob/101a92c4f408f9e6ce7b55aacb39cded9394521d/Python/Ruikowa/ObjectRegex/Tokenizer.py#L184-L205
train
thautwarm/EBNFParser
Python/Ruikowa/ObjectRegex/Tokenizer.py
regex_matcher
def regex_matcher(regex_pat): """ generate token names' cache :param regex_pat: :return: """ if isinstance(regex_pat, str): regex_pat = re.compile(regex_pat) def f(inp_str, pos): m = regex_pat.match(inp_str, pos) return m.group() if m else None retu...
python
def regex_matcher(regex_pat): """ generate token names' cache :param regex_pat: :return: """ if isinstance(regex_pat, str): regex_pat = re.compile(regex_pat) def f(inp_str, pos): m = regex_pat.match(inp_str, pos) return m.group() if m else None retu...
[ "def", "regex_matcher", "(", "regex_pat", ")", ":", "if", "isinstance", "(", "regex_pat", ",", "str", ")", ":", "regex_pat", "=", "re", ".", "compile", "(", "regex_pat", ")", "def", "f", "(", "inp_str", ",", "pos", ")", ":", "m", "=", "regex_pat", "....
generate token names' cache :param regex_pat: :return:
[ "generate", "token", "names", "cache", ":", "param", "regex_pat", ":", ":", "return", ":" ]
101a92c4f408f9e6ce7b55aacb39cded9394521d
https://github.com/thautwarm/EBNFParser/blob/101a92c4f408f9e6ce7b55aacb39cded9394521d/Python/Ruikowa/ObjectRegex/Tokenizer.py#L208-L221
train
thautwarm/EBNFParser
Python/Ruikowa/Bootstrap/Ast.py
Compiler.ast_for_stmts
def ast_for_stmts(self, stmts: T) -> None: """ Stmts ::= TokenDef{0, 1} Equals*; """ if not stmts: raise ValueError('no ast found!') head, *equals = stmts if head.name is NameEnum.TokenDef: self.ast_for_token_def(head) elif he...
python
def ast_for_stmts(self, stmts: T) -> None: """ Stmts ::= TokenDef{0, 1} Equals*; """ if not stmts: raise ValueError('no ast found!') head, *equals = stmts if head.name is NameEnum.TokenDef: self.ast_for_token_def(head) elif he...
[ "def", "ast_for_stmts", "(", "self", ",", "stmts", ":", "T", ")", "->", "None", ":", "if", "not", "stmts", ":", "raise", "ValueError", "(", "'no ast found!'", ")", "head", ",", "", "*", "equals", "=", "stmts", "if", "head", ".", "name", "is", "NameEn...
Stmts ::= TokenDef{0, 1} Equals*;
[ "Stmts", "::", "=", "TokenDef", "{", "0", "1", "}", "Equals", "*", ";" ]
101a92c4f408f9e6ce7b55aacb39cded9394521d
https://github.com/thautwarm/EBNFParser/blob/101a92c4f408f9e6ce7b55aacb39cded9394521d/Python/Ruikowa/Bootstrap/Ast.py#L54-L75
train
andela-sjames/paystack-python
paystackapi/base.py
PayStackRequests._request
def _request(self, method, resource_uri, **kwargs): """Perform a method on a resource. Args: method: requests.`method` resource_uri: resource endpoint Raises: HTTPError Returns: JSON Response """ data = kwargs.get('data') ...
python
def _request(self, method, resource_uri, **kwargs): """Perform a method on a resource. Args: method: requests.`method` resource_uri: resource endpoint Raises: HTTPError Returns: JSON Response """ data = kwargs.get('data') ...
[ "def", "_request", "(", "self", ",", "method", ",", "resource_uri", ",", "*", "*", "kwargs", ")", ":", "data", "=", "kwargs", ".", "get", "(", "'data'", ")", "response", "=", "method", "(", "self", ".", "API_BASE_URL", "+", "resource_uri", ",", "json",...
Perform a method on a resource. Args: method: requests.`method` resource_uri: resource endpoint Raises: HTTPError Returns: JSON Response
[ "Perform", "a", "method", "on", "a", "resource", "." ]
c9e4bddcb76e1490fefc362e71a21486400dccd4
https://github.com/andela-sjames/paystack-python/blob/c9e4bddcb76e1490fefc362e71a21486400dccd4/paystackapi/base.py#L45-L60
train
andela-sjames/paystack-python
paystackapi/base.py
PayStackRequests.get
def get(self, endpoint, **kwargs): """Get a resource. Args: endpoint: resource endpoint. """ return self._request(requests.get, endpoint, **kwargs)
python
def get(self, endpoint, **kwargs): """Get a resource. Args: endpoint: resource endpoint. """ return self._request(requests.get, endpoint, **kwargs)
[ "def", "get", "(", "self", ",", "endpoint", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "requests", ".", "get", ",", "endpoint", ",", "*", "*", "kwargs", ")" ]
Get a resource. Args: endpoint: resource endpoint.
[ "Get", "a", "resource", "." ]
c9e4bddcb76e1490fefc362e71a21486400dccd4
https://github.com/andela-sjames/paystack-python/blob/c9e4bddcb76e1490fefc362e71a21486400dccd4/paystackapi/base.py#L62-L68
train
andela-sjames/paystack-python
paystackapi/base.py
PayStackRequests.post
def post(self, endpoint, **kwargs): """Create a resource. Args: endpoint: resource endpoint. """ return self._request(requests.post, endpoint, **kwargs)
python
def post(self, endpoint, **kwargs): """Create a resource. Args: endpoint: resource endpoint. """ return self._request(requests.post, endpoint, **kwargs)
[ "def", "post", "(", "self", ",", "endpoint", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "requests", ".", "post", ",", "endpoint", ",", "*", "*", "kwargs", ")" ]
Create a resource. Args: endpoint: resource endpoint.
[ "Create", "a", "resource", "." ]
c9e4bddcb76e1490fefc362e71a21486400dccd4
https://github.com/andela-sjames/paystack-python/blob/c9e4bddcb76e1490fefc362e71a21486400dccd4/paystackapi/base.py#L70-L76
train
andela-sjames/paystack-python
paystackapi/base.py
PayStackRequests.put
def put(self, endpoint, **kwargs): """Update a resource. Args: endpoint: resource endpoint. """ return self._request(requests.put, endpoint, **kwargs)
python
def put(self, endpoint, **kwargs): """Update a resource. Args: endpoint: resource endpoint. """ return self._request(requests.put, endpoint, **kwargs)
[ "def", "put", "(", "self", ",", "endpoint", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "requests", ".", "put", ",", "endpoint", ",", "*", "*", "kwargs", ")" ]
Update a resource. Args: endpoint: resource endpoint.
[ "Update", "a", "resource", "." ]
c9e4bddcb76e1490fefc362e71a21486400dccd4
https://github.com/andela-sjames/paystack-python/blob/c9e4bddcb76e1490fefc362e71a21486400dccd4/paystackapi/base.py#L78-L84
train
andela-sjames/paystack-python
paystackapi/customer.py
Customer.update
def update(cls, customer_id, **kwargs): """ Static method defined to update paystack customer data by id. Args: customer_id: paystack customer id. first_name: customer's first name(optional). last_name: customer's last name(optional). email: custo...
python
def update(cls, customer_id, **kwargs): """ Static method defined to update paystack customer data by id. Args: customer_id: paystack customer id. first_name: customer's first name(optional). last_name: customer's last name(optional). email: custo...
[ "def", "update", "(", "cls", ",", "customer_id", ",", "*", "*", "kwargs", ")", ":", "return", "cls", "(", ")", ".", "requests", ".", "put", "(", "'customer/{customer_id}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ",", "data", "=", "k...
Static method defined to update paystack customer data by id. Args: customer_id: paystack customer id. first_name: customer's first name(optional). last_name: customer's last name(optional). email: customer's email address(optional). phone:customer's ...
[ "Static", "method", "defined", "to", "update", "paystack", "customer", "data", "by", "id", "." ]
c9e4bddcb76e1490fefc362e71a21486400dccd4
https://github.com/andela-sjames/paystack-python/blob/c9e4bddcb76e1490fefc362e71a21486400dccd4/paystackapi/customer.py#L50-L65
train
datadesk/slackdown
slackdown/__init__.py
render
def render(txt): """ Accepts Slack formatted text and returns HTML. """ # Removing links to other channels txt = re.sub(r'<#[^\|]*\|(.*)>', r'#\g<1>', txt) # Removing links to other users txt = re.sub(r'<(@.*)>', r'\g<1>', txt) # handle named hyperlinks txt = re.sub(r'<([^\|]*)\|(...
python
def render(txt): """ Accepts Slack formatted text and returns HTML. """ # Removing links to other channels txt = re.sub(r'<#[^\|]*\|(.*)>', r'#\g<1>', txt) # Removing links to other users txt = re.sub(r'<(@.*)>', r'\g<1>', txt) # handle named hyperlinks txt = re.sub(r'<([^\|]*)\|(...
[ "def", "render", "(", "txt", ")", ":", "# Removing links to other channels", "txt", "=", "re", ".", "sub", "(", "r'<#[^\\|]*\\|(.*)>'", ",", "r'#\\g<1>'", ",", "txt", ")", "# Removing links to other users", "txt", "=", "re", ".", "sub", "(", "r'<(@.*)>'", ",", ...
Accepts Slack formatted text and returns HTML.
[ "Accepts", "Slack", "formatted", "text", "and", "returns", "HTML", "." ]
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L59-L114
train
datadesk/slackdown
slackdown/__init__.py
CustomSlackdownHTMLParser._open_list
def _open_list(self, list_type): """ Add an open list tag corresponding to the specification in the parser's LIST_TYPES. """ if list_type in LIST_TYPES.keys(): tag = LIST_TYPES[list_type] else: raise Exception('CustomSlackdownHTMLParser:_open_list:...
python
def _open_list(self, list_type): """ Add an open list tag corresponding to the specification in the parser's LIST_TYPES. """ if list_type in LIST_TYPES.keys(): tag = LIST_TYPES[list_type] else: raise Exception('CustomSlackdownHTMLParser:_open_list:...
[ "def", "_open_list", "(", "self", ",", "list_type", ")", ":", "if", "list_type", "in", "LIST_TYPES", ".", "keys", "(", ")", ":", "tag", "=", "LIST_TYPES", "[", "list_type", "]", "else", ":", "raise", "Exception", "(", "'CustomSlackdownHTMLParser:_open_list: No...
Add an open list tag corresponding to the specification in the parser's LIST_TYPES.
[ "Add", "an", "open", "list", "tag", "corresponding", "to", "the", "specification", "in", "the", "parser", "s", "LIST_TYPES", "." ]
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L134-L150
train
datadesk/slackdown
slackdown/__init__.py
CustomSlackdownHTMLParser._close_list
def _close_list(self): """ Add an close list tag corresponding to the currently open list found in current_parent_element. """ list_type = self.current_parent_element['attrs']['class'] tag = LIST_TYPES[list_type] html = '</{t}>'.format( t=tag ...
python
def _close_list(self): """ Add an close list tag corresponding to the currently open list found in current_parent_element. """ list_type = self.current_parent_element['attrs']['class'] tag = LIST_TYPES[list_type] html = '</{t}>'.format( t=tag ...
[ "def", "_close_list", "(", "self", ")", ":", "list_type", "=", "self", ".", "current_parent_element", "[", "'attrs'", "]", "[", "'class'", "]", "tag", "=", "LIST_TYPES", "[", "list_type", "]", "html", "=", "'</{t}>'", ".", "format", "(", "t", "=", "tag",...
Add an close list tag corresponding to the currently open list found in current_parent_element.
[ "Add", "an", "close", "list", "tag", "corresponding", "to", "the", "currently", "open", "list", "found", "in", "current_parent_element", "." ]
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L152-L165
train
datadesk/slackdown
slackdown/__init__.py
CustomSlackdownHTMLParser.handle_starttag
def handle_starttag(self, tag, attrs): """ Called by HTMLParser.feed when a start tag is found. """ # Parse the tag attributes attrs_dict = dict(t for t in attrs) # If the tag is a predefined parent element if tag in PARENT_ELEMENTS: # If parser is pa...
python
def handle_starttag(self, tag, attrs): """ Called by HTMLParser.feed when a start tag is found. """ # Parse the tag attributes attrs_dict = dict(t for t in attrs) # If the tag is a predefined parent element if tag in PARENT_ELEMENTS: # If parser is pa...
[ "def", "handle_starttag", "(", "self", ",", "tag", ",", "attrs", ")", ":", "# Parse the tag attributes", "attrs_dict", "=", "dict", "(", "t", "for", "t", "in", "attrs", ")", "# If the tag is a predefined parent element", "if", "tag", "in", "PARENT_ELEMENTS", ":", ...
Called by HTMLParser.feed when a start tag is found.
[ "Called", "by", "HTMLParser", ".", "feed", "when", "a", "start", "tag", "is", "found", "." ]
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L167-L245
train
datadesk/slackdown
slackdown/__init__.py
CustomSlackdownHTMLParser.handle_endtag
def handle_endtag(self, tag): """ Called by HTMLParser.feed when an end tag is found. """ if tag in PARENT_ELEMENTS: self.current_parent_element['tag'] = '' self.current_parent_element['attrs'] = '' if tag == 'li': self.parsing_li = True ...
python
def handle_endtag(self, tag): """ Called by HTMLParser.feed when an end tag is found. """ if tag in PARENT_ELEMENTS: self.current_parent_element['tag'] = '' self.current_parent_element['attrs'] = '' if tag == 'li': self.parsing_li = True ...
[ "def", "handle_endtag", "(", "self", ",", "tag", ")", ":", "if", "tag", "in", "PARENT_ELEMENTS", ":", "self", ".", "current_parent_element", "[", "'tag'", "]", "=", "''", "self", ".", "current_parent_element", "[", "'attrs'", "]", "=", "''", "if", "tag", ...
Called by HTMLParser.feed when an end tag is found.
[ "Called", "by", "HTMLParser", ".", "feed", "when", "an", "end", "tag", "is", "found", "." ]
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L247-L258
train
datadesk/slackdown
slackdown/__init__.py
CustomSlackdownHTMLParser.handle_data
def handle_data(self, data): """ Called by HTMLParser.feed when text is found. """ if self.current_parent_element['tag'] == '': self.cleaned_html += '<p>' self.current_parent_element['tag'] = 'p' self.cleaned_html += data
python
def handle_data(self, data): """ Called by HTMLParser.feed when text is found. """ if self.current_parent_element['tag'] == '': self.cleaned_html += '<p>' self.current_parent_element['tag'] = 'p' self.cleaned_html += data
[ "def", "handle_data", "(", "self", ",", "data", ")", ":", "if", "self", ".", "current_parent_element", "[", "'tag'", "]", "==", "''", ":", "self", ".", "cleaned_html", "+=", "'<p>'", "self", ".", "current_parent_element", "[", "'tag'", "]", "=", "'p'", "...
Called by HTMLParser.feed when text is found.
[ "Called", "by", "HTMLParser", ".", "feed", "when", "text", "is", "found", "." ]
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L260-L268
train
datadesk/slackdown
slackdown/__init__.py
CustomSlackdownHTMLParser._remove_pre_formatting
def _remove_pre_formatting(self): """ Removes formatting tags added to pre elements. """ preformatted_wrappers = [ 'pre', 'code' ] for wrapper in preformatted_wrappers: for formatter in FORMATTERS: tag = FORMATTERS[form...
python
def _remove_pre_formatting(self): """ Removes formatting tags added to pre elements. """ preformatted_wrappers = [ 'pre', 'code' ] for wrapper in preformatted_wrappers: for formatter in FORMATTERS: tag = FORMATTERS[form...
[ "def", "_remove_pre_formatting", "(", "self", ")", ":", "preformatted_wrappers", "=", "[", "'pre'", ",", "'code'", "]", "for", "wrapper", "in", "preformatted_wrappers", ":", "for", "formatter", "in", "FORMATTERS", ":", "tag", "=", "FORMATTERS", "[", "formatter",...
Removes formatting tags added to pre elements.
[ "Removes", "formatting", "tags", "added", "to", "pre", "elements", "." ]
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L270-L289
train
datadesk/slackdown
slackdown/__init__.py
CustomSlackdownHTMLParser.clean
def clean(self): """ Goes through the txt input and cleans up any problematic HTML. """ # Calls handle_starttag, handle_endtag, and handle_data self.feed() # Clean up any parent tags left open if self.current_parent_element['tag'] != '': self.cleaned_...
python
def clean(self): """ Goes through the txt input and cleans up any problematic HTML. """ # Calls handle_starttag, handle_endtag, and handle_data self.feed() # Clean up any parent tags left open if self.current_parent_element['tag'] != '': self.cleaned_...
[ "def", "clean", "(", "self", ")", ":", "# Calls handle_starttag, handle_endtag, and handle_data", "self", ".", "feed", "(", ")", "# Clean up any parent tags left open", "if", "self", ".", "current_parent_element", "[", "'tag'", "]", "!=", "''", ":", "self", ".", "cl...
Goes through the txt input and cleans up any problematic HTML.
[ "Goes", "through", "the", "txt", "input", "and", "cleans", "up", "any", "problematic", "HTML", "." ]
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L297-L313
train
datadesk/slackdown
slackdown/templates.py
render_author
def render_author(**kwargs): """ Unstrict template block for rendering authors: <div class="author"> <img class="author-avatar" src="{author_avatar}"> <p class="author-name"> <a href="{author_link}">{author_name}</a> </p> <p class="user-handle">{author_handle}</p>...
python
def render_author(**kwargs): """ Unstrict template block for rendering authors: <div class="author"> <img class="author-avatar" src="{author_avatar}"> <p class="author-name"> <a href="{author_link}">{author_name}</a> </p> <p class="user-handle">{author_handle}</p>...
[ "def", "render_author", "(", "*", "*", "kwargs", ")", ":", "html", "=", "'<div class=\"user\">'", "author_avatar", "=", "kwargs", ".", "get", "(", "'author_avatar'", ",", "None", ")", "if", "author_avatar", ":", "html", "+=", "'<img class=\"user-avatar\" src=\"{}\...
Unstrict template block for rendering authors: <div class="author"> <img class="author-avatar" src="{author_avatar}"> <p class="author-name"> <a href="{author_link}">{author_name}</a> </p> <p class="user-handle">{author_handle}</p> </div>
[ "Unstrict", "template", "block", "for", "rendering", "authors", ":", "<div", "class", "=", "author", ">", "<img", "class", "=", "author", "-", "avatar", "src", "=", "{", "author_avatar", "}", ">", "<p", "class", "=", "author", "-", "name", ">", "<a", "...
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/templates.py#L1-L37
train
datadesk/slackdown
slackdown/templates.py
render_metadata
def render_metadata(**kwargs): """ Unstrict template block for rendering metadata: <div class="metadata"> <img class="metadata-logo" src="{service_logo}"> <p class="metadata-name">{service_name}</p> <p class="metadata-timestamp"> <a href="{timestamp_link}">{timestamp}</a>...
python
def render_metadata(**kwargs): """ Unstrict template block for rendering metadata: <div class="metadata"> <img class="metadata-logo" src="{service_logo}"> <p class="metadata-name">{service_name}</p> <p class="metadata-timestamp"> <a href="{timestamp_link}">{timestamp}</a>...
[ "def", "render_metadata", "(", "*", "*", "kwargs", ")", ":", "html", "=", "'<div class=\"metadata\">'", "service_logo", "=", "kwargs", ".", "get", "(", "'service_logo'", ",", "None", ")", "if", "service_logo", ":", "html", "+=", "'<img class=\"metadata-logo\" src=...
Unstrict template block for rendering metadata: <div class="metadata"> <img class="metadata-logo" src="{service_logo}"> <p class="metadata-name">{service_name}</p> <p class="metadata-timestamp"> <a href="{timestamp_link}">{timestamp}</a> </p> </div>
[ "Unstrict", "template", "block", "for", "rendering", "metadata", ":", "<div", "class", "=", "metadata", ">", "<img", "class", "=", "metadata", "-", "logo", "src", "=", "{", "service_logo", "}", ">", "<p", "class", "=", "metadata", "-", "name", ">", "{", ...
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/templates.py#L40-L76
train
datadesk/slackdown
slackdown/templates.py
render_image
def render_image(**kwargs): """ Unstrict template block for rendering an image: <img alt="{alt_text}" title="{title}" src="{url}"> """ html = '' url = kwargs.get('url', None) if url: html = '<img' alt_text = kwargs.get('alt_text', None) if alt_text: html...
python
def render_image(**kwargs): """ Unstrict template block for rendering an image: <img alt="{alt_text}" title="{title}" src="{url}"> """ html = '' url = kwargs.get('url', None) if url: html = '<img' alt_text = kwargs.get('alt_text', None) if alt_text: html...
[ "def", "render_image", "(", "*", "*", "kwargs", ")", ":", "html", "=", "''", "url", "=", "kwargs", ".", "get", "(", "'url'", ",", "None", ")", "if", "url", ":", "html", "=", "'<img'", "alt_text", "=", "kwargs", ".", "get", "(", "'alt_text'", ",", ...
Unstrict template block for rendering an image: <img alt="{alt_text}" title="{title}" src="{url}">
[ "Unstrict", "template", "block", "for", "rendering", "an", "image", ":", "<img", "alt", "=", "{", "alt_text", "}", "title", "=", "{", "title", "}", "src", "=", "{", "url", "}", ">" ]
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/templates.py#L79-L100
train
datadesk/slackdown
slackdown/templates.py
render_twitter
def render_twitter(text, **kwargs): """ Strict template block for rendering twitter embeds. """ author = render_author(**kwargs['author']) metadata = render_metadata(**kwargs['metadata']) image = render_image(**kwargs['image']) html = """ <div class="attachment attachment-twitter"> ...
python
def render_twitter(text, **kwargs): """ Strict template block for rendering twitter embeds. """ author = render_author(**kwargs['author']) metadata = render_metadata(**kwargs['metadata']) image = render_image(**kwargs['image']) html = """ <div class="attachment attachment-twitter"> ...
[ "def", "render_twitter", "(", "text", ",", "*", "*", "kwargs", ")", ":", "author", "=", "render_author", "(", "*", "*", "kwargs", "[", "'author'", "]", ")", "metadata", "=", "render_metadata", "(", "*", "*", "kwargs", "[", "'metadata'", "]", ")", "imag...
Strict template block for rendering twitter embeds.
[ "Strict", "template", "block", "for", "rendering", "twitter", "embeds", "." ]
2c5c2faf2673d0d58183f590f234d2c7e1fe8508
https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/templates.py#L103-L125
train
annayqho/TheCannon
code/lamost/li_giants/find_all_candidates.py
get_model
def get_model(LAB_DIR): """ Cannon model params """ coeffs = np.load("%s/coeffs.npz" %LAB_DIR)['arr_0'] scatters = np.load("%s/scatters.npz" %LAB_DIR)['arr_0'] chisqs = np.load("%s/chisqs.npz" %LAB_DIR)['arr_0'] pivots = np.load("%s/pivots.npz" %LAB_DIR)['arr_0'] return coeffs, scatters, chisqs,...
python
def get_model(LAB_DIR): """ Cannon model params """ coeffs = np.load("%s/coeffs.npz" %LAB_DIR)['arr_0'] scatters = np.load("%s/scatters.npz" %LAB_DIR)['arr_0'] chisqs = np.load("%s/chisqs.npz" %LAB_DIR)['arr_0'] pivots = np.load("%s/pivots.npz" %LAB_DIR)['arr_0'] return coeffs, scatters, chisqs,...
[ "def", "get_model", "(", "LAB_DIR", ")", ":", "coeffs", "=", "np", ".", "load", "(", "\"%s/coeffs.npz\"", "%", "LAB_DIR", ")", "[", "'arr_0'", "]", "scatters", "=", "np", ".", "load", "(", "\"%s/scatters.npz\"", "%", "LAB_DIR", ")", "[", "'arr_0'", "]", ...
Cannon model params
[ "Cannon", "model", "params" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/find_all_candidates.py#L50-L56
train
annayqho/TheCannon
code/lamost/li_giants/find_all_candidates.py
get_labels
def get_labels(ids_find): """ Labels to make Cannon model spectra """ a = pyfits.open("%s/lamost_catalog_full.fits" %LAB_DIR) data = a[1].data a.close() id_all = data['lamost_id'] id_all = np.array(id_all) id_all = np.array([val.strip() for val in id_all]) snr_all = data['cannon_snrg'] ...
python
def get_labels(ids_find): """ Labels to make Cannon model spectra """ a = pyfits.open("%s/lamost_catalog_full.fits" %LAB_DIR) data = a[1].data a.close() id_all = data['lamost_id'] id_all = np.array(id_all) id_all = np.array([val.strip() for val in id_all]) snr_all = data['cannon_snrg'] ...
[ "def", "get_labels", "(", "ids_find", ")", ":", "a", "=", "pyfits", ".", "open", "(", "\"%s/lamost_catalog_full.fits\"", "%", "LAB_DIR", ")", "data", "=", "a", "[", "1", "]", ".", "data", "a", ".", "close", "(", ")", "id_all", "=", "data", "[", "'lam...
Labels to make Cannon model spectra
[ "Labels", "to", "make", "Cannon", "model", "spectra" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/find_all_candidates.py#L59-L83
train
annayqho/TheCannon
code/lamost/li_giants/find_all_candidates.py
get_normed_spectra
def get_normed_spectra(): """ Spectra to compare with models """ wl = np.load("%s/wl.npz" %LAB_DIR)['arr_0'] filenames = np.array( [SPEC_DIR + "/Spectra" + "/" + val for val in lamost_id]) grid, fluxes, ivars, npix, SNRs = lamost.load_spectra( lamost_id, input_grid=wl) ds = d...
python
def get_normed_spectra(): """ Spectra to compare with models """ wl = np.load("%s/wl.npz" %LAB_DIR)['arr_0'] filenames = np.array( [SPEC_DIR + "/Spectra" + "/" + val for val in lamost_id]) grid, fluxes, ivars, npix, SNRs = lamost.load_spectra( lamost_id, input_grid=wl) ds = d...
[ "def", "get_normed_spectra", "(", ")", ":", "wl", "=", "np", ".", "load", "(", "\"%s/wl.npz\"", "%", "LAB_DIR", ")", "[", "'arr_0'", "]", "filenames", "=", "np", ".", "array", "(", "[", "SPEC_DIR", "+", "\"/Spectra\"", "+", "\"/\"", "+", "val", "for", ...
Spectra to compare with models
[ "Spectra", "to", "compare", "with", "models" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/find_all_candidates.py#L86-L99
train
annayqho/TheCannon
code/lamost/li_giants/find_all_candidates.py
wget_files
def wget_files(): """ Pull the files from the LAMOST archive """ for f in lamost_id: short = (f.split('-')[2]).split('_')[0] filename = "%s/%s.gz" %(short,f) DIR = "/Users/annaho/Data/Li_Giants/Spectra_APOKASC" searchfor = "%s/%s.gz" %(DIR,f) if glob.glob(searchfor): ...
python
def wget_files(): """ Pull the files from the LAMOST archive """ for f in lamost_id: short = (f.split('-')[2]).split('_')[0] filename = "%s/%s.gz" %(short,f) DIR = "/Users/annaho/Data/Li_Giants/Spectra_APOKASC" searchfor = "%s/%s.gz" %(DIR,f) if glob.glob(searchfor): ...
[ "def", "wget_files", "(", ")", ":", "for", "f", "in", "lamost_id", ":", "short", "=", "(", "f", ".", "split", "(", "'-'", ")", "[", "2", "]", ")", ".", "split", "(", "'_'", ")", "[", "0", "]", "filename", "=", "\"%s/%s.gz\"", "%", "(", "short",...
Pull the files from the LAMOST archive
[ "Pull", "the", "files", "from", "the", "LAMOST", "archive" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/find_all_candidates.py#L102-L117
train
annayqho/TheCannon
code/lamost/li_giants/find_apokasc_candidates.py
get_labels
def get_labels(): """ Labels to make Cannon model spectra """ cannon_teff = data['cannon_teff_2'] cannon_logg = data['cannon_logg_2'] cannon_m_h = data['cannon_m_h'] cannon_alpha_m = data['cannon_alpha_m'] cannon_a_k = data['cannon_a_k'] labels = np.vstack( (cannon_teff, cannon_l...
python
def get_labels(): """ Labels to make Cannon model spectra """ cannon_teff = data['cannon_teff_2'] cannon_logg = data['cannon_logg_2'] cannon_m_h = data['cannon_m_h'] cannon_alpha_m = data['cannon_alpha_m'] cannon_a_k = data['cannon_a_k'] labels = np.vstack( (cannon_teff, cannon_l...
[ "def", "get_labels", "(", ")", ":", "cannon_teff", "=", "data", "[", "'cannon_teff_2'", "]", "cannon_logg", "=", "data", "[", "'cannon_logg_2'", "]", "cannon_m_h", "=", "data", "[", "'cannon_m_h'", "]", "cannon_alpha_m", "=", "data", "[", "'cannon_alpha_m'", "...
Labels to make Cannon model spectra
[ "Labels", "to", "make", "Cannon", "model", "spectra" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/find_apokasc_candidates.py#L30-L44
train
annayqho/TheCannon
code/lamost/abundances/calc_gradient_spectra.py
cannon_normalize
def cannon_normalize(spec_raw): """ Normalize according to The Cannon """ spec = np.array([spec_raw]) wl = np.arange(0, spec.shape[1]) w = continuum_normalization.gaussian_weight_matrix(wl, L=50) ivar = np.ones(spec.shape)*0.5 cont = continuum_normalization._find_cont_gaussian_smooth( ...
python
def cannon_normalize(spec_raw): """ Normalize according to The Cannon """ spec = np.array([spec_raw]) wl = np.arange(0, spec.shape[1]) w = continuum_normalization.gaussian_weight_matrix(wl, L=50) ivar = np.ones(spec.shape)*0.5 cont = continuum_normalization._find_cont_gaussian_smooth( ...
[ "def", "cannon_normalize", "(", "spec_raw", ")", ":", "spec", "=", "np", ".", "array", "(", "[", "spec_raw", "]", ")", "wl", "=", "np", ".", "arange", "(", "0", ",", "spec", ".", "shape", "[", "1", "]", ")", "w", "=", "continuum_normalization", "."...
Normalize according to The Cannon
[ "Normalize", "according", "to", "The", "Cannon" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/abundances/calc_gradient_spectra.py#L25-L35
train
annayqho/TheCannon
code/lamost/abundances/calc_gradient_spectra.py
resample
def resample(grid, wl, flux): """ Resample spectrum onto desired grid """ flux_rs = (interpolate.interp1d(wl, flux))(grid) return flux_rs
python
def resample(grid, wl, flux): """ Resample spectrum onto desired grid """ flux_rs = (interpolate.interp1d(wl, flux))(grid) return flux_rs
[ "def", "resample", "(", "grid", ",", "wl", ",", "flux", ")", ":", "flux_rs", "=", "(", "interpolate", ".", "interp1d", "(", "wl", ",", "flux", ")", ")", "(", "grid", ")", "return", "flux_rs" ]
Resample spectrum onto desired grid
[ "Resample", "spectrum", "onto", "desired", "grid" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/abundances/calc_gradient_spectra.py#L38-L41
train
annayqho/TheCannon
code/lamost/abundances/calc_gradient_spectra.py
gen_cannon_grad_spec
def gen_cannon_grad_spec(choose, coeffs, pivots): """ Generate Cannon gradient spectra Parameters ---------- labels: default values for [teff, logg, feh, cfe, nfe, afe, ak] choose: val of cfe or nfe, whatever you're varying low: lowest val of cfe or nfe, whatever you're varying high: highes...
python
def gen_cannon_grad_spec(choose, coeffs, pivots): """ Generate Cannon gradient spectra Parameters ---------- labels: default values for [teff, logg, feh, cfe, nfe, afe, ak] choose: val of cfe or nfe, whatever you're varying low: lowest val of cfe or nfe, whatever you're varying high: highes...
[ "def", "gen_cannon_grad_spec", "(", "choose", ",", "coeffs", ",", "pivots", ")", ":", "base_labels", "=", "[", "4800", ",", "2.5", ",", "0.03", ",", "0.10", ",", "-", "0.17", ",", "-", "0.17", ",", "0", ",", "-", "0.16", ",", "-", "0.13", ",", "-...
Generate Cannon gradient spectra Parameters ---------- labels: default values for [teff, logg, feh, cfe, nfe, afe, ak] choose: val of cfe or nfe, whatever you're varying low: lowest val of cfe or nfe, whatever you're varying high: highest val of cfe or nfe, whatever you're varying
[ "Generate", "Cannon", "gradient", "spectra" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/abundances/calc_gradient_spectra.py#L62-L94
train
annayqho/TheCannon
code/lamost/abundances/calc_gradient_spectra.py
get_model_spec_ting
def get_model_spec_ting(atomic_number): """ X_u_template[0:2] are teff, logg, vturb in km/s X_u_template[:,3] -> onward, put atomic number atomic_number is 6 for C, 7 for N """ DATA_DIR = "/Users/annaho/Data/LAMOST/Mass_And_Age" temp = np.load("%s/X_u_template_KGh_res=1800.npz" %DATA_DIR) ...
python
def get_model_spec_ting(atomic_number): """ X_u_template[0:2] are teff, logg, vturb in km/s X_u_template[:,3] -> onward, put atomic number atomic_number is 6 for C, 7 for N """ DATA_DIR = "/Users/annaho/Data/LAMOST/Mass_And_Age" temp = np.load("%s/X_u_template_KGh_res=1800.npz" %DATA_DIR) ...
[ "def", "get_model_spec_ting", "(", "atomic_number", ")", ":", "DATA_DIR", "=", "\"/Users/annaho/Data/LAMOST/Mass_And_Age\"", "temp", "=", "np", ".", "load", "(", "\"%s/X_u_template_KGh_res=1800.npz\"", "%", "DATA_DIR", ")", "X_u_template", "=", "temp", "[", "\"X_u_templ...
X_u_template[0:2] are teff, logg, vturb in km/s X_u_template[:,3] -> onward, put atomic number atomic_number is 6 for C, 7 for N
[ "X_u_template", "[", "0", ":", "2", "]", "are", "teff", "logg", "vturb", "in", "km", "/", "s", "X_u_template", "[", ":", "3", "]", "-", ">", "onward", "put", "atomic", "number", "atomic_number", "is", "6", "for", "C", "7", "for", "N" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/abundances/calc_gradient_spectra.py#L129-L140
train
annayqho/TheCannon
code/lamost/li_giants/residuals.py
get_residuals
def get_residuals(ds, m): """ Using the dataset and model object, calculate the residuals and return Parameters ---------- ds: dataset object m: model object Return ------ residuals: array of residuals, spec minus model spec """ model_spectra = get_model_spectra(ds, m) resid...
python
def get_residuals(ds, m): """ Using the dataset and model object, calculate the residuals and return Parameters ---------- ds: dataset object m: model object Return ------ residuals: array of residuals, spec minus model spec """ model_spectra = get_model_spectra(ds, m) resid...
[ "def", "get_residuals", "(", "ds", ",", "m", ")", ":", "model_spectra", "=", "get_model_spectra", "(", "ds", ",", "m", ")", "resid", "=", "ds", ".", "test_flux", "-", "model_spectra", "return", "resid" ]
Using the dataset and model object, calculate the residuals and return Parameters ---------- ds: dataset object m: model object Return ------ residuals: array of residuals, spec minus model spec
[ "Using", "the", "dataset", "and", "model", "object", "calculate", "the", "residuals", "and", "return" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L27-L40
train
annayqho/TheCannon
code/lamost/li_giants/residuals.py
load_model
def load_model(): """ Load the model Parameters ---------- direc: directory with all of the model files Returns ------- m: model object """ direc = "/home/annaho/TheCannon/code/lamost/mass_age/cn" m = model.CannonModel(2) m.coeffs = np.load(direc + "/coeffs.npz")['arr_...
python
def load_model(): """ Load the model Parameters ---------- direc: directory with all of the model files Returns ------- m: model object """ direc = "/home/annaho/TheCannon/code/lamost/mass_age/cn" m = model.CannonModel(2) m.coeffs = np.load(direc + "/coeffs.npz")['arr_...
[ "def", "load_model", "(", ")", ":", "direc", "=", "\"/home/annaho/TheCannon/code/lamost/mass_age/cn\"", "m", "=", "model", ".", "CannonModel", "(", "2", ")", "m", ".", "coeffs", "=", "np", ".", "load", "(", "direc", "+", "\"/coeffs.npz\"", ")", "[", "'arr_0'...
Load the model Parameters ---------- direc: directory with all of the model files Returns ------- m: model object
[ "Load", "the", "model" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L48-L65
train
annayqho/TheCannon
code/lamost/li_giants/residuals.py
load_dataset
def load_dataset(date): """ Load the dataset for a single date Parameters ---------- date: the date (string) for which to load the data & dataset Returns ------- ds: the dataset object """ LAB_DIR = "/home/annaho/TheCannon/data/lamost" WL_DIR = "/home/annaho/TheCannon/code...
python
def load_dataset(date): """ Load the dataset for a single date Parameters ---------- date: the date (string) for which to load the data & dataset Returns ------- ds: the dataset object """ LAB_DIR = "/home/annaho/TheCannon/data/lamost" WL_DIR = "/home/annaho/TheCannon/code...
[ "def", "load_dataset", "(", "date", ")", ":", "LAB_DIR", "=", "\"/home/annaho/TheCannon/data/lamost\"", "WL_DIR", "=", "\"/home/annaho/TheCannon/code/lamost/mass_age/cn\"", "SPEC_DIR", "=", "\"/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels/output\"", "wl", "=", "np", "....
Load the dataset for a single date Parameters ---------- date: the date (string) for which to load the data & dataset Returns ------- ds: the dataset object
[ "Load", "the", "dataset", "for", "a", "single", "date", "Parameters", "----------", "date", ":", "the", "date", "(", "string", ")", "for", "which", "to", "load", "the", "data", "&", "dataset" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L68-L90
train
annayqho/TheCannon
code/lamost/li_giants/residuals.py
fit_gaussian
def fit_gaussian(x, y, yerr, p0): """ Fit a Gaussian to the data """ try: popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True) except RuntimeError: return [0],[0] return popt, pcov
python
def fit_gaussian(x, y, yerr, p0): """ Fit a Gaussian to the data """ try: popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True) except RuntimeError: return [0],[0] return popt, pcov
[ "def", "fit_gaussian", "(", "x", ",", "y", ",", "yerr", ",", "p0", ")", ":", "try", ":", "popt", ",", "pcov", "=", "curve_fit", "(", "gaussian", ",", "x", ",", "y", ",", "sigma", "=", "yerr", ",", "p0", "=", "p0", ",", "absolute_sigma", "=", "T...
Fit a Gaussian to the data
[ "Fit", "a", "Gaussian", "to", "the", "data" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L93-L99
train
annayqho/TheCannon
code/lamost/li_giants/residuals.py
select
def select(yerrs, amps, amp_errs, widths): """ criteria for keeping an object """ keep_1 = np.logical_and(amps < 0, widths > 1) keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps)) keep = np.logical_and(keep_1, keep_2) return keep
python
def select(yerrs, amps, amp_errs, widths): """ criteria for keeping an object """ keep_1 = np.logical_and(amps < 0, widths > 1) keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps)) keep = np.logical_and(keep_1, keep_2) return keep
[ "def", "select", "(", "yerrs", ",", "amps", ",", "amp_errs", ",", "widths", ")", ":", "keep_1", "=", "np", ".", "logical_and", "(", "amps", "<", "0", ",", "widths", ">", "1", ")", "keep_2", "=", "np", ".", "logical_and", "(", "np", ".", "abs", "(...
criteria for keeping an object
[ "criteria", "for", "keeping", "an", "object" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L131-L136
train
annayqho/TheCannon
code/lamost/li_giants/residuals.py
run_all
def run_all(): """ Load the data that we're using to search for Li-rich giants. Store it in dataset and model objects. """ DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels" dates = os.listdir("/home/share/LAMOST/DR2/DR2_release") dates = np.array(dates) dates = np.delete(date...
python
def run_all(): """ Load the data that we're using to search for Li-rich giants. Store it in dataset and model objects. """ DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels" dates = os.listdir("/home/share/LAMOST/DR2/DR2_release") dates = np.array(dates) dates = np.delete(date...
[ "def", "run_all", "(", ")", ":", "DATA_DIR", "=", "\"/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels\"", "dates", "=", "os", ".", "listdir", "(", "\"/home/share/LAMOST/DR2/DR2_release\"", ")", "dates", "=", "np", ".", "array", "(", "dates", ")", "dates", "=...
Load the data that we're using to search for Li-rich giants. Store it in dataset and model objects.
[ "Load", "the", "data", "that", "we", "re", "using", "to", "search", "for", "Li", "-", "rich", "giants", ".", "Store", "it", "in", "dataset", "and", "model", "objects", "." ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L212-L227
train
annayqho/TheCannon
code/lamost/mass_age/paper_plots/cn_features.py
gen_cannon_grad_spec
def gen_cannon_grad_spec(base_labels, choose, low, high, coeffs, pivots): """ Generate Cannon gradient spectra Parameters ---------- labels: default values for [teff, logg, feh, cfe, nfe, afe, ak] choose: val of cfe or nfe, whatever you're varying low: lowest val of cfe or nfe, whatever you're ...
python
def gen_cannon_grad_spec(base_labels, choose, low, high, coeffs, pivots): """ Generate Cannon gradient spectra Parameters ---------- labels: default values for [teff, logg, feh, cfe, nfe, afe, ak] choose: val of cfe or nfe, whatever you're varying low: lowest val of cfe or nfe, whatever you're ...
[ "def", "gen_cannon_grad_spec", "(", "base_labels", ",", "choose", ",", "low", ",", "high", ",", "coeffs", ",", "pivots", ")", ":", "# Generate Cannon gradient spectra", "low_lab", "=", "copy", ".", "copy", "(", "base_labels", ")", "low_lab", "[", "choose", "]"...
Generate Cannon gradient spectra Parameters ---------- labels: default values for [teff, logg, feh, cfe, nfe, afe, ak] choose: val of cfe or nfe, whatever you're varying low: lowest val of cfe or nfe, whatever you're varying high: highest val of cfe or nfe, whatever you're varying
[ "Generate", "Cannon", "gradient", "spectra" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/mass_age/paper_plots/cn_features.py#L55-L75
train
annayqho/TheCannon
code/lamost/mass_age/cn/write_table.py
get_err
def get_err(snr): """ Get approximate scatters from SNR as determined in the code, snr_test.py Order: Teff, logg, MH, CM, NM, alpha """ quad_terms = np.array( [3.11e-3, 1.10e-5, 6.95e-6, 5.05e-6, 4.65e-6, 4.10e-6]) lin_terms = np.array( [-0.869, -2.07e-3, -1.40e-3, -1.03e-3,...
python
def get_err(snr): """ Get approximate scatters from SNR as determined in the code, snr_test.py Order: Teff, logg, MH, CM, NM, alpha """ quad_terms = np.array( [3.11e-3, 1.10e-5, 6.95e-6, 5.05e-6, 4.65e-6, 4.10e-6]) lin_terms = np.array( [-0.869, -2.07e-3, -1.40e-3, -1.03e-3,...
[ "def", "get_err", "(", "snr", ")", ":", "quad_terms", "=", "np", ".", "array", "(", "[", "3.11e-3", ",", "1.10e-5", ",", "6.95e-6", ",", "5.05e-6", ",", "4.65e-6", ",", "4.10e-6", "]", ")", "lin_terms", "=", "np", ".", "array", "(", "[", "-", "0.86...
Get approximate scatters from SNR as determined in the code, snr_test.py Order: Teff, logg, MH, CM, NM, alpha
[ "Get", "approximate", "scatters", "from", "SNR", "as", "determined", "in", "the", "code", "snr_test", ".", "py", "Order", ":", "Teff", "logg", "MH", "CM", "NM", "alpha" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/mass_age/cn/write_table.py#L12-L31
train
annayqho/TheCannon
code/lamost/mass_age/cn/get_colors.py
get_colors
def get_colors(catalog): """ Pull colors from catalog Parameters ---------- catalog: filename """ print("Get Colors") a = pyfits.open(catalog) data = a[1].data a.close() all_ids = data['LAMOST_ID_1'] all_ids = np.array([val.strip() for val in all_ids]) # G magnitude...
python
def get_colors(catalog): """ Pull colors from catalog Parameters ---------- catalog: filename """ print("Get Colors") a = pyfits.open(catalog) data = a[1].data a.close() all_ids = data['LAMOST_ID_1'] all_ids = np.array([val.strip() for val in all_ids]) # G magnitude...
[ "def", "get_colors", "(", "catalog", ")", ":", "print", "(", "\"Get Colors\"", ")", "a", "=", "pyfits", ".", "open", "(", "catalog", ")", "data", "=", "a", "[", "1", "]", ".", "data", "a", ".", "close", "(", ")", "all_ids", "=", "data", "[", "'LA...
Pull colors from catalog Parameters ---------- catalog: filename
[ "Pull", "colors", "from", "catalog" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/mass_age/cn/get_colors.py#L4-L56
train
annayqho/TheCannon
spectral_model.py
draw_spectra
def draw_spectra(md, ds): """ Generate best-fit spectra for all the test objects Parameters ---------- md: model The Cannon spectral model ds: Dataset Dataset object Returns ------- best_fluxes: ndarray The best-fit test fluxes best_ivars: The ...
python
def draw_spectra(md, ds): """ Generate best-fit spectra for all the test objects Parameters ---------- md: model The Cannon spectral model ds: Dataset Dataset object Returns ------- best_fluxes: ndarray The best-fit test fluxes best_ivars: The ...
[ "def", "draw_spectra", "(", "md", ",", "ds", ")", ":", "coeffs_all", ",", "covs", ",", "scatters", ",", "red_chisqs", ",", "pivots", ",", "label_vector", "=", "model", ".", "model", "nstars", "=", "len", "(", "dataset", ".", "test_SNR", ")", "cannon_flux...
Generate best-fit spectra for all the test objects Parameters ---------- md: model The Cannon spectral model ds: Dataset Dataset object Returns ------- best_fluxes: ndarray The best-fit test fluxes best_ivars: The best-fit test inverse variances
[ "Generate", "best", "-", "fit", "spectra", "for", "all", "the", "test", "objects" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/spectral_model.py#L3-L32
train
annayqho/TheCannon
spectral_model.py
overlay_spectra
def overlay_spectra(model, dataset): """ Run a series of diagnostics on the fitted spectra Parameters ---------- model: model best-fit Cannon spectral model dataset: Dataset original spectra """ best_flux, best_ivar = draw_spectra(model, dataset) coeffs_all, covs,...
python
def overlay_spectra(model, dataset): """ Run a series of diagnostics on the fitted spectra Parameters ---------- model: model best-fit Cannon spectral model dataset: Dataset original spectra """ best_flux, best_ivar = draw_spectra(model, dataset) coeffs_all, covs,...
[ "def", "overlay_spectra", "(", "model", ",", "dataset", ")", ":", "best_flux", ",", "best_ivar", "=", "draw_spectra", "(", "model", ",", "dataset", ")", "coeffs_all", ",", "covs", ",", "scatters", ",", "all_chisqs", ",", "pivots", ",", "label_vector", "=", ...
Run a series of diagnostics on the fitted spectra Parameters ---------- model: model best-fit Cannon spectral model dataset: Dataset original spectra
[ "Run", "a", "series", "of", "diagnostics", "on", "the", "fitted", "spectra" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/spectral_model.py#L35-L111
train
annayqho/TheCannon
spectral_model.py
residuals
def residuals(cannon_set, dataset): """ Stack spectrum fit residuals, sort by each label. Include histogram of the RMS at each pixel. Parameters ---------- cannon_set: Dataset best-fit Cannon spectra dataset: Dataset original spectra """ print("Stacking spectrum fit res...
python
def residuals(cannon_set, dataset): """ Stack spectrum fit residuals, sort by each label. Include histogram of the RMS at each pixel. Parameters ---------- cannon_set: Dataset best-fit Cannon spectra dataset: Dataset original spectra """ print("Stacking spectrum fit res...
[ "def", "residuals", "(", "cannon_set", ",", "dataset", ")", ":", "print", "(", "\"Stacking spectrum fit residuals\"", ")", "res", "=", "dataset", ".", "test_fluxes", "-", "cannon_set", ".", "test_fluxes", "bad", "=", "dataset", ".", "test_ivars", "==", "SMALL", ...
Stack spectrum fit residuals, sort by each label. Include histogram of the RMS at each pixel. Parameters ---------- cannon_set: Dataset best-fit Cannon spectra dataset: Dataset original spectra
[ "Stack", "spectrum", "fit", "residuals", "sort", "by", "each", "label", ".", "Include", "histogram", "of", "the", "RMS", "at", "each", "pixel", "." ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/spectral_model.py#L114-L211
train
annayqho/TheCannon
TheCannon/find_continuum_pixels.py
_find_contpix_given_cuts
def _find_contpix_given_cuts(f_cut, sig_cut, wl, fluxes, ivars): """ Find and return continuum pixels given the flux and sigma cut Parameters ---------- f_cut: float the upper limit imposed on the quantity (fbar-1) sig_cut: float the upper limit imposed on the quantity (f_sig) w...
python
def _find_contpix_given_cuts(f_cut, sig_cut, wl, fluxes, ivars): """ Find and return continuum pixels given the flux and sigma cut Parameters ---------- f_cut: float the upper limit imposed on the quantity (fbar-1) sig_cut: float the upper limit imposed on the quantity (f_sig) w...
[ "def", "_find_contpix_given_cuts", "(", "f_cut", ",", "sig_cut", ",", "wl", ",", "fluxes", ",", "ivars", ")", ":", "f_bar", "=", "np", ".", "median", "(", "fluxes", ",", "axis", "=", "0", ")", "sigma_f", "=", "np", ".", "var", "(", "fluxes", ",", "...
Find and return continuum pixels given the flux and sigma cut Parameters ---------- f_cut: float the upper limit imposed on the quantity (fbar-1) sig_cut: float the upper limit imposed on the quantity (f_sig) wl: numpy ndarray of length npixels rest-frame wavelength vector ...
[ "Find", "and", "return", "continuum", "pixels", "given", "the", "flux", "and", "sigma", "cut" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/find_continuum_pixels.py#L6-L34
train
annayqho/TheCannon
TheCannon/find_continuum_pixels.py
_find_contpix
def _find_contpix(wl, fluxes, ivars, target_frac): """ Find continuum pix in spec, meeting a set target fraction Parameters ---------- wl: numpy ndarray rest-frame wavelength vector fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, par...
python
def _find_contpix(wl, fluxes, ivars, target_frac): """ Find continuum pix in spec, meeting a set target fraction Parameters ---------- wl: numpy ndarray rest-frame wavelength vector fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, par...
[ "def", "_find_contpix", "(", "wl", ",", "fluxes", ",", "ivars", ",", "target_frac", ")", ":", "print", "(", "\"Target frac: %s\"", "%", "(", "target_frac", ")", ")", "bad1", "=", "np", ".", "median", "(", "ivars", ",", "axis", "=", "0", ")", "==", "S...
Find continuum pix in spec, meeting a set target fraction Parameters ---------- wl: numpy ndarray rest-frame wavelength vector fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, parallel to fluxes target_frac: float the fractio...
[ "Find", "continuum", "pix", "in", "spec", "meeting", "a", "set", "target", "fraction" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/find_continuum_pixels.py#L37-L85
train
annayqho/TheCannon
TheCannon/find_continuum_pixels.py
_find_contpix_regions
def _find_contpix_regions(wl, fluxes, ivars, frac, ranges): """ Find continuum pix in a spectrum split into chunks Parameters ---------- wl: numpy ndarray rest-frame wavelength vector fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, paral...
python
def _find_contpix_regions(wl, fluxes, ivars, frac, ranges): """ Find continuum pix in a spectrum split into chunks Parameters ---------- wl: numpy ndarray rest-frame wavelength vector fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, paral...
[ "def", "_find_contpix_regions", "(", "wl", ",", "fluxes", ",", "ivars", ",", "frac", ",", "ranges", ")", ":", "contmask", "=", "np", ".", "zeros", "(", "len", "(", "wl", ")", ",", "dtype", "=", "bool", ")", "for", "chunk", "in", "ranges", ":", "sta...
Find continuum pix in a spectrum split into chunks Parameters ---------- wl: numpy ndarray rest-frame wavelength vector fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, parallel to fluxes frac: float fraction of pixels in spectru...
[ "Find", "continuum", "pix", "in", "a", "spectrum", "split", "into", "chunks" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/find_continuum_pixels.py#L88-L119
train
annayqho/TheCannon
code/lamost/xcalib_5labels/cross_validation.py
group_data
def group_data(): """ Load the reference data, and assign each object a random integer from 0 to 7. Save the IDs. """ tr_obj = np.load("%s/ref_id.npz" %direc_ref)['arr_0'] groups = np.random.randint(0, 8, size=len(tr_obj)) np.savez("ref_groups.npz", groups)
python
def group_data(): """ Load the reference data, and assign each object a random integer from 0 to 7. Save the IDs. """ tr_obj = np.load("%s/ref_id.npz" %direc_ref)['arr_0'] groups = np.random.randint(0, 8, size=len(tr_obj)) np.savez("ref_groups.npz", groups)
[ "def", "group_data", "(", ")", ":", "tr_obj", "=", "np", ".", "load", "(", "\"%s/ref_id.npz\"", "%", "direc_ref", ")", "[", "'arr_0'", "]", "groups", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "8", ",", "size", "=", "len", "(", "tr_ob...
Load the reference data, and assign each object a random integer from 0 to 7. Save the IDs.
[ "Load", "the", "reference", "data", "and", "assign", "each", "object", "a", "random", "integer", "from", "0", "to", "7", ".", "Save", "the", "IDs", "." ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/xcalib_5labels/cross_validation.py#L26-L32
train
annayqho/TheCannon
code/lamost/xcalib_5labels/cross_validation.py
train
def train(ds, ii): """ Run the training step, given a dataset object. """ print("Loading model") m = model.CannonModel(2) print("Training...") m.fit(ds) np.savez("./ex%s_coeffs.npz" %ii, m.coeffs) np.savez("./ex%s_scatters.npz" %ii, m.scatters) np.savez("./ex%s_chisqs.npz" %ii, m.chisqs)...
python
def train(ds, ii): """ Run the training step, given a dataset object. """ print("Loading model") m = model.CannonModel(2) print("Training...") m.fit(ds) np.savez("./ex%s_coeffs.npz" %ii, m.coeffs) np.savez("./ex%s_scatters.npz" %ii, m.scatters) np.savez("./ex%s_chisqs.npz" %ii, m.chisqs)...
[ "def", "train", "(", "ds", ",", "ii", ")", ":", "print", "(", "\"Loading model\"", ")", "m", "=", "model", ".", "CannonModel", "(", "2", ")", "print", "(", "\"Training...\"", ")", "m", ".", "fit", "(", "ds", ")", "np", ".", "savez", "(", "\"./ex%s_...
Run the training step, given a dataset object.
[ "Run", "the", "training", "step", "given", "a", "dataset", "object", "." ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/xcalib_5labels/cross_validation.py#L35-L49
train
annayqho/TheCannon
code/lamost/xcalib_5labels/cross_validation.py
xvalidate
def xvalidate(): """ Train a model, leaving out a group corresponding to a random integer from 0 to 7, e.g. leave out 0. Test on the remaining 1/8 of the sample. """ print("Loading data") groups = np.load("ref_groups.npz")['arr_0'] ref_label = np.load("%s/ref_label.npz" %direc_ref)['arr_0'] ...
python
def xvalidate(): """ Train a model, leaving out a group corresponding to a random integer from 0 to 7, e.g. leave out 0. Test on the remaining 1/8 of the sample. """ print("Loading data") groups = np.load("ref_groups.npz")['arr_0'] ref_label = np.load("%s/ref_label.npz" %direc_ref)['arr_0'] ...
[ "def", "xvalidate", "(", ")", ":", "print", "(", "\"Loading data\"", ")", "groups", "=", "np", ".", "load", "(", "\"ref_groups.npz\"", ")", "[", "'arr_0'", "]", "ref_label", "=", "np", ".", "load", "(", "\"%s/ref_label.npz\"", "%", "direc_ref", ")", "[", ...
Train a model, leaving out a group corresponding to a random integer from 0 to 7, e.g. leave out 0. Test on the remaining 1/8 of the sample.
[ "Train", "a", "model", "leaving", "out", "a", "group", "corresponding", "to", "a", "random", "integer", "from", "0", "to", "7", "e", ".", "g", ".", "leave", "out", "0", ".", "Test", "on", "the", "remaining", "1", "/", "8", "of", "the", "sample", "....
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/xcalib_5labels/cross_validation.py#L159-L207
train
annayqho/TheCannon
code/aaomega/aaomega_munge_data.py
weighted_std
def weighted_std(values, weights): """ Calculate standard deviation weighted by errors """ average = np.average(values, weights=weights) variance = np.average((values-average)**2, weights=weights) return np.sqrt(variance)
python
def weighted_std(values, weights): """ Calculate standard deviation weighted by errors """ average = np.average(values, weights=weights) variance = np.average((values-average)**2, weights=weights) return np.sqrt(variance)
[ "def", "weighted_std", "(", "values", ",", "weights", ")", ":", "average", "=", "np", ".", "average", "(", "values", ",", "weights", "=", "weights", ")", "variance", "=", "np", ".", "average", "(", "(", "values", "-", "average", ")", "**", "2", ",", ...
Calculate standard deviation weighted by errors
[ "Calculate", "standard", "deviation", "weighted", "by", "errors" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/aaomega/aaomega_munge_data.py#L12-L16
train
annayqho/TheCannon
code/aaomega/aaomega_munge_data.py
estimate_noise
def estimate_noise(fluxes, contmask): """ Estimate the scatter in a region of the spectrum taken to be continuum """ nstars = fluxes.shape[0] scatter = np.zeros(nstars) for i,spec in enumerate(fluxes): cont = spec[contmask] scatter[i] = stats.funcs.mad_std(cont) return scatter
python
def estimate_noise(fluxes, contmask): """ Estimate the scatter in a region of the spectrum taken to be continuum """ nstars = fluxes.shape[0] scatter = np.zeros(nstars) for i,spec in enumerate(fluxes): cont = spec[contmask] scatter[i] = stats.funcs.mad_std(cont) return scatter
[ "def", "estimate_noise", "(", "fluxes", ",", "contmask", ")", ":", "nstars", "=", "fluxes", ".", "shape", "[", "0", "]", "scatter", "=", "np", ".", "zeros", "(", "nstars", ")", "for", "i", ",", "spec", "in", "enumerate", "(", "fluxes", ")", ":", "c...
Estimate the scatter in a region of the spectrum taken to be continuum
[ "Estimate", "the", "scatter", "in", "a", "region", "of", "the", "spectrum", "taken", "to", "be", "continuum" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/aaomega/aaomega_munge_data.py#L19-L27
train
annayqho/TheCannon
code/aaomega/aaomega_munge_data.py
load_ref_spectra
def load_ref_spectra(): """ Pull out wl, flux, ivar from files of training spectra """ data_dir = "/Users/annaho/Data/AAOmega/ref_spectra" # Load the files & count the number of training objects ff = glob.glob("%s/*.txt" %data_dir) nstars = len(ff) print("We have %s training objects" %nstars) ...
python
def load_ref_spectra(): """ Pull out wl, flux, ivar from files of training spectra """ data_dir = "/Users/annaho/Data/AAOmega/ref_spectra" # Load the files & count the number of training objects ff = glob.glob("%s/*.txt" %data_dir) nstars = len(ff) print("We have %s training objects" %nstars) ...
[ "def", "load_ref_spectra", "(", ")", ":", "data_dir", "=", "\"/Users/annaho/Data/AAOmega/ref_spectra\"", "# Load the files & count the number of training objects", "ff", "=", "glob", ".", "glob", "(", "\"%s/*.txt\"", "%", "data_dir", ")", "nstars", "=", "len", "(", "ff"...
Pull out wl, flux, ivar from files of training spectra
[ "Pull", "out", "wl", "flux", "ivar", "from", "files", "of", "training", "spectra" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/aaomega/aaomega_munge_data.py#L30-L55
train
annayqho/TheCannon
code/aaomega/aaomega_munge_data.py
load_data
def load_data(): data_dir = "/Users/annaho/Data/AAOmega" out_dir = "%s/%s" %(data_dir, "Run_13_July") """ Use all the above functions to set data up for The Cannon """ ff, wl, tr_flux, tr_ivar = load_ref_spectra() """ pick one that doesn't have extra dead pixels """ skylines = tr_ivar[4,:] # s...
python
def load_data(): data_dir = "/Users/annaho/Data/AAOmega" out_dir = "%s/%s" %(data_dir, "Run_13_July") """ Use all the above functions to set data up for The Cannon """ ff, wl, tr_flux, tr_ivar = load_ref_spectra() """ pick one that doesn't have extra dead pixels """ skylines = tr_ivar[4,:] # s...
[ "def", "load_data", "(", ")", ":", "data_dir", "=", "\"/Users/annaho/Data/AAOmega\"", "out_dir", "=", "\"%s/%s\"", "%", "(", "data_dir", ",", "\"Run_13_July\"", ")", "ff", ",", "wl", ",", "tr_flux", ",", "tr_ivar", "=", "load_ref_spectra", "(", ")", "\"\"\" pi...
Use all the above functions to set data up for The Cannon
[ "Use", "all", "the", "above", "functions", "to", "set", "data", "up", "for", "The", "Cannon" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/aaomega/aaomega_munge_data.py#L109-L157
train
annayqho/TheCannon
code/aaomega/aaomega_munge_data.py
make_full_ivar
def make_full_ivar(): """ take the scatters and skylines and make final ivars """ # skylines come as an ivar # don't use them for now, because I don't really trust them... # skylines = np.load("%s/skylines.npz" %DATA_DIR)['arr_0'] ref_flux = np.load("%s/ref_flux_all.npz" %DATA_DIR)['arr_0'] re...
python
def make_full_ivar(): """ take the scatters and skylines and make final ivars """ # skylines come as an ivar # don't use them for now, because I don't really trust them... # skylines = np.load("%s/skylines.npz" %DATA_DIR)['arr_0'] ref_flux = np.load("%s/ref_flux_all.npz" %DATA_DIR)['arr_0'] re...
[ "def", "make_full_ivar", "(", ")", ":", "# skylines come as an ivar", "# don't use them for now, because I don't really trust them...", "# skylines = np.load(\"%s/skylines.npz\" %DATA_DIR)['arr_0']", "ref_flux", "=", "np", ".", "load", "(", "\"%s/ref_flux_all.npz\"", "%", "DATA_DIR",...
take the scatters and skylines and make final ivars
[ "take", "the", "scatters", "and", "skylines", "and", "make", "final", "ivars" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/aaomega/aaomega_munge_data.py#L160-L183
train
annayqho/TheCannon
TheCannon/normalization.py
_sinusoid
def _sinusoid(x, p, L, y): """ Return the sinusoid cont func evaluated at input x for the continuum. Parameters ---------- x: float or np.array data, input to function p: ndarray coefficients of fitting function L: float width of x data y: float or np.array ...
python
def _sinusoid(x, p, L, y): """ Return the sinusoid cont func evaluated at input x for the continuum. Parameters ---------- x: float or np.array data, input to function p: ndarray coefficients of fitting function L: float width of x data y: float or np.array ...
[ "def", "_sinusoid", "(", "x", ",", "p", ",", "L", ",", "y", ")", ":", "N", "=", "int", "(", "len", "(", "p", ")", "/", "2", ")", "n", "=", "np", ".", "linspace", "(", "0", ",", "N", ",", "N", "+", "1", ")", "k", "=", "n", "*", "np", ...
Return the sinusoid cont func evaluated at input x for the continuum. Parameters ---------- x: float or np.array data, input to function p: ndarray coefficients of fitting function L: float width of x data y: float or np.array output data corresponding to input ...
[ "Return", "the", "sinusoid", "cont", "func", "evaluated", "at", "input", "x", "for", "the", "continuum", "." ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L33-L58
train
annayqho/TheCannon
TheCannon/normalization.py
_weighted_median
def _weighted_median(values, weights, quantile): """ Calculate a weighted median for values above a particular quantile cut Used in pseudo continuum normalization Parameters ---------- values: np ndarray of floats the values to take the median of weights: np ndarray of floats t...
python
def _weighted_median(values, weights, quantile): """ Calculate a weighted median for values above a particular quantile cut Used in pseudo continuum normalization Parameters ---------- values: np ndarray of floats the values to take the median of weights: np ndarray of floats t...
[ "def", "_weighted_median", "(", "values", ",", "weights", ",", "quantile", ")", ":", "sindx", "=", "np", ".", "argsort", "(", "values", ")", "cvalues", "=", "1.", "*", "np", ".", "cumsum", "(", "weights", "[", "sindx", "]", ")", "if", "cvalues", "[",...
Calculate a weighted median for values above a particular quantile cut Used in pseudo continuum normalization Parameters ---------- values: np ndarray of floats the values to take the median of weights: np ndarray of floats the weights associated with the values quantile: float...
[ "Calculate", "a", "weighted", "median", "for", "values", "above", "a", "particular", "quantile", "cut" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L61-L88
train
annayqho/TheCannon
TheCannon/normalization.py
_find_cont_gaussian_smooth
def _find_cont_gaussian_smooth(wl, fluxes, ivars, w): """ Returns the weighted mean block of spectra Parameters ---------- wl: numpy ndarray wavelength vector flux: numpy ndarray block of flux values ivar: numpy ndarray block of ivar values L: float width of...
python
def _find_cont_gaussian_smooth(wl, fluxes, ivars, w): """ Returns the weighted mean block of spectra Parameters ---------- wl: numpy ndarray wavelength vector flux: numpy ndarray block of flux values ivar: numpy ndarray block of ivar values L: float width of...
[ "def", "_find_cont_gaussian_smooth", "(", "wl", ",", "fluxes", ",", "ivars", ",", "w", ")", ":", "print", "(", "\"Finding the continuum\"", ")", "bot", "=", "np", ".", "dot", "(", "ivars", ",", "w", ".", "T", ")", "top", "=", "np", ".", "dot", "(", ...
Returns the weighted mean block of spectra Parameters ---------- wl: numpy ndarray wavelength vector flux: numpy ndarray block of flux values ivar: numpy ndarray block of ivar values L: float width of Gaussian used to assign weights Returns ------- ...
[ "Returns", "the", "weighted", "mean", "block", "of", "spectra" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L91-L116
train
annayqho/TheCannon
TheCannon/normalization.py
_cont_norm_gaussian_smooth
def _cont_norm_gaussian_smooth(dataset, L): """ Continuum normalize by dividing by a Gaussian-weighted smoothed spectrum Parameters ---------- dataset: Dataset the dataset to continuum normalize L: float the width of the Gaussian used for weighting Returns ------- datas...
python
def _cont_norm_gaussian_smooth(dataset, L): """ Continuum normalize by dividing by a Gaussian-weighted smoothed spectrum Parameters ---------- dataset: Dataset the dataset to continuum normalize L: float the width of the Gaussian used for weighting Returns ------- datas...
[ "def", "_cont_norm_gaussian_smooth", "(", "dataset", ",", "L", ")", ":", "print", "(", "\"Gaussian smoothing the entire dataset...\"", ")", "w", "=", "gaussian_weight_matrix", "(", "dataset", ".", "wl", ",", "L", ")", "print", "(", "\"Gaussian smoothing the training s...
Continuum normalize by dividing by a Gaussian-weighted smoothed spectrum Parameters ---------- dataset: Dataset the dataset to continuum normalize L: float the width of the Gaussian used for weighting Returns ------- dataset: Dataset updated dataset
[ "Continuum", "normalize", "by", "dividing", "by", "a", "Gaussian", "-", "weighted", "smoothed", "spectrum" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L119-L147
train
annayqho/TheCannon
TheCannon/normalization.py
_find_cont_fitfunc
def _find_cont_fitfunc(fluxes, ivars, contmask, deg, ffunc, n_proc=1): """ Fit a continuum to a continuum pixels in a segment of spectra Functional form can be either sinusoid or chebyshev, with specified degree Parameters ---------- fluxes: numpy ndarray of shape (nstars, npixels) trainin...
python
def _find_cont_fitfunc(fluxes, ivars, contmask, deg, ffunc, n_proc=1): """ Fit a continuum to a continuum pixels in a segment of spectra Functional form can be either sinusoid or chebyshev, with specified degree Parameters ---------- fluxes: numpy ndarray of shape (nstars, npixels) trainin...
[ "def", "_find_cont_fitfunc", "(", "fluxes", ",", "ivars", ",", "contmask", ",", "deg", ",", "ffunc", ",", "n_proc", "=", "1", ")", ":", "nstars", "=", "fluxes", ".", "shape", "[", "0", "]", "npixels", "=", "fluxes", ".", "shape", "[", "1", "]", "co...
Fit a continuum to a continuum pixels in a segment of spectra Functional form can be either sinusoid or chebyshev, with specified degree Parameters ---------- fluxes: numpy ndarray of shape (nstars, npixels) training set or test set pixel intensities ivars: numpy ndarray of shape (nstars,...
[ "Fit", "a", "continuum", "to", "a", "continuum", "pixels", "in", "a", "segment", "of", "spectra" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L150-L220
train
annayqho/TheCannon
TheCannon/normalization.py
_find_cont_fitfunc_regions
def _find_cont_fitfunc_regions(fluxes, ivars, contmask, deg, ranges, ffunc, n_proc=1): """ Run fit_cont, dealing with spectrum in regions or chunks This is useful if a spectrum has gaps. Parameters ---------- fluxes: ndarray of shape (nstars, npixels) trainin...
python
def _find_cont_fitfunc_regions(fluxes, ivars, contmask, deg, ranges, ffunc, n_proc=1): """ Run fit_cont, dealing with spectrum in regions or chunks This is useful if a spectrum has gaps. Parameters ---------- fluxes: ndarray of shape (nstars, npixels) trainin...
[ "def", "_find_cont_fitfunc_regions", "(", "fluxes", ",", "ivars", ",", "contmask", ",", "deg", ",", "ranges", ",", "ffunc", ",", "n_proc", "=", "1", ")", ":", "nstars", "=", "fluxes", ".", "shape", "[", "0", "]", "npixels", "=", "fluxes", ".", "shape",...
Run fit_cont, dealing with spectrum in regions or chunks This is useful if a spectrum has gaps. Parameters ---------- fluxes: ndarray of shape (nstars, npixels) training set or test set pixel intensities ivars: numpy ndarray of shape (nstars, npixels) inverse variances, parallel t...
[ "Run", "fit_cont", "dealing", "with", "spectrum", "in", "regions", "or", "chunks" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L223-L271
train
annayqho/TheCannon
TheCannon/normalization.py
_find_cont_running_quantile
def _find_cont_running_quantile(wl, fluxes, ivars, q, delta_lambda, verbose=False): """ Perform continuum normalization using a running quantile Parameters ---------- wl: numpy ndarray wavelength vector fluxes: numpy ndarray of shape (nstars, npixels) ...
python
def _find_cont_running_quantile(wl, fluxes, ivars, q, delta_lambda, verbose=False): """ Perform continuum normalization using a running quantile Parameters ---------- wl: numpy ndarray wavelength vector fluxes: numpy ndarray of shape (nstars, npixels) ...
[ "def", "_find_cont_running_quantile", "(", "wl", ",", "fluxes", ",", "ivars", ",", "q", ",", "delta_lambda", ",", "verbose", "=", "False", ")", ":", "cont", "=", "np", ".", "zeros", "(", "fluxes", ".", "shape", ")", "nstars", "=", "fluxes", ".", "shape...
Perform continuum normalization using a running quantile Parameters ---------- wl: numpy ndarray wavelength vector fluxes: numpy ndarray of shape (nstars, npixels) pixel intensities ivars: numpy ndarray of shape (nstars, npixels) inverse variances, parallel to fluxes q:...
[ "Perform", "continuum", "normalization", "using", "a", "running", "quantile" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L274-L310
train
annayqho/TheCannon
TheCannon/normalization.py
_cont_norm_running_quantile_mp
def _cont_norm_running_quantile_mp(wl, fluxes, ivars, q, delta_lambda, n_proc=2, verbose=False): """ The same as _cont_norm_running_quantile() above, but using multi-processing. Bo Zhang (NAOC) """ nStar = fluxes.shape[0] # start mp.Pool mp_results = ...
python
def _cont_norm_running_quantile_mp(wl, fluxes, ivars, q, delta_lambda, n_proc=2, verbose=False): """ The same as _cont_norm_running_quantile() above, but using multi-processing. Bo Zhang (NAOC) """ nStar = fluxes.shape[0] # start mp.Pool mp_results = ...
[ "def", "_cont_norm_running_quantile_mp", "(", "wl", ",", "fluxes", ",", "ivars", ",", "q", ",", "delta_lambda", ",", "n_proc", "=", "2", ",", "verbose", "=", "False", ")", ":", "nStar", "=", "fluxes", ".", "shape", "[", "0", "]", "# start mp.Pool", "mp_r...
The same as _cont_norm_running_quantile() above, but using multi-processing. Bo Zhang (NAOC)
[ "The", "same", "as", "_cont_norm_running_quantile", "()", "above", "but", "using", "multi", "-", "processing", "." ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L337-L371
train
annayqho/TheCannon
TheCannon/normalization.py
_cont_norm_running_quantile_regions
def _cont_norm_running_quantile_regions(wl, fluxes, ivars, q, delta_lambda, ranges, verbose=True): """ Perform continuum normalization using running quantile, for spectrum that comes in chunks """ print("contnorm.py: continuum norm using running quantile") pri...
python
def _cont_norm_running_quantile_regions(wl, fluxes, ivars, q, delta_lambda, ranges, verbose=True): """ Perform continuum normalization using running quantile, for spectrum that comes in chunks """ print("contnorm.py: continuum norm using running quantile") pri...
[ "def", "_cont_norm_running_quantile_regions", "(", "wl", ",", "fluxes", ",", "ivars", ",", "q", ",", "delta_lambda", ",", "ranges", ",", "verbose", "=", "True", ")", ":", "print", "(", "\"contnorm.py: continuum norm using running quantile\"", ")", "print", "(", "\...
Perform continuum normalization using running quantile, for spectrum that comes in chunks
[ "Perform", "continuum", "normalization", "using", "running", "quantile", "for", "spectrum", "that", "comes", "in", "chunks" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L380-L398
train
annayqho/TheCannon
TheCannon/normalization.py
_cont_norm_running_quantile_regions_mp
def _cont_norm_running_quantile_regions_mp(wl, fluxes, ivars, q, delta_lambda, ranges, n_proc=2, verbose=False): """ Perform continuum normalization using running quantile, for spectrum that comes in chunks. The same as _cont_norm_running_quantile_regions(), ...
python
def _cont_norm_running_quantile_regions_mp(wl, fluxes, ivars, q, delta_lambda, ranges, n_proc=2, verbose=False): """ Perform continuum normalization using running quantile, for spectrum that comes in chunks. The same as _cont_norm_running_quantile_regions(), ...
[ "def", "_cont_norm_running_quantile_regions_mp", "(", "wl", ",", "fluxes", ",", "ivars", ",", "q", ",", "delta_lambda", ",", "ranges", ",", "n_proc", "=", "2", ",", "verbose", "=", "False", ")", ":", "print", "(", "\"contnorm.py: continuum norm using running quant...
Perform continuum normalization using running quantile, for spectrum that comes in chunks. The same as _cont_norm_running_quantile_regions(), but using multi-processing. Bo Zhang (NAOC)
[ "Perform", "continuum", "normalization", "using", "running", "quantile", "for", "spectrum", "that", "comes", "in", "chunks", "." ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L401-L431
train
annayqho/TheCannon
TheCannon/normalization.py
_cont_norm
def _cont_norm(fluxes, ivars, cont): """ Continuum-normalize a continuous segment of spectra. Parameters ---------- fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, parallel to fluxes contmask: boolean mask True indicates that pixel is co...
python
def _cont_norm(fluxes, ivars, cont): """ Continuum-normalize a continuous segment of spectra. Parameters ---------- fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, parallel to fluxes contmask: boolean mask True indicates that pixel is co...
[ "def", "_cont_norm", "(", "fluxes", ",", "ivars", ",", "cont", ")", ":", "nstars", "=", "fluxes", ".", "shape", "[", "0", "]", "npixels", "=", "fluxes", ".", "shape", "[", "1", "]", "norm_fluxes", "=", "np", ".", "ones", "(", "fluxes", ".", "shape"...
Continuum-normalize a continuous segment of spectra. Parameters ---------- fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, parallel to fluxes contmask: boolean mask True indicates that pixel is continuum Returns ------- norm_flu...
[ "Continuum", "-", "normalize", "a", "continuous", "segment", "of", "spectra", "." ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L434-L461
train
annayqho/TheCannon
TheCannon/normalization.py
_cont_norm_regions
def _cont_norm_regions(fluxes, ivars, cont, ranges): """ Perform continuum normalization for spectra in chunks Useful for spectra that have gaps Parameters --------- fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, parallel to fluxes cont: num...
python
def _cont_norm_regions(fluxes, ivars, cont, ranges): """ Perform continuum normalization for spectra in chunks Useful for spectra that have gaps Parameters --------- fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, parallel to fluxes cont: num...
[ "def", "_cont_norm_regions", "(", "fluxes", ",", "ivars", ",", "cont", ",", "ranges", ")", ":", "nstars", "=", "fluxes", ".", "shape", "[", "0", "]", "norm_fluxes", "=", "np", ".", "zeros", "(", "fluxes", ".", "shape", ")", "norm_ivars", "=", "np", "...
Perform continuum normalization for spectra in chunks Useful for spectra that have gaps Parameters --------- fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, parallel to fluxes cont: numpy ndarray the continuum ranges: list or np ndarr...
[ "Perform", "continuum", "normalization", "for", "spectra", "in", "chunks" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L464-L501
train
annayqho/TheCannon
TheCannon/model.py
CannonModel.train
def train(self, ds): """ Run training step: solve for best-fit spectral model """ if self.useErrors: self.coeffs, self.scatters, self.new_tr_labels, self.chisqs, self.pivots, self.scales = _train_model_new(ds) else: self.coeffs, self.scatters, self.chisqs, self.pivots, se...
python
def train(self, ds): """ Run training step: solve for best-fit spectral model """ if self.useErrors: self.coeffs, self.scatters, self.new_tr_labels, self.chisqs, self.pivots, self.scales = _train_model_new(ds) else: self.coeffs, self.scatters, self.chisqs, self.pivots, se...
[ "def", "train", "(", "self", ",", "ds", ")", ":", "if", "self", ".", "useErrors", ":", "self", ".", "coeffs", ",", "self", ".", "scatters", ",", "self", ".", "new_tr_labels", ",", "self", ".", "chisqs", ",", "self", ".", "pivots", ",", "self", ".",...
Run training step: solve for best-fit spectral model
[ "Run", "training", "step", ":", "solve", "for", "best", "-", "fit", "spectral", "model" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/model.py#L36-L41
train
annayqho/TheCannon
TheCannon/model.py
CannonModel.infer_spectra
def infer_spectra(self, ds): """ After inferring labels for the test spectra, infer the model spectra and update the dataset model_spectra attribute. Parameters ---------- ds: Dataset object """ lvec_all = _get_lvec(ds.test_label_vals, se...
python
def infer_spectra(self, ds): """ After inferring labels for the test spectra, infer the model spectra and update the dataset model_spectra attribute. Parameters ---------- ds: Dataset object """ lvec_all = _get_lvec(ds.test_label_vals, se...
[ "def", "infer_spectra", "(", "self", ",", "ds", ")", ":", "lvec_all", "=", "_get_lvec", "(", "ds", ".", "test_label_vals", ",", "self", ".", "pivots", ",", "self", ".", "scales", ",", "derivs", "=", "False", ")", "self", ".", "model_spectra", "=", "np"...
After inferring labels for the test spectra, infer the model spectra and update the dataset model_spectra attribute. Parameters ---------- ds: Dataset object
[ "After", "inferring", "labels", "for", "the", "test", "spectra", "infer", "the", "model", "spectra", "and", "update", "the", "dataset", "model_spectra", "attribute", ".", "Parameters", "----------", "ds", ":", "Dataset", "object" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/model.py#L66-L77
train
annayqho/TheCannon
TheCannon/model.py
CannonModel.plot_contpix
def plot_contpix(self, x, y, contpix_x, contpix_y, figname): """ Plot baseline spec with continuum pix overlaid Parameters ---------- """ fig, axarr = plt.subplots(2, sharex=True) plt.xlabel(r"Wavelength $\lambda (\AA)$") plt.xlim(min(x), max(x)) ax = ax...
python
def plot_contpix(self, x, y, contpix_x, contpix_y, figname): """ Plot baseline spec with continuum pix overlaid Parameters ---------- """ fig, axarr = plt.subplots(2, sharex=True) plt.xlabel(r"Wavelength $\lambda (\AA)$") plt.xlim(min(x), max(x)) ax = ax...
[ "def", "plot_contpix", "(", "self", ",", "x", ",", "y", ",", "contpix_x", ",", "contpix_y", ",", "figname", ")", ":", "fig", ",", "axarr", "=", "plt", ".", "subplots", "(", "2", ",", "sharex", "=", "True", ")", "plt", ".", "xlabel", "(", "r\"Wavele...
Plot baseline spec with continuum pix overlaid Parameters ----------
[ "Plot", "baseline", "spec", "with", "continuum", "pix", "overlaid" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/model.py#L80-L111
train
annayqho/TheCannon
TheCannon/model.py
CannonModel.diagnostics_contpix
def diagnostics_contpix(self, data, nchunks=10, fig = "baseline_spec_with_cont_pix"): """ Call plot_contpix once for each nth of the spectrum """ if data.contmask is None: print("No contmask set") else: coeffs_all = self.coeffs wl = data.wl baselin...
python
def diagnostics_contpix(self, data, nchunks=10, fig = "baseline_spec_with_cont_pix"): """ Call plot_contpix once for each nth of the spectrum """ if data.contmask is None: print("No contmask set") else: coeffs_all = self.coeffs wl = data.wl baselin...
[ "def", "diagnostics_contpix", "(", "self", ",", "data", ",", "nchunks", "=", "10", ",", "fig", "=", "\"baseline_spec_with_cont_pix\"", ")", ":", "if", "data", ".", "contmask", "is", "None", ":", "print", "(", "\"No contmask set\"", ")", "else", ":", "coeffs_...
Call plot_contpix once for each nth of the spectrum
[ "Call", "plot_contpix", "once", "for", "each", "nth", "of", "the", "spectrum" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/model.py#L114-L138
train
annayqho/TheCannon
TheCannon/model.py
CannonModel.diagnostics_plot_chisq
def diagnostics_plot_chisq(self, ds, figname = "modelfit_chisqs.png"): """ Produce a set of diagnostic plots for the model Parameters ---------- (optional) chisq_dist_plot_name: str Filename of output saved plot """ label_names = ds.get_plotting_labels() ...
python
def diagnostics_plot_chisq(self, ds, figname = "modelfit_chisqs.png"): """ Produce a set of diagnostic plots for the model Parameters ---------- (optional) chisq_dist_plot_name: str Filename of output saved plot """ label_names = ds.get_plotting_labels() ...
[ "def", "diagnostics_plot_chisq", "(", "self", ",", "ds", ",", "figname", "=", "\"modelfit_chisqs.png\"", ")", ":", "label_names", "=", "ds", ".", "get_plotting_labels", "(", ")", "lams", "=", "ds", ".", "wl", "pivots", "=", "self", ".", "pivots", "npixels", ...
Produce a set of diagnostic plots for the model Parameters ---------- (optional) chisq_dist_plot_name: str Filename of output saved plot
[ "Produce", "a", "set", "of", "diagnostic", "plots", "for", "the", "model" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/model.py#L213-L242
train
annayqho/TheCannon
code/lamost/mass_age/cn/calc_astroseismic_mass.py
calc_mass
def calc_mass(nu_max, delta_nu, teff): """ asteroseismic scaling relations """ NU_MAX = 3140.0 # microHz DELTA_NU = 135.03 # microHz TEFF = 5777.0 return (nu_max/NU_MAX)**3 * (delta_nu/DELTA_NU)**(-4) * (teff/TEFF)**1.5
python
def calc_mass(nu_max, delta_nu, teff): """ asteroseismic scaling relations """ NU_MAX = 3140.0 # microHz DELTA_NU = 135.03 # microHz TEFF = 5777.0 return (nu_max/NU_MAX)**3 * (delta_nu/DELTA_NU)**(-4) * (teff/TEFF)**1.5
[ "def", "calc_mass", "(", "nu_max", ",", "delta_nu", ",", "teff", ")", ":", "NU_MAX", "=", "3140.0", "# microHz", "DELTA_NU", "=", "135.03", "# microHz", "TEFF", "=", "5777.0", "return", "(", "nu_max", "/", "NU_MAX", ")", "**", "3", "*", "(", "delta_nu", ...
asteroseismic scaling relations
[ "asteroseismic", "scaling", "relations" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/mass_age/cn/calc_astroseismic_mass.py#L3-L8
train
annayqho/TheCannon
code/lamost/mass_age/mass_age_functions.py
calc_mass_2
def calc_mass_2(mh,cm,nm,teff,logg): """ Table A2 in Martig 2016 """ CplusN = calc_sum(mh,cm,nm) t = teff/4000. return (95.8689 - 10.4042*mh - 0.7266*mh**2 + 41.3642*cm - 5.3242*cm*mh - 46.7792*cm**2 + 15.0508*nm - 0.9342*nm*mh - 30.5159*nm*cm - 1.6083*nm**2 - 67.6093...
python
def calc_mass_2(mh,cm,nm,teff,logg): """ Table A2 in Martig 2016 """ CplusN = calc_sum(mh,cm,nm) t = teff/4000. return (95.8689 - 10.4042*mh - 0.7266*mh**2 + 41.3642*cm - 5.3242*cm*mh - 46.7792*cm**2 + 15.0508*nm - 0.9342*nm*mh - 30.5159*nm*cm - 1.6083*nm**2 - 67.6093...
[ "def", "calc_mass_2", "(", "mh", ",", "cm", ",", "nm", ",", "teff", ",", "logg", ")", ":", "CplusN", "=", "calc_sum", "(", "mh", ",", "cm", ",", "nm", ")", "t", "=", "teff", "/", "4000.", "return", "(", "95.8689", "-", "10.4042", "*", "mh", "-"...
Table A2 in Martig 2016
[ "Table", "A2", "in", "Martig", "2016" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/mass_age/mass_age_functions.py#L39-L48
train
annayqho/TheCannon
TheCannon/helpers/corner/corner.py
corner
def corner(xs, bins=20, range=None, weights=None, color="k", smooth=None, smooth1d=None, labels=None, label_kwargs=None, show_titles=False, title_fmt=".2f", title_kwargs=None, truths=None, truth_color="#4682b4", scale_hist=False, quantiles=None, verbose=False, fig=...
python
def corner(xs, bins=20, range=None, weights=None, color="k", smooth=None, smooth1d=None, labels=None, label_kwargs=None, show_titles=False, title_fmt=".2f", title_kwargs=None, truths=None, truth_color="#4682b4", scale_hist=False, quantiles=None, verbose=False, fig=...
[ "def", "corner", "(", "xs", ",", "bins", "=", "20", ",", "range", "=", "None", ",", "weights", "=", "None", ",", "color", "=", "\"k\"", ",", "smooth", "=", "None", ",", "smooth1d", "=", "None", ",", "labels", "=", "None", ",", "label_kwargs", "=", ...
Make a *sick* corner plot showing the projections of a data set in a multi-dimensional space. kwargs are passed to hist2d() or used for `matplotlib` styling. Parameters ---------- xs : array_like (nsamples, ndim) The samples. This should be a 1- or 2-dimensional array. For a 1-D arr...
[ "Make", "a", "*", "sick", "*", "corner", "plot", "showing", "the", "projections", "of", "a", "data", "set", "in", "a", "multi", "-", "dimensional", "space", ".", "kwargs", "are", "passed", "to", "hist2d", "()", "or", "used", "for", "matplotlib", "styling...
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/helpers/corner/corner.py#L43-L392
train
annayqho/TheCannon
TheCannon/helpers/corner/corner.py
quantile
def quantile(x, q, weights=None): """ Like numpy.percentile, but: * Values of q are quantiles [0., 1.] rather than percentiles [0., 100.] * scalar q not supported (q must be iterable) * optional weights on x """ if weights is None: return np.percentile(x, [100. * qi for qi in q]) ...
python
def quantile(x, q, weights=None): """ Like numpy.percentile, but: * Values of q are quantiles [0., 1.] rather than percentiles [0., 100.] * scalar q not supported (q must be iterable) * optional weights on x """ if weights is None: return np.percentile(x, [100. * qi for qi in q]) ...
[ "def", "quantile", "(", "x", ",", "q", ",", "weights", "=", "None", ")", ":", "if", "weights", "is", "None", ":", "return", "np", ".", "percentile", "(", "x", ",", "[", "100.", "*", "qi", "for", "qi", "in", "q", "]", ")", "else", ":", "idx", ...
Like numpy.percentile, but: * Values of q are quantiles [0., 1.] rather than percentiles [0., 100.] * scalar q not supported (q must be iterable) * optional weights on x
[ "Like", "numpy", ".", "percentile", "but", ":" ]
8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/helpers/corner/corner.py#L395-L411
train