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
mrstephenneal/mysql-toolkit
mysql/toolkit/components/manipulate/insert.py
Insert.insert_uniques
def insert_uniques(self, table, columns, values): """ Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted """ # Rows that exist in the table existing_rows = self.select(table, columns) # Rows that DO NOT exist in the table unique = diff(existing_rows, values, y_only=True) # Get values that are not in existing_rows # Keys that exist in the table keys = self.get_primary_key_vals(table) # Primary key's column index pk_col = self.get_primary_key(table) pk_index = columns.index(pk_col) # Split list of unique rows into list of rows to update and rows to insert to_insert, to_update = [], [] for index, row in enumerate(unique): # Primary key is not in list of pk values, insert new row if row[pk_index] not in keys: to_insert.append(unique[index]) # Primary key exists, update row rather than insert elif row[pk_index] in keys: to_update.append(unique[index]) # Insert new rows if len(to_insert) > 0: self.insert_many(table, columns, to_insert) # Update existing rows if len(to_update) > 0: self.update_many(table, columns, to_update, pk_col, 0) # No inserted or updated rows if len(to_insert) < 1 and len(to_update) < 0: self._printer('No rows added to', table)
python
def insert_uniques(self, table, columns, values): """ Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted """ # Rows that exist in the table existing_rows = self.select(table, columns) # Rows that DO NOT exist in the table unique = diff(existing_rows, values, y_only=True) # Get values that are not in existing_rows # Keys that exist in the table keys = self.get_primary_key_vals(table) # Primary key's column index pk_col = self.get_primary_key(table) pk_index = columns.index(pk_col) # Split list of unique rows into list of rows to update and rows to insert to_insert, to_update = [], [] for index, row in enumerate(unique): # Primary key is not in list of pk values, insert new row if row[pk_index] not in keys: to_insert.append(unique[index]) # Primary key exists, update row rather than insert elif row[pk_index] in keys: to_update.append(unique[index]) # Insert new rows if len(to_insert) > 0: self.insert_many(table, columns, to_insert) # Update existing rows if len(to_update) > 0: self.update_many(table, columns, to_update, pk_col, 0) # No inserted or updated rows if len(to_insert) < 1 and len(to_update) < 0: self._printer('No rows added to', table)
[ "def", "insert_uniques", "(", "self", ",", "table", ",", "columns", ",", "values", ")", ":", "# Rows that exist in the table", "existing_rows", "=", "self", ".", "select", "(", "table", ",", "columns", ")", "# Rows that DO NOT exist in the table", "unique", "=", "...
Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted
[ "Insert", "multiple", "rows", "into", "a", "table", "that", "do", "not", "already", "exist", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/manipulate/insert.py#L7-L48
mrstephenneal/mysql-toolkit
mysql/toolkit/components/manipulate/insert.py
Insert.insert
def insert(self, table, columns, values, execute=True): """Insert a single row into a table.""" # TODO: Cant accept lists? # Concatenate statement cols, vals = get_col_val_str(columns) statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(wrap(table), cols, vals) # Execute statement if execute: self._cursor.execute(statement, values) self._commit() self._printer('\tMySQL row successfully inserted into {0}'.format(table)) # Only return statement else: return statement
python
def insert(self, table, columns, values, execute=True): """Insert a single row into a table.""" # TODO: Cant accept lists? # Concatenate statement cols, vals = get_col_val_str(columns) statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(wrap(table), cols, vals) # Execute statement if execute: self._cursor.execute(statement, values) self._commit() self._printer('\tMySQL row successfully inserted into {0}'.format(table)) # Only return statement else: return statement
[ "def", "insert", "(", "self", ",", "table", ",", "columns", ",", "values", ",", "execute", "=", "True", ")", ":", "# TODO: Cant accept lists?", "# Concatenate statement", "cols", ",", "vals", "=", "get_col_val_str", "(", "columns", ")", "statement", "=", "\"IN...
Insert a single row into a table.
[ "Insert", "a", "single", "row", "into", "a", "table", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/manipulate/insert.py#L50-L65
mrstephenneal/mysql-toolkit
mysql/toolkit/components/manipulate/insert.py
Insert.insert_many
def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True): """ Insert multiple rows into a table. If only one row is found, self.insert method will be used. """ # Make values a list of lists if it is a flat list if not isinstance(values[0], (list, set, tuple)): values = [] for v in values: if v is not None and len(v) > 0: values.append([v]) else: values.append([None]) # Concatenate statement cols, vals = get_col_val_str(columns) statement = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(wrap(table), cols, vals) if execute and len(values) > limit: while len(values) > 0: vals = [values.pop(0) for i in range(0, min(limit, len(values)))] self._cursor.executemany(statement, vals) self._commit() elif execute: # Execute statement self._cursor.executemany(statement, values) self._commit() self._printer('\tMySQL rows (' + str(len(values)) + ') successfully INSERTED') # Only return statement else: return statement
python
def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True): """ Insert multiple rows into a table. If only one row is found, self.insert method will be used. """ # Make values a list of lists if it is a flat list if not isinstance(values[0], (list, set, tuple)): values = [] for v in values: if v is not None and len(v) > 0: values.append([v]) else: values.append([None]) # Concatenate statement cols, vals = get_col_val_str(columns) statement = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(wrap(table), cols, vals) if execute and len(values) > limit: while len(values) > 0: vals = [values.pop(0) for i in range(0, min(limit, len(values)))] self._cursor.executemany(statement, vals) self._commit() elif execute: # Execute statement self._cursor.executemany(statement, values) self._commit() self._printer('\tMySQL rows (' + str(len(values)) + ') successfully INSERTED') # Only return statement else: return statement
[ "def", "insert_many", "(", "self", ",", "table", ",", "columns", ",", "values", ",", "limit", "=", "MAX_ROWS_PER_QUERY", ",", "execute", "=", "True", ")", ":", "# Make values a list of lists if it is a flat list", "if", "not", "isinstance", "(", "values", "[", "...
Insert multiple rows into a table. If only one row is found, self.insert method will be used.
[ "Insert", "multiple", "rows", "into", "a", "table", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/manipulate/insert.py#L67-L100
PGower/PyCanvas
pycanvas/apis/quizzes.py
QuizzesAPI.list_quizzes_in_course
def list_quizzes_in_course(self, course_id, search_term=None): """ List quizzes in a course. Returns the list of Quizzes in this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - search_term """The partial title of the quizzes to match and return.""" if search_term is not None: params["search_term"] = search_term self.logger.debug("GET /api/v1/courses/{course_id}/quizzes with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes".format(**path), data=data, params=params, all_pages=True)
python
def list_quizzes_in_course(self, course_id, search_term=None): """ List quizzes in a course. Returns the list of Quizzes in this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - search_term """The partial title of the quizzes to match and return.""" if search_term is not None: params["search_term"] = search_term self.logger.debug("GET /api/v1/courses/{course_id}/quizzes with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_quizzes_in_course", "(", "self", ",", "course_id", ",", "search_term", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"course_id\"",...
List quizzes in a course. Returns the list of Quizzes in this course.
[ "List", "quizzes", "in", "a", "course", ".", "Returns", "the", "list", "of", "Quizzes", "in", "this", "course", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quizzes.py#L19-L39
PGower/PyCanvas
pycanvas/apis/quizzes.py
QuizzesAPI.create_quiz
def create_quiz(self, course_id, quiz_title, quiz_access_code=None, quiz_allowed_attempts=None, quiz_assignment_group_id=None, quiz_cant_go_back=None, quiz_description=None, quiz_due_at=None, quiz_hide_correct_answers_at=None, quiz_hide_results=None, quiz_ip_filter=None, quiz_lock_at=None, quiz_one_question_at_a_time=None, quiz_one_time_results=None, quiz_only_visible_to_overrides=None, quiz_published=None, quiz_quiz_type=None, quiz_scoring_policy=None, quiz_show_correct_answers=None, quiz_show_correct_answers_at=None, quiz_show_correct_answers_last_attempt=None, quiz_shuffle_answers=None, quiz_time_limit=None, quiz_unlock_at=None): """ Create a quiz. Create a new quiz for this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - quiz[title] """The quiz title.""" data["quiz[title]"] = quiz_title # OPTIONAL - quiz[description] """A description of the quiz.""" if quiz_description is not None: data["quiz[description]"] = quiz_description # OPTIONAL - quiz[quiz_type] """The type of quiz.""" if quiz_quiz_type is not None: self._validate_enum(quiz_quiz_type, ["practice_quiz", "assignment", "graded_survey", "survey"]) data["quiz[quiz_type]"] = quiz_quiz_type # OPTIONAL - quiz[assignment_group_id] """The assignment group id to put the assignment in. Defaults to the top assignment group in the course. Only valid if the quiz is graded, i.e. if quiz_type is "assignment" or "graded_survey".""" if quiz_assignment_group_id is not None: data["quiz[assignment_group_id]"] = quiz_assignment_group_id # OPTIONAL - quiz[time_limit] """Time limit to take this quiz, in minutes. Set to null for no time limit. Defaults to null.""" if quiz_time_limit is not None: data["quiz[time_limit]"] = quiz_time_limit # OPTIONAL - quiz[shuffle_answers] """If true, quiz answers for multiple choice questions will be randomized for each student. Defaults to false.""" if quiz_shuffle_answers is not None: data["quiz[shuffle_answers]"] = quiz_shuffle_answers # OPTIONAL - quiz[hide_results] """Dictates whether or not quiz results are hidden from students. If null, students can see their results after any attempt. If "always", students can never see their results. If "until_after_last_attempt", students can only see results after their last attempt. (Only valid if allowed_attempts > 1). Defaults to null.""" if quiz_hide_results is not None: self._validate_enum(quiz_hide_results, ["always", "until_after_last_attempt"]) data["quiz[hide_results]"] = quiz_hide_results # OPTIONAL - quiz[show_correct_answers] """Only valid if hide_results=null If false, hides correct answers from students when quiz results are viewed. Defaults to true.""" if quiz_show_correct_answers is not None: data["quiz[show_correct_answers]"] = quiz_show_correct_answers # OPTIONAL - quiz[show_correct_answers_last_attempt] """Only valid if show_correct_answers=true and allowed_attempts > 1 If true, hides correct answers from students when quiz results are viewed until they submit the last attempt for the quiz. Defaults to false.""" if quiz_show_correct_answers_last_attempt is not None: data["quiz[show_correct_answers_last_attempt]"] = quiz_show_correct_answers_last_attempt # OPTIONAL - quiz[show_correct_answers_at] """Only valid if show_correct_answers=true If set, the correct answers will be visible by students only after this date, otherwise the correct answers are visible once the student hands in their quiz submission.""" if quiz_show_correct_answers_at is not None: data["quiz[show_correct_answers_at]"] = quiz_show_correct_answers_at # OPTIONAL - quiz[hide_correct_answers_at] """Only valid if show_correct_answers=true If set, the correct answers will stop being visible once this date has passed. Otherwise, the correct answers will be visible indefinitely.""" if quiz_hide_correct_answers_at is not None: data["quiz[hide_correct_answers_at]"] = quiz_hide_correct_answers_at # OPTIONAL - quiz[allowed_attempts] """Number of times a student is allowed to take a quiz. Set to -1 for unlimited attempts. Defaults to 1.""" if quiz_allowed_attempts is not None: data["quiz[allowed_attempts]"] = quiz_allowed_attempts # OPTIONAL - quiz[scoring_policy] """Required and only valid if allowed_attempts > 1. Scoring policy for a quiz that students can take multiple times. Defaults to "keep_highest".""" if quiz_scoring_policy is not None: self._validate_enum(quiz_scoring_policy, ["keep_highest", "keep_latest"]) data["quiz[scoring_policy]"] = quiz_scoring_policy # OPTIONAL - quiz[one_question_at_a_time] """If true, shows quiz to student one question at a time. Defaults to false.""" if quiz_one_question_at_a_time is not None: data["quiz[one_question_at_a_time]"] = quiz_one_question_at_a_time # OPTIONAL - quiz[cant_go_back] """Only valid if one_question_at_a_time=true If true, questions are locked after answering. Defaults to false.""" if quiz_cant_go_back is not None: data["quiz[cant_go_back]"] = quiz_cant_go_back # OPTIONAL - quiz[access_code] """Restricts access to the quiz with a password. For no access code restriction, set to null. Defaults to null.""" if quiz_access_code is not None: data["quiz[access_code]"] = quiz_access_code # OPTIONAL - quiz[ip_filter] """Restricts access to the quiz to computers in a specified IP range. Filters can be a comma-separated list of addresses, or an address followed by a mask Examples: "192.168.217.1" "192.168.217.1/24" "192.168.217.1/255.255.255.0" For no IP filter restriction, set to null. Defaults to null.""" if quiz_ip_filter is not None: data["quiz[ip_filter]"] = quiz_ip_filter # OPTIONAL - quiz[due_at] """The day/time the quiz is due. Accepts times in ISO 8601 format, e.g. 2011-10-21T18:48Z.""" if quiz_due_at is not None: data["quiz[due_at]"] = quiz_due_at # OPTIONAL - quiz[lock_at] """The day/time the quiz is locked for students. Accepts times in ISO 8601 format, e.g. 2011-10-21T18:48Z.""" if quiz_lock_at is not None: data["quiz[lock_at]"] = quiz_lock_at # OPTIONAL - quiz[unlock_at] """The day/time the quiz is unlocked for students. Accepts times in ISO 8601 format, e.g. 2011-10-21T18:48Z.""" if quiz_unlock_at is not None: data["quiz[unlock_at]"] = quiz_unlock_at # OPTIONAL - quiz[published] """Whether the quiz should have a draft state of published or unpublished. NOTE: If students have started taking the quiz, or there are any submissions for the quiz, you may not unpublish a quiz and will recieve an error.""" if quiz_published is not None: data["quiz[published]"] = quiz_published # OPTIONAL - quiz[one_time_results] """Whether students should be prevented from viewing their quiz results past the first time (right after they turn the quiz in.) Only valid if "hide_results" is not set to "always". Defaults to false.""" if quiz_one_time_results is not None: data["quiz[one_time_results]"] = quiz_one_time_results # OPTIONAL - quiz[only_visible_to_overrides] """Whether this quiz is only visible to overrides (Only useful if 'differentiated assignments' account setting is on) Defaults to false.""" if quiz_only_visible_to_overrides is not None: data["quiz[only_visible_to_overrides]"] = quiz_only_visible_to_overrides self.logger.debug("POST /api/v1/courses/{course_id}/quizzes with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes".format(**path), data=data, params=params, single_item=True)
python
def create_quiz(self, course_id, quiz_title, quiz_access_code=None, quiz_allowed_attempts=None, quiz_assignment_group_id=None, quiz_cant_go_back=None, quiz_description=None, quiz_due_at=None, quiz_hide_correct_answers_at=None, quiz_hide_results=None, quiz_ip_filter=None, quiz_lock_at=None, quiz_one_question_at_a_time=None, quiz_one_time_results=None, quiz_only_visible_to_overrides=None, quiz_published=None, quiz_quiz_type=None, quiz_scoring_policy=None, quiz_show_correct_answers=None, quiz_show_correct_answers_at=None, quiz_show_correct_answers_last_attempt=None, quiz_shuffle_answers=None, quiz_time_limit=None, quiz_unlock_at=None): """ Create a quiz. Create a new quiz for this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - quiz[title] """The quiz title.""" data["quiz[title]"] = quiz_title # OPTIONAL - quiz[description] """A description of the quiz.""" if quiz_description is not None: data["quiz[description]"] = quiz_description # OPTIONAL - quiz[quiz_type] """The type of quiz.""" if quiz_quiz_type is not None: self._validate_enum(quiz_quiz_type, ["practice_quiz", "assignment", "graded_survey", "survey"]) data["quiz[quiz_type]"] = quiz_quiz_type # OPTIONAL - quiz[assignment_group_id] """The assignment group id to put the assignment in. Defaults to the top assignment group in the course. Only valid if the quiz is graded, i.e. if quiz_type is "assignment" or "graded_survey".""" if quiz_assignment_group_id is not None: data["quiz[assignment_group_id]"] = quiz_assignment_group_id # OPTIONAL - quiz[time_limit] """Time limit to take this quiz, in minutes. Set to null for no time limit. Defaults to null.""" if quiz_time_limit is not None: data["quiz[time_limit]"] = quiz_time_limit # OPTIONAL - quiz[shuffle_answers] """If true, quiz answers for multiple choice questions will be randomized for each student. Defaults to false.""" if quiz_shuffle_answers is not None: data["quiz[shuffle_answers]"] = quiz_shuffle_answers # OPTIONAL - quiz[hide_results] """Dictates whether or not quiz results are hidden from students. If null, students can see their results after any attempt. If "always", students can never see their results. If "until_after_last_attempt", students can only see results after their last attempt. (Only valid if allowed_attempts > 1). Defaults to null.""" if quiz_hide_results is not None: self._validate_enum(quiz_hide_results, ["always", "until_after_last_attempt"]) data["quiz[hide_results]"] = quiz_hide_results # OPTIONAL - quiz[show_correct_answers] """Only valid if hide_results=null If false, hides correct answers from students when quiz results are viewed. Defaults to true.""" if quiz_show_correct_answers is not None: data["quiz[show_correct_answers]"] = quiz_show_correct_answers # OPTIONAL - quiz[show_correct_answers_last_attempt] """Only valid if show_correct_answers=true and allowed_attempts > 1 If true, hides correct answers from students when quiz results are viewed until they submit the last attempt for the quiz. Defaults to false.""" if quiz_show_correct_answers_last_attempt is not None: data["quiz[show_correct_answers_last_attempt]"] = quiz_show_correct_answers_last_attempt # OPTIONAL - quiz[show_correct_answers_at] """Only valid if show_correct_answers=true If set, the correct answers will be visible by students only after this date, otherwise the correct answers are visible once the student hands in their quiz submission.""" if quiz_show_correct_answers_at is not None: data["quiz[show_correct_answers_at]"] = quiz_show_correct_answers_at # OPTIONAL - quiz[hide_correct_answers_at] """Only valid if show_correct_answers=true If set, the correct answers will stop being visible once this date has passed. Otherwise, the correct answers will be visible indefinitely.""" if quiz_hide_correct_answers_at is not None: data["quiz[hide_correct_answers_at]"] = quiz_hide_correct_answers_at # OPTIONAL - quiz[allowed_attempts] """Number of times a student is allowed to take a quiz. Set to -1 for unlimited attempts. Defaults to 1.""" if quiz_allowed_attempts is not None: data["quiz[allowed_attempts]"] = quiz_allowed_attempts # OPTIONAL - quiz[scoring_policy] """Required and only valid if allowed_attempts > 1. Scoring policy for a quiz that students can take multiple times. Defaults to "keep_highest".""" if quiz_scoring_policy is not None: self._validate_enum(quiz_scoring_policy, ["keep_highest", "keep_latest"]) data["quiz[scoring_policy]"] = quiz_scoring_policy # OPTIONAL - quiz[one_question_at_a_time] """If true, shows quiz to student one question at a time. Defaults to false.""" if quiz_one_question_at_a_time is not None: data["quiz[one_question_at_a_time]"] = quiz_one_question_at_a_time # OPTIONAL - quiz[cant_go_back] """Only valid if one_question_at_a_time=true If true, questions are locked after answering. Defaults to false.""" if quiz_cant_go_back is not None: data["quiz[cant_go_back]"] = quiz_cant_go_back # OPTIONAL - quiz[access_code] """Restricts access to the quiz with a password. For no access code restriction, set to null. Defaults to null.""" if quiz_access_code is not None: data["quiz[access_code]"] = quiz_access_code # OPTIONAL - quiz[ip_filter] """Restricts access to the quiz to computers in a specified IP range. Filters can be a comma-separated list of addresses, or an address followed by a mask Examples: "192.168.217.1" "192.168.217.1/24" "192.168.217.1/255.255.255.0" For no IP filter restriction, set to null. Defaults to null.""" if quiz_ip_filter is not None: data["quiz[ip_filter]"] = quiz_ip_filter # OPTIONAL - quiz[due_at] """The day/time the quiz is due. Accepts times in ISO 8601 format, e.g. 2011-10-21T18:48Z.""" if quiz_due_at is not None: data["quiz[due_at]"] = quiz_due_at # OPTIONAL - quiz[lock_at] """The day/time the quiz is locked for students. Accepts times in ISO 8601 format, e.g. 2011-10-21T18:48Z.""" if quiz_lock_at is not None: data["quiz[lock_at]"] = quiz_lock_at # OPTIONAL - quiz[unlock_at] """The day/time the quiz is unlocked for students. Accepts times in ISO 8601 format, e.g. 2011-10-21T18:48Z.""" if quiz_unlock_at is not None: data["quiz[unlock_at]"] = quiz_unlock_at # OPTIONAL - quiz[published] """Whether the quiz should have a draft state of published or unpublished. NOTE: If students have started taking the quiz, or there are any submissions for the quiz, you may not unpublish a quiz and will recieve an error.""" if quiz_published is not None: data["quiz[published]"] = quiz_published # OPTIONAL - quiz[one_time_results] """Whether students should be prevented from viewing their quiz results past the first time (right after they turn the quiz in.) Only valid if "hide_results" is not set to "always". Defaults to false.""" if quiz_one_time_results is not None: data["quiz[one_time_results]"] = quiz_one_time_results # OPTIONAL - quiz[only_visible_to_overrides] """Whether this quiz is only visible to overrides (Only useful if 'differentiated assignments' account setting is on) Defaults to false.""" if quiz_only_visible_to_overrides is not None: data["quiz[only_visible_to_overrides]"] = quiz_only_visible_to_overrides self.logger.debug("POST /api/v1/courses/{course_id}/quizzes with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes".format(**path), data=data, params=params, single_item=True)
[ "def", "create_quiz", "(", "self", ",", "course_id", ",", "quiz_title", ",", "quiz_access_code", "=", "None", ",", "quiz_allowed_attempts", "=", "None", ",", "quiz_assignment_group_id", "=", "None", ",", "quiz_cant_go_back", "=", "None", ",", "quiz_description", "...
Create a quiz. Create a new quiz for this course.
[ "Create", "a", "quiz", ".", "Create", "a", "new", "quiz", "for", "this", "course", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quizzes.py#L62-L241
PGower/PyCanvas
pycanvas/apis/quizzes.py
QuizzesAPI.validate_quiz_access_code
def validate_quiz_access_code(self, id, course_id, access_code): """ Validate quiz access code. Accepts an access code and returns a boolean indicating whether that access code is correct """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - access_code """The access code being validated""" data["access_code"] = access_code self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{id}/validate_access_code with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{id}/validate_access_code".format(**path), data=data, params=params)
python
def validate_quiz_access_code(self, id, course_id, access_code): """ Validate quiz access code. Accepts an access code and returns a boolean indicating whether that access code is correct """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - access_code """The access code being validated""" data["access_code"] = access_code self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{id}/validate_access_code with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{id}/validate_access_code".format(**path), data=data, params=params)
[ "def", "validate_quiz_access_code", "(", "self", ",", "id", ",", "course_id", ",", "access_code", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"course_id\""...
Validate quiz access code. Accepts an access code and returns a boolean indicating whether that access code is correct
[ "Validate", "quiz", "access", "code", ".", "Accepts", "an", "access", "code", "and", "returns", "a", "boolean", "indicating", "whether", "that", "access", "code", "is", "correct" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quizzes.py#L326-L349
saghul/evergreen
evergreen/queue.py
Queue.get
def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case). """ self.not_empty.acquire() try: if not block: if not self._qsize(): raise Empty elif timeout is None: while not self._qsize(): self.not_empty.wait() elif timeout < 0: raise ValueError("'timeout' must be a positive number") else: if not self._qsize(): self.not_empty.wait(timeout) if not self._qsize(): raise Empty item = self._get() self.not_full.notify() return item finally: self.not_empty.release()
python
def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case). """ self.not_empty.acquire() try: if not block: if not self._qsize(): raise Empty elif timeout is None: while not self._qsize(): self.not_empty.wait() elif timeout < 0: raise ValueError("'timeout' must be a positive number") else: if not self._qsize(): self.not_empty.wait(timeout) if not self._qsize(): raise Empty item = self._get() self.not_full.notify() return item finally: self.not_empty.release()
[ "def", "get", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "self", ".", "not_empty", ".", "acquire", "(", ")", "try", ":", "if", "not", "block", ":", "if", "not", "self", ".", "_qsize", "(", ")", ":", "raise", ...
Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case).
[ "Remove", "and", "return", "an", "item", "from", "the", "queue", "." ]
train
https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/queue.py#L164-L194
LIVVkit/LIVVkit
livvkit/components/validation.py
run_suite
def run_suite(case, config, summary): """ Run the full suite of validation tests """ m = _load_case_module(case, config) result = m.run(case, config) summary[case] = _summarize_result(m, result) _print_summary(m, case, summary) if result['Type'] == 'Book': for name, page in six.iteritems(result['Data']): functions.create_page_from_template("validation.html", os.path.join(livvkit.index_dir, "validation", name + ".html")) functions.write_json(page, os.path.join(livvkit.output_dir, "validation"), name + ".json") else: functions.create_page_from_template("validation.html", os.path.join(livvkit.index_dir, "validation", case + ".html")) functions.write_json(result, os.path.join(livvkit.output_dir, "validation"), case + ".json")
python
def run_suite(case, config, summary): """ Run the full suite of validation tests """ m = _load_case_module(case, config) result = m.run(case, config) summary[case] = _summarize_result(m, result) _print_summary(m, case, summary) if result['Type'] == 'Book': for name, page in six.iteritems(result['Data']): functions.create_page_from_template("validation.html", os.path.join(livvkit.index_dir, "validation", name + ".html")) functions.write_json(page, os.path.join(livvkit.output_dir, "validation"), name + ".json") else: functions.create_page_from_template("validation.html", os.path.join(livvkit.index_dir, "validation", case + ".html")) functions.write_json(result, os.path.join(livvkit.output_dir, "validation"), case + ".json")
[ "def", "run_suite", "(", "case", ",", "config", ",", "summary", ")", ":", "m", "=", "_load_case_module", "(", "case", ",", "config", ")", "result", "=", "m", ".", "run", "(", "case", ",", "config", ")", "summary", "[", "case", "]", "=", "_summarize_r...
Run the full suite of validation tests
[ "Run", "the", "full", "suite", "of", "validation", "tests" ]
train
https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/components/validation.py#L122-L138
bioasp/caspo
travis-ci/upload.py
artifact_already_exists
def artifact_already_exists(cli, meta, owner): """ Checks to see whether the built recipe (aka distribution) already exists on the owner/user's binstar account. """ distro_name = '{}/{}.tar.bz2'.format(conda.config.subdir, meta.dist()) try: dist_info = cli.distribution(owner, meta.name(), meta.version(), distro_name) except binstar_client.errors.NotFound: dist_info = {} return bool(dist_info)
python
def artifact_already_exists(cli, meta, owner): """ Checks to see whether the built recipe (aka distribution) already exists on the owner/user's binstar account. """ distro_name = '{}/{}.tar.bz2'.format(conda.config.subdir, meta.dist()) try: dist_info = cli.distribution(owner, meta.name(), meta.version(), distro_name) except binstar_client.errors.NotFound: dist_info = {} return bool(dist_info)
[ "def", "artifact_already_exists", "(", "cli", ",", "meta", ",", "owner", ")", ":", "distro_name", "=", "'{}/{}.tar.bz2'", ".", "format", "(", "conda", ".", "config", ".", "subdir", ",", "meta", ".", "dist", "(", ")", ")", "try", ":", "dist_info", "=", ...
Checks to see whether the built recipe (aka distribution) already exists on the owner/user's binstar account.
[ "Checks", "to", "see", "whether", "the", "built", "recipe", "(", "aka", "distribution", ")", "already", "exists", "on", "the", "owner", "/", "user", "s", "binstar", "account", "." ]
train
https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/travis-ci/upload.py#L11-L23
anomaly/prestans
prestans/devel/__init__.py
ArgParserFactory._add_generate_sub_commands
def _add_generate_sub_commands(self): """ Sub commands for generating models for usage by clients. Currently supports Google Closure. """ gen_parser = self._subparsers_handle.add_parser( name="gen", help="generate client side model stubs, filters" ) gen_parser.add_argument( "-t", "--template", choices=['closure.model', 'closure.filter'], default='closure.model', required=True, dest="template", help="template to use for client side code generation" ) gen_parser.add_argument( "-m", "--model", required=True, dest="models_definition", help="path to models definition file or package" ) gen_parser.add_argument( "-o", "--output", default=".", dest="output", help="output path for generated code" ) gen_parser.add_argument( "-n", "--namespace", required=True, dest="namespace", help="namespace to use with template e.g prestans.data.model" ) gen_parser.add_argument( "-fn", "--filter-namespace", required=False, default=None, dest="filter_namespace", help="filter namespace to use with template e.g prestans.data.filter" )
python
def _add_generate_sub_commands(self): """ Sub commands for generating models for usage by clients. Currently supports Google Closure. """ gen_parser = self._subparsers_handle.add_parser( name="gen", help="generate client side model stubs, filters" ) gen_parser.add_argument( "-t", "--template", choices=['closure.model', 'closure.filter'], default='closure.model', required=True, dest="template", help="template to use for client side code generation" ) gen_parser.add_argument( "-m", "--model", required=True, dest="models_definition", help="path to models definition file or package" ) gen_parser.add_argument( "-o", "--output", default=".", dest="output", help="output path for generated code" ) gen_parser.add_argument( "-n", "--namespace", required=True, dest="namespace", help="namespace to use with template e.g prestans.data.model" ) gen_parser.add_argument( "-fn", "--filter-namespace", required=False, default=None, dest="filter_namespace", help="filter namespace to use with template e.g prestans.data.filter" )
[ "def", "_add_generate_sub_commands", "(", "self", ")", ":", "gen_parser", "=", "self", ".", "_subparsers_handle", ".", "add_parser", "(", "name", "=", "\"gen\"", ",", "help", "=", "\"generate client side model stubs, filters\"", ")", "gen_parser", ".", "add_argument",...
Sub commands for generating models for usage by clients. Currently supports Google Closure.
[ "Sub", "commands", "for", "generating", "models", "for", "usage", "by", "clients", ".", "Currently", "supports", "Google", "Closure", "." ]
train
https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/devel/__init__.py#L72-L124
anomaly/prestans
prestans/devel/__init__.py
CommandDispatcher._dispatch_gen
def _dispatch_gen(self): """ Process the generate subset of commands. """ if not os.path.isdir(self._args.output): raise exception.Base("%s is not a writeable directory" % self._args.output) if not os.path.isfile(self._args.models_definition): if not self.check_package_exists(self._args.models_definition): raise exception.Base("failed to locate package or models definitions file at: %s" % self._args.models_definition) from prestans.devel.gen import Preplate preplate = Preplate( template_type=self._args.template, models_definition=self._args.models_definition, namespace=self._args.namespace, filter_namespace=self._args.filter_namespace, output_directory=self._args.output) preplate.run()
python
def _dispatch_gen(self): """ Process the generate subset of commands. """ if not os.path.isdir(self._args.output): raise exception.Base("%s is not a writeable directory" % self._args.output) if not os.path.isfile(self._args.models_definition): if not self.check_package_exists(self._args.models_definition): raise exception.Base("failed to locate package or models definitions file at: %s" % self._args.models_definition) from prestans.devel.gen import Preplate preplate = Preplate( template_type=self._args.template, models_definition=self._args.models_definition, namespace=self._args.namespace, filter_namespace=self._args.filter_namespace, output_directory=self._args.output) preplate.run()
[ "def", "_dispatch_gen", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "_args", ".", "output", ")", ":", "raise", "exception", ".", "Base", "(", "\"%s is not a writeable directory\"", "%", "self", ".", "_args", "."...
Process the generate subset of commands.
[ "Process", "the", "generate", "subset", "of", "commands", "." ]
train
https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/devel/__init__.py#L143-L163
theonion/django-bulbs
bulbs/special_coverage/search.py
SearchParty.search
def search(self): """Return a search using the combined query of all associated special coverage objects.""" # Retrieve all Or filters pertinent to the special coverage query. should_filters = [ es_filter.Terms(pk=self.query.get("included_ids", [])), es_filter.Terms(pk=self.query.get("pinned_ids", [])) ] should_filters += self.get_group_filters() # Compile list of all Must filters. must_filters = [ es_filter.Bool(should=should_filters), ~es_filter.Terms(pk=self.query.get("excluded_ids", [])) ] return Content.search_objects.search().filter(es_filter.Bool(must=must_filters))
python
def search(self): """Return a search using the combined query of all associated special coverage objects.""" # Retrieve all Or filters pertinent to the special coverage query. should_filters = [ es_filter.Terms(pk=self.query.get("included_ids", [])), es_filter.Terms(pk=self.query.get("pinned_ids", [])) ] should_filters += self.get_group_filters() # Compile list of all Must filters. must_filters = [ es_filter.Bool(should=should_filters), ~es_filter.Terms(pk=self.query.get("excluded_ids", [])) ] return Content.search_objects.search().filter(es_filter.Bool(must=must_filters))
[ "def", "search", "(", "self", ")", ":", "# Retrieve all Or filters pertinent to the special coverage query.", "should_filters", "=", "[", "es_filter", ".", "Terms", "(", "pk", "=", "self", ".", "query", ".", "get", "(", "\"included_ids\"", ",", "[", "]", ")", ")...
Return a search using the combined query of all associated special coverage objects.
[ "Return", "a", "search", "using", "the", "combined", "query", "of", "all", "associated", "special", "coverage", "objects", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/search.py#L17-L32
theonion/django-bulbs
bulbs/special_coverage/search.py
SearchParty.get_group_filters
def get_group_filters(self): """Return es OR filters to include all special coverage group conditions.""" group_filters = [] field_map = { "feature-type": "feature_type.slug", "tag": "tags.slug", "content-type": "_type" } for group_set in self.query.get("groups", []): for group in group_set: group_filter = es_filter.MatchAll() for condition in group.get("conditions", []): group_filter &= get_condition_filter(condition, field_map=field_map) group_filters.append(group_filter) return group_filters
python
def get_group_filters(self): """Return es OR filters to include all special coverage group conditions.""" group_filters = [] field_map = { "feature-type": "feature_type.slug", "tag": "tags.slug", "content-type": "_type" } for group_set in self.query.get("groups", []): for group in group_set: group_filter = es_filter.MatchAll() for condition in group.get("conditions", []): group_filter &= get_condition_filter(condition, field_map=field_map) group_filters.append(group_filter) return group_filters
[ "def", "get_group_filters", "(", "self", ")", ":", "group_filters", "=", "[", "]", "field_map", "=", "{", "\"feature-type\"", ":", "\"feature_type.slug\"", ",", "\"tag\"", ":", "\"tags.slug\"", ",", "\"content-type\"", ":", "\"_type\"", "}", "for", "group_set", ...
Return es OR filters to include all special coverage group conditions.
[ "Return", "es", "OR", "filters", "to", "include", "all", "special", "coverage", "group", "conditions", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/search.py#L34-L48
theonion/django-bulbs
bulbs/special_coverage/search.py
SearchParty.query
def query(self): """Group the self.special_coverages queries and memoize them.""" if not self._query: self._query.update({ "excluded_ids": [], "included_ids": [], "pinned_ids": [], "groups": [], }) for special_coverage in self._special_coverages: # Access query at dict level. query = getattr(special_coverage, "query", {}) if "query" in query: query = query.get("query") self._query["excluded_ids"] += query.get("excluded_ids", []) self._query["included_ids"] += query.get("included_ids", []) self._query["pinned_ids"] += query.get("pinned_ids", []) self._query["groups"] += [query.get("groups", [])] return self._query
python
def query(self): """Group the self.special_coverages queries and memoize them.""" if not self._query: self._query.update({ "excluded_ids": [], "included_ids": [], "pinned_ids": [], "groups": [], }) for special_coverage in self._special_coverages: # Access query at dict level. query = getattr(special_coverage, "query", {}) if "query" in query: query = query.get("query") self._query["excluded_ids"] += query.get("excluded_ids", []) self._query["included_ids"] += query.get("included_ids", []) self._query["pinned_ids"] += query.get("pinned_ids", []) self._query["groups"] += [query.get("groups", [])] return self._query
[ "def", "query", "(", "self", ")", ":", "if", "not", "self", ".", "_query", ":", "self", ".", "_query", ".", "update", "(", "{", "\"excluded_ids\"", ":", "[", "]", ",", "\"included_ids\"", ":", "[", "]", ",", "\"pinned_ids\"", ":", "[", "]", ",", "\...
Group the self.special_coverages queries and memoize them.
[ "Group", "the", "self", ".", "special_coverages", "queries", "and", "memoize", "them", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/search.py#L51-L69
PGower/PyCanvas
pycanvas/apis/course_quiz_extensions.py
CourseQuizExtensionsAPI.set_extensions_for_student_quiz_submissions
def set_extensions_for_student_quiz_submissions(self, user_id, course_id, extend_from_end_at=None, extend_from_now=None, extra_attempts=None, extra_time=None, manually_unlocked=None): """ Set extensions for student quiz submissions. <b>Responses</b> * <b>200 OK</b> if the request was successful * <b>403 Forbidden</b> if you are not allowed to extend quizzes for this course """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - user_id """The ID of the user we want to add quiz extensions for.""" data["user_id"] = user_id # OPTIONAL - extra_attempts """Number of times the student is allowed to re-take the quiz over the multiple-attempt limit. This is limited to 1000 attempts or less.""" if extra_attempts is not None: data["extra_attempts"] = extra_attempts # OPTIONAL - extra_time """The number of extra minutes to allow for all attempts. This will add to the existing time limit on the submission. This is limited to 10080 minutes (1 week)""" if extra_time is not None: data["extra_time"] = extra_time # OPTIONAL - manually_unlocked """Allow the student to take the quiz even if it's locked for everyone else.""" if manually_unlocked is not None: data["manually_unlocked"] = manually_unlocked # OPTIONAL - extend_from_now """The number of minutes to extend the quiz from the current time. This is mutually exclusive to extend_from_end_at. This is limited to 1440 minutes (24 hours)""" if extend_from_now is not None: data["extend_from_now"] = extend_from_now # OPTIONAL - extend_from_end_at """The number of minutes to extend the quiz beyond the quiz's current ending time. This is mutually exclusive to extend_from_now. This is limited to 1440 minutes (24 hours)""" if extend_from_end_at is not None: data["extend_from_end_at"] = extend_from_end_at self.logger.debug("POST /api/v1/courses/{course_id}/quiz_extensions with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quiz_extensions".format(**path), data=data, params=params, no_data=True)
python
def set_extensions_for_student_quiz_submissions(self, user_id, course_id, extend_from_end_at=None, extend_from_now=None, extra_attempts=None, extra_time=None, manually_unlocked=None): """ Set extensions for student quiz submissions. <b>Responses</b> * <b>200 OK</b> if the request was successful * <b>403 Forbidden</b> if you are not allowed to extend quizzes for this course """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - user_id """The ID of the user we want to add quiz extensions for.""" data["user_id"] = user_id # OPTIONAL - extra_attempts """Number of times the student is allowed to re-take the quiz over the multiple-attempt limit. This is limited to 1000 attempts or less.""" if extra_attempts is not None: data["extra_attempts"] = extra_attempts # OPTIONAL - extra_time """The number of extra minutes to allow for all attempts. This will add to the existing time limit on the submission. This is limited to 10080 minutes (1 week)""" if extra_time is not None: data["extra_time"] = extra_time # OPTIONAL - manually_unlocked """Allow the student to take the quiz even if it's locked for everyone else.""" if manually_unlocked is not None: data["manually_unlocked"] = manually_unlocked # OPTIONAL - extend_from_now """The number of minutes to extend the quiz from the current time. This is mutually exclusive to extend_from_end_at. This is limited to 1440 minutes (24 hours)""" if extend_from_now is not None: data["extend_from_now"] = extend_from_now # OPTIONAL - extend_from_end_at """The number of minutes to extend the quiz beyond the quiz's current ending time. This is mutually exclusive to extend_from_now. This is limited to 1440 minutes (24 hours)""" if extend_from_end_at is not None: data["extend_from_end_at"] = extend_from_end_at self.logger.debug("POST /api/v1/courses/{course_id}/quiz_extensions with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quiz_extensions".format(**path), data=data, params=params, no_data=True)
[ "def", "set_extensions_for_student_quiz_submissions", "(", "self", ",", "user_id", ",", "course_id", ",", "extend_from_end_at", "=", "None", ",", "extend_from_now", "=", "None", ",", "extra_attempts", "=", "None", ",", "extra_time", "=", "None", ",", "manually_unloc...
Set extensions for student quiz submissions. <b>Responses</b> * <b>200 OK</b> if the request was successful * <b>403 Forbidden</b> if you are not allowed to extend quizzes for this course
[ "Set", "extensions", "for", "student", "quiz", "submissions", ".", "<b", ">", "Responses<", "/", "b", ">", "*", "<b", ">", "200", "OK<", "/", "b", ">", "if", "the", "request", "was", "successful", "*", "<b", ">", "403", "Forbidden<", "/", "b", ">", ...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/course_quiz_extensions.py#L19-L74
karel-brinda/rnftools
rnftools/scripts.py
sam2rnf
def sam2rnf(args): """Convert SAM to RNF-based FASTQ with respect to argparse parameters. Args: args (...): Arguments parsed by argparse """ rnftools.mishmash.Source.recode_sam_reads( sam_fn=args.sam_fn, fastq_rnf_fo=args.fq_fo, fai_fo=args.fai_fo, genome_id=args.genome_id, number_of_read_tuples=10**9, simulator_name=args.simulator_name, allow_unmapped=args.allow_unmapped, )
python
def sam2rnf(args): """Convert SAM to RNF-based FASTQ with respect to argparse parameters. Args: args (...): Arguments parsed by argparse """ rnftools.mishmash.Source.recode_sam_reads( sam_fn=args.sam_fn, fastq_rnf_fo=args.fq_fo, fai_fo=args.fai_fo, genome_id=args.genome_id, number_of_read_tuples=10**9, simulator_name=args.simulator_name, allow_unmapped=args.allow_unmapped, )
[ "def", "sam2rnf", "(", "args", ")", ":", "rnftools", ".", "mishmash", ".", "Source", ".", "recode_sam_reads", "(", "sam_fn", "=", "args", ".", "sam_fn", ",", "fastq_rnf_fo", "=", "args", ".", "fq_fo", ",", "fai_fo", "=", "args", ".", "fai_fo", ",", "ge...
Convert SAM to RNF-based FASTQ with respect to argparse parameters. Args: args (...): Arguments parsed by argparse
[ "Convert", "SAM", "to", "RNF", "-", "based", "FASTQ", "with", "respect", "to", "argparse", "parameters", "." ]
train
https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/scripts.py#L58-L73
karel-brinda/rnftools
rnftools/scripts.py
add_sam2rnf_parser
def add_sam2rnf_parser(subparsers, subcommand, help, description, simulator_name=None): """Add another parser for a SAM2RNF-like command. Args: subparsers (subparsers): File name of the genome from which read tuples are created (FASTA file). simulator_name (str): Name of the simulator used in comments. """ parser_sam2rnf = subparsers.add_parser(subcommand, help=help, description=description) parser_sam2rnf.set_defaults(func=sam2rnf) parser_sam2rnf.add_argument( '-s', '--sam', type=str, metavar='file', dest='sam_fn', required=True, help='Input SAM/BAM with true (expected) alignments of the reads (- for standard input).' ) _add_shared_params(parser_sam2rnf, unmapped_switcher=True) parser_sam2rnf.add_argument( '-n', '--simulator-name', type=str, metavar='str', dest='simulator_name', default=simulator_name, help='Name of the simulator (for RNF).' if simulator_name is not None else argparse.SUPPRESS, )
python
def add_sam2rnf_parser(subparsers, subcommand, help, description, simulator_name=None): """Add another parser for a SAM2RNF-like command. Args: subparsers (subparsers): File name of the genome from which read tuples are created (FASTA file). simulator_name (str): Name of the simulator used in comments. """ parser_sam2rnf = subparsers.add_parser(subcommand, help=help, description=description) parser_sam2rnf.set_defaults(func=sam2rnf) parser_sam2rnf.add_argument( '-s', '--sam', type=str, metavar='file', dest='sam_fn', required=True, help='Input SAM/BAM with true (expected) alignments of the reads (- for standard input).' ) _add_shared_params(parser_sam2rnf, unmapped_switcher=True) parser_sam2rnf.add_argument( '-n', '--simulator-name', type=str, metavar='str', dest='simulator_name', default=simulator_name, help='Name of the simulator (for RNF).' if simulator_name is not None else argparse.SUPPRESS, )
[ "def", "add_sam2rnf_parser", "(", "subparsers", ",", "subcommand", ",", "help", ",", "description", ",", "simulator_name", "=", "None", ")", ":", "parser_sam2rnf", "=", "subparsers", ".", "add_parser", "(", "subcommand", ",", "help", "=", "help", ",", "descrip...
Add another parser for a SAM2RNF-like command. Args: subparsers (subparsers): File name of the genome from which read tuples are created (FASTA file). simulator_name (str): Name of the simulator used in comments.
[ "Add", "another", "parser", "for", "a", "SAM2RNF", "-", "like", "command", "." ]
train
https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/scripts.py#L76-L103
Stranger6667/pyoffers
pyoffers/models/affiliate.py
AffiliateManager.create_with_user
def create_with_user(self, user_params, **kwargs): """ Creates an affiliate and corresponding affiliate user :param user_params: kwargs for user creation :param kwargs: :return: affiliate instance """ affiliate = self.create(**kwargs) self.api.affiliate_users.create(affiliate_id=affiliate.id, **user_params) return affiliate
python
def create_with_user(self, user_params, **kwargs): """ Creates an affiliate and corresponding affiliate user :param user_params: kwargs for user creation :param kwargs: :return: affiliate instance """ affiliate = self.create(**kwargs) self.api.affiliate_users.create(affiliate_id=affiliate.id, **user_params) return affiliate
[ "def", "create_with_user", "(", "self", ",", "user_params", ",", "*", "*", "kwargs", ")", ":", "affiliate", "=", "self", ".", "create", "(", "*", "*", "kwargs", ")", "self", ".", "api", ".", "affiliate_users", ".", "create", "(", "affiliate_id", "=", "...
Creates an affiliate and corresponding affiliate user :param user_params: kwargs for user creation :param kwargs: :return: affiliate instance
[ "Creates", "an", "affiliate", "and", "corresponding", "affiliate", "user", ":", "param", "user_params", ":", "kwargs", "for", "user", "creation", ":", "param", "kwargs", ":", ":", "return", ":", "affiliate", "instance" ]
train
https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/models/affiliate.py#L77-L86
PGower/PyCanvas
pycanvas/apis/roles.py
list_roles
def list_roles(self, account_id, show_inherited=None, state=None): """ List roles. List the roles available to an account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """The id of the account to retrieve roles for.""" path["account_id"] = account_id # OPTIONAL - state """Filter by role state. If this argument is omitted, only 'active' roles are returned.""" if state is not None: self._validate_enum(state, ["active", "inactive"]) params["state"] = state # OPTIONAL - show_inherited """If this argument is true, all roles inherited from parent accounts will be included.""" if show_inherited is not None: params["show_inherited"] = show_inherited self.logger.debug("GET /api/v1/accounts/{account_id}/roles with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/accounts/{account_id}/roles".format(**path), data=data, params=params, all_pages=True)
python
def list_roles(self, account_id, show_inherited=None, state=None): """ List roles. List the roles available to an account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """The id of the account to retrieve roles for.""" path["account_id"] = account_id # OPTIONAL - state """Filter by role state. If this argument is omitted, only 'active' roles are returned.""" if state is not None: self._validate_enum(state, ["active", "inactive"]) params["state"] = state # OPTIONAL - show_inherited """If this argument is true, all roles inherited from parent accounts will be included.""" if show_inherited is not None: params["show_inherited"] = show_inherited self.logger.debug("GET /api/v1/accounts/{account_id}/roles with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/accounts/{account_id}/roles".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_roles", "(", "self", ",", "account_id", ",", "show_inherited", "=", "None", ",", "state", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - account_id\r", "\"\"\"The id of the acco...
List roles. List the roles available to an account.
[ "List", "roles", ".", "List", "the", "roles", "available", "to", "an", "account", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/roles.py#L19-L47
PGower/PyCanvas
pycanvas/apis/roles.py
get_single_role
def get_single_role(self, id, role_id, account_id, role=None): """ Get a single role. Retrieve information about a single role """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - PATH - account_id """The id of the account containing the role""" path["account_id"] = account_id # REQUIRED - role_id """The unique identifier for the role""" params["role_id"] = role_id # OPTIONAL - role """The name for the role""" if role is not None: params["role"] = role self.logger.debug("GET /api/v1/accounts/{account_id}/roles/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/accounts/{account_id}/roles/{id}".format(**path), data=data, params=params, single_item=True)
python
def get_single_role(self, id, role_id, account_id, role=None): """ Get a single role. Retrieve information about a single role """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - PATH - account_id """The id of the account containing the role""" path["account_id"] = account_id # REQUIRED - role_id """The unique identifier for the role""" params["role_id"] = role_id # OPTIONAL - role """The name for the role""" if role is not None: params["role"] = role self.logger.debug("GET /api/v1/accounts/{account_id}/roles/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/accounts/{account_id}/roles/{id}".format(**path), data=data, params=params, single_item=True)
[ "def", "get_single_role", "(", "self", ",", "id", ",", "role_id", ",", "account_id", ",", "role", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - id\r", "\"\"\"ID\"\"\"", "path", "[", "...
Get a single role. Retrieve information about a single role
[ "Get", "a", "single", "role", ".", "Retrieve", "information", "about", "a", "single", "role" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/roles.py#L49-L77
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/__init__.py
Operations.execute_script
def execute_script(self, sql_script=None, commands=None, split_algo='sql_split', prep_statements=False, dump_fails=True, execute_fails=True, ignored_commands=('DROP', 'UNLOCK', 'LOCK')): """Wrapper method for SQLScript class.""" ss = Execute(sql_script, split_algo, prep_statements, dump_fails, self) ss.execute(commands, ignored_commands=ignored_commands, execute_fails=execute_fails)
python
def execute_script(self, sql_script=None, commands=None, split_algo='sql_split', prep_statements=False, dump_fails=True, execute_fails=True, ignored_commands=('DROP', 'UNLOCK', 'LOCK')): """Wrapper method for SQLScript class.""" ss = Execute(sql_script, split_algo, prep_statements, dump_fails, self) ss.execute(commands, ignored_commands=ignored_commands, execute_fails=execute_fails)
[ "def", "execute_script", "(", "self", ",", "sql_script", "=", "None", ",", "commands", "=", "None", ",", "split_algo", "=", "'sql_split'", ",", "prep_statements", "=", "False", ",", "dump_fails", "=", "True", ",", "execute_fails", "=", "True", ",", "ignored_...
Wrapper method for SQLScript class.
[ "Wrapper", "method", "for", "SQLScript", "class", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/__init__.py#L10-L14
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/__init__.py
Operations.script
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True): """Wrapper method providing access to the SQLScript class's methods and properties.""" return Execute(sql_script, split_algo, prep_statements, dump_fails, self)
python
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True): """Wrapper method providing access to the SQLScript class's methods and properties.""" return Execute(sql_script, split_algo, prep_statements, dump_fails, self)
[ "def", "script", "(", "self", ",", "sql_script", ",", "split_algo", "=", "'sql_split'", ",", "prep_statements", "=", "True", ",", "dump_fails", "=", "True", ")", ":", "return", "Execute", "(", "sql_script", ",", "split_algo", ",", "prep_statements", ",", "du...
Wrapper method providing access to the SQLScript class's methods and properties.
[ "Wrapper", "method", "providing", "access", "to", "the", "SQLScript", "class", "s", "methods", "and", "properties", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/__init__.py#L16-L18
jjkester/moneybird-python
moneybird/authentication.py
OAuthAuthentication.authorize_url
def authorize_url(self, scope: list, state: str = None) -> tuple: """ Returns the URL to which the user can be redirected to authorize your application to access his/her account. It will also return the state which can be used for CSRF protection. A state is generated if not passed to this method. Example: >>> auth = OAuthAuthentication('https://example.com/oauth/moneybird/', 'your_id', 'your_secret') >>> auth.authorize_url() ('https://moneybird.com/oauth/authorize?client_id=your_id&redirect_uri=https%3A%2F%2Fexample.com%2Flogin%2F moneybird&state=random_string', 'random_string') :param scope: The requested scope. :param state: Optional state, when omitted a random value is generated. :return: 2-tuple containing the URL to redirect the user to and the randomly generated state. """ url = urljoin(self.base_url, self.auth_url) params = { 'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': self.redirect_url, 'scope': ' '.join(scope), 'state': state if state is not None else self._generate_state(), } return "%s?%s" % (url, urlencode(params)), params['state']
python
def authorize_url(self, scope: list, state: str = None) -> tuple: """ Returns the URL to which the user can be redirected to authorize your application to access his/her account. It will also return the state which can be used for CSRF protection. A state is generated if not passed to this method. Example: >>> auth = OAuthAuthentication('https://example.com/oauth/moneybird/', 'your_id', 'your_secret') >>> auth.authorize_url() ('https://moneybird.com/oauth/authorize?client_id=your_id&redirect_uri=https%3A%2F%2Fexample.com%2Flogin%2F moneybird&state=random_string', 'random_string') :param scope: The requested scope. :param state: Optional state, when omitted a random value is generated. :return: 2-tuple containing the URL to redirect the user to and the randomly generated state. """ url = urljoin(self.base_url, self.auth_url) params = { 'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': self.redirect_url, 'scope': ' '.join(scope), 'state': state if state is not None else self._generate_state(), } return "%s?%s" % (url, urlencode(params)), params['state']
[ "def", "authorize_url", "(", "self", ",", "scope", ":", "list", ",", "state", ":", "str", "=", "None", ")", "->", "tuple", ":", "url", "=", "urljoin", "(", "self", ".", "base_url", ",", "self", ".", "auth_url", ")", "params", "=", "{", "'response_typ...
Returns the URL to which the user can be redirected to authorize your application to access his/her account. It will also return the state which can be used for CSRF protection. A state is generated if not passed to this method. Example: >>> auth = OAuthAuthentication('https://example.com/oauth/moneybird/', 'your_id', 'your_secret') >>> auth.authorize_url() ('https://moneybird.com/oauth/authorize?client_id=your_id&redirect_uri=https%3A%2F%2Fexample.com%2Flogin%2F moneybird&state=random_string', 'random_string') :param scope: The requested scope. :param state: Optional state, when omitted a random value is generated. :return: 2-tuple containing the URL to redirect the user to and the randomly generated state.
[ "Returns", "the", "URL", "to", "which", "the", "user", "can", "be", "redirected", "to", "authorize", "your", "application", "to", "access", "his", "/", "her", "account", ".", "It", "will", "also", "return", "the", "state", "which", "can", "be", "used", "...
train
https://github.com/jjkester/moneybird-python/blob/da5f4c8c7ae6c8ed717dc273514a464bc9c284ed/moneybird/authentication.py#L84-L109
jjkester/moneybird-python
moneybird/authentication.py
OAuthAuthentication.obtain_token
def obtain_token(self, redirect_url: str, state: str) -> str: """ Exchange the code that was obtained using `authorize_url` for an authorization token. The code is extracted from the URL that redirected the user back to your site. Example: >>> auth = OAuthAuthentication('https://example.com/oauth/moneybird/', 'your_id', 'your_secret') >>> auth.obtain_token('https://example.com/oauth/moneybird/?code=any&state=random_string', 'random_string') 'token_for_auth' >>> auth.is_ready() True :param redirect_url: The full URL the user was redirected to. :param state: The state used in the authorize url. :return: The authorization token. """ url_data = parse_qs(redirect_url.split('?', 1)[1]) if 'error' in url_data: logger.warning("Error received in OAuth authentication response: %s" % url_data.get('error')) raise OAuthAuthentication.OAuthError(url_data['error'], url_data.get('error_description', None)) if 'code' not in url_data: logger.error("The provided URL is not a valid OAuth authentication response: no code") raise ValueError("The provided URL is not a valid OAuth authentication response: no code") if state and [state] != url_data['state']: logger.warning("OAuth CSRF attack detected: the state in the provided URL does not equal the given state") raise ValueError("CSRF attack detected: the state in the provided URL does not equal the given state") try: response = requests.post( url=urljoin(self.base_url, self.token_url), data={ 'grant_type': 'authorization_code', 'code': url_data['code'][0], 'redirect_uri': self.redirect_url, 'client_id': self.client_id, 'client_secret': self.client_secret, }, ).json() except ValueError: logger.error("The OAuth server returned an invalid response when obtaining a token: JSON error") raise ValueError("The OAuth server returned an invalid response when obtaining a token: JSON error") if 'error' in response: logger.warning("Error while obtaining OAuth authorization token: %s" % response['error']) raise OAuthAuthentication.OAuthError(response['error'], response.get('error', '')) if 'access_token' not in response: logger.error("The OAuth server returned an invalid response when obtaining a token: no access token") raise ValueError("The remote server returned an invalid response when obtaining a token: no access token") self.real_auth.set_token(response['access_token']) logger.debug("Obtained authentication token for state %s: %s" % (state, self.real_auth.auth_token)) return response['access_token']
python
def obtain_token(self, redirect_url: str, state: str) -> str: """ Exchange the code that was obtained using `authorize_url` for an authorization token. The code is extracted from the URL that redirected the user back to your site. Example: >>> auth = OAuthAuthentication('https://example.com/oauth/moneybird/', 'your_id', 'your_secret') >>> auth.obtain_token('https://example.com/oauth/moneybird/?code=any&state=random_string', 'random_string') 'token_for_auth' >>> auth.is_ready() True :param redirect_url: The full URL the user was redirected to. :param state: The state used in the authorize url. :return: The authorization token. """ url_data = parse_qs(redirect_url.split('?', 1)[1]) if 'error' in url_data: logger.warning("Error received in OAuth authentication response: %s" % url_data.get('error')) raise OAuthAuthentication.OAuthError(url_data['error'], url_data.get('error_description', None)) if 'code' not in url_data: logger.error("The provided URL is not a valid OAuth authentication response: no code") raise ValueError("The provided URL is not a valid OAuth authentication response: no code") if state and [state] != url_data['state']: logger.warning("OAuth CSRF attack detected: the state in the provided URL does not equal the given state") raise ValueError("CSRF attack detected: the state in the provided URL does not equal the given state") try: response = requests.post( url=urljoin(self.base_url, self.token_url), data={ 'grant_type': 'authorization_code', 'code': url_data['code'][0], 'redirect_uri': self.redirect_url, 'client_id': self.client_id, 'client_secret': self.client_secret, }, ).json() except ValueError: logger.error("The OAuth server returned an invalid response when obtaining a token: JSON error") raise ValueError("The OAuth server returned an invalid response when obtaining a token: JSON error") if 'error' in response: logger.warning("Error while obtaining OAuth authorization token: %s" % response['error']) raise OAuthAuthentication.OAuthError(response['error'], response.get('error', '')) if 'access_token' not in response: logger.error("The OAuth server returned an invalid response when obtaining a token: no access token") raise ValueError("The remote server returned an invalid response when obtaining a token: no access token") self.real_auth.set_token(response['access_token']) logger.debug("Obtained authentication token for state %s: %s" % (state, self.real_auth.auth_token)) return response['access_token']
[ "def", "obtain_token", "(", "self", ",", "redirect_url", ":", "str", ",", "state", ":", "str", ")", "->", "str", ":", "url_data", "=", "parse_qs", "(", "redirect_url", ".", "split", "(", "'?'", ",", "1", ")", "[", "1", "]", ")", "if", "'error'", "i...
Exchange the code that was obtained using `authorize_url` for an authorization token. The code is extracted from the URL that redirected the user back to your site. Example: >>> auth = OAuthAuthentication('https://example.com/oauth/moneybird/', 'your_id', 'your_secret') >>> auth.obtain_token('https://example.com/oauth/moneybird/?code=any&state=random_string', 'random_string') 'token_for_auth' >>> auth.is_ready() True :param redirect_url: The full URL the user was redirected to. :param state: The state used in the authorize url. :return: The authorization token.
[ "Exchange", "the", "code", "that", "was", "obtained", "using", "authorize_url", "for", "an", "authorization", "token", ".", "The", "code", "is", "extracted", "from", "the", "URL", "that", "redirected", "the", "user", "back", "to", "your", "site", "." ]
train
https://github.com/jjkester/moneybird-python/blob/da5f4c8c7ae6c8ed717dc273514a464bc9c284ed/moneybird/authentication.py#L111-L167
jjkester/moneybird-python
moneybird/authentication.py
OAuthAuthentication._generate_state
def _generate_state() -> str: """ Generates a new random string to be used as OAuth state. :return: A randomly generated OAuth state. """ state = str(uuid.uuid4()).replace('-', '') logger.debug("Generated OAuth state: %s" % state) return state
python
def _generate_state() -> str: """ Generates a new random string to be used as OAuth state. :return: A randomly generated OAuth state. """ state = str(uuid.uuid4()).replace('-', '') logger.debug("Generated OAuth state: %s" % state) return state
[ "def", "_generate_state", "(", ")", "->", "str", ":", "state", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ".", "replace", "(", "'-'", ",", "''", ")", "logger", ".", "debug", "(", "\"Generated OAuth state: %s\"", "%", "state", ")", "return", ...
Generates a new random string to be used as OAuth state. :return: A randomly generated OAuth state.
[ "Generates", "a", "new", "random", "string", "to", "be", "used", "as", "OAuth", "state", ".", ":", "return", ":", "A", "randomly", "generated", "OAuth", "state", "." ]
train
https://github.com/jjkester/moneybird-python/blob/da5f4c8c7ae6c8ed717dc273514a464bc9c284ed/moneybird/authentication.py#L176-L183
mrstephenneal/mysql-toolkit
mysql/toolkit/datatypes/__init__.py
sql_column_type
def sql_column_type(column_data, prefer_varchar=False, prefer_int=False): """ Retrieve the best fit data type for a column of a MySQL table. Accepts a iterable of values ONLY for the column whose data type is in question. :param column_data: Iterable of values from a MySQL table column :param prefer_varchar: Use type VARCHAR if valid :param prefer_int: Use type INT if valid :return: data type """ # Collect list of type, length tuples type_len_pairs = [ValueType(record).get_type_len for record in column_data] # Retrieve frequency counts of each type types_count = {t: type_len_pairs.count(t) for t in set([type_ for type_, len_, len_dec in type_len_pairs])} # Most frequently occurring datatype most_frequent = max(types_count.items(), key=itemgetter(1))[0] # Get max length of all rows to determine suitable limit len_lst, len_decimals_lst = [], [] for type_, len_, len_dec in type_len_pairs: if type_ == most_frequent: if type(len_) is int: len_lst.append(len_) if type(len_dec) is int: len_decimals_lst.append(len_dec) # Catch errors if current type has no len try: max_len = max(len_lst) except ValueError: max_len = None try: max_len_decimal = max(len_decimals_lst) except ValueError: max_len_decimal = None # Return VARCHAR or INT type if flag is on if prefer_varchar and most_frequent != 'VARCHAR' and 'text' in most_frequent.lower(): most_frequent = 'VARCHAR' elif prefer_int and most_frequent != 'INT' and 'int' in most_frequent.lower(): most_frequent = 'INT' # Return MySQL datatype in proper format, only include length if it is set if max_len and max_len_decimal: return '{0} ({1}, {2})'.format(most_frequent, max_len, max_len_decimal) elif max_len: return '{0} ({1})'.format(most_frequent, max_len) else: return most_frequent
python
def sql_column_type(column_data, prefer_varchar=False, prefer_int=False): """ Retrieve the best fit data type for a column of a MySQL table. Accepts a iterable of values ONLY for the column whose data type is in question. :param column_data: Iterable of values from a MySQL table column :param prefer_varchar: Use type VARCHAR if valid :param prefer_int: Use type INT if valid :return: data type """ # Collect list of type, length tuples type_len_pairs = [ValueType(record).get_type_len for record in column_data] # Retrieve frequency counts of each type types_count = {t: type_len_pairs.count(t) for t in set([type_ for type_, len_, len_dec in type_len_pairs])} # Most frequently occurring datatype most_frequent = max(types_count.items(), key=itemgetter(1))[0] # Get max length of all rows to determine suitable limit len_lst, len_decimals_lst = [], [] for type_, len_, len_dec in type_len_pairs: if type_ == most_frequent: if type(len_) is int: len_lst.append(len_) if type(len_dec) is int: len_decimals_lst.append(len_dec) # Catch errors if current type has no len try: max_len = max(len_lst) except ValueError: max_len = None try: max_len_decimal = max(len_decimals_lst) except ValueError: max_len_decimal = None # Return VARCHAR or INT type if flag is on if prefer_varchar and most_frequent != 'VARCHAR' and 'text' in most_frequent.lower(): most_frequent = 'VARCHAR' elif prefer_int and most_frequent != 'INT' and 'int' in most_frequent.lower(): most_frequent = 'INT' # Return MySQL datatype in proper format, only include length if it is set if max_len and max_len_decimal: return '{0} ({1}, {2})'.format(most_frequent, max_len, max_len_decimal) elif max_len: return '{0} ({1})'.format(most_frequent, max_len) else: return most_frequent
[ "def", "sql_column_type", "(", "column_data", ",", "prefer_varchar", "=", "False", ",", "prefer_int", "=", "False", ")", ":", "# Collect list of type, length tuples", "type_len_pairs", "=", "[", "ValueType", "(", "record", ")", ".", "get_type_len", "for", "record", ...
Retrieve the best fit data type for a column of a MySQL table. Accepts a iterable of values ONLY for the column whose data type is in question. :param column_data: Iterable of values from a MySQL table column :param prefer_varchar: Use type VARCHAR if valid :param prefer_int: Use type INT if valid :return: data type
[ "Retrieve", "the", "best", "fit", "data", "type", "for", "a", "column", "of", "a", "MySQL", "table", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/datatypes/__init__.py#L58-L110
mrstephenneal/mysql-toolkit
mysql/toolkit/datatypes/__init__.py
ValueType.get_sql
def get_sql(self): """Retrieve the data type for a data record.""" test_method = [ self.is_time, self.is_date, self.is_datetime, self.is_decimal, self.is_year, self.is_tinyint, self.is_smallint, self.is_mediumint, self.is_int, self.is_bigint, self.is_tinytext, self.is_varchar, self.is_mediumtext, self.is_longtext, ] # Loop through test methods until a test returns True for method in test_method: if method(): return self.sql
python
def get_sql(self): """Retrieve the data type for a data record.""" test_method = [ self.is_time, self.is_date, self.is_datetime, self.is_decimal, self.is_year, self.is_tinyint, self.is_smallint, self.is_mediumint, self.is_int, self.is_bigint, self.is_tinytext, self.is_varchar, self.is_mediumtext, self.is_longtext, ] # Loop through test methods until a test returns True for method in test_method: if method(): return self.sql
[ "def", "get_sql", "(", "self", ")", ":", "test_method", "=", "[", "self", ".", "is_time", ",", "self", ".", "is_date", ",", "self", ".", "is_datetime", ",", "self", ".", "is_decimal", ",", "self", ".", "is_year", ",", "self", ".", "is_tinyint", ",", ...
Retrieve the data type for a data record.
[ "Retrieve", "the", "data", "type", "for", "a", "data", "record", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/datatypes/__init__.py#L27-L48
mrstephenneal/mysql-toolkit
mysql/toolkit/datatypes/__init__.py
ValueType.get_type_len
def get_type_len(self): """Retrieve the type and length for a data record.""" # Check types and set type/len self.get_sql() return self.type, self.len, self.len_decimal
python
def get_type_len(self): """Retrieve the type and length for a data record.""" # Check types and set type/len self.get_sql() return self.type, self.len, self.len_decimal
[ "def", "get_type_len", "(", "self", ")", ":", "# Check types and set type/len", "self", ".", "get_sql", "(", ")", "return", "self", ".", "type", ",", "self", ".", "len", ",", "self", ".", "len_decimal" ]
Retrieve the type and length for a data record.
[ "Retrieve", "the", "type", "and", "length", "for", "a", "data", "record", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/datatypes/__init__.py#L51-L55
PGower/PyCanvas
pycanvas/apis/sections.py
SectionsAPI.create_course_section
def create_course_section(self, course_id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None, enable_sis_reactivation=None): """ Create course section. Creates a new section for this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - course_section[name] """The name of the section""" if course_section_name is not None: data["course_section[name]"] = course_section_name # OPTIONAL - course_section[sis_section_id] """The sis ID of the section""" if course_section_sis_section_id is not None: data["course_section[sis_section_id]"] = course_section_sis_section_id # OPTIONAL - course_section[start_at] """Section start date in ISO8601 format, e.g. 2011-01-01T01:00Z""" if course_section_start_at is not None: data["course_section[start_at]"] = course_section_start_at # OPTIONAL - course_section[end_at] """Section end date in ISO8601 format. e.g. 2011-01-01T01:00Z""" if course_section_end_at is not None: data["course_section[end_at]"] = course_section_end_at # OPTIONAL - course_section[restrict_enrollments_to_section_dates] """Set to true to restrict user enrollments to the start and end dates of the section.""" if course_section_restrict_enrollments_to_section_dates is not None: data["course_section[restrict_enrollments_to_section_dates]"] = course_section_restrict_enrollments_to_section_dates # OPTIONAL - enable_sis_reactivation """When true, will first try to re-activate a deleted section with matching sis_section_id if possible.""" if enable_sis_reactivation is not None: data["enable_sis_reactivation"] = enable_sis_reactivation self.logger.debug("POST /api/v1/courses/{course_id}/sections with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/sections".format(**path), data=data, params=params, single_item=True)
python
def create_course_section(self, course_id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None, enable_sis_reactivation=None): """ Create course section. Creates a new section for this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - course_section[name] """The name of the section""" if course_section_name is not None: data["course_section[name]"] = course_section_name # OPTIONAL - course_section[sis_section_id] """The sis ID of the section""" if course_section_sis_section_id is not None: data["course_section[sis_section_id]"] = course_section_sis_section_id # OPTIONAL - course_section[start_at] """Section start date in ISO8601 format, e.g. 2011-01-01T01:00Z""" if course_section_start_at is not None: data["course_section[start_at]"] = course_section_start_at # OPTIONAL - course_section[end_at] """Section end date in ISO8601 format. e.g. 2011-01-01T01:00Z""" if course_section_end_at is not None: data["course_section[end_at]"] = course_section_end_at # OPTIONAL - course_section[restrict_enrollments_to_section_dates] """Set to true to restrict user enrollments to the start and end dates of the section.""" if course_section_restrict_enrollments_to_section_dates is not None: data["course_section[restrict_enrollments_to_section_dates]"] = course_section_restrict_enrollments_to_section_dates # OPTIONAL - enable_sis_reactivation """When true, will first try to re-activate a deleted section with matching sis_section_id if possible.""" if enable_sis_reactivation is not None: data["enable_sis_reactivation"] = enable_sis_reactivation self.logger.debug("POST /api/v1/courses/{course_id}/sections with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/sections".format(**path), data=data, params=params, single_item=True)
[ "def", "create_course_section", "(", "self", ",", "course_id", ",", "course_section_end_at", "=", "None", ",", "course_section_name", "=", "None", ",", "course_section_restrict_enrollments_to_section_dates", "=", "None", ",", "course_section_sis_section_id", "=", "None", ...
Create course section. Creates a new section for this course.
[ "Create", "course", "section", ".", "Creates", "a", "new", "section", "for", "this", "course", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/sections.py#L49-L94
PGower/PyCanvas
pycanvas/apis/sections.py
SectionsAPI.cross_list_section
def cross_list_section(self, id, new_course_id): """ Cross-list a Section. Move the Section to another course. The new course may be in a different account (department), but must belong to the same root account (institution). """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - PATH - new_course_id """ID""" path["new_course_id"] = new_course_id self.logger.debug("POST /api/v1/sections/{id}/crosslist/{new_course_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/sections/{id}/crosslist/{new_course_id}".format(**path), data=data, params=params, single_item=True)
python
def cross_list_section(self, id, new_course_id): """ Cross-list a Section. Move the Section to another course. The new course may be in a different account (department), but must belong to the same root account (institution). """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - PATH - new_course_id """ID""" path["new_course_id"] = new_course_id self.logger.debug("POST /api/v1/sections/{id}/crosslist/{new_course_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/sections/{id}/crosslist/{new_course_id}".format(**path), data=data, params=params, single_item=True)
[ "def", "cross_list_section", "(", "self", ",", "id", ",", "new_course_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - id\r", "\"\"\"ID\"\"\"", "path", "[", "\"id\"", "]", "=", "id", "# REQUIRED - P...
Cross-list a Section. Move the Section to another course. The new course may be in a different account (department), but must belong to the same root account (institution).
[ "Cross", "-", "list", "a", "Section", ".", "Move", "the", "Section", "to", "another", "course", ".", "The", "new", "course", "may", "be", "in", "a", "different", "account", "(", "department", ")", "but", "must", "belong", "to", "the", "same", "root", "...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/sections.py#L96-L116
PGower/PyCanvas
pycanvas/apis/sections.py
SectionsAPI.edit_section
def edit_section(self, id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None): """ Edit a section. Modify an existing section. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - course_section[name] """The name of the section""" if course_section_name is not None: data["course_section[name]"] = course_section_name # OPTIONAL - course_section[sis_section_id] """The sis ID of the section""" if course_section_sis_section_id is not None: data["course_section[sis_section_id]"] = course_section_sis_section_id # OPTIONAL - course_section[start_at] """Section start date in ISO8601 format, e.g. 2011-01-01T01:00Z""" if course_section_start_at is not None: data["course_section[start_at]"] = course_section_start_at # OPTIONAL - course_section[end_at] """Section end date in ISO8601 format. e.g. 2011-01-01T01:00Z""" if course_section_end_at is not None: data["course_section[end_at]"] = course_section_end_at # OPTIONAL - course_section[restrict_enrollments_to_section_dates] """Set to true to restrict user enrollments to the start and end dates of the section.""" if course_section_restrict_enrollments_to_section_dates is not None: data["course_section[restrict_enrollments_to_section_dates]"] = course_section_restrict_enrollments_to_section_dates self.logger.debug("PUT /api/v1/sections/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/sections/{id}".format(**path), data=data, params=params, single_item=True)
python
def edit_section(self, id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None): """ Edit a section. Modify an existing section. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - course_section[name] """The name of the section""" if course_section_name is not None: data["course_section[name]"] = course_section_name # OPTIONAL - course_section[sis_section_id] """The sis ID of the section""" if course_section_sis_section_id is not None: data["course_section[sis_section_id]"] = course_section_sis_section_id # OPTIONAL - course_section[start_at] """Section start date in ISO8601 format, e.g. 2011-01-01T01:00Z""" if course_section_start_at is not None: data["course_section[start_at]"] = course_section_start_at # OPTIONAL - course_section[end_at] """Section end date in ISO8601 format. e.g. 2011-01-01T01:00Z""" if course_section_end_at is not None: data["course_section[end_at]"] = course_section_end_at # OPTIONAL - course_section[restrict_enrollments_to_section_dates] """Set to true to restrict user enrollments to the start and end dates of the section.""" if course_section_restrict_enrollments_to_section_dates is not None: data["course_section[restrict_enrollments_to_section_dates]"] = course_section_restrict_enrollments_to_section_dates self.logger.debug("PUT /api/v1/sections/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/sections/{id}".format(**path), data=data, params=params, single_item=True)
[ "def", "edit_section", "(", "self", ",", "id", ",", "course_section_end_at", "=", "None", ",", "course_section_name", "=", "None", ",", "course_section_restrict_enrollments_to_section_dates", "=", "None", ",", "course_section_sis_section_id", "=", "None", ",", "course_s...
Edit a section. Modify an existing section.
[ "Edit", "a", "section", ".", "Modify", "an", "existing", "section", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/sections.py#L135-L175
mrstephenneal/mysql-toolkit
mysql/toolkit/components/connector.py
Connector.change_db
def change_db(self, db, user=None): """Change connect database.""" # Get original config and change database key config = self._config config['database'] = db if user: config['user'] = user self.database = db # Close current database connection self._disconnect() # Reconnect to the new database self._connect(config)
python
def change_db(self, db, user=None): """Change connect database.""" # Get original config and change database key config = self._config config['database'] = db if user: config['user'] = user self.database = db # Close current database connection self._disconnect() # Reconnect to the new database self._connect(config)
[ "def", "change_db", "(", "self", ",", "db", ",", "user", "=", "None", ")", ":", "# Get original config and change database key", "config", "=", "self", ".", "_config", "config", "[", "'database'", "]", "=", "db", "if", "user", ":", "config", "[", "'user'", ...
Change connect database.
[ "Change", "connect", "database", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/connector.py#L22-L35
mrstephenneal/mysql-toolkit
mysql/toolkit/components/connector.py
Connector.execute
def execute(self, command): """Execute a single SQL query without returning a result.""" self._cursor.execute(command) self._commit() return True
python
def execute(self, command): """Execute a single SQL query without returning a result.""" self._cursor.execute(command) self._commit() return True
[ "def", "execute", "(", "self", ",", "command", ")", ":", "self", ".", "_cursor", ".", "execute", "(", "command", ")", "self", ".", "_commit", "(", ")", "return", "True" ]
Execute a single SQL query without returning a result.
[ "Execute", "a", "single", "SQL", "query", "without", "returning", "a", "result", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/connector.py#L49-L53
mrstephenneal/mysql-toolkit
mysql/toolkit/components/connector.py
Connector.executemany
def executemany(self, command, params=None, max_attempts=5): """Execute multiple SQL queries without returning a result.""" attempts = 0 while attempts < max_attempts: try: # Execute statement self._cursor.executemany(command, params) self._commit() return True except Exception as e: attempts += 1 self.reconnect() continue
python
def executemany(self, command, params=None, max_attempts=5): """Execute multiple SQL queries without returning a result.""" attempts = 0 while attempts < max_attempts: try: # Execute statement self._cursor.executemany(command, params) self._commit() return True except Exception as e: attempts += 1 self.reconnect() continue
[ "def", "executemany", "(", "self", ",", "command", ",", "params", "=", "None", ",", "max_attempts", "=", "5", ")", ":", "attempts", "=", "0", "while", "attempts", "<", "max_attempts", ":", "try", ":", "# Execute statement", "self", ".", "_cursor", ".", "...
Execute multiple SQL queries without returning a result.
[ "Execute", "multiple", "SQL", "queries", "without", "returning", "a", "result", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/connector.py#L60-L72
mrstephenneal/mysql-toolkit
mysql/toolkit/components/connector.py
Connector._connect
def _connect(self, config): """Establish a connection with a MySQL database.""" if 'connection_timeout' not in self._config: self._config['connection_timeout'] = 480 try: self._cnx = connect(**config) self._cursor = self._cnx.cursor() self._printer('\tMySQL DB connection established with db', config['database']) except Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") raise err
python
def _connect(self, config): """Establish a connection with a MySQL database.""" if 'connection_timeout' not in self._config: self._config['connection_timeout'] = 480 try: self._cnx = connect(**config) self._cursor = self._cnx.cursor() self._printer('\tMySQL DB connection established with db', config['database']) except Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") raise err
[ "def", "_connect", "(", "self", ",", "config", ")", ":", "if", "'connection_timeout'", "not", "in", "self", ".", "_config", ":", "self", ".", "_config", "[", "'connection_timeout'", "]", "=", "480", "try", ":", "self", ".", "_cnx", "=", "connect", "(", ...
Establish a connection with a MySQL database.
[ "Establish", "a", "connection", "with", "a", "MySQL", "database", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/connector.py#L74-L87
mrstephenneal/mysql-toolkit
mysql/toolkit/components/connector.py
Connector._fetch
def _fetch(self, statement, commit, max_attempts=5): """ Execute a SQL query and return a result. Recursively disconnect and reconnect to the database if an error occurs. """ if self._auto_reconnect: attempts = 0 while attempts < max_attempts: try: # Execute statement self._cursor.execute(statement) fetch = self._cursor.fetchall() rows = self._fetch_rows(fetch) if commit: self._commit() # Return a single item if the list only has one item return rows[0] if len(rows) == 1 else rows except Exception as e: if attempts >= max_attempts: raise e else: attempts += 1 self.reconnect() continue else: # Execute statement self._cursor.execute(statement) fetch = self._cursor.fetchall() rows = self._fetch_rows(fetch) if commit: self._commit() # Return a single item if the list only has one item return rows[0] if len(rows) == 1 else rows
python
def _fetch(self, statement, commit, max_attempts=5): """ Execute a SQL query and return a result. Recursively disconnect and reconnect to the database if an error occurs. """ if self._auto_reconnect: attempts = 0 while attempts < max_attempts: try: # Execute statement self._cursor.execute(statement) fetch = self._cursor.fetchall() rows = self._fetch_rows(fetch) if commit: self._commit() # Return a single item if the list only has one item return rows[0] if len(rows) == 1 else rows except Exception as e: if attempts >= max_attempts: raise e else: attempts += 1 self.reconnect() continue else: # Execute statement self._cursor.execute(statement) fetch = self._cursor.fetchall() rows = self._fetch_rows(fetch) if commit: self._commit() # Return a single item if the list only has one item return rows[0] if len(rows) == 1 else rows
[ "def", "_fetch", "(", "self", ",", "statement", ",", "commit", ",", "max_attempts", "=", "5", ")", ":", "if", "self", ".", "_auto_reconnect", ":", "attempts", "=", "0", "while", "attempts", "<", "max_attempts", ":", "try", ":", "# Execute statement", "self...
Execute a SQL query and return a result. Recursively disconnect and reconnect to the database if an error occurs.
[ "Execute", "a", "SQL", "query", "and", "return", "a", "result", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/connector.py#L113-L149
lordmauve/lepton
examples/bouncy.py
resize
def resize(widthWindow, heightWindow): """Initial settings for the OpenGL state machine, clear color, window size, etc""" glEnable(GL_BLEND) glEnable(GL_POINT_SMOOTH) glShadeModel(GL_SMOOTH)# Enables Smooth Shading glBlendFunc(GL_SRC_ALPHA,GL_ONE)#Type Of Blending To Perform glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);#Really Nice Perspective Calculations glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);#Really Nice Point Smoothing glDisable(GL_DEPTH_TEST)
python
def resize(widthWindow, heightWindow): """Initial settings for the OpenGL state machine, clear color, window size, etc""" glEnable(GL_BLEND) glEnable(GL_POINT_SMOOTH) glShadeModel(GL_SMOOTH)# Enables Smooth Shading glBlendFunc(GL_SRC_ALPHA,GL_ONE)#Type Of Blending To Perform glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);#Really Nice Perspective Calculations glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);#Really Nice Point Smoothing glDisable(GL_DEPTH_TEST)
[ "def", "resize", "(", "widthWindow", ",", "heightWindow", ")", ":", "glEnable", "(", "GL_BLEND", ")", "glEnable", "(", "GL_POINT_SMOOTH", ")", "glShadeModel", "(", "GL_SMOOTH", ")", "# Enables Smooth Shading", "glBlendFunc", "(", "GL_SRC_ALPHA", ",", "GL_ONE", ")"...
Initial settings for the OpenGL state machine, clear color, window size, etc
[ "Initial", "settings", "for", "the", "OpenGL", "state", "machine", "clear", "color", "window", "size", "etc" ]
train
https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/bouncy.py#L46-L54
lordmauve/lepton
examples/bouncy.py
Bumper.set_bumper_color
def set_bumper_color(self, particle, group, bumper, collision_point, collision_normal): """Set bumper color to the color of the particle that collided with it""" self.color = tuple(particle.color)[:3]
python
def set_bumper_color(self, particle, group, bumper, collision_point, collision_normal): """Set bumper color to the color of the particle that collided with it""" self.color = tuple(particle.color)[:3]
[ "def", "set_bumper_color", "(", "self", ",", "particle", ",", "group", ",", "bumper", ",", "collision_point", ",", "collision_normal", ")", ":", "self", ".", "color", "=", "tuple", "(", "particle", ".", "color", ")", "[", ":", "3", "]" ]
Set bumper color to the color of the particle that collided with it
[ "Set", "bumper", "color", "to", "the", "color", "of", "the", "particle", "that", "collided", "with", "it" ]
train
https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/bouncy.py#L38-L40
tariqdaouda/rabaDB
rabaDB/filters.py
RabaQuery.reset
def reset(self, rabaClass, namespace = None) : """rabaClass can either be a raba class of a string of a raba class name. In the latter case you must provide the namespace argument. If it's a Raba Class the argument is ignored. If you fear cicular imports use strings""" if type(rabaClass) is types.StringType : self._raba_namespace = namespace self.con = stp.RabaConnection(self._raba_namespace) self.rabaClass = self.con.getClass(rabaClass) else : self.rabaClass = rabaClass self._raba_namespace = self.rabaClass._raba_namespace self.con = stp.RabaConnection(self._raba_namespace) self.filters = [] self.tables = set() #self.fctPattern = re.compile("\s*([^\s]+)\s*\(\s*([^\s]+)\s*\)\s*([=><])\s*([^\s]+)\s*") self.fieldPattern = re.compile("\s*([^\s\(\)]+)\s*([=><]|([L|l][I|i][K|k][E|e]))\s*(.+)") self.operators = set(['LIKE', '=', '<', '>', '=', '>=', '<=', '<>', '!=', 'IS'])
python
def reset(self, rabaClass, namespace = None) : """rabaClass can either be a raba class of a string of a raba class name. In the latter case you must provide the namespace argument. If it's a Raba Class the argument is ignored. If you fear cicular imports use strings""" if type(rabaClass) is types.StringType : self._raba_namespace = namespace self.con = stp.RabaConnection(self._raba_namespace) self.rabaClass = self.con.getClass(rabaClass) else : self.rabaClass = rabaClass self._raba_namespace = self.rabaClass._raba_namespace self.con = stp.RabaConnection(self._raba_namespace) self.filters = [] self.tables = set() #self.fctPattern = re.compile("\s*([^\s]+)\s*\(\s*([^\s]+)\s*\)\s*([=><])\s*([^\s]+)\s*") self.fieldPattern = re.compile("\s*([^\s\(\)]+)\s*([=><]|([L|l][I|i][K|k][E|e]))\s*(.+)") self.operators = set(['LIKE', '=', '<', '>', '=', '>=', '<=', '<>', '!=', 'IS'])
[ "def", "reset", "(", "self", ",", "rabaClass", ",", "namespace", "=", "None", ")", ":", "if", "type", "(", "rabaClass", ")", "is", "types", ".", "StringType", ":", "self", ".", "_raba_namespace", "=", "namespace", "self", ".", "con", "=", "stp", ".", ...
rabaClass can either be a raba class of a string of a raba class name. In the latter case you must provide the namespace argument. If it's a Raba Class the argument is ignored. If you fear cicular imports use strings
[ "rabaClass", "can", "either", "be", "a", "raba", "class", "of", "a", "string", "of", "a", "raba", "class", "name", ".", "In", "the", "latter", "case", "you", "must", "provide", "the", "namespace", "argument", ".", "If", "it", "s", "a", "Raba", "Class",...
train
https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/filters.py#L51-L69
tariqdaouda/rabaDB
rabaDB/filters.py
RabaQuery.addFilter
def addFilter(self, *lstFilters, **dctFilters) : "add a new filter to the query" dstF = {} if len(lstFilters) > 0 : if type(lstFilters[0]) is types.DictType : dstF = lstFilters[0] lstFilters = lstFilters[1:] if len(dctFilters) > 0 : dstF = dict(dstF, **dctFilters) filts = {} for k, v in dstF.iteritems() : sk = k.split(' ') if len(sk) == 2 : operator = sk[-1].strip().upper() if operator not in self.operators : raise ValueError('Unrecognized operator "%s"' % operator) kk = '%s.%s'% (self.rabaClass.__name__, k) elif len(sk) == 1 : operator = "=" kk = '%s.%s ='% (self.rabaClass.__name__, k) else : raise ValueError('Invalid field %s' % k) if isRabaObject(v) : vv = v.getJsonEncoding() else : vv = v if sk[0].find('.') > -1 : kk = self._parseJoint(sk[0], operator) filts[kk] = vv for lt in lstFilters : for l in lt : match = self.fieldPattern.match(l) if match == None : raise ValueError("RabaQuery Error: Invalid filter '%s'" % l) field = match.group(1) operator = match.group(2) value = match.group(4) if field.find('.') > -1 : joink = self._parseJoint(field, operator, value) filts[joink] = value else : filts['%s.%s %s' %(self.rabaClass.__name__, field, operator)] = value self.filters.append(filts)
python
def addFilter(self, *lstFilters, **dctFilters) : "add a new filter to the query" dstF = {} if len(lstFilters) > 0 : if type(lstFilters[0]) is types.DictType : dstF = lstFilters[0] lstFilters = lstFilters[1:] if len(dctFilters) > 0 : dstF = dict(dstF, **dctFilters) filts = {} for k, v in dstF.iteritems() : sk = k.split(' ') if len(sk) == 2 : operator = sk[-1].strip().upper() if operator not in self.operators : raise ValueError('Unrecognized operator "%s"' % operator) kk = '%s.%s'% (self.rabaClass.__name__, k) elif len(sk) == 1 : operator = "=" kk = '%s.%s ='% (self.rabaClass.__name__, k) else : raise ValueError('Invalid field %s' % k) if isRabaObject(v) : vv = v.getJsonEncoding() else : vv = v if sk[0].find('.') > -1 : kk = self._parseJoint(sk[0], operator) filts[kk] = vv for lt in lstFilters : for l in lt : match = self.fieldPattern.match(l) if match == None : raise ValueError("RabaQuery Error: Invalid filter '%s'" % l) field = match.group(1) operator = match.group(2) value = match.group(4) if field.find('.') > -1 : joink = self._parseJoint(field, operator, value) filts[joink] = value else : filts['%s.%s %s' %(self.rabaClass.__name__, field, operator)] = value self.filters.append(filts)
[ "def", "addFilter", "(", "self", ",", "*", "lstFilters", ",", "*", "*", "dctFilters", ")", ":", "dstF", "=", "{", "}", "if", "len", "(", "lstFilters", ")", ">", "0", ":", "if", "type", "(", "lstFilters", "[", "0", "]", ")", "is", "types", ".", ...
add a new filter to the query
[ "add", "a", "new", "filter", "to", "the", "query" ]
train
https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/filters.py#L76-L128
tariqdaouda/rabaDB
rabaDB/filters.py
RabaQuery.getSQLQuery
def getSQLQuery(self, count = False) : "Returns the query without performing it. If count, the query returned will be a SELECT COUNT() instead of a SELECT" sqlFilters = [] sqlValues = [] # print self.filters for f in self.filters : filt = [] for k, vv in f.iteritems() : if type(vv) is types.ListType or type(vv) is types.TupleType : sqlValues.extend(vv) kk = 'OR %s ? '%k * len(vv) kk = "(%s)" % kk[3:] else : kk = k sqlValues.append(vv) filt.append(kk) sqlFilters.append('(%s ?)' % ' ? AND '.join(filt)) if len(sqlValues) > stp.SQLITE_LIMIT_VARIABLE_NUMBER : raise ValueError("""The limit number of parameters imposed by sqlite is %s. You will have to break your query into several smaller one. Sorry about that. (actual number of parameters is: %s)""" % (stp.SQLITE_LIMIT_VARIABLE_NUMBER, len(sqlValues))) sqlFilters =' OR '.join(sqlFilters) if len(self.tables) < 2 : tablesStr = self.rabaClass.__name__ else : tablesStr = ', '.join(self.tables) if len(sqlFilters) == 0 : sqlFilters = '1' if count : sql = 'SELECT COUNT(*) FROM %s WHERE %s' % (tablesStr, sqlFilters) else : sql = 'SELECT %s.raba_id FROM %s WHERE %s' % (self.rabaClass.__name__, tablesStr, sqlFilters) return (sql, sqlValues)
python
def getSQLQuery(self, count = False) : "Returns the query without performing it. If count, the query returned will be a SELECT COUNT() instead of a SELECT" sqlFilters = [] sqlValues = [] # print self.filters for f in self.filters : filt = [] for k, vv in f.iteritems() : if type(vv) is types.ListType or type(vv) is types.TupleType : sqlValues.extend(vv) kk = 'OR %s ? '%k * len(vv) kk = "(%s)" % kk[3:] else : kk = k sqlValues.append(vv) filt.append(kk) sqlFilters.append('(%s ?)' % ' ? AND '.join(filt)) if len(sqlValues) > stp.SQLITE_LIMIT_VARIABLE_NUMBER : raise ValueError("""The limit number of parameters imposed by sqlite is %s. You will have to break your query into several smaller one. Sorry about that. (actual number of parameters is: %s)""" % (stp.SQLITE_LIMIT_VARIABLE_NUMBER, len(sqlValues))) sqlFilters =' OR '.join(sqlFilters) if len(self.tables) < 2 : tablesStr = self.rabaClass.__name__ else : tablesStr = ', '.join(self.tables) if len(sqlFilters) == 0 : sqlFilters = '1' if count : sql = 'SELECT COUNT(*) FROM %s WHERE %s' % (tablesStr, sqlFilters) else : sql = 'SELECT %s.raba_id FROM %s WHERE %s' % (self.rabaClass.__name__, tablesStr, sqlFilters) return (sql, sqlValues)
[ "def", "getSQLQuery", "(", "self", ",", "count", "=", "False", ")", ":", "sqlFilters", "=", "[", "]", "sqlValues", "=", "[", "]", "# print self.filters", "for", "f", "in", "self", ".", "filters", ":", "filt", "=", "[", "]", "for", "k", ",", "vv", "...
Returns the query without performing it. If count, the query returned will be a SELECT COUNT() instead of a SELECT
[ "Returns", "the", "query", "without", "performing", "it", ".", "If", "count", "the", "query", "returned", "will", "be", "a", "SELECT", "COUNT", "()", "instead", "of", "a", "SELECT" ]
train
https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/filters.py#L155-L192
tariqdaouda/rabaDB
rabaDB/filters.py
RabaQuery.iterRun
def iterRun(self, sqlTail = '', raw = False) : """Compile filters and run the query and returns an iterator. This much more efficient for large data sets but you get the results one element at a time. One thing to keep in mind is that this function keeps the cursor open, that means that the sqlite databae is locked (no updates/inserts etc...) until all the elements have been fetched. For batch updates to the database, preload the results into a list using get, then do you updates. You can use sqlTail to add things such as order by If raw, returns the raw tuple data (not wrapped into a raba object)""" sql, sqlValues = self.getSQLQuery() cur = self.con.execute('%s %s'% (sql, sqlTail), sqlValues) for v in cur : if not raw : yield RabaPupa(self.rabaClass, v[0]) else : yield v
python
def iterRun(self, sqlTail = '', raw = False) : """Compile filters and run the query and returns an iterator. This much more efficient for large data sets but you get the results one element at a time. One thing to keep in mind is that this function keeps the cursor open, that means that the sqlite databae is locked (no updates/inserts etc...) until all the elements have been fetched. For batch updates to the database, preload the results into a list using get, then do you updates. You can use sqlTail to add things such as order by If raw, returns the raw tuple data (not wrapped into a raba object)""" sql, sqlValues = self.getSQLQuery() cur = self.con.execute('%s %s'% (sql, sqlTail), sqlValues) for v in cur : if not raw : yield RabaPupa(self.rabaClass, v[0]) else : yield v
[ "def", "iterRun", "(", "self", ",", "sqlTail", "=", "''", ",", "raw", "=", "False", ")", ":", "sql", ",", "sqlValues", "=", "self", ".", "getSQLQuery", "(", ")", "cur", "=", "self", ".", "con", ".", "execute", "(", "'%s %s'", "%", "(", "sql", ","...
Compile filters and run the query and returns an iterator. This much more efficient for large data sets but you get the results one element at a time. One thing to keep in mind is that this function keeps the cursor open, that means that the sqlite databae is locked (no updates/inserts etc...) until all the elements have been fetched. For batch updates to the database, preload the results into a list using get, then do you updates. You can use sqlTail to add things such as order by If raw, returns the raw tuple data (not wrapped into a raba object)
[ "Compile", "filters", "and", "run", "the", "query", "and", "returns", "an", "iterator", ".", "This", "much", "more", "efficient", "for", "large", "data", "sets", "but", "you", "get", "the", "results", "one", "element", "at", "a", "time", ".", "One", "thi...
train
https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/filters.py#L194-L207
tariqdaouda/rabaDB
rabaDB/filters.py
RabaQuery.run
def run(self, sqlTail = '', raw = False) : """Compile filters and run the query and returns the entire result. You can use sqlTail to add things such as order by. If raw, returns the raw tuple data (not wrapped into a raba object)""" sql, sqlValues = self.getSQLQuery() cur = self.con.execute('%s %s'% (sql, sqlTail), sqlValues) res = [] for v in cur : if not raw : res.append(RabaPupa(self.rabaClass, v[0])) else : return v return res
python
def run(self, sqlTail = '', raw = False) : """Compile filters and run the query and returns the entire result. You can use sqlTail to add things such as order by. If raw, returns the raw tuple data (not wrapped into a raba object)""" sql, sqlValues = self.getSQLQuery() cur = self.con.execute('%s %s'% (sql, sqlTail), sqlValues) res = [] for v in cur : if not raw : res.append(RabaPupa(self.rabaClass, v[0])) else : return v return res
[ "def", "run", "(", "self", ",", "sqlTail", "=", "''", ",", "raw", "=", "False", ")", ":", "sql", ",", "sqlValues", "=", "self", ".", "getSQLQuery", "(", ")", "cur", "=", "self", ".", "con", ".", "execute", "(", "'%s %s'", "%", "(", "sql", ",", ...
Compile filters and run the query and returns the entire result. You can use sqlTail to add things such as order by. If raw, returns the raw tuple data (not wrapped into a raba object)
[ "Compile", "filters", "and", "run", "the", "query", "and", "returns", "the", "entire", "result", ".", "You", "can", "use", "sqlTail", "to", "add", "things", "such", "as", "order", "by", ".", "If", "raw", "returns", "the", "raw", "tuple", "data", "(", "...
train
https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/filters.py#L209-L221
tariqdaouda/rabaDB
rabaDB/filters.py
RabaQuery.count
def count(self, sqlTail = '') : "Compile filters and counts the number of results. You can use sqlTail to add things such as order by" sql, sqlValues = self.getSQLQuery(count = True) return int(self.con.execute('%s %s'% (sql, sqlTail), sqlValues).fetchone()[0])
python
def count(self, sqlTail = '') : "Compile filters and counts the number of results. You can use sqlTail to add things such as order by" sql, sqlValues = self.getSQLQuery(count = True) return int(self.con.execute('%s %s'% (sql, sqlTail), sqlValues).fetchone()[0])
[ "def", "count", "(", "self", ",", "sqlTail", "=", "''", ")", ":", "sql", ",", "sqlValues", "=", "self", ".", "getSQLQuery", "(", "count", "=", "True", ")", "return", "int", "(", "self", ".", "con", ".", "execute", "(", "'%s %s'", "%", "(", "sql", ...
Compile filters and counts the number of results. You can use sqlTail to add things such as order by
[ "Compile", "filters", "and", "counts", "the", "number", "of", "results", ".", "You", "can", "use", "sqlTail", "to", "add", "things", "such", "as", "order", "by" ]
train
https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/filters.py#L223-L226
tariqdaouda/rabaDB
rabaDB/filters.py
RabaQuery.runWhere
def runWhere(self, whereAndTail, params = (), raw = False) : """You get to write your own where + tail clauses. If raw, returns the raw tuple data (not wrapped into a raba object).If raw, returns the raw tuple data (not wrapped into a raba object)""" sql = "SELECT %s.raba_id FROM %s WHERE %s" % (self.rabaClass.__name__, self.rabaClass.__name__, whereAndTail) cur = self.con.execute(sql, params) res = [] for v in cur : if not raw : res.append(RabaPupa(self.rabaClass, v[0])) else : return v return res
python
def runWhere(self, whereAndTail, params = (), raw = False) : """You get to write your own where + tail clauses. If raw, returns the raw tuple data (not wrapped into a raba object).If raw, returns the raw tuple data (not wrapped into a raba object)""" sql = "SELECT %s.raba_id FROM %s WHERE %s" % (self.rabaClass.__name__, self.rabaClass.__name__, whereAndTail) cur = self.con.execute(sql, params) res = [] for v in cur : if not raw : res.append(RabaPupa(self.rabaClass, v[0])) else : return v return res
[ "def", "runWhere", "(", "self", ",", "whereAndTail", ",", "params", "=", "(", ")", ",", "raw", "=", "False", ")", ":", "sql", "=", "\"SELECT %s.raba_id FROM %s WHERE %s\"", "%", "(", "self", ".", "rabaClass", ".", "__name__", ",", "self", ".", "rabaClass",...
You get to write your own where + tail clauses. If raw, returns the raw tuple data (not wrapped into a raba object).If raw, returns the raw tuple data (not wrapped into a raba object)
[ "You", "get", "to", "write", "your", "own", "where", "+", "tail", "clauses", ".", "If", "raw", "returns", "the", "raw", "tuple", "data", "(", "not", "wrapped", "into", "a", "raba", "object", ")", ".", "If", "raw", "returns", "the", "raw", "tuple", "d...
train
https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/filters.py#L228-L239
mrstephenneal/mysql-toolkit
mysql/toolkit/components/structure/schema.py
Schema.show_schema
def show_schema(self, tables=None): """Print schema information.""" tables = tables if tables else self.tables for t in tables: self._printer('\t{0}'.format(t)) for col in self.get_schema(t, True): self._printer('\t\t{0:30} {1:15} {2:10} {3:10} {4:10} {5:10}'.format(*col))
python
def show_schema(self, tables=None): """Print schema information.""" tables = tables if tables else self.tables for t in tables: self._printer('\t{0}'.format(t)) for col in self.get_schema(t, True): self._printer('\t\t{0:30} {1:15} {2:10} {3:10} {4:10} {5:10}'.format(*col))
[ "def", "show_schema", "(", "self", ",", "tables", "=", "None", ")", ":", "tables", "=", "tables", "if", "tables", "else", "self", ".", "tables", "for", "t", "in", "tables", ":", "self", ".", "_printer", "(", "'\\t{0}'", ".", "format", "(", "t", ")", ...
Print schema information.
[ "Print", "schema", "information", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/schema.py#L6-L12
mrstephenneal/mysql-toolkit
mysql/toolkit/components/structure/schema.py
Schema.get_schema_dict
def get_schema_dict(self, table): """ Retrieve the database schema in key, value pairs for easier references and comparisons. """ # Retrieve schema in list form schema = self.get_schema(table, with_headers=True) # Pop headers from first item in list headers = schema.pop(0) # Create dictionary by zipping headers with each row return {values[0]: dict(zip(headers, values[0:])) for values in schema}
python
def get_schema_dict(self, table): """ Retrieve the database schema in key, value pairs for easier references and comparisons. """ # Retrieve schema in list form schema = self.get_schema(table, with_headers=True) # Pop headers from first item in list headers = schema.pop(0) # Create dictionary by zipping headers with each row return {values[0]: dict(zip(headers, values[0:])) for values in schema}
[ "def", "get_schema_dict", "(", "self", ",", "table", ")", ":", "# Retrieve schema in list form", "schema", "=", "self", ".", "get_schema", "(", "table", ",", "with_headers", "=", "True", ")", "# Pop headers from first item in list", "headers", "=", "schema", ".", ...
Retrieve the database schema in key, value pairs for easier references and comparisons.
[ "Retrieve", "the", "database", "schema", "in", "key", "value", "pairs", "for", "easier", "references", "and", "comparisons", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/schema.py#L18-L30
mrstephenneal/mysql-toolkit
mysql/toolkit/components/structure/schema.py
Schema.get_schema
def get_schema(self, table, with_headers=False): """Retrieve the database schema for a particular table.""" f = self.fetch('desc ' + wrap(table)) if not isinstance(f[0], list): f = [f] # Replace None with '' schema = [['' if col is None else col for col in row] for row in f] # If with_headers is True, insert headers to first row before returning if with_headers: schema.insert(0, ['Column', 'Type', 'Null', 'Key', 'Default', 'Extra']) return schema
python
def get_schema(self, table, with_headers=False): """Retrieve the database schema for a particular table.""" f = self.fetch('desc ' + wrap(table)) if not isinstance(f[0], list): f = [f] # Replace None with '' schema = [['' if col is None else col for col in row] for row in f] # If with_headers is True, insert headers to first row before returning if with_headers: schema.insert(0, ['Column', 'Type', 'Null', 'Key', 'Default', 'Extra']) return schema
[ "def", "get_schema", "(", "self", ",", "table", ",", "with_headers", "=", "False", ")", ":", "f", "=", "self", ".", "fetch", "(", "'desc '", "+", "wrap", "(", "table", ")", ")", "if", "not", "isinstance", "(", "f", "[", "0", "]", ",", "list", ")"...
Retrieve the database schema for a particular table.
[ "Retrieve", "the", "database", "schema", "for", "a", "particular", "table", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/schema.py#L32-L44
mrstephenneal/mysql-toolkit
mysql/toolkit/components/structure/schema.py
Schema.add_column
def add_column(self, table, name='ID', data_type='int(11)', after_col=None, null=False, primary_key=False): """Add a column to an existing table.""" location = 'AFTER {0}'.format(after_col) if after_col else 'FIRST' null_ = 'NULL' if null else 'NOT NULL' comment = "COMMENT 'Column auto created by mysql-toolkit'" pk = 'AUTO_INCREMENT PRIMARY KEY {0}'.format(comment) if primary_key else '' query = 'ALTER TABLE {0} ADD COLUMN {1} {2} {3} {4} {5}'.format(wrap(table), name, data_type, null_, pk, location) self.execute(query) self._printer("\tAdded column '{0}' to '{1}' {2}".format(name, table, '(Primary Key)' if primary_key else '')) return name
python
def add_column(self, table, name='ID', data_type='int(11)', after_col=None, null=False, primary_key=False): """Add a column to an existing table.""" location = 'AFTER {0}'.format(after_col) if after_col else 'FIRST' null_ = 'NULL' if null else 'NOT NULL' comment = "COMMENT 'Column auto created by mysql-toolkit'" pk = 'AUTO_INCREMENT PRIMARY KEY {0}'.format(comment) if primary_key else '' query = 'ALTER TABLE {0} ADD COLUMN {1} {2} {3} {4} {5}'.format(wrap(table), name, data_type, null_, pk, location) self.execute(query) self._printer("\tAdded column '{0}' to '{1}' {2}".format(name, table, '(Primary Key)' if primary_key else '')) return name
[ "def", "add_column", "(", "self", ",", "table", ",", "name", "=", "'ID'", ",", "data_type", "=", "'int(11)'", ",", "after_col", "=", "None", ",", "null", "=", "False", ",", "primary_key", "=", "False", ")", ":", "location", "=", "'AFTER {0}'", ".", "fo...
Add a column to an existing table.
[ "Add", "a", "column", "to", "an", "existing", "table", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/schema.py#L46-L56
mrstephenneal/mysql-toolkit
mysql/toolkit/components/structure/schema.py
Schema.drop_column
def drop_column(self, table, name): """Remove a column to an existing table.""" try: self.execute('ALTER TABLE {0} DROP COLUMN {1}'.format(wrap(table), name)) self._printer('\tDropped column {0} from {1}'.format(name, table)) except ProgrammingError: self._printer("\tCan't DROP '{0}'; check that column/key exists in '{1}'".format(name, table)) return name
python
def drop_column(self, table, name): """Remove a column to an existing table.""" try: self.execute('ALTER TABLE {0} DROP COLUMN {1}'.format(wrap(table), name)) self._printer('\tDropped column {0} from {1}'.format(name, table)) except ProgrammingError: self._printer("\tCan't DROP '{0}'; check that column/key exists in '{1}'".format(name, table)) return name
[ "def", "drop_column", "(", "self", ",", "table", ",", "name", ")", ":", "try", ":", "self", ".", "execute", "(", "'ALTER TABLE {0} DROP COLUMN {1}'", ".", "format", "(", "wrap", "(", "table", ")", ",", "name", ")", ")", "self", ".", "_printer", "(", "'...
Remove a column to an existing table.
[ "Remove", "a", "column", "to", "an", "existing", "table", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/schema.py#L58-L65
mrstephenneal/mysql-toolkit
mysql/toolkit/components/structure/schema.py
Schema.drop_index
def drop_index(self, table, column): """Drop an index from a table.""" self.execute('ALTER TABLE {0} DROP INDEX {1}'.format(wrap(table), column)) self._printer('\tDropped index from column {0}'.format(column))
python
def drop_index(self, table, column): """Drop an index from a table.""" self.execute('ALTER TABLE {0} DROP INDEX {1}'.format(wrap(table), column)) self._printer('\tDropped index from column {0}'.format(column))
[ "def", "drop_index", "(", "self", ",", "table", ",", "column", ")", ":", "self", ".", "execute", "(", "'ALTER TABLE {0} DROP INDEX {1}'", ".", "format", "(", "wrap", "(", "table", ")", ",", "column", ")", ")", "self", ".", "_printer", "(", "'\\tDropped ind...
Drop an index from a table.
[ "Drop", "an", "index", "from", "a", "table", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/schema.py#L67-L70
mrstephenneal/mysql-toolkit
mysql/toolkit/components/structure/schema.py
Schema.add_comment
def add_comment(self, table, column, comment): """Add a comment to an existing column in a table.""" col_def = self.get_column_definition(table, column) query = "ALTER TABLE {0} MODIFY COLUMN {1} {2} COMMENT '{3}'".format(table, column, col_def, comment) self.execute(query) self._printer('\tAdded comment to column {0}'.format(column)) return True
python
def add_comment(self, table, column, comment): """Add a comment to an existing column in a table.""" col_def = self.get_column_definition(table, column) query = "ALTER TABLE {0} MODIFY COLUMN {1} {2} COMMENT '{3}'".format(table, column, col_def, comment) self.execute(query) self._printer('\tAdded comment to column {0}'.format(column)) return True
[ "def", "add_comment", "(", "self", ",", "table", ",", "column", ",", "comment", ")", ":", "col_def", "=", "self", ".", "get_column_definition", "(", "table", ",", "column", ")", "query", "=", "\"ALTER TABLE {0} MODIFY COLUMN {1} {2} COMMENT '{3}'\"", ".", "format"...
Add a comment to an existing column in a table.
[ "Add", "a", "comment", "to", "an", "existing", "column", "in", "a", "table", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/schema.py#L72-L78
mrstephenneal/mysql-toolkit
mysql/toolkit/components/structure/schema.py
Schema.add_auto_increment
def add_auto_increment(self, table, name): """Modify an existing column.""" # Get current column definition and add auto_incrementing definition = self.get_column_definition(table, name) + ' AUTO_INCREMENT' # Concatenate and execute modify statement self.execute("ALTER TABLE {0} MODIFY {1}".format(table, definition)) self._printer('\tAdded AUTO_INCREMENT to column {0}'.format(name)) return True
python
def add_auto_increment(self, table, name): """Modify an existing column.""" # Get current column definition and add auto_incrementing definition = self.get_column_definition(table, name) + ' AUTO_INCREMENT' # Concatenate and execute modify statement self.execute("ALTER TABLE {0} MODIFY {1}".format(table, definition)) self._printer('\tAdded AUTO_INCREMENT to column {0}'.format(name)) return True
[ "def", "add_auto_increment", "(", "self", ",", "table", ",", "name", ")", ":", "# Get current column definition and add auto_incrementing", "definition", "=", "self", ".", "get_column_definition", "(", "table", ",", "name", ")", "+", "' AUTO_INCREMENT'", "# Concatenate ...
Modify an existing column.
[ "Modify", "an", "existing", "column", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/schema.py#L80-L88
mrstephenneal/mysql-toolkit
mysql/toolkit/components/structure/schema.py
Schema.modify_column
def modify_column(self, table, name, new_name=None, data_type=None, null=None, default=None): """Modify an existing column.""" existing_def = self.get_schema_dict(table)[name] # Set column name new_name = new_name if new_name is not None else name # Set data type if not data_type: data_type = existing_def['Type'] # Set NULL if null is None: null_ = 'NULL' if existing_def['Null'].lower() == 'yes' else 'NOT NULL' else: null_ = 'NULL' if null else 'NOT NULL' default = 'DEFAULT {0}'.format(default if default else null_) query = 'ALTER TABLE {0} CHANGE {1} {2} {3} {4} {5}'.format(wrap(table), wrap(name), wrap(new_name), data_type, null_, default) self.execute(query) self._printer('\tModified column {0}'.format(name))
python
def modify_column(self, table, name, new_name=None, data_type=None, null=None, default=None): """Modify an existing column.""" existing_def = self.get_schema_dict(table)[name] # Set column name new_name = new_name if new_name is not None else name # Set data type if not data_type: data_type = existing_def['Type'] # Set NULL if null is None: null_ = 'NULL' if existing_def['Null'].lower() == 'yes' else 'NOT NULL' else: null_ = 'NULL' if null else 'NOT NULL' default = 'DEFAULT {0}'.format(default if default else null_) query = 'ALTER TABLE {0} CHANGE {1} {2} {3} {4} {5}'.format(wrap(table), wrap(name), wrap(new_name), data_type, null_, default) self.execute(query) self._printer('\tModified column {0}'.format(name))
[ "def", "modify_column", "(", "self", ",", "table", ",", "name", ",", "new_name", "=", "None", ",", "data_type", "=", "None", ",", "null", "=", "None", ",", "default", "=", "None", ")", ":", "existing_def", "=", "self", ".", "get_schema_dict", "(", "tab...
Modify an existing column.
[ "Modify", "an", "existing", "column", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/schema.py#L90-L112
PGower/PyCanvas
pycanvas/apis/modules.py
ModulesAPI.list_modules
def list_modules(self, course_id, include=None, search_term=None, student_id=None): """ List modules. List the modules in a course """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - include """- "items": Return module items inline if possible. This parameter suggests that Canvas return module items directly in the Module object JSON, to avoid having to make separate API requests for each module when enumerating modules and items. Canvas is free to omit 'items' for any particular module if it deems them too numerous to return inline. Callers must be prepared to use the {api:ContextModuleItemsApiController#index List Module Items API} if items are not returned. - "content_details": Requires include['items']. Returns additional details with module items specific to their associated content items. Includes standard lock information for each item.""" if include is not None: self._validate_enum(include, ["items", "content_details"]) params["include"] = include # OPTIONAL - search_term """The partial name of the modules (and module items, if include['items'] is specified) to match and return.""" if search_term is not None: params["search_term"] = search_term # OPTIONAL - student_id """Returns module completion information for the student with this id.""" if student_id is not None: params["student_id"] = student_id self.logger.debug("GET /api/v1/courses/{course_id}/modules with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/modules".format(**path), data=data, params=params, all_pages=True)
python
def list_modules(self, course_id, include=None, search_term=None, student_id=None): """ List modules. List the modules in a course """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - include """- "items": Return module items inline if possible. This parameter suggests that Canvas return module items directly in the Module object JSON, to avoid having to make separate API requests for each module when enumerating modules and items. Canvas is free to omit 'items' for any particular module if it deems them too numerous to return inline. Callers must be prepared to use the {api:ContextModuleItemsApiController#index List Module Items API} if items are not returned. - "content_details": Requires include['items']. Returns additional details with module items specific to their associated content items. Includes standard lock information for each item.""" if include is not None: self._validate_enum(include, ["items", "content_details"]) params["include"] = include # OPTIONAL - search_term """The partial name of the modules (and module items, if include['items'] is specified) to match and return.""" if search_term is not None: params["search_term"] = search_term # OPTIONAL - student_id """Returns module completion information for the student with this id.""" if student_id is not None: params["student_id"] = student_id self.logger.debug("GET /api/v1/courses/{course_id}/modules with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/modules".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_modules", "(", "self", ",", "course_id", ",", "include", "=", "None", ",", "search_term", "=", "None", ",", "student_id", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - co...
List modules. List the modules in a course
[ "List", "modules", ".", "List", "the", "modules", "in", "a", "course" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/modules.py#L19-L61
PGower/PyCanvas
pycanvas/apis/modules.py
ModulesAPI.create_module
def create_module(self, course_id, module_name, module_position=None, module_prerequisite_module_ids=None, module_publish_final_grade=None, module_require_sequential_progress=None, module_unlock_at=None): """ Create a module. Create and return a new module """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - module[name] """The name of the module""" data["module[name]"] = module_name # OPTIONAL - module[unlock_at] """The date the module will unlock""" if module_unlock_at is not None: data["module[unlock_at]"] = module_unlock_at # OPTIONAL - module[position] """The position of this module in the course (1-based)""" if module_position is not None: data["module[position]"] = module_position # OPTIONAL - module[require_sequential_progress] """Whether module items must be unlocked in order""" if module_require_sequential_progress is not None: data["module[require_sequential_progress]"] = module_require_sequential_progress # OPTIONAL - module[prerequisite_module_ids] """IDs of Modules that must be completed before this one is unlocked. Prerequisite modules must precede this module (i.e. have a lower position value), otherwise they will be ignored""" if module_prerequisite_module_ids is not None: data["module[prerequisite_module_ids]"] = module_prerequisite_module_ids # OPTIONAL - module[publish_final_grade] """Whether to publish the student's final grade for the course upon completion of this module.""" if module_publish_final_grade is not None: data["module[publish_final_grade]"] = module_publish_final_grade self.logger.debug("POST /api/v1/courses/{course_id}/modules with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/modules".format(**path), data=data, params=params, single_item=True)
python
def create_module(self, course_id, module_name, module_position=None, module_prerequisite_module_ids=None, module_publish_final_grade=None, module_require_sequential_progress=None, module_unlock_at=None): """ Create a module. Create and return a new module """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - module[name] """The name of the module""" data["module[name]"] = module_name # OPTIONAL - module[unlock_at] """The date the module will unlock""" if module_unlock_at is not None: data["module[unlock_at]"] = module_unlock_at # OPTIONAL - module[position] """The position of this module in the course (1-based)""" if module_position is not None: data["module[position]"] = module_position # OPTIONAL - module[require_sequential_progress] """Whether module items must be unlocked in order""" if module_require_sequential_progress is not None: data["module[require_sequential_progress]"] = module_require_sequential_progress # OPTIONAL - module[prerequisite_module_ids] """IDs of Modules that must be completed before this one is unlocked. Prerequisite modules must precede this module (i.e. have a lower position value), otherwise they will be ignored""" if module_prerequisite_module_ids is not None: data["module[prerequisite_module_ids]"] = module_prerequisite_module_ids # OPTIONAL - module[publish_final_grade] """Whether to publish the student's final grade for the course upon completion of this module.""" if module_publish_final_grade is not None: data["module[publish_final_grade]"] = module_publish_final_grade self.logger.debug("POST /api/v1/courses/{course_id}/modules with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/modules".format(**path), data=data, params=params, single_item=True)
[ "def", "create_module", "(", "self", ",", "course_id", ",", "module_name", ",", "module_position", "=", "None", ",", "module_prerequisite_module_ids", "=", "None", ",", "module_publish_final_grade", "=", "None", ",", "module_require_sequential_progress", "=", "None", ...
Create a module. Create and return a new module
[ "Create", "a", "module", ".", "Create", "and", "return", "a", "new", "module" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/modules.py#L105-L152
PGower/PyCanvas
pycanvas/apis/modules.py
ModulesAPI.create_module_item
def create_module_item(self, course_id, module_id, module_item_type, module_item_content_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_new_tab=None, module_item_page_url=None, module_item_position=None, module_item_title=None): """ Create a module item. Create and return a new module item """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - module_id """ID""" path["module_id"] = module_id # OPTIONAL - module_item[title] """The name of the module item and associated content""" if module_item_title is not None: data["module_item[title]"] = module_item_title # REQUIRED - module_item[type] """The type of content linked to the item""" self._validate_enum(module_item_type, ["File", "Page", "Discussion", "Assignment", "Quiz", "SubHeader", "ExternalUrl", "ExternalTool"]) data["module_item[type]"] = module_item_type # REQUIRED - module_item[content_id] """The id of the content to link to the module item. Required, except for 'ExternalUrl', 'Page', and 'SubHeader' types.""" data["module_item[content_id]"] = module_item_content_id # OPTIONAL - module_item[position] """The position of this item in the module (1-based).""" if module_item_position is not None: data["module_item[position]"] = module_item_position # OPTIONAL - module_item[indent] """0-based indent level; module items may be indented to show a hierarchy""" if module_item_indent is not None: data["module_item[indent]"] = module_item_indent # OPTIONAL - module_item[page_url] """Suffix for the linked wiki page (e.g. 'front-page'). Required for 'Page' type.""" if module_item_page_url is not None: data["module_item[page_url]"] = module_item_page_url # OPTIONAL - module_item[external_url] """External url that the item points to. [Required for 'ExternalUrl' and 'ExternalTool' types.""" if module_item_external_url is not None: data["module_item[external_url]"] = module_item_external_url # OPTIONAL - module_item[new_tab] """Whether the external tool opens in a new tab. Only applies to 'ExternalTool' type.""" if module_item_new_tab is not None: data["module_item[new_tab]"] = module_item_new_tab # OPTIONAL - module_item[completion_requirement][type] """Completion requirement for this module item. "must_view": Applies to all item types "must_contribute": Only applies to "Assignment", "Discussion", and "Page" types "must_submit", "min_score": Only apply to "Assignment" and "Quiz" types Inapplicable types will be ignored""" if module_item_completion_requirement_type is not None: self._validate_enum(module_item_completion_requirement_type, ["must_view", "must_contribute", "must_submit"]) data["module_item[completion_requirement][type]"] = module_item_completion_requirement_type # OPTIONAL - module_item[completion_requirement][min_score] """Minimum score required to complete. Required for completion_requirement type 'min_score'.""" if module_item_completion_requirement_min_score is not None: data["module_item[completion_requirement][min_score]"] = module_item_completion_requirement_min_score self.logger.debug("POST /api/v1/courses/{course_id}/modules/{module_id}/items with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/modules/{module_id}/items".format(**path), data=data, params=params, single_item=True)
python
def create_module_item(self, course_id, module_id, module_item_type, module_item_content_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_new_tab=None, module_item_page_url=None, module_item_position=None, module_item_title=None): """ Create a module item. Create and return a new module item """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - module_id """ID""" path["module_id"] = module_id # OPTIONAL - module_item[title] """The name of the module item and associated content""" if module_item_title is not None: data["module_item[title]"] = module_item_title # REQUIRED - module_item[type] """The type of content linked to the item""" self._validate_enum(module_item_type, ["File", "Page", "Discussion", "Assignment", "Quiz", "SubHeader", "ExternalUrl", "ExternalTool"]) data["module_item[type]"] = module_item_type # REQUIRED - module_item[content_id] """The id of the content to link to the module item. Required, except for 'ExternalUrl', 'Page', and 'SubHeader' types.""" data["module_item[content_id]"] = module_item_content_id # OPTIONAL - module_item[position] """The position of this item in the module (1-based).""" if module_item_position is not None: data["module_item[position]"] = module_item_position # OPTIONAL - module_item[indent] """0-based indent level; module items may be indented to show a hierarchy""" if module_item_indent is not None: data["module_item[indent]"] = module_item_indent # OPTIONAL - module_item[page_url] """Suffix for the linked wiki page (e.g. 'front-page'). Required for 'Page' type.""" if module_item_page_url is not None: data["module_item[page_url]"] = module_item_page_url # OPTIONAL - module_item[external_url] """External url that the item points to. [Required for 'ExternalUrl' and 'ExternalTool' types.""" if module_item_external_url is not None: data["module_item[external_url]"] = module_item_external_url # OPTIONAL - module_item[new_tab] """Whether the external tool opens in a new tab. Only applies to 'ExternalTool' type.""" if module_item_new_tab is not None: data["module_item[new_tab]"] = module_item_new_tab # OPTIONAL - module_item[completion_requirement][type] """Completion requirement for this module item. "must_view": Applies to all item types "must_contribute": Only applies to "Assignment", "Discussion", and "Page" types "must_submit", "min_score": Only apply to "Assignment" and "Quiz" types Inapplicable types will be ignored""" if module_item_completion_requirement_type is not None: self._validate_enum(module_item_completion_requirement_type, ["must_view", "must_contribute", "must_submit"]) data["module_item[completion_requirement][type]"] = module_item_completion_requirement_type # OPTIONAL - module_item[completion_requirement][min_score] """Minimum score required to complete. Required for completion_requirement type 'min_score'.""" if module_item_completion_requirement_min_score is not None: data["module_item[completion_requirement][min_score]"] = module_item_completion_requirement_min_score self.logger.debug("POST /api/v1/courses/{course_id}/modules/{module_id}/items with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/modules/{module_id}/items".format(**path), data=data, params=params, single_item=True)
[ "def", "create_module_item", "(", "self", ",", "course_id", ",", "module_id", ",", "module_item_type", ",", "module_item_content_id", ",", "module_item_completion_requirement_min_score", "=", "None", ",", "module_item_completion_requirement_type", "=", "None", ",", "module_...
Create a module item. Create and return a new module item
[ "Create", "a", "module", "item", ".", "Create", "and", "return", "a", "new", "module", "item" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/modules.py#L338-L416
PGower/PyCanvas
pycanvas/apis/modules.py
ModulesAPI.update_module_item
def update_module_item(self, id, course_id, module_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_module_id=None, module_item_new_tab=None, module_item_position=None, module_item_published=None, module_item_title=None): """ Update a module item. Update and return an existing module item """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - module_id """ID""" path["module_id"] = module_id # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - module_item[title] """The name of the module item""" if module_item_title is not None: data["module_item[title]"] = module_item_title # OPTIONAL - module_item[position] """The position of this item in the module (1-based)""" if module_item_position is not None: data["module_item[position]"] = module_item_position # OPTIONAL - module_item[indent] """0-based indent level; module items may be indented to show a hierarchy""" if module_item_indent is not None: data["module_item[indent]"] = module_item_indent # OPTIONAL - module_item[external_url] """External url that the item points to. Only applies to 'ExternalUrl' type.""" if module_item_external_url is not None: data["module_item[external_url]"] = module_item_external_url # OPTIONAL - module_item[new_tab] """Whether the external tool opens in a new tab. Only applies to 'ExternalTool' type.""" if module_item_new_tab is not None: data["module_item[new_tab]"] = module_item_new_tab # OPTIONAL - module_item[completion_requirement][type] """Completion requirement for this module item. "must_view": Applies to all item types "must_contribute": Only applies to "Assignment", "Discussion", and "Page" types "must_submit", "min_score": Only apply to "Assignment" and "Quiz" types Inapplicable types will be ignored""" if module_item_completion_requirement_type is not None: self._validate_enum(module_item_completion_requirement_type, ["must_view", "must_contribute", "must_submit"]) data["module_item[completion_requirement][type]"] = module_item_completion_requirement_type # OPTIONAL - module_item[completion_requirement][min_score] """Minimum score required to complete, Required for completion_requirement type 'min_score'.""" if module_item_completion_requirement_min_score is not None: data["module_item[completion_requirement][min_score]"] = module_item_completion_requirement_min_score # OPTIONAL - module_item[published] """Whether the module item is published and visible to students.""" if module_item_published is not None: data["module_item[published]"] = module_item_published # OPTIONAL - module_item[module_id] """Move this item to another module by specifying the target module id here. The target module must be in the same course.""" if module_item_module_id is not None: data["module_item[module_id]"] = module_item_module_id self.logger.debug("PUT /api/v1/courses/{course_id}/modules/{module_id}/items/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/courses/{course_id}/modules/{module_id}/items/{id}".format(**path), data=data, params=params, single_item=True)
python
def update_module_item(self, id, course_id, module_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_module_id=None, module_item_new_tab=None, module_item_position=None, module_item_published=None, module_item_title=None): """ Update a module item. Update and return an existing module item """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - module_id """ID""" path["module_id"] = module_id # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - module_item[title] """The name of the module item""" if module_item_title is not None: data["module_item[title]"] = module_item_title # OPTIONAL - module_item[position] """The position of this item in the module (1-based)""" if module_item_position is not None: data["module_item[position]"] = module_item_position # OPTIONAL - module_item[indent] """0-based indent level; module items may be indented to show a hierarchy""" if module_item_indent is not None: data["module_item[indent]"] = module_item_indent # OPTIONAL - module_item[external_url] """External url that the item points to. Only applies to 'ExternalUrl' type.""" if module_item_external_url is not None: data["module_item[external_url]"] = module_item_external_url # OPTIONAL - module_item[new_tab] """Whether the external tool opens in a new tab. Only applies to 'ExternalTool' type.""" if module_item_new_tab is not None: data["module_item[new_tab]"] = module_item_new_tab # OPTIONAL - module_item[completion_requirement][type] """Completion requirement for this module item. "must_view": Applies to all item types "must_contribute": Only applies to "Assignment", "Discussion", and "Page" types "must_submit", "min_score": Only apply to "Assignment" and "Quiz" types Inapplicable types will be ignored""" if module_item_completion_requirement_type is not None: self._validate_enum(module_item_completion_requirement_type, ["must_view", "must_contribute", "must_submit"]) data["module_item[completion_requirement][type]"] = module_item_completion_requirement_type # OPTIONAL - module_item[completion_requirement][min_score] """Minimum score required to complete, Required for completion_requirement type 'min_score'.""" if module_item_completion_requirement_min_score is not None: data["module_item[completion_requirement][min_score]"] = module_item_completion_requirement_min_score # OPTIONAL - module_item[published] """Whether the module item is published and visible to students.""" if module_item_published is not None: data["module_item[published]"] = module_item_published # OPTIONAL - module_item[module_id] """Move this item to another module by specifying the target module id here. The target module must be in the same course.""" if module_item_module_id is not None: data["module_item[module_id]"] = module_item_module_id self.logger.debug("PUT /api/v1/courses/{course_id}/modules/{module_id}/items/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/courses/{course_id}/modules/{module_id}/items/{id}".format(**path), data=data, params=params, single_item=True)
[ "def", "update_module_item", "(", "self", ",", "id", ",", "course_id", ",", "module_id", ",", "module_item_completion_requirement_min_score", "=", "None", ",", "module_item_completion_requirement_type", "=", "None", ",", "module_item_external_url", "=", "None", ",", "mo...
Update a module item. Update and return an existing module item
[ "Update", "a", "module", "item", ".", "Update", "and", "return", "an", "existing", "module", "item" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/modules.py#L418-L494
PGower/PyCanvas
pycanvas/apis/modules.py
ModulesAPI.select_mastery_path
def select_mastery_path(self, id, course_id, module_id, assignment_set_id=None, student_id=None): """ Select a mastery path. Select a mastery path when module item includes several possible paths. Requires Mastery Paths feature to be enabled. Returns a compound document with the assignments included in the given path and any module items related to those assignments """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - module_id """ID""" path["module_id"] = module_id # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - assignment_set_id """Assignment set chosen, as specified in the mastery_paths portion of the context module item response""" if assignment_set_id is not None: data["assignment_set_id"] = assignment_set_id # OPTIONAL - student_id """Which student the selection applies to. If not specified, current user is implied.""" if student_id is not None: data["student_id"] = student_id self.logger.debug("POST /api/v1/courses/{course_id}/modules/{module_id}/items/{id}/select_mastery_path with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/modules/{module_id}/items/{id}/select_mastery_path".format(**path), data=data, params=params, no_data=True)
python
def select_mastery_path(self, id, course_id, module_id, assignment_set_id=None, student_id=None): """ Select a mastery path. Select a mastery path when module item includes several possible paths. Requires Mastery Paths feature to be enabled. Returns a compound document with the assignments included in the given path and any module items related to those assignments """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - module_id """ID""" path["module_id"] = module_id # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - assignment_set_id """Assignment set chosen, as specified in the mastery_paths portion of the context module item response""" if assignment_set_id is not None: data["assignment_set_id"] = assignment_set_id # OPTIONAL - student_id """Which student the selection applies to. If not specified, current user is implied.""" if student_id is not None: data["student_id"] = student_id self.logger.debug("POST /api/v1/courses/{course_id}/modules/{module_id}/items/{id}/select_mastery_path with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/modules/{module_id}/items/{id}/select_mastery_path".format(**path), data=data, params=params, no_data=True)
[ "def", "select_mastery_path", "(", "self", ",", "id", ",", "course_id", ",", "module_id", ",", "assignment_set_id", "=", "None", ",", "student_id", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRE...
Select a mastery path. Select a mastery path when module item includes several possible paths. Requires Mastery Paths feature to be enabled. Returns a compound document with the assignments included in the given path and any module items related to those assignments
[ "Select", "a", "mastery", "path", ".", "Select", "a", "mastery", "path", "when", "module", "item", "includes", "several", "possible", "paths", ".", "Requires", "Mastery", "Paths", "feature", "to", "be", "enabled", ".", "Returns", "a", "compound", "document", ...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/modules.py#L496-L534
PGower/PyCanvas
pycanvas/apis/modules.py
ModulesAPI.get_module_item_sequence
def get_module_item_sequence(self, course_id, asset_id=None, asset_type=None): """ Get module item sequence. Given an asset in a course, find the ModuleItem it belongs to, and also the previous and next Module Items in the course sequence. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - asset_type """The type of asset to find module sequence information for. Use the ModuleItem if it is known (e.g., the user navigated from a module item), since this will avoid ambiguity if the asset appears more than once in the module sequence.""" if asset_type is not None: self._validate_enum(asset_type, ["ModuleItem", "File", "Page", "Discussion", "Assignment", "Quiz", "ExternalTool"]) params["asset_type"] = asset_type # OPTIONAL - asset_id """The id of the asset (or the url in the case of a Page)""" if asset_id is not None: params["asset_id"] = asset_id self.logger.debug("GET /api/v1/courses/{course_id}/module_item_sequence with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/module_item_sequence".format(**path), data=data, params=params, single_item=True)
python
def get_module_item_sequence(self, course_id, asset_id=None, asset_type=None): """ Get module item sequence. Given an asset in a course, find the ModuleItem it belongs to, and also the previous and next Module Items in the course sequence. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - asset_type """The type of asset to find module sequence information for. Use the ModuleItem if it is known (e.g., the user navigated from a module item), since this will avoid ambiguity if the asset appears more than once in the module sequence.""" if asset_type is not None: self._validate_enum(asset_type, ["ModuleItem", "File", "Page", "Discussion", "Assignment", "Quiz", "ExternalTool"]) params["asset_type"] = asset_type # OPTIONAL - asset_id """The id of the asset (or the url in the case of a Page)""" if asset_id is not None: params["asset_id"] = asset_id self.logger.debug("GET /api/v1/courses/{course_id}/module_item_sequence with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/module_item_sequence".format(**path), data=data, params=params, single_item=True)
[ "def", "get_module_item_sequence", "(", "self", ",", "course_id", ",", "asset_id", "=", "None", ",", "asset_type", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\...
Get module item sequence. Given an asset in a course, find the ModuleItem it belongs to, and also the previous and next Module Items in the course sequence.
[ "Get", "module", "item", "sequence", ".", "Given", "an", "asset", "in", "a", "course", "find", "the", "ModuleItem", "it", "belongs", "to", "and", "also", "the", "previous", "and", "next", "Module", "Items", "in", "the", "course", "sequence", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/modules.py#L587-L616
20c/vodka
vodka/data/data_types.py
instantiate_from_config
def instantiate_from_config(cfg): """Instantiate data types from config""" for h in cfg: if h.get("type") in data_types: raise KeyError("Data type '%s' already exists" % h) data_types[h.get("type")] = DataType(h)
python
def instantiate_from_config(cfg): """Instantiate data types from config""" for h in cfg: if h.get("type") in data_types: raise KeyError("Data type '%s' already exists" % h) data_types[h.get("type")] = DataType(h)
[ "def", "instantiate_from_config", "(", "cfg", ")", ":", "for", "h", "in", "cfg", ":", "if", "h", ".", "get", "(", "\"type\"", ")", "in", "data_types", ":", "raise", "KeyError", "(", "\"Data type '%s' already exists\"", "%", "h", ")", "data_types", "[", "h"...
Instantiate data types from config
[ "Instantiate", "data", "types", "from", "config" ]
train
https://github.com/20c/vodka/blob/9615148ac6560298453704bb5246b35b66b3339c/vodka/data/data_types.py#L7-L12
PGower/PyCanvas
pycanvas/apis/base.py
BaseCanvasAPI.extract_data_from_response
def extract_data_from_response(self, response, data_key=None): """Given a response and an optional data_key should return a dictionary of data returned as part of the response.""" response_json_data = response.json() # Seems to be two types of response, a dict with keys and then lists of data or a flat list data with no key. if type(response_json_data) == list: # Return the data return response_json_data elif type(response_json_data) == dict: if data_key is None: return response_json_data else: return response_json_data[data_key] else: raise CanvasAPIError(response)
python
def extract_data_from_response(self, response, data_key=None): """Given a response and an optional data_key should return a dictionary of data returned as part of the response.""" response_json_data = response.json() # Seems to be two types of response, a dict with keys and then lists of data or a flat list data with no key. if type(response_json_data) == list: # Return the data return response_json_data elif type(response_json_data) == dict: if data_key is None: return response_json_data else: return response_json_data[data_key] else: raise CanvasAPIError(response)
[ "def", "extract_data_from_response", "(", "self", ",", "response", ",", "data_key", "=", "None", ")", ":", "response_json_data", "=", "response", ".", "json", "(", ")", "# Seems to be two types of response, a dict with keys and then lists of data or a flat list data with no key...
Given a response and an optional data_key should return a dictionary of data returned as part of the response.
[ "Given", "a", "response", "and", "an", "optional", "data_key", "should", "return", "a", "dictionary", "of", "data", "returned", "as", "part", "of", "the", "response", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/base.py#L24-L37
PGower/PyCanvas
pycanvas/apis/base.py
BaseCanvasAPI.extract_pagination_links
def extract_pagination_links(self, response): '''Given a wrapped_response from a Canvas API endpoint, extract the pagination links from the response headers''' try: link_header = response.headers['Link'] except KeyError: logger.warn('Unable to find the Link header. Unable to continue with pagination.') return None split_header = link_header.split(',') exploded_split_header = [i.split(';') for i in split_header] pagination_links = {} for h in exploded_split_header: link = h[0] rel = h[1] # Check that the link format is what we expect if link.startswith('<') and link.endswith('>'): link = link[1:-1] else: continue # Extract the rel argument m = self.rel_matcher.match(rel) try: rel = m.groups()[0] except AttributeError: # Match returned None, just skip. continue except IndexError: # Matched but no groups returned continue pagination_links[rel] = link return pagination_links
python
def extract_pagination_links(self, response): '''Given a wrapped_response from a Canvas API endpoint, extract the pagination links from the response headers''' try: link_header = response.headers['Link'] except KeyError: logger.warn('Unable to find the Link header. Unable to continue with pagination.') return None split_header = link_header.split(',') exploded_split_header = [i.split(';') for i in split_header] pagination_links = {} for h in exploded_split_header: link = h[0] rel = h[1] # Check that the link format is what we expect if link.startswith('<') and link.endswith('>'): link = link[1:-1] else: continue # Extract the rel argument m = self.rel_matcher.match(rel) try: rel = m.groups()[0] except AttributeError: # Match returned None, just skip. continue except IndexError: # Matched but no groups returned continue pagination_links[rel] = link return pagination_links
[ "def", "extract_pagination_links", "(", "self", ",", "response", ")", ":", "try", ":", "link_header", "=", "response", ".", "headers", "[", "'Link'", "]", "except", "KeyError", ":", "logger", ".", "warn", "(", "'Unable to find the Link header. Unable to continue wit...
Given a wrapped_response from a Canvas API endpoint, extract the pagination links from the response headers
[ "Given", "a", "wrapped_response", "from", "a", "Canvas", "API", "endpoint", "extract", "the", "pagination", "links", "from", "the", "response", "headers" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/base.py#L39-L72
PGower/PyCanvas
pycanvas/apis/base.py
BaseCanvasAPI.generic_request
def generic_request(self, method, uri, all_pages=False, data_key=None, no_data=False, do_not_process=False, force_urlencode_data=False, data=None, params=None, files=None, single_item=False): """Generic Canvas Request Method.""" if not uri.startswith('http'): uri = self.uri_for(uri) if force_urlencode_data is True: uri += '?' + urllib.urlencode(data) assert method in ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'] if method == 'GET': response = self.session.get(uri, params=params) elif method == 'POST': response = self.session.post(uri, data=data, files=files) elif method == 'PUT': response = self.session.put(uri, data=data) elif method == 'DELETE': response = self.session.delete(uri, params=params) elif method == 'HEAD': response = self.session.head(uri, params=params) elif method == 'OPTIONS': response = self.session.options(uri, params=params) response.raise_for_status() if do_not_process is True: return response if no_data: return response.status_code if all_pages: return self.depaginate(response, data_key) if single_item: r = response.json() if data_key: return r[data_key] else: return r return response.json()
python
def generic_request(self, method, uri, all_pages=False, data_key=None, no_data=False, do_not_process=False, force_urlencode_data=False, data=None, params=None, files=None, single_item=False): """Generic Canvas Request Method.""" if not uri.startswith('http'): uri = self.uri_for(uri) if force_urlencode_data is True: uri += '?' + urllib.urlencode(data) assert method in ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'] if method == 'GET': response = self.session.get(uri, params=params) elif method == 'POST': response = self.session.post(uri, data=data, files=files) elif method == 'PUT': response = self.session.put(uri, data=data) elif method == 'DELETE': response = self.session.delete(uri, params=params) elif method == 'HEAD': response = self.session.head(uri, params=params) elif method == 'OPTIONS': response = self.session.options(uri, params=params) response.raise_for_status() if do_not_process is True: return response if no_data: return response.status_code if all_pages: return self.depaginate(response, data_key) if single_item: r = response.json() if data_key: return r[data_key] else: return r return response.json()
[ "def", "generic_request", "(", "self", ",", "method", ",", "uri", ",", "all_pages", "=", "False", ",", "data_key", "=", "None", ",", "no_data", "=", "False", ",", "do_not_process", "=", "False", ",", "force_urlencode_data", "=", "False", ",", "data", "=", ...
Generic Canvas Request Method.
[ "Generic", "Canvas", "Request", "Method", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/base.py#L102-L152
PGower/PyCanvas
pycanvas/apis/base.py
BaseCanvasAPI._validate_iso8601_string
def _validate_iso8601_string(self, value): """Return the value or raise a ValueError if it is not a string in ISO8601 format.""" ISO8601_REGEX = r'(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})([+-](\d{2})\:(\d{2})|Z)' if re.match(ISO8601_REGEX, value): return value else: raise ValueError('{} must be in ISO8601 format.'.format(value))
python
def _validate_iso8601_string(self, value): """Return the value or raise a ValueError if it is not a string in ISO8601 format.""" ISO8601_REGEX = r'(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})([+-](\d{2})\:(\d{2})|Z)' if re.match(ISO8601_REGEX, value): return value else: raise ValueError('{} must be in ISO8601 format.'.format(value))
[ "def", "_validate_iso8601_string", "(", "self", ",", "value", ")", ":", "ISO8601_REGEX", "=", "r'(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2})\\:(\\d{2})\\:(\\d{2})([+-](\\d{2})\\:(\\d{2})|Z)'", "if", "re", ".", "match", "(", "ISO8601_REGEX", ",", "value", ")", ":", "return", "valu...
Return the value or raise a ValueError if it is not a string in ISO8601 format.
[ "Return", "the", "value", "or", "raise", "a", "ValueError", "if", "it", "is", "not", "a", "string", "in", "ISO8601", "format", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/base.py#L164-L170
BDNYC/astrodbkit
astrodbkit/astrodb.py
create_database
def create_database(dbpath, schema='', overwrite=True): """ Create a new database at the given dbpath Parameters ---------- dbpath: str The full path for the new database, including the filename and .db file extension. schema: str The path to the .sql schema for the database overwrite: bool Overwrite dbpath if it already exists """ if dbpath.endswith('.db'): if os.path.isfile(dbpath) and overwrite: os.system('rm {}'.format(dbpath)) # Load the schema if given if schema: os.system("cat {} | sqlite3 {}".format(schema,dbpath)) # Otherwise just make an empty SOURCES table else: sources_table = "CREATE TABLE sources (id INTEGER PRIMARY KEY, ra REAL, dec REAL, designation TEXT, " \ "publication_id INTEGER, shortname TEXT, names TEXT, comments TEXT)" os.system("sqlite3 {} '{}'".format(dbpath, sources_table)) if os.path.isfile(dbpath): print( "\nDatabase created! To load, run\n\ndb = astrodb.Database('{}')" "\n\nThen run db.modify_table() method to create tables.".format(dbpath)) else: print("Please provide a path and file name with a .db file extension, e.g. /Users/<username>/Desktop/test.db")
python
def create_database(dbpath, schema='', overwrite=True): """ Create a new database at the given dbpath Parameters ---------- dbpath: str The full path for the new database, including the filename and .db file extension. schema: str The path to the .sql schema for the database overwrite: bool Overwrite dbpath if it already exists """ if dbpath.endswith('.db'): if os.path.isfile(dbpath) and overwrite: os.system('rm {}'.format(dbpath)) # Load the schema if given if schema: os.system("cat {} | sqlite3 {}".format(schema,dbpath)) # Otherwise just make an empty SOURCES table else: sources_table = "CREATE TABLE sources (id INTEGER PRIMARY KEY, ra REAL, dec REAL, designation TEXT, " \ "publication_id INTEGER, shortname TEXT, names TEXT, comments TEXT)" os.system("sqlite3 {} '{}'".format(dbpath, sources_table)) if os.path.isfile(dbpath): print( "\nDatabase created! To load, run\n\ndb = astrodb.Database('{}')" "\n\nThen run db.modify_table() method to create tables.".format(dbpath)) else: print("Please provide a path and file name with a .db file extension, e.g. /Users/<username>/Desktop/test.db")
[ "def", "create_database", "(", "dbpath", ",", "schema", "=", "''", ",", "overwrite", "=", "True", ")", ":", "if", "dbpath", ".", "endswith", "(", "'.db'", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "dbpath", ")", "and", "overwrite", ":", ...
Create a new database at the given dbpath Parameters ---------- dbpath: str The full path for the new database, including the filename and .db file extension. schema: str The path to the .sql schema for the database overwrite: bool Overwrite dbpath if it already exists
[ "Create", "a", "new", "database", "at", "the", "given", "dbpath" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L36-L69
BDNYC/astrodbkit
astrodbkit/astrodb.py
adapt_array
def adapt_array(arr): """ Adapts a Numpy array into an ARRAY string to put into the database. Parameters ---------- arr: array The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file. Returns ------- ARRAY The adapted array object """ out = io.BytesIO() np.save(out, arr), out.seek(0) return buffer(out.read())
python
def adapt_array(arr): """ Adapts a Numpy array into an ARRAY string to put into the database. Parameters ---------- arr: array The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file. Returns ------- ARRAY The adapted array object """ out = io.BytesIO() np.save(out, arr), out.seek(0) return buffer(out.read())
[ "def", "adapt_array", "(", "arr", ")", ":", "out", "=", "io", ".", "BytesIO", "(", ")", "np", ".", "save", "(", "out", ",", "arr", ")", ",", "out", ".", "seek", "(", "0", ")", "return", "buffer", "(", "out", ".", "read", "(", ")", ")" ]
Adapts a Numpy array into an ARRAY string to put into the database. Parameters ---------- arr: array The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file. Returns ------- ARRAY The adapted array object
[ "Adapts", "a", "Numpy", "array", "into", "an", "ARRAY", "string", "to", "put", "into", "the", "database", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L2124-L2141
BDNYC/astrodbkit
astrodbkit/astrodb.py
ang_sep
def ang_sep(row, ra1, dec1): """ Calculate angular separation between two coordinates Uses Vicenty Formula (http://en.wikipedia.org/wiki/Great-circle_distance) and adapts from astropy's SkyCoord Written to be used within the Database.search() method Parameters ---------- row: dict, pandas Row Coordinate structure containing ra and dec keys in decimal degrees ra1: float RA to compare with, in decimal degrees dec1: float Dec to compare with, in decimal degrees Returns ------- Angular distance, in degrees, between the coordinates """ factor = math.pi / 180 sdlon = math.sin((row['ra'] - ra1) * factor) # RA is longitude cdlon = math.cos((row['ra'] - ra1) * factor) slat1 = math.sin(dec1 * factor) # Dec is latitude slat2 = math.sin(row['dec'] * factor) clat1 = math.cos(dec1 * factor) clat2 = math.cos(row['dec'] * factor) num1 = clat2 * sdlon num2 = clat1 * slat2 - slat1 * clat2 * cdlon numerator = math.sqrt(num1 ** 2 + num2 ** 2) denominator = slat1 * slat2 + clat1 * clat2 * cdlon return np.arctan2(numerator, denominator) / factor
python
def ang_sep(row, ra1, dec1): """ Calculate angular separation between two coordinates Uses Vicenty Formula (http://en.wikipedia.org/wiki/Great-circle_distance) and adapts from astropy's SkyCoord Written to be used within the Database.search() method Parameters ---------- row: dict, pandas Row Coordinate structure containing ra and dec keys in decimal degrees ra1: float RA to compare with, in decimal degrees dec1: float Dec to compare with, in decimal degrees Returns ------- Angular distance, in degrees, between the coordinates """ factor = math.pi / 180 sdlon = math.sin((row['ra'] - ra1) * factor) # RA is longitude cdlon = math.cos((row['ra'] - ra1) * factor) slat1 = math.sin(dec1 * factor) # Dec is latitude slat2 = math.sin(row['dec'] * factor) clat1 = math.cos(dec1 * factor) clat2 = math.cos(row['dec'] * factor) num1 = clat2 * sdlon num2 = clat1 * slat2 - slat1 * clat2 * cdlon numerator = math.sqrt(num1 ** 2 + num2 ** 2) denominator = slat1 * slat2 + clat1 * clat2 * cdlon return np.arctan2(numerator, denominator) / factor
[ "def", "ang_sep", "(", "row", ",", "ra1", ",", "dec1", ")", ":", "factor", "=", "math", ".", "pi", "/", "180", "sdlon", "=", "math", ".", "sin", "(", "(", "row", "[", "'ra'", "]", "-", "ra1", ")", "*", "factor", ")", "# RA is longitude", "cdlon",...
Calculate angular separation between two coordinates Uses Vicenty Formula (http://en.wikipedia.org/wiki/Great-circle_distance) and adapts from astropy's SkyCoord Written to be used within the Database.search() method Parameters ---------- row: dict, pandas Row Coordinate structure containing ra and dec keys in decimal degrees ra1: float RA to compare with, in decimal degrees dec1: float Dec to compare with, in decimal degrees Returns ------- Angular distance, in degrees, between the coordinates
[ "Calculate", "angular", "separation", "between", "two", "coordinates", "Uses", "Vicenty", "Formula", "(", "http", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Great", "-", "circle_distance", ")", "and", "adapts", "from", "astropy", "s", ...
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L2144-L2177
BDNYC/astrodbkit
astrodbkit/astrodb.py
convert_array
def convert_array(array): """ Converts an ARRAY string stored in the database back into a Numpy array. Parameters ---------- array: ARRAY The array object to be converted back into a Numpy array. Returns ------- array The converted Numpy array. """ out = io.BytesIO(array) out.seek(0) return np.load(out)
python
def convert_array(array): """ Converts an ARRAY string stored in the database back into a Numpy array. Parameters ---------- array: ARRAY The array object to be converted back into a Numpy array. Returns ------- array The converted Numpy array. """ out = io.BytesIO(array) out.seek(0) return np.load(out)
[ "def", "convert_array", "(", "array", ")", ":", "out", "=", "io", ".", "BytesIO", "(", "array", ")", "out", ".", "seek", "(", "0", ")", "return", "np", ".", "load", "(", "out", ")" ]
Converts an ARRAY string stored in the database back into a Numpy array. Parameters ---------- array: ARRAY The array object to be converted back into a Numpy array. Returns ------- array The converted Numpy array.
[ "Converts", "an", "ARRAY", "string", "stored", "in", "the", "database", "back", "into", "a", "Numpy", "array", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L2180-L2197
BDNYC/astrodbkit
astrodbkit/astrodb.py
convert_image
def convert_image(File, verbose=False): """ Converts a IMAGE data type stored in the database into a data cube Parameters ---------- File: str The URL or filepath of the file to be converted into arrays. verbose: bool Whether or not to display some diagnostic information (Default: False) Returns ------- sequence The converted image """ image, header = '', '' if isinstance(File, type(b'')): # Decode if needed (ie, for Python 3) File = File.decode('utf-8') if isinstance(File, (str, type(u''))): # Convert variable path to absolute path if File.startswith('$'): abspath = os.popen('echo {}'.format(File.split('/')[0])).read()[:-1] if abspath: File = File.replace(File.split('/')[0], abspath) if File.startswith('http'): if verbose: print('Downloading {}'.format(File)) # Download only once downloaded_file = download_file(File, cache=True) else: downloaded_file = File try: # Get the data image, header = pf.getdata(downloaded_file, cache=True, header=True) # If no data, then clear out all retrieved info for object if not isinstance(image, np.ndarray): image = None if verbose: print('Read as FITS...') except (IOError, KeyError): # Check if the FITS file is just Numpy arrays try: image, header = pf.getdata(downloaded_file, cache=True, header=True) if verbose: print('Read as FITS Numpy array...') except (IOError, KeyError): try: # Try ascii image = ii.read(downloaded_file) image = np.array([np.asarray(image.columns[n]) for n in range(len(image.columns))]) if verbose: print('Read as ascii...') txt, header = open(downloaded_file), [] for i in txt: if any([i.startswith(char) for char in ['#', '|', '\\']]): header.append(i.replace('\n', '')) txt.close() except: pass if image == '': print('Could not retrieve image at {}.'.format(File)) return File else: image = Image(image, header, File) return image
python
def convert_image(File, verbose=False): """ Converts a IMAGE data type stored in the database into a data cube Parameters ---------- File: str The URL or filepath of the file to be converted into arrays. verbose: bool Whether or not to display some diagnostic information (Default: False) Returns ------- sequence The converted image """ image, header = '', '' if isinstance(File, type(b'')): # Decode if needed (ie, for Python 3) File = File.decode('utf-8') if isinstance(File, (str, type(u''))): # Convert variable path to absolute path if File.startswith('$'): abspath = os.popen('echo {}'.format(File.split('/')[0])).read()[:-1] if abspath: File = File.replace(File.split('/')[0], abspath) if File.startswith('http'): if verbose: print('Downloading {}'.format(File)) # Download only once downloaded_file = download_file(File, cache=True) else: downloaded_file = File try: # Get the data image, header = pf.getdata(downloaded_file, cache=True, header=True) # If no data, then clear out all retrieved info for object if not isinstance(image, np.ndarray): image = None if verbose: print('Read as FITS...') except (IOError, KeyError): # Check if the FITS file is just Numpy arrays try: image, header = pf.getdata(downloaded_file, cache=True, header=True) if verbose: print('Read as FITS Numpy array...') except (IOError, KeyError): try: # Try ascii image = ii.read(downloaded_file) image = np.array([np.asarray(image.columns[n]) for n in range(len(image.columns))]) if verbose: print('Read as ascii...') txt, header = open(downloaded_file), [] for i in txt: if any([i.startswith(char) for char in ['#', '|', '\\']]): header.append(i.replace('\n', '')) txt.close() except: pass if image == '': print('Could not retrieve image at {}.'.format(File)) return File else: image = Image(image, header, File) return image
[ "def", "convert_image", "(", "File", ",", "verbose", "=", "False", ")", ":", "image", ",", "header", "=", "''", ",", "''", "if", "isinstance", "(", "File", ",", "type", "(", "b''", ")", ")", ":", "# Decode if needed (ie, for Python 3)", "File", "=", "Fil...
Converts a IMAGE data type stored in the database into a data cube Parameters ---------- File: str The URL or filepath of the file to be converted into arrays. verbose: bool Whether or not to display some diagnostic information (Default: False) Returns ------- sequence The converted image
[ "Converts", "a", "IMAGE", "data", "type", "stored", "in", "the", "database", "into", "a", "data", "cube" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L2199-L2277
BDNYC/astrodbkit
astrodbkit/astrodb.py
convert_spectrum
def convert_spectrum(File, verbose=False): """ Converts a SPECTRUM data type stored in the database into a (W,F,E) sequence of arrays. Parameters ---------- File: str The URL or filepath of the file to be converted into arrays. verbose: bool Whether or not to display some diagnostic information (Default: False) Returns ------- sequence The converted spectrum. """ spectrum, header = '', '' if isinstance(File, type(b'')): # Decode if needed (ie, for Python 3) File = File.decode('utf-8') if isinstance(File, (str, type(u''))): # Convert variable path to absolute path if File.startswith('$'): abspath = os.popen('echo {}'.format(File.split('/')[0])).read()[:-1] if abspath: File = File.replace(File.split('/')[0], abspath) if File.startswith('http'): if verbose: print('Downloading {}'.format(File)) downloaded_file = download_file(File, cache=True) # download only once else: downloaded_file = File try: # Try FITS files first # Get the data # try: spectrum, header = pf.getdata(downloaded_file, cache=True, header=True) # except: # spectrum, header = pf.getdata(File, cache=False, header=True) # Check the key type KEY_TYPE = ['CTYPE1'] setType = set(KEY_TYPE).intersection(set(header.keys())) if len(setType) == 0: isLinear = True else: valType = header[setType.pop()] isLinear = valType.strip().upper() == 'LINEAR' # Get wl, flux & error data from fits file spectrum = __get_spec(spectrum, header, File) # Generate wl axis when needed if not isinstance(spectrum[0], np.ndarray): tempwav = __create_waxis(header, len(spectrum[1]), File) # Check to see if it's a FIRE spectrum with CDELT1, if so needs wlog=True if 'INSTRUME' in header.keys(): if header['INSTRUME'].strip() == 'FIRE' and 'CDELT1' in header.keys(): tempwav = __create_waxis(header, len(spectrum[1]), File, wlog=True) spectrum[0] = tempwav # If no wl axis generated, then clear out all retrieved data for object if not isinstance(spectrum[0], np.ndarray): spectrum = None if verbose: print('Read as FITS...') except (IOError, KeyError): # Check if the FITS file is just Numpy arrays try: spectrum, header = pf.getdata(downloaded_file, cache=True, header=True) if verbose: print('Read as FITS Numpy array...') except (IOError, KeyError): try: # Try ascii spectrum = ii.read(downloaded_file) spectrum = np.array([np.asarray(spectrum.columns[n]) for n in range(len(spectrum.columns))]) if verbose: print('Read as ascii...') txt, header = open(downloaded_file), [] for i in txt: if any([i.startswith(char) for char in ['#', '|', '\\']]): header.append(i.replace('\n', '')) txt.close() except: pass if spectrum == '': print('Could not retrieve spectrum at {}.'.format(File)) return File else: spectrum = Spectrum(spectrum, header, File) return spectrum
python
def convert_spectrum(File, verbose=False): """ Converts a SPECTRUM data type stored in the database into a (W,F,E) sequence of arrays. Parameters ---------- File: str The URL or filepath of the file to be converted into arrays. verbose: bool Whether or not to display some diagnostic information (Default: False) Returns ------- sequence The converted spectrum. """ spectrum, header = '', '' if isinstance(File, type(b'')): # Decode if needed (ie, for Python 3) File = File.decode('utf-8') if isinstance(File, (str, type(u''))): # Convert variable path to absolute path if File.startswith('$'): abspath = os.popen('echo {}'.format(File.split('/')[0])).read()[:-1] if abspath: File = File.replace(File.split('/')[0], abspath) if File.startswith('http'): if verbose: print('Downloading {}'.format(File)) downloaded_file = download_file(File, cache=True) # download only once else: downloaded_file = File try: # Try FITS files first # Get the data # try: spectrum, header = pf.getdata(downloaded_file, cache=True, header=True) # except: # spectrum, header = pf.getdata(File, cache=False, header=True) # Check the key type KEY_TYPE = ['CTYPE1'] setType = set(KEY_TYPE).intersection(set(header.keys())) if len(setType) == 0: isLinear = True else: valType = header[setType.pop()] isLinear = valType.strip().upper() == 'LINEAR' # Get wl, flux & error data from fits file spectrum = __get_spec(spectrum, header, File) # Generate wl axis when needed if not isinstance(spectrum[0], np.ndarray): tempwav = __create_waxis(header, len(spectrum[1]), File) # Check to see if it's a FIRE spectrum with CDELT1, if so needs wlog=True if 'INSTRUME' in header.keys(): if header['INSTRUME'].strip() == 'FIRE' and 'CDELT1' in header.keys(): tempwav = __create_waxis(header, len(spectrum[1]), File, wlog=True) spectrum[0] = tempwav # If no wl axis generated, then clear out all retrieved data for object if not isinstance(spectrum[0], np.ndarray): spectrum = None if verbose: print('Read as FITS...') except (IOError, KeyError): # Check if the FITS file is just Numpy arrays try: spectrum, header = pf.getdata(downloaded_file, cache=True, header=True) if verbose: print('Read as FITS Numpy array...') except (IOError, KeyError): try: # Try ascii spectrum = ii.read(downloaded_file) spectrum = np.array([np.asarray(spectrum.columns[n]) for n in range(len(spectrum.columns))]) if verbose: print('Read as ascii...') txt, header = open(downloaded_file), [] for i in txt: if any([i.startswith(char) for char in ['#', '|', '\\']]): header.append(i.replace('\n', '')) txt.close() except: pass if spectrum == '': print('Could not retrieve spectrum at {}.'.format(File)) return File else: spectrum = Spectrum(spectrum, header, File) return spectrum
[ "def", "convert_spectrum", "(", "File", ",", "verbose", "=", "False", ")", ":", "spectrum", ",", "header", "=", "''", ",", "''", "if", "isinstance", "(", "File", ",", "type", "(", "b''", ")", ")", ":", "# Decode if needed (ie, for Python 3)", "File", "=", ...
Converts a SPECTRUM data type stored in the database into a (W,F,E) sequence of arrays. Parameters ---------- File: str The URL or filepath of the file to be converted into arrays. verbose: bool Whether or not to display some diagnostic information (Default: False) Returns ------- sequence The converted spectrum.
[ "Converts", "a", "SPECTRUM", "data", "type", "stored", "in", "the", "database", "into", "a", "(", "W", "F", "E", ")", "sequence", "of", "arrays", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L2279-L2372
BDNYC/astrodbkit
astrodbkit/astrodb.py
pprint
def pprint(data, names='', title='', formats={}): """ Prints tables with a bit of formatting Parameters ---------- data: (sequence, dict, table) The data to print in the table names: sequence The column names title: str (optional) The title of the table formats: dict A dictionary of column:format values """ # Make the data into a table if it isn't already if type(data) != at.Table: data = at.Table(data, names=names) # Make a copy pdata = data.copy() # Put the title in the metadata try: title = title or pdata.meta['name'] except: pass # Shorten the column names for slimmer data for old, new in zip(*[pdata.colnames, [ i.replace('wavelength', 'wav').replace('publication', 'pub').replace('instrument', 'inst')\ .replace('telescope','scope') for i in pdata.colnames]]): pdata.rename_column(old, new) if new != old else None # Format the columns formats.update({'comments': '%.15s', 'obs_date': '%.10s', 'names': '%.30s', 'description': '%.50s'}) # print it! if title: print('\n' + title) try: ii.write(pdata, sys.stdout, Writer=ii.FixedWidthTwoLine, formats=formats, fill_values=[('None', '-')]) except UnicodeDecodeError: # Fix for Unicode characters. Print out in close approximation to ii.write() max_length = 50 str_lengths = dict() for key in pdata.keys(): lengths = map(lambda x: len(str(x).decode('utf-8')), pdata[key].data) lengths.append(len(key)) str_lengths[key] = min(max(lengths), max_length) print(' '.join(key.rjust(str_lengths[key]) for key in pdata.keys())) print(' '.join('-' * str_lengths[key] for key in pdata.keys())) for i in pdata: print(' '.join([str(i[key]).decode('utf-8')[:max_length].rjust(str_lengths[key]) if i[key] else '-'.rjust(str_lengths[key]) for key in pdata.keys()]))
python
def pprint(data, names='', title='', formats={}): """ Prints tables with a bit of formatting Parameters ---------- data: (sequence, dict, table) The data to print in the table names: sequence The column names title: str (optional) The title of the table formats: dict A dictionary of column:format values """ # Make the data into a table if it isn't already if type(data) != at.Table: data = at.Table(data, names=names) # Make a copy pdata = data.copy() # Put the title in the metadata try: title = title or pdata.meta['name'] except: pass # Shorten the column names for slimmer data for old, new in zip(*[pdata.colnames, [ i.replace('wavelength', 'wav').replace('publication', 'pub').replace('instrument', 'inst')\ .replace('telescope','scope') for i in pdata.colnames]]): pdata.rename_column(old, new) if new != old else None # Format the columns formats.update({'comments': '%.15s', 'obs_date': '%.10s', 'names': '%.30s', 'description': '%.50s'}) # print it! if title: print('\n' + title) try: ii.write(pdata, sys.stdout, Writer=ii.FixedWidthTwoLine, formats=formats, fill_values=[('None', '-')]) except UnicodeDecodeError: # Fix for Unicode characters. Print out in close approximation to ii.write() max_length = 50 str_lengths = dict() for key in pdata.keys(): lengths = map(lambda x: len(str(x).decode('utf-8')), pdata[key].data) lengths.append(len(key)) str_lengths[key] = min(max(lengths), max_length) print(' '.join(key.rjust(str_lengths[key]) for key in pdata.keys())) print(' '.join('-' * str_lengths[key] for key in pdata.keys())) for i in pdata: print(' '.join([str(i[key]).decode('utf-8')[:max_length].rjust(str_lengths[key]) if i[key] else '-'.rjust(str_lengths[key]) for key in pdata.keys()]))
[ "def", "pprint", "(", "data", ",", "names", "=", "''", ",", "title", "=", "''", ",", "formats", "=", "{", "}", ")", ":", "# Make the data into a table if it isn't already", "if", "type", "(", "data", ")", "!=", "at", ".", "Table", ":", "data", "=", "at...
Prints tables with a bit of formatting Parameters ---------- data: (sequence, dict, table) The data to print in the table names: sequence The column names title: str (optional) The title of the table formats: dict A dictionary of column:format values
[ "Prints", "tables", "with", "a", "bit", "of", "formatting" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L2523-L2576
BDNYC/astrodbkit
astrodbkit/astrodb.py
scrub
def scrub(data, units=False): """ For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponding wavelengths and errors) removed. """ units = [i.unit if hasattr(i, 'unit') else 1 for i in data] data = [np.asarray(i.value if hasattr(i, 'unit') else i, dtype=np.float32) for i in data if isinstance(i, np.ndarray)] data = [i[np.where(~np.isinf(data[1]))] for i in data] data = [i[np.where(np.logical_and(data[1] > 0, ~np.isnan(data[1])))] for i in data] data = [i[np.unique(data[0], return_index=True)[1]] for i in data] return [i[np.lexsort([data[0]])] * Q for i, Q in zip(data, units)] if units else [i[np.lexsort([data[0]])] for i in data]
python
def scrub(data, units=False): """ For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponding wavelengths and errors) removed. """ units = [i.unit if hasattr(i, 'unit') else 1 for i in data] data = [np.asarray(i.value if hasattr(i, 'unit') else i, dtype=np.float32) for i in data if isinstance(i, np.ndarray)] data = [i[np.where(~np.isinf(data[1]))] for i in data] data = [i[np.where(np.logical_and(data[1] > 0, ~np.isnan(data[1])))] for i in data] data = [i[np.unique(data[0], return_index=True)[1]] for i in data] return [i[np.lexsort([data[0]])] * Q for i, Q in zip(data, units)] if units else [i[np.lexsort([data[0]])] for i in data]
[ "def", "scrub", "(", "data", ",", "units", "=", "False", ")", ":", "units", "=", "[", "i", ".", "unit", "if", "hasattr", "(", "i", ",", "'unit'", ")", "else", "1", "for", "i", "in", "data", "]", "data", "=", "[", "np", ".", "asarray", "(", "i...
For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponding wavelengths and errors) removed.
[ "For", "input", "data", "[", "w", "f", "e", "]", "or", "[", "w", "f", "]", "returns", "the", "list", "with", "NaN", "negative", "and", "zero", "flux", "(", "and", "corresponding", "wavelengths", "and", "errors", ")", "removed", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L2608-L2620
BDNYC/astrodbkit
astrodbkit/astrodb.py
_autofill_spec_record
def _autofill_spec_record(record): """ Returns an astropy table with columns auto-filled from FITS header Parameters ---------- record: astropy.io.fits.table.table.Row The spectrum table row to scrape Returns ------- record: astropy.io.fits.table.table.Row The spectrum table row with possible new rows inserted """ try: record['filename'] = os.path.basename(record['spectrum']) if record['spectrum'].endswith('.fits'): header = pf.getheader(record['spectrum']) # Wavelength units if not record['wavelength_units']: try: record['wavelength_units'] = header['XUNITS'] except KeyError: try: if header['BUNIT']: record['wavelength_units'] = 'um' except KeyError: pass if 'microns' in record['wavelength_units'] or 'Microns' in record['wavelength_units'] or 'um' in record[ 'wavelength_units']: record['wavelength_units'] = 'um' # Flux units if not record['flux_units']: try: record['flux_units'] = header['YUNITS'].replace(' ', '') except KeyError: try: record['flux_units'] = header['BUNIT'].replace(' ', '') except KeyError: pass if 'erg' in record['flux_units'] and 'A' in record['flux_units']: record['flux_units'] = 'ergs-1cm-2A-1' if 'erg' in record['flux_units'] and 'A' in record['flux_units'] \ else 'ergs-1cm-2um-1' if 'erg' in record['flux_units'] and 'um' in record['flux_units'] \ else 'Wm-2um-1' if 'W' in record['flux_units'] and 'um' in record['flux_units'] \ else 'Wm-2A-1' if 'W' in record['flux_units'] and 'A' in record['flux_units'] \ else '' # Observation date if not record['obs_date']: try: record['obs_date'] = header['DATE_OBS'] except KeyError: try: record['obs_date'] = header['DATE-OBS'] except KeyError: try: record['obs_date'] = header['DATE'] except KeyError: pass # Telescope id if not record['telescope_id']: try: n = header['TELESCOP'].lower() if isinstance(header['TELESCOP'], str) else '' record['telescope_id'] = 5 if 'hst' in n \ else 6 if 'spitzer' in n \ else 7 if 'irtf' in n \ else 9 if 'keck' in n and 'ii' in n \ else 8 if 'keck' in n and 'i' in n \ else 10 if 'kp' in n and '4' in n \ else 11 if 'kp' in n and '2' in n \ else 12 if 'bok' in n \ else 13 if 'mmt' in n \ else 14 if 'ctio' in n and '1' in n \ else 15 if 'ctio' in n and '4' in n \ else 16 if 'gemini' in n and 'north' in n \ else 17 if 'gemini' in n and 'south' in n \ else 18 if ('vlt' in n and 'U2' in n) \ else 19 if '3.5m' in n \ else 20 if 'subaru' in n \ else 21 if ('mag' in n and 'ii' in n) or ('clay' in n) \ else 22 if ('mag' in n and 'i' in n) or ('baade' in n) \ else 23 if ('eso' in n and '1m' in n) \ else 24 if 'cfht' in n \ else 25 if 'ntt' in n \ else 26 if ('palomar' in n and '200-inch' in n) \ else 27 if 'pan-starrs' in n \ else 28 if ('palomar' in n and '60-inch' in n) \ else 29 if ('ctio' in n and '0.9m' in n) \ else 30 if 'soar' in n \ else 31 if ('vlt' in n and 'U3' in n) \ else 32 if ('vlt' in n and 'U4' in n) \ else 33 if 'gtc' in n \ else None except KeyError: pass # Instrument id if not record['instrument_id']: try: i = header['INSTRUME'].lower() record[ 'instrument_id'] = 1 if 'r-c spec' in i or 'test' in i or 'nod' in i else 2 if 'gmos-n' in i else 3 if 'gmos-s' in i else 4 if 'fors' in i else 5 if 'lris' in i else 6 if 'spex' in i else 7 if 'ldss3' in i else 8 if 'focas' in i else 9 if 'nirspec' in i else 10 if 'irs' in i else 11 if 'fire' in i else 12 if 'mage' in i else 13 if 'goldcam' in i else 14 if 'sinfoni' in i else 15 if 'osiris' in i else 16 if 'triplespec' in i else 17 if 'x-shooter' in i else 18 if 'gnirs' in i else 19 if 'wircam' in i else 20 if 'cormass' in i else 21 if 'isaac' in i else 22 if 'irac' in i else 23 if 'dis' in i else 24 if 'susi2' in i else 25 if 'ircs' in i else 26 if 'nirc' in i else 29 if 'stis' in i else 0 except KeyError: pass except: pass return record
python
def _autofill_spec_record(record): """ Returns an astropy table with columns auto-filled from FITS header Parameters ---------- record: astropy.io.fits.table.table.Row The spectrum table row to scrape Returns ------- record: astropy.io.fits.table.table.Row The spectrum table row with possible new rows inserted """ try: record['filename'] = os.path.basename(record['spectrum']) if record['spectrum'].endswith('.fits'): header = pf.getheader(record['spectrum']) # Wavelength units if not record['wavelength_units']: try: record['wavelength_units'] = header['XUNITS'] except KeyError: try: if header['BUNIT']: record['wavelength_units'] = 'um' except KeyError: pass if 'microns' in record['wavelength_units'] or 'Microns' in record['wavelength_units'] or 'um' in record[ 'wavelength_units']: record['wavelength_units'] = 'um' # Flux units if not record['flux_units']: try: record['flux_units'] = header['YUNITS'].replace(' ', '') except KeyError: try: record['flux_units'] = header['BUNIT'].replace(' ', '') except KeyError: pass if 'erg' in record['flux_units'] and 'A' in record['flux_units']: record['flux_units'] = 'ergs-1cm-2A-1' if 'erg' in record['flux_units'] and 'A' in record['flux_units'] \ else 'ergs-1cm-2um-1' if 'erg' in record['flux_units'] and 'um' in record['flux_units'] \ else 'Wm-2um-1' if 'W' in record['flux_units'] and 'um' in record['flux_units'] \ else 'Wm-2A-1' if 'W' in record['flux_units'] and 'A' in record['flux_units'] \ else '' # Observation date if not record['obs_date']: try: record['obs_date'] = header['DATE_OBS'] except KeyError: try: record['obs_date'] = header['DATE-OBS'] except KeyError: try: record['obs_date'] = header['DATE'] except KeyError: pass # Telescope id if not record['telescope_id']: try: n = header['TELESCOP'].lower() if isinstance(header['TELESCOP'], str) else '' record['telescope_id'] = 5 if 'hst' in n \ else 6 if 'spitzer' in n \ else 7 if 'irtf' in n \ else 9 if 'keck' in n and 'ii' in n \ else 8 if 'keck' in n and 'i' in n \ else 10 if 'kp' in n and '4' in n \ else 11 if 'kp' in n and '2' in n \ else 12 if 'bok' in n \ else 13 if 'mmt' in n \ else 14 if 'ctio' in n and '1' in n \ else 15 if 'ctio' in n and '4' in n \ else 16 if 'gemini' in n and 'north' in n \ else 17 if 'gemini' in n and 'south' in n \ else 18 if ('vlt' in n and 'U2' in n) \ else 19 if '3.5m' in n \ else 20 if 'subaru' in n \ else 21 if ('mag' in n and 'ii' in n) or ('clay' in n) \ else 22 if ('mag' in n and 'i' in n) or ('baade' in n) \ else 23 if ('eso' in n and '1m' in n) \ else 24 if 'cfht' in n \ else 25 if 'ntt' in n \ else 26 if ('palomar' in n and '200-inch' in n) \ else 27 if 'pan-starrs' in n \ else 28 if ('palomar' in n and '60-inch' in n) \ else 29 if ('ctio' in n and '0.9m' in n) \ else 30 if 'soar' in n \ else 31 if ('vlt' in n and 'U3' in n) \ else 32 if ('vlt' in n and 'U4' in n) \ else 33 if 'gtc' in n \ else None except KeyError: pass # Instrument id if not record['instrument_id']: try: i = header['INSTRUME'].lower() record[ 'instrument_id'] = 1 if 'r-c spec' in i or 'test' in i or 'nod' in i else 2 if 'gmos-n' in i else 3 if 'gmos-s' in i else 4 if 'fors' in i else 5 if 'lris' in i else 6 if 'spex' in i else 7 if 'ldss3' in i else 8 if 'focas' in i else 9 if 'nirspec' in i else 10 if 'irs' in i else 11 if 'fire' in i else 12 if 'mage' in i else 13 if 'goldcam' in i else 14 if 'sinfoni' in i else 15 if 'osiris' in i else 16 if 'triplespec' in i else 17 if 'x-shooter' in i else 18 if 'gnirs' in i else 19 if 'wircam' in i else 20 if 'cormass' in i else 21 if 'isaac' in i else 22 if 'irac' in i else 23 if 'dis' in i else 24 if 'susi2' in i else 25 if 'ircs' in i else 26 if 'nirc' in i else 29 if 'stis' in i else 0 except KeyError: pass except: pass return record
[ "def", "_autofill_spec_record", "(", "record", ")", ":", "try", ":", "record", "[", "'filename'", "]", "=", "os", ".", "path", ".", "basename", "(", "record", "[", "'spectrum'", "]", ")", "if", "record", "[", "'spectrum'", "]", ".", "endswith", "(", "'...
Returns an astropy table with columns auto-filled from FITS header Parameters ---------- record: astropy.io.fits.table.table.Row The spectrum table row to scrape Returns ------- record: astropy.io.fits.table.table.Row The spectrum table row with possible new rows inserted
[ "Returns", "an", "astropy", "table", "with", "columns", "auto", "-", "filled", "from", "FITS", "header" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L2623-L2734
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.add_changelog
def add_changelog(self, user="", mod_tables="", user_desc=""): """ Add an entry to the changelog table. This should be run when changes or edits are done to the database. Parameters ---------- user: str Name of the person who made the edits mod_tables: str Table or tables that were edited user_desc: str A short message describing the changes """ import datetime import socket # Spit out warning messages if the user does not provide the needed information if user == "" or mod_tables == "" or user_desc == "": print("You must supply your name, the name(s) of table(s) edited, " "and a description for add_changelog() to work.") raise InputError('Did not supply the required input, see help(db.add_changelog) for more information.\n' 'Your inputs: \n\t user = {}\n\t mod_tables = {}\n\t user_desc = {}'.format(user, mod_tables, user_desc)) # Making tables all uppercase for consistency mod_tables = mod_tables.upper() data = list() data.append(['date', 'user', 'machine_name', 'modified_tables', 'user_description']) datestr = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") machine = socket.gethostname() data.append([datestr, user, machine, mod_tables, user_desc]) self.add_data(data, 'changelog')
python
def add_changelog(self, user="", mod_tables="", user_desc=""): """ Add an entry to the changelog table. This should be run when changes or edits are done to the database. Parameters ---------- user: str Name of the person who made the edits mod_tables: str Table or tables that were edited user_desc: str A short message describing the changes """ import datetime import socket # Spit out warning messages if the user does not provide the needed information if user == "" or mod_tables == "" or user_desc == "": print("You must supply your name, the name(s) of table(s) edited, " "and a description for add_changelog() to work.") raise InputError('Did not supply the required input, see help(db.add_changelog) for more information.\n' 'Your inputs: \n\t user = {}\n\t mod_tables = {}\n\t user_desc = {}'.format(user, mod_tables, user_desc)) # Making tables all uppercase for consistency mod_tables = mod_tables.upper() data = list() data.append(['date', 'user', 'machine_name', 'modified_tables', 'user_description']) datestr = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") machine = socket.gethostname() data.append([datestr, user, machine, mod_tables, user_desc]) self.add_data(data, 'changelog')
[ "def", "add_changelog", "(", "self", ",", "user", "=", "\"\"", ",", "mod_tables", "=", "\"\"", ",", "user_desc", "=", "\"\"", ")", ":", "import", "datetime", "import", "socket", "# Spit out warning messages if the user does not provide the needed information", "if", "...
Add an entry to the changelog table. This should be run when changes or edits are done to the database. Parameters ---------- user: str Name of the person who made the edits mod_tables: str Table or tables that were edited user_desc: str A short message describing the changes
[ "Add", "an", "entry", "to", "the", "changelog", "table", ".", "This", "should", "be", "run", "when", "changes", "or", "edits", "are", "done", "to", "the", "database", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L241-L272
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.add_data
def add_data(self, data, table, delimiter='|', bands='', clean_up=True, rename_columns={}, column_fill={}, verbose=False): """ Adds data to the specified database table. Column names must match table fields to insert, however order and completeness don't matter. Parameters ---------- data: str, array-like, astropy.table.Table The path to an ascii file, array-like object, or table. The first row or element must be the list of column names table: str The name of the table into which the data should be inserted delimiter: str The string to use as the delimiter when parsing the ascii file bands: sequence Sequence of band to look for in the data header when digesting columns of multiple photometric measurements (e.g. ['MKO_J','MKO_H','MKO_K']) into individual rows of data for database insertion clean_up: bool Run self.clean_up() rename_columns: dict A dictionary of the {input_col_name:desired_col_name} for table columns, e.g. {'e_Jmag':'J_unc', 'RAJ2000':'ra'} column_fill: dict A dictionary of the column name and value to fill, e.g. {'instrument_id':2, 'band':'2MASS.J'} verbose: bool Print diagnostic messages """ # Store raw entry entry, del_records = data, [] # Digest the ascii file into table if isinstance(data, str) and os.path.isfile(data): data = ii.read(data, delimiter=delimiter) # Or read the sequence of data elements into a table elif isinstance(data, (list, tuple, np.ndarray)): data = ii.read(['|'.join(map(str, row)) for row in data], data_start=1, delimiter='|') # Or convert pandas dataframe to astropy table elif isinstance(data, pd.core.frame.DataFrame): data = at.Table.from_pandas(data) # Or if it's already an astropy table elif isinstance(data, at.Table): pass else: data = None if data: # Rename columns if isinstance(rename_columns,str): rename_columns = astrocat.default_rename_columns(rename_columns) for input_name,new_name in rename_columns.items(): data.rename_column(input_name,new_name) # Add column fills if isinstance(column_fill,str): column_fill = astrocat.default_column_fill(column_fill) for colname,fill_value in column_fill.items(): data[colname] = [fill_value]*len(data) # Get list of all columns and make an empty table for new records metadata = self.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, required = [np.array(metadata[n]) for n in ['name', 'type', 'notnull']] new_records = at.Table(names=columns, dtype=[type_dict[t] for t in types]) # Fix column dtypes and blanks for col in data.colnames: # Convert data dtypes to those of the existing table try: temp = data[col].astype(new_records[col].dtype) data.replace_column(col, temp) except KeyError: continue # If a row contains photometry for multiple bands, use the *multiband argument and execute this if bands and table.lower() == 'photometry': # Pull out columns that are band names for b in list(set(bands) & set(data.colnames)): try: # Get the repeated data plus the band data and rename the columns band = data[list(set(columns) & set(data.colnames)) + [b, b + '_unc']] for suf in ['', '_unc']: band.rename_column(b+suf, 'magnitude'+suf) temp = band['magnitude'+suf].astype(new_records['magnitude'+suf].dtype) band.replace_column('magnitude'+suf, temp) band.add_column(at.Column([b] * len(band), name='band', dtype='O')) # Add the band data to the list of new_records new_records = at.vstack([new_records, band]) except IOError: pass else: # Inject data into full database table format new_records = at.vstack([new_records, data])[new_records.colnames] # Reject rows that fail column requirements, e.g. NOT NULL fields like 'source_id' for r in columns[np.where(np.logical_and(required, columns != 'id'))]: # Null values... new_records = new_records[np.where(new_records[r])] # Masked values... try: new_records = new_records[~new_records[r].mask] except: pass # NaN values... if new_records.dtype[r] in (int, float): new_records = new_records[~np.isnan(new_records[r])] # For spectra, try to populate the table by reading the FITS header if table.lower() == 'spectra': for n, new_rec in enumerate(new_records): # Convert relative path to absolute path relpath = new_rec['spectrum'] if relpath.startswith('$'): abspath = os.popen('echo {}'.format(relpath.split('/')[0])).read()[:-1] if abspath: new_rec['spectrum'] = relpath.replace(relpath.split('/')[0], abspath) # Test if the file exists and try to pull metadata from the FITS header if os.path.isfile(new_rec['spectrum']): new_records[n]['spectrum'] = relpath new_records[n] = _autofill_spec_record(new_rec) else: print('Error adding the spectrum at {}'.format(new_rec['spectrum'])) del_records.append(n) # Remove bad records from the table new_records.remove_rows(del_records) # For images, try to populate the table by reading the FITS header if table.lower() == 'images': for n, new_rec in enumerate(new_records): # Convert relative path to absolute path relpath = new_rec['image'] if relpath.startswith('$'): abspath = os.popen('echo {}'.format(relpath.split('/')[0])).read()[:-1] if abspath: new_rec['image'] = relpath.replace(relpath.split('/')[0], abspath) # Test if the file exists and try to pull metadata from the FITS header if os.path.isfile(new_rec['image']): new_records[n]['image'] = relpath new_records[n] = _autofill_spec_record(new_rec) else: print('Error adding the image at {}'.format(new_rec['image'])) del_records.append(n) # Remove bad records from the table new_records.remove_rows(del_records) # Get some new row ids for the good records rowids = self._lowest_rowids(table, len(new_records)) # Add the new records keepers, rejects = [], [] for N, new_rec in enumerate(new_records): new_rec = list(new_rec) new_rec[0] = rowids[N] for n, col in enumerate(new_rec): if type(col) == np.int64 and sys.version_info[0] >= 3: # Fix for Py3 and sqlite3 issue with numpy types new_rec[n] = col.item() if type(col) == np.ma.core.MaskedConstant: new_rec[n] = None try: self.modify("INSERT INTO {} VALUES({})".format(table, ','.join('?'*len(columns))), new_rec, verbose=verbose) keepers.append(N) except IOError: rejects.append(N) new_records[N]['id'] = rowids[N] # Make tables of keepers and rejects rejected = new_records[rejects] new_records = new_records[keepers] # Print a table of the new records or bad news if new_records: print("\033[1;32m{} new records added to the {} table.\033[1;m".format(len(new_records), table.upper())) new_records.pprint() if rejected: print("\033[1;31m{} records rejected from the {} table.\033[1;m".format(len(rejected), table.upper())) rejected.pprint() # Run table clean up if clean_up: self.clean_up(table, verbose) else: print('Please check your input: {}'.format(entry))
python
def add_data(self, data, table, delimiter='|', bands='', clean_up=True, rename_columns={}, column_fill={}, verbose=False): """ Adds data to the specified database table. Column names must match table fields to insert, however order and completeness don't matter. Parameters ---------- data: str, array-like, astropy.table.Table The path to an ascii file, array-like object, or table. The first row or element must be the list of column names table: str The name of the table into which the data should be inserted delimiter: str The string to use as the delimiter when parsing the ascii file bands: sequence Sequence of band to look for in the data header when digesting columns of multiple photometric measurements (e.g. ['MKO_J','MKO_H','MKO_K']) into individual rows of data for database insertion clean_up: bool Run self.clean_up() rename_columns: dict A dictionary of the {input_col_name:desired_col_name} for table columns, e.g. {'e_Jmag':'J_unc', 'RAJ2000':'ra'} column_fill: dict A dictionary of the column name and value to fill, e.g. {'instrument_id':2, 'band':'2MASS.J'} verbose: bool Print diagnostic messages """ # Store raw entry entry, del_records = data, [] # Digest the ascii file into table if isinstance(data, str) and os.path.isfile(data): data = ii.read(data, delimiter=delimiter) # Or read the sequence of data elements into a table elif isinstance(data, (list, tuple, np.ndarray)): data = ii.read(['|'.join(map(str, row)) for row in data], data_start=1, delimiter='|') # Or convert pandas dataframe to astropy table elif isinstance(data, pd.core.frame.DataFrame): data = at.Table.from_pandas(data) # Or if it's already an astropy table elif isinstance(data, at.Table): pass else: data = None if data: # Rename columns if isinstance(rename_columns,str): rename_columns = astrocat.default_rename_columns(rename_columns) for input_name,new_name in rename_columns.items(): data.rename_column(input_name,new_name) # Add column fills if isinstance(column_fill,str): column_fill = astrocat.default_column_fill(column_fill) for colname,fill_value in column_fill.items(): data[colname] = [fill_value]*len(data) # Get list of all columns and make an empty table for new records metadata = self.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, required = [np.array(metadata[n]) for n in ['name', 'type', 'notnull']] new_records = at.Table(names=columns, dtype=[type_dict[t] for t in types]) # Fix column dtypes and blanks for col in data.colnames: # Convert data dtypes to those of the existing table try: temp = data[col].astype(new_records[col].dtype) data.replace_column(col, temp) except KeyError: continue # If a row contains photometry for multiple bands, use the *multiband argument and execute this if bands and table.lower() == 'photometry': # Pull out columns that are band names for b in list(set(bands) & set(data.colnames)): try: # Get the repeated data plus the band data and rename the columns band = data[list(set(columns) & set(data.colnames)) + [b, b + '_unc']] for suf in ['', '_unc']: band.rename_column(b+suf, 'magnitude'+suf) temp = band['magnitude'+suf].astype(new_records['magnitude'+suf].dtype) band.replace_column('magnitude'+suf, temp) band.add_column(at.Column([b] * len(band), name='band', dtype='O')) # Add the band data to the list of new_records new_records = at.vstack([new_records, band]) except IOError: pass else: # Inject data into full database table format new_records = at.vstack([new_records, data])[new_records.colnames] # Reject rows that fail column requirements, e.g. NOT NULL fields like 'source_id' for r in columns[np.where(np.logical_and(required, columns != 'id'))]: # Null values... new_records = new_records[np.where(new_records[r])] # Masked values... try: new_records = new_records[~new_records[r].mask] except: pass # NaN values... if new_records.dtype[r] in (int, float): new_records = new_records[~np.isnan(new_records[r])] # For spectra, try to populate the table by reading the FITS header if table.lower() == 'spectra': for n, new_rec in enumerate(new_records): # Convert relative path to absolute path relpath = new_rec['spectrum'] if relpath.startswith('$'): abspath = os.popen('echo {}'.format(relpath.split('/')[0])).read()[:-1] if abspath: new_rec['spectrum'] = relpath.replace(relpath.split('/')[0], abspath) # Test if the file exists and try to pull metadata from the FITS header if os.path.isfile(new_rec['spectrum']): new_records[n]['spectrum'] = relpath new_records[n] = _autofill_spec_record(new_rec) else: print('Error adding the spectrum at {}'.format(new_rec['spectrum'])) del_records.append(n) # Remove bad records from the table new_records.remove_rows(del_records) # For images, try to populate the table by reading the FITS header if table.lower() == 'images': for n, new_rec in enumerate(new_records): # Convert relative path to absolute path relpath = new_rec['image'] if relpath.startswith('$'): abspath = os.popen('echo {}'.format(relpath.split('/')[0])).read()[:-1] if abspath: new_rec['image'] = relpath.replace(relpath.split('/')[0], abspath) # Test if the file exists and try to pull metadata from the FITS header if os.path.isfile(new_rec['image']): new_records[n]['image'] = relpath new_records[n] = _autofill_spec_record(new_rec) else: print('Error adding the image at {}'.format(new_rec['image'])) del_records.append(n) # Remove bad records from the table new_records.remove_rows(del_records) # Get some new row ids for the good records rowids = self._lowest_rowids(table, len(new_records)) # Add the new records keepers, rejects = [], [] for N, new_rec in enumerate(new_records): new_rec = list(new_rec) new_rec[0] = rowids[N] for n, col in enumerate(new_rec): if type(col) == np.int64 and sys.version_info[0] >= 3: # Fix for Py3 and sqlite3 issue with numpy types new_rec[n] = col.item() if type(col) == np.ma.core.MaskedConstant: new_rec[n] = None try: self.modify("INSERT INTO {} VALUES({})".format(table, ','.join('?'*len(columns))), new_rec, verbose=verbose) keepers.append(N) except IOError: rejects.append(N) new_records[N]['id'] = rowids[N] # Make tables of keepers and rejects rejected = new_records[rejects] new_records = new_records[keepers] # Print a table of the new records or bad news if new_records: print("\033[1;32m{} new records added to the {} table.\033[1;m".format(len(new_records), table.upper())) new_records.pprint() if rejected: print("\033[1;31m{} records rejected from the {} table.\033[1;m".format(len(rejected), table.upper())) rejected.pprint() # Run table clean up if clean_up: self.clean_up(table, verbose) else: print('Please check your input: {}'.format(entry))
[ "def", "add_data", "(", "self", ",", "data", ",", "table", ",", "delimiter", "=", "'|'", ",", "bands", "=", "''", ",", "clean_up", "=", "True", ",", "rename_columns", "=", "{", "}", ",", "column_fill", "=", "{", "}", ",", "verbose", "=", "False", "...
Adds data to the specified database table. Column names must match table fields to insert, however order and completeness don't matter. Parameters ---------- data: str, array-like, astropy.table.Table The path to an ascii file, array-like object, or table. The first row or element must be the list of column names table: str The name of the table into which the data should be inserted delimiter: str The string to use as the delimiter when parsing the ascii file bands: sequence Sequence of band to look for in the data header when digesting columns of multiple photometric measurements (e.g. ['MKO_J','MKO_H','MKO_K']) into individual rows of data for database insertion clean_up: bool Run self.clean_up() rename_columns: dict A dictionary of the {input_col_name:desired_col_name} for table columns, e.g. {'e_Jmag':'J_unc', 'RAJ2000':'ra'} column_fill: dict A dictionary of the column name and value to fill, e.g. {'instrument_id':2, 'band':'2MASS.J'} verbose: bool Print diagnostic messages
[ "Adds", "data", "to", "the", "specified", "database", "table", ".", "Column", "names", "must", "match", "table", "fields", "to", "insert", "however", "order", "and", "completeness", "don", "t", "matter", ".", "Parameters", "----------", "data", ":", "str", "...
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L274-L478
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.add_foreign_key
def add_foreign_key(self, table, parent, key_child, key_parent, verbose=True): """ Add foreign key (**key_parent** from **parent**) to **table** column **key_child** Parameters ---------- table: string The name of the table to modify. This is the child table. parent: string or list of strings The name of the reference table. This is the parent table. key_child: string or list of strings Column in **table** to set as foreign key. This is the child key. key_parent: string or list of strings Column in **parent** that the foreign key refers to. This is the parent key. verbose: bool, optional Verbose output """ # Temporarily turn off foreign keys self.list('PRAGMA foreign_keys=OFF') metadata = self.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, required, pk = [np.array(metadata[n]) for n in ['name', 'type', 'notnull', 'pk']] # Set constraints constraints = [] for elem in required: if elem > 0: constraints.append('NOT NULL') else: constraints.append('') # Set PRIMARY KEY columns ind, = np.where(pk >= 1) for i in ind: constraints[i] += ' UNIQUE' # Add UNIQUE constraint to primary keys pk_names = columns[ind] try: # Rename the old table and create a new one self.list("DROP TABLE IF EXISTS TempOldTable_foreign") self.list("ALTER TABLE {0} RENAME TO TempOldTable_foreign".format(table)) # Re-create the table specifying the FOREIGN KEY sqltxt = "CREATE TABLE {0} (\n\t{1}".format(table, ', \n\t'.join(['{} {} {}'.format(c, t, r) for c, t, r in zip(columns, types, constraints)])) sqltxt += ', \n\tPRIMARY KEY({})'.format(', '.join([elem for elem in pk_names])) if isinstance(key_child, type(list())): for kc, p, kp in zip(key_child, parent, key_parent): sqltxt += ', \n\tFOREIGN KEY ({0}) REFERENCES {1} ({2}) ON UPDATE CASCADE'.format(kc, p, kp) else: sqltxt += ', \n\tFOREIGN KEY ({0}) REFERENCES {1} ({2}) ON UPDATE CASCADE'.format(key_child, parent, key_parent) sqltxt += ' \n)' self.list(sqltxt) # Populate the new table and drop the old one tempdata = self.query("PRAGMA table_info(TempOldTable_foreign)", fmt='table') old_columns = [c for c in tempdata['name'] if c in columns] self.list("INSERT INTO {0} ({1}) SELECT {1} FROM TempOldTable_foreign".format(table, ','.join(old_columns))) self.list("DROP TABLE TempOldTable_foreign") if verbose: # print('Successfully added foreign key.') t = self.query('SELECT name, sql FROM sqlite_master', fmt='table') # print(t[t['name'] == table]['sql'][0].replace(',', ',\n')) print(t[t['name'] == table]['sql'][0]) except: print('Error attempting to add foreign key.') self.list("DROP TABLE IF EXISTS {0}".format(table)) self.list("ALTER TABLE TempOldTable_foreign RENAME TO {0}".format(table)) raise sqlite3.IntegrityError('Failed to add foreign key') # Reactivate foreign keys self.list('PRAGMA foreign_keys=ON')
python
def add_foreign_key(self, table, parent, key_child, key_parent, verbose=True): """ Add foreign key (**key_parent** from **parent**) to **table** column **key_child** Parameters ---------- table: string The name of the table to modify. This is the child table. parent: string or list of strings The name of the reference table. This is the parent table. key_child: string or list of strings Column in **table** to set as foreign key. This is the child key. key_parent: string or list of strings Column in **parent** that the foreign key refers to. This is the parent key. verbose: bool, optional Verbose output """ # Temporarily turn off foreign keys self.list('PRAGMA foreign_keys=OFF') metadata = self.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, required, pk = [np.array(metadata[n]) for n in ['name', 'type', 'notnull', 'pk']] # Set constraints constraints = [] for elem in required: if elem > 0: constraints.append('NOT NULL') else: constraints.append('') # Set PRIMARY KEY columns ind, = np.where(pk >= 1) for i in ind: constraints[i] += ' UNIQUE' # Add UNIQUE constraint to primary keys pk_names = columns[ind] try: # Rename the old table and create a new one self.list("DROP TABLE IF EXISTS TempOldTable_foreign") self.list("ALTER TABLE {0} RENAME TO TempOldTable_foreign".format(table)) # Re-create the table specifying the FOREIGN KEY sqltxt = "CREATE TABLE {0} (\n\t{1}".format(table, ', \n\t'.join(['{} {} {}'.format(c, t, r) for c, t, r in zip(columns, types, constraints)])) sqltxt += ', \n\tPRIMARY KEY({})'.format(', '.join([elem for elem in pk_names])) if isinstance(key_child, type(list())): for kc, p, kp in zip(key_child, parent, key_parent): sqltxt += ', \n\tFOREIGN KEY ({0}) REFERENCES {1} ({2}) ON UPDATE CASCADE'.format(kc, p, kp) else: sqltxt += ', \n\tFOREIGN KEY ({0}) REFERENCES {1} ({2}) ON UPDATE CASCADE'.format(key_child, parent, key_parent) sqltxt += ' \n)' self.list(sqltxt) # Populate the new table and drop the old one tempdata = self.query("PRAGMA table_info(TempOldTable_foreign)", fmt='table') old_columns = [c for c in tempdata['name'] if c in columns] self.list("INSERT INTO {0} ({1}) SELECT {1} FROM TempOldTable_foreign".format(table, ','.join(old_columns))) self.list("DROP TABLE TempOldTable_foreign") if verbose: # print('Successfully added foreign key.') t = self.query('SELECT name, sql FROM sqlite_master', fmt='table') # print(t[t['name'] == table]['sql'][0].replace(',', ',\n')) print(t[t['name'] == table]['sql'][0]) except: print('Error attempting to add foreign key.') self.list("DROP TABLE IF EXISTS {0}".format(table)) self.list("ALTER TABLE TempOldTable_foreign RENAME TO {0}".format(table)) raise sqlite3.IntegrityError('Failed to add foreign key') # Reactivate foreign keys self.list('PRAGMA foreign_keys=ON')
[ "def", "add_foreign_key", "(", "self", ",", "table", ",", "parent", ",", "key_child", ",", "key_parent", ",", "verbose", "=", "True", ")", ":", "# Temporarily turn off foreign keys", "self", ".", "list", "(", "'PRAGMA foreign_keys=OFF'", ")", "metadata", "=", "s...
Add foreign key (**key_parent** from **parent**) to **table** column **key_child** Parameters ---------- table: string The name of the table to modify. This is the child table. parent: string or list of strings The name of the reference table. This is the parent table. key_child: string or list of strings Column in **table** to set as foreign key. This is the child key. key_parent: string or list of strings Column in **parent** that the foreign key refers to. This is the parent key. verbose: bool, optional Verbose output
[ "Add", "foreign", "key", "(", "**", "key_parent", "**", "from", "**", "parent", "**", ")", "to", "**", "table", "**", "column", "**", "key_child", "**" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L480-L555
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.clean_up
def clean_up(self, table, verbose=False): """ Removes exact duplicates, blank records or data without a *source_id* from the specified **table**. Then finds possible duplicates and prompts for conflict resolution. Parameters ---------- table: str The name of the table to remove duplicates, blanks, and data without source attributions. verbose: bool Print out some diagnostic messages """ # Get the table info and all the records metadata = self.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, required = [np.array(metadata[n]) for n in ['name', 'type', 'notnull']] # records = self.query("SELECT * FROM {}".format(table), fmt='table', use_converters=False) ignore = self.query("SELECT * FROM ignore WHERE tablename LIKE ?", (table,)) duplicate, command = [1], '' # Remove records with missing required values req_keys = columns[np.where(required)] try: self.modify("DELETE FROM {} WHERE {}".format(table, ' OR '.join([i + ' IS NULL' for i in req_keys])), verbose=False) self.modify( "DELETE FROM {} WHERE {}".format(table, ' OR '.join([i + " IN ('null','None','')" for i in req_keys])), verbose=False) except: pass # Remove exact duplicates self.modify("DELETE FROM {0} WHERE id NOT IN (SELECT min(id) FROM {0} GROUP BY {1})".format(table, ', '.join( columns[1:])), verbose=False) # Check for records with identical required values but different ids. if table.lower() != 'sources': req_keys = columns[np.where(np.logical_and(required, columns != 'id'))] # List of old and new pairs to ignore if not type(ignore) == np.ndarray: ignore = np.array([]) new_ignore = [] while any(duplicate): # Pull out duplicates one by one if 'source_id' not in columns: # Check if there is a source_id in the columns SQL = "SELECT t1.id, t2.id FROM {0} t1 JOIN {0} t2 ON t1.id=t2.id WHERE ".format(table) else: SQL = "SELECT t1.id, t2.id FROM {0} t1 JOIN {0} t2 ON t1.source_id=t2.source_id " \ "WHERE t1.id!=t2.id AND ".format(table) if any(req_keys): SQL += ' AND '.join(['t1.{0}=t2.{0}'.format(i) for i in req_keys]) + ' AND ' if any(ignore): SQL += ' AND '.join( ["(t1.id NOT IN ({0}) AND t2.id NOT IN ({0}))".format(','.join(map(str, [id1, id2]))) for id1, id2 in zip(ignore['id1'], ignore['id2'])] if any(ignore) else '') + ' AND ' if any(new_ignore): SQL += ' AND '.join( ["(t1.id NOT IN ({0}) AND t2.id NOT IN ({0}))".format(','.join(map(str, ni))) for ni in new_ignore] if new_ignore else '') + ' AND ' # Clean up empty WHERE at end if it's present (eg, for empty req_keys, ignore, and new_ignore) if SQL[-6:] == 'WHERE ': SQL = SQL[:-6] # Clean up hanging AND if present if SQL[-5:] == ' AND ': SQL = SQL[:-5] if verbose: print('\nSearching for duplicates with: {}\n'.format(SQL)) duplicate = self.query(SQL, fetch='one') # Compare potential duplicates and prompt user for action on each try: # Run record matches through comparison and return the command command = self._compare_records(table, duplicate) # Add acceptable duplicates to ignore list or abort if command == 'keep': new_ignore.append([duplicate[0], duplicate[1]]) self.list("INSERT INTO ignore VALUES(?,?,?,?)", (None, duplicate[0], duplicate[1], table.lower())) elif command == 'undo': pass # TODO: Add this functionality! elif command == 'abort': break else: pass except: break # Finish or abort table clean up if command == 'abort': print('\nAborted clean up of {} table.'.format(table.upper())) return 'abort' else: print('\nFinished clean up on {} table.'.format(table.upper()))
python
def clean_up(self, table, verbose=False): """ Removes exact duplicates, blank records or data without a *source_id* from the specified **table**. Then finds possible duplicates and prompts for conflict resolution. Parameters ---------- table: str The name of the table to remove duplicates, blanks, and data without source attributions. verbose: bool Print out some diagnostic messages """ # Get the table info and all the records metadata = self.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, required = [np.array(metadata[n]) for n in ['name', 'type', 'notnull']] # records = self.query("SELECT * FROM {}".format(table), fmt='table', use_converters=False) ignore = self.query("SELECT * FROM ignore WHERE tablename LIKE ?", (table,)) duplicate, command = [1], '' # Remove records with missing required values req_keys = columns[np.where(required)] try: self.modify("DELETE FROM {} WHERE {}".format(table, ' OR '.join([i + ' IS NULL' for i in req_keys])), verbose=False) self.modify( "DELETE FROM {} WHERE {}".format(table, ' OR '.join([i + " IN ('null','None','')" for i in req_keys])), verbose=False) except: pass # Remove exact duplicates self.modify("DELETE FROM {0} WHERE id NOT IN (SELECT min(id) FROM {0} GROUP BY {1})".format(table, ', '.join( columns[1:])), verbose=False) # Check for records with identical required values but different ids. if table.lower() != 'sources': req_keys = columns[np.where(np.logical_and(required, columns != 'id'))] # List of old and new pairs to ignore if not type(ignore) == np.ndarray: ignore = np.array([]) new_ignore = [] while any(duplicate): # Pull out duplicates one by one if 'source_id' not in columns: # Check if there is a source_id in the columns SQL = "SELECT t1.id, t2.id FROM {0} t1 JOIN {0} t2 ON t1.id=t2.id WHERE ".format(table) else: SQL = "SELECT t1.id, t2.id FROM {0} t1 JOIN {0} t2 ON t1.source_id=t2.source_id " \ "WHERE t1.id!=t2.id AND ".format(table) if any(req_keys): SQL += ' AND '.join(['t1.{0}=t2.{0}'.format(i) for i in req_keys]) + ' AND ' if any(ignore): SQL += ' AND '.join( ["(t1.id NOT IN ({0}) AND t2.id NOT IN ({0}))".format(','.join(map(str, [id1, id2]))) for id1, id2 in zip(ignore['id1'], ignore['id2'])] if any(ignore) else '') + ' AND ' if any(new_ignore): SQL += ' AND '.join( ["(t1.id NOT IN ({0}) AND t2.id NOT IN ({0}))".format(','.join(map(str, ni))) for ni in new_ignore] if new_ignore else '') + ' AND ' # Clean up empty WHERE at end if it's present (eg, for empty req_keys, ignore, and new_ignore) if SQL[-6:] == 'WHERE ': SQL = SQL[:-6] # Clean up hanging AND if present if SQL[-5:] == ' AND ': SQL = SQL[:-5] if verbose: print('\nSearching for duplicates with: {}\n'.format(SQL)) duplicate = self.query(SQL, fetch='one') # Compare potential duplicates and prompt user for action on each try: # Run record matches through comparison and return the command command = self._compare_records(table, duplicate) # Add acceptable duplicates to ignore list or abort if command == 'keep': new_ignore.append([duplicate[0], duplicate[1]]) self.list("INSERT INTO ignore VALUES(?,?,?,?)", (None, duplicate[0], duplicate[1], table.lower())) elif command == 'undo': pass # TODO: Add this functionality! elif command == 'abort': break else: pass except: break # Finish or abort table clean up if command == 'abort': print('\nAborted clean up of {} table.'.format(table.upper())) return 'abort' else: print('\nFinished clean up on {} table.'.format(table.upper()))
[ "def", "clean_up", "(", "self", ",", "table", ",", "verbose", "=", "False", ")", ":", "# Get the table info and all the records", "metadata", "=", "self", ".", "query", "(", "\"PRAGMA table_info({})\"", ".", "format", "(", "table", ")", ",", "fmt", "=", "'tabl...
Removes exact duplicates, blank records or data without a *source_id* from the specified **table**. Then finds possible duplicates and prompts for conflict resolution. Parameters ---------- table: str The name of the table to remove duplicates, blanks, and data without source attributions. verbose: bool Print out some diagnostic messages
[ "Removes", "exact", "duplicates", "blank", "records", "or", "data", "without", "a", "*", "source_id", "*", "from", "the", "specified", "**", "table", "**", ".", "Then", "finds", "possible", "duplicates", "and", "prompts", "for", "conflict", "resolution", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L557-L657
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.close
def close(self, silent=False): """ Close the database and ask to save and delete the file Parameters ---------- silent: bool Close quietly without saving or deleting (Default: False). """ if not silent: saveme = get_input("Save database contents to '{}/'? (y, [n]) \n" "To save elsewhere, run db.save() before closing. ".format(self.directory)) if saveme.lower() == 'y': self.save() delete = get_input("Do you want to delete {0}? (y,[n]) \n" "Don't worry, a new one will be generated if you run astrodb.Database('{1}') " .format(self.dbpath, self.sqlpath)) if delete.lower() == 'y': print("Deleting {}".format(self.dbpath)) os.system("rm {}".format(self.dbpath)) print('Closing connection') self.conn.close()
python
def close(self, silent=False): """ Close the database and ask to save and delete the file Parameters ---------- silent: bool Close quietly without saving or deleting (Default: False). """ if not silent: saveme = get_input("Save database contents to '{}/'? (y, [n]) \n" "To save elsewhere, run db.save() before closing. ".format(self.directory)) if saveme.lower() == 'y': self.save() delete = get_input("Do you want to delete {0}? (y,[n]) \n" "Don't worry, a new one will be generated if you run astrodb.Database('{1}') " .format(self.dbpath, self.sqlpath)) if delete.lower() == 'y': print("Deleting {}".format(self.dbpath)) os.system("rm {}".format(self.dbpath)) print('Closing connection') self.conn.close()
[ "def", "close", "(", "self", ",", "silent", "=", "False", ")", ":", "if", "not", "silent", ":", "saveme", "=", "get_input", "(", "\"Save database contents to '{}/'? (y, [n]) \\n\"", "\"To save elsewhere, run db.save() before closing. \"", ".", "format", "(", "self", "...
Close the database and ask to save and delete the file Parameters ---------- silent: bool Close quietly without saving or deleting (Default: False).
[ "Close", "the", "database", "and", "ask", "to", "save", "and", "delete", "the", "file" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L660-L683
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database._compare_records
def _compare_records(self, table, duplicate, options=['r', 'c', 'k', 'sql']): """ Compares similar records and prompts the user to make decisions about keeping, updating, or modifying records in question. Parameters ---------- table: str The name of the table whose records are being compared. duplicate: sequence The ids of the potentially duplicate records options: list The allowed options: 'r' for replace, 'c' for complete, 'k' for keep, 'sql' for raw SQL input. """ # print the old and new records suspected of being duplicates verbose = True if duplicate[0] == duplicate[1]: # No need to display if no duplicates were found verbose = False data = self.query("SELECT * FROM {} WHERE id IN ({})".format(table, ','.join(map(str, duplicate))), \ fmt='table', verbose=verbose, use_converters=False) columns = data.colnames[1:] old, new = [[data[n][k] for k in columns[1:]] for n in [0, 1]] # Prompt the user for action replace = get_input( "\nKeep both records [k]? Or replace [r], complete [c], or keep only [Press *Enter*] record {}? (Type column name to inspect or 'help' for options): ".format( duplicate[0])).lower() replace = replace.strip() while replace in columns or replace == 'help': if replace in columns: pprint(np.asarray([[i for idx, i in enumerate(old) if idx in [0, columns.index(replace)]], \ [i for idx, i in enumerate(new) if idx in [0, columns.index(replace)]]]), \ names=['id', replace]) elif replace == 'help': _help() replace = get_input( "\nKeep both records [k]? Or replace [r], complete [c], or keep only [Press *Enter*] record {}? (Type column name to inspect or 'help' for options): ".format( duplicate[0])).lower() if replace and replace.split()[0] in options: # Replace the entire old record with the new record if replace == 'r': sure = get_input( 'Are you sure you want to replace record {} with record {}? [y/n] : '.format(*duplicate)) if sure.lower() == 'y': self.modify("DELETE FROM {} WHERE id={}".format(table, duplicate[0]), verbose=False) self.modify("UPDATE {} SET id={} WHERE id={}".format(table, duplicate[0], duplicate[1]), verbose=False) # Replace specific columns elif replace.startswith('r'): replace_cols = replace.split()[1:] if all([i in columns for i in replace_cols]): empty_cols, new_vals = zip( *[['{}=?'.format(e), n] for e, n in zip(columns, new) if e in replace_cols]) if empty_cols: self.modify("DELETE FROM {} WHERE id={}".format(table, duplicate[1]), verbose=False) self.modify("UPDATE {} SET {} WHERE id={}".format(table, ','.join(empty_cols), duplicate[0]), tuple(new_vals), verbose=False) else: badcols = ','.join([i for i in replace_cols if i not in columns]) print("\nInvalid column names for {} table: {}".format(table, badcols)) # Complete the old record with any missing data provided in the new record, then delete the new record elif replace == 'c': try: empty_cols, new_vals = zip( *[['{}=?'.format(e), n] for e, o, n in zip(columns[1:], old, new) if n and not o]) self.modify("DELETE FROM {} WHERE id={}".format(table, duplicate[1]), verbose=False) self.modify("UPDATE {} SET {} WHERE id={}".format(table, ','.join(empty_cols), duplicate[0]), tuple(new_vals), verbose=False) except: pass # Keep both records elif replace == 'k': return 'keep' # Execute raw SQL elif replace.startswith('sql') and 'sql' in options: self.modify(replace[4:], verbose=False) # Abort the current database clean up elif replace == 'abort': return 'abort' # Delete the higher id record elif not replace: self.modify("DELETE FROM {} WHERE id={}".format(table, max(duplicate)), verbose=False) # Prompt again else: print("\nInvalid command: {}\nTry again or type 'help' or 'abort'.\n".format(replace))
python
def _compare_records(self, table, duplicate, options=['r', 'c', 'k', 'sql']): """ Compares similar records and prompts the user to make decisions about keeping, updating, or modifying records in question. Parameters ---------- table: str The name of the table whose records are being compared. duplicate: sequence The ids of the potentially duplicate records options: list The allowed options: 'r' for replace, 'c' for complete, 'k' for keep, 'sql' for raw SQL input. """ # print the old and new records suspected of being duplicates verbose = True if duplicate[0] == duplicate[1]: # No need to display if no duplicates were found verbose = False data = self.query("SELECT * FROM {} WHERE id IN ({})".format(table, ','.join(map(str, duplicate))), \ fmt='table', verbose=verbose, use_converters=False) columns = data.colnames[1:] old, new = [[data[n][k] for k in columns[1:]] for n in [0, 1]] # Prompt the user for action replace = get_input( "\nKeep both records [k]? Or replace [r], complete [c], or keep only [Press *Enter*] record {}? (Type column name to inspect or 'help' for options): ".format( duplicate[0])).lower() replace = replace.strip() while replace in columns or replace == 'help': if replace in columns: pprint(np.asarray([[i for idx, i in enumerate(old) if idx in [0, columns.index(replace)]], \ [i for idx, i in enumerate(new) if idx in [0, columns.index(replace)]]]), \ names=['id', replace]) elif replace == 'help': _help() replace = get_input( "\nKeep both records [k]? Or replace [r], complete [c], or keep only [Press *Enter*] record {}? (Type column name to inspect or 'help' for options): ".format( duplicate[0])).lower() if replace and replace.split()[0] in options: # Replace the entire old record with the new record if replace == 'r': sure = get_input( 'Are you sure you want to replace record {} with record {}? [y/n] : '.format(*duplicate)) if sure.lower() == 'y': self.modify("DELETE FROM {} WHERE id={}".format(table, duplicate[0]), verbose=False) self.modify("UPDATE {} SET id={} WHERE id={}".format(table, duplicate[0], duplicate[1]), verbose=False) # Replace specific columns elif replace.startswith('r'): replace_cols = replace.split()[1:] if all([i in columns for i in replace_cols]): empty_cols, new_vals = zip( *[['{}=?'.format(e), n] for e, n in zip(columns, new) if e in replace_cols]) if empty_cols: self.modify("DELETE FROM {} WHERE id={}".format(table, duplicate[1]), verbose=False) self.modify("UPDATE {} SET {} WHERE id={}".format(table, ','.join(empty_cols), duplicate[0]), tuple(new_vals), verbose=False) else: badcols = ','.join([i for i in replace_cols if i not in columns]) print("\nInvalid column names for {} table: {}".format(table, badcols)) # Complete the old record with any missing data provided in the new record, then delete the new record elif replace == 'c': try: empty_cols, new_vals = zip( *[['{}=?'.format(e), n] for e, o, n in zip(columns[1:], old, new) if n and not o]) self.modify("DELETE FROM {} WHERE id={}".format(table, duplicate[1]), verbose=False) self.modify("UPDATE {} SET {} WHERE id={}".format(table, ','.join(empty_cols), duplicate[0]), tuple(new_vals), verbose=False) except: pass # Keep both records elif replace == 'k': return 'keep' # Execute raw SQL elif replace.startswith('sql') and 'sql' in options: self.modify(replace[4:], verbose=False) # Abort the current database clean up elif replace == 'abort': return 'abort' # Delete the higher id record elif not replace: self.modify("DELETE FROM {} WHERE id={}".format(table, max(duplicate)), verbose=False) # Prompt again else: print("\nInvalid command: {}\nTry again or type 'help' or 'abort'.\n".format(replace))
[ "def", "_compare_records", "(", "self", ",", "table", ",", "duplicate", ",", "options", "=", "[", "'r'", ",", "'c'", ",", "'k'", ",", "'sql'", "]", ")", ":", "# print the old and new records suspected of being duplicates", "verbose", "=", "True", "if", "duplicat...
Compares similar records and prompts the user to make decisions about keeping, updating, or modifying records in question. Parameters ---------- table: str The name of the table whose records are being compared. duplicate: sequence The ids of the potentially duplicate records options: list The allowed options: 'r' for replace, 'c' for complete, 'k' for keep, 'sql' for raw SQL input.
[ "Compares", "similar", "records", "and", "prompts", "the", "user", "to", "make", "decisions", "about", "keeping", "updating", "or", "modifying", "records", "in", "question", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L685-L782
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database._explicit_query
def _explicit_query(self, SQL, use_converters=True): """ Sorts the column names so they are returned in the same order they are queried. Also turns ambiguous SELECT statements into explicit SQLite language in case column names are not unique. HERE BE DRAGONS!!! Bad bad bad. This method needs to be reworked. Parameters ---------- SQL: str The SQLite query to parse use_converters: bool Apply converters to columns with custom data types Returns ------- (SQL, columns): (str, sequence) The new SQLite string to use in the query and the ordered column names """ try: # If field names are given, sort so that they come out in the same order they are fetched if 'select' in SQL.lower() and 'from' in SQL.lower(): # Make a dictionary of the table aliases tdict = {} from_clause = SQL.lower().split('from ')[-1].split(' where')[0] tables = [j for k in [i.split(' on ') for i in from_clause.split(' join ')] for j in k if '=' not in j] for t in tables: t = t.replace('as', '') try: name, alias = t.split() tdict[alias] = name except: tdict[t] = t # Get all the column names and dtype placeholders columns = \ SQL.replace(' ', '').lower().split('distinct' if 'distinct' in SQL.lower() else 'select')[1].split( 'from')[0].split(',') # Replace * with the field names for n, col in enumerate(columns): if '.' in col: t, col = col.split('.') else: t = tables[0] if '*' in col: col = np.array(self.list("PRAGMA table_info({})".format(tdict.get(t))).fetchall()).T[1] else: col = [col] columns[n] = ["{}.{}".format(t, c) if len(tables) > 1 else c for c in col] # Flatten the list of columns and dtypes columns = [j for k in columns for j in k] # Get the dtypes dSQL = "SELECT " \ + ','.join(["typeof({})".format(col) for col in columns]) \ + ' FROM ' + SQL.replace('from', 'FROM').split('FROM')[-1] if use_converters: dtypes = [None] * len(columns) else: dtypes = self.list(dSQL).fetchone() # Reconstruct SQL query SQL = "SELECT {}".format('DISTINCT ' if 'distinct' in SQL.lower() else '') \ + (','.join(["{0} AS '{0}'".format(col) for col in columns]) \ if use_converters else ','.join(["{1}{0}{2} AS '{0}'".format(col, 'CAST(' if dt != 'null' else '', ' AS {})'.format( dt) if dt != 'null' else '') \ for dt, col in zip(dtypes, columns)])) \ + ' FROM ' \ + SQL.replace('from', 'FROM').split('FROM')[-1] elif 'pragma' in SQL.lower(): columns = ['cid', 'name', 'type', 'notnull', 'dflt_value', 'pk'] return SQL, columns except: return SQL, ''
python
def _explicit_query(self, SQL, use_converters=True): """ Sorts the column names so they are returned in the same order they are queried. Also turns ambiguous SELECT statements into explicit SQLite language in case column names are not unique. HERE BE DRAGONS!!! Bad bad bad. This method needs to be reworked. Parameters ---------- SQL: str The SQLite query to parse use_converters: bool Apply converters to columns with custom data types Returns ------- (SQL, columns): (str, sequence) The new SQLite string to use in the query and the ordered column names """ try: # If field names are given, sort so that they come out in the same order they are fetched if 'select' in SQL.lower() and 'from' in SQL.lower(): # Make a dictionary of the table aliases tdict = {} from_clause = SQL.lower().split('from ')[-1].split(' where')[0] tables = [j for k in [i.split(' on ') for i in from_clause.split(' join ')] for j in k if '=' not in j] for t in tables: t = t.replace('as', '') try: name, alias = t.split() tdict[alias] = name except: tdict[t] = t # Get all the column names and dtype placeholders columns = \ SQL.replace(' ', '').lower().split('distinct' if 'distinct' in SQL.lower() else 'select')[1].split( 'from')[0].split(',') # Replace * with the field names for n, col in enumerate(columns): if '.' in col: t, col = col.split('.') else: t = tables[0] if '*' in col: col = np.array(self.list("PRAGMA table_info({})".format(tdict.get(t))).fetchall()).T[1] else: col = [col] columns[n] = ["{}.{}".format(t, c) if len(tables) > 1 else c for c in col] # Flatten the list of columns and dtypes columns = [j for k in columns for j in k] # Get the dtypes dSQL = "SELECT " \ + ','.join(["typeof({})".format(col) for col in columns]) \ + ' FROM ' + SQL.replace('from', 'FROM').split('FROM')[-1] if use_converters: dtypes = [None] * len(columns) else: dtypes = self.list(dSQL).fetchone() # Reconstruct SQL query SQL = "SELECT {}".format('DISTINCT ' if 'distinct' in SQL.lower() else '') \ + (','.join(["{0} AS '{0}'".format(col) for col in columns]) \ if use_converters else ','.join(["{1}{0}{2} AS '{0}'".format(col, 'CAST(' if dt != 'null' else '', ' AS {})'.format( dt) if dt != 'null' else '') \ for dt, col in zip(dtypes, columns)])) \ + ' FROM ' \ + SQL.replace('from', 'FROM').split('FROM')[-1] elif 'pragma' in SQL.lower(): columns = ['cid', 'name', 'type', 'notnull', 'dflt_value', 'pk'] return SQL, columns except: return SQL, ''
[ "def", "_explicit_query", "(", "self", ",", "SQL", ",", "use_converters", "=", "True", ")", ":", "try", ":", "# If field names are given, sort so that they come out in the same order they are fetched", "if", "'select'", "in", "SQL", ".", "lower", "(", ")", "and", "'fr...
Sorts the column names so they are returned in the same order they are queried. Also turns ambiguous SELECT statements into explicit SQLite language in case column names are not unique. HERE BE DRAGONS!!! Bad bad bad. This method needs to be reworked. Parameters ---------- SQL: str The SQLite query to parse use_converters: bool Apply converters to columns with custom data types Returns ------- (SQL, columns): (str, sequence) The new SQLite string to use in the query and the ordered column names
[ "Sorts", "the", "column", "names", "so", "they", "are", "returned", "in", "the", "same", "order", "they", "are", "queried", ".", "Also", "turns", "ambiguous", "SELECT", "statements", "into", "explicit", "SQLite", "language", "in", "case", "column", "names", ...
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L784-L869
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.get_bibtex
def get_bibtex(self, id, fetch=False, table='publications'): """ Grab bibtex entry from NASA ADS Parameters ---------- id: int or str The id or shortname from the PUBLICATIONS table to search fetch: bool Whether or not to return the bibtex string in addition to printing (default: False) table: str Table name, defaults to publications Returns ------- bibtex: str If fetch=True, return the bibtex string """ import requests bibcode_name = 'bibcode' if isinstance(id, type(1)): bibcode = self.query("SELECT {} FROM {} WHERE id={}".format(bibcode_name, table, id), fetch='one') else: bibcode = self.query("SELECT {} FROM {} WHERE shortname='{}'".format(bibcode_name, table, id), fetch='one') # Check for empty bibcodes if isinstance(bibcode, type(None)): print('No bibcode for {}'.format(id)) return bibcode = bibcode[0] if bibcode == '': print('No bibcode for {}'.format(id)) return # Construct URL and grab data url = 'http://adsabs.harvard.edu/cgi-bin/nph-bib_query?bibcode={}&data_type=BIBTEX&db_key=AST&nocookieset=1'.\ format(bibcode) try: r = requests.get(url) except Exception as ex: print('Error accessing url {}'.format(url)) print(ex.message) return # Check status and display results if r.status_code == 200: ind = r.content.find(b'@') print(r.content[ind:].strip().decode('utf-8')) if fetch: return r.content[ind:].strip() else: print('Error getting bibtex') return
python
def get_bibtex(self, id, fetch=False, table='publications'): """ Grab bibtex entry from NASA ADS Parameters ---------- id: int or str The id or shortname from the PUBLICATIONS table to search fetch: bool Whether or not to return the bibtex string in addition to printing (default: False) table: str Table name, defaults to publications Returns ------- bibtex: str If fetch=True, return the bibtex string """ import requests bibcode_name = 'bibcode' if isinstance(id, type(1)): bibcode = self.query("SELECT {} FROM {} WHERE id={}".format(bibcode_name, table, id), fetch='one') else: bibcode = self.query("SELECT {} FROM {} WHERE shortname='{}'".format(bibcode_name, table, id), fetch='one') # Check for empty bibcodes if isinstance(bibcode, type(None)): print('No bibcode for {}'.format(id)) return bibcode = bibcode[0] if bibcode == '': print('No bibcode for {}'.format(id)) return # Construct URL and grab data url = 'http://adsabs.harvard.edu/cgi-bin/nph-bib_query?bibcode={}&data_type=BIBTEX&db_key=AST&nocookieset=1'.\ format(bibcode) try: r = requests.get(url) except Exception as ex: print('Error accessing url {}'.format(url)) print(ex.message) return # Check status and display results if r.status_code == 200: ind = r.content.find(b'@') print(r.content[ind:].strip().decode('utf-8')) if fetch: return r.content[ind:].strip() else: print('Error getting bibtex') return
[ "def", "get_bibtex", "(", "self", ",", "id", ",", "fetch", "=", "False", ",", "table", "=", "'publications'", ")", ":", "import", "requests", "bibcode_name", "=", "'bibcode'", "if", "isinstance", "(", "id", ",", "type", "(", "1", ")", ")", ":", "bibcod...
Grab bibtex entry from NASA ADS Parameters ---------- id: int or str The id or shortname from the PUBLICATIONS table to search fetch: bool Whether or not to return the bibtex string in addition to printing (default: False) table: str Table name, defaults to publications Returns ------- bibtex: str If fetch=True, return the bibtex string
[ "Grab", "bibtex", "entry", "from", "NASA", "ADS" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L871-L927
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.info
def info(self): """ Prints out information for the loaded database, namely the available tables and the number of entries for each. """ t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() print('\nDatabase path: {} \nSQL path: {}\n'.format(self.dbpath, self.sqlpath)) print('Database Inventory') print('==================') for table in ['sources'] + [t for t in all_tables if t not in ['sources', 'sqlite_sequence']]: x = self.query('select count() from {}'.format(table), fmt='array', fetch='one') if x is None: continue print('{}: {}'.format(table.upper(), x[0]))
python
def info(self): """ Prints out information for the loaded database, namely the available tables and the number of entries for each. """ t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() print('\nDatabase path: {} \nSQL path: {}\n'.format(self.dbpath, self.sqlpath)) print('Database Inventory') print('==================') for table in ['sources'] + [t for t in all_tables if t not in ['sources', 'sqlite_sequence']]: x = self.query('select count() from {}'.format(table), fmt='array', fetch='one') if x is None: continue print('{}: {}'.format(table.upper(), x[0]))
[ "def", "info", "(", "self", ")", ":", "t", "=", "self", ".", "query", "(", "\"SELECT * FROM sqlite_master WHERE type='table'\"", ",", "fmt", "=", "'table'", ")", "all_tables", "=", "t", "[", "'name'", "]", ".", "tolist", "(", ")", "print", "(", "'\\nDataba...
Prints out information for the loaded database, namely the available tables and the number of entries for each.
[ "Prints", "out", "information", "for", "the", "loaded", "database", "namely", "the", "available", "tables", "and", "the", "number", "of", "entries", "for", "each", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L957-L970
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.inventory
def inventory(self, source_id, fetch=False, fmt='table'): """ Prints a summary of all objects in the database. Input string or list of strings in **ID** or **unum** for specific objects. Parameters ---------- source_id: int The id from the SOURCES table whose data across all tables is to be printed. fetch: bool Return the results. fmt: str Returns the data as a dictionary, array, or astropy.table given 'dict', 'array', or 'table' Returns ------- data_tables: dict Returns a dictionary of astropy tables with the table name as the keys. """ data_tables = {} t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() for table in ['sources'] + [t for t in all_tables if t not in ['sources', 'sqlite_sequence']]: try: # Get the columns, pull out redundant ones, and query the table for this source's data t = self.query("PRAGMA table_info({})".format(table), fmt='table') columns = np.array(t['name']) types = np.array(t['type']) if table == 'sources' or 'source_id' in columns: # If printing, only get simple data types and exclude redundant 'source_id' for nicer printing if not fetch: columns = columns[ ((types == 'REAL') | (types == 'INTEGER') | (types == 'TEXT')) & (columns != 'source_id')] # Query the table try: id = 'id' if table.lower() == 'sources' else 'source_id' data = self.query( "SELECT {} FROM {} WHERE {}={}".format(','.join(columns), table, id, source_id), fmt='table') if not data and table.lower() == 'sources': print( 'No source with id {}. Try db.search() to search the database for a source_id.'.format( source_id)) except: data = None # If there's data for this table, save it if data: if fetch: data_tables[table] = self.query( "SELECT {} FROM {} WHERE {}={}".format(','.join(columns), table, id, source_id), \ fetch=True, fmt=fmt) else: data = data[[c.lower() for c in columns]] pprint(data, title=table.upper()) else: pass except: print('Could not retrieve data from {} table.'.format(table.upper())) if fetch: return data_tables
python
def inventory(self, source_id, fetch=False, fmt='table'): """ Prints a summary of all objects in the database. Input string or list of strings in **ID** or **unum** for specific objects. Parameters ---------- source_id: int The id from the SOURCES table whose data across all tables is to be printed. fetch: bool Return the results. fmt: str Returns the data as a dictionary, array, or astropy.table given 'dict', 'array', or 'table' Returns ------- data_tables: dict Returns a dictionary of astropy tables with the table name as the keys. """ data_tables = {} t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() for table in ['sources'] + [t for t in all_tables if t not in ['sources', 'sqlite_sequence']]: try: # Get the columns, pull out redundant ones, and query the table for this source's data t = self.query("PRAGMA table_info({})".format(table), fmt='table') columns = np.array(t['name']) types = np.array(t['type']) if table == 'sources' or 'source_id' in columns: # If printing, only get simple data types and exclude redundant 'source_id' for nicer printing if not fetch: columns = columns[ ((types == 'REAL') | (types == 'INTEGER') | (types == 'TEXT')) & (columns != 'source_id')] # Query the table try: id = 'id' if table.lower() == 'sources' else 'source_id' data = self.query( "SELECT {} FROM {} WHERE {}={}".format(','.join(columns), table, id, source_id), fmt='table') if not data and table.lower() == 'sources': print( 'No source with id {}. Try db.search() to search the database for a source_id.'.format( source_id)) except: data = None # If there's data for this table, save it if data: if fetch: data_tables[table] = self.query( "SELECT {} FROM {} WHERE {}={}".format(','.join(columns), table, id, source_id), \ fetch=True, fmt=fmt) else: data = data[[c.lower() for c in columns]] pprint(data, title=table.upper()) else: pass except: print('Could not retrieve data from {} table.'.format(table.upper())) if fetch: return data_tables
[ "def", "inventory", "(", "self", ",", "source_id", ",", "fetch", "=", "False", ",", "fmt", "=", "'table'", ")", ":", "data_tables", "=", "{", "}", "t", "=", "self", ".", "query", "(", "\"SELECT * FROM sqlite_master WHERE type='table'\"", ",", "fmt", "=", "...
Prints a summary of all objects in the database. Input string or list of strings in **ID** or **unum** for specific objects. Parameters ---------- source_id: int The id from the SOURCES table whose data across all tables is to be printed. fetch: bool Return the results. fmt: str Returns the data as a dictionary, array, or astropy.table given 'dict', 'array', or 'table' Returns ------- data_tables: dict Returns a dictionary of astropy tables with the table name as the keys.
[ "Prints", "a", "summary", "of", "all", "objects", "in", "the", "database", ".", "Input", "string", "or", "list", "of", "strings", "in", "**", "ID", "**", "or", "**", "unum", "**", "for", "specific", "objects", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L972-L1044
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.lookup
def lookup(self, criteria, table, columns=''): """ Returns a table of records from *table* the same length as *criteria* with the best match for each element. Parameters ---------- criteria: sequence The search criteria table: str The table to search columns: sequence The column name in the sources table to search Returns ------- results: sequence A sequence the same length as objlist with source_ids that correspond to successful matches and blanks where no matches could be made """ results, colmasks = [], [] # Iterate through the list, trying to match objects for n,criterion in enumerate(criteria): records = self.search(criterion, table, columns=columns, fetch=True) # If multiple matches, take the first but notify the user of the other matches if len(records)>1: print("'{}' matched to {} other record{}.".format(criterion, len(records)-1, \ 's' if len(records)-1>1 else '')) # If no matches, make an empty row if len(records)==0: records.add_row(np.asarray(np.zeros(len(records.colnames))).T) colmasks.append([True]*len(records.colnames)) else: colmasks.append([False]*len(records.colnames)) # Grab the first row results.append(records[0]) # Add all the rows to the results table table = at.Table(rows=results, names=results[0].colnames, masked=True) # Mask the rows with no matches for col,msk in zip(records.colnames,np.asarray(colmasks).T): table[col].mask = msk return table
python
def lookup(self, criteria, table, columns=''): """ Returns a table of records from *table* the same length as *criteria* with the best match for each element. Parameters ---------- criteria: sequence The search criteria table: str The table to search columns: sequence The column name in the sources table to search Returns ------- results: sequence A sequence the same length as objlist with source_ids that correspond to successful matches and blanks where no matches could be made """ results, colmasks = [], [] # Iterate through the list, trying to match objects for n,criterion in enumerate(criteria): records = self.search(criterion, table, columns=columns, fetch=True) # If multiple matches, take the first but notify the user of the other matches if len(records)>1: print("'{}' matched to {} other record{}.".format(criterion, len(records)-1, \ 's' if len(records)-1>1 else '')) # If no matches, make an empty row if len(records)==0: records.add_row(np.asarray(np.zeros(len(records.colnames))).T) colmasks.append([True]*len(records.colnames)) else: colmasks.append([False]*len(records.colnames)) # Grab the first row results.append(records[0]) # Add all the rows to the results table table = at.Table(rows=results, names=results[0].colnames, masked=True) # Mask the rows with no matches for col,msk in zip(records.colnames,np.asarray(colmasks).T): table[col].mask = msk return table
[ "def", "lookup", "(", "self", ",", "criteria", ",", "table", ",", "columns", "=", "''", ")", ":", "results", ",", "colmasks", "=", "[", "]", ",", "[", "]", "# Iterate through the list, trying to match objects", "for", "n", ",", "criterion", "in", "enumerate"...
Returns a table of records from *table* the same length as *criteria* with the best match for each element. Parameters ---------- criteria: sequence The search criteria table: str The table to search columns: sequence The column name in the sources table to search Returns ------- results: sequence A sequence the same length as objlist with source_ids that correspond to successful matches and blanks where no matches could be made
[ "Returns", "a", "table", "of", "records", "from", "*", "table", "*", "the", "same", "length", "as", "*", "criteria", "*", "with", "the", "best", "match", "for", "each", "element", ".", "Parameters", "----------", "criteria", ":", "sequence", "The", "search...
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1046-L1094
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database._lowest_rowids
def _lowest_rowids(self, table, limit): """ Gets the lowest available row ids for table insertion. Keeps things tidy! Parameters ---------- table: str The name of the table being modified limit: int The number of row ids needed Returns ------- available: sequence An array of all available row ids """ try: t = self.query("SELECT id FROM {}".format(table), unpack=True, fmt='table') ids = t['id'] all_ids = np.array(range(1, max(ids))) except TypeError: ids = None all_ids = np.array(range(1, limit+1)) available = all_ids[np.in1d(all_ids, ids, assume_unique=True, invert=True)][:limit] # If there aren't enough empty row ids, start using the new ones if len(available) < limit: diff = limit - len(available) available = np.concatenate((available, np.array(range(max(ids) + 1, max(ids) + 1 + diff)))) return available
python
def _lowest_rowids(self, table, limit): """ Gets the lowest available row ids for table insertion. Keeps things tidy! Parameters ---------- table: str The name of the table being modified limit: int The number of row ids needed Returns ------- available: sequence An array of all available row ids """ try: t = self.query("SELECT id FROM {}".format(table), unpack=True, fmt='table') ids = t['id'] all_ids = np.array(range(1, max(ids))) except TypeError: ids = None all_ids = np.array(range(1, limit+1)) available = all_ids[np.in1d(all_ids, ids, assume_unique=True, invert=True)][:limit] # If there aren't enough empty row ids, start using the new ones if len(available) < limit: diff = limit - len(available) available = np.concatenate((available, np.array(range(max(ids) + 1, max(ids) + 1 + diff)))) return available
[ "def", "_lowest_rowids", "(", "self", ",", "table", ",", "limit", ")", ":", "try", ":", "t", "=", "self", ".", "query", "(", "\"SELECT id FROM {}\"", ".", "format", "(", "table", ")", ",", "unpack", "=", "True", ",", "fmt", "=", "'table'", ")", "ids"...
Gets the lowest available row ids for table insertion. Keeps things tidy! Parameters ---------- table: str The name of the table being modified limit: int The number of row ids needed Returns ------- available: sequence An array of all available row ids
[ "Gets", "the", "lowest", "available", "row", "ids", "for", "table", "insertion", ".", "Keeps", "things", "tidy!" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1096-L1128
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.merge
def merge(self, conflicted, tables=[], diff_only=True): """ Merges specific **tables** or all tables of **conflicted** database into the master database. Parameters ---------- conflicted: str The path of the SQL database to be merged into the master. tables: list (optional) The list of tables to merge. If None, all tables are merged. diff_only: bool If True, only prints the differences of each table and doesn't actually merge anything. """ if os.path.isfile(conflicted): # Load and attach master and conflicted databases con, master, reassign = Database(conflicted), self.list("PRAGMA database_list").fetchall()[0][2], {} con.modify("ATTACH DATABASE '{}' AS m".format(master), verbose=False) self.modify("ATTACH DATABASE '{}' AS c".format(conflicted), verbose=False) con.modify("ATTACH DATABASE '{}' AS c".format(conflicted), verbose=False) self.modify("ATTACH DATABASE '{}' AS m".format(master), verbose=False) # Drop any backup tables from failed merges for table in tables: self.modify("DROP TABLE IF EXISTS Backup_{0}".format(table), verbose=False) # Gather user data to add to CHANGELOG table import socket, datetime if not diff_only: user = get_input('Please enter your name : ') machine_name = socket.gethostname() date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") modified_tables = [] # Merge table by table, starting with SOURCES if not isinstance(tables, type(list())): tables = [tables] tables = tables or ['sources'] + [t for t in zip(*self.list( "SELECT * FROM sqlite_master WHERE name NOT LIKE '%Backup%' AND name!='sqlite_sequence' AND type='table'{}".format( " AND name IN ({})".format("'" + "','".join(tables) + "'") if tables else '')))[1] if t != 'sources'] for table in tables: # Get column names and data types from master table and column names from conflicted table metadata = self.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, constraints = [np.array(metadata[n]) for n in ['name', 'type', 'notnull']] # columns, types, constraints = self.query("PRAGMA table_info({})".format(table), unpack=True)[1:4] conflicted_cols = con.query("PRAGMA table_info({})".format(table), unpack=True)[1] if any([i not in columns for i in conflicted_cols]): # Abort table merge if conflicted has new columns not present in master. New columns must be added to the master database first via db.edit_columns(). print( "\nMerge of {0} table aborted since conflicted copy has columns {1} not present in master.\nAdd new columns to master with astrodb.table() method and try again.\n".format( table.upper(), [i for i in conflicted_cols if i not in columns])) else: # Add new columns from master table to conflicted table if necessary if any([i not in conflicted_cols for i in columns]): con.modify("DROP TABLE IF EXISTS Conflicted_{0}".format(table)) con.modify("ALTER TABLE {0} RENAME TO Conflicted_{0}".format(table)) # TODO: Update to allow multiple primary and foreign keys con.modify("CREATE TABLE {0} ({1})".format(table, ', '.join( \ ['{} {} {}{}'.format(c, t, r, ' UNIQUE PRIMARY KEY' if c == 'id' else '') \ for c, t, r in zip(columns, types, constraints * ['NOT NULL'])]))) con.modify("INSERT INTO {0} ({1}) SELECT {1} FROM Conflicted_{0}".format(table, ','.join( conflicted_cols))) con.modify("DROP TABLE Conflicted_{0}".format(table)) # Pull unique records from conflicted table data = map(list, con.list( "SELECT * FROM (SELECT 1 AS db, {0} FROM m.{2} UNION ALL SELECT 2 AS db, {0} FROM c.{2}) GROUP BY {1} HAVING COUNT(*)=1 AND db=2".format( ','.join(columns), ','.join(columns[1:]), table)).fetchall()) if data: # Just print the table differences if diff_only: pprint(zip(*data)[1:], names=columns, title='New {} records'.format(table.upper())) # Add new records to the master and then clean up tables else: # Make temporary table copy so changes can be undone at any time self.modify("DROP TABLE IF EXISTS Backup_{0}".format(table), verbose=False) self.modify("ALTER TABLE {0} RENAME TO Backup_{0}".format(table), verbose=False) self.modify("CREATE TABLE {0} ({1})".format(table, ', '.join( \ ['{} {} {}{}'.format(c, t, r, ' UNIQUE PRIMARY KEY' if c == 'id' else '') \ for c, t, r in zip(columns, types, constraints * ['NOT NULL'])])), verbose=False) self.modify( "INSERT INTO {0} ({1}) SELECT {1} FROM Backup_{0}".format(table, ','.join(columns)), verbose=False) # Create a dictionary of any reassigned ids from merged SOURCES tables and replace applicable source_ids in other tables. print("\nMerging {} tables.\n".format(table.upper())) try: count = self.query("SELECT MAX(id) FROM {}".format(table), fetch='one')[0] + 1 except TypeError: count = 1 for n, i in enumerate([d[1:] for d in data]): if table == 'sources': reassign[i[0]] = count elif 'source_id' in columns and i[1] in reassign.keys(): i[1] = reassign[i[1]] else: pass i[0] = count data[n] = i count += 1 # Insert unique records into master for d in data: self.modify( "INSERT INTO {} VALUES({})".format(table, ','.join(['?' for c in columns])), d, verbose=False) pprint(zip(*data), names=columns, title="{} records added to {} table at '{}':".format(len(data), table, master)) # Run clean_up on the table to check for conflicts abort = self.clean_up(table) # Undo all changes to table if merge is aborted. Otherwise, push table changes to master. if abort: self.modify("DROP TABLE {0}".format(table), verbose=False) self.modify("ALTER TABLE Backup_{0} RENAME TO {0}".format(table), verbose=False) else: self.modify("DROP TABLE Backup_{0}".format(table), verbose=False) modified_tables.append(table.upper()) else: print("\n{} tables identical.".format(table.upper())) # Add data to CHANGELOG table if not diff_only: user_description = get_input('\nPlease describe the changes made in this merge: ') self.list("INSERT INTO changelog VALUES(?, ?, ?, ?, ?, ?, ?)", \ (None, date, str(user), machine_name, ', '.join(modified_tables), user_description, os.path.basename(conflicted))) # Finish up and detach if diff_only: print("\nDiff complete. No changes made to either database. Set `diff_only=False' to apply merge.") else: print("\nMerge complete!") con.modify("DETACH DATABASE c", verbose=False) self.modify("DETACH DATABASE c", verbose=False) con.modify("DETACH DATABASE m", verbose=False) self.modify("DETACH DATABASE m", verbose=False) else: print("File '{}' not found!".format(conflicted))
python
def merge(self, conflicted, tables=[], diff_only=True): """ Merges specific **tables** or all tables of **conflicted** database into the master database. Parameters ---------- conflicted: str The path of the SQL database to be merged into the master. tables: list (optional) The list of tables to merge. If None, all tables are merged. diff_only: bool If True, only prints the differences of each table and doesn't actually merge anything. """ if os.path.isfile(conflicted): # Load and attach master and conflicted databases con, master, reassign = Database(conflicted), self.list("PRAGMA database_list").fetchall()[0][2], {} con.modify("ATTACH DATABASE '{}' AS m".format(master), verbose=False) self.modify("ATTACH DATABASE '{}' AS c".format(conflicted), verbose=False) con.modify("ATTACH DATABASE '{}' AS c".format(conflicted), verbose=False) self.modify("ATTACH DATABASE '{}' AS m".format(master), verbose=False) # Drop any backup tables from failed merges for table in tables: self.modify("DROP TABLE IF EXISTS Backup_{0}".format(table), verbose=False) # Gather user data to add to CHANGELOG table import socket, datetime if not diff_only: user = get_input('Please enter your name : ') machine_name = socket.gethostname() date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") modified_tables = [] # Merge table by table, starting with SOURCES if not isinstance(tables, type(list())): tables = [tables] tables = tables or ['sources'] + [t for t in zip(*self.list( "SELECT * FROM sqlite_master WHERE name NOT LIKE '%Backup%' AND name!='sqlite_sequence' AND type='table'{}".format( " AND name IN ({})".format("'" + "','".join(tables) + "'") if tables else '')))[1] if t != 'sources'] for table in tables: # Get column names and data types from master table and column names from conflicted table metadata = self.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, constraints = [np.array(metadata[n]) for n in ['name', 'type', 'notnull']] # columns, types, constraints = self.query("PRAGMA table_info({})".format(table), unpack=True)[1:4] conflicted_cols = con.query("PRAGMA table_info({})".format(table), unpack=True)[1] if any([i not in columns for i in conflicted_cols]): # Abort table merge if conflicted has new columns not present in master. New columns must be added to the master database first via db.edit_columns(). print( "\nMerge of {0} table aborted since conflicted copy has columns {1} not present in master.\nAdd new columns to master with astrodb.table() method and try again.\n".format( table.upper(), [i for i in conflicted_cols if i not in columns])) else: # Add new columns from master table to conflicted table if necessary if any([i not in conflicted_cols for i in columns]): con.modify("DROP TABLE IF EXISTS Conflicted_{0}".format(table)) con.modify("ALTER TABLE {0} RENAME TO Conflicted_{0}".format(table)) # TODO: Update to allow multiple primary and foreign keys con.modify("CREATE TABLE {0} ({1})".format(table, ', '.join( \ ['{} {} {}{}'.format(c, t, r, ' UNIQUE PRIMARY KEY' if c == 'id' else '') \ for c, t, r in zip(columns, types, constraints * ['NOT NULL'])]))) con.modify("INSERT INTO {0} ({1}) SELECT {1} FROM Conflicted_{0}".format(table, ','.join( conflicted_cols))) con.modify("DROP TABLE Conflicted_{0}".format(table)) # Pull unique records from conflicted table data = map(list, con.list( "SELECT * FROM (SELECT 1 AS db, {0} FROM m.{2} UNION ALL SELECT 2 AS db, {0} FROM c.{2}) GROUP BY {1} HAVING COUNT(*)=1 AND db=2".format( ','.join(columns), ','.join(columns[1:]), table)).fetchall()) if data: # Just print the table differences if diff_only: pprint(zip(*data)[1:], names=columns, title='New {} records'.format(table.upper())) # Add new records to the master and then clean up tables else: # Make temporary table copy so changes can be undone at any time self.modify("DROP TABLE IF EXISTS Backup_{0}".format(table), verbose=False) self.modify("ALTER TABLE {0} RENAME TO Backup_{0}".format(table), verbose=False) self.modify("CREATE TABLE {0} ({1})".format(table, ', '.join( \ ['{} {} {}{}'.format(c, t, r, ' UNIQUE PRIMARY KEY' if c == 'id' else '') \ for c, t, r in zip(columns, types, constraints * ['NOT NULL'])])), verbose=False) self.modify( "INSERT INTO {0} ({1}) SELECT {1} FROM Backup_{0}".format(table, ','.join(columns)), verbose=False) # Create a dictionary of any reassigned ids from merged SOURCES tables and replace applicable source_ids in other tables. print("\nMerging {} tables.\n".format(table.upper())) try: count = self.query("SELECT MAX(id) FROM {}".format(table), fetch='one')[0] + 1 except TypeError: count = 1 for n, i in enumerate([d[1:] for d in data]): if table == 'sources': reassign[i[0]] = count elif 'source_id' in columns and i[1] in reassign.keys(): i[1] = reassign[i[1]] else: pass i[0] = count data[n] = i count += 1 # Insert unique records into master for d in data: self.modify( "INSERT INTO {} VALUES({})".format(table, ','.join(['?' for c in columns])), d, verbose=False) pprint(zip(*data), names=columns, title="{} records added to {} table at '{}':".format(len(data), table, master)) # Run clean_up on the table to check for conflicts abort = self.clean_up(table) # Undo all changes to table if merge is aborted. Otherwise, push table changes to master. if abort: self.modify("DROP TABLE {0}".format(table), verbose=False) self.modify("ALTER TABLE Backup_{0} RENAME TO {0}".format(table), verbose=False) else: self.modify("DROP TABLE Backup_{0}".format(table), verbose=False) modified_tables.append(table.upper()) else: print("\n{} tables identical.".format(table.upper())) # Add data to CHANGELOG table if not diff_only: user_description = get_input('\nPlease describe the changes made in this merge: ') self.list("INSERT INTO changelog VALUES(?, ?, ?, ?, ?, ?, ?)", \ (None, date, str(user), machine_name, ', '.join(modified_tables), user_description, os.path.basename(conflicted))) # Finish up and detach if diff_only: print("\nDiff complete. No changes made to either database. Set `diff_only=False' to apply merge.") else: print("\nMerge complete!") con.modify("DETACH DATABASE c", verbose=False) self.modify("DETACH DATABASE c", verbose=False) con.modify("DETACH DATABASE m", verbose=False) self.modify("DETACH DATABASE m", verbose=False) else: print("File '{}' not found!".format(conflicted))
[ "def", "merge", "(", "self", ",", "conflicted", ",", "tables", "=", "[", "]", ",", "diff_only", "=", "True", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "conflicted", ")", ":", "# Load and attach master and conflicted databases", "con", ",", "ma...
Merges specific **tables** or all tables of **conflicted** database into the master database. Parameters ---------- conflicted: str The path of the SQL database to be merged into the master. tables: list (optional) The list of tables to merge. If None, all tables are merged. diff_only: bool If True, only prints the differences of each table and doesn't actually merge anything.
[ "Merges", "specific", "**", "tables", "**", "or", "all", "tables", "of", "**", "conflicted", "**", "database", "into", "the", "master", "database", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1130-L1275
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.modify
def modify(self, SQL, params='', verbose=True): """ Wrapper for CRUD operations to make them distinct from queries and automatically pass commit() method to cursor. Parameters ---------- SQL: str The SQL query to execute params: sequence Mimics the native parameter substitution of sqlite3 verbose: bool Prints the number of modified records """ # Make sure the database isn't locked self.conn.commit() if SQL.lower().startswith('select'): print('Use self.query method for queries.') else: self.list(SQL, params) self.conn.commit() if verbose: print('Number of records modified: {}'.format(self.list("SELECT changes()").fetchone()[0] or '0'))
python
def modify(self, SQL, params='', verbose=True): """ Wrapper for CRUD operations to make them distinct from queries and automatically pass commit() method to cursor. Parameters ---------- SQL: str The SQL query to execute params: sequence Mimics the native parameter substitution of sqlite3 verbose: bool Prints the number of modified records """ # Make sure the database isn't locked self.conn.commit() if SQL.lower().startswith('select'): print('Use self.query method for queries.') else: self.list(SQL, params) self.conn.commit() if verbose: print('Number of records modified: {}'.format(self.list("SELECT changes()").fetchone()[0] or '0'))
[ "def", "modify", "(", "self", ",", "SQL", ",", "params", "=", "''", ",", "verbose", "=", "True", ")", ":", "# Make sure the database isn't locked", "self", ".", "conn", ".", "commit", "(", ")", "if", "SQL", ".", "lower", "(", ")", ".", "startswith", "(...
Wrapper for CRUD operations to make them distinct from queries and automatically pass commit() method to cursor. Parameters ---------- SQL: str The SQL query to execute params: sequence Mimics the native parameter substitution of sqlite3 verbose: bool Prints the number of modified records
[ "Wrapper", "for", "CRUD", "operations", "to", "make", "them", "distinct", "from", "queries", "and", "automatically", "pass", "commit", "()", "method", "to", "cursor", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1277-L1299
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.output_spectrum
def output_spectrum(self, spectrum, filepath, header={}): """ Prints a file of the given spectrum to an ascii file with specified filepath. Parameters ---------- spectrum: int, sequence The id from the SPECTRA table or a [w,f,e] sequence filepath: str The path of the file to print the data to. header: dict A dictionary of metadata to add of update in the header """ # If an integer is supplied, get the spectrum from the SPECTRA table if isinstance(spectrum, int): data = self.query("SELECT * FROM spectra WHERE id={}".format(spectrum), fetch='one', fmt='dict') try: data['header'] = list(map(list, data['spectrum'].header.cards)) + [[k, v, ''] for k, v in header.items()] except: data['header'] = '' # If a [w,f,e] sequence is supplied, make it into a Spectrum object elif isinstance(spectrum, (list, tuple, np.ndarray)): data = {'spectrum': Spectrum(spectrum, header=header), 'wavelength_units': '', 'flux_units': ''} try: data['header'] = list(map(list, data['spectrum'].header.cards)) except: data['header'] = '' if data: fn = filepath if filepath.endswith('.txt') else filepath + 'spectrum.txt' # Write the header if data['header']: for n, line in enumerate(data['header']): data['header'][n] = ['# {}'.format(str(line[0])).ljust(10)[:10], '{:50s} / {}'.format(*map(str, line[1:]))] try: ii.write([np.asarray(i) for i in np.asarray(data['header']).T], fn, delimiter='\t', format='no_header') except IOError: pass # Write the data names = ['# wavelength [{}]'.format(data['wavelength_units']), 'flux [{}]'.format(data['flux_units'])] if len(data['spectrum'].data) == 3: if type(data['spectrum'].data[2]) in [np.ndarray, list]: names += ['unc [{}]'.format(data['flux_units'])] else: data['spectrum'].data = data['spectrum'].data[:2] with open(fn, mode='a') as f: ii.write([np.asarray(i, dtype=np.float64) for i in data['spectrum'].data], f, names=names, delimiter='\t') else: print("Could not output spectrum: {}".format(spectrum))
python
def output_spectrum(self, spectrum, filepath, header={}): """ Prints a file of the given spectrum to an ascii file with specified filepath. Parameters ---------- spectrum: int, sequence The id from the SPECTRA table or a [w,f,e] sequence filepath: str The path of the file to print the data to. header: dict A dictionary of metadata to add of update in the header """ # If an integer is supplied, get the spectrum from the SPECTRA table if isinstance(spectrum, int): data = self.query("SELECT * FROM spectra WHERE id={}".format(spectrum), fetch='one', fmt='dict') try: data['header'] = list(map(list, data['spectrum'].header.cards)) + [[k, v, ''] for k, v in header.items()] except: data['header'] = '' # If a [w,f,e] sequence is supplied, make it into a Spectrum object elif isinstance(spectrum, (list, tuple, np.ndarray)): data = {'spectrum': Spectrum(spectrum, header=header), 'wavelength_units': '', 'flux_units': ''} try: data['header'] = list(map(list, data['spectrum'].header.cards)) except: data['header'] = '' if data: fn = filepath if filepath.endswith('.txt') else filepath + 'spectrum.txt' # Write the header if data['header']: for n, line in enumerate(data['header']): data['header'][n] = ['# {}'.format(str(line[0])).ljust(10)[:10], '{:50s} / {}'.format(*map(str, line[1:]))] try: ii.write([np.asarray(i) for i in np.asarray(data['header']).T], fn, delimiter='\t', format='no_header') except IOError: pass # Write the data names = ['# wavelength [{}]'.format(data['wavelength_units']), 'flux [{}]'.format(data['flux_units'])] if len(data['spectrum'].data) == 3: if type(data['spectrum'].data[2]) in [np.ndarray, list]: names += ['unc [{}]'.format(data['flux_units'])] else: data['spectrum'].data = data['spectrum'].data[:2] with open(fn, mode='a') as f: ii.write([np.asarray(i, dtype=np.float64) for i in data['spectrum'].data], f, names=names, delimiter='\t') else: print("Could not output spectrum: {}".format(spectrum))
[ "def", "output_spectrum", "(", "self", ",", "spectrum", ",", "filepath", ",", "header", "=", "{", "}", ")", ":", "# If an integer is supplied, get the spectrum from the SPECTRA table", "if", "isinstance", "(", "spectrum", ",", "int", ")", ":", "data", "=", "self",...
Prints a file of the given spectrum to an ascii file with specified filepath. Parameters ---------- spectrum: int, sequence The id from the SPECTRA table or a [w,f,e] sequence filepath: str The path of the file to print the data to. header: dict A dictionary of metadata to add of update in the header
[ "Prints", "a", "file", "of", "the", "given", "spectrum", "to", "an", "ascii", "file", "with", "specified", "filepath", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1301-L1359
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.show_image
def show_image(self, image_id, table='images', column='image', overplot=False, cmap='hot', log=False): """ Plots a spectrum from the given column and table Parameters ---------- image_id: int The id from the table of the images to plot. overplot: bool Overplot the image table: str The table from which the plot is being made column: str The column with IMAGE data type to plot cmap: str The colormap used for the data """ # TODO: Look into axes number formats. As is it will sometimes not display any numbers for wavelength i = self.query("SELECT * FROM {} WHERE id={}".format(table, image_id), fetch='one', fmt='dict') if i: try: img = i['image'].data # Draw the axes and add the metadata if not overplot: fig, ax = plt.subplots() plt.rc('text', usetex=False) plt.figtext(0.15, 0.88, '\n'.join(['{}: {}'.format(k, v) for k, v in i.items() if k != column]), \ verticalalignment='top') ax.legend(loc=8, frameon=False) else: ax = plt.gca() # Plot the data cmap = plt.get_cmap(cmap) cmap.set_under(color='white') vmin = 0.0000001 vmax = np.nanmax(img) if log: from matplotlib.colors import LogNorm ax.imshow(img, cmap=cmap, norm=LogNorm(vmin=vmin,vmax=vmax), interpolation='none') else: ax.imshow(img, cmap=cmap, interpolation='none', vmin=0.0000001) X, Y = plt.xlim(), plt.ylim() plt.ion() except IOError: print("Could not plot image {}".format(image_id)) plt.close() else: print("No image {} in the {} table.".format(image_id, table.upper()))
python
def show_image(self, image_id, table='images', column='image', overplot=False, cmap='hot', log=False): """ Plots a spectrum from the given column and table Parameters ---------- image_id: int The id from the table of the images to plot. overplot: bool Overplot the image table: str The table from which the plot is being made column: str The column with IMAGE data type to plot cmap: str The colormap used for the data """ # TODO: Look into axes number formats. As is it will sometimes not display any numbers for wavelength i = self.query("SELECT * FROM {} WHERE id={}".format(table, image_id), fetch='one', fmt='dict') if i: try: img = i['image'].data # Draw the axes and add the metadata if not overplot: fig, ax = plt.subplots() plt.rc('text', usetex=False) plt.figtext(0.15, 0.88, '\n'.join(['{}: {}'.format(k, v) for k, v in i.items() if k != column]), \ verticalalignment='top') ax.legend(loc=8, frameon=False) else: ax = plt.gca() # Plot the data cmap = plt.get_cmap(cmap) cmap.set_under(color='white') vmin = 0.0000001 vmax = np.nanmax(img) if log: from matplotlib.colors import LogNorm ax.imshow(img, cmap=cmap, norm=LogNorm(vmin=vmin,vmax=vmax), interpolation='none') else: ax.imshow(img, cmap=cmap, interpolation='none', vmin=0.0000001) X, Y = plt.xlim(), plt.ylim() plt.ion() except IOError: print("Could not plot image {}".format(image_id)) plt.close() else: print("No image {} in the {} table.".format(image_id, table.upper()))
[ "def", "show_image", "(", "self", ",", "image_id", ",", "table", "=", "'images'", ",", "column", "=", "'image'", ",", "overplot", "=", "False", ",", "cmap", "=", "'hot'", ",", "log", "=", "False", ")", ":", "# TODO: Look into axes number formats. As is it will...
Plots a spectrum from the given column and table Parameters ---------- image_id: int The id from the table of the images to plot. overplot: bool Overplot the image table: str The table from which the plot is being made column: str The column with IMAGE data type to plot cmap: str The colormap used for the data
[ "Plots", "a", "spectrum", "from", "the", "given", "column", "and", "table" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1361-L1413
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.plot_spectrum
def plot_spectrum(self, spectrum_id, table='spectra', column='spectrum', overplot=False, color='b', norm=False): """ Plots a spectrum from the given column and table Parameters ---------- spectrum_id: int The id from the table of the spectrum to plot. overplot: bool Overplot the spectrum table: str The table from which the plot is being made column: str The column with SPECTRUM data type to plot color: str The color used for the data norm: bool, sequence True or (min,max) wavelength range in which to normalize the spectrum """ # TODO: Look into axes number formats. As is it will sometimes not display any numbers for wavelength i = self.query("SELECT * FROM {} WHERE id={}".format(table, spectrum_id), fetch='one', fmt='dict') if i: try: spec = scrub(i[column].data, units=False) w, f = spec[:2] try: e = spec[2] except: e = '' # Draw the axes and add the metadata if not overplot: fig, ax = plt.subplots() plt.rc('text', usetex=False) ax.set_yscale('log', nonposy='clip') plt.figtext(0.15, 0.88, '\n'.join(['{}: {}'.format(k, v) for k, v in i.items() if k != column]), \ verticalalignment='top') try: ax.set_xlabel(r'$\lambda$ [{}]'.format(i.get('wavelength_units'))) ax.set_ylabel(r'$F_\lambda$ [{}]'.format(i.get('flux_units'))) except: pass ax.legend(loc=8, frameon=False) else: ax = plt.gca() # Normalize the data if norm: try: if isinstance(norm, bool): norm = (min(w), max(w)) # Normalize to the specified window norm_mask = np.logical_and(w >= norm[0], w <= norm[1]) C = 1. / np.trapz(f[norm_mask], x=w[norm_mask]) f *= C try: e *= C except: pass except: print('Could not normalize.') # Plot the data ax.loglog(w, f, c=color, label='spec_id: {}'.format(i['id'])) X, Y = plt.xlim(), plt.ylim() try: ax.fill_between(w, f - e, f + e, color=color, alpha=0.3), ax.set_xlim(X), ax.set_ylim(Y) except: print('No uncertainty array for spectrum {}'.format(spectrum_id)) plt.ion() except IOError: print("Could not plot spectrum {}".format(spectrum_id)) plt.close() else: print("No spectrum {} in the {} table.".format(spectrum_id, table.upper()))
python
def plot_spectrum(self, spectrum_id, table='spectra', column='spectrum', overplot=False, color='b', norm=False): """ Plots a spectrum from the given column and table Parameters ---------- spectrum_id: int The id from the table of the spectrum to plot. overplot: bool Overplot the spectrum table: str The table from which the plot is being made column: str The column with SPECTRUM data type to plot color: str The color used for the data norm: bool, sequence True or (min,max) wavelength range in which to normalize the spectrum """ # TODO: Look into axes number formats. As is it will sometimes not display any numbers for wavelength i = self.query("SELECT * FROM {} WHERE id={}".format(table, spectrum_id), fetch='one', fmt='dict') if i: try: spec = scrub(i[column].data, units=False) w, f = spec[:2] try: e = spec[2] except: e = '' # Draw the axes and add the metadata if not overplot: fig, ax = plt.subplots() plt.rc('text', usetex=False) ax.set_yscale('log', nonposy='clip') plt.figtext(0.15, 0.88, '\n'.join(['{}: {}'.format(k, v) for k, v in i.items() if k != column]), \ verticalalignment='top') try: ax.set_xlabel(r'$\lambda$ [{}]'.format(i.get('wavelength_units'))) ax.set_ylabel(r'$F_\lambda$ [{}]'.format(i.get('flux_units'))) except: pass ax.legend(loc=8, frameon=False) else: ax = plt.gca() # Normalize the data if norm: try: if isinstance(norm, bool): norm = (min(w), max(w)) # Normalize to the specified window norm_mask = np.logical_and(w >= norm[0], w <= norm[1]) C = 1. / np.trapz(f[norm_mask], x=w[norm_mask]) f *= C try: e *= C except: pass except: print('Could not normalize.') # Plot the data ax.loglog(w, f, c=color, label='spec_id: {}'.format(i['id'])) X, Y = plt.xlim(), plt.ylim() try: ax.fill_between(w, f - e, f + e, color=color, alpha=0.3), ax.set_xlim(X), ax.set_ylim(Y) except: print('No uncertainty array for spectrum {}'.format(spectrum_id)) plt.ion() except IOError: print("Could not plot spectrum {}".format(spectrum_id)) plt.close() else: print("No spectrum {} in the {} table.".format(spectrum_id, table.upper()))
[ "def", "plot_spectrum", "(", "self", ",", "spectrum_id", ",", "table", "=", "'spectra'", ",", "column", "=", "'spectrum'", ",", "overplot", "=", "False", ",", "color", "=", "'b'", ",", "norm", "=", "False", ")", ":", "# TODO: Look into axes number formats. As ...
Plots a spectrum from the given column and table Parameters ---------- spectrum_id: int The id from the table of the spectrum to plot. overplot: bool Overplot the spectrum table: str The table from which the plot is being made column: str The column with SPECTRUM data type to plot color: str The color used for the data norm: bool, sequence True or (min,max) wavelength range in which to normalize the spectrum
[ "Plots", "a", "spectrum", "from", "the", "given", "column", "and", "table" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1416-L1495
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.query
def query(self, SQL, params='', fmt='array', fetch='all', unpack=False, export='', \ verbose=False, use_converters=True): """ Returns data satisfying the provided **SQL** script. Only SELECT or PRAGMA statements are allowed. Results can be returned in a variety of formats. For example, to extract the ra and dec of all entries in SOURCES in astropy.Table format one can write: data = db.query('SELECT ra, dec FROM sources', fmt='table') For more general SQL statements, see the modify() method. Parameters ---------- SQL: str The SQL query to execute params: sequence Mimics the native parameter substitution of sqlite3 fmt: str Returns the data as a dictionary, array, astropy.table, or pandas.Dataframe given 'dict', 'array', 'table', or 'pandas' fetch: str String indicating whether to return **all** results or just **one** unpack: bool Returns the transpose of the data export: str The file path of the ascii file to which the data should be exported verbose: bool print the data as well use_converters: bool Apply converters to columns with custom data types Returns ------- result: (array,dict,table) The result of the database query """ try: # Restrict queries to SELECT and PRAGMA statements if SQL.lower().startswith('select') or SQL.lower().startswith('pragma'): # Make the query explicit so that column and table names are preserved # Then, get the data as a dictionary origSQL = SQL try: SQL, columns = self._explicit_query(SQL, use_converters=use_converters) dictionary = self.dict(SQL, params).fetchall() except: print('WARNING: Unable to use converters') dictionary = self.dict(origSQL, params).fetchall() if any(dictionary): # Fetch one if fetch == 'one': dictionary = [dictionary.pop(0)] # Make an Astropy table table = at.Table(dictionary) # Reorder the columns try: table = table[columns] except: pass # Make an array array = np.asarray(table) # Unpack the results if necessary (data types are not preserved) if unpack: array = np.array(zip(*array)) # print on screen if verbose: pprint(table) # print the results to file if export: # If .vot or .xml, assume VOTable export with votools if export.lower().endswith('.xml') or export.lower().endswith('.vot'): votools.dict_tovot(dictionary, export) # Otherwise print as ascii else: ii.write(table, export, Writer=ii.FixedWidthTwoLine, fill_values=[('None', '-')]) # Or return the results else: if fetch == 'one': dictionary, array = dictionary[0], array if unpack else np.array(list(array[0])) if fmt == 'table': return table elif fmt == 'dict': return dictionary elif fmt == 'pandas': return table.to_pandas() else: return array else: return else: print( 'Queries must begin with a SELECT or PRAGMA statement. For database modifications use self.modify() method.') except IOError: print('Could not execute: ' + SQL)
python
def query(self, SQL, params='', fmt='array', fetch='all', unpack=False, export='', \ verbose=False, use_converters=True): """ Returns data satisfying the provided **SQL** script. Only SELECT or PRAGMA statements are allowed. Results can be returned in a variety of formats. For example, to extract the ra and dec of all entries in SOURCES in astropy.Table format one can write: data = db.query('SELECT ra, dec FROM sources', fmt='table') For more general SQL statements, see the modify() method. Parameters ---------- SQL: str The SQL query to execute params: sequence Mimics the native parameter substitution of sqlite3 fmt: str Returns the data as a dictionary, array, astropy.table, or pandas.Dataframe given 'dict', 'array', 'table', or 'pandas' fetch: str String indicating whether to return **all** results or just **one** unpack: bool Returns the transpose of the data export: str The file path of the ascii file to which the data should be exported verbose: bool print the data as well use_converters: bool Apply converters to columns with custom data types Returns ------- result: (array,dict,table) The result of the database query """ try: # Restrict queries to SELECT and PRAGMA statements if SQL.lower().startswith('select') or SQL.lower().startswith('pragma'): # Make the query explicit so that column and table names are preserved # Then, get the data as a dictionary origSQL = SQL try: SQL, columns = self._explicit_query(SQL, use_converters=use_converters) dictionary = self.dict(SQL, params).fetchall() except: print('WARNING: Unable to use converters') dictionary = self.dict(origSQL, params).fetchall() if any(dictionary): # Fetch one if fetch == 'one': dictionary = [dictionary.pop(0)] # Make an Astropy table table = at.Table(dictionary) # Reorder the columns try: table = table[columns] except: pass # Make an array array = np.asarray(table) # Unpack the results if necessary (data types are not preserved) if unpack: array = np.array(zip(*array)) # print on screen if verbose: pprint(table) # print the results to file if export: # If .vot or .xml, assume VOTable export with votools if export.lower().endswith('.xml') or export.lower().endswith('.vot'): votools.dict_tovot(dictionary, export) # Otherwise print as ascii else: ii.write(table, export, Writer=ii.FixedWidthTwoLine, fill_values=[('None', '-')]) # Or return the results else: if fetch == 'one': dictionary, array = dictionary[0], array if unpack else np.array(list(array[0])) if fmt == 'table': return table elif fmt == 'dict': return dictionary elif fmt == 'pandas': return table.to_pandas() else: return array else: return else: print( 'Queries must begin with a SELECT or PRAGMA statement. For database modifications use self.modify() method.') except IOError: print('Could not execute: ' + SQL)
[ "def", "query", "(", "self", ",", "SQL", ",", "params", "=", "''", ",", "fmt", "=", "'array'", ",", "fetch", "=", "'all'", ",", "unpack", "=", "False", ",", "export", "=", "''", ",", "verbose", "=", "False", ",", "use_converters", "=", "True", ")",...
Returns data satisfying the provided **SQL** script. Only SELECT or PRAGMA statements are allowed. Results can be returned in a variety of formats. For example, to extract the ra and dec of all entries in SOURCES in astropy.Table format one can write: data = db.query('SELECT ra, dec FROM sources', fmt='table') For more general SQL statements, see the modify() method. Parameters ---------- SQL: str The SQL query to execute params: sequence Mimics the native parameter substitution of sqlite3 fmt: str Returns the data as a dictionary, array, astropy.table, or pandas.Dataframe given 'dict', 'array', 'table', or 'pandas' fetch: str String indicating whether to return **all** results or just **one** unpack: bool Returns the transpose of the data export: str The file path of the ascii file to which the data should be exported verbose: bool print the data as well use_converters: bool Apply converters to columns with custom data types Returns ------- result: (array,dict,table) The result of the database query
[ "Returns", "data", "satisfying", "the", "provided", "**", "SQL", "**", "script", ".", "Only", "SELECT", "or", "PRAGMA", "statements", "are", "allowed", ".", "Results", "can", "be", "returned", "in", "a", "variety", "of", "formats", ".", "For", "example", "...
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1497-L1604
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.references
def references(self, criteria, publications='publications', column_name='publication_shortname', fetch=False): """ Do a reverse lookup on the **publications** table. Will return every entry that matches that reference. Parameters ---------- criteria: int or str The id from the PUBLICATIONS table whose data across all tables is to be printed. publications: str Name of the publications table column_name: str Name of the reference column in other tables fetch: bool Return the results. Returns ------- data_tables: dict Returns a dictionary of astropy tables with the table name as the keys. """ data_tables = dict() # If an ID is provided but the column name is publication shortname, grab the shortname if isinstance(criteria, type(1)) and column_name == 'publication_shortname': t = self.query("SELECT * FROM {} WHERE id={}".format(publications, criteria), fmt='table') if len(t) > 0: criteria = t['shortname'][0] else: print('No match found for {}'.format(criteria)) return t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() for table in ['sources'] + [t for t in all_tables if t not in ['publications', 'sqlite_sequence', 'sources']]: # Get the columns, pull out redundant ones, and query the table for this source's data t = self.query("PRAGMA table_info({})".format(table), fmt='table') columns = np.array(t['name']) types = np.array(t['type']) # Only get simple data types and exclude redundant ones for nicer printing columns = columns[ ((types == 'REAL') | (types == 'INTEGER') | (types == 'TEXT')) & (columns != column_name)] # Query the table try: data = self.query("SELECT {} FROM {} WHERE {}='{}'".format(','.join(columns), table, column_name, criteria), fmt='table') except: data = None # If there's data for this table, save it if data: if fetch: data_tables[table] = self.query( "SELECT {} FROM {} WHERE {}='{}'".format( ','.join(columns), table, column_name, criteria), fmt='table', fetch=True) else: data = data[[c.lower() for c in columns]] # force lowercase since astropy.Tables have all lowercase pprint(data, title=table.upper()) if fetch: return data_tables
python
def references(self, criteria, publications='publications', column_name='publication_shortname', fetch=False): """ Do a reverse lookup on the **publications** table. Will return every entry that matches that reference. Parameters ---------- criteria: int or str The id from the PUBLICATIONS table whose data across all tables is to be printed. publications: str Name of the publications table column_name: str Name of the reference column in other tables fetch: bool Return the results. Returns ------- data_tables: dict Returns a dictionary of astropy tables with the table name as the keys. """ data_tables = dict() # If an ID is provided but the column name is publication shortname, grab the shortname if isinstance(criteria, type(1)) and column_name == 'publication_shortname': t = self.query("SELECT * FROM {} WHERE id={}".format(publications, criteria), fmt='table') if len(t) > 0: criteria = t['shortname'][0] else: print('No match found for {}'.format(criteria)) return t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() for table in ['sources'] + [t for t in all_tables if t not in ['publications', 'sqlite_sequence', 'sources']]: # Get the columns, pull out redundant ones, and query the table for this source's data t = self.query("PRAGMA table_info({})".format(table), fmt='table') columns = np.array(t['name']) types = np.array(t['type']) # Only get simple data types and exclude redundant ones for nicer printing columns = columns[ ((types == 'REAL') | (types == 'INTEGER') | (types == 'TEXT')) & (columns != column_name)] # Query the table try: data = self.query("SELECT {} FROM {} WHERE {}='{}'".format(','.join(columns), table, column_name, criteria), fmt='table') except: data = None # If there's data for this table, save it if data: if fetch: data_tables[table] = self.query( "SELECT {} FROM {} WHERE {}='{}'".format( ','.join(columns), table, column_name, criteria), fmt='table', fetch=True) else: data = data[[c.lower() for c in columns]] # force lowercase since astropy.Tables have all lowercase pprint(data, title=table.upper()) if fetch: return data_tables
[ "def", "references", "(", "self", ",", "criteria", ",", "publications", "=", "'publications'", ",", "column_name", "=", "'publication_shortname'", ",", "fetch", "=", "False", ")", ":", "data_tables", "=", "dict", "(", ")", "# If an ID is provided but the column name...
Do a reverse lookup on the **publications** table. Will return every entry that matches that reference. Parameters ---------- criteria: int or str The id from the PUBLICATIONS table whose data across all tables is to be printed. publications: str Name of the publications table column_name: str Name of the reference column in other tables fetch: bool Return the results. Returns ------- data_tables: dict Returns a dictionary of astropy tables with the table name as the keys.
[ "Do", "a", "reverse", "lookup", "on", "the", "**", "publications", "**", "table", ".", "Will", "return", "every", "entry", "that", "matches", "that", "reference", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1606-L1670
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.save
def save(self, directory=None): """ Dump the entire contents of the database into the tabledata directory as ascii files """ from subprocess import call # If user did not supply a new directory, use the one loaded (default: tabledata) if isinstance(directory, type(None)): directory = self.directory # Create the .sql file is it doesn't exist, i.e. if the Database class called a .db file initially if not os.path.isfile(self.sqlpath): self.sqlpath = self.dbpath.replace('.db', '.sql') os.system('touch {}'.format(self.sqlpath)) # # Write the data to the .sql file # with open(self.sqlpath, 'w') as f: # for line in self.conn.iterdump(): # f.write('%s\n' % line) # Alternatively... # Write the schema os.system("echo '.output {}\n.schema' | sqlite3 {}".format(self.sqlpath, self.dbpath)) # Write the table files to the tabledata directory os.system("mkdir -p {}".format(directory)) tables = self.query("select tbl_name from sqlite_master where type='table'")['tbl_name'] tablepaths = [self.sqlpath] for table in tables: print('Generating {}...'.format(table)) tablepath = '{0}/{1}.sql'.format(directory, table) tablepaths.append(tablepath) with open(tablepath, 'w') as f: for line in self.conn.iterdump(): line = line.strip() if line.startswith('INSERT INTO "{}"'.format(table)): if sys.version_info.major == 2: f.write(u'{}\n'.format(line).encode('utf-8')) else: f.write(u'{}\n'.format(line)) print("Tables saved to directory {}/".format(directory)) print("""======================================================================================= You can now run git to commit and push these changes, if needed. For example, if on the master branch you can do the following: git add {0} {1}/*.sql git commit -m "COMMIT MESSAGE HERE" git push origin master You can then issue a pull request on GitHub to have these changes reviewed and accepted =======================================================================================""" .format(self.sqlpath, directory))
python
def save(self, directory=None): """ Dump the entire contents of the database into the tabledata directory as ascii files """ from subprocess import call # If user did not supply a new directory, use the one loaded (default: tabledata) if isinstance(directory, type(None)): directory = self.directory # Create the .sql file is it doesn't exist, i.e. if the Database class called a .db file initially if not os.path.isfile(self.sqlpath): self.sqlpath = self.dbpath.replace('.db', '.sql') os.system('touch {}'.format(self.sqlpath)) # # Write the data to the .sql file # with open(self.sqlpath, 'w') as f: # for line in self.conn.iterdump(): # f.write('%s\n' % line) # Alternatively... # Write the schema os.system("echo '.output {}\n.schema' | sqlite3 {}".format(self.sqlpath, self.dbpath)) # Write the table files to the tabledata directory os.system("mkdir -p {}".format(directory)) tables = self.query("select tbl_name from sqlite_master where type='table'")['tbl_name'] tablepaths = [self.sqlpath] for table in tables: print('Generating {}...'.format(table)) tablepath = '{0}/{1}.sql'.format(directory, table) tablepaths.append(tablepath) with open(tablepath, 'w') as f: for line in self.conn.iterdump(): line = line.strip() if line.startswith('INSERT INTO "{}"'.format(table)): if sys.version_info.major == 2: f.write(u'{}\n'.format(line).encode('utf-8')) else: f.write(u'{}\n'.format(line)) print("Tables saved to directory {}/".format(directory)) print("""======================================================================================= You can now run git to commit and push these changes, if needed. For example, if on the master branch you can do the following: git add {0} {1}/*.sql git commit -m "COMMIT MESSAGE HERE" git push origin master You can then issue a pull request on GitHub to have these changes reviewed and accepted =======================================================================================""" .format(self.sqlpath, directory))
[ "def", "save", "(", "self", ",", "directory", "=", "None", ")", ":", "from", "subprocess", "import", "call", "# If user did not supply a new directory, use the one loaded (default: tabledata)", "if", "isinstance", "(", "directory", ",", "type", "(", "None", ")", ")", ...
Dump the entire contents of the database into the tabledata directory as ascii files
[ "Dump", "the", "entire", "contents", "of", "the", "database", "into", "the", "tabledata", "directory", "as", "ascii", "files" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1672-L1722
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.schema
def schema(self, table): """ Print the table schema Parameters ---------- table: str The table name """ try: pprint(self.query("PRAGMA table_info({})".format(table), fmt='table')) except ValueError: print('Table {} not found'.format(table))
python
def schema(self, table): """ Print the table schema Parameters ---------- table: str The table name """ try: pprint(self.query("PRAGMA table_info({})".format(table), fmt='table')) except ValueError: print('Table {} not found'.format(table))
[ "def", "schema", "(", "self", ",", "table", ")", ":", "try", ":", "pprint", "(", "self", ".", "query", "(", "\"PRAGMA table_info({})\"", ".", "format", "(", "table", ")", ",", "fmt", "=", "'table'", ")", ")", "except", "ValueError", ":", "print", "(", ...
Print the table schema Parameters ---------- table: str The table name
[ "Print", "the", "table", "schema" ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1740-L1753
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.search
def search(self, criterion, table, columns='', fetch=False, radius=1/60., use_converters=False, sql_search=False): """ General search method for tables. For (ra,dec) input in decimal degrees, i.e. (12.3456,-65.4321), returns all sources within 1 arcminute, or the specified radius. For string input, i.e. 'vb10', returns all sources with case-insensitive partial text matches in columns with 'TEXT' data type. For integer input, i.e. 123, returns all exact matches of columns with INTEGER data type. Parameters ---------- criterion: (str, int, sequence, tuple) The text, integer, coordinate tuple, or sequence thereof to search the table with. table: str The name of the table to search columns: sequence Specific column names to search, otherwise searches all columns fetch: bool Return the results of the query as an Astropy table radius: float Radius in degrees in which to search for objects if using (ra,dec). Default: 1/60 degree use_converters: bool Apply converters to columns with custom data types sql_search: bool Perform the search by coordinates in a box defined within the SQL commands, rather than with true angular separations. Faster, but not a true radial search. """ # Get list of columns to search and format properly t = self.query("PRAGMA table_info({})".format(table), unpack=True, fmt='table') all_columns = t['name'].tolist() types = t['type'].tolist() columns = columns or all_columns columns = np.asarray([columns] if isinstance(columns, str) else columns) # Separate good and bad columns and corresponding types badcols = columns[~np.in1d(columns, all_columns)] columns = columns[np.in1d(columns, all_columns)] columns = np.array([c for c in all_columns if c in columns]) types = np.array([t for c, t in zip(all_columns, types) if c in columns])[np.in1d(columns, all_columns)] for col in badcols: print("'{}' is not a column in the {} table.".format(col, table.upper())) # Coordinate search if sys.version_info[0] == 2: str_check = (str, unicode) else: str_check = str results = '' if isinstance(criterion, (tuple, list, np.ndarray)): try: if sql_search: q = "SELECT * FROM {} WHERE ra BETWEEN ".format(table) \ + str(criterion[0] - radius) + " AND " \ + str(criterion[0] + radius) + " AND dec BETWEEN " \ + str(criterion[1] - radius) + " AND " \ + str(criterion[1] + radius) results = self.query(q, fmt='table') else: t = self.query('SELECT id,ra,dec FROM sources', fmt='table') df = t.to_pandas() df[['ra', 'dec']] = df[['ra', 'dec']].apply(pd.to_numeric) # convert everything to floats mask = df['ra'].isnull() df = df[~mask] df['theta'] = df.apply(ang_sep, axis=1, args=(criterion[0], criterion[1])) good = df['theta'] <= radius if sum(good) > 0: params = ", ".join(['{}'.format(s) for s in df[good]['id'].tolist()]) try: results = self.query('SELECT * FROM {} WHERE source_id IN ({})'.format(table, params), fmt='table') except: results = self.query('SELECT * FROM {} WHERE id IN ({})'.format(table, params), fmt='table') except: print("Could not search {} table by coordinates {}. Try again.".format(table.upper(), criterion)) # Text string search of columns with 'TEXT' data type elif isinstance(criterion, str_check) and any(columns) and 'TEXT' in types: try: q = "SELECT * FROM {} WHERE {}".format(table, ' OR '.join([r"REPLACE(" + c + r",' ','') like '%" \ + criterion.replace(' ', '') + r"%'" for c, t in zip(columns,types[np.in1d(columns, all_columns)]) \ if t == 'TEXT'])) results = self.query(q, fmt='table', use_converters=use_converters) except: print("Could not search {} table by string {}. Try again.".format(table.upper(), criterion)) # Integer search of columns with 'INTEGER' data type elif isinstance(criterion, int): try: q = "SELECT * FROM {} WHERE {}".format(table, ' OR '.join(['{}={}'.format(c, criterion) \ for c, t in zip(columns, types[np.in1d(columns, all_columns)]) if t == 'INTEGER'])) results = self.query(q, fmt='table', use_converters=use_converters) except: print("Could not search {} table by id {}. Try again.".format(table.upper(), criterion)) # Problem! else: print("Could not search {} table by '{}'. Try again.".format(table.upper(), criterion)) # Print or return the results if fetch: return results or at.Table(names=columns, dtype=[type_dict[t] for t in types], masked=True) else: if results: pprint(results, title=table.upper()) else: print("No results found for {} in the {} table.".format(criterion, table.upper()))
python
def search(self, criterion, table, columns='', fetch=False, radius=1/60., use_converters=False, sql_search=False): """ General search method for tables. For (ra,dec) input in decimal degrees, i.e. (12.3456,-65.4321), returns all sources within 1 arcminute, or the specified radius. For string input, i.e. 'vb10', returns all sources with case-insensitive partial text matches in columns with 'TEXT' data type. For integer input, i.e. 123, returns all exact matches of columns with INTEGER data type. Parameters ---------- criterion: (str, int, sequence, tuple) The text, integer, coordinate tuple, or sequence thereof to search the table with. table: str The name of the table to search columns: sequence Specific column names to search, otherwise searches all columns fetch: bool Return the results of the query as an Astropy table radius: float Radius in degrees in which to search for objects if using (ra,dec). Default: 1/60 degree use_converters: bool Apply converters to columns with custom data types sql_search: bool Perform the search by coordinates in a box defined within the SQL commands, rather than with true angular separations. Faster, but not a true radial search. """ # Get list of columns to search and format properly t = self.query("PRAGMA table_info({})".format(table), unpack=True, fmt='table') all_columns = t['name'].tolist() types = t['type'].tolist() columns = columns or all_columns columns = np.asarray([columns] if isinstance(columns, str) else columns) # Separate good and bad columns and corresponding types badcols = columns[~np.in1d(columns, all_columns)] columns = columns[np.in1d(columns, all_columns)] columns = np.array([c for c in all_columns if c in columns]) types = np.array([t for c, t in zip(all_columns, types) if c in columns])[np.in1d(columns, all_columns)] for col in badcols: print("'{}' is not a column in the {} table.".format(col, table.upper())) # Coordinate search if sys.version_info[0] == 2: str_check = (str, unicode) else: str_check = str results = '' if isinstance(criterion, (tuple, list, np.ndarray)): try: if sql_search: q = "SELECT * FROM {} WHERE ra BETWEEN ".format(table) \ + str(criterion[0] - radius) + " AND " \ + str(criterion[0] + radius) + " AND dec BETWEEN " \ + str(criterion[1] - radius) + " AND " \ + str(criterion[1] + radius) results = self.query(q, fmt='table') else: t = self.query('SELECT id,ra,dec FROM sources', fmt='table') df = t.to_pandas() df[['ra', 'dec']] = df[['ra', 'dec']].apply(pd.to_numeric) # convert everything to floats mask = df['ra'].isnull() df = df[~mask] df['theta'] = df.apply(ang_sep, axis=1, args=(criterion[0], criterion[1])) good = df['theta'] <= radius if sum(good) > 0: params = ", ".join(['{}'.format(s) for s in df[good]['id'].tolist()]) try: results = self.query('SELECT * FROM {} WHERE source_id IN ({})'.format(table, params), fmt='table') except: results = self.query('SELECT * FROM {} WHERE id IN ({})'.format(table, params), fmt='table') except: print("Could not search {} table by coordinates {}. Try again.".format(table.upper(), criterion)) # Text string search of columns with 'TEXT' data type elif isinstance(criterion, str_check) and any(columns) and 'TEXT' in types: try: q = "SELECT * FROM {} WHERE {}".format(table, ' OR '.join([r"REPLACE(" + c + r",' ','') like '%" \ + criterion.replace(' ', '') + r"%'" for c, t in zip(columns,types[np.in1d(columns, all_columns)]) \ if t == 'TEXT'])) results = self.query(q, fmt='table', use_converters=use_converters) except: print("Could not search {} table by string {}. Try again.".format(table.upper(), criterion)) # Integer search of columns with 'INTEGER' data type elif isinstance(criterion, int): try: q = "SELECT * FROM {} WHERE {}".format(table, ' OR '.join(['{}={}'.format(c, criterion) \ for c, t in zip(columns, types[np.in1d(columns, all_columns)]) if t == 'INTEGER'])) results = self.query(q, fmt='table', use_converters=use_converters) except: print("Could not search {} table by id {}. Try again.".format(table.upper(), criterion)) # Problem! else: print("Could not search {} table by '{}'. Try again.".format(table.upper(), criterion)) # Print or return the results if fetch: return results or at.Table(names=columns, dtype=[type_dict[t] for t in types], masked=True) else: if results: pprint(results, title=table.upper()) else: print("No results found for {} in the {} table.".format(criterion, table.upper()))
[ "def", "search", "(", "self", ",", "criterion", ",", "table", ",", "columns", "=", "''", ",", "fetch", "=", "False", ",", "radius", "=", "1", "/", "60.", ",", "use_converters", "=", "False", ",", "sql_search", "=", "False", ")", ":", "# Get list of col...
General search method for tables. For (ra,dec) input in decimal degrees, i.e. (12.3456,-65.4321), returns all sources within 1 arcminute, or the specified radius. For string input, i.e. 'vb10', returns all sources with case-insensitive partial text matches in columns with 'TEXT' data type. For integer input, i.e. 123, returns all exact matches of columns with INTEGER data type. Parameters ---------- criterion: (str, int, sequence, tuple) The text, integer, coordinate tuple, or sequence thereof to search the table with. table: str The name of the table to search columns: sequence Specific column names to search, otherwise searches all columns fetch: bool Return the results of the query as an Astropy table radius: float Radius in degrees in which to search for objects if using (ra,dec). Default: 1/60 degree use_converters: bool Apply converters to columns with custom data types sql_search: bool Perform the search by coordinates in a box defined within the SQL commands, rather than with true angular separations. Faster, but not a true radial search.
[ "General", "search", "method", "for", "tables", ".", "For", "(", "ra", "dec", ")", "input", "in", "decimal", "degrees", "i", ".", "e", ".", "(", "12", ".", "3456", "-", "65", ".", "4321", ")", "returns", "all", "sources", "within", "1", "arcminute", ...
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1755-L1865
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.snapshot
def snapshot(self, name_db='export.db', version=1.0): """ Function to generate a snapshot of the database by version number. Parameters ---------- name_db: string Name of the new database (Default: export.db) version: float Version number to export (Default: 1.0) """ # Check if file exists if os.path.isfile(name_db): import datetime date = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M") print("Renaming existing file {} to {}".format(name_db, name_db.replace('.db', date + '.db'))) os.system("mv {} {}".format(name_db, name_db.replace('.db', date + '.db'))) # Create a new database from existing database schema t, = self.query("select sql from sqlite_master where type = 'table'", unpack=True) schema = ';\n'.join(t) + ';' os.system("sqlite3 {} '{}'".format(name_db, schema)) # Attach database to newly created database db = Database(name_db) db.list('PRAGMA foreign_keys=OFF') # Temporarily deactivate foreign keys for the snapshot db.list("ATTACH DATABASE '{}' AS orig".format(self.dbpath)) # For each table in database, insert records if they match version number t = db.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() for table in [t for t in all_tables if t not in ['sqlite_sequence', 'changelog']]: # Check if this is table with version column metadata = db.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, required, pk = [np.array(metadata[n]) for n in ['name', 'type', 'notnull', 'pk']] print(table, columns) if 'version' not in columns: db.modify("INSERT INTO {0} SELECT * FROM orig.{0}".format(table)) else: db.modify("INSERT INTO {0} SELECT * FROM orig.{0} WHERE orig.{0}.version<={1}".format(table, version)) # Detach original database db.list('DETACH DATABASE orig') db.list('PRAGMA foreign_keys=ON') db.close(silent=True)
python
def snapshot(self, name_db='export.db', version=1.0): """ Function to generate a snapshot of the database by version number. Parameters ---------- name_db: string Name of the new database (Default: export.db) version: float Version number to export (Default: 1.0) """ # Check if file exists if os.path.isfile(name_db): import datetime date = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M") print("Renaming existing file {} to {}".format(name_db, name_db.replace('.db', date + '.db'))) os.system("mv {} {}".format(name_db, name_db.replace('.db', date + '.db'))) # Create a new database from existing database schema t, = self.query("select sql from sqlite_master where type = 'table'", unpack=True) schema = ';\n'.join(t) + ';' os.system("sqlite3 {} '{}'".format(name_db, schema)) # Attach database to newly created database db = Database(name_db) db.list('PRAGMA foreign_keys=OFF') # Temporarily deactivate foreign keys for the snapshot db.list("ATTACH DATABASE '{}' AS orig".format(self.dbpath)) # For each table in database, insert records if they match version number t = db.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() for table in [t for t in all_tables if t not in ['sqlite_sequence', 'changelog']]: # Check if this is table with version column metadata = db.query("PRAGMA table_info({})".format(table), fmt='table') columns, types, required, pk = [np.array(metadata[n]) for n in ['name', 'type', 'notnull', 'pk']] print(table, columns) if 'version' not in columns: db.modify("INSERT INTO {0} SELECT * FROM orig.{0}".format(table)) else: db.modify("INSERT INTO {0} SELECT * FROM orig.{0} WHERE orig.{0}.version<={1}".format(table, version)) # Detach original database db.list('DETACH DATABASE orig') db.list('PRAGMA foreign_keys=ON') db.close(silent=True)
[ "def", "snapshot", "(", "self", ",", "name_db", "=", "'export.db'", ",", "version", "=", "1.0", ")", ":", "# Check if file exists", "if", "os", ".", "path", ".", "isfile", "(", "name_db", ")", ":", "import", "datetime", "date", "=", "datetime", ".", "dat...
Function to generate a snapshot of the database by version number. Parameters ---------- name_db: string Name of the new database (Default: export.db) version: float Version number to export (Default: 1.0)
[ "Function", "to", "generate", "a", "snapshot", "of", "the", "database", "by", "version", "number", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1867-L1912
BDNYC/astrodbkit
astrodbkit/astrodb.py
Database.table
def table(self, table, columns, types, constraints='', pk='', new_table=False): """ Rearrange, add or delete columns from database **table** with desired ordered list of **columns** and corresponding data **types**. Parameters ---------- table: sequence The name of the table to modify columns: list A sequence of the columns in the order in which they are to appear in the SQL table types: sequence A sequence of the types corresponding to each column in the columns list above. constraints: sequence (optional) A sequence of the constraints for each column, e.g. '', 'UNIQUE', 'NOT NULL', etc. pk: string or list Name(s) of the primary key(s) if other than ID new_table: bool Create a new table """ goodtogo = True # Make sure there is an integer primary key, unique, not null 'id' column # and the appropriate number of elements in each sequence if columns[0] != 'id': print("Column 1 must be called 'id'") goodtogo = False if constraints: if 'UNIQUE' not in constraints[0].upper() and 'NOT NULL' not in constraints[0].upper(): print("'id' column constraints must be 'UNIQUE NOT NULL'") goodtogo = False else: constraints = ['UNIQUE NOT NULL'] + ([''] * (len(columns) - 1)) # Set UNIQUE NOT NULL constraints for the primary keys, except ID which is already has them if pk: if not isinstance(pk, type(list())): pk = list(pk) for elem in pk: if elem == 'id': continue else: ind, = np.where(columns == elem) constraints[ind] = 'UNIQUE NOT NULL' else: pk = ['id'] if not len(columns) == len(types) == len(constraints): print("Must provide equal length *columns ({}), *types ({}), and *constraints ({}) sequences." \ .format(len(columns), len(types), len(constraints))) goodtogo = False if goodtogo: t = self.query("SELECT name FROM sqlite_master", unpack=True, fmt='table') tables = t['name'].tolist() # If the table exists, modify the columns if table in tables and not new_table: # Rename the old table and create a new one self.list("DROP TABLE IF EXISTS TempOldTable") self.list("ALTER TABLE {0} RENAME TO TempOldTable".format(table)) create_txt = "CREATE TABLE {0} (\n\t{1}".format(table, ', \n\t'.join( ['{} {} {}'.format(c, t, r) for c, t, r in zip(columns, types, constraints)])) create_txt += ', \n\tPRIMARY KEY({})\n)'.format(', '.join([elem for elem in pk])) # print(create_txt.replace(',', ',\n')) self.list(create_txt) # Populate the new table and drop the old one old_columns = [c for c in self.query("PRAGMA table_info(TempOldTable)", unpack=True)[1] if c in columns] self.list("INSERT INTO {0} ({1}) SELECT {1} FROM TempOldTable".format(table, ','.join(old_columns))) # Check for and add any foreign key constraints t = self.query('PRAGMA foreign_key_list(TempOldTable)', fmt='table') if not isinstance(t, type(None)): self.list("DROP TABLE TempOldTable") self.add_foreign_key(table, t['table'].tolist(), t['from'].tolist(), t['to'].tolist()) else: self.list("DROP TABLE TempOldTable") # If the table does not exist and new_table is True, create it elif table not in tables and new_table: create_txt = "CREATE TABLE {0} (\n\t{1}".format(table, ', \n\t'.join( ['{} {} {}'.format(c, t, r) for c, t, r in zip(columns, types, constraints)])) create_txt += ', \n\tPRIMARY KEY({})\n)'.format(', '.join([elem for elem in pk])) # print(create_txt.replace(',', ',\n')) print(create_txt) self.list(create_txt) # Otherwise the table to be modified doesn't exist or the new table to add already exists, so do nothing else: if new_table: print('Table {} already exists. Set *new_table=False to modify.'.format(table.upper())) else: print('Table {} does not exist. Could not modify. Set *new_table=True to add a new table.'.format( table.upper())) else: print('The {} table has not been {}. Please make sure your table columns, \ types, and constraints are formatted properly.'.format(table.upper(), \ 'created' if new_table else 'modified'))
python
def table(self, table, columns, types, constraints='', pk='', new_table=False): """ Rearrange, add or delete columns from database **table** with desired ordered list of **columns** and corresponding data **types**. Parameters ---------- table: sequence The name of the table to modify columns: list A sequence of the columns in the order in which they are to appear in the SQL table types: sequence A sequence of the types corresponding to each column in the columns list above. constraints: sequence (optional) A sequence of the constraints for each column, e.g. '', 'UNIQUE', 'NOT NULL', etc. pk: string or list Name(s) of the primary key(s) if other than ID new_table: bool Create a new table """ goodtogo = True # Make sure there is an integer primary key, unique, not null 'id' column # and the appropriate number of elements in each sequence if columns[0] != 'id': print("Column 1 must be called 'id'") goodtogo = False if constraints: if 'UNIQUE' not in constraints[0].upper() and 'NOT NULL' not in constraints[0].upper(): print("'id' column constraints must be 'UNIQUE NOT NULL'") goodtogo = False else: constraints = ['UNIQUE NOT NULL'] + ([''] * (len(columns) - 1)) # Set UNIQUE NOT NULL constraints for the primary keys, except ID which is already has them if pk: if not isinstance(pk, type(list())): pk = list(pk) for elem in pk: if elem == 'id': continue else: ind, = np.where(columns == elem) constraints[ind] = 'UNIQUE NOT NULL' else: pk = ['id'] if not len(columns) == len(types) == len(constraints): print("Must provide equal length *columns ({}), *types ({}), and *constraints ({}) sequences." \ .format(len(columns), len(types), len(constraints))) goodtogo = False if goodtogo: t = self.query("SELECT name FROM sqlite_master", unpack=True, fmt='table') tables = t['name'].tolist() # If the table exists, modify the columns if table in tables and not new_table: # Rename the old table and create a new one self.list("DROP TABLE IF EXISTS TempOldTable") self.list("ALTER TABLE {0} RENAME TO TempOldTable".format(table)) create_txt = "CREATE TABLE {0} (\n\t{1}".format(table, ', \n\t'.join( ['{} {} {}'.format(c, t, r) for c, t, r in zip(columns, types, constraints)])) create_txt += ', \n\tPRIMARY KEY({})\n)'.format(', '.join([elem for elem in pk])) # print(create_txt.replace(',', ',\n')) self.list(create_txt) # Populate the new table and drop the old one old_columns = [c for c in self.query("PRAGMA table_info(TempOldTable)", unpack=True)[1] if c in columns] self.list("INSERT INTO {0} ({1}) SELECT {1} FROM TempOldTable".format(table, ','.join(old_columns))) # Check for and add any foreign key constraints t = self.query('PRAGMA foreign_key_list(TempOldTable)', fmt='table') if not isinstance(t, type(None)): self.list("DROP TABLE TempOldTable") self.add_foreign_key(table, t['table'].tolist(), t['from'].tolist(), t['to'].tolist()) else: self.list("DROP TABLE TempOldTable") # If the table does not exist and new_table is True, create it elif table not in tables and new_table: create_txt = "CREATE TABLE {0} (\n\t{1}".format(table, ', \n\t'.join( ['{} {} {}'.format(c, t, r) for c, t, r in zip(columns, types, constraints)])) create_txt += ', \n\tPRIMARY KEY({})\n)'.format(', '.join([elem for elem in pk])) # print(create_txt.replace(',', ',\n')) print(create_txt) self.list(create_txt) # Otherwise the table to be modified doesn't exist or the new table to add already exists, so do nothing else: if new_table: print('Table {} already exists. Set *new_table=False to modify.'.format(table.upper())) else: print('Table {} does not exist. Could not modify. Set *new_table=True to add a new table.'.format( table.upper())) else: print('The {} table has not been {}. Please make sure your table columns, \ types, and constraints are formatted properly.'.format(table.upper(), \ 'created' if new_table else 'modified'))
[ "def", "table", "(", "self", ",", "table", ",", "columns", ",", "types", ",", "constraints", "=", "''", ",", "pk", "=", "''", ",", "new_table", "=", "False", ")", ":", "goodtogo", "=", "True", "# Make sure there is an integer primary key, unique, not null 'id' c...
Rearrange, add or delete columns from database **table** with desired ordered list of **columns** and corresponding data **types**. Parameters ---------- table: sequence The name of the table to modify columns: list A sequence of the columns in the order in which they are to appear in the SQL table types: sequence A sequence of the types corresponding to each column in the columns list above. constraints: sequence (optional) A sequence of the constraints for each column, e.g. '', 'UNIQUE', 'NOT NULL', etc. pk: string or list Name(s) of the primary key(s) if other than ID new_table: bool Create a new table
[ "Rearrange", "add", "or", "delete", "columns", "from", "database", "**", "table", "**", "with", "desired", "ordered", "list", "of", "**", "columns", "**", "and", "corresponding", "data", "**", "types", "**", "." ]
train
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L1914-L2016
theonion/django-bulbs
bulbs/utils/vault.py
read
def read(path): """Read a secret from Vault REST endpoint""" url = '{}/{}/{}'.format(settings.VAULT_BASE_URL.rstrip('/'), settings.VAULT_BASE_SECRET_PATH.strip('/'), path.lstrip('/')) headers = {'X-Vault-Token': settings.VAULT_ACCESS_TOKEN} resp = requests.get(url, headers=headers) if resp.ok: return resp.json()['data'] else: log.error('Failed VAULT GET request: %s %s', resp.status_code, resp.text) raise Exception('Failed Vault GET request: {} {}'.format(resp.status_code, resp.text))
python
def read(path): """Read a secret from Vault REST endpoint""" url = '{}/{}/{}'.format(settings.VAULT_BASE_URL.rstrip('/'), settings.VAULT_BASE_SECRET_PATH.strip('/'), path.lstrip('/')) headers = {'X-Vault-Token': settings.VAULT_ACCESS_TOKEN} resp = requests.get(url, headers=headers) if resp.ok: return resp.json()['data'] else: log.error('Failed VAULT GET request: %s %s', resp.status_code, resp.text) raise Exception('Failed Vault GET request: {} {}'.format(resp.status_code, resp.text))
[ "def", "read", "(", "path", ")", ":", "url", "=", "'{}/{}/{}'", ".", "format", "(", "settings", ".", "VAULT_BASE_URL", ".", "rstrip", "(", "'/'", ")", ",", "settings", ".", "VAULT_BASE_SECRET_PATH", ".", "strip", "(", "'/'", ")", ",", "path", ".", "lst...
Read a secret from Vault REST endpoint
[ "Read", "a", "secret", "from", "Vault", "REST", "endpoint" ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/utils/vault.py#L15-L27
tariqdaouda/rabaDB
rabaDB/rabaSetup.py
RabaConnection.getIndexes
def getIndexes(self, rabaOnly = True) : "returns a list of all indexes in the sql database. rabaOnly returns only the indexes created by raba" sql = "SELECT * FROM sqlite_master WHERE type='index'" cur = self.execute(sql) l = [] for n in cur : if rabaOnly : if n[1].lower().find('raba') == 0 : l.append(n) else : l.append(n) return l
python
def getIndexes(self, rabaOnly = True) : "returns a list of all indexes in the sql database. rabaOnly returns only the indexes created by raba" sql = "SELECT * FROM sqlite_master WHERE type='index'" cur = self.execute(sql) l = [] for n in cur : if rabaOnly : if n[1].lower().find('raba') == 0 : l.append(n) else : l.append(n) return l
[ "def", "getIndexes", "(", "self", ",", "rabaOnly", "=", "True", ")", ":", "sql", "=", "\"SELECT * FROM sqlite_master WHERE type='index'\"", "cur", "=", "self", ".", "execute", "(", "sql", ")", "l", "=", "[", "]", "for", "n", "in", "cur", ":", "if", "raba...
returns a list of all indexes in the sql database. rabaOnly returns only the indexes created by raba
[ "returns", "a", "list", "of", "all", "indexes", "in", "the", "sql", "database", ".", "rabaOnly", "returns", "only", "the", "indexes", "created", "by", "raba" ]
train
https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L81-L92