repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.delete_columns | def delete_columns(self, columns):
"""
Delete columns from the DataFrame
:param columns: list of columns to delete
:return: nothing
"""
columns = [columns] if not isinstance(columns, (list, blist)) else columns
if not all([x in self._columns for x in columns]):
... | python | def delete_columns(self, columns):
"""
Delete columns from the DataFrame
:param columns: list of columns to delete
:return: nothing
"""
columns = [columns] if not isinstance(columns, (list, blist)) else columns
if not all([x in self._columns for x in columns]):
... | [
"def",
"delete_columns",
"(",
"self",
",",
"columns",
")",
":",
"columns",
"=",
"[",
"columns",
"]",
"if",
"not",
"isinstance",
"(",
"columns",
",",
"(",
"list",
",",
"blist",
")",
")",
"else",
"columns",
"if",
"not",
"all",
"(",
"[",
"x",
"in",
"s... | Delete columns from the DataFrame
:param columns: list of columns to delete
:return: nothing | [
"Delete",
"columns",
"from",
"the",
"DataFrame"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L945-L960 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.sort_index | def sort_index(self):
"""
Sort the DataFrame by the index. The sort modifies the DataFrame inplace
:return: nothing
"""
sort = sorted_list_indexes(self._index)
# sort index
self._index = blist([self._index[x] for x in sort]) if self._blist else [self._index[x] fo... | python | def sort_index(self):
"""
Sort the DataFrame by the index. The sort modifies the DataFrame inplace
:return: nothing
"""
sort = sorted_list_indexes(self._index)
# sort index
self._index = blist([self._index[x] for x in sort]) if self._blist else [self._index[x] fo... | [
"def",
"sort_index",
"(",
"self",
")",
":",
"sort",
"=",
"sorted_list_indexes",
"(",
"self",
".",
"_index",
")",
"# sort index",
"self",
".",
"_index",
"=",
"blist",
"(",
"[",
"self",
".",
"_index",
"[",
"x",
"]",
"for",
"x",
"in",
"sort",
"]",
")",
... | Sort the DataFrame by the index. The sort modifies the DataFrame inplace
:return: nothing | [
"Sort",
"the",
"DataFrame",
"by",
"the",
"index",
".",
"The",
"sort",
"modifies",
"the",
"DataFrame",
"inplace"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L962-L973 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.sort_columns | def sort_columns(self, column, key=None, reverse=False):
"""
Sort the DataFrame by one of the columns. The sort modifies the DataFrame inplace. The key and reverse
parameters have the same meaning as for the built-in sort() function.
:param column: column name to use for the sort
... | python | def sort_columns(self, column, key=None, reverse=False):
"""
Sort the DataFrame by one of the columns. The sort modifies the DataFrame inplace. The key and reverse
parameters have the same meaning as for the built-in sort() function.
:param column: column name to use for the sort
... | [
"def",
"sort_columns",
"(",
"self",
",",
"column",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"column",
",",
"(",
"list",
",",
"blist",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Can only sort by a single c... | Sort the DataFrame by one of the columns. The sort modifies the DataFrame inplace. The key and reverse
parameters have the same meaning as for the built-in sort() function.
:param column: column name to use for the sort
:param key: if not None then a function of one argument that is used to ext... | [
"Sort",
"the",
"DataFrame",
"by",
"one",
"of",
"the",
"columns",
".",
"The",
"sort",
"modifies",
"the",
"DataFrame",
"inplace",
".",
"The",
"key",
"and",
"reverse",
"parameters",
"have",
"the",
"same",
"meaning",
"as",
"for",
"the",
"built",
"-",
"in",
"... | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L975-L993 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.validate_integrity | def validate_integrity(self):
"""
Validate the integrity of the DataFrame. This checks that the indexes, column names and internal data are not
corrupted. Will raise an error if there is a problem.
:return: nothing
"""
self._validate_columns(self._columns)
self._... | python | def validate_integrity(self):
"""
Validate the integrity of the DataFrame. This checks that the indexes, column names and internal data are not
corrupted. Will raise an error if there is a problem.
:return: nothing
"""
self._validate_columns(self._columns)
self._... | [
"def",
"validate_integrity",
"(",
"self",
")",
":",
"self",
".",
"_validate_columns",
"(",
"self",
".",
"_columns",
")",
"self",
".",
"_validate_index",
"(",
"self",
".",
"_index",
")",
"self",
".",
"_validate_data",
"(",
")"
] | Validate the integrity of the DataFrame. This checks that the indexes, column names and internal data are not
corrupted. Will raise an error if there is a problem.
:return: nothing | [
"Validate",
"the",
"integrity",
"of",
"the",
"DataFrame",
".",
"This",
"checks",
"that",
"the",
"indexes",
"column",
"names",
"and",
"internal",
"data",
"are",
"not",
"corrupted",
".",
"Will",
"raise",
"an",
"error",
"if",
"there",
"is",
"a",
"problem",
".... | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L1016-L1025 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.append | def append(self, data_frame):
"""
Append another DataFrame to this DataFrame. If the new data_frame has columns that are not in the current
DataFrame then new columns will be created. All of the indexes in the data_frame must be different from the
current indexes or will raise an error.
... | python | def append(self, data_frame):
"""
Append another DataFrame to this DataFrame. If the new data_frame has columns that are not in the current
DataFrame then new columns will be created. All of the indexes in the data_frame must be different from the
current indexes or will raise an error.
... | [
"def",
"append",
"(",
"self",
",",
"data_frame",
")",
":",
"if",
"len",
"(",
"data_frame",
")",
"==",
"0",
":",
"# empty DataFrame, do nothing",
"return",
"data_frame_index",
"=",
"data_frame",
".",
"index",
"combined_index",
"=",
"self",
".",
"_index",
"+",
... | Append another DataFrame to this DataFrame. If the new data_frame has columns that are not in the current
DataFrame then new columns will be created. All of the indexes in the data_frame must be different from the
current indexes or will raise an error.
:param data_frame: DataFrame to append
... | [
"Append",
"another",
"DataFrame",
"to",
"this",
"DataFrame",
".",
"If",
"the",
"new",
"data_frame",
"has",
"columns",
"that",
"are",
"not",
"in",
"the",
"current",
"DataFrame",
"then",
"new",
"columns",
"will",
"be",
"created",
".",
"All",
"of",
"the",
"in... | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L1027-L1047 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.add | def add(self, left_column, right_column, indexes=None):
"""
Math helper method that adds element-wise two columns. If indexes are not None then will only perform the math
on that sub-set of the columns.
:param left_column: first column name
:param right_column: second column nam... | python | def add(self, left_column, right_column, indexes=None):
"""
Math helper method that adds element-wise two columns. If indexes are not None then will only perform the math
on that sub-set of the columns.
:param left_column: first column name
:param right_column: second column nam... | [
"def",
"add",
"(",
"self",
",",
"left_column",
",",
"right_column",
",",
"indexes",
"=",
"None",
")",
":",
"left_list",
",",
"right_list",
"=",
"self",
".",
"_get_lists",
"(",
"left_column",
",",
"right_column",
",",
"indexes",
")",
"return",
"[",
"l",
"... | Math helper method that adds element-wise two columns. If indexes are not None then will only perform the math
on that sub-set of the columns.
:param left_column: first column name
:param right_column: second column name
:param indexes: list of index values or list of booleans. If a lis... | [
"Math",
"helper",
"method",
"that",
"adds",
"element",
"-",
"wise",
"two",
"columns",
".",
"If",
"indexes",
"are",
"not",
"None",
"then",
"will",
"only",
"perform",
"the",
"math",
"on",
"that",
"sub",
"-",
"set",
"of",
"the",
"columns",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L1070-L1082 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.isin | def isin(self, column, compare_list):
"""
Returns a boolean list where each elements is whether that element in the column is in the compare_list.
:param column: single column name, does not work for multiple columns
:param compare_list: list of items to compare to
:return: list... | python | def isin(self, column, compare_list):
"""
Returns a boolean list where each elements is whether that element in the column is in the compare_list.
:param column: single column name, does not work for multiple columns
:param compare_list: list of items to compare to
:return: list... | [
"def",
"isin",
"(",
"self",
",",
"column",
",",
"compare_list",
")",
":",
"return",
"[",
"x",
"in",
"compare_list",
"for",
"x",
"in",
"self",
".",
"_data",
"[",
"self",
".",
"_columns",
".",
"index",
"(",
"column",
")",
"]",
"]"
] | Returns a boolean list where each elements is whether that element in the column is in the compare_list.
:param column: single column name, does not work for multiple columns
:param compare_list: list of items to compare to
:return: list of booleans | [
"Returns",
"a",
"boolean",
"list",
"where",
"each",
"elements",
"is",
"whether",
"that",
"element",
"in",
"the",
"column",
"is",
"in",
"the",
"compare_list",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L1126-L1134 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.iterrows | def iterrows(self, index=True):
"""
Iterates over DataFrame rows as dictionary of the values. The index will be included.
:param index: if True include the index in the results
:return: dictionary
"""
for i in range(len(self._index)):
row = {self._index_name:... | python | def iterrows(self, index=True):
"""
Iterates over DataFrame rows as dictionary of the values. The index will be included.
:param index: if True include the index in the results
:return: dictionary
"""
for i in range(len(self._index)):
row = {self._index_name:... | [
"def",
"iterrows",
"(",
"self",
",",
"index",
"=",
"True",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_index",
")",
")",
":",
"row",
"=",
"{",
"self",
".",
"_index_name",
":",
"self",
".",
"_index",
"[",
"i",
"]",
"}",
... | Iterates over DataFrame rows as dictionary of the values. The index will be included.
:param index: if True include the index in the results
:return: dictionary | [
"Iterates",
"over",
"DataFrame",
"rows",
"as",
"dictionary",
"of",
"the",
"values",
".",
"The",
"index",
"will",
"be",
"included",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L1136-L1147 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.itertuples | def itertuples(self, index=True, name='Raccoon'):
"""
Iterates over DataFrame rows as tuple of the values.
:param index: if True then include the index
:param name: name of the namedtuple
:return: namedtuple
"""
fields = [self._index_name] if index else list()
... | python | def itertuples(self, index=True, name='Raccoon'):
"""
Iterates over DataFrame rows as tuple of the values.
:param index: if True then include the index
:param name: name of the namedtuple
:return: namedtuple
"""
fields = [self._index_name] if index else list()
... | [
"def",
"itertuples",
"(",
"self",
",",
"index",
"=",
"True",
",",
"name",
"=",
"'Raccoon'",
")",
":",
"fields",
"=",
"[",
"self",
".",
"_index_name",
"]",
"if",
"index",
"else",
"list",
"(",
")",
"fields",
".",
"extend",
"(",
"self",
".",
"_columns",... | Iterates over DataFrame rows as tuple of the values.
:param index: if True then include the index
:param name: name of the namedtuple
:return: namedtuple | [
"Iterates",
"over",
"DataFrame",
"rows",
"as",
"tuple",
"of",
"the",
"values",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L1149-L1164 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.reset_index | def reset_index(self, drop=False):
"""
Resets the index of the DataFrame to simple integer list and the index name to 'index'. If drop is True then
the existing index is dropped, if drop is False then the current index is made a column in the DataFrame with
the index name the name of the... | python | def reset_index(self, drop=False):
"""
Resets the index of the DataFrame to simple integer list and the index name to 'index'. If drop is True then
the existing index is dropped, if drop is False then the current index is made a column in the DataFrame with
the index name the name of the... | [
"def",
"reset_index",
"(",
"self",
",",
"drop",
"=",
"False",
")",
":",
"if",
"not",
"drop",
":",
"if",
"isinstance",
"(",
"self",
".",
"index_name",
",",
"tuple",
")",
":",
"index_data",
"=",
"list",
"(",
"map",
"(",
"list",
",",
"zip",
"(",
"*",
... | Resets the index of the DataFrame to simple integer list and the index name to 'index'. If drop is True then
the existing index is dropped, if drop is False then the current index is made a column in the DataFrame with
the index name the name of the column. If the index is a tuple multi-index then each ... | [
"Resets",
"the",
"index",
"of",
"the",
"DataFrame",
"to",
"simple",
"integer",
"list",
"and",
"the",
"index",
"name",
"to",
"index",
".",
"If",
"drop",
"is",
"True",
"then",
"the",
"existing",
"index",
"is",
"dropped",
"if",
"drop",
"is",
"False",
"then"... | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L1166-L1186 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.from_json | def from_json(cls, json_string):
"""
Creates and return a DataFrame from a JSON of the type created by to_json
:param json_string: JSON
:return: DataFrame
"""
input_dict = json.loads(json_string)
# convert index to tuple if required
if input_dict['index']... | python | def from_json(cls, json_string):
"""
Creates and return a DataFrame from a JSON of the type created by to_json
:param json_string: JSON
:return: DataFrame
"""
input_dict = json.loads(json_string)
# convert index to tuple if required
if input_dict['index']... | [
"def",
"from_json",
"(",
"cls",
",",
"json_string",
")",
":",
"input_dict",
"=",
"json",
".",
"loads",
"(",
"json_string",
")",
"# convert index to tuple if required",
"if",
"input_dict",
"[",
"'index'",
"]",
"and",
"isinstance",
"(",
"input_dict",
"[",
"'index'... | Creates and return a DataFrame from a JSON of the type created by to_json
:param json_string: JSON
:return: DataFrame | [
"Creates",
"and",
"return",
"a",
"DataFrame",
"from",
"a",
"JSON",
"of",
"the",
"type",
"created",
"by",
"to_json"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L1190-L1205 |
vmlaker/mpipe | src/FilterWorker.py | FilterWorker.doTask | def doTask(self, task):
"""Filter input *task* to pipelines -- make sure each one has no more
than *max_tasks* tasks in it. Return a tuple
(*task*, *results*)
where *task* is the given task, and *results* is
a list of latest retrieved results from pipelines."""
# If w... | python | def doTask(self, task):
"""Filter input *task* to pipelines -- make sure each one has no more
than *max_tasks* tasks in it. Return a tuple
(*task*, *results*)
where *task* is the given task, and *results* is
a list of latest retrieved results from pipelines."""
# If w... | [
"def",
"doTask",
"(",
"self",
",",
"task",
")",
":",
"# If we're not caching, then clear the table of last results.",
"if",
"not",
"self",
".",
"_cache_results",
":",
"self",
".",
"_last_results",
"=",
"dict",
"(",
")",
"# Iterate the list of pipelines, draining each one ... | Filter input *task* to pipelines -- make sure each one has no more
than *max_tasks* tasks in it. Return a tuple
(*task*, *results*)
where *task* is the given task, and *results* is
a list of latest retrieved results from pipelines. | [
"Filter",
"input",
"*",
"task",
"*",
"to",
"pipelines",
"--",
"make",
"sure",
"each",
"one",
"has",
"no",
"more",
"than",
"*",
"max_tasks",
"*",
"tasks",
"in",
"it",
".",
"Return",
"a",
"tuple",
"(",
"*",
"task",
"*",
"*",
"results",
"*",
")",
"whe... | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/FilterWorker.py#L47-L94 |
rsheftel/raccoon | raccoon/utils.py | assert_frame_equal | def assert_frame_equal(left, right, data_function=None, data_args=None):
"""
For unit testing equality of two DataFrames.
:param left: first DataFrame
:param right: second DataFrame
:param data_function: if provided will use this function to assert compare the df.data
:param data_args: argument... | python | def assert_frame_equal(left, right, data_function=None, data_args=None):
"""
For unit testing equality of two DataFrames.
:param left: first DataFrame
:param right: second DataFrame
:param data_function: if provided will use this function to assert compare the df.data
:param data_args: argument... | [
"def",
"assert_frame_equal",
"(",
"left",
",",
"right",
",",
"data_function",
"=",
"None",
",",
"data_args",
"=",
"None",
")",
":",
"if",
"data_function",
":",
"data_args",
"=",
"{",
"}",
"if",
"not",
"data_args",
"else",
"data_args",
"data_function",
"(",
... | For unit testing equality of two DataFrames.
:param left: first DataFrame
:param right: second DataFrame
:param data_function: if provided will use this function to assert compare the df.data
:param data_args: arguments to pass to the data_function
:return: nothing | [
"For",
"unit",
"testing",
"equality",
"of",
"two",
"DataFrames",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/utils.py#L8-L27 |
rsheftel/raccoon | raccoon/utils.py | assert_series_equal | def assert_series_equal(left, right, data_function=None, data_args=None):
"""
For unit testing equality of two Series.
:param left: first Series
:param right: second Series
:param data_function: if provided will use this function to assert compare the df.data
:param data_args: arguments to pass... | python | def assert_series_equal(left, right, data_function=None, data_args=None):
"""
For unit testing equality of two Series.
:param left: first Series
:param right: second Series
:param data_function: if provided will use this function to assert compare the df.data
:param data_args: arguments to pass... | [
"def",
"assert_series_equal",
"(",
"left",
",",
"right",
",",
"data_function",
"=",
"None",
",",
"data_args",
"=",
"None",
")",
":",
"assert",
"type",
"(",
"left",
")",
"==",
"type",
"(",
"right",
")",
"if",
"data_function",
":",
"data_args",
"=",
"{",
... | For unit testing equality of two Series.
:param left: first Series
:param right: second Series
:param data_function: if provided will use this function to assert compare the df.data
:param data_args: arguments to pass to the data_function
:return: nothing | [
"For",
"unit",
"testing",
"equality",
"of",
"two",
"Series",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/utils.py#L30-L53 |
vmlaker/mpipe | src/Pipeline.py | Pipeline.get | def get(self, timeout=None):
"""Return result from the pipeline."""
result = None
for stage in self._output_stages:
result = stage.get(timeout)
return result | python | def get(self, timeout=None):
"""Return result from the pipeline."""
result = None
for stage in self._output_stages:
result = stage.get(timeout)
return result | [
"def",
"get",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"result",
"=",
"None",
"for",
"stage",
"in",
"self",
".",
"_output_stages",
":",
"result",
"=",
"stage",
".",
"get",
"(",
"timeout",
")",
"return",
"result"
] | Return result from the pipeline. | [
"Return",
"result",
"from",
"the",
"pipeline",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/Pipeline.py#L15-L20 |
brenns10/tswift | tswift.py | main | def main():
"""
Run the CLI.
"""
parser = argparse.ArgumentParser(
description='Search artists, lyrics, and songs!'
)
parser.add_argument(
'artist',
help='Specify an artist name (Default: Taylor Swift)',
default='Taylor Swift',
nargs='?',
)
parser.... | python | def main():
"""
Run the CLI.
"""
parser = argparse.ArgumentParser(
description='Search artists, lyrics, and songs!'
)
parser.add_argument(
'artist',
help='Specify an artist name (Default: Taylor Swift)',
default='Taylor Swift',
nargs='?',
)
parser.... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Search artists, lyrics, and songs!'",
")",
"parser",
".",
"add_argument",
"(",
"'artist'",
",",
"help",
"=",
"'Specify an artist name (Default: Taylor Swift)'",
... | Run the CLI. | [
"Run",
"the",
"CLI",
"."
] | train | https://github.com/brenns10/tswift/blob/f4a8f3127e088d6b3a9669496f107c2704f4d1a3/tswift.py#L156-L198 |
brenns10/tswift | tswift.py | Song.load | def load(self):
"""Load the lyrics from MetroLyrics."""
page = requests.get(self._url)
# Forces utf-8 to prevent character mangling
page.encoding = 'utf-8'
tree = html.fromstring(page.text)
lyric_div = tree.get_element_by_id('lyrics-body-text')
verses = [c.text_c... | python | def load(self):
"""Load the lyrics from MetroLyrics."""
page = requests.get(self._url)
# Forces utf-8 to prevent character mangling
page.encoding = 'utf-8'
tree = html.fromstring(page.text)
lyric_div = tree.get_element_by_id('lyrics-body-text')
verses = [c.text_c... | [
"def",
"load",
"(",
"self",
")",
":",
"page",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_url",
")",
"# Forces utf-8 to prevent character mangling",
"page",
".",
"encoding",
"=",
"'utf-8'",
"tree",
"=",
"html",
".",
"fromstring",
"(",
"page",
".",
"te... | Load the lyrics from MetroLyrics. | [
"Load",
"the",
"lyrics",
"from",
"MetroLyrics",
"."
] | train | https://github.com/brenns10/tswift/blob/f4a8f3127e088d6b3a9669496f107c2704f4d1a3/tswift.py#L61-L71 |
brenns10/tswift | tswift.py | Artist.load | def load(self, verbose=False):
"""
Load the list of songs.
Note that this only loads a list of songs that this artist was the main
artist of. If they were only featured in the song, that song won't be
listed here. There is a list on the artist page for that, I just
hav... | python | def load(self, verbose=False):
"""
Load the list of songs.
Note that this only loads a list of songs that this artist was the main
artist of. If they were only featured in the song, that song won't be
listed here. There is a list on the artist page for that, I just
hav... | [
"def",
"load",
"(",
"self",
",",
"verbose",
"=",
"False",
")",
":",
"self",
".",
"_songs",
"=",
"[",
"]",
"page_num",
"=",
"1",
"total_pages",
"=",
"1",
"while",
"page_num",
"<=",
"total_pages",
":",
"if",
"verbose",
":",
"print",
"(",
"'retrieving pag... | Load the list of songs.
Note that this only loads a list of songs that this artist was the main
artist of. If they were only featured in the song, that song won't be
listed here. There is a list on the artist page for that, I just
haven't added any parsing code for that, since I don't... | [
"Load",
"the",
"list",
"of",
"songs",
"."
] | train | https://github.com/brenns10/tswift/blob/f4a8f3127e088d6b3a9669496f107c2704f4d1a3/tswift.py#L113-L144 |
jwass/geog | geog/geog.py | distance | def distance(p0, p1, deg=True, r=r_earth_mean):
"""
Return the distance between two points on the surface of the Earth.
Parameters
----------
p0 : point-like (or array of point-like) [longitude, latitude] objects
p1 : point-like (or array of point-like) [longitude, latitude] objects
deg : b... | python | def distance(p0, p1, deg=True, r=r_earth_mean):
"""
Return the distance between two points on the surface of the Earth.
Parameters
----------
p0 : point-like (or array of point-like) [longitude, latitude] objects
p1 : point-like (or array of point-like) [longitude, latitude] objects
deg : b... | [
"def",
"distance",
"(",
"p0",
",",
"p1",
",",
"deg",
"=",
"True",
",",
"r",
"=",
"r_earth_mean",
")",
":",
"single",
",",
"(",
"p0",
",",
"p1",
")",
"=",
"_to_arrays",
"(",
"(",
"p0",
",",
"2",
")",
",",
"(",
"p1",
",",
"2",
")",
")",
"if",... | Return the distance between two points on the surface of the Earth.
Parameters
----------
p0 : point-like (or array of point-like) [longitude, latitude] objects
p1 : point-like (or array of point-like) [longitude, latitude] objects
deg : bool, optional (default True)
indicates if p0 and p1 ... | [
"Return",
"the",
"distance",
"between",
"two",
"points",
"on",
"the",
"surface",
"of",
"the",
"Earth",
"."
] | train | https://github.com/jwass/geog/blob/52ceb9b543454b31c63694ee459aad9cd52f011a/geog/geog.py#L32-L74 |
jwass/geog | geog/geog.py | course | def course(p0, p1, deg=True, bearing=False):
"""
Compute the initial bearing along the great circle from p0 to p1
NB: The angle returned by course() is not the traditional definition of
bearing. It is definted such that 0 degrees to due East increasing
counter-clockwise such that 90 degrees is due ... | python | def course(p0, p1, deg=True, bearing=False):
"""
Compute the initial bearing along the great circle from p0 to p1
NB: The angle returned by course() is not the traditional definition of
bearing. It is definted such that 0 degrees to due East increasing
counter-clockwise such that 90 degrees is due ... | [
"def",
"course",
"(",
"p0",
",",
"p1",
",",
"deg",
"=",
"True",
",",
"bearing",
"=",
"False",
")",
":",
"single",
",",
"(",
"p0",
",",
"p1",
")",
"=",
"_to_arrays",
"(",
"(",
"p0",
",",
"2",
")",
",",
"(",
"p1",
",",
"2",
")",
")",
"if",
... | Compute the initial bearing along the great circle from p0 to p1
NB: The angle returned by course() is not the traditional definition of
bearing. It is definted such that 0 degrees to due East increasing
counter-clockwise such that 90 degrees is due North. To obtain the bearing
(0 degrees is due North ... | [
"Compute",
"the",
"initial",
"bearing",
"along",
"the",
"great",
"circle",
"from",
"p0",
"to",
"p1"
] | train | https://github.com/jwass/geog/blob/52ceb9b543454b31c63694ee459aad9cd52f011a/geog/geog.py#L77-L126 |
jwass/geog | geog/geog.py | propagate | def propagate(p0, angle, d, deg=True, bearing=False, r=r_earth_mean):
"""
Given an initial point and angle, move distance d along the surface
Parameters
----------
p0 : point-like (or array of point-like) [lon, lat] objects
angle : float (or array of float)
bearing. Note that by default... | python | def propagate(p0, angle, d, deg=True, bearing=False, r=r_earth_mean):
"""
Given an initial point and angle, move distance d along the surface
Parameters
----------
p0 : point-like (or array of point-like) [lon, lat] objects
angle : float (or array of float)
bearing. Note that by default... | [
"def",
"propagate",
"(",
"p0",
",",
"angle",
",",
"d",
",",
"deg",
"=",
"True",
",",
"bearing",
"=",
"False",
",",
"r",
"=",
"r_earth_mean",
")",
":",
"single",
",",
"(",
"p0",
",",
"angle",
",",
"d",
")",
"=",
"_to_arrays",
"(",
"(",
"p0",
","... | Given an initial point and angle, move distance d along the surface
Parameters
----------
p0 : point-like (or array of point-like) [lon, lat] objects
angle : float (or array of float)
bearing. Note that by default, 0 degrees is due East increasing
clockwise so that 90 degrees is due No... | [
"Given",
"an",
"initial",
"point",
"and",
"angle",
"move",
"distance",
"d",
"along",
"the",
"surface"
] | train | https://github.com/jwass/geog/blob/52ceb9b543454b31c63694ee459aad9cd52f011a/geog/geog.py#L129-L184 |
lepture/flask-weixin | flask_weixin.py | Weixin.validate | def validate(self, signature, timestamp, nonce):
"""Validate request signature.
:param signature: A string signature parameter sent by weixin.
:param timestamp: A int timestamp parameter sent by weixin.
:param nonce: A int nonce parameter sent by weixin.
"""
if not self.... | python | def validate(self, signature, timestamp, nonce):
"""Validate request signature.
:param signature: A string signature parameter sent by weixin.
:param timestamp: A int timestamp parameter sent by weixin.
:param nonce: A int nonce parameter sent by weixin.
"""
if not self.... | [
"def",
"validate",
"(",
"self",
",",
"signature",
",",
"timestamp",
",",
"nonce",
")",
":",
"if",
"not",
"self",
".",
"token",
":",
"raise",
"RuntimeError",
"(",
"'WEIXIN_TOKEN is missing'",
")",
"if",
"self",
".",
"expires_in",
":",
"try",
":",
"timestamp... | Validate request signature.
:param signature: A string signature parameter sent by weixin.
:param timestamp: A int timestamp parameter sent by weixin.
:param nonce: A int nonce parameter sent by weixin. | [
"Validate",
"request",
"signature",
"."
] | train | https://github.com/lepture/flask-weixin/blob/abf0b507d41b9780257507aa78fc0817fdc75719/flask_weixin.py#L77-L106 |
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",
"."
] | train | https://github.com/lepture/flask-weixin/blob/abf0b507d41b9780257507aa78fc0817fdc75719/flask_weixin.py#L108-L133 |
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",
"."
] | train | https://github.com/lepture/flask-weixin/blob/abf0b507d41b9780257507aa78fc0817fdc75719/flask_weixin.py#L187-L258 |
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",
"."
] | train | https://github.com/lepture/flask-weixin/blob/abf0b507d41b9780257507aa78fc0817fdc75719/flask_weixin.py#L260-L292 |
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",
"."
] | train | https://github.com/lepture/flask-weixin/blob/abf0b507d41b9780257507aa78fc0817fdc75719/flask_weixin.py#L313-L369 |
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",
"()"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__main__.py#L107-L111 |
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"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__main__.py#L117-L122 |
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",
"()"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__main__.py#L130-L141 |
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"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__main__.py#L88-L92 |
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",
")"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__main__.py#L94-L100 |
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"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L11-L25 |
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",
")"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L56-L79 |
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",
")",
"."
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L81-L107 |
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... | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L109-L141 |
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",... | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L143-L158 |
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... | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L161-L187 |
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",
... | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L190-L227 |
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",
"()... | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L229-L251 |
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"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/github.py#L258-L280 |
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",
")"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__init__.py#L12-L19 |
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",... | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/__init__.py#L21-L30 |
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"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/request.py#L26-L28 |
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"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/request.py#L30-L32 |
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"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/request.py#L34-L36 |
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",
")"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/local.py#L23-L41 |
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"
] | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/local.py#L43-L53 |
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",
"(",
... | train | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/local.py#L55-L75 |
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"
] | train | https://github.com/thautwarm/EBNFParser/blob/101a92c4f408f9e6ce7b55aacb39cded9394521d/Python/Ruikowa/ObjectRegex/Tokenizer.py#L159-L181 |
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"
] | train | https://github.com/thautwarm/EBNFParser/blob/101a92c4f408f9e6ce7b55aacb39cded9394521d/Python/Ruikowa/ObjectRegex/Tokenizer.py#L184-L205 |
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",
":"
] | train | https://github.com/thautwarm/EBNFParser/blob/101a92c4f408f9e6ce7b55aacb39cded9394521d/Python/Ruikowa/ObjectRegex/Tokenizer.py#L208-L221 |
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",
"*",
";"
] | train | https://github.com/thautwarm/EBNFParser/blob/101a92c4f408f9e6ce7b55aacb39cded9394521d/Python/Ruikowa/Bootstrap/Ast.py#L54-L75 |
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",
"."
] | train | https://github.com/andela-sjames/paystack-python/blob/c9e4bddcb76e1490fefc362e71a21486400dccd4/paystackapi/base.py#L45-L60 |
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",
"."
] | train | https://github.com/andela-sjames/paystack-python/blob/c9e4bddcb76e1490fefc362e71a21486400dccd4/paystackapi/base.py#L62-L68 |
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",
"."
] | train | https://github.com/andela-sjames/paystack-python/blob/c9e4bddcb76e1490fefc362e71a21486400dccd4/paystackapi/base.py#L70-L76 |
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",
"."
] | train | https://github.com/andela-sjames/paystack-python/blob/c9e4bddcb76e1490fefc362e71a21486400dccd4/paystackapi/base.py#L78-L84 |
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",
"."
] | train | https://github.com/andela-sjames/paystack-python/blob/c9e4bddcb76e1490fefc362e71a21486400dccd4/paystackapi/customer.py#L50-L65 |
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",
"."
] | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L59-L114 |
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",
"."
] | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L134-L150 |
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",
"."
] | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L152-L165 |
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",
"."
] | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L167-L245 |
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",
"."
] | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L247-L258 |
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",
"."
] | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L260-L268 |
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",
"."
] | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L270-L289 |
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",
"."
] | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L297-L313 |
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",
"... | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/templates.py#L1-L37 |
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",
">",
"{",
... | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/templates.py#L40-L76 |
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",
"}",
">"
] | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/templates.py#L79-L100 |
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",
"."
] | train | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/templates.py#L103-L125 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/find_all_candidates.py#L50-L56 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/find_all_candidates.py#L59-L83 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/find_all_candidates.py#L86-L99 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/find_all_candidates.py#L102-L117 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/find_apokasc_candidates.py#L30-L44 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/abundances/calc_gradient_spectra.py#L25-L35 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/abundances/calc_gradient_spectra.py#L38-L41 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/abundances/calc_gradient_spectra.py#L62-L94 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/abundances/calc_gradient_spectra.py#L129-L140 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L27-L40 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L48-L65 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L68-L90 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L93-L99 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L131-L136 |
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",
"."
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L212-L227 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/mass_age/paper_plots/cn_features.py#L55-L75 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/mass_age/cn/write_table.py#L12-L31 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/mass_age/cn/get_colors.py#L4-L56 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/spectral_model.py#L3-L32 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/spectral_model.py#L35-L111 |
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",
"."
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/spectral_model.py#L114-L211 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/find_continuum_pixels.py#L6-L34 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/find_continuum_pixels.py#L37-L85 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/find_continuum_pixels.py#L88-L119 |
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",
"."
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/xcalib_5labels/cross_validation.py#L26-L32 |
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",
"."
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/xcalib_5labels/cross_validation.py#L35-L49 |
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",
".... | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/xcalib_5labels/cross_validation.py#L159-L207 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/aaomega/aaomega_munge_data.py#L12-L16 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/aaomega/aaomega_munge_data.py#L19-L27 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/aaomega/aaomega_munge_data.py#L30-L55 |
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"
] | train | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/aaomega/aaomega_munge_data.py#L109-L157 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.