code
stringlengths
1
18.2k
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 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 V...
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 # Re...
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, ] # ...
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 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. "...
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 sect...
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...
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"...
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=param...
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 execute(self, command): """Execute a single SQL query without returning a result.""" self._cursor.execute(command) self._commit() return True
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() cont...
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...
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._curso...
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_NIC...
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 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._rab...
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(...
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'...
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 type...
'.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__...
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...
not raw : yield RabaPupa(self.rabaClass, v[0]) else : yield v
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), sq...
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 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__...
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 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 ea...
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...
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 = '...
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 '{...
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 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}'...
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)) s...
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...
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 para...
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_te...
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_...
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 u...
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=...
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 N...
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_it...
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, mod...
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 ta...
"""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."...
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 a...
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_re...
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[...
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_s...
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 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 n...
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 spli...
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...
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 form...
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 alrea...
print("Please provide a path and file name with a .db file extension, e.g. /Users/<username>/Desktop/test.db")
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) retur...
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 conta...
slat2 - slat1 * clat2 * cdlon numerator = math.sqrt(num1 ** 2 + num2 ** 2) denominator = slat1 * slat2 + clat1 * clat2 * cdlon return np.arctan2(numerator, denominator) / factor
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_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 co...
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....
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...
= 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 = valT...
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) spect...
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 ...
'%.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 = di...
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 dat...
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:...
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['DA...
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...
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 ...
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 'o...
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 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...
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, mo...
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.tabl...
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, st...
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, ...
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')...
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.isf...
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_reco...
{} 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: {}'...
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 ...
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 TAB...
', \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...
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 sour...
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( column...
= "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(s...
== ' 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, duplicat...
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. "...
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 id...
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'...
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(tabl...
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...
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.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 col...
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 = "...
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 ...