Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def copy_dash(self, dashboard_id): session = db.session() data = json.loads(request.form.get('data')) dash = models.Dashboard() original_dash = ( session .query(models.Dashboard) .filter_by(id=dashb...
[ "Copy dashboard" ]
Please provide a description of the function:def save_dash(self, dashboard_id): session = db.session() dash = (session .query(models.Dashboard) .filter_by(id=dashboard_id).first()) check_ownership(dash, raise_if_false=True) data = json.loads(reque...
[ "Save a dashboard's metadata" ]
Please provide a description of the function:def add_slices(self, dashboard_id): data = json.loads(request.form.get('data')) session = db.session() Slice = models.Slice # noqa dash = ( session.query(models.Dashboard).filter_by(id=dashboard_id).first()) check...
[ "Add and save slices to a dashboard" ]
Please provide a description of the function:def recent_activity(self, user_id): M = models # noqa if request.args.get('limit'): limit = int(request.args.get('limit')) else: limit = 1000 qry = ( db.session.query(M.Log, M.Dashboard, M.Slice)...
[ "Recent activity (actions) for a given user" ]
Please provide a description of the function:def fave_dashboards_by_username(self, username): user = security_manager.find_user(username=username) return self.fave_dashboards(user.get_id())
[ "This lets us use a user's username to pull favourite dashboards" ]
Please provide a description of the function:def user_slices(self, user_id=None): if not user_id: user_id = g.user.id Slice = models.Slice # noqa FavStar = models.FavStar # noqa qry = ( db.session.query(Slice, FavStar.dttm).j...
[ "List of slices a user created, or faved" ]
Please provide a description of the function:def created_slices(self, user_id=None): if not user_id: user_id = g.user.id Slice = models.Slice # noqa qry = ( db.session.query(Slice) .filter( sqla.or_( Slice.created_...
[ "List of slices created by this user" ]
Please provide a description of the function:def fave_slices(self, user_id=None): if not user_id: user_id = g.user.id qry = ( db.session.query( models.Slice, models.FavStar.dttm, ) .join( models.FavS...
[ "Favorite slices for a user" ]
Please provide a description of the function:def warm_up_cache(self): slices = None session = db.session() slice_id = request.args.get('slice_id') table_name = request.args.get('table_name') db_name = request.args.get('db_name') if not slice_id and not (table_na...
[ "Warms up the cache for the slice or table.\n\n Note for slices a force refresh occurs.\n " ]
Please provide a description of the function:def favstar(self, class_name, obj_id, action): session = db.session() FavStar = models.FavStar # noqa count = 0 favs = session.query(FavStar).filter_by( class_name=class_name, obj_id=obj_id, user_id=g.user.get...
[ "Toggle favorite stars on Slices and Dashboard" ]
Please provide a description of the function:def dashboard(self, dashboard_id): session = db.session() qry = session.query(models.Dashboard) if dashboard_id.isdigit(): qry = qry.filter_by(id=int(dashboard_id)) else: qry = qry.filter_by(slug=dashboard_id) ...
[ "Server side rendering for a dashboard" ]
Please provide a description of the function:def sync_druid_source(self): payload = request.get_json(force=True) druid_config = payload['config'] user_name = payload['user'] cluster_name = payload['cluster'] user = security_manager.find_user(username=user_name) ...
[ "Syncs the druid datasource in main db with the provided config.\n\n The endpoint takes 3 arguments:\n user - user name to perform the operation as\n cluster - name of the druid cluster\n config - configuration stored in json that contains:\n name: druid dataso...
Please provide a description of the function:def cache_key_exist(self, key): key_exist = True if cache.get(key) else False status = 200 if key_exist else 404 return json_success(json.dumps({'key_exist': key_exist}), status=status)
[ "Returns if a key from cache exist" ]
Please provide a description of the function:def results(self, key): if not results_backend: return json_error_response("Results backend isn't configured") read_from_results_backend_start = now_as_float() blob = results_backend.get(key) stats_logger.timing( ...
[ "Serves a key off of the results backend" ]
Please provide a description of the function:def sql_json(self): async_ = request.form.get('runAsync') == 'true' sql = request.form.get('sql') database_id = request.form.get('database_id') schema = request.form.get('schema') or None template_params = json.loads( ...
[ "Runs arbitrary sql and returns and json" ]
Please provide a description of the function:def csv(self, client_id): logging.info('Exporting CSV file [{}]'.format(client_id)) query = ( db.session.query(Query) .filter_by(client_id=client_id) .one() ) rejected_tables = security_manager.rej...
[ "Download the query results as csv." ]
Please provide a description of the function:def queries(self, last_updated_ms): stats_logger.incr('queries') if not g.user.get_id(): return json_error_response( 'Please login to access the queries.', status=403) # Unix time, milliseconds. last_updat...
[ "Get the updated queries." ]
Please provide a description of the function:def search_queries(self) -> Response: query = db.session.query(Query) if security_manager.can_only_access_owned_queries(): search_user_id = g.user.get_user_id() else: search_user_id = request.args.get('user_id') ...
[ "\n Search for previously run sqllab queries. Used for Sqllab Query Search\n page /superset/sqllab#search.\n\n Custom permission can_only_search_queries_owned restricts queries\n to only queries run by current user.\n\n :returns: Response with list of sql query dicts\n " ]
Please provide a description of the function:def welcome(self): if not g.user or not g.user.get_id(): return redirect(appbuilder.get_url_for_login) welcome_dashboard_id = ( db.session .query(UserAttribute.welcome_dashboard_id) .filter_by(user_id=...
[ "Personalized welcome page" ]
Please provide a description of the function:def profile(self, username): if not username and g.user: username = g.user.username payload = { 'user': bootstrap_user_data(username, include_perms=True), 'common': self.common_bootsrap_payload(), } ...
[ "User profile page" ]
Please provide a description of the function:def sqllab(self): d = { 'defaultDbId': config.get('SQLLAB_DEFAULT_DBID'), 'common': self.common_bootsrap_payload(), } return self.render_template( 'superset/basic.html', entry='sqllab', ...
[ "SQL Editor" ]
Please provide a description of the function:def slice_query(self, slice_id): viz_obj = get_viz(slice_id) security_manager.assert_datasource_permission(viz_obj.datasource) return self.get_query_string_response(viz_obj)
[ "\n This method exposes an API endpoint to\n get the database query string for this slice\n " ]
Please provide a description of the function:def schemas_access_for_csv_upload(self): if not request.args.get('db_id'): return json_error_response( 'No database is allowed for your csv upload') db_id = int(request.args.get('db_id')) database = ( ...
[ "\n This method exposes an API endpoint to\n get the schema access control settings for csv upload in this database\n " ]
Please provide a description of the function:def stats_timing(stats_key, stats_logger): start_ts = now_as_float() try: yield start_ts except Exception as e: raise e finally: stats_logger.timing(stats_key, now_as_float() - start_ts)
[ "Provide a transactional scope around a series of operations." ]
Please provide a description of the function:def etag_cache(max_age, check_perms=bool): def decorator(f): @wraps(f) def wrapper(*args, **kwargs): # check if the user can access the resource check_perms(*args, **kwargs) # for POST requests we can't set cache ...
[ "\n A decorator for caching views and handling etag conditional requests.\n\n The decorator adds headers to GET requests that help with caching: Last-\n Modified, Expires and ETag. It also handles conditional requests, when the\n client send an If-Matches header.\n\n If a cache is set, the decorator ...
Please provide a description of the function:def apply_limit_to_sql(cls, sql, limit, database): if cls.limit_method == LimitMethod.WRAP_SQL: sql = sql.strip('\t\n ;') qry = ( select('*') .select_from( TextAsFrom(text(sql), ['*'...
[ "Alters the SQL statement to apply a LIMIT clause" ]
Please provide a description of the function:def modify_url_for_impersonation(cls, url, impersonate_user, username): if impersonate_user is not None and username is not None: url.username = username
[ "\n Modify the SQL Alchemy URL object with the user to impersonate if applicable.\n :param url: SQLAlchemy URL object\n :param impersonate_user: Bool indicating if impersonation is enabled\n :param username: Effective username\n " ]
Please provide a description of the function:def make_label_compatible(cls, label): label_mutated = cls.mutate_label(label) if cls.max_column_name_length and len(label_mutated) > cls.max_column_name_length: label_mutated = cls.truncate_label(label) if cls.force_column_alias_...
[ "\n Conditionally mutate and/or quote a sql column/expression label. If\n force_column_alias_quotes is set to True, return the label as a\n sqlalchemy.sql.elements.quoted_name object to ensure that the select query\n and query results have same case. Otherwise return the mutated label as...
Please provide a description of the function:def truncate_label(cls, label): label = hashlib.md5(label.encode('utf-8')).hexdigest() # truncate hash if it exceeds max length if cls.max_column_name_length and len(label) > cls.max_column_name_length: label = label[:cls.max_colu...
[ "\n In the case that a label exceeds the max length supported by the engine,\n this method is used to construct a deterministic and unique label based on\n an md5 hash.\n " ]
Please provide a description of the function:def get_table_names(cls, inspector, schema): tables = inspector.get_table_names(schema) tables.extend(inspector.get_foreign_table_names(schema)) return sorted(tables)
[ "Need to consider foreign tables for PostgreSQL" ]
Please provide a description of the function:def get_timestamp_column(expression, column_name): if expression: return expression elif column_name.lower() != column_name: return f'"{column_name}"' return column_name
[ "Postgres is unable to identify mixed case column names unless they\n are quoted." ]
Please provide a description of the function:def extract_error_message(cls, e): message = str(e) try: if isinstance(e.args, tuple) and len(e.args) > 1: message = e.args[1] except Exception: pass return message
[ "Extract error message for queries" ]
Please provide a description of the function:def fetch_result_sets(cls, db, datasource_type): result_set_df = db.get_df( .format( datasource_type.upper(), ), None) result_sets = [] for unused, row in result_set_df.iterrows(): ...
[ "Returns a list of tables [schema1.table1, schema2.table2, ...]\n\n Datasource_type can be 'table' or 'view'.\n Empty schema corresponds to the list of full names of the all\n tables or views: <schema>.<result_set_name>.\n ", "SELECT table_schema, table_name FROM INFORMATION_SCHEMA.{}S...
Please provide a description of the function:def handle_cursor(cls, cursor, query, session): logging.info('Polling the cursor for progress') polled = cursor.poll() # poll returns dict -- JSON status information or ``None`` # if the query is done # https://github.com/drop...
[ "Updates progress information" ]
Please provide a description of the function:def _partition_query( cls, table_name, limit=0, order_by=None, filters=None): limit_clause = 'LIMIT {}'.format(limit) if limit else '' order_by_clause = '' if order_by: l = [] # noqa: E741 for field, desc ...
[ "Returns a partition query\n\n :param table_name: the name of the table to get partitions from\n :type table_name: str\n :param limit: the number of partitions to be returned\n :type limit: int\n :param order_by: a list of tuples of field name and a boolean\n that deter...
Please provide a description of the function:def create_table_from_csv(form, table): def convert_to_hive_type(col_type): tableschema_to_hive_types = { 'boolean': 'BOOLEAN', 'integer': 'INT', 'number': 'DOUBLE', 'st...
[ "Uploads a csv file and creates a superset datasource in Hive.", "maps tableschema's types to hive types", "CREATE TABLE {full_table_name} ( {schema_definition} )\n ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS\n TEXTFILE LOCATION '{location}'\n tblproperties ('skip.he...
Please provide a description of the function:def handle_cursor(cls, cursor, query, session): from pyhive import hive # pylint: disable=no-name-in-module unfinished_states = ( hive.ttypes.TOperationState.INITIALIZED_STATE, hive.ttypes.TOperationState.RUNNING_STATE, ...
[ "Updates progress information" ]
Please provide a description of the function:def get_configuration_for_impersonation(cls, uri, impersonate_user, username): configuration = {} url = make_url(uri) backend_name = url.get_backend_name() # Must be Hive connection, enable impersonation, and set param auth=LDAP|KERB...
[ "\n Return a configuration dictionary that can be merged with other configs\n that can set the correct properties for impersonating users\n :param uri: URI string\n :param impersonate_user: Bool indicating if impersonation is enabled\n :param username: Effective username\n ...
Please provide a description of the function:def mutate_label(label): label_hashed = '_' + hashlib.md5(label.encode('utf-8')).hexdigest() # if label starts with number, add underscore as first character label_mutated = '_' + label if re.match(r'^\d', label) else label # replac...
[ "\n BigQuery field_name should start with a letter or underscore and contain only\n alphanumeric characters. Labels that start with a number are prefixed with an\n underscore. Any unsupported characters are replaced with underscores and an\n md5 hash is added to the end of the label to a...
Please provide a description of the function:def _get_fields(cls, cols): return [sqla.literal_column(c.get('name')).label(c.get('name').replace('.', '__')) for c in cols]
[ "\n BigQuery dialect requires us to not use backtick in the fieldname which are\n nested.\n Using literal_column handles that issue.\n https://docs.sqlalchemy.org/en/latest/core/tutorial.html#using-more-specific-text-with-table-literal-column-and-column\n Also explicility specifyi...
Please provide a description of the function:def load_multiformat_time_series(): data = get_example_data('multiformat_time_series.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='s') pdf.ds2 = pd.to_datetime(pdf.ds2, unit='s') pdf.to_sql( 'multiformat_time_serie...
[ "Loading time series data from a zip file in the repo" ]
Please provide a description of the function:def import_dashboards(session, data_stream, import_time=None): current_tt = int(time.time()) import_time = current_tt if import_time is None else import_time data = json.loads(data_stream.read(), object_hook=decode_dashboards) # TODO: import DRUID dataso...
[ "Imports dashboards from a stream to databases" ]
Please provide a description of the function:def export_dashboards(session): logging.info('Starting export') dashboards = session.query(Dashboard) dashboard_ids = [] for dashboard in dashboards: dashboard_ids.append(dashboard.id) data = Dashboard.export_dashboards(dashboard_ids) ret...
[ "Returns all dashboards metadata as a json dump" ]
Please provide a description of the function:def cache_key(self, **extra): cache_dict = self.to_dict() cache_dict.update(extra) for k in ['from_dttm', 'to_dttm']: del cache_dict[k] if self.time_range: cache_dict['time_range'] = self.time_range js...
[ "\n The cache key is made out of the key/values in `query_obj`, plus any\n other key/values in `extra`\n We remove datetime bounds that are hard values, and replace them with\n the use-provided inputs to bounds, which may be time-relative (as in\n \"5 days ago\" or \"now\").\n ...
Please provide a description of the function:def handle_query_error(msg, query, session, payload=None): payload = payload or {} troubleshooting_link = config['TROUBLESHOOTING_LINK'] query.error_message = msg query.status = QueryStatus.FAILED query.tmp_table_name = None session.commit() ...
[ "Local method handling error while processing the SQL" ]
Please provide a description of the function:def get_query(query_id, session, retry_count=5): query = None attempt = 0 while not query and attempt < retry_count: try: query = session.query(Query).filter_by(id=query_id).one() except Exception: attempt += 1 ...
[ "attemps to get the query and retry if it cannot" ]
Please provide a description of the function:def session_scope(nullpool): if nullpool: engine = sqlalchemy.create_engine( app.config.get('SQLALCHEMY_DATABASE_URI'), poolclass=NullPool) session_class = sessionmaker() session_class.configure(bind=engine) session = sess...
[ "Provide a transactional scope around a series of operations." ]
Please provide a description of the function:def get_sql_results( ctask, query_id, rendered_query, return_results=True, store_results=False, user_name=None, start_time=None): with session_scope(not ctask.request.called_directly) as session: try: return execute_sql_statements( ...
[ "Executes the sql query returns the results." ]
Please provide a description of the function:def execute_sql_statement(sql_statement, query, user_name, session, cursor): database = query.database db_engine_spec = database.db_engine_spec parsed_query = ParsedQuery(sql_statement) sql = parsed_query.stripped() SQL_MAX_ROWS = app.config.get('SQL...
[ "Executes a single SQL statement" ]
Please provide a description of the function:def execute_sql_statements( ctask, query_id, rendered_query, return_results=True, store_results=False, user_name=None, session=None, start_time=None, ): if store_results and start_time: # only asynchronous queries stats_logger.timing( ...
[ "Executes the sql query returns the results." ]
Please provide a description of the function:def flasher(msg, severity=None): try: flash(msg, severity) except RuntimeError: if severity == 'danger': logging.error(msg) else: logging.info(msg)
[ "Flask's flash if available, logging call if not" ]
Please provide a description of the function:def string_to_num(s: str): if isinstance(s, (int, float)): return s if s.isdigit(): return int(s) try: return float(s) except ValueError: return None
[ "Converts a string to an int/float\n\n Returns ``None`` if it can't be converted\n\n >>> string_to_num('5')\n 5\n >>> string_to_num('5.2')\n 5.2\n >>> string_to_num(10)\n 10\n >>> string_to_num(10.1)\n 10.1\n >>> string_to_num('this is not a string') is None\n True\n " ]
Please provide a description of the function:def list_minus(l: List, minus: List) -> List: return [o for o in l if o not in minus]
[ "Returns l without what is in minus\n\n >>> list_minus([1, 2, 3], [2])\n [1, 3]\n " ]
Please provide a description of the function:def parse_human_datetime(s): if not s: return None try: dttm = parse(s) except Exception: try: cal = parsedatetime.Calendar() parsed_dttm, parsed_flags = cal.parseDT(s) # when time is not extracted,...
[ "\n Returns ``datetime.datetime`` from human readable strings\n\n >>> from datetime import date, timedelta\n >>> from dateutil.relativedelta import relativedelta\n >>> parse_human_datetime('2015-04-03')\n datetime.datetime(2015, 4, 3, 0, 0)\n >>> parse_human_datetime('2/3/1969')\n datetime.date...
Please provide a description of the function:def decode_dashboards(o): import superset.models.core as models from superset.connectors.sqla.models import ( SqlaTable, SqlMetric, TableColumn, ) if '__Dashboard__' in o: d = models.Dashboard() d.__dict__.update(o['__Dashboard__...
[ "\n Function to be passed into json.loads obj_hook parameter\n Recreates the dashboard object from a json representation.\n " ]
Please provide a description of the function:def parse_human_timedelta(s: str): cal = parsedatetime.Calendar() dttm = dttm_from_timtuple(datetime.now().timetuple()) d = cal.parse(s or '', dttm)[0] d = datetime(d.tm_year, d.tm_mon, d.tm_mday, d.tm_hour, d.tm_min, d.tm_sec) return d - dttm
[ "\n Returns ``datetime.datetime`` from natural language time deltas\n\n >>> parse_human_datetime('now') <= datetime.now()\n True\n " ]
Please provide a description of the function:def datetime_f(dttm): if dttm: dttm = dttm.isoformat() now_iso = datetime.now().isoformat() if now_iso[:10] == dttm[:10]: dttm = dttm[11:] elif now_iso[:4] == dttm[:4]: dttm = dttm[5:] return '<nobr>{}</nob...
[ "Formats datetime to take less room when it is recent" ]
Please provide a description of the function:def json_iso_dttm_ser(obj, pessimistic: Optional[bool] = False): val = base_json_conv(obj) if val is not None: return val if isinstance(obj, (datetime, date, time, pd.Timestamp)): obj = obj.isoformat() else: if pessimistic: ...
[ "\n json serializer that deals with dates\n\n >>> dttm = datetime(1970, 1, 1)\n >>> json.dumps({'dttm': dttm}, default=json_iso_dttm_ser)\n '{\"dttm\": \"1970-01-01T00:00:00\"}'\n " ]
Please provide a description of the function:def json_int_dttm_ser(obj): val = base_json_conv(obj) if val is not None: return val if isinstance(obj, (datetime, pd.Timestamp)): obj = datetime_to_epoch(obj) elif isinstance(obj, date): obj = (obj - EPOCH.date()).total_seconds()...
[ "json serializer that deals with dates" ]
Please provide a description of the function:def error_msg_from_exception(e): msg = '' if hasattr(e, 'message'): if isinstance(e.message, dict): msg = e.message.get('message') elif e.message: msg = '{}'.format(e.message) return msg or '{}'.format(e)
[ "Translate exception into error message\n\n Database have different ways to handle exception. This function attempts\n to make sense of the exception object and construct a human readable\n sentence.\n\n TODO(bkyryliuk): parse the Presto error message from the connection\n created vi...
Please provide a description of the function:def generic_find_constraint_name(table, columns, referenced, db): t = sa.Table(table, db.metadata, autoload=True, autoload_with=db.engine) for fk in t.foreign_key_constraints: if fk.referred_table.name == referenced and set(fk.column_keys) == columns: ...
[ "Utility to find a constraint name in alembic migrations" ]
Please provide a description of the function:def generic_find_fk_constraint_name(table, columns, referenced, insp): for fk in insp.get_foreign_keys(table): if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns: return fk['name']
[ "Utility to find a foreign-key constraint name in alembic migrations" ]
Please provide a description of the function:def generic_find_fk_constraint_names(table, columns, referenced, insp): names = set() for fk in insp.get_foreign_keys(table): if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns: names.add(fk['name']) return...
[ "Utility to find foreign-key constraint names in alembic migrations" ]
Please provide a description of the function:def generic_find_uq_constraint_name(table, columns, insp): for uq in insp.get_unique_constraints(table): if columns == set(uq['column_names']): return uq['name']
[ "Utility to find a unique constraint name in alembic migrations" ]
Please provide a description of the function:def table_has_constraint(table, name, db): t = sa.Table(table, db.metadata, autoload=True, autoload_with=db.engine) for c in t.constraints: if c.name == name: return True return False
[ "Utility to find a constraint name in alembic migrations" ]
Please provide a description of the function:def send_email_smtp(to, subject, html_content, config, files=None, data=None, images=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed'): smtp_mail_from = config.get('SMTP_MAIL_FROM') to = get_email_address_list(t...
[ "\n Send an email with html content, eg:\n send_email_smtp(\n 'test@example.com', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True)\n " ]
Please provide a description of the function:def setup_cache(app: Flask, cache_config) -> Optional[Cache]: if cache_config and cache_config.get('CACHE_TYPE') != 'null': return Cache(app, config=cache_config) return None
[ "Setup the flask-cache on a flask app" ]
Please provide a description of the function:def zlib_compress(data): if PY3K: if isinstance(data, str): return zlib.compress(bytes(data, 'utf-8')) return zlib.compress(data) return zlib.compress(data)
[ "\n Compress things in a py2/3 safe fashion\n >>> json_str = '{\"test\": 1}'\n >>> blob = zlib_compress(json_str)\n " ]
Please provide a description of the function:def zlib_decompress_to_string(blob): if PY3K: if isinstance(blob, bytes): decompressed = zlib.decompress(blob) else: decompressed = zlib.decompress(bytes(blob, 'utf-8')) return decompressed.decode('utf-8') return z...
[ "\n Decompress things to a string in a py2/3 safe fashion\n >>> json_str = '{\"test\": 1}'\n >>> blob = zlib_compress(json_str)\n >>> got_str = zlib_decompress_to_string(blob)\n >>> got_str == json_str\n True\n " ]
Please provide a description of the function:def user_label(user: User) -> Optional[str]: if user: if user.first_name and user.last_name: return user.first_name + ' ' + user.last_name else: return user.username return None
[ "Given a user ORM FAB object, returns a label" ]
Please provide a description of the function:def get_since_until(time_range: Optional[str] = None, since: Optional[str] = None, until: Optional[str] = None, time_shift: Optional[str] = None, relative_end: Optional[str] = None) -> Tuple[date...
[ "Return `since` and `until` date time tuple from string representations of\n time_range, since, until and time_shift.\n\n This functiom supports both reading the keys separately (from `since` and\n `until`), as well as the new `time_range` key. Valid formats are:\n\n - ISO 8601\n - X days/yea...
Please provide a description of the function:def add_ago_to_since(since: str) -> str: since_words = since.split(' ') grains = ['days', 'years', 'hours', 'day', 'year', 'weeks'] if (len(since_words) == 2 and since_words[1] in grains): since += ' ago' return since
[ "\n Backwards compatibility hack. Without this slices with since: 7 days will\n be treated as 7 days in the future.\n\n :param str since:\n :returns: Since with ago added if necessary\n :rtype: str\n " ]
Please provide a description of the function:def split_adhoc_filters_into_base_filters(fd): adhoc_filters = fd.get('adhoc_filters') if isinstance(adhoc_filters, list): simple_where_filters = [] simple_having_filters = [] sql_where_filters = [] sql_having_filters = [] ...
[ "\n Mutates form data to restructure the adhoc filters in the form of the four base\n filters, `where`, `having`, `filters`, and `having_filters` which represent\n free form where sql, free form having sql, structured where clauses and structured\n having clauses.\n " ]
Please provide a description of the function:def load_energy(): tbl_name = 'energy_usage' data = get_example_data('energy.json.gz') pdf = pd.read_json(data) pdf.to_sql( tbl_name, db.engine, if_exists='replace', chunksize=500, dtype={ 'source': Str...
[ "Loads an energy related dataset to use with sankey and graphs", "\\\n {\n \"collapsed_fieldsets\": \"\",\n \"groupby\": [\n \"source\",\n \"target\"\n ],\n \"having\": \"\",\n \"metric\": \"sum__value\",\n \"ro...
Please provide a description of the function:def load_random_time_series_data(): data = get_example_data('random_time_series.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='s') pdf.to_sql( 'random_time_series', db.engine, if_exists='replace', ...
[ "Loading random time series data from a zip file in the repo" ]
Please provide a description of the function:def runserver(debug, console_log, use_reloader, address, port, timeout, workers, socket): debug = debug or config.get('DEBUG') or console_log if debug: print(Fore.BLUE + '-=' * 20) print( Fore.YELLOW + 'Starting Superset server in ' +...
[ "Starts a Superset web server." ]
Please provide a description of the function:def version(verbose): print(Fore.BLUE + '-=' * 15) print(Fore.YELLOW + 'Superset ' + Fore.CYAN + '{version}'.format( version=config.get('VERSION_STRING'))) print(Fore.BLUE + '-=' * 15) if verbose: print('[DB] : ' + '{}'.format(db.engine))...
[ "Prints the current version number" ]
Please provide a description of the function:def refresh_druid(datasource, merge): session = db.session() from superset.connectors.druid.models import DruidCluster for cluster in session.query(DruidCluster).all(): try: cluster.refresh_datasources(datasource_name=datasource, ...
[ "Refresh druid datasources" ]
Please provide a description of the function:def import_dashboards(path, recursive): p = Path(path) files = [] if p.is_file(): files.append(p) elif p.exists() and not recursive: files.extend(p.glob('*.json')) elif p.exists() and recursive: files.extend(p.rglob('*.json'))...
[ "Import dashboards from JSON" ]
Please provide a description of the function:def export_dashboards(print_stdout, dashboard_file): data = dashboard_import_export.export_dashboards(db.session) if print_stdout or not dashboard_file: print(data) if dashboard_file: logging.info('Exporting dashboards to %s', dashboard_file)...
[ "Export dashboards to JSON" ]
Please provide a description of the function:def import_datasources(path, sync, recursive): sync_array = sync.split(',') p = Path(path) files = [] if p.is_file(): files.append(p) elif p.exists() and not recursive: files.extend(p.glob('*.yaml')) files.extend(p.glob('*.yml...
[ "Import datasources from YAML" ]
Please provide a description of the function:def export_datasources(print_stdout, datasource_file, back_references, include_defaults): data = dict_import_export.export_to_dict( session=db.session, recursive=True, back_references=back_references, include_de...
[ "Export datasources to YAML" ]
Please provide a description of the function:def export_datasource_schema(back_references): data = dict_import_export.export_schema_to_dict( back_references=back_references) yaml.safe_dump(data, stdout, default_flow_style=False)
[ "Export datasource YAML schema to stdout" ]
Please provide a description of the function:def update_datasources_cache(): from superset.models.core import Database for database in db.session.query(Database).all(): if database.allow_multi_schema_metadata_fetch: print('Fetching {} datasources ...'.format(database.name)) ...
[ "Refresh sqllab datasources cache" ]
Please provide a description of the function:def worker(workers): logging.info( "The 'superset worker' command is deprecated. Please use the 'celery " "worker' command instead.") if workers: celery_app.conf.update(CELERYD_CONCURRENCY=workers) elif config.get('SUPERSET_CELERY_WOR...
[ "Starts a Superset worker for async SQL query execution." ]
Please provide a description of the function:def flower(port, address): BROKER_URL = celery_app.conf.BROKER_URL cmd = ( 'celery flower ' f'--broker={BROKER_URL} ' f'--port={port} ' f'--address={address} ' ) logging.info( "The 'superset flower' command is depr...
[ "Runs a Celery Flower web server\n\n Celery Flower is a UI to monitor the Celery operation on a given\n broker" ]
Please provide a description of the function:def load_flights(): tbl_name = 'flights' data = get_example_data('flight_data.csv.gz', make_bytes=True) pdf = pd.read_csv(data, encoding='latin-1') # Loading airports info to join and get lat/long airports_bytes = get_example_data('airports.csv.gz',...
[ "Loading random time series data from a zip file in the repo" ]
Please provide a description of the function:def load_birth_names(): data = get_example_data('birth_names.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='ms') pdf.to_sql( 'birth_names', db.engine, if_exists='replace', chunksize=500, d...
[ "Loading birth name dataset from a zip file in the repo", "\\\n <div style='text-align:center'>\n <h1>Birth Names Dashboard</h1>\n <p>\n The source dataset came from\n <a href='https://github.com/hadley/babynames' target='_blank'>[here]</a>\n </p>\n <img src='/...
Please provide a description of the function:def refresh_datasources(self, refreshAll=True): session = db.session() DruidCluster = ConnectorRegistry.sources['druid'].cluster_class for cluster in session.query(DruidCluster).all(): cluster_name = cluster.cluster_name ...
[ "endpoint that refreshes druid datasources metadata" ]
Please provide a description of the function:def convert_to_list(number: int) -> Node: if number >= 0: head = Node(0) current = head remainder = number % 10 quotient = number // 10 while quotient != 0: current.next = Node(remainder) current = cur...
[ "\n converts a positive integer into a (reversed) linked list.\n for example: give 112\n result 2 -> 1 -> 1\n " ]
Please provide a description of the function:def convert_to_str(l: Node) -> str: result = "" while l: result += str(l.val) l = l.next return result
[ "\n converts the non-negative number list into a string.\n " ]
Please provide a description of the function:def longest_consecutive(root): if root is None: return 0 max_len = 0 dfs(root, 0, root.val, max_len) return max_len
[ "\n :type root: TreeNode\n :rtype: int\n " ]
Please provide a description of the function:def three_sum(array): res = set() array.sort() for i in range(len(array) - 2): if i > 0 and array[i] == array[i - 1]: continue l, r = i + 1, len(array) - 1 while l < r: s = array[i] + array[l] + array[r] ...
[ "\n :param array: List[int]\n :return: Set[ Tuple[int, int, int] ]\n " ]
Please provide a description of the function:def top_sort_recursive(graph): order, enter, state = [], set(graph), {} def dfs(node): state[node] = GRAY #print(node) for k in graph.get(node, ()): sk = state.get(k, None) if sk == GRAY: raise...
[ " Time complexity is the same as DFS, which is O(V + E)\n Space complexity: O(V)\n " ]
Please provide a description of the function:def top_sort(graph): order, enter, state = [], set(graph), {} def is_ready(node): lst = graph.get(node, ()) if len(lst) == 0: return True for k in lst: sk = state.get(k, None) if sk == GRAY: ...
[ " Time complexity is the same as DFS, which is O(V + E)\n Space complexity: O(V)\n " ]
Please provide a description of the function:def max_product(nums): lmin = lmax = gmax = nums[0] for i in range(len(nums)): t1 = nums[i] * lmax t2 = nums[i] * lmin lmax = max(max(t1, t2), nums[i]) lmin = min(min(t1, t2), nums[i]) gmax = max(gmax, lmax)
[ "\n :type nums: List[int]\n :rtype: int\n " ]
Please provide a description of the function:def subarray_with_max_product(arr): ''' arr is list of positive/negative numbers ''' l = len(arr) product_so_far = max_product_end = 1 max_start_i = 0 so_far_start_i = so_far_end_i = 0 all_negative_flag = True for i in range(l): max_produ...
[]
Please provide a description of the function:def text_justification(words, max_width): ''' :type words: list :type max_width: int :rtype: list ''' ret = [] # return value row_len = 0 # current length of strs in a row row_words = [] # current words in a row index = 0 # the index o...
[]
Please provide a description of the function:def insertion_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos - 1] > cursor: ...
[ " Insertion Sort\n Complexity: O(n^2)\n " ]
Please provide a description of the function:def cycle_sort(arr): len_arr = len(arr) # Finding cycle to rotate. for cur in range(len_arr - 1): item = arr[cur] # Finding an indx to put items in. index = cur for i in range(cur + 1, len_arr): if arr[i] < item: ...
[ "\n cycle_sort\n This is based on the idea that the permutations to be sorted\n can be decomposed into cycles,\n and the results can be individually sorted by cycling.\n \n reference: https://en.wikipedia.org/wiki/Cycle_sort\n \n Average time complexity : O(N^2)\n Worst case time complexi...