code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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, t...
def drop_column(self, table, name)
Remove a column to an existing table.
4.565419
4.764328
0.95825
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)
Drop an index from a table.
6.189994
5.835585
1.060733
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)
Add a comment to an existing column in a table.
3.060736
2.936763
1.042214
# 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...
def add_auto_increment(self, table, name)
Modify an existing column.
5.887384
5.447969
1.080657
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_ = 'NUL...
def modify_column(self, table, name, new_name=None, data_type=None, null=None, default=None)
Modify an existing column.
2.758869
2.71662
1.015552
def list_modules(self, course_id, include=None, search_term=None, student_id=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # OPTIONAL - include if include is not None: ...
List modules. List the modules in a course
null
null
null
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): path = {} data = {} params = {} # REQUIRED - PATH - course_id ...
Create a module. Create and return a new module
null
null
null
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=...
Create a module item. Create and return a new module item
null
null
null
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...
Update a module item. Update and return an existing module item
null
null
null
def select_mastery_path(self, id, course_id, module_id, assignment_set_id=None, student_id=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - PATH - module_id pat...
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
null
null
null
def get_module_item_sequence(self, course_id, asset_id=None, asset_type=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # OPTIONAL - asset_type if asset_type is not 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.
null
null
null
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)
Instantiate data types from config
5.731238
4.47327
1.281219
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. if type(response_json_data) == list: # Return the data ...
Given a response and an optional data_key should return a dictionary of data returned as part of the response.
null
null
null
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 ...
Given a wrapped_response from a Canvas API endpoint, extract the pagination links from the response headers
null
null
null
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, ...
Generic Canvas Request Method.
null
null
null
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 value else: raise ValueError('{} must be in ISO8601 format.'.format(value))
Return the value or raise a ValueError if it is not a string in ISO8601 format.
null
null
null
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 empt...
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
4.727242
4.779905
0.988982
out = io.BytesIO() np.save(out, arr), out.seek(0) return buffer(out.read())
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
4.870843
8.23115
0.591757
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'] * fac...
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 containin...
1.994099
1.995994
0.99905
out = io.BytesIO(array) out.seek(0) return np.load(out)
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.
4.031502
6.359038
0.63398
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('ec...
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 ...
4.216298
4.39309
0.959757
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...
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 ----...
4.253037
4.303964
0.988167
# 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 name...
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
4.294712
4.359903
0.985048
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.is...
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.
2.584593
2.595891
0.995648
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 d...
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 sho...
4.024909
4.066832
0.989692
# 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 ...
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 ...
2.761321
2.844056
0.970909
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 y...
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).
5.92949
5.510353
1.076064
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().spl...
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:...
3.487639
3.414109
1.021537
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 ...
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 nam...
2.84174
2.734226
1.039322
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 ['so...
def info(self)
Prints out information for the loaded database, namely the available tables and the number of entries for each.
5.536893
4.998719
1.107662
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: ...
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 Retu...
3.761315
3.735317
1.00696
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 ...
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 colu...
4.537169
4.490466
1.0104
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.in...
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...
3.479913
3.149599
1.104875
# 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...
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 ...
7.005466
6.759964
1.036317
# 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'].heade...
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 ...
3.183359
2.991204
1.06424
# 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 ...
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 ...
3.795572
3.825335
0.99222
# 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) ...
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: ...
3.415719
3.424873
0.997327
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 dict...
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 sou...
5.39101
5.021765
1.073529
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='tabl...
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 publ...
3.78145
3.615457
1.045912
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 i...
def save(self, directory=None)
Dump the entire contents of the database into the tabledata directory as ascii files
3.583929
3.372391
1.062726
try: pprint(self.query("PRAGMA table_info({})".format(table), fmt='table')) except ValueError: print('Table {} not found'.format(table))
def schema(self, table)
Print the table schema Parameters ---------- table: str The table name
5.300868
5.052184
1.049223
# 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 {} {}".forma...
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)
3.24056
3.194247
1.014499
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: ...
def read(path)
Read a secret from Vault REST endpoint
2.641351
2.393916
1.10336
"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) retu...
def getIndexes(self, rabaOnly = True)
returns a list of all indexes in the sql database. rabaOnly returns only the indexes created by raba
3.098352
2.231757
1.388302
"drops all indexes created by Raba" for n in self.getIndexes(rabaOnly = True) : self.dropIndexByName(n[1])
def flushIndexes(self)
drops all indexes created by Raba
13.926283
6.806672
2.045975
versioTest = sq.sqlite_version_info[0] >= 3 and sq.sqlite_version_info[1] >= 8 if len(where) > 0 and not versioTest : #raise FutureWarning("Partial joints (with the WHERE clause) where only implemented in sqlite 3.8.0+, your version is: %s. Sorry about that." % sq.sqlite_version) sys.stderr.write("WARNIN...
def createIndex(self, table, fields, where = '', whereValues = [])
Creates indexes for Raba Class a fields resulting in significantly faster SELECTs but potentially slower UPADTES/INSERTS and a bigger DBs Fields can be a list of fields for Multi-Column Indices, or siply the name of one single field. With the where close you can create a partial index by adding conditions ----- ...
3.237124
3.100317
1.044127
"DROPs an index created by RabaDb see createIndexes()" indexTable = self.makeIndexTableName(table, fields, where) self.dropIndexByName(indexTable)
def dropIndex(self, table, fields, where = '')
DROPs an index created by RabaDb see createIndexes()
20.279015
4.539651
4.467086
"If bol == True, Raba will keep a count of every query time performed, logQueries == True it will also keep a record of all the queries " self._enableStats = bol self._logQueries = logQueries if bol : self._enableStats = True self.eraseStats() self.startTime = time.time()
def enableStats(self, bol, logQueries = False)
If bol == True, Raba will keep a count of every query time performed, logQueries == True it will also keep a record of all the queries
7.811359
2.730992
2.860264
"executes an sql command for you or appends it to the current transacations. returns a cursor" sql = sql.strip() self._debugActions(sql, values) cur = self.connection.cursor() cur.execute(sql, values) return cur
def execute(self, sql, values = ())
executes an sql command for you or appends it to the current transacations. returns a cursor
7.850294
3.06398
2.562123
if self.saveIniator != None : return False self.saveIniator = obj return True
def initateSave(self, obj)
Tries to initiates a save sessions. Each object can only be saved once during a session. The session begins when a raba object initates it and ends when this object and all it's dependencies have been saved
7.887726
7.940967
0.993295
if self.saveIniator is obj and not self.inTransaction : self.saveIniator = None self.savedObject = set() self.connection.commit() return True return False
def freeSave(self, obj)
THIS IS WHERE COMMITS TAKE PLACE! Ends a saving session, only the initiator can end a session. The commit is performed at the end of the session
8.496527
7.211232
1.178235
if obj._runtimeId in self.savedObject : return False self.savedObject.add(obj._runtimeId) return True
def registerSave(self, obj)
Each object can only be save donce during a session, returns False if the object has already been saved. True otherwise
6.067129
5.341877
1.135767
sql = 'DELETE FROM %s WHERE %s' % (table, where) return self.execute(sql, values)
def delete(self, table, where, values = ())
where is a string of condictions without the sql 'WHERE'. ex: deleteRabaObject('Gene', where = raba_id = ?, values = (33,))
2.844976
2.247963
1.26558
self.loadedRabaClasses[cls.__name__] = cls sql = 'SELECT MAX(raba_id) from %s LIMIT 1' % (cls.__name__) cur = self.execute(sql) res = cur.fetchone() try : return int(res[0])+1 except TypeError: return 0
def getLastRabaId(self, cls)
keep track all loaded raba classes
3.530496
3.109343
1.135448
'creates a table and resturns the ursor, if the table already exists returns None' if not self.tableExits(tableName) : sql = 'CREATE TABLE %s ( %s)' % (tableName, strFields) self.execute(sql) self.tables.add(tableName) return True return False
def createTable(self, tableName, strFields)
creates a table and resturns the ursor, if the table already exists returns None
5.285258
2.949157
1.792125
"Removes columns from a RabaObj table. lstFieldsToKeep should not contain raba_id or json fileds" if len(lstFieldsToKeep) == 0 : raise ValueError("There are no fields to keep") cpy = name+'_copy' sqlFiledsStr = ', '.join(lstFieldsToKeep) self.createTable(cpy, 'raba_id INTEGER PRIMARY KEY AUTOINCREMENT, js...
def dropColumnsFromRabaObjTable(self, name, lstFieldsToKeep)
Removes columns from a RabaObj table. lstFieldsToKeep should not contain raba_id or json fileds
3.576998
2.716604
1.316717
response = self.client.get( self.client.USER_LIKES % (self.name, offset, limit)) return self._parse_response(response, strack)
def get_likes(self, offset=0, limit=50)
Get user's likes.
8.915491
7.598961
1.173251
response = self.client.get( self.client.USER_TRACKS % (self.name, offset, limit)) return self._parse_response(response, strack)
def get_tracks(self, offset=0, limit=50)
Get user's tracks.
8.357672
7.10254
1.176716
response = self.client.get( self.client.USER_PLAYLISTS % (self.name, offset, limit)) return self._parse_response(response, splaylist) return playlists
def get_playlists(self, offset=0, limit=50)
Get user's playlists.
8.464819
7.563987
1.119095
objects = json.loads(response.read().decode("utf-8")) list = [] for obj in objects: list.append(target_object(obj, client=self.client)) return list
def _parse_response(self, response, target_object=strack)
Generic response parser method
3.322648
3.26702
1.017027
def create_external_feed_courses(self, url, course_id, header_match=None, verbosity=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - url data["url"] = url ...
Create an external feed. Create a new external feed for the course or group.
null
null
null
def create_external_feed_groups(self, url, group_id, header_match=None, verbosity=None): path = {} data = {} params = {} # REQUIRED - PATH - group_id path["group_id"] = group_id # REQUIRED - url data["url"] = url ...
Create an external feed. Create a new external feed for the course or group.
null
null
null
def delete_external_feed_courses(self, course_id, external_feed_id): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - PATH - external_feed_id path["external_feed_id"] ...
Delete an external feed. Deletes the external feed.
null
null
null
def delete_external_feed_groups(self, group_id, external_feed_id): path = {} data = {} params = {} # REQUIRED - PATH - group_id path["group_id"] = group_id # REQUIRED - PATH - external_feed_id path["external_feed_id"] = ext...
Delete an external feed. Deletes the external feed.
null
null
null
counts = {} for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts
def count_token_occurrences(cls, words)
Creates a key/value set of word/count for a given sample of text :param words: full list of all tokens, non-unique :type words: list :return: key/value pairs of words and their counts in the list :rtype: dict
1.869123
2.243773
0.833027
total_tally = 0.0 probs = {} for category, bayes_category in \ self.categories.get_categories().items(): count = bayes_category.get_tally() total_tally += count probs[category] = count # Calculating the probability for...
def calculate_category_probability(self)
Caches the individual probabilities for each category
3.187222
3.107884
1.025528
try: bayes_category = self.categories.get_category(category) except KeyError: bayes_category = self.categories.add_category(category) tokens = self.tokenizer(str(text)) occurrence_counts = self.count_token_occurrences(tokens) for word, count in ...
def train(self, category, text)
Trains a category with a sample of text :param category: the name of the category we want to train :type category: str :param text: the text we want to train the category with :type text: str
4.06773
4.029119
1.009583
try: bayes_category = self.categories.get_category(category) except KeyError: return tokens = self.tokenizer(str(text)) occurance_counts = self.count_token_occurrences(tokens) for word, count in occurance_counts.items(): bayes_catego...
def untrain(self, category, text)
Untrains a category with a sample of text :param category: the name of the category we want to train :type category: str :param text: the text we want to untrain the category with :type text: str
4.835713
4.923694
0.982131
score = self.score(text) if not score: return None return sorted(score.items(), key=lambda v: v[1])[-1][0]
def classify(self, text)
Chooses the highest scoring category for a sample of text :param text: sample text to classify :type text: str :return: the "winning" category :rtype: str
3.773208
4.220073
0.89411
occurs = self.count_token_occurrences(self.tokenizer(text)) scores = {} for category in self.categories.get_categories().keys(): scores[category] = 0 categories = self.categories.get_categories().items() for word, count in occurs.items(): token_...
def score(self, text)
Scores a sample of text :param text: sample text to score :type text: str :return: dict of scores per category :rtype: dict
3.676246
3.710863
0.990672
# P that any given token IS in this category prc = self.probabilities[cat]['prc'] # P that any given token is NOT in this category prnc = self.probabilities[cat]['prnc'] # P that this token is NOT of this category prtnc = (token_tally - token_score) / token_tally...
def calculate_bayesian_probability(self, cat, token_score, token_tally)
Calculates the bayesian probability for a given token/category :param cat: The category we're scoring for this token :type cat: str :param token_score: The tally of this token for this category :type token_score: float :param token_tally: The tally total for this token from all ...
3.937947
3.739333
1.053115
try: bayes_category = self.categories.get_category(category) except KeyError: return 0 return bayes_category.get_tally()
def tally(self, category)
Gets the tally for a requested category :param category: The category we want a tally for :type category: str :return: tally for a given category :rtype: int
4.574537
4.719685
0.969246
filename = self.cache_path if \ self.cache_path[-1:] == '/' else \ self.cache_path + '/' filename += self.cache_file return filename
def get_cache_location(self)
Gets the location of the cache file :return: the location of the cache file :rtype: string
4.860465
5.442874
0.892996
filename = self.get_cache_location() pickle.dump(self.categories, open(filename, 'wb'))
def cache_persist(self)
Saves the current trained data to the cache. This is initiated by the program using this module
6.633926
6.001108
1.10545
filename = self.get_cache_location() if not os.path.exists(filename): return False categories = pickle.load(open(filename, 'rb')) assert isinstance(categories, BayesCategories), \ "Cache data is either corrupt or invalid" self.categories = cat...
def cache_train(self)
Loads the data for this classifier from a cache file :return: whether or not we were successful :rtype: bool
6.78118
6.27338
1.080945
if created: for feature_type in FeatureType.objects.all(): FeatureTypeRate.objects.create(role=self, feature_type=feature_type, rate=0)
def create_feature_type_rates(self, created=False)
If the role is being created we want to populate a rate for all existing feature_types.
2.663527
1.891465
1.408182
if namespace is None: namespace = [] if isinstance(namespace, basestring): namespace = [namespace] for n, m in inspect.getmembers(self, inspect.ismethod): if hasattr(m, 'export_rpc'): try: name = seperator.join(nam...
def addToService(self, service, namespace=None, seperator='.')
Add this Handler's exported methods to an RPC Service instance.
3.05482
2.576052
1.185853
if total > 0: n = int(float(width) * float(done) / float(total)) sys.stdout.write("\r{0} [{1}{2}] ({3}/{4})".format(text, '#' * n, ' ' * (width - n), done, total)) sys.stdout.flush()
def print_progress_bar(text, done, total, width)
Print progress bar.
2.085719
2.128079
0.980094
from collections import Iterable, namedtuple, defaultdict from autocmake.extract import extract_list, to_d, to_l from autocmake.parse_rst import parse_cmake_module cleaned_config = defaultdict(lambda: []) modules = [] Module = namedtuple('Module', 'path name') num_sources = len(extra...
def fetch_modules(config, relative_path, download_directory)
Assemble modules which will be included in CMakeLists.txt.
3.797705
3.710705
1.023446
if len(argv) != 2: sys.stderr.write("\nYou can update a project in two steps.\n\n") sys.stderr.write("Step 1: Update or create infrastructure files\n") sys.stderr.write(" which will be needed to configure and build the project:\n") sys.stderr.write(" $ {0} --self\...
def main(argv)
Main function.
3.321248
3.333266
0.996394
# we do not use the nicer sys.version_info.major # for compatibility with Python < 2.7 if sys.version_info[0] > 2: import urllib.request class URLopener(urllib.request.FancyURLopener): def http_error_default(self, url, fp, errcode, errmsg, headers): sys.stde...
def fetch_url(src, dst)
Fetch file from URL src and save it to dst.
1.995779
1.97987
1.008035
def get_single_poll_submission(self, id, poll_id, poll_session_id): path = {} data = {} params = {} # REQUIRED - PATH - poll_id path["poll_id"] = poll_id # REQUIRED - PATH - poll_session_id path["poll_session_id"] = poll_se...
Get a single poll submission. Returns the poll submission with the given id
null
null
null
def create_single_poll_submission(self, poll_id, poll_session_id, poll_submissions_poll_choice_id): path = {} data = {} params = {} # REQUIRED - PATH - poll_id path["poll_id"] = poll_id # REQUIRED - PATH - poll_session_id p...
Create a single poll submission. Create a new poll submission for this poll session
null
null
null
search_kwargs = {"published": False} query_params = get_query_params(self.request) for field_name in ("status"): if field_name in query_params: search_kwargs[field_name] = query_params.get(field_name) if "search" in query_params: search...
def list(self, request, *args, **kwargs)
Modified list view to driving listing from ES
2.640218
2.577585
1.024299
# Give permission if we're not protecting this method if self.protected_methods and request.method not in self.protected_methods: return True user = getattr(request, "user", None) if not user or user.is_anonymous(): return False if self.require...
def has_object_permission(self, request, view, obj)
determines if requesting user has permissions for the object :param request: WSGI request object - where we get the user from :param view: the view calling for permission :param obj: the object in question :return: `bool`
4.119857
4.28758
0.960882
has_permission = False if request.method == "GET" \ or request.method in ["PUT", "POST", "DELETE"] \ and request.user and request.user.is_superuser: has_permission = True return has_permission
def has_permission(self, request, view)
If method is GET, user can access, if method is PUT or POST user must be a superuser.
2.954451
2.333886
1.265893
self.parent = app app.add_subapp(self.prefix, self.app)
def bind(self, app)
Bind API to Muffin.
6.982262
6.839777
1.020832
if isinstance(methods, str): methods = [methods] def wrapper(handler): if isinstance(handler, (FunctionType, MethodType)): handler = RESTHandler.from_view(handler, *(methods or ['GET'])) if handler.name in self.handlers: rai...
def register(self, *paths, methods=None, name=None)
Register handler to the API.
3.897657
3.808631
1.023375
if self.parent is None: return {} spec = APISpec( self.parent.name, self.parent.cfg.get('VERSION', ''), plugins=['apispec.ext.marshmallow'], basePatch=self.prefix ) for paths, handler in self.handlers.items(): spec.add_tag({ ...
def swagger_schema(self, request)
Render API Schema.
3.478577
3.434894
1.012717
import warnings warnings.warn("lepton.domain.Box is deprecated, use AABox instead. " "This domain class will mean something different in future versions of lepton", stacklevel=2) return AABox(*args, **kw)
def Box(*args, **kw)
Axis-aligned box domain (same as AABox for now) WARNING: Deprecated, use AABox instead. This domain will mean something different in future versions of lepton
9.605921
2.867407
3.350037
pzone = PZone.objects.get(**kwargs) # get the data and loop through operate_on, applying them if necessary when = timezone.now() data = pzone.data for operation in pzone.operations.filter(when__lte=when, applied=False): data = operation.apply(data) operation.applied = True ...
def update_pzone(**kwargs)
Update pzone data in the DB
5.373383
5.402475
0.994615
# get pzone based on id pzone = self.get(**kwargs) # cache the current time now = timezone.now() # ensure we have some value for when if when is None: when = now if when < now: histories = pzone.history.filter(date__lte=when) ...
def operate_on(self, when=None, apply=False, **kwargs)
Do something with operate_on. If apply is True, all transactions will be applied and saved via celery task.
5.275754
5.022749
1.050372
return self.operate_on(when=when, apply=False, **kwargs)
def preview(self, when=timezone.now(), **kwargs)
Preview transactions, but don't actually save changes to list.
13.06559
9.874812
1.323123
url = None if not self.get("downloadable"): try: url = self.client.get_location( self.client.STREAM_URL % self.get("id")) except serror as e: print(e) if not url: try: url = self.cli...
def get_download_link(self)
Get direct download link with soudcloud's redirect system.
3.627482
3.283287
1.104833
mtype = magic.from_file(filepath, mime=True) if type(mtype) == bytes: mtype = mtype.decode("utf-8") if mtype == "audio/mpeg": ext = ".mp3" elif mtype == "audio/x-wav": ext = ".wav" else: ext = "." + self.get("original-form...
def get_file_extension(self, filepath)
This method check mimetype to define file extension. If it can't, it use original-format metadata.
2.778816
2.136987
1.300343
directory = "{0}/{1}/".format(localdir, self.get("username")) if not os.path.exists(directory): os.makedirs(directory) return directory
def gen_localdir(self, localdir)
Generate local directory where track will be saved. Create it if not exists.
3.653125
3.217123
1.135525
path = glob.glob(self.gen_localdir(localdir) + self.gen_filename() + "*") if len(path) > 0 and os.path.getsize(path[0]) > 0: return True return False
def track_exists(self, localdir)
Check if track exists in local directory.
3.907495
3.435857
1.137269
ignore_file = "%s/.ignore" % localdir list = [] if os.path.exists(ignore_file): f = open(ignore_file) ignored = f.readlines() f.close() for i in ignored: list.append("%s/%s" % (localdir, i.rstrip())) return list
def get_ignored_tracks(self, localdir)
Get ignored tracks list.
2.61513
2.437745
1.072766
local_file = self.gen_localdir(localdir) + self.gen_filename() if self.track_exists(localdir): print("Track {0} already downloaded, skipping!".format( self.get("id"))) return False if local_file in self.get_ignored_tracks(localdir): ...
def download(self, localdir, max_retry)
Download a track in local directory.
3.135658
3.015913
1.039704
if self.downloaded is False: raise serror("Track not downloaded, can't process tags..") filetype = magic.from_file(self.filepath, mime=True) if filetype != "audio/mpeg": raise serror("Cannot process tags for file type %s." % filetype) print("Processing t...
def process_tags(self, tag=None)
Process ID3 Tags for mp3 files.
4.691761
4.170908
1.124878