repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
PythonRails/rails
rails/router.py
Router.get_action_handler
def get_action_handler(self, controller_name, action_name): """ Return action of controller as callable. If requested controller isn't found - return 'not_found' action of requested controller or Index controller. """ try_actions = [ controller_name + '/' + action_name, controller_name + '/not_found', # call Index controller to catch all unhandled pages 'index/not_found' ] # search first appropriate action handler for path in try_actions: if path in self._controllers: return self._controllers[path] return None
python
def get_action_handler(self, controller_name, action_name): """ Return action of controller as callable. If requested controller isn't found - return 'not_found' action of requested controller or Index controller. """ try_actions = [ controller_name + '/' + action_name, controller_name + '/not_found', # call Index controller to catch all unhandled pages 'index/not_found' ] # search first appropriate action handler for path in try_actions: if path in self._controllers: return self._controllers[path] return None
[ "def", "get_action_handler", "(", "self", ",", "controller_name", ",", "action_name", ")", ":", "try_actions", "=", "[", "controller_name", "+", "'/'", "+", "action_name", ",", "controller_name", "+", "'/not_found'", ",", "# call Index controller to catch all unhandled ...
Return action of controller as callable. If requested controller isn't found - return 'not_found' action of requested controller or Index controller.
[ "Return", "action", "of", "controller", "as", "callable", "." ]
train
https://github.com/PythonRails/rails/blob/1e199b9da4da5b24fef39fc6212d71fc9fbb18a5/rails/router.py#L111-L128
SmartTeleMax/iktomi
iktomi/cli/fcgi.py
Flup.command_start
def command_start(self, daemonize=False): ''' Start a server:: ./manage.py flup:start [--daemonize] ''' if daemonize: safe_makedirs(self.logfile, self.pidfile) flup_fastcgi(self.app, bind=self.bind, pidfile=self.pidfile, logfile=self.logfile, daemonize=daemonize, cwd=self.cwd, umask=self.umask, **self.fastcgi_params)
python
def command_start(self, daemonize=False): ''' Start a server:: ./manage.py flup:start [--daemonize] ''' if daemonize: safe_makedirs(self.logfile, self.pidfile) flup_fastcgi(self.app, bind=self.bind, pidfile=self.pidfile, logfile=self.logfile, daemonize=daemonize, cwd=self.cwd, umask=self.umask, **self.fastcgi_params)
[ "def", "command_start", "(", "self", ",", "daemonize", "=", "False", ")", ":", "if", "daemonize", ":", "safe_makedirs", "(", "self", ".", "logfile", ",", "self", ".", "pidfile", ")", "flup_fastcgi", "(", "self", ".", "app", ",", "bind", "=", "self", "....
Start a server:: ./manage.py flup:start [--daemonize]
[ "Start", "a", "server", "::" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/fcgi.py#L74-L84
SmartTeleMax/iktomi
iktomi/cli/fcgi.py
Flup.command_stop
def command_stop(self): ''' Stop a server:: ./manage.py flup:stop ''' if self.pidfile: if not os.path.exists(self.pidfile): sys.exit("Pidfile {!r} doesn't exist".format(self.pidfile)) with open(self.pidfile) as pidfile: pid = int(pidfile.read()) for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGKILL]: try: if terminate(pid, sig, 3): os.remove(self.pidfile) # NOTE: we are not performing sys.exit here, # otherwise restart command will not work return except OSError as exc: if exc.errno != errno.ESRCH: raise elif sig == signal.SIGINT: sys.exit('Not running') sys.exit('No pidfile provided')
python
def command_stop(self): ''' Stop a server:: ./manage.py flup:stop ''' if self.pidfile: if not os.path.exists(self.pidfile): sys.exit("Pidfile {!r} doesn't exist".format(self.pidfile)) with open(self.pidfile) as pidfile: pid = int(pidfile.read()) for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGKILL]: try: if terminate(pid, sig, 3): os.remove(self.pidfile) # NOTE: we are not performing sys.exit here, # otherwise restart command will not work return except OSError as exc: if exc.errno != errno.ESRCH: raise elif sig == signal.SIGINT: sys.exit('Not running') sys.exit('No pidfile provided')
[ "def", "command_stop", "(", "self", ")", ":", "if", "self", ".", "pidfile", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "pidfile", ")", ":", "sys", ".", "exit", "(", "\"Pidfile {!r} doesn't exist\"", ".", "format", "(", "self"...
Stop a server:: ./manage.py flup:stop
[ "Stop", "a", "server", "::" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/fcgi.py#L86-L109
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
_preprocess_sqlite_view
def _preprocess_sqlite_view(asql_query, library, backend, connection): """ Finds view or materialized view in the asql query and converts it to create table/insert rows. Note: Assume virtual tables for all partitions already created. Args: asql_query (str): asql query library (ambry.Library): backend (SQLiteBackend): connection (apsw.Connection): Returns: str: valid sql query containing create table and insert into queries if asql_query contains 'create materialized view'. If asql_query does not contain 'create materialized view' returns asql_query as is. """ new_query = None if 'create materialized view' in asql_query.lower() or 'create view' in asql_query.lower(): logger.debug( '_preprocess_sqlite_view: materialized view found.\n asql query: {}' .format(asql_query)) view = parse_view(asql_query) tablename = view.name.replace('-', '_').lower().replace('.', '_') create_query_columns = {} for column in view.columns: create_query_columns[column.name] = column.alias ref_to_partition_map = {} # key is ref found in the query, value is Partition instance. alias_to_partition_map = {} # key is alias of ref found in the query, value is Partition instance. # collect sources from select statement of the view. for source in view.sources: partition = library.partition(source.name) ref_to_partition_map[source.name] = partition if source.alias: alias_to_partition_map[source.alias] = partition # collect sources from joins of the view. for join in view.joins: partition = library.partition(join.source.name) ref_to_partition_map[join.source.name] = partition if join.source.alias: alias_to_partition_map[join.source.alias] = partition # collect and convert columns. TYPE_MAP = { 'int': 'INTEGER', 'float': 'REAL', six.binary_type.__name__: 'TEXT', six.text_type.__name__: 'TEXT', 'date': 'DATE', 'datetime': 'TIMESTAMP WITHOUT TIME ZONE' } column_types = [] column_names = [] for column in view.columns: if '.' in column.name: source_alias, column_name = column.name.split('.') else: # TODO: Test that case. source_alias = None column_name = column.name # find column specification in the mpr file. if source_alias: partition = alias_to_partition_map[source_alias] for part_column in partition.datafile.reader.columns: if part_column['name'] == column_name: sqlite_type = TYPE_MAP.get(part_column['type']) if not sqlite_type: raise Exception( 'Do not know how to convert {} to sql column.' .format(column['type'])) column_types.append( ' {} {}' .format(column.alias if column.alias else column.name, sqlite_type)) column_names.append(column.alias if column.alias else column.name) column_types_str = ',\n'.join(column_types) column_names_str = ', '.join(column_names) create_query = 'CREATE TABLE IF NOT EXISTS {}(\n{});'.format(tablename, column_types_str) # drop 'create materialized view' part _, select_part = asql_query.split(view.name) select_part = select_part.strip() assert select_part.lower().startswith('as') # drop 'as' keyword select_part = select_part.strip()[2:].strip() assert select_part.lower().strip().startswith('select') # Create query to copy data from mpr to just created table. copy_query = 'INSERT INTO {table}(\n{columns})\n {select}'.format( table=tablename, columns=column_names_str, select=select_part) if not copy_query.strip().lower().endswith(';'): copy_query = copy_query + ';' new_query = '{}\n\n{}'.format(create_query, copy_query) logger.debug( '_preprocess_sqlite_view: preprocess finished.\n asql query: {}\n\n new query: {}' .format(asql_query, new_query)) return new_query or asql_query
python
def _preprocess_sqlite_view(asql_query, library, backend, connection): """ Finds view or materialized view in the asql query and converts it to create table/insert rows. Note: Assume virtual tables for all partitions already created. Args: asql_query (str): asql query library (ambry.Library): backend (SQLiteBackend): connection (apsw.Connection): Returns: str: valid sql query containing create table and insert into queries if asql_query contains 'create materialized view'. If asql_query does not contain 'create materialized view' returns asql_query as is. """ new_query = None if 'create materialized view' in asql_query.lower() or 'create view' in asql_query.lower(): logger.debug( '_preprocess_sqlite_view: materialized view found.\n asql query: {}' .format(asql_query)) view = parse_view(asql_query) tablename = view.name.replace('-', '_').lower().replace('.', '_') create_query_columns = {} for column in view.columns: create_query_columns[column.name] = column.alias ref_to_partition_map = {} # key is ref found in the query, value is Partition instance. alias_to_partition_map = {} # key is alias of ref found in the query, value is Partition instance. # collect sources from select statement of the view. for source in view.sources: partition = library.partition(source.name) ref_to_partition_map[source.name] = partition if source.alias: alias_to_partition_map[source.alias] = partition # collect sources from joins of the view. for join in view.joins: partition = library.partition(join.source.name) ref_to_partition_map[join.source.name] = partition if join.source.alias: alias_to_partition_map[join.source.alias] = partition # collect and convert columns. TYPE_MAP = { 'int': 'INTEGER', 'float': 'REAL', six.binary_type.__name__: 'TEXT', six.text_type.__name__: 'TEXT', 'date': 'DATE', 'datetime': 'TIMESTAMP WITHOUT TIME ZONE' } column_types = [] column_names = [] for column in view.columns: if '.' in column.name: source_alias, column_name = column.name.split('.') else: # TODO: Test that case. source_alias = None column_name = column.name # find column specification in the mpr file. if source_alias: partition = alias_to_partition_map[source_alias] for part_column in partition.datafile.reader.columns: if part_column['name'] == column_name: sqlite_type = TYPE_MAP.get(part_column['type']) if not sqlite_type: raise Exception( 'Do not know how to convert {} to sql column.' .format(column['type'])) column_types.append( ' {} {}' .format(column.alias if column.alias else column.name, sqlite_type)) column_names.append(column.alias if column.alias else column.name) column_types_str = ',\n'.join(column_types) column_names_str = ', '.join(column_names) create_query = 'CREATE TABLE IF NOT EXISTS {}(\n{});'.format(tablename, column_types_str) # drop 'create materialized view' part _, select_part = asql_query.split(view.name) select_part = select_part.strip() assert select_part.lower().startswith('as') # drop 'as' keyword select_part = select_part.strip()[2:].strip() assert select_part.lower().strip().startswith('select') # Create query to copy data from mpr to just created table. copy_query = 'INSERT INTO {table}(\n{columns})\n {select}'.format( table=tablename, columns=column_names_str, select=select_part) if not copy_query.strip().lower().endswith(';'): copy_query = copy_query + ';' new_query = '{}\n\n{}'.format(create_query, copy_query) logger.debug( '_preprocess_sqlite_view: preprocess finished.\n asql query: {}\n\n new query: {}' .format(asql_query, new_query)) return new_query or asql_query
[ "def", "_preprocess_sqlite_view", "(", "asql_query", ",", "library", ",", "backend", ",", "connection", ")", ":", "new_query", "=", "None", "if", "'create materialized view'", "in", "asql_query", ".", "lower", "(", ")", "or", "'create view'", "in", "asql_query", ...
Finds view or materialized view in the asql query and converts it to create table/insert rows. Note: Assume virtual tables for all partitions already created. Args: asql_query (str): asql query library (ambry.Library): backend (SQLiteBackend): connection (apsw.Connection): Returns: str: valid sql query containing create table and insert into queries if asql_query contains 'create materialized view'. If asql_query does not contain 'create materialized view' returns asql_query as is.
[ "Finds", "view", "or", "materialized", "view", "in", "the", "asql", "query", "and", "converts", "it", "to", "create", "table", "/", "insert", "rows", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L363-L473
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
_preprocess_sqlite_index
def _preprocess_sqlite_index(asql_query, library, backend, connection): """ Creates materialized view for each indexed partition found in the query. Args: asql_query (str): asql query library (ambry.Library): backend (SQLiteBackend): connection (apsw.Connection): Returns: str: converted asql if it contains index query. If not, returns asql_query as is. """ new_query = None if asql_query.strip().lower().startswith('index'): logger.debug( '_preprocess_index: create index query found.\n asql query: {}' .format(asql_query)) index = parse_index(asql_query) partition = library.partition(index.source) table = backend.install(connection, partition, materialize=True) index_name = '{}_{}_ind'.format(partition.vid, '_'.join(index.columns)) new_query = 'CREATE INDEX IF NOT EXISTS {index} ON {table} ({columns});'.format( index=index_name, table=table, columns=','.join(index.columns)) logger.debug( '_preprocess_index: preprocess finished.\n asql query: {}\n new query: {}' .format(asql_query, new_query)) return new_query or asql_query
python
def _preprocess_sqlite_index(asql_query, library, backend, connection): """ Creates materialized view for each indexed partition found in the query. Args: asql_query (str): asql query library (ambry.Library): backend (SQLiteBackend): connection (apsw.Connection): Returns: str: converted asql if it contains index query. If not, returns asql_query as is. """ new_query = None if asql_query.strip().lower().startswith('index'): logger.debug( '_preprocess_index: create index query found.\n asql query: {}' .format(asql_query)) index = parse_index(asql_query) partition = library.partition(index.source) table = backend.install(connection, partition, materialize=True) index_name = '{}_{}_ind'.format(partition.vid, '_'.join(index.columns)) new_query = 'CREATE INDEX IF NOT EXISTS {index} ON {table} ({columns});'.format( index=index_name, table=table, columns=','.join(index.columns)) logger.debug( '_preprocess_index: preprocess finished.\n asql query: {}\n new query: {}' .format(asql_query, new_query)) return new_query or asql_query
[ "def", "_preprocess_sqlite_index", "(", "asql_query", ",", "library", ",", "backend", ",", "connection", ")", ":", "new_query", "=", "None", "if", "asql_query", ".", "strip", "(", ")", ".", "lower", "(", ")", ".", "startswith", "(", "'index'", ")", ":", ...
Creates materialized view for each indexed partition found in the query. Args: asql_query (str): asql query library (ambry.Library): backend (SQLiteBackend): connection (apsw.Connection): Returns: str: converted asql if it contains index query. If not, returns asql_query as is.
[ "Creates", "materialized", "view", "for", "each", "indexed", "partition", "found", "in", "the", "query", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L476-L508
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
SQLiteBackend.install
def install(self, connection, partition, table_name = None, index_columns=None, materialize=False, logger = None): """ Creates virtual table or read-only table for gion. Args: ref (str): id, vid, name or versioned name of the partition. materialize (boolean): if True, create read-only table. If False create virtual table. Returns: str: name of the created table. """ virtual_table = partition.vid table = partition.vid if not table_name else table_name if self._relation_exists(connection, table): if logger: logger.debug("Skipping '{}'; already installed".format(table)) return else: if logger: logger.info("Installing '{}'".format(table)) partition.localize() virtual_table = partition.vid + '_vt' self._add_partition(connection, partition) if materialize: if self._relation_exists(connection, table): debug_logger.debug( 'Materialized table of the partition already exists.\n partition: {}, table: {}' .format(partition.name, table)) else: cursor = connection.cursor() # create table create_query = self.__class__._get_create_query(partition, table) debug_logger.debug( 'Creating new materialized view for partition mpr.' '\n partition: {}, view: {}, query: {}' .format(partition.name, table, create_query)) cursor.execute(create_query) # populate just created table with data from virtual table. copy_query = '''INSERT INTO {} SELECT * FROM {};'''.format(table, virtual_table) debug_logger.debug( 'Populating sqlite table with rows from partition mpr.' '\n partition: {}, view: {}, query: {}' .format(partition.name, table, copy_query)) cursor.execute(copy_query) cursor.close() else: cursor = connection.cursor() view_q = "CREATE VIEW IF NOT EXISTS {} AS SELECT * FROM {} ".format(partition.vid, virtual_table) cursor.execute(view_q) cursor.close() if index_columns is not None: self.index(connection,table, index_columns) return table
python
def install(self, connection, partition, table_name = None, index_columns=None, materialize=False, logger = None): """ Creates virtual table or read-only table for gion. Args: ref (str): id, vid, name or versioned name of the partition. materialize (boolean): if True, create read-only table. If False create virtual table. Returns: str: name of the created table. """ virtual_table = partition.vid table = partition.vid if not table_name else table_name if self._relation_exists(connection, table): if logger: logger.debug("Skipping '{}'; already installed".format(table)) return else: if logger: logger.info("Installing '{}'".format(table)) partition.localize() virtual_table = partition.vid + '_vt' self._add_partition(connection, partition) if materialize: if self._relation_exists(connection, table): debug_logger.debug( 'Materialized table of the partition already exists.\n partition: {}, table: {}' .format(partition.name, table)) else: cursor = connection.cursor() # create table create_query = self.__class__._get_create_query(partition, table) debug_logger.debug( 'Creating new materialized view for partition mpr.' '\n partition: {}, view: {}, query: {}' .format(partition.name, table, create_query)) cursor.execute(create_query) # populate just created table with data from virtual table. copy_query = '''INSERT INTO {} SELECT * FROM {};'''.format(table, virtual_table) debug_logger.debug( 'Populating sqlite table with rows from partition mpr.' '\n partition: {}, view: {}, query: {}' .format(partition.name, table, copy_query)) cursor.execute(copy_query) cursor.close() else: cursor = connection.cursor() view_q = "CREATE VIEW IF NOT EXISTS {} AS SELECT * FROM {} ".format(partition.vid, virtual_table) cursor.execute(view_q) cursor.close() if index_columns is not None: self.index(connection,table, index_columns) return table
[ "def", "install", "(", "self", ",", "connection", ",", "partition", ",", "table_name", "=", "None", ",", "index_columns", "=", "None", ",", "materialize", "=", "False", ",", "logger", "=", "None", ")", ":", "virtual_table", "=", "partition", ".", "vid", ...
Creates virtual table or read-only table for gion. Args: ref (str): id, vid, name or versioned name of the partition. materialize (boolean): if True, create read-only table. If False create virtual table. Returns: str: name of the created table.
[ "Creates", "virtual", "table", "or", "read", "-", "only", "table", "for", "gion", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L32-L100
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
SQLiteBackend.index
def index(self, connection, partition, columns): """ Create an index on the columns. Args: connection (apsw.Connection): connection to sqlite database who stores mpr table or view. partition (orm.Partition): columns (list of str): """ import hashlib query_tmpl = ''' CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} ({columns}); ''' if not isinstance(columns,(list,tuple)): columns = [columns] col_list = ','.join('"{}"'.format(col) for col in columns) col_hash = hashlib.md5(col_list).hexdigest() try: table_name = partition.vid except AttributeError: table_name = partition # Its really a table name query = query_tmpl.format( index_name='{}_{}_i'.format(table_name, col_hash), table_name=table_name, columns=col_list) logger.debug('Creating sqlite index: query: {}'.format(query)) cursor = connection.cursor() cursor.execute(query)
python
def index(self, connection, partition, columns): """ Create an index on the columns. Args: connection (apsw.Connection): connection to sqlite database who stores mpr table or view. partition (orm.Partition): columns (list of str): """ import hashlib query_tmpl = ''' CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} ({columns}); ''' if not isinstance(columns,(list,tuple)): columns = [columns] col_list = ','.join('"{}"'.format(col) for col in columns) col_hash = hashlib.md5(col_list).hexdigest() try: table_name = partition.vid except AttributeError: table_name = partition # Its really a table name query = query_tmpl.format( index_name='{}_{}_i'.format(table_name, col_hash), table_name=table_name, columns=col_list) logger.debug('Creating sqlite index: query: {}'.format(query)) cursor = connection.cursor() cursor.execute(query)
[ "def", "index", "(", "self", ",", "connection", ",", "partition", ",", "columns", ")", ":", "import", "hashlib", "query_tmpl", "=", "'''\n CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} ({columns});\n '''", "if", "not", "isinstance", "(", "columns...
Create an index on the columns. Args: connection (apsw.Connection): connection to sqlite database who stores mpr table or view. partition (orm.Partition): columns (list of str):
[ "Create", "an", "index", "on", "the", "columns", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L102-L136
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
SQLiteBackend.close
def close(self): """ Closes connection to sqlite database. """ if getattr(self, '_connection', None): logger.debug('Closing sqlite connection.') self._connection.close() self._connection = None
python
def close(self): """ Closes connection to sqlite database. """ if getattr(self, '_connection', None): logger.debug('Closing sqlite connection.') self._connection.close() self._connection = None
[ "def", "close", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_connection'", ",", "None", ")", ":", "logger", ".", "debug", "(", "'Closing sqlite connection.'", ")", "self", ".", "_connection", ".", "close", "(", ")", "self", ".", "_connect...
Closes connection to sqlite database.
[ "Closes", "connection", "to", "sqlite", "database", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L138-L143
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
SQLiteBackend._get_mpr_view
def _get_mpr_view(self, connection, table): """ Finds and returns view name in the sqlite db represented by given connection. Args: connection: connection to sqlite db where to look for partition table. table (orm.Table): Raises: MissingViewError: if database does not have partition table. Returns: str: database table storing partition data. """ logger.debug( 'Looking for view of the table.\n table: {}'.format(table.vid)) view = self.get_view_name(table) view_exists = self._relation_exists(connection, view) if view_exists: logger.debug( 'View of the table exists.\n table: {}, view: {}' .format(table.vid, view)) return view raise MissingViewError('sqlite database does not have view for {} table.' .format(table.vid))
python
def _get_mpr_view(self, connection, table): """ Finds and returns view name in the sqlite db represented by given connection. Args: connection: connection to sqlite db where to look for partition table. table (orm.Table): Raises: MissingViewError: if database does not have partition table. Returns: str: database table storing partition data. """ logger.debug( 'Looking for view of the table.\n table: {}'.format(table.vid)) view = self.get_view_name(table) view_exists = self._relation_exists(connection, view) if view_exists: logger.debug( 'View of the table exists.\n table: {}, view: {}' .format(table.vid, view)) return view raise MissingViewError('sqlite database does not have view for {} table.' .format(table.vid))
[ "def", "_get_mpr_view", "(", "self", ",", "connection", ",", "table", ")", ":", "logger", ".", "debug", "(", "'Looking for view of the table.\\n table: {}'", ".", "format", "(", "table", ".", "vid", ")", ")", "view", "=", "self", ".", "get_view_name", "(", ...
Finds and returns view name in the sqlite db represented by given connection. Args: connection: connection to sqlite db where to look for partition table. table (orm.Table): Raises: MissingViewError: if database does not have partition table. Returns: str: database table storing partition data.
[ "Finds", "and", "returns", "view", "name", "in", "the", "sqlite", "db", "represented", "by", "given", "connection", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L149-L173
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
SQLiteBackend._get_mpr_table
def _get_mpr_table(self, connection, partition): """ Returns name of the sqlite table who stores mpr data. Args: connection (apsw.Connection): connection to sqlite database who stores mpr data. partition (orm.Partition): Returns: str: Raises: MissingTableError: if partition table not found in the db. """ # TODO: This is the first candidate for optimization. Add field to partition # with table name and update it while table creation. # Optimized version. # # return partition.mpr_table or raise exception # Not optimized version. # # first check either partition has readonly table. virtual_table = partition.vid table = '{}_v'.format(virtual_table) logger.debug( 'Looking for materialized table of the partition.\n partition: {}'.format(partition.name)) table_exists = self._relation_exists(connection, table) if table_exists: logger.debug( 'Materialized table of the partition found.\n partition: {}, table: {}' .format(partition.name, table)) return table # now check for virtual table logger.debug( 'Looking for a virtual table of the partition.\n partition: {}'.format(partition.name)) virtual_exists = self._relation_exists(connection, virtual_table) if virtual_exists: logger.debug( 'Virtual table of the partition found.\n partition: {}, table: {}' .format(partition.name, table)) return virtual_table raise MissingTableError('sqlite database does not have table for mpr of {} partition.' .format(partition.vid))
python
def _get_mpr_table(self, connection, partition): """ Returns name of the sqlite table who stores mpr data. Args: connection (apsw.Connection): connection to sqlite database who stores mpr data. partition (orm.Partition): Returns: str: Raises: MissingTableError: if partition table not found in the db. """ # TODO: This is the first candidate for optimization. Add field to partition # with table name and update it while table creation. # Optimized version. # # return partition.mpr_table or raise exception # Not optimized version. # # first check either partition has readonly table. virtual_table = partition.vid table = '{}_v'.format(virtual_table) logger.debug( 'Looking for materialized table of the partition.\n partition: {}'.format(partition.name)) table_exists = self._relation_exists(connection, table) if table_exists: logger.debug( 'Materialized table of the partition found.\n partition: {}, table: {}' .format(partition.name, table)) return table # now check for virtual table logger.debug( 'Looking for a virtual table of the partition.\n partition: {}'.format(partition.name)) virtual_exists = self._relation_exists(connection, virtual_table) if virtual_exists: logger.debug( 'Virtual table of the partition found.\n partition: {}, table: {}' .format(partition.name, table)) return virtual_table raise MissingTableError('sqlite database does not have table for mpr of {} partition.' .format(partition.vid))
[ "def", "_get_mpr_table", "(", "self", ",", "connection", ",", "partition", ")", ":", "# TODO: This is the first candidate for optimization. Add field to partition", "# with table name and update it while table creation.", "# Optimized version.", "#", "# return partition.mpr_table or rais...
Returns name of the sqlite table who stores mpr data. Args: connection (apsw.Connection): connection to sqlite database who stores mpr data. partition (orm.Partition): Returns: str: Raises: MissingTableError: if partition table not found in the db.
[ "Returns", "name", "of", "the", "sqlite", "table", "who", "stores", "mpr", "data", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L175-L219
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
SQLiteBackend._relation_exists
def _relation_exists(self, connection, relation): """ Returns True if relation (table or view) exists in the sqlite db. Otherwise returns False. Args: connection (apsw.Connection): connection to sqlite database who stores mpr data. partition (orm.Partition): Returns: boolean: True if relation exists, False otherwise. """ query = 'SELECT 1 FROM sqlite_master WHERE (type=\'table\' OR type=\'view\') AND name=?;' cursor = connection.cursor() cursor.execute(query, [relation]) result = cursor.fetchall() return result == [(1,)]
python
def _relation_exists(self, connection, relation): """ Returns True if relation (table or view) exists in the sqlite db. Otherwise returns False. Args: connection (apsw.Connection): connection to sqlite database who stores mpr data. partition (orm.Partition): Returns: boolean: True if relation exists, False otherwise. """ query = 'SELECT 1 FROM sqlite_master WHERE (type=\'table\' OR type=\'view\') AND name=?;' cursor = connection.cursor() cursor.execute(query, [relation]) result = cursor.fetchall() return result == [(1,)]
[ "def", "_relation_exists", "(", "self", ",", "connection", ",", "relation", ")", ":", "query", "=", "'SELECT 1 FROM sqlite_master WHERE (type=\\'table\\' OR type=\\'view\\') AND name=?;'", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "...
Returns True if relation (table or view) exists in the sqlite db. Otherwise returns False. Args: connection (apsw.Connection): connection to sqlite database who stores mpr data. partition (orm.Partition): Returns: boolean: True if relation exists, False otherwise.
[ "Returns", "True", "if", "relation", "(", "table", "or", "view", ")", "exists", "in", "the", "sqlite", "db", ".", "Otherwise", "returns", "False", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L221-L236
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
SQLiteBackend._get_create_query
def _get_create_query(partition, tablename, include=None): """ Creates and returns `CREATE TABLE ...` sql statement for given mprows. Args: partition (orm.Partition): tablename (str): name of the table in the return create query. include (list of str, optional): list of columns to include to query. Returns: str: create table query. """ TYPE_MAP = { 'int': 'INTEGER', 'float': 'REAL', six.binary_type.__name__: 'TEXT', six.text_type.__name__: 'TEXT', 'date': 'DATE', 'datetime': 'TIMESTAMP WITHOUT TIME ZONE' } columns_types = [] if not include: include = [] for column in sorted(partition.datafile.reader.columns, key=lambda x: x['pos']): if include and column['name'] not in include: continue sqlite_type = TYPE_MAP.get(column['type']) if not sqlite_type: raise Exception('Do not know how to convert {} to sql column.'.format(column['type'])) columns_types.append(' "{}" {}'.format(column['name'], sqlite_type)) columns_types_str = ',\n'.join(columns_types) query = 'CREATE TABLE IF NOT EXISTS {}(\n{})'.format(tablename, columns_types_str) return query
python
def _get_create_query(partition, tablename, include=None): """ Creates and returns `CREATE TABLE ...` sql statement for given mprows. Args: partition (orm.Partition): tablename (str): name of the table in the return create query. include (list of str, optional): list of columns to include to query. Returns: str: create table query. """ TYPE_MAP = { 'int': 'INTEGER', 'float': 'REAL', six.binary_type.__name__: 'TEXT', six.text_type.__name__: 'TEXT', 'date': 'DATE', 'datetime': 'TIMESTAMP WITHOUT TIME ZONE' } columns_types = [] if not include: include = [] for column in sorted(partition.datafile.reader.columns, key=lambda x: x['pos']): if include and column['name'] not in include: continue sqlite_type = TYPE_MAP.get(column['type']) if not sqlite_type: raise Exception('Do not know how to convert {} to sql column.'.format(column['type'])) columns_types.append(' "{}" {}'.format(column['name'], sqlite_type)) columns_types_str = ',\n'.join(columns_types) query = 'CREATE TABLE IF NOT EXISTS {}(\n{})'.format(tablename, columns_types_str) return query
[ "def", "_get_create_query", "(", "partition", ",", "tablename", ",", "include", "=", "None", ")", ":", "TYPE_MAP", "=", "{", "'int'", ":", "'INTEGER'", ",", "'float'", ":", "'REAL'", ",", "six", ".", "binary_type", ".", "__name__", ":", "'TEXT'", ",", "s...
Creates and returns `CREATE TABLE ...` sql statement for given mprows. Args: partition (orm.Partition): tablename (str): name of the table in the return create query. include (list of str, optional): list of columns to include to query. Returns: str: create table query.
[ "Creates", "and", "returns", "CREATE", "TABLE", "...", "sql", "statement", "for", "given", "mprows", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L239-L271
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
SQLiteBackend._get_connection
def _get_connection(self): """ Returns connection to sqlite db. Returns: connection to the sqlite db who stores mpr data. """ if getattr(self, '_connection', None): logger.debug('Connection to sqlite db already exists. Using existing one.') else: dsn = self._dsn if dsn == 'sqlite://': dsn = ':memory:' else: dsn = dsn.replace('sqlite:///', '') logger.debug( 'Creating new apsw connection.\n dsn: {}, config_dsn: {}' .format(dsn, self._dsn)) self._connection = apsw.Connection(dsn) return self._connection
python
def _get_connection(self): """ Returns connection to sqlite db. Returns: connection to the sqlite db who stores mpr data. """ if getattr(self, '_connection', None): logger.debug('Connection to sqlite db already exists. Using existing one.') else: dsn = self._dsn if dsn == 'sqlite://': dsn = ':memory:' else: dsn = dsn.replace('sqlite:///', '') logger.debug( 'Creating new apsw connection.\n dsn: {}, config_dsn: {}' .format(dsn, self._dsn)) self._connection = apsw.Connection(dsn) return self._connection
[ "def", "_get_connection", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_connection'", ",", "None", ")", ":", "logger", ".", "debug", "(", "'Connection to sqlite db already exists. Using existing one.'", ")", "else", ":", "dsn", "=", "self", ".", ...
Returns connection to sqlite db. Returns: connection to the sqlite db who stores mpr data.
[ "Returns", "connection", "to", "sqlite", "db", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L273-L294
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
SQLiteBackend._add_partition
def _add_partition(self, connection, partition): """ Creates sqlite virtual table for mpr file of the given partition. Args: connection: connection to the sqlite db who stores mpr data. partition (orm.Partition): """ logger.debug('Creating virtual table for partition.\n partition: {}'.format(partition.name)) sqlite_med.add_partition(connection, partition.datafile, partition.vid+'_vt')
python
def _add_partition(self, connection, partition): """ Creates sqlite virtual table for mpr file of the given partition. Args: connection: connection to the sqlite db who stores mpr data. partition (orm.Partition): """ logger.debug('Creating virtual table for partition.\n partition: {}'.format(partition.name)) sqlite_med.add_partition(connection, partition.datafile, partition.vid+'_vt')
[ "def", "_add_partition", "(", "self", ",", "connection", ",", "partition", ")", ":", "logger", ".", "debug", "(", "'Creating virtual table for partition.\\n partition: {}'", ".", "format", "(", "partition", ".", "name", ")", ")", "sqlite_med", ".", "add_partition...
Creates sqlite virtual table for mpr file of the given partition. Args: connection: connection to the sqlite db who stores mpr data. partition (orm.Partition):
[ "Creates", "sqlite", "virtual", "table", "for", "mpr", "file", "of", "the", "given", "partition", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L296-L305
CivicSpleen/ambry
ambry/mprlib/backends/sqlite.py
SQLiteBackend._execute
def _execute(self, connection, query, fetch=True): """ Executes given query using given connection. Args: connection (apsw.Connection): connection to the sqlite db who stores mpr data. query (str): sql query fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch. Returns: iterable with query result. """ cursor = connection.cursor() try: cursor.execute(query) except Exception as e: from ambry.mprlib.exceptions import BadSQLError raise BadSQLError("Failed to execute query: {}; {}".format(query, e)) if fetch: return cursor.fetchall() else: return cursor
python
def _execute(self, connection, query, fetch=True): """ Executes given query using given connection. Args: connection (apsw.Connection): connection to the sqlite db who stores mpr data. query (str): sql query fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch. Returns: iterable with query result. """ cursor = connection.cursor() try: cursor.execute(query) except Exception as e: from ambry.mprlib.exceptions import BadSQLError raise BadSQLError("Failed to execute query: {}; {}".format(query, e)) if fetch: return cursor.fetchall() else: return cursor
[ "def", "_execute", "(", "self", ",", "connection", ",", "query", ",", "fetch", "=", "True", ")", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "query", ")", "except", "Exception", "as", "e", ":"...
Executes given query using given connection. Args: connection (apsw.Connection): connection to the sqlite db who stores mpr data. query (str): sql query fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch. Returns: iterable with query result.
[ "Executes", "given", "query", "using", "given", "connection", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L307-L330
flaviogrossi/sockjs-cyclone
sockjs/cyclone/basehandler.py
BaseHandler._log_disconnect
def _log_disconnect(self): """ Decrement connection count """ if self.logged: self.server.stats.connectionClosed() self.logged = False
python
def _log_disconnect(self): """ Decrement connection count """ if self.logged: self.server.stats.connectionClosed() self.logged = False
[ "def", "_log_disconnect", "(", "self", ")", ":", "if", "self", ".", "logged", ":", "self", ".", "server", ".", "stats", ".", "connectionClosed", "(", ")", "self", ".", "logged", "=", "False" ]
Decrement connection count
[ "Decrement", "connection", "count" ]
train
https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/basehandler.py#L29-L33
flaviogrossi/sockjs-cyclone
sockjs/cyclone/basehandler.py
BaseHandler.enable_cache
def enable_cache(self): """ Enable client-side caching for the current request """ self.set_header('Cache-Control', 'max-age=%d, public' % self.CACHE_TIME) now = datetime.datetime.now() expires = now + datetime.timedelta(seconds=self.CACHE_TIME) self.set_header('Expires', expires.strftime('%a, %d %b %Y %H:%M:%S')) self.set_header('access-control-max-age', self.CACHE_TIME)
python
def enable_cache(self): """ Enable client-side caching for the current request """ self.set_header('Cache-Control', 'max-age=%d, public' % self.CACHE_TIME) now = datetime.datetime.now() expires = now + datetime.timedelta(seconds=self.CACHE_TIME) self.set_header('Expires', expires.strftime('%a, %d %b %Y %H:%M:%S')) self.set_header('access-control-max-age', self.CACHE_TIME)
[ "def", "enable_cache", "(", "self", ")", ":", "self", ".", "set_header", "(", "'Cache-Control'", ",", "'max-age=%d, public'", "%", "self", ".", "CACHE_TIME", ")", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "expires", "=", "now", "+", ...
Enable client-side caching for the current request
[ "Enable", "client", "-", "side", "caching", "for", "the", "current", "request" ]
train
https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/basehandler.py#L45-L53
project-ncl/pnc-cli
pnc_cli/productmilestones.py
list_milestones
def list_milestones(page_size=200, page_index=0, q="", sort=""): """ List all ProductMilestones """ data = list_milestones_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
python
def list_milestones(page_size=200, page_index=0, q="", sort=""): """ List all ProductMilestones """ data = list_milestones_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
[ "def", "list_milestones", "(", "page_size", "=", "200", ",", "page_index", "=", "0", ",", "q", "=", "\"\"", ",", "sort", "=", "\"\"", ")", ":", "data", "=", "list_milestones_raw", "(", "page_size", ",", "page_index", ",", "sort", ",", "q", ")", "if", ...
List all ProductMilestones
[ "List", "all", "ProductMilestones" ]
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/productmilestones.py#L41-L47
project-ncl/pnc-cli
pnc_cli/productmilestones.py
update_milestone
def update_milestone(id, **kwargs): """ Update a ProductMilestone """ data = update_milestone_raw(id, **kwargs) if data: return utils.format_json(data)
python
def update_milestone(id, **kwargs): """ Update a ProductMilestone """ data = update_milestone_raw(id, **kwargs) if data: return utils.format_json(data)
[ "def", "update_milestone", "(", "id", ",", "*", "*", "kwargs", ")", ":", "data", "=", "update_milestone_raw", "(", "id", ",", "*", "*", "kwargs", ")", "if", "data", ":", "return", "utils", ".", "format_json", "(", "data", ")" ]
Update a ProductMilestone
[ "Update", "a", "ProductMilestone" ]
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/productmilestones.py#L121-L127
project-ncl/pnc-cli
pnc_cli/productmilestones.py
close_milestone
def close_milestone(id, **kwargs): """ Close a milestone. This triggers its release process. The user can optionally specify the release-date, otherwise today's date is used. If the wait parameter is specified and set to True, upon closing the milestone, we'll periodically check that the release being processed is done. Required: - id: int Optional: - wait key: bool """ data = close_milestone_raw(id, **kwargs) if data: return utils.format_json(data)
python
def close_milestone(id, **kwargs): """ Close a milestone. This triggers its release process. The user can optionally specify the release-date, otherwise today's date is used. If the wait parameter is specified and set to True, upon closing the milestone, we'll periodically check that the release being processed is done. Required: - id: int Optional: - wait key: bool """ data = close_milestone_raw(id, **kwargs) if data: return utils.format_json(data)
[ "def", "close_milestone", "(", "id", ",", "*", "*", "kwargs", ")", ":", "data", "=", "close_milestone_raw", "(", "id", ",", "*", "*", "kwargs", ")", "if", "data", ":", "return", "utils", ".", "format_json", "(", "data", ")" ]
Close a milestone. This triggers its release process. The user can optionally specify the release-date, otherwise today's date is used. If the wait parameter is specified and set to True, upon closing the milestone, we'll periodically check that the release being processed is done. Required: - id: int Optional: - wait key: bool
[ "Close", "a", "milestone", ".", "This", "triggers", "its", "release", "process", "." ]
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/productmilestones.py#L156-L174
carsongee/flask-htpasswd
flask_htpasswd.py
HtPasswdAuth.init_app
def init_app(self, app): """ Find and configure the user database from specified file """ app.config.setdefault('FLASK_AUTH_ALL', False) app.config.setdefault('FLASK_AUTH_REALM', 'Login Required') # Default set to bad file to trigger IOError app.config.setdefault('FLASK_HTPASSWD_PATH', '/^^^/^^^') # Load up user database try: self.load_users(app) except IOError: log.critical( 'No htpasswd file loaded, please set `FLASK_HTPASSWD`' 'or `FLASK_HTPASSWD_PATH` environment variable to a ' 'valid apache htpasswd file.' ) # Allow requiring auth for entire app, with pre request method @app.before_request def require_auth(): # pylint: disable=unused-variable """Pre request processing for enabling full app authentication.""" if not current_app.config['FLASK_AUTH_ALL']: return is_valid, user = self.authenticate() if not is_valid: return self.auth_failed() g.user = user
python
def init_app(self, app): """ Find and configure the user database from specified file """ app.config.setdefault('FLASK_AUTH_ALL', False) app.config.setdefault('FLASK_AUTH_REALM', 'Login Required') # Default set to bad file to trigger IOError app.config.setdefault('FLASK_HTPASSWD_PATH', '/^^^/^^^') # Load up user database try: self.load_users(app) except IOError: log.critical( 'No htpasswd file loaded, please set `FLASK_HTPASSWD`' 'or `FLASK_HTPASSWD_PATH` environment variable to a ' 'valid apache htpasswd file.' ) # Allow requiring auth for entire app, with pre request method @app.before_request def require_auth(): # pylint: disable=unused-variable """Pre request processing for enabling full app authentication.""" if not current_app.config['FLASK_AUTH_ALL']: return is_valid, user = self.authenticate() if not is_valid: return self.auth_failed() g.user = user
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "app", ".", "config", ".", "setdefault", "(", "'FLASK_AUTH_ALL'", ",", "False", ")", "app", ".", "config", ".", "setdefault", "(", "'FLASK_AUTH_REALM'", ",", "'Login Required'", ")", "# Default set to bad f...
Find and configure the user database from specified file
[ "Find", "and", "configure", "the", "user", "database", "from", "specified", "file" ]
train
https://github.com/carsongee/flask-htpasswd/blob/db6fe596dd167f33aeb3d77e975c861d0534cecf/flask_htpasswd.py#L30-L58
carsongee/flask-htpasswd
flask_htpasswd.py
HtPasswdAuth.check_basic_auth
def check_basic_auth(self, username, password): """ This function is called to check if a username / password combination is valid via the htpasswd file. """ valid = self.users.check_password( username, password ) if not valid: log.warning('Invalid login from %s', username) valid = False return ( valid, username )
python
def check_basic_auth(self, username, password): """ This function is called to check if a username / password combination is valid via the htpasswd file. """ valid = self.users.check_password( username, password ) if not valid: log.warning('Invalid login from %s', username) valid = False return ( valid, username )
[ "def", "check_basic_auth", "(", "self", ",", "username", ",", "password", ")", ":", "valid", "=", "self", ".", "users", ".", "check_password", "(", "username", ",", "password", ")", "if", "not", "valid", ":", "log", ".", "warning", "(", "'Invalid login fro...
This function is called to check if a username / password combination is valid via the htpasswd file.
[ "This", "function", "is", "called", "to", "check", "if", "a", "username", "/", "password", "combination", "is", "valid", "via", "the", "htpasswd", "file", "." ]
train
https://github.com/carsongee/flask-htpasswd/blob/db6fe596dd167f33aeb3d77e975c861d0534cecf/flask_htpasswd.py#L76-L90
carsongee/flask-htpasswd
flask_htpasswd.py
HtPasswdAuth.get_hashhash
def get_hashhash(self, username): """ Generate a digest of the htpasswd hash """ return hashlib.sha256( self.users.get_hash(username) ).hexdigest()
python
def get_hashhash(self, username): """ Generate a digest of the htpasswd hash """ return hashlib.sha256( self.users.get_hash(username) ).hexdigest()
[ "def", "get_hashhash", "(", "self", ",", "username", ")", ":", "return", "hashlib", ".", "sha256", "(", "self", ".", "users", ".", "get_hash", "(", "username", ")", ")", ".", "hexdigest", "(", ")" ]
Generate a digest of the htpasswd hash
[ "Generate", "a", "digest", "of", "the", "htpasswd", "hash" ]
train
https://github.com/carsongee/flask-htpasswd/blob/db6fe596dd167f33aeb3d77e975c861d0534cecf/flask_htpasswd.py#L99-L105
carsongee/flask-htpasswd
flask_htpasswd.py
HtPasswdAuth.generate_token
def generate_token(self, username): """ assumes user exists in htpasswd file. Return the token for the given user by signing a token of the username and a hash of the htpasswd string. """ serializer = self.get_signature() return serializer.dumps( { 'username': username, 'hashhash': self.get_hashhash(username) } ).decode('UTF-8')
python
def generate_token(self, username): """ assumes user exists in htpasswd file. Return the token for the given user by signing a token of the username and a hash of the htpasswd string. """ serializer = self.get_signature() return serializer.dumps( { 'username': username, 'hashhash': self.get_hashhash(username) } ).decode('UTF-8')
[ "def", "generate_token", "(", "self", ",", "username", ")", ":", "serializer", "=", "self", ".", "get_signature", "(", ")", "return", "serializer", ".", "dumps", "(", "{", "'username'", ":", "username", ",", "'hashhash'", ":", "self", ".", "get_hashhash", ...
assumes user exists in htpasswd file. Return the token for the given user by signing a token of the username and a hash of the htpasswd string.
[ "assumes", "user", "exists", "in", "htpasswd", "file", "." ]
train
https://github.com/carsongee/flask-htpasswd/blob/db6fe596dd167f33aeb3d77e975c861d0534cecf/flask_htpasswd.py#L107-L120
carsongee/flask-htpasswd
flask_htpasswd.py
HtPasswdAuth.check_token_auth
def check_token_auth(self, token): """ Check to see who this is and if their token gets them into the system. """ serializer = self.get_signature() try: data = serializer.loads(token) except BadSignature: log.warning('Received bad token signature') return False, None if data['username'] not in self.users.users(): log.warning( 'Token auth signed message, but invalid user %s', data['username'] ) return False, None if data['hashhash'] != self.get_hashhash(data['username']): log.warning( 'Token and password do not match, %s ' 'needs to regenerate token', data['username'] ) return False, None return True, data['username']
python
def check_token_auth(self, token): """ Check to see who this is and if their token gets them into the system. """ serializer = self.get_signature() try: data = serializer.loads(token) except BadSignature: log.warning('Received bad token signature') return False, None if data['username'] not in self.users.users(): log.warning( 'Token auth signed message, but invalid user %s', data['username'] ) return False, None if data['hashhash'] != self.get_hashhash(data['username']): log.warning( 'Token and password do not match, %s ' 'needs to regenerate token', data['username'] ) return False, None return True, data['username']
[ "def", "check_token_auth", "(", "self", ",", "token", ")", ":", "serializer", "=", "self", ".", "get_signature", "(", ")", "try", ":", "data", "=", "serializer", ".", "loads", "(", "token", ")", "except", "BadSignature", ":", "log", ".", "warning", "(", ...
Check to see who this is and if their token gets them into the system.
[ "Check", "to", "see", "who", "this", "is", "and", "if", "their", "token", "gets", "them", "into", "the", "system", "." ]
train
https://github.com/carsongee/flask-htpasswd/blob/db6fe596dd167f33aeb3d77e975c861d0534cecf/flask_htpasswd.py#L122-L147
carsongee/flask-htpasswd
flask_htpasswd.py
HtPasswdAuth.authenticate
def authenticate(self): """Authenticate user by any means and return either true or false. Args: Returns: tuple (is_valid, username): True is valid user, False if not """ basic_auth = request.authorization is_valid = False user = None if basic_auth: is_valid, user = self.check_basic_auth( basic_auth.username, basic_auth.password ) else: # Try token auth token = request.headers.get('Authorization', None) param_token = request.args.get('access_token') if token or param_token: if token: # slice the 'token ' piece of the header (following # github style): token = token[6:] else: # Grab it from query dict instead token = param_token log.debug('Received token: %s', token) is_valid, user = self.check_token_auth(token) return (is_valid, user)
python
def authenticate(self): """Authenticate user by any means and return either true or false. Args: Returns: tuple (is_valid, username): True is valid user, False if not """ basic_auth = request.authorization is_valid = False user = None if basic_auth: is_valid, user = self.check_basic_auth( basic_auth.username, basic_auth.password ) else: # Try token auth token = request.headers.get('Authorization', None) param_token = request.args.get('access_token') if token or param_token: if token: # slice the 'token ' piece of the header (following # github style): token = token[6:] else: # Grab it from query dict instead token = param_token log.debug('Received token: %s', token) is_valid, user = self.check_token_auth(token) return (is_valid, user)
[ "def", "authenticate", "(", "self", ")", ":", "basic_auth", "=", "request", ".", "authorization", "is_valid", "=", "False", "user", "=", "None", "if", "basic_auth", ":", "is_valid", ",", "user", "=", "self", ".", "check_basic_auth", "(", "basic_auth", ".", ...
Authenticate user by any means and return either true or false. Args: Returns: tuple (is_valid, username): True is valid user, False if not
[ "Authenticate", "user", "by", "any", "means", "and", "return", "either", "true", "or", "false", "." ]
train
https://github.com/carsongee/flask-htpasswd/blob/db6fe596dd167f33aeb3d77e975c861d0534cecf/flask_htpasswd.py#L163-L192
carsongee/flask-htpasswd
flask_htpasswd.py
HtPasswdAuth.required
def required(self, func): """ Decorator function with basic and token authentication handler """ @wraps(func) def decorated(*args, **kwargs): """ Actual wrapper to run the auth checks. """ is_valid, user = self.authenticate() if not is_valid: return self.auth_failed() kwargs['user'] = user return func(*args, **kwargs) return decorated
python
def required(self, func): """ Decorator function with basic and token authentication handler """ @wraps(func) def decorated(*args, **kwargs): """ Actual wrapper to run the auth checks. """ is_valid, user = self.authenticate() if not is_valid: return self.auth_failed() kwargs['user'] = user return func(*args, **kwargs) return decorated
[ "def", "required", "(", "self", ",", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Actual wrapper to run the auth checks.\n \"\"\"", "is_valid", ",", "us...
Decorator function with basic and token authentication handler
[ "Decorator", "function", "with", "basic", "and", "token", "authentication", "handler" ]
train
https://github.com/carsongee/flask-htpasswd/blob/db6fe596dd167f33aeb3d77e975c861d0534cecf/flask_htpasswd.py#L194-L208
CivicSpleen/ambry
ambry/identity.py
Name._dict
def _dict(self, with_name=True): """Returns the identity as a dict. values that are empty are removed """ d = dict([(k, getattr(self, k)) for k, _, _ in self.name_parts]) if with_name: d['name'] = self.name try: d['vname'] = self.vname except ValueError: pass return self.clear_dict(d)
python
def _dict(self, with_name=True): """Returns the identity as a dict. values that are empty are removed """ d = dict([(k, getattr(self, k)) for k, _, _ in self.name_parts]) if with_name: d['name'] = self.name try: d['vname'] = self.vname except ValueError: pass return self.clear_dict(d)
[ "def", "_dict", "(", "self", ",", "with_name", "=", "True", ")", ":", "d", "=", "dict", "(", "[", "(", "k", ",", "getattr", "(", "self", ",", "k", ")", ")", "for", "k", ",", "_", ",", "_", "in", "self", ".", "name_parts", "]", ")", "if", "w...
Returns the identity as a dict. values that are empty are removed
[ "Returns", "the", "identity", "as", "a", "dict", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L162-L178
CivicSpleen/ambry
ambry/identity.py
Name.source_path
def source_path(self): """The name in a form suitable for use in a filesystem. Excludes the revision """ # Need to do this to ensure the function produces the # bundle path when called from subclasses names = [k for k, _, _ in self._name_parts] parts = [self.source] if self.bspace: parts.append(self.bspace) parts.append( self._path_join(names=names, excludes=['source', 'version', 'bspace'], sep=self.NAME_PART_SEP)) return os.path.join(*parts)
python
def source_path(self): """The name in a form suitable for use in a filesystem. Excludes the revision """ # Need to do this to ensure the function produces the # bundle path when called from subclasses names = [k for k, _, _ in self._name_parts] parts = [self.source] if self.bspace: parts.append(self.bspace) parts.append( self._path_join(names=names, excludes=['source', 'version', 'bspace'], sep=self.NAME_PART_SEP)) return os.path.join(*parts)
[ "def", "source_path", "(", "self", ")", ":", "# Need to do this to ensure the function produces the", "# bundle path when called from subclasses", "names", "=", "[", "k", "for", "k", ",", "_", ",", "_", "in", "self", ".", "_name_parts", "]", "parts", "=", "[", "se...
The name in a form suitable for use in a filesystem. Excludes the revision
[ "The", "name", "in", "a", "form", "suitable", "for", "use", "in", "a", "filesystem", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L239-L257
CivicSpleen/ambry
ambry/identity.py
Name.cache_key
def cache_key(self): """The name in a form suitable for use as a cache-key""" try: return self.path except TypeError: raise TypeError("self.path is invalild: '{}', '{}'".format(str(self.path), type(self.path)))
python
def cache_key(self): """The name in a form suitable for use as a cache-key""" try: return self.path except TypeError: raise TypeError("self.path is invalild: '{}', '{}'".format(str(self.path), type(self.path)))
[ "def", "cache_key", "(", "self", ")", ":", "try", ":", "return", "self", ".", "path", "except", "TypeError", ":", "raise", "TypeError", "(", "\"self.path is invalild: '{}', '{}'\"", ".", "format", "(", "str", "(", "self", ".", "path", ")", ",", "type", "("...
The name in a form suitable for use as a cache-key
[ "The", "name", "in", "a", "form", "suitable", "for", "use", "as", "a", "cache", "-", "key" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L260-L265
CivicSpleen/ambry
ambry/identity.py
Name.ver
def ver(self, revision): """Clone and change the version.""" c = self.clone() c.version = self._parse_version(self.version) return c
python
def ver(self, revision): """Clone and change the version.""" c = self.clone() c.version = self._parse_version(self.version) return c
[ "def", "ver", "(", "self", ",", "revision", ")", ":", "c", "=", "self", ".", "clone", "(", ")", "c", ".", "version", "=", "self", ".", "_parse_version", "(", "self", ".", "version", ")", "return", "c" ]
Clone and change the version.
[ "Clone", "and", "change", "the", "version", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L270-L277
CivicSpleen/ambry
ambry/identity.py
Name.as_partition
def as_partition(self, **kwargs): """Return a PartitionName based on this name.""" return PartitionName(**dict(list(self.dict.items()) + list(kwargs.items())))
python
def as_partition(self, **kwargs): """Return a PartitionName based on this name.""" return PartitionName(**dict(list(self.dict.items()) + list(kwargs.items())))
[ "def", "as_partition", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "PartitionName", "(", "*", "*", "dict", "(", "list", "(", "self", ".", "dict", ".", "items", "(", ")", ")", "+", "list", "(", "kwargs", ".", "items", "(", ")", ")", ...
Return a PartitionName based on this name.
[ "Return", "a", "PartitionName", "based", "on", "this", "name", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L328-L331
CivicSpleen/ambry
ambry/identity.py
PartialPartitionName.promote
def promote(self, name): """Promote to a PartitionName by combining with a bundle Name.""" return PartitionName(**dict(list(name.dict.items()) + list(self.dict.items())))
python
def promote(self, name): """Promote to a PartitionName by combining with a bundle Name.""" return PartitionName(**dict(list(name.dict.items()) + list(self.dict.items())))
[ "def", "promote", "(", "self", ",", "name", ")", ":", "return", "PartitionName", "(", "*", "*", "dict", "(", "list", "(", "name", ".", "dict", ".", "items", "(", ")", ")", "+", "list", "(", "self", ".", "dict", ".", "items", "(", ")", ")", ")",...
Promote to a PartitionName by combining with a bundle Name.
[ "Promote", "to", "a", "PartitionName", "by", "combining", "with", "a", "bundle", "Name", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L363-L365
CivicSpleen/ambry
ambry/identity.py
PartitionName.path
def path(self): """The path of the bundle source. Includes the revision. """ # Need to do this to ensure the function produces the # bundle path when called from subclasses names = [k for k, _, _ in Name._name_parts] return os.path.join(self.source, self._path_join(names=names, excludes=['source', 'format'], sep=self.NAME_PART_SEP), *self._local_parts() )
python
def path(self): """The path of the bundle source. Includes the revision. """ # Need to do this to ensure the function produces the # bundle path when called from subclasses names = [k for k, _, _ in Name._name_parts] return os.path.join(self.source, self._path_join(names=names, excludes=['source', 'format'], sep=self.NAME_PART_SEP), *self._local_parts() )
[ "def", "path", "(", "self", ")", ":", "# Need to do this to ensure the function produces the", "# bundle path when called from subclasses", "names", "=", "[", "k", "for", "k", ",", "_", ",", "_", "in", "Name", ".", "_name_parts", "]", "return", "os", ".", "path", ...
The path of the bundle source. Includes the revision.
[ "The", "path", "of", "the", "bundle", "source", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L438-L452
CivicSpleen/ambry
ambry/identity.py
PartitionName.sub_path
def sub_path(self): """The path of the partition source, excluding the bundle path parts. Includes the revision. """ try: return os.path.join(*(self._local_parts())) except TypeError as e: raise TypeError( "Path failed for partition {} : {}".format( self.name, e.message))
python
def sub_path(self): """The path of the partition source, excluding the bundle path parts. Includes the revision. """ try: return os.path.join(*(self._local_parts())) except TypeError as e: raise TypeError( "Path failed for partition {} : {}".format( self.name, e.message))
[ "def", "sub_path", "(", "self", ")", ":", "try", ":", "return", "os", ".", "path", ".", "join", "(", "*", "(", "self", ".", "_local_parts", "(", ")", ")", ")", "except", "TypeError", "as", "e", ":", "raise", "TypeError", "(", "\"Path failed for partiti...
The path of the partition source, excluding the bundle path parts. Includes the revision.
[ "The", "path", "of", "the", "partition", "source", "excluding", "the", "bundle", "path", "parts", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L459-L472
CivicSpleen/ambry
ambry/identity.py
PartitionName.partital_dict
def partital_dict(self, with_name=True): """Returns the name as a dict, but with only the items that are particular to a PartitionName.""" d = self._dict(with_name=False) d = {k: d.get(k) for k, _, _ in PartialPartitionName._name_parts if d.get(k, False)} if 'format' in d and d['format'] == Name.DEFAULT_FORMAT: del d['format'] d['name'] = self.name return d
python
def partital_dict(self, with_name=True): """Returns the name as a dict, but with only the items that are particular to a PartitionName.""" d = self._dict(with_name=False) d = {k: d.get(k) for k, _, _ in PartialPartitionName._name_parts if d.get(k, False)} if 'format' in d and d['format'] == Name.DEFAULT_FORMAT: del d['format'] d['name'] = self.name return d
[ "def", "partital_dict", "(", "self", ",", "with_name", "=", "True", ")", ":", "d", "=", "self", ".", "_dict", "(", "with_name", "=", "False", ")", "d", "=", "{", "k", ":", "d", ".", "get", "(", "k", ")", "for", "k", ",", "_", ",", "_", "in", ...
Returns the name as a dict, but with only the items that are particular to a PartitionName.
[ "Returns", "the", "name", "as", "a", "dict", "but", "with", "only", "the", "items", "that", "are", "particular", "to", "a", "PartitionName", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L496-L509
CivicSpleen/ambry
ambry/identity.py
PartialMixin._dict
def _dict(self, with_name=True): """Returns the identity as a dict. values that are empty are removed """ d = dict([(k, getattr(self, k)) for k, _, _ in self.name_parts]) return self.clear_dict(d)
python
def _dict(self, with_name=True): """Returns the identity as a dict. values that are empty are removed """ d = dict([(k, getattr(self, k)) for k, _, _ in self.name_parts]) return self.clear_dict(d)
[ "def", "_dict", "(", "self", ",", "with_name", "=", "True", ")", ":", "d", "=", "dict", "(", "[", "(", "k", ",", "getattr", "(", "self", ",", "k", ")", ")", "for", "k", ",", "_", ",", "_", "in", "self", ".", "name_parts", "]", ")", "return", ...
Returns the identity as a dict. values that are empty are removed
[ "Returns", "the", "identity", "as", "a", "dict", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L525-L534
CivicSpleen/ambry
ambry/identity.py
PartialMixin.with_none
def with_none(self): """Convert the NameQuery.NONE to None. This is needed because on the kwargs list, a None value means the field is not specified, which equates to ANY. The _find_orm() routine, however, is easier to write if the NONE value is actually None. Returns a clone of the origin, with NONE converted to None """ n = self.clone() for k, _, _ in n.name_parts: if getattr(n, k) == n.NONE: delattr(n, k) n.use_clear_dict = False return n
python
def with_none(self): """Convert the NameQuery.NONE to None. This is needed because on the kwargs list, a None value means the field is not specified, which equates to ANY. The _find_orm() routine, however, is easier to write if the NONE value is actually None. Returns a clone of the origin, with NONE converted to None """ n = self.clone() for k, _, _ in n.name_parts: if getattr(n, k) == n.NONE: delattr(n, k) n.use_clear_dict = False return n
[ "def", "with_none", "(", "self", ")", ":", "n", "=", "self", ".", "clone", "(", ")", "for", "k", ",", "_", ",", "_", "in", "n", ".", "name_parts", ":", "if", "getattr", "(", "n", ",", "k", ")", "==", "n", ".", "NONE", ":", "delattr", "(", "...
Convert the NameQuery.NONE to None. This is needed because on the kwargs list, a None value means the field is not specified, which equates to ANY. The _find_orm() routine, however, is easier to write if the NONE value is actually None. Returns a clone of the origin, with NONE converted to None
[ "Convert", "the", "NameQuery", ".", "NONE", "to", "None", ".", "This", "is", "needed", "because", "on", "the", "kwargs", "list", "a", "None", "value", "means", "the", "field", "is", "not", "specified", "which", "equates", "to", "ANY", ".", "The", "_find_...
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L536-L555
CivicSpleen/ambry
ambry/identity.py
NameQuery.name_parts
def name_parts(self): """Works with PartialNameMixin.clear_dict to set NONE and ANY values.""" default = PartialMixin.ANY np = ([(k, default, True) for k, _, _ in super(NameQuery, self).name_parts] + [(k, default, True) for k, _, _ in Name._generated_names] ) return np
python
def name_parts(self): """Works with PartialNameMixin.clear_dict to set NONE and ANY values.""" default = PartialMixin.ANY np = ([(k, default, True) for k, _, _ in super(NameQuery, self).name_parts] + [(k, default, True) for k, _, _ in Name._generated_names] ) return np
[ "def", "name_parts", "(", "self", ")", ":", "default", "=", "PartialMixin", ".", "ANY", "np", "=", "(", "[", "(", "k", ",", "default", ",", "True", ")", "for", "k", ",", "_", ",", "_", "in", "super", "(", "NameQuery", ",", "self", ")", ".", "na...
Works with PartialNameMixin.clear_dict to set NONE and ANY values.
[ "Works", "with", "PartialNameMixin", ".", "clear_dict", "to", "set", "NONE", "and", "ANY", "values", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L600-L613
CivicSpleen/ambry
ambry/identity.py
PartitionNameQuery.name_parts
def name_parts(self): """Works with PartialNameMixin.clear_dict to set NONE and ANY values.""" default = PartialMixin.ANY return ([(k, default, True) for k, _, _ in PartitionName._name_parts] + [(k, default, True) for k, _, _ in Name._generated_names] )
python
def name_parts(self): """Works with PartialNameMixin.clear_dict to set NONE and ANY values.""" default = PartialMixin.ANY return ([(k, default, True) for k, _, _ in PartitionName._name_parts] + [(k, default, True) for k, _, _ in Name._generated_names] )
[ "def", "name_parts", "(", "self", ")", ":", "default", "=", "PartialMixin", ".", "ANY", "return", "(", "[", "(", "k", ",", "default", ",", "True", ")", "for", "k", ",", "_", ",", "_", "in", "PartitionName", ".", "_name_parts", "]", "+", "[", "(", ...
Works with PartialNameMixin.clear_dict to set NONE and ANY values.
[ "Works", "with", "PartialNameMixin", ".", "clear_dict", "to", "set", "NONE", "and", "ANY", "values", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L640-L651
CivicSpleen/ambry
ambry/identity.py
ObjectNumber.parse
def parse(cls, on_str, force_type=None): # @ReservedAssignment """Parse a string into one of the object number classes.""" on_str_orig = on_str if on_str is None: return None if not on_str: raise NotObjectNumberError("Got null input") if not isinstance(on_str, string_types): raise NotObjectNumberError("Must be a string. Got a {} ".format(type(on_str))) # if isinstance(on_str, unicode): # dataset = on_str.encode('ascii') if force_type: type_ = force_type else: type_ = on_str[0] on_str = on_str[1:] if type_ not in list(cls.NDS_LENGTH.keys()): raise NotObjectNumberError("Unknown type character '{}' for '{}'".format(type_, on_str_orig)) ds_length = len(on_str) - cls.NDS_LENGTH[type_] if ds_length not in cls.DATASET_LENGTHS: raise NotObjectNumberError( "Dataset string '{}' has an unfamiliar length: {}".format(on_str_orig, ds_length)) ds_lengths = cls.DATASET_LENGTHS[ds_length] assignment_class = ds_lengths[2] try: dataset = int(ObjectNumber.base62_decode(on_str[0:ds_lengths[0]])) if ds_lengths[1]: i = len(on_str) - ds_lengths[1] revision = int(ObjectNumber.base62_decode(on_str[i:])) on_str = on_str[0:i] # remove the revision else: revision = None on_str = on_str[ds_lengths[0]:] if type_ == cls.TYPE.DATASET: return DatasetNumber(dataset, revision=revision, assignment_class=assignment_class) elif type_ == cls.TYPE.TABLE: table = int(ObjectNumber.base62_decode(on_str)) return TableNumber( DatasetNumber(dataset, assignment_class=assignment_class), table, revision=revision) elif type_ == cls.TYPE.PARTITION: partition = int(ObjectNumber.base62_decode(on_str)) return PartitionNumber( DatasetNumber(dataset, assignment_class=assignment_class), partition, revision=revision) elif type_ == cls.TYPE.COLUMN: table = int(ObjectNumber.base62_decode(on_str[0:cls.DLEN.TABLE])) column = int(ObjectNumber.base62_decode(on_str[cls.DLEN.TABLE:])) return ColumnNumber( TableNumber(DatasetNumber(dataset, assignment_class=assignment_class), table), column, revision=revision) elif type_ == cls.TYPE.OTHER1 or type_ == cls.TYPE.CONFIG: return GeneralNumber1(on_str_orig[0], DatasetNumber(dataset, assignment_class=assignment_class), int(ObjectNumber.base62_decode(on_str[0:cls.DLEN.OTHER1])), revision=revision) elif type_ == cls.TYPE.OTHER2: return GeneralNumber2(on_str_orig[0], DatasetNumber(dataset, assignment_class=assignment_class), int(ObjectNumber.base62_decode(on_str[0:cls.DLEN.OTHER1])), int(ObjectNumber.base62_decode( on_str[cls.DLEN.OTHER1:cls.DLEN.OTHER1+cls.DLEN.OTHER2])), revision=revision) else: raise NotObjectNumberError('Unknown type character: ' + type_ + ' in ' + str(on_str_orig)) except Base62DecodeError as e: raise NotObjectNumberError('Unknown character: ' + str(e))
python
def parse(cls, on_str, force_type=None): # @ReservedAssignment """Parse a string into one of the object number classes.""" on_str_orig = on_str if on_str is None: return None if not on_str: raise NotObjectNumberError("Got null input") if not isinstance(on_str, string_types): raise NotObjectNumberError("Must be a string. Got a {} ".format(type(on_str))) # if isinstance(on_str, unicode): # dataset = on_str.encode('ascii') if force_type: type_ = force_type else: type_ = on_str[0] on_str = on_str[1:] if type_ not in list(cls.NDS_LENGTH.keys()): raise NotObjectNumberError("Unknown type character '{}' for '{}'".format(type_, on_str_orig)) ds_length = len(on_str) - cls.NDS_LENGTH[type_] if ds_length not in cls.DATASET_LENGTHS: raise NotObjectNumberError( "Dataset string '{}' has an unfamiliar length: {}".format(on_str_orig, ds_length)) ds_lengths = cls.DATASET_LENGTHS[ds_length] assignment_class = ds_lengths[2] try: dataset = int(ObjectNumber.base62_decode(on_str[0:ds_lengths[0]])) if ds_lengths[1]: i = len(on_str) - ds_lengths[1] revision = int(ObjectNumber.base62_decode(on_str[i:])) on_str = on_str[0:i] # remove the revision else: revision = None on_str = on_str[ds_lengths[0]:] if type_ == cls.TYPE.DATASET: return DatasetNumber(dataset, revision=revision, assignment_class=assignment_class) elif type_ == cls.TYPE.TABLE: table = int(ObjectNumber.base62_decode(on_str)) return TableNumber( DatasetNumber(dataset, assignment_class=assignment_class), table, revision=revision) elif type_ == cls.TYPE.PARTITION: partition = int(ObjectNumber.base62_decode(on_str)) return PartitionNumber( DatasetNumber(dataset, assignment_class=assignment_class), partition, revision=revision) elif type_ == cls.TYPE.COLUMN: table = int(ObjectNumber.base62_decode(on_str[0:cls.DLEN.TABLE])) column = int(ObjectNumber.base62_decode(on_str[cls.DLEN.TABLE:])) return ColumnNumber( TableNumber(DatasetNumber(dataset, assignment_class=assignment_class), table), column, revision=revision) elif type_ == cls.TYPE.OTHER1 or type_ == cls.TYPE.CONFIG: return GeneralNumber1(on_str_orig[0], DatasetNumber(dataset, assignment_class=assignment_class), int(ObjectNumber.base62_decode(on_str[0:cls.DLEN.OTHER1])), revision=revision) elif type_ == cls.TYPE.OTHER2: return GeneralNumber2(on_str_orig[0], DatasetNumber(dataset, assignment_class=assignment_class), int(ObjectNumber.base62_decode(on_str[0:cls.DLEN.OTHER1])), int(ObjectNumber.base62_decode( on_str[cls.DLEN.OTHER1:cls.DLEN.OTHER1+cls.DLEN.OTHER2])), revision=revision) else: raise NotObjectNumberError('Unknown type character: ' + type_ + ' in ' + str(on_str_orig)) except Base62DecodeError as e: raise NotObjectNumberError('Unknown character: ' + str(e))
[ "def", "parse", "(", "cls", ",", "on_str", ",", "force_type", "=", "None", ")", ":", "# @ReservedAssignment", "on_str_orig", "=", "on_str", "if", "on_str", "is", "None", ":", "return", "None", "if", "not", "on_str", ":", "raise", "NotObjectNumberError", "(",...
Parse a string into one of the object number classes.
[ "Parse", "a", "string", "into", "one", "of", "the", "object", "number", "classes", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L737-L826
CivicSpleen/ambry
ambry/identity.py
ObjectNumber.base62_encode
def base62_encode(cls, num): """Encode a number in Base X. `num`: The number to encode `alphabet`: The alphabet to use for encoding Stolen from: http://stackoverflow.com/a/1119769/1144479 """ alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" if num == 0: return alphabet[0] arr = [] base = len(alphabet) while num: rem = num % base num = num // base arr.append(alphabet[rem]) arr.reverse() return ''.join(arr)
python
def base62_encode(cls, num): """Encode a number in Base X. `num`: The number to encode `alphabet`: The alphabet to use for encoding Stolen from: http://stackoverflow.com/a/1119769/1144479 """ alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" if num == 0: return alphabet[0] arr = [] base = len(alphabet) while num: rem = num % base num = num // base arr.append(alphabet[rem]) arr.reverse() return ''.join(arr)
[ "def", "base62_encode", "(", "cls", ",", "num", ")", ":", "alphabet", "=", "\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"", "if", "num", "==", "0", ":", "return", "alphabet", "[", "0", "]", "arr", "=", "[", "]", "base", "=", "len", "(", ...
Encode a number in Base X. `num`: The number to encode `alphabet`: The alphabet to use for encoding Stolen from: http://stackoverflow.com/a/1119769/1144479
[ "Encode", "a", "number", "in", "Base", "X", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L829-L849
CivicSpleen/ambry
ambry/identity.py
ObjectNumber.base62_decode
def base62_decode(cls, string): """Decode a Base X encoded string into the number. Arguments: - `string`: The encoded string - `alphabet`: The alphabet to use for encoding Stolen from: http://stackoverflow.com/a/1119769/1144479 """ alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" base = len(alphabet) strlen = len(string) num = 0 idx = 0 for char in string: power = (strlen - (idx + 1)) try: num += alphabet.index(char) * (base ** power) except ValueError: raise Base62DecodeError( "Failed to decode char: '{}'".format(char)) idx += 1 return num
python
def base62_decode(cls, string): """Decode a Base X encoded string into the number. Arguments: - `string`: The encoded string - `alphabet`: The alphabet to use for encoding Stolen from: http://stackoverflow.com/a/1119769/1144479 """ alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" base = len(alphabet) strlen = len(string) num = 0 idx = 0 for char in string: power = (strlen - (idx + 1)) try: num += alphabet.index(char) * (base ** power) except ValueError: raise Base62DecodeError( "Failed to decode char: '{}'".format(char)) idx += 1 return num
[ "def", "base62_decode", "(", "cls", ",", "string", ")", ":", "alphabet", "=", "\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"", "base", "=", "len", "(", "alphabet", ")", "strlen", "=", "len", "(", "string", ")", "num", "=", "0", "idx", "=", ...
Decode a Base X encoded string into the number. Arguments: - `string`: The encoded string - `alphabet`: The alphabet to use for encoding Stolen from: http://stackoverflow.com/a/1119769/1144479
[ "Decode", "a", "Base", "X", "encoded", "string", "into", "the", "number", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L852-L878
CivicSpleen/ambry
ambry/identity.py
ObjectNumber.increment
def increment(cls, v): """Increment the version number of an object number of object number string""" if not isinstance(v, ObjectNumber): v = ObjectNumber.parse(v) return v.rev(v.revision+1)
python
def increment(cls, v): """Increment the version number of an object number of object number string""" if not isinstance(v, ObjectNumber): v = ObjectNumber.parse(v) return v.rev(v.revision+1)
[ "def", "increment", "(", "cls", ",", "v", ")", ":", "if", "not", "isinstance", "(", "v", ",", "ObjectNumber", ")", ":", "v", "=", "ObjectNumber", ".", "parse", "(", "v", ")", "return", "v", ".", "rev", "(", "v", ".", "revision", "+", "1", ")" ]
Increment the version number of an object number of object number string
[ "Increment", "the", "version", "number", "of", "an", "object", "number", "of", "object", "number", "string" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L881-L886
CivicSpleen/ambry
ambry/identity.py
ObjectNumber.rev
def rev(self, i): """Return a clone with a different revision.""" on = copy(self) on.revision = i return on
python
def rev(self, i): """Return a clone with a different revision.""" on = copy(self) on.revision = i return on
[ "def", "rev", "(", "self", ",", "i", ")", ":", "on", "=", "copy", "(", "self", ")", "on", ".", "revision", "=", "i", "return", "on" ]
Return a clone with a different revision.
[ "Return", "a", "clone", "with", "a", "different", "revision", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L889-L893
CivicSpleen/ambry
ambry/identity.py
TopNumber.from_hex
def from_hex(cls, h, space, assignment_class='self'): """Produce a TopNumber, with a length to match the given assignment class, based on an input hex string. This can be used to create TopNumbers from a hash of a string. """ from math import log # Use the ln(N)/ln(base) trick to find the right number of hext digits # to use hex_digits = int( round(log(62 ** TopNumber.DLEN.DATASET_CLASSES[assignment_class]) / log(16), 0)) i = int(h[:hex_digits], 16) return TopNumber(space, i, assignment_class=assignment_class)
python
def from_hex(cls, h, space, assignment_class='self'): """Produce a TopNumber, with a length to match the given assignment class, based on an input hex string. This can be used to create TopNumbers from a hash of a string. """ from math import log # Use the ln(N)/ln(base) trick to find the right number of hext digits # to use hex_digits = int( round(log(62 ** TopNumber.DLEN.DATASET_CLASSES[assignment_class]) / log(16), 0)) i = int(h[:hex_digits], 16) return TopNumber(space, i, assignment_class=assignment_class)
[ "def", "from_hex", "(", "cls", ",", "h", ",", "space", ",", "assignment_class", "=", "'self'", ")", ":", "from", "math", "import", "log", "# Use the ln(N)/ln(base) trick to find the right number of hext digits", "# to use", "hex_digits", "=", "int", "(", "round", "...
Produce a TopNumber, with a length to match the given assignment class, based on an input hex string. This can be used to create TopNumbers from a hash of a string.
[ "Produce", "a", "TopNumber", "with", "a", "length", "to", "match", "the", "given", "assignment", "class", "based", "on", "an", "input", "hex", "string", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L941-L959
CivicSpleen/ambry
ambry/identity.py
TopNumber.from_string
def from_string(cls, s, space): """Produce a TopNumber by hashing a string.""" import hashlib hs = hashlib.sha1(s).hexdigest() return cls.from_hex(hs, space)
python
def from_string(cls, s, space): """Produce a TopNumber by hashing a string.""" import hashlib hs = hashlib.sha1(s).hexdigest() return cls.from_hex(hs, space)
[ "def", "from_string", "(", "cls", ",", "s", ",", "space", ")", ":", "import", "hashlib", "hs", "=", "hashlib", ".", "sha1", "(", "s", ")", ".", "hexdigest", "(", ")", "return", "cls", ".", "from_hex", "(", "hs", ",", "space", ")" ]
Produce a TopNumber by hashing a string.
[ "Produce", "a", "TopNumber", "by", "hashing", "a", "string", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L962-L969
CivicSpleen/ambry
ambry/identity.py
Identity.classify
def classify(cls, o): """Break an Identity name into parts, or describe the type of other forms. Break a name or object number into parts and classify them. Returns a named tuple that indicates which parts of input string are name components, object number and version number. Does not completely parse the name components. Also can handle Name, Identity and ObjectNumbers :param o: Input object to split """ # from collections import namedtuple s = str(o) if o is None: raise ValueError("Input cannot be None") class IdentityParts(object): on = None name = None isa = None name = None vname = None sname = None name_parts = None version = None cache_key = None # namedtuple('IdentityParts', ['isa', 'name', 'name_parts','on','version', 'vspec']) ip = IdentityParts() if isinstance(o, (DatasetNumber, PartitionNumber)): ip.on = o ip.name = None ip.isa = type(ip.on) ip.name_parts = None elif isinstance(o, Name): ip.on = None ip.isa = type(o) ip.name = str(o) ip.name_parts = ip.name.split(Name.NAME_PART_SEP) elif '/' in s: # A cache key ip.cache_key = s.strip() ip.isa = str elif cls.OBJECT_NUMBER_SEP in s: # Must be a fqname ip.name, on_s = s.strip().split(cls.OBJECT_NUMBER_SEP) ip.on = ObjectNumber.parse(on_s) ip.name_parts = ip.name.split(Name.NAME_PART_SEP) ip.isa = type(ip.on) elif Name.NAME_PART_SEP in s: # Must be an sname or vname ip.name = s ip.on = None ip.name_parts = ip.name.split(Name.NAME_PART_SEP) ip.isa = Name else: # Probably an Object Number in string form ip.name = None ip.name_parts = None ip.on = ObjectNumber.parse(s.strip()) ip.isa = type(ip.on) if ip.name_parts: last = ip.name_parts[-1] try: ip.version = sv.Version(last) ip.vname = ip.name except ValueError: try: ip.version = sv.Spec(last) ip.vname = None # Specs aren't vnames you can query except ValueError: pass if ip.version: ip.name_parts.pop() ip.sname = Name.NAME_PART_SEP.join(ip.name_parts) else: ip.sname = ip.name return ip
python
def classify(cls, o): """Break an Identity name into parts, or describe the type of other forms. Break a name or object number into parts and classify them. Returns a named tuple that indicates which parts of input string are name components, object number and version number. Does not completely parse the name components. Also can handle Name, Identity and ObjectNumbers :param o: Input object to split """ # from collections import namedtuple s = str(o) if o is None: raise ValueError("Input cannot be None") class IdentityParts(object): on = None name = None isa = None name = None vname = None sname = None name_parts = None version = None cache_key = None # namedtuple('IdentityParts', ['isa', 'name', 'name_parts','on','version', 'vspec']) ip = IdentityParts() if isinstance(o, (DatasetNumber, PartitionNumber)): ip.on = o ip.name = None ip.isa = type(ip.on) ip.name_parts = None elif isinstance(o, Name): ip.on = None ip.isa = type(o) ip.name = str(o) ip.name_parts = ip.name.split(Name.NAME_PART_SEP) elif '/' in s: # A cache key ip.cache_key = s.strip() ip.isa = str elif cls.OBJECT_NUMBER_SEP in s: # Must be a fqname ip.name, on_s = s.strip().split(cls.OBJECT_NUMBER_SEP) ip.on = ObjectNumber.parse(on_s) ip.name_parts = ip.name.split(Name.NAME_PART_SEP) ip.isa = type(ip.on) elif Name.NAME_PART_SEP in s: # Must be an sname or vname ip.name = s ip.on = None ip.name_parts = ip.name.split(Name.NAME_PART_SEP) ip.isa = Name else: # Probably an Object Number in string form ip.name = None ip.name_parts = None ip.on = ObjectNumber.parse(s.strip()) ip.isa = type(ip.on) if ip.name_parts: last = ip.name_parts[-1] try: ip.version = sv.Version(last) ip.vname = ip.name except ValueError: try: ip.version = sv.Spec(last) ip.vname = None # Specs aren't vnames you can query except ValueError: pass if ip.version: ip.name_parts.pop() ip.sname = Name.NAME_PART_SEP.join(ip.name_parts) else: ip.sname = ip.name return ip
[ "def", "classify", "(", "cls", ",", "o", ")", ":", "# from collections import namedtuple", "s", "=", "str", "(", "o", ")", "if", "o", "is", "None", ":", "raise", "ValueError", "(", "\"Input cannot be None\"", ")", "class", "IdentityParts", "(", "object", ")"...
Break an Identity name into parts, or describe the type of other forms. Break a name or object number into parts and classify them. Returns a named tuple that indicates which parts of input string are name components, object number and version number. Does not completely parse the name components. Also can handle Name, Identity and ObjectNumbers :param o: Input object to split
[ "Break", "an", "Identity", "name", "into", "parts", "or", "describe", "the", "type", "of", "other", "forms", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1332-L1423
CivicSpleen/ambry
ambry/identity.py
Identity.to_meta
def to_meta(self, md5=None, file=None): """Return a dictionary of metadata, for use in the Remote api.""" # from collections import OrderedDict if not md5: if not file: raise ValueError('Must specify either file or md5') md5 = md5_for_file(file) size = os.stat(file).st_size else: size = None return { 'id': self.id_, 'identity': json.dumps(self.dict), 'name': self.sname, 'fqname': self.fqname, 'md5': md5, # This causes errors with calculating the AWS signature 'size': size }
python
def to_meta(self, md5=None, file=None): """Return a dictionary of metadata, for use in the Remote api.""" # from collections import OrderedDict if not md5: if not file: raise ValueError('Must specify either file or md5') md5 = md5_for_file(file) size = os.stat(file).st_size else: size = None return { 'id': self.id_, 'identity': json.dumps(self.dict), 'name': self.sname, 'fqname': self.fqname, 'md5': md5, # This causes errors with calculating the AWS signature 'size': size }
[ "def", "to_meta", "(", "self", ",", "md5", "=", "None", ",", "file", "=", "None", ")", ":", "# from collections import OrderedDict", "if", "not", "md5", ":", "if", "not", "file", ":", "raise", "ValueError", "(", "'Must specify either file or md5'", ")", "md5",...
Return a dictionary of metadata, for use in the Remote api.
[ "Return", "a", "dictionary", "of", "metadata", "for", "use", "in", "the", "Remote", "api", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1425-L1446
CivicSpleen/ambry
ambry/identity.py
Identity.names_dict
def names_dict(self): """A dictionary with only the generated names, name, vname and fqname.""" INCLUDE_KEYS = ['name', 'vname', 'vid'] d = {k: v for k, v in iteritems(self.dict) if k in INCLUDE_KEYS} d['fqname'] = self.fqname return d
python
def names_dict(self): """A dictionary with only the generated names, name, vname and fqname.""" INCLUDE_KEYS = ['name', 'vname', 'vid'] d = {k: v for k, v in iteritems(self.dict) if k in INCLUDE_KEYS} d['fqname'] = self.fqname return d
[ "def", "names_dict", "(", "self", ")", ":", "INCLUDE_KEYS", "=", "[", "'name'", ",", "'vname'", ",", "'vid'", "]", "d", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "dict", ")", "if", "k", "in", "INCLUDE_KEY...
A dictionary with only the generated names, name, vname and fqname.
[ "A", "dictionary", "with", "only", "the", "generated", "names", "name", "vname", "and", "fqname", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1557-L1565
CivicSpleen/ambry
ambry/identity.py
Identity.ident_dict
def ident_dict(self): """A dictionary with only the items required to specify the identy, excluding the generated names, name, vname and fqname.""" SKIP_KEYS = ['name','vname','fqname','vid','cache_key'] return {k: v for k, v in iteritems(self.dict) if k not in SKIP_KEYS}
python
def ident_dict(self): """A dictionary with only the items required to specify the identy, excluding the generated names, name, vname and fqname.""" SKIP_KEYS = ['name','vname','fqname','vid','cache_key'] return {k: v for k, v in iteritems(self.dict) if k not in SKIP_KEYS}
[ "def", "ident_dict", "(", "self", ")", ":", "SKIP_KEYS", "=", "[", "'name'", ",", "'vname'", ",", "'fqname'", ",", "'vid'", ",", "'cache_key'", "]", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "dict", ")...
A dictionary with only the items required to specify the identy, excluding the generated names, name, vname and fqname.
[ "A", "dictionary", "with", "only", "the", "items", "required", "to", "specify", "the", "identy", "excluding", "the", "generated", "names", "name", "vname", "and", "fqname", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1568-L1573
CivicSpleen/ambry
ambry/identity.py
Identity.as_partition
def as_partition(self, partition=0, **kwargs): """Return a new PartitionIdentity based on this Identity. :param partition: Integer partition number for PartitionObjectNumber :param kwargs: """ assert isinstance(self._name, Name), "Wrong type: {}".format(type(self._name)) assert isinstance(self._on, DatasetNumber), "Wrong type: {}".format(type(self._on)) name = self._name.as_partition(**kwargs) on = self._on.as_partition(partition) return PartitionIdentity(name, on)
python
def as_partition(self, partition=0, **kwargs): """Return a new PartitionIdentity based on this Identity. :param partition: Integer partition number for PartitionObjectNumber :param kwargs: """ assert isinstance(self._name, Name), "Wrong type: {}".format(type(self._name)) assert isinstance(self._on, DatasetNumber), "Wrong type: {}".format(type(self._on)) name = self._name.as_partition(**kwargs) on = self._on.as_partition(partition) return PartitionIdentity(name, on)
[ "def", "as_partition", "(", "self", ",", "partition", "=", "0", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "self", ".", "_name", ",", "Name", ")", ",", "\"Wrong type: {}\"", ".", "format", "(", "type", "(", "self", ".", "_name", ...
Return a new PartitionIdentity based on this Identity. :param partition: Integer partition number for PartitionObjectNumber :param kwargs:
[ "Return", "a", "new", "PartitionIdentity", "based", "on", "this", "Identity", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1581-L1595
CivicSpleen/ambry
ambry/identity.py
Identity.add_partition
def add_partition(self, p): """Add a partition identity as a child of a dataset identity.""" if not self.partitions: self.partitions = {} self.partitions[p.vid] = p
python
def add_partition(self, p): """Add a partition identity as a child of a dataset identity.""" if not self.partitions: self.partitions = {} self.partitions[p.vid] = p
[ "def", "add_partition", "(", "self", ",", "p", ")", ":", "if", "not", "self", ".", "partitions", ":", "self", ".", "partitions", "=", "{", "}", "self", ".", "partitions", "[", "p", ".", "vid", "]", "=", "p" ]
Add a partition identity as a child of a dataset identity.
[ "Add", "a", "partition", "identity", "as", "a", "child", "of", "a", "dataset", "identity", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1597-L1603
CivicSpleen/ambry
ambry/identity.py
Identity.add_file
def add_file(self, f): """Add a partition identity as a child of a dataset identity.""" if not self.files: self.files = set() self.files.add(f) self.locations.set(f.type_)
python
def add_file(self, f): """Add a partition identity as a child of a dataset identity.""" if not self.files: self.files = set() self.files.add(f) self.locations.set(f.type_)
[ "def", "add_file", "(", "self", ",", "f", ")", ":", "if", "not", "self", ".", "files", ":", "self", ".", "files", "=", "set", "(", ")", "self", ".", "files", ".", "add", "(", "f", ")", "self", ".", "locations", ".", "set", "(", "f", ".", "typ...
Add a partition identity as a child of a dataset identity.
[ "Add", "a", "partition", "identity", "as", "a", "child", "of", "a", "dataset", "identity", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1605-L1613
CivicSpleen/ambry
ambry/identity.py
Identity.partition
def partition(self): """Convenience function for accessing the first partition in the partitions list, when there is only one.""" if not self.partitions: return None if len(self.partitions) > 1: raise ValueError( "Can't use this method when there is more than one partition") return list(self.partitions.values())[0]
python
def partition(self): """Convenience function for accessing the first partition in the partitions list, when there is only one.""" if not self.partitions: return None if len(self.partitions) > 1: raise ValueError( "Can't use this method when there is more than one partition") return list(self.partitions.values())[0]
[ "def", "partition", "(", "self", ")", ":", "if", "not", "self", ".", "partitions", ":", "return", "None", "if", "len", "(", "self", ".", "partitions", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Can't use this method when there is more than one partition\...
Convenience function for accessing the first partition in the partitions list, when there is only one.
[ "Convenience", "function", "for", "accessing", "the", "first", "partition", "in", "the", "partitions", "list", "when", "there", "is", "only", "one", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1616-L1627
CivicSpleen/ambry
ambry/identity.py
Identity.rev
def rev(self, rev): """Return a new identity with the given revision""" d = self.dict d['revision'] = rev return self.from_dict(d)
python
def rev(self, rev): """Return a new identity with the given revision""" d = self.dict d['revision'] = rev return self.from_dict(d)
[ "def", "rev", "(", "self", ",", "rev", ")", ":", "d", "=", "self", ".", "dict", "d", "[", "'revision'", "]", "=", "rev", "return", "self", ".", "from_dict", "(", "d", ")" ]
Return a new identity with the given revision
[ "Return", "a", "new", "identity", "with", "the", "given", "revision" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1629-L1633
CivicSpleen/ambry
ambry/identity.py
Identity._info
def _info(self): """Returns an OrderedDict of information, for human display.""" d = OrderedDict() d['vid'] = self.vid d['sname'] = self.sname d['vname'] = self.vname return d
python
def _info(self): """Returns an OrderedDict of information, for human display.""" d = OrderedDict() d['vid'] = self.vid d['sname'] = self.sname d['vname'] = self.vname return d
[ "def", "_info", "(", "self", ")", ":", "d", "=", "OrderedDict", "(", ")", "d", "[", "'vid'", "]", "=", "self", ".", "vid", "d", "[", "'sname'", "]", "=", "self", ".", "sname", "d", "[", "'vname'", "]", "=", "self", ".", "vname", "return", "d" ]
Returns an OrderedDict of information, for human display.
[ "Returns", "an", "OrderedDict", "of", "information", "for", "human", "display", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1638-L1646
CivicSpleen/ambry
ambry/identity.py
PartitionIdentity.from_dict
def from_dict(cls, d): """Like Identity.from_dict, but will cast the class type based on the format. i.e. if the format is hdf, return an HdfPartitionIdentity. :param d: :return: """ name = PartitionIdentity._name_class(**d) if 'id' in d and 'revision' in d: # The vid should be constructed from the id and the revision on = (ObjectNumber.parse(d['id']).rev(d['revision'])) elif 'vid' in d: on = ObjectNumber.parse(d['vid']) else: raise ValueError("Must have id and revision, or vid") try: return PartitionIdentity(name, on) except TypeError as e: raise TypeError( "Failed to make identity from \n{}\n: {}".format( d, e.message))
python
def from_dict(cls, d): """Like Identity.from_dict, but will cast the class type based on the format. i.e. if the format is hdf, return an HdfPartitionIdentity. :param d: :return: """ name = PartitionIdentity._name_class(**d) if 'id' in d and 'revision' in d: # The vid should be constructed from the id and the revision on = (ObjectNumber.parse(d['id']).rev(d['revision'])) elif 'vid' in d: on = ObjectNumber.parse(d['vid']) else: raise ValueError("Must have id and revision, or vid") try: return PartitionIdentity(name, on) except TypeError as e: raise TypeError( "Failed to make identity from \n{}\n: {}".format( d, e.message))
[ "def", "from_dict", "(", "cls", ",", "d", ")", ":", "name", "=", "PartitionIdentity", ".", "_name_class", "(", "*", "*", "d", ")", "if", "'id'", "in", "d", "and", "'revision'", "in", "d", ":", "# The vid should be constructed from the id and the revision", "on...
Like Identity.from_dict, but will cast the class type based on the format. i.e. if the format is hdf, return an HdfPartitionIdentity. :param d: :return:
[ "Like", "Identity", ".", "from_dict", "but", "will", "cast", "the", "class", "type", "based", "on", "the", "format", ".", "i", ".", "e", ".", "if", "the", "format", "is", "hdf", "return", "an", "HdfPartitionIdentity", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1669-L1694
CivicSpleen/ambry
ambry/identity.py
PartitionIdentity.as_dataset
def as_dataset(self): """Convert this identity to the identity of the corresponding dataset.""" on = self.on.dataset on.revision = self.on.revision name = Name(**self.name.dict) return Identity(name, on)
python
def as_dataset(self): """Convert this identity to the identity of the corresponding dataset.""" on = self.on.dataset on.revision = self.on.revision name = Name(**self.name.dict) return Identity(name, on)
[ "def", "as_dataset", "(", "self", ")", ":", "on", "=", "self", ".", "on", ".", "dataset", "on", ".", "revision", "=", "self", ".", "on", ".", "revision", "name", "=", "Name", "(", "*", "*", "self", ".", "name", ".", "dict", ")", "return", "Identi...
Convert this identity to the identity of the corresponding dataset.
[ "Convert", "this", "identity", "to", "the", "identity", "of", "the", "corresponding", "dataset", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1700-L1710
CivicSpleen/ambry
ambry/identity.py
NumberServer.sleep
def sleep(self): """Wait for the sleep time of the last response, to avoid being rate limited.""" if self.next_time and time.time() < self.next_time: time.sleep(self.next_time - time.time())
python
def sleep(self): """Wait for the sleep time of the last response, to avoid being rate limited.""" if self.next_time and time.time() < self.next_time: time.sleep(self.next_time - time.time())
[ "def", "sleep", "(", "self", ")", ":", "if", "self", ".", "next_time", "and", "time", ".", "time", "(", ")", "<", "self", ".", "next_time", ":", "time", ".", "sleep", "(", "self", ".", "next_time", "-", "time", ".", "time", "(", ")", ")" ]
Wait for the sleep time of the last response, to avoid being rate limited.
[ "Wait", "for", "the", "sleep", "time", "of", "the", "last", "response", "to", "avoid", "being", "rate", "limited", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1798-L1803
CivicSpleen/ambry
ambry/cli/root.py
root_sync
def root_sync(args, l, config): """Sync with the remote. For more options, use library sync """ from requests.exceptions import ConnectionError all_remote_names = [ r.short_name for r in l.remotes ] if args.all: remotes = all_remote_names else: remotes = args.refs prt("Sync with {} remotes or bundles ".format(len(remotes))) if not remotes: return for ref in remotes: l.commit() try: if ref in all_remote_names: # It's a remote name l.sync_remote(l.remote(ref)) else: # It's a bundle reference l.checkin_remote_bundle(ref) except NotFoundError as e: warn(e) continue except ConnectionError as e: warn(e) continue
python
def root_sync(args, l, config): """Sync with the remote. For more options, use library sync """ from requests.exceptions import ConnectionError all_remote_names = [ r.short_name for r in l.remotes ] if args.all: remotes = all_remote_names else: remotes = args.refs prt("Sync with {} remotes or bundles ".format(len(remotes))) if not remotes: return for ref in remotes: l.commit() try: if ref in all_remote_names: # It's a remote name l.sync_remote(l.remote(ref)) else: # It's a bundle reference l.checkin_remote_bundle(ref) except NotFoundError as e: warn(e) continue except ConnectionError as e: warn(e) continue
[ "def", "root_sync", "(", "args", ",", "l", ",", "config", ")", ":", "from", "requests", ".", "exceptions", "import", "ConnectionError", "all_remote_names", "=", "[", "r", ".", "short_name", "for", "r", "in", "l", ".", "remotes", "]", "if", "args", ".", ...
Sync with the remote. For more options, use library sync
[ "Sync", "with", "the", "remote", ".", "For", "more", "options", "use", "library", "sync" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/cli/root.py#L267-L300
CivicSpleen/ambry
ambry/bundle/bundle.py
_CaptureException
def _CaptureException(f, *args, **kwargs): """Decorator implementation for capturing exceptions.""" from ambry.dbexceptions import LoggedException b = args[0] # The 'self' argument try: return f(*args, **kwargs) except Exception as e: raise try: b.set_error_state() b.commit() except Exception as e2: b.log('Failed to set bundle error state: {}'.format(e)) raise e if b.capture_exceptions: b.logged_exception(e) raise LoggedException(e, b) else: b.exception(e) raise
python
def _CaptureException(f, *args, **kwargs): """Decorator implementation for capturing exceptions.""" from ambry.dbexceptions import LoggedException b = args[0] # The 'self' argument try: return f(*args, **kwargs) except Exception as e: raise try: b.set_error_state() b.commit() except Exception as e2: b.log('Failed to set bundle error state: {}'.format(e)) raise e if b.capture_exceptions: b.logged_exception(e) raise LoggedException(e, b) else: b.exception(e) raise
[ "def", "_CaptureException", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "ambry", ".", "dbexceptions", "import", "LoggedException", "b", "=", "args", "[", "0", "]", "# The 'self' argument", "try", ":", "return", "f", "(", "*", ...
Decorator implementation for capturing exceptions.
[ "Decorator", "implementation", "for", "capturing", "exceptions", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L31-L53
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.set_file_system
def set_file_system(self, source_url=False, build_url=False): """Set the source file filesystem and/or build file system""" assert isinstance(source_url, string_types) or source_url is None or source_url is False assert isinstance(build_url, string_types) or build_url is False if source_url: self._source_url = source_url self.dataset.config.library.source.url = self._source_url self._source_fs = None elif source_url is None: self._source_url = None self.dataset.config.library.source.url = self._source_url self._source_fs = None if build_url: self._build_url = build_url self.dataset.config.library.build.url = self._build_url self._build_fs = None self.dataset.commit()
python
def set_file_system(self, source_url=False, build_url=False): """Set the source file filesystem and/or build file system""" assert isinstance(source_url, string_types) or source_url is None or source_url is False assert isinstance(build_url, string_types) or build_url is False if source_url: self._source_url = source_url self.dataset.config.library.source.url = self._source_url self._source_fs = None elif source_url is None: self._source_url = None self.dataset.config.library.source.url = self._source_url self._source_fs = None if build_url: self._build_url = build_url self.dataset.config.library.build.url = self._build_url self._build_fs = None self.dataset.commit()
[ "def", "set_file_system", "(", "self", ",", "source_url", "=", "False", ",", "build_url", "=", "False", ")", ":", "assert", "isinstance", "(", "source_url", ",", "string_types", ")", "or", "source_url", "is", "None", "or", "source_url", "is", "False", "asser...
Set the source file filesystem and/or build file system
[ "Set", "the", "source", "file", "filesystem", "and", "/", "or", "build", "file", "system" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L151-L172
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.clear_file_systems
def clear_file_systems(self): """Remove references to build and source file systems, reverting to the defaults""" self._source_url = None self.dataset.config.library.source.url = None self._source_fs = None self._build_url = None self.dataset.config.library.build.url = None self._build_fs = None self.dataset.commit()
python
def clear_file_systems(self): """Remove references to build and source file systems, reverting to the defaults""" self._source_url = None self.dataset.config.library.source.url = None self._source_fs = None self._build_url = None self.dataset.config.library.build.url = None self._build_fs = None self.dataset.commit()
[ "def", "clear_file_systems", "(", "self", ")", ":", "self", ".", "_source_url", "=", "None", "self", ".", "dataset", ".", "config", ".", "library", ".", "source", ".", "url", "=", "None", "self", ".", "_source_fs", "=", "None", "self", ".", "_build_url",...
Remove references to build and source file systems, reverting to the defaults
[ "Remove", "references", "to", "build", "and", "source", "file", "systems", "reverting", "to", "the", "defaults" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L174-L185
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.cast_to_subclass
def cast_to_subclass(self): """ Load the bundle file from the database to get the derived bundle class, then return a new bundle built on that class :return: """ self.import_lib() self.load_requirements() try: self.commit() # To ensure the rollback() doesn't clear out anything important bsf = self.build_source_files.file(File.BSFILE.BUILD) except Exception as e: self.log('Error trying to create a bundle source file ... {} '.format(e)) raise self.rollback() return self try: clz = bsf.import_bundle() except Exception as e: raise BundleError('Failed to load bundle code file, skipping : {}'.format(e)) b = clz(self._dataset, self._library, self._source_url, self._build_url) b.limited_run = self.limited_run b.capture_exceptions = self.capture_exceptions b.multi = self.multi return b
python
def cast_to_subclass(self): """ Load the bundle file from the database to get the derived bundle class, then return a new bundle built on that class :return: """ self.import_lib() self.load_requirements() try: self.commit() # To ensure the rollback() doesn't clear out anything important bsf = self.build_source_files.file(File.BSFILE.BUILD) except Exception as e: self.log('Error trying to create a bundle source file ... {} '.format(e)) raise self.rollback() return self try: clz = bsf.import_bundle() except Exception as e: raise BundleError('Failed to load bundle code file, skipping : {}'.format(e)) b = clz(self._dataset, self._library, self._source_url, self._build_url) b.limited_run = self.limited_run b.capture_exceptions = self.capture_exceptions b.multi = self.multi return b
[ "def", "cast_to_subclass", "(", "self", ")", ":", "self", ".", "import_lib", "(", ")", "self", ".", "load_requirements", "(", ")", "try", ":", "self", ".", "commit", "(", ")", "# To ensure the rollback() doesn't clear out anything important", "bsf", "=", "self", ...
Load the bundle file from the database to get the derived bundle class, then return a new bundle built on that class :return:
[ "Load", "the", "bundle", "file", "from", "the", "database", "to", "get", "the", "derived", "bundle", "class", "then", "return", "a", "new", "bundle", "built", "on", "that", "class" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L187-L219
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.load_requirements
def load_requirements(self): """If there are python library requirements set, append the python dir to the path.""" for module_name, pip_name in iteritems(self.metadata.requirements): extant = self.dataset.config.requirements[module_name].url force = (extant and extant != pip_name) self._library.install_packages(module_name, pip_name, force=force) self.dataset.config.requirements[module_name].url = pip_name python_dir = self._library.filesystem.python() sys.path.append(python_dir)
python
def load_requirements(self): """If there are python library requirements set, append the python dir to the path.""" for module_name, pip_name in iteritems(self.metadata.requirements): extant = self.dataset.config.requirements[module_name].url force = (extant and extant != pip_name) self._library.install_packages(module_name, pip_name, force=force) self.dataset.config.requirements[module_name].url = pip_name python_dir = self._library.filesystem.python() sys.path.append(python_dir)
[ "def", "load_requirements", "(", "self", ")", ":", "for", "module_name", ",", "pip_name", "in", "iteritems", "(", "self", ".", "metadata", ".", "requirements", ")", ":", "extant", "=", "self", ".", "dataset", ".", "config", ".", "requirements", "[", "modul...
If there are python library requirements set, append the python dir to the path.
[ "If", "there", "are", "python", "library", "requirements", "set", "append", "the", "python", "dir", "to", "the", "path", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L225-L239
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.dep
def dep(self, source_name): """Return a bundle dependency from the sources list :param source_name: Source name. The URL field must be a bundle or partition reference :return: """ from ambry.orm.exc import NotFoundError from ambry.dbexceptions import ConfigurationError source = self.source(source_name) ref = source.url if not ref: raise ValueError("Got an empty ref for source '{}' ".format(source.name)) try: try: p = self.library.partition(ref) except NotFoundError: self.warn("Partition reference {} not found, try to download it".format(ref)) remote, vname = self.library.find_remote_bundle(ref, try_harder=True) if remote: self.warn("Installing {} from {}".format(remote, vname)) self.library.checkin_remote_bundle(vname, remote) p = self.library.partition(ref) else: raise if not p.is_local: with self.progress.start('test', 0, message='localizing') as ps: p.localize(ps) return p except NotFoundError: return self.library.bundle(ref)
python
def dep(self, source_name): """Return a bundle dependency from the sources list :param source_name: Source name. The URL field must be a bundle or partition reference :return: """ from ambry.orm.exc import NotFoundError from ambry.dbexceptions import ConfigurationError source = self.source(source_name) ref = source.url if not ref: raise ValueError("Got an empty ref for source '{}' ".format(source.name)) try: try: p = self.library.partition(ref) except NotFoundError: self.warn("Partition reference {} not found, try to download it".format(ref)) remote, vname = self.library.find_remote_bundle(ref, try_harder=True) if remote: self.warn("Installing {} from {}".format(remote, vname)) self.library.checkin_remote_bundle(vname, remote) p = self.library.partition(ref) else: raise if not p.is_local: with self.progress.start('test', 0, message='localizing') as ps: p.localize(ps) return p except NotFoundError: return self.library.bundle(ref)
[ "def", "dep", "(", "self", ",", "source_name", ")", ":", "from", "ambry", ".", "orm", ".", "exc", "import", "NotFoundError", "from", "ambry", ".", "dbexceptions", "import", "ConfigurationError", "source", "=", "self", ".", "source", "(", "source_name", ")", ...
Return a bundle dependency from the sources list :param source_name: Source name. The URL field must be a bundle or partition reference :return:
[ "Return", "a", "bundle", "dependency", "from", "the", "sources", "list" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L297-L335
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.documentation
def documentation(self): """Return the documentation, from the documentation.md file, with template substitutions""" # Return the documentation as a scalar term, which has .text() and .html methods to do # metadata substitution using Jinja s = '' rc = self.build_source_files.documentation.record_content if rc: s += rc for k, v in self.metadata.documentation.items(): if v: s += '\n### {}\n{}'.format(k.title(), v) return self.metadata.scalar_term(s)
python
def documentation(self): """Return the documentation, from the documentation.md file, with template substitutions""" # Return the documentation as a scalar term, which has .text() and .html methods to do # metadata substitution using Jinja s = '' rc = self.build_source_files.documentation.record_content if rc: s += rc for k, v in self.metadata.documentation.items(): if v: s += '\n### {}\n{}'.format(k.title(), v) return self.metadata.scalar_term(s)
[ "def", "documentation", "(", "self", ")", ":", "# Return the documentation as a scalar term, which has .text() and .html methods to do", "# metadata substitution using Jinja", "s", "=", "''", "rc", "=", "self", ".", "build_source_files", ".", "documentation", ".", "record_conte...
Return the documentation, from the documentation.md file, with template substitutions
[ "Return", "the", "documentation", "from", "the", "documentation", ".", "md", "file", "with", "template", "substitutions" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L355-L372
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.progress
def progress(self): """Returned a cached ProcessLogger to record build progress """ if not self._progress: # If won't be building, only use one connection new_connection = False if self._library.read_only else True self._progress = ProcessLogger(self.dataset, self.logger, new_connection=new_connection) return self._progress
python
def progress(self): """Returned a cached ProcessLogger to record build progress """ if not self._progress: # If won't be building, only use one connection new_connection = False if self._library.read_only else True self._progress = ProcessLogger(self.dataset, self.logger, new_connection=new_connection) return self._progress
[ "def", "progress", "(", "self", ")", ":", "if", "not", "self", ".", "_progress", ":", "# If won't be building, only use one connection", "new_connection", "=", "False", "if", "self", ".", "_library", ".", "read_only", "else", "True", "self", ".", "_progress", "=...
Returned a cached ProcessLogger to record build progress
[ "Returned", "a", "cached", "ProcessLogger", "to", "record", "build", "progress" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L375-L385
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.partition
def partition(self, ref=None, **kwargs): """Return a partition in this bundle for a vid reference or name parts""" from ambry.orm.exc import NotFoundError from sqlalchemy.orm.exc import NoResultFound if not ref and not kwargs: return None if ref: for p in self.partitions: if ref == p.name or ref == p.vname or ref == p.vid or ref == p.id: p._bundle = self return p raise NotFoundError("No partition found for '{}' (a)".format(ref)) elif kwargs: from ..identity import PartitionNameQuery pnq = PartitionNameQuery(**kwargs) try: p = self.partitions._find_orm(pnq).one() if p: p._bundle = self return p except NoResultFound: raise NotFoundError("No partition found for '{}' (b)".format(kwargs))
python
def partition(self, ref=None, **kwargs): """Return a partition in this bundle for a vid reference or name parts""" from ambry.orm.exc import NotFoundError from sqlalchemy.orm.exc import NoResultFound if not ref and not kwargs: return None if ref: for p in self.partitions: if ref == p.name or ref == p.vname or ref == p.vid or ref == p.id: p._bundle = self return p raise NotFoundError("No partition found for '{}' (a)".format(ref)) elif kwargs: from ..identity import PartitionNameQuery pnq = PartitionNameQuery(**kwargs) try: p = self.partitions._find_orm(pnq).one() if p: p._bundle = self return p except NoResultFound: raise NotFoundError("No partition found for '{}' (b)".format(kwargs))
[ "def", "partition", "(", "self", ",", "ref", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "ambry", ".", "orm", ".", "exc", "import", "NotFoundError", "from", "sqlalchemy", ".", "orm", ".", "exc", "import", "NoResultFound", "if", "not", "ref"...
Return a partition in this bundle for a vid reference or name parts
[ "Return", "a", "partition", "in", "this", "bundle", "for", "a", "vid", "reference", "or", "name", "parts" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L393-L418
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.partition_by_vid
def partition_by_vid(self, ref): """A much faster way to get partitions, by vid only""" from ambry.orm import Partition p = self.session.query(Partition).filter(Partition.vid == str(ref)).first() if p: return self.wrap_partition(p) else: return None
python
def partition_by_vid(self, ref): """A much faster way to get partitions, by vid only""" from ambry.orm import Partition p = self.session.query(Partition).filter(Partition.vid == str(ref)).first() if p: return self.wrap_partition(p) else: return None
[ "def", "partition_by_vid", "(", "self", ",", "ref", ")", ":", "from", "ambry", ".", "orm", "import", "Partition", "p", "=", "self", ".", "session", ".", "query", "(", "Partition", ")", ".", "filter", "(", "Partition", ".", "vid", "==", "str", "(", "r...
A much faster way to get partitions, by vid only
[ "A", "much", "faster", "way", "to", "get", "partitions", "by", "vid", "only" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L420-L428
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.tables
def tables(self): """ Return a iterator of tables in this bundle :return: """ from ambry.orm import Table from sqlalchemy.orm import lazyload return (self.dataset.session.query(Table) .filter(Table.d_vid == self.dataset.vid) .options(lazyload('*')) .all())
python
def tables(self): """ Return a iterator of tables in this bundle :return: """ from ambry.orm import Table from sqlalchemy.orm import lazyload return (self.dataset.session.query(Table) .filter(Table.d_vid == self.dataset.vid) .options(lazyload('*')) .all())
[ "def", "tables", "(", "self", ")", ":", "from", "ambry", ".", "orm", "import", "Table", "from", "sqlalchemy", ".", "orm", "import", "lazyload", "return", "(", "self", ".", "dataset", ".", "session", ".", "query", "(", "Table", ")", ".", "filter", "(", ...
Return a iterator of tables in this bundle :return:
[ "Return", "a", "iterator", "of", "tables", "in", "this", "bundle", ":", "return", ":" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L470-L480
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.new_table
def new_table(self, name, add_id=True, **kwargs): """ Create a new table, if it does not exist, or update an existing table if it does :param name: Table name :param add_id: If True, add an id field ( default is True ) :param kwargs: Other options passed to table object :return: """ return self.dataset.new_table(name=name, add_id=add_id, **kwargs)
python
def new_table(self, name, add_id=True, **kwargs): """ Create a new table, if it does not exist, or update an existing table if it does :param name: Table name :param add_id: If True, add an id field ( default is True ) :param kwargs: Other options passed to table object :return: """ return self.dataset.new_table(name=name, add_id=add_id, **kwargs)
[ "def", "new_table", "(", "self", ",", "name", ",", "add_id", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "dataset", ".", "new_table", "(", "name", "=", "name", ",", "add_id", "=", "add_id", ",", "*", "*", "kwargs", ")" ]
Create a new table, if it does not exist, or update an existing table if it does :param name: Table name :param add_id: If True, add an id field ( default is True ) :param kwargs: Other options passed to table object :return:
[ "Create", "a", "new", "table", "if", "it", "does", "not", "exist", "or", "update", "an", "existing", "table", "if", "it", "does", ":", "param", "name", ":", "Table", "name", ":", "param", "add_id", ":", "If", "True", "add", "an", "id", "field", "(", ...
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L482-L491
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.sources
def sources(self): """Iterate over downloadable sources""" def set_bundle(s): s._bundle = self return s return list(set_bundle(s) for s in self.dataset.sources)
python
def sources(self): """Iterate over downloadable sources""" def set_bundle(s): s._bundle = self return s return list(set_bundle(s) for s in self.dataset.sources)
[ "def", "sources", "(", "self", ")", ":", "def", "set_bundle", "(", "s", ")", ":", "s", ".", "_bundle", "=", "self", "return", "s", "return", "list", "(", "set_bundle", "(", "s", ")", "for", "s", "in", "self", ".", "dataset", ".", "sources", ")" ]
Iterate over downloadable sources
[ "Iterate", "over", "downloadable", "sources" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L499-L505
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle._resolve_sources
def _resolve_sources(self, sources, tables, stage=None, predicate=None): """ Determine what sources to run from an input of sources and tables :param sources: A collection of source objects, source names, or source vids :param tables: A collection of table names :param stage: If not None, select only sources from this stage :param predicate: If not none, a callable that selects a source to return when True :return: """ assert sources is None or tables is None if not sources: if tables: sources = list(s for s in self.sources if s.dest_table_name in tables) else: sources = self.sources elif not isinstance(sources, (list, tuple)): sources = [sources] def objectify(source): if isinstance(source, basestring): source_name = source return self.source(source_name) else: return source sources = [objectify(s) for s in sources] if predicate: sources = [s for s in sources if predicate(s)] if stage: sources = [s for s in sources if str(s.stage) == str(stage)] return sources
python
def _resolve_sources(self, sources, tables, stage=None, predicate=None): """ Determine what sources to run from an input of sources and tables :param sources: A collection of source objects, source names, or source vids :param tables: A collection of table names :param stage: If not None, select only sources from this stage :param predicate: If not none, a callable that selects a source to return when True :return: """ assert sources is None or tables is None if not sources: if tables: sources = list(s for s in self.sources if s.dest_table_name in tables) else: sources = self.sources elif not isinstance(sources, (list, tuple)): sources = [sources] def objectify(source): if isinstance(source, basestring): source_name = source return self.source(source_name) else: return source sources = [objectify(s) for s in sources] if predicate: sources = [s for s in sources if predicate(s)] if stage: sources = [s for s in sources if str(s.stage) == str(stage)] return sources
[ "def", "_resolve_sources", "(", "self", ",", "sources", ",", "tables", ",", "stage", "=", "None", ",", "predicate", "=", "None", ")", ":", "assert", "sources", "is", "None", "or", "tables", "is", "None", "if", "not", "sources", ":", "if", "tables", ":"...
Determine what sources to run from an input of sources and tables :param sources: A collection of source objects, source names, or source vids :param tables: A collection of table names :param stage: If not None, select only sources from this stage :param predicate: If not none, a callable that selects a source to return when True :return:
[ "Determine", "what", "sources", "to", "run", "from", "an", "input", "of", "sources", "and", "tables" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L507-L544
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.refs
def refs(self): """Iterate over downloadable sources -- references and templates""" def set_bundle(s): s._bundle = self return s return list(set_bundle(s) for s in self.dataset.sources if not s.is_downloadable)
python
def refs(self): """Iterate over downloadable sources -- references and templates""" def set_bundle(s): s._bundle = self return s return list(set_bundle(s) for s in self.dataset.sources if not s.is_downloadable)
[ "def", "refs", "(", "self", ")", ":", "def", "set_bundle", "(", "s", ")", ":", "s", ".", "_bundle", "=", "self", "return", "s", "return", "list", "(", "set_bundle", "(", "s", ")", "for", "s", "in", "self", ".", "dataset", ".", "sources", "if", "n...
Iterate over downloadable sources -- references and templates
[ "Iterate", "over", "downloadable", "sources", "--", "references", "and", "templates" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L547-L554
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.build_source_files
def build_source_files(self): """Return acessors to the build files""" from .files import BuildSourceFileAccessor return BuildSourceFileAccessor(self, self.dataset, self.source_fs)
python
def build_source_files(self): """Return acessors to the build files""" from .files import BuildSourceFileAccessor return BuildSourceFileAccessor(self, self.dataset, self.source_fs)
[ "def", "build_source_files", "(", "self", ")", ":", "from", ".", "files", "import", "BuildSourceFileAccessor", "return", "BuildSourceFileAccessor", "(", "self", ",", "self", ".", "dataset", ",", "self", ".", "source_fs", ")" ]
Return acessors to the build files
[ "Return", "acessors", "to", "the", "build", "files" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L568-L572
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.build_partition_fs
def build_partition_fs(self): """Return a pyfilesystem subdirectory for the build directory for the bundle. This the sub-directory of the build FS that holds the compiled SQLite file and the partition data files""" base_path = os.path.dirname(self.identity.cache_key) if not self.build_fs.exists(base_path): self.build_fs.makedir(base_path, recursive=True, allow_recreate=True) return self.build_fs.opendir(base_path)
python
def build_partition_fs(self): """Return a pyfilesystem subdirectory for the build directory for the bundle. This the sub-directory of the build FS that holds the compiled SQLite file and the partition data files""" base_path = os.path.dirname(self.identity.cache_key) if not self.build_fs.exists(base_path): self.build_fs.makedir(base_path, recursive=True, allow_recreate=True) return self.build_fs.opendir(base_path)
[ "def", "build_partition_fs", "(", "self", ")", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "identity", ".", "cache_key", ")", "if", "not", "self", ".", "build_fs", ".", "exists", "(", "base_path", ")", ":", "self", ".", ...
Return a pyfilesystem subdirectory for the build directory for the bundle. This the sub-directory of the build FS that holds the compiled SQLite file and the partition data files
[ "Return", "a", "pyfilesystem", "subdirectory", "for", "the", "build", "directory", "for", "the", "bundle", ".", "This", "the", "sub", "-", "directory", "of", "the", "build", "FS", "that", "holds", "the", "compiled", "SQLite", "file", "and", "the", "partition...
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L622-L631
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.build_ingest_fs
def build_ingest_fs(self): """Return a pyfilesystem subdirectory for the ingested source files""" base_path = 'ingest' if not self.build_fs.exists(base_path): self.build_fs.makedir(base_path, recursive=True, allow_recreate=True) return self.build_fs.opendir(base_path)
python
def build_ingest_fs(self): """Return a pyfilesystem subdirectory for the ingested source files""" base_path = 'ingest' if not self.build_fs.exists(base_path): self.build_fs.makedir(base_path, recursive=True, allow_recreate=True) return self.build_fs.opendir(base_path)
[ "def", "build_ingest_fs", "(", "self", ")", ":", "base_path", "=", "'ingest'", "if", "not", "self", ".", "build_fs", ".", "exists", "(", "base_path", ")", ":", "self", ".", "build_fs", ".", "makedir", "(", "base_path", ",", "recursive", "=", "True", ",",...
Return a pyfilesystem subdirectory for the ingested source files
[ "Return", "a", "pyfilesystem", "subdirectory", "for", "the", "ingested", "source", "files" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L634-L642
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.phase_search_names
def phase_search_names(self, source, phase): """Search the bundle.yaml metadata file for pipeline configurations. Looks for: - <phase>-<source_table> - <phase>-<dest_table> - <phase>-<source_name> """ search = [] assert phase is not None # Create a search list of names for getting a pipline from the metadata if source and source.source_table_name: search.append(phase + '-' + source.source_table_name) if source and source.dest_table_name: search.append(phase + '-' + source.dest_table_name) if source: search.append(phase + '-' + source.name) search.append(phase) return search
python
def phase_search_names(self, source, phase): """Search the bundle.yaml metadata file for pipeline configurations. Looks for: - <phase>-<source_table> - <phase>-<dest_table> - <phase>-<source_name> """ search = [] assert phase is not None # Create a search list of names for getting a pipline from the metadata if source and source.source_table_name: search.append(phase + '-' + source.source_table_name) if source and source.dest_table_name: search.append(phase + '-' + source.dest_table_name) if source: search.append(phase + '-' + source.name) search.append(phase) return search
[ "def", "phase_search_names", "(", "self", ",", "source", ",", "phase", ")", ":", "search", "=", "[", "]", "assert", "phase", "is", "not", "None", "# Create a search list of names for getting a pipline from the metadata", "if", "source", "and", "source", ".", "source...
Search the bundle.yaml metadata file for pipeline configurations. Looks for: - <phase>-<source_table> - <phase>-<dest_table> - <phase>-<source_name>
[ "Search", "the", "bundle", ".", "yaml", "metadata", "file", "for", "pipeline", "configurations", ".", "Looks", "for", ":", "-", "<phase", ">", "-", "<source_table", ">", "-", "<phase", ">", "-", "<dest_table", ">", "-", "<phase", ">", "-", "<source_name", ...
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L644-L667
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.logger
def logger(self): """The bundle logger.""" if not self._logger: ident = self.identity if self.multi: template = '%(levelname)s %(process)d {} %(message)s'.format(ident.vid) else: template = '%(levelname)s {} %(message)s'.format(ident.vid) try: file_name = self.build_fs.getsyspath(self.log_file) self._logger = get_logger(__name__, template=template, stream=sys.stdout, file_name=file_name) except NoSysPathError: # file does not exists in the os - memory fs for example. self._logger = get_logger(__name__, template=template, stream=sys.stdout) self._logger.setLevel(self._log_level) return self._logger
python
def logger(self): """The bundle logger.""" if not self._logger: ident = self.identity if self.multi: template = '%(levelname)s %(process)d {} %(message)s'.format(ident.vid) else: template = '%(levelname)s {} %(message)s'.format(ident.vid) try: file_name = self.build_fs.getsyspath(self.log_file) self._logger = get_logger(__name__, template=template, stream=sys.stdout, file_name=file_name) except NoSysPathError: # file does not exists in the os - memory fs for example. self._logger = get_logger(__name__, template=template, stream=sys.stdout) self._logger.setLevel(self._log_level) return self._logger
[ "def", "logger", "(", "self", ")", ":", "if", "not", "self", ".", "_logger", ":", "ident", "=", "self", ".", "identity", "if", "self", ".", "multi", ":", "template", "=", "'%(levelname)s %(process)d {} %(message)s'", ".", "format", "(", "ident", ".", "vid"...
The bundle logger.
[ "The", "bundle", "logger", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L690-L711
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.log_to_file
def log_to_file(self, message): """Write a log message only to the file""" with self.build_fs.open(self.log_file, 'a+') as f: f.write(unicode(message + '\n'))
python
def log_to_file(self, message): """Write a log message only to the file""" with self.build_fs.open(self.log_file, 'a+') as f: f.write(unicode(message + '\n'))
[ "def", "log_to_file", "(", "self", ",", "message", ")", ":", "with", "self", ".", "build_fs", ".", "open", "(", "self", ".", "log_file", ",", "'a+'", ")", "as", "f", ":", "f", ".", "write", "(", "unicode", "(", "message", "+", "'\\n'", ")", ")" ]
Write a log message only to the file
[ "Write", "a", "log", "message", "only", "to", "the", "file" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L713-L717
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.error
def error(self, message, set_error_state=False): """Log an error messsage. :param message: Log message. """ if set_error_state: if message not in self._errors: self._errors.append(message) self.set_error_state() self.logger.error(message)
python
def error(self, message, set_error_state=False): """Log an error messsage. :param message: Log message. """ if set_error_state: if message not in self._errors: self._errors.append(message) self.set_error_state() self.logger.error(message)
[ "def", "error", "(", "self", ",", "message", ",", "set_error_state", "=", "False", ")", ":", "if", "set_error_state", ":", "if", "message", "not", "in", "self", ".", "_errors", ":", "self", ".", "_errors", ".", "append", "(", "message", ")", "self", "....
Log an error messsage. :param message: Log message.
[ "Log", "an", "error", "messsage", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L727-L739
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.exception
def exception(self, e): """Log an error messsage. :param e: Exception to log. """ self.logged_exception(e) self.logger.exception(e)
python
def exception(self, e): """Log an error messsage. :param e: Exception to log. """ self.logged_exception(e) self.logger.exception(e)
[ "def", "exception", "(", "self", ",", "e", ")", ":", "self", ".", "logged_exception", "(", "e", ")", "self", ".", "logger", ".", "exception", "(", "e", ")" ]
Log an error messsage. :param e: Exception to log.
[ "Log", "an", "error", "messsage", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L741-L748
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.logged_exception
def logged_exception(self, e): """Record the exception, but don't log it; it's already been logged :param e: Exception to log. """ if str(e) not in self._errors: self._errors.append(str(e)) self.set_error_state() self.buildstate.state.exception_type = str(e.__class__.__name__) self.buildstate.state.exception = str(e)
python
def logged_exception(self, e): """Record the exception, but don't log it; it's already been logged :param e: Exception to log. """ if str(e) not in self._errors: self._errors.append(str(e)) self.set_error_state() self.buildstate.state.exception_type = str(e.__class__.__name__) self.buildstate.state.exception = str(e)
[ "def", "logged_exception", "(", "self", ",", "e", ")", ":", "if", "str", "(", "e", ")", "not", "in", "self", ".", "_errors", ":", "self", ".", "_errors", ".", "append", "(", "str", "(", "e", ")", ")", "self", ".", "set_error_state", "(", ")", "se...
Record the exception, but don't log it; it's already been logged :param e: Exception to log.
[ "Record", "the", "exception", "but", "don", "t", "log", "it", ";", "it", "s", "already", "been", "logged" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L750-L761
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.warn
def warn(self, message): """Log an error messsage. :param message: Log message. """ if message not in self._warnings: self._warnings.append(message) self.logger.warn(message)
python
def warn(self, message): """Log an error messsage. :param message: Log message. """ if message not in self._warnings: self._warnings.append(message) self.logger.warn(message)
[ "def", "warn", "(", "self", ",", "message", ")", ":", "if", "message", "not", "in", "self", ".", "_warnings", ":", "self", ".", "_warnings", ".", "append", "(", "message", ")", "self", ".", "logger", ".", "warn", "(", "message", ")" ]
Log an error messsage. :param message: Log message.
[ "Log", "an", "error", "messsage", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L763-L772
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.fatal
def fatal(self, message): """Log a fatal messsage and exit. :param message: Log message. """ self.logger.fatal(message) sys.stderr.flush() if self.exit_on_fatal: sys.exit(1) else: raise FatalError(message)
python
def fatal(self, message): """Log a fatal messsage and exit. :param message: Log message. """ self.logger.fatal(message) sys.stderr.flush() if self.exit_on_fatal: sys.exit(1) else: raise FatalError(message)
[ "def", "fatal", "(", "self", ",", "message", ")", ":", "self", ".", "logger", ".", "fatal", "(", "message", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "if", "self", ".", "exit_on_fatal", ":", "sys", ".", "exit", "(", "1", ")", "else", ":"...
Log a fatal messsage and exit. :param message: Log message.
[ "Log", "a", "fatal", "messsage", "and", "exit", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L774-L786
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.log_pipeline
def log_pipeline(self, pl): """Write a report of the pipeline out to a file """ from datetime import datetime from ambry.etl.pipeline import CastColumns self.build_fs.makedir('pipeline', allow_recreate=True) try: ccp = pl[CastColumns] caster_code = ccp.pretty_code except Exception as e: caster_code = str(e) templ = u(""" Pipeline : {} run time : {} phase : {} source name : {} source table : {} dest table : {} ======================================================== {} Pipeline Headers ================ {} Caster Code =========== {} """) try: v = templ.format(pl.name, str(datetime.now()), pl.phase, pl.source_name, pl.source_table, pl.dest_table, unicode(pl), pl.headers_report(), caster_code) except UnicodeError as e: v = '' self.error('Faled to write pipeline log for pipeline {} '.format(pl.name)) path = os.path.join('pipeline', pl.phase + '-' + pl.file_name + '.txt') self.build_fs.makedir(os.path.dirname(path), allow_recreate=True, recursive=True) # LazyFS should handled differently because of: # TypeError: lazy_fs.setcontents(..., encoding='utf-8') got an unexpected keyword argument 'encoding' if isinstance(self.build_fs, LazyFS): self.build_fs.wrapped_fs.setcontents(path, v, encoding='utf8') else: self.build_fs.setcontents(path, v, encoding='utf8')
python
def log_pipeline(self, pl): """Write a report of the pipeline out to a file """ from datetime import datetime from ambry.etl.pipeline import CastColumns self.build_fs.makedir('pipeline', allow_recreate=True) try: ccp = pl[CastColumns] caster_code = ccp.pretty_code except Exception as e: caster_code = str(e) templ = u(""" Pipeline : {} run time : {} phase : {} source name : {} source table : {} dest table : {} ======================================================== {} Pipeline Headers ================ {} Caster Code =========== {} """) try: v = templ.format(pl.name, str(datetime.now()), pl.phase, pl.source_name, pl.source_table, pl.dest_table, unicode(pl), pl.headers_report(), caster_code) except UnicodeError as e: v = '' self.error('Faled to write pipeline log for pipeline {} '.format(pl.name)) path = os.path.join('pipeline', pl.phase + '-' + pl.file_name + '.txt') self.build_fs.makedir(os.path.dirname(path), allow_recreate=True, recursive=True) # LazyFS should handled differently because of: # TypeError: lazy_fs.setcontents(..., encoding='utf-8') got an unexpected keyword argument 'encoding' if isinstance(self.build_fs, LazyFS): self.build_fs.wrapped_fs.setcontents(path, v, encoding='utf8') else: self.build_fs.setcontents(path, v, encoding='utf8')
[ "def", "log_pipeline", "(", "self", ",", "pl", ")", ":", "from", "datetime", "import", "datetime", "from", "ambry", ".", "etl", ".", "pipeline", "import", "CastColumns", "self", ".", "build_fs", ".", "makedir", "(", "'pipeline'", ",", "allow_recreate", "=", ...
Write a report of the pipeline out to a file
[ "Write", "a", "report", "of", "the", "pipeline", "out", "to", "a", "file" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L801-L848
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.pipeline
def pipeline(self, source=None, phase='build', ps=None): """ Construct the ETL pipeline for all phases. Segments that are not used for the current phase are filtered out later. :param source: A source object, or a source string name :return: an etl Pipeline """ from ambry.etl.pipeline import Pipeline, PartitionWriter from ambry.dbexceptions import ConfigurationError if source: source = self.source(source) if isinstance(source, string_types) else source else: source = None sf, sp = self.source_pipe(source, ps) if source else (None, None) pl = Pipeline(self, source=sp) # Get the default pipeline, from the config at the head of this file. try: phase_config = self.default_pipelines[phase] except KeyError: phase_config = None # Ok for non-conventional pipe names if phase_config: pl.configure(phase_config) # Find the pipe configuration, from the metadata pipe_config = None pipe_name = None if source and source.pipeline: pipe_name = source.pipeline try: pipe_config = self.metadata.pipelines[pipe_name] except KeyError: raise ConfigurationError("Pipeline '{}' declared in source '{}', but not found in metadata" .format(source.pipeline, source.name)) else: pipe_name, pipe_config = self._find_pipeline(source, phase) if pipe_name: pl.name = pipe_name else: pl.name = phase pl.phase = phase # The pipe_config can either be a list, in which case it is a list of pipe pipes for the # augment segment or it could be a dict, in which case each is a list of pipes # for the named segments. def apply_config(pl, pipe_config): if isinstance(pipe_config, (list, tuple)): # Just convert it to dict form for the next section # PartitionWriters are always moved to the 'store' section store, body = [], [] for pipe in pipe_config: store.append(pipe) if isinstance(pipe, PartitionWriter) else body.append(pipe) pipe_config = dict(body=body, store=store) if pipe_config: pl.configure(pipe_config) apply_config(pl, pipe_config) # One more time, for the configuration for 'all' phases if 'all' in self.metadata.pipelines: apply_config(pl, self.metadata.pipelines['all']) # Allows developer to over ride pipe configuration in code self.edit_pipeline(pl) try: pl.dest_table = source.dest_table_name pl.source_table = source.source_table.name pl.source_name = source.name except AttributeError: pl.dest_table = None return pl
python
def pipeline(self, source=None, phase='build', ps=None): """ Construct the ETL pipeline for all phases. Segments that are not used for the current phase are filtered out later. :param source: A source object, or a source string name :return: an etl Pipeline """ from ambry.etl.pipeline import Pipeline, PartitionWriter from ambry.dbexceptions import ConfigurationError if source: source = self.source(source) if isinstance(source, string_types) else source else: source = None sf, sp = self.source_pipe(source, ps) if source else (None, None) pl = Pipeline(self, source=sp) # Get the default pipeline, from the config at the head of this file. try: phase_config = self.default_pipelines[phase] except KeyError: phase_config = None # Ok for non-conventional pipe names if phase_config: pl.configure(phase_config) # Find the pipe configuration, from the metadata pipe_config = None pipe_name = None if source and source.pipeline: pipe_name = source.pipeline try: pipe_config = self.metadata.pipelines[pipe_name] except KeyError: raise ConfigurationError("Pipeline '{}' declared in source '{}', but not found in metadata" .format(source.pipeline, source.name)) else: pipe_name, pipe_config = self._find_pipeline(source, phase) if pipe_name: pl.name = pipe_name else: pl.name = phase pl.phase = phase # The pipe_config can either be a list, in which case it is a list of pipe pipes for the # augment segment or it could be a dict, in which case each is a list of pipes # for the named segments. def apply_config(pl, pipe_config): if isinstance(pipe_config, (list, tuple)): # Just convert it to dict form for the next section # PartitionWriters are always moved to the 'store' section store, body = [], [] for pipe in pipe_config: store.append(pipe) if isinstance(pipe, PartitionWriter) else body.append(pipe) pipe_config = dict(body=body, store=store) if pipe_config: pl.configure(pipe_config) apply_config(pl, pipe_config) # One more time, for the configuration for 'all' phases if 'all' in self.metadata.pipelines: apply_config(pl, self.metadata.pipelines['all']) # Allows developer to over ride pipe configuration in code self.edit_pipeline(pl) try: pl.dest_table = source.dest_table_name pl.source_table = source.source_table.name pl.source_name = source.name except AttributeError: pl.dest_table = None return pl
[ "def", "pipeline", "(", "self", ",", "source", "=", "None", ",", "phase", "=", "'build'", ",", "ps", "=", "None", ")", ":", "from", "ambry", ".", "etl", ".", "pipeline", "import", "Pipeline", ",", "PartitionWriter", "from", "ambry", ".", "dbexceptions", ...
Construct the ETL pipeline for all phases. Segments that are not used for the current phase are filtered out later. :param source: A source object, or a source string name :return: an etl Pipeline
[ "Construct", "the", "ETL", "pipeline", "for", "all", "phases", ".", "Segments", "that", "are", "not", "used", "for", "the", "current", "phase", "are", "filtered", "out", "later", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L858-L946
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.field_row
def field_row(self, fields): """ Return a list of values to match the fields values. This is used when listing bundles to produce a table of information about the bundle. :param fields: A list of names of data items. :return: A list of values, in the same order as the fields input The names in the fields llist can be: - state: The current build state - source_fs: The URL of the build source filesystem - about.*: Any of the metadata fields in the about section """ row = self.dataset.row(fields) # Modify for special fields for i, f in enumerate(fields): if f == 'bstate': row[i] = self.state elif f == 'dstate': row[i] = self.dstate elif f == 'source_fs': row[i] = self.source_fs elif f.startswith('about'): # all metadata in the about section, ie: about.title _, key = f.split('.') row[i] = self.metadata.about[key] elif f.startswith('state'): _, key = f.split('.') row[i] = self.buildstate.state[key] elif f.startswith('count'): _, key = f.split('.') if key == 'sources': row[i] = len(self.dataset.sources) elif key == 'tables': row[i] = len(self.dataset.tables) return row
python
def field_row(self, fields): """ Return a list of values to match the fields values. This is used when listing bundles to produce a table of information about the bundle. :param fields: A list of names of data items. :return: A list of values, in the same order as the fields input The names in the fields llist can be: - state: The current build state - source_fs: The URL of the build source filesystem - about.*: Any of the metadata fields in the about section """ row = self.dataset.row(fields) # Modify for special fields for i, f in enumerate(fields): if f == 'bstate': row[i] = self.state elif f == 'dstate': row[i] = self.dstate elif f == 'source_fs': row[i] = self.source_fs elif f.startswith('about'): # all metadata in the about section, ie: about.title _, key = f.split('.') row[i] = self.metadata.about[key] elif f.startswith('state'): _, key = f.split('.') row[i] = self.buildstate.state[key] elif f.startswith('count'): _, key = f.split('.') if key == 'sources': row[i] = len(self.dataset.sources) elif key == 'tables': row[i] = len(self.dataset.tables) return row
[ "def", "field_row", "(", "self", ",", "fields", ")", ":", "row", "=", "self", ".", "dataset", ".", "row", "(", "fields", ")", "# Modify for special fields", "for", "i", ",", "f", "in", "enumerate", "(", "fields", ")", ":", "if", "f", "==", "'bstate'", ...
Return a list of values to match the fields values. This is used when listing bundles to produce a table of information about the bundle. :param fields: A list of names of data items. :return: A list of values, in the same order as the fields input The names in the fields llist can be: - state: The current build state - source_fs: The URL of the build source filesystem - about.*: Any of the metadata fields in the about section
[ "Return", "a", "list", "of", "values", "to", "match", "the", "fields", "values", ".", "This", "is", "used", "when", "listing", "bundles", "to", "produce", "a", "table", "of", "information", "about", "the", "bundle", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L962-L1001
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.source_pipe
def source_pipe(self, source, ps=None): """Create a source pipe for a source, giving it access to download files to the local cache""" if isinstance(source, string_types): source = self.source(source) source.dataset = self.dataset source._bundle = self iter_source, source_pipe = self._iterable_source(source, ps) if self.limited_run: source_pipe.limit = 500 return iter_source, source_pipe
python
def source_pipe(self, source, ps=None): """Create a source pipe for a source, giving it access to download files to the local cache""" if isinstance(source, string_types): source = self.source(source) source.dataset = self.dataset source._bundle = self iter_source, source_pipe = self._iterable_source(source, ps) if self.limited_run: source_pipe.limit = 500 return iter_source, source_pipe
[ "def", "source_pipe", "(", "self", ",", "source", ",", "ps", "=", "None", ")", ":", "if", "isinstance", "(", "source", ",", "string_types", ")", ":", "source", "=", "self", ".", "source", "(", "source", ")", "source", ".", "dataset", "=", "self", "."...
Create a source pipe for a source, giving it access to download files to the local cache
[ "Create", "a", "source", "pipe", "for", "a", "source", "giving", "it", "access", "to", "download", "files", "to", "the", "local", "cache" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1003-L1017
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.get_source
def get_source(self, source, clean=False, callback=None): """ Download a file from a URL and return it wrapped in a row-generating acessor object. :param spec: A SourceSpec that describes the source to fetch. :param account_accessor: A callable to return the username and password to use for access FTP and S3 URLs. :param clean: Delete files in cache and re-download. :param callback: A callback, called while reading files in download. signatire is f(read_len, total_len) :return: a SourceFile object. """ from fs.zipfs import ZipOpenError import os from ambry_sources.sources import ( GoogleSource, CsvSource, TsvSource, FixedSource, ExcelSource, PartitionSource, SourceError, DelayedOpen, DelayedDownload, ShapefileSource, SocrataSource ) from ambry_sources import extract_file_from_zip spec = source.spec cache_fs = self.library.download_cache account_accessor = self.library.account_accessor # FIXME. urltype should be moved to reftype. url_type = spec.get_urltype() def do_download(): from ambry_sources.fetch import download return download(spec.url, cache_fs, account_accessor, clean=clean, logger=self.logger, callback=callback) if url_type == 'file': from fs.opener import fsopen syspath = spec.url.replace('file://', '') cache_path = syspath.strip('/') cache_fs.makedir(os.path.dirname(cache_path), recursive=True, allow_recreate=True) if os.path.isabs(syspath): # FIXME! Probably should not be with open(syspath) as f: cache_fs.setcontents(cache_path, f) else: cache_fs.setcontents(cache_path, self.source_fs.getcontents(syspath)) elif url_type not in ('gs', 'socrata'): # FIXME. Need to clean up the logic for gs types. try: cache_path, download_time = do_download() spec.download_time = download_time except Exception as e: from ambry_sources.exceptions import DownloadError raise DownloadError("Failed to download {}; {}".format(spec.url, e)) else: cache_path, download_time = None, None if url_type == 'zip': try: fstor = extract_file_from_zip(cache_fs, cache_path, spec.url, spec.file) except ZipOpenError: # Try it again cache_fs.remove(cache_path) cache_path, spec.download_time = do_download() fstor = extract_file_from_zip(cache_fs, cache_path, spec.url, spec.file) file_type = spec.get_filetype(fstor.path) elif url_type == 'gs': fstor = get_gs(spec.url, spec.segment, account_accessor) file_type = 'gs' elif url_type == 'socrata': spec.encoding = 'utf8' spec.header_lines = [0] spec.start_line = 1 url = SocrataSource.download_url(spec) fstor = DelayedDownload(url, cache_fs) file_type = 'socrata' else: fstor = DelayedOpen(cache_fs, cache_path, 'rb') file_type = spec.get_filetype(fstor.path) spec.filetype = file_type TYPE_TO_SOURCE_MAP = { 'gs': GoogleSource, 'csv': CsvSource, 'tsv': TsvSource, 'fixed': FixedSource, 'txt': FixedSource, 'xls': ExcelSource, 'xlsx': ExcelSource, 'partition': PartitionSource, 'shape': ShapefileSource, 'socrata': SocrataSource } cls = TYPE_TO_SOURCE_MAP.get(file_type) if cls is None: raise SourceError( "Failed to determine file type for source '{}'; unknown type '{}' " .format(spec.name, file_type)) return cls(spec, fstor)
python
def get_source(self, source, clean=False, callback=None): """ Download a file from a URL and return it wrapped in a row-generating acessor object. :param spec: A SourceSpec that describes the source to fetch. :param account_accessor: A callable to return the username and password to use for access FTP and S3 URLs. :param clean: Delete files in cache and re-download. :param callback: A callback, called while reading files in download. signatire is f(read_len, total_len) :return: a SourceFile object. """ from fs.zipfs import ZipOpenError import os from ambry_sources.sources import ( GoogleSource, CsvSource, TsvSource, FixedSource, ExcelSource, PartitionSource, SourceError, DelayedOpen, DelayedDownload, ShapefileSource, SocrataSource ) from ambry_sources import extract_file_from_zip spec = source.spec cache_fs = self.library.download_cache account_accessor = self.library.account_accessor # FIXME. urltype should be moved to reftype. url_type = spec.get_urltype() def do_download(): from ambry_sources.fetch import download return download(spec.url, cache_fs, account_accessor, clean=clean, logger=self.logger, callback=callback) if url_type == 'file': from fs.opener import fsopen syspath = spec.url.replace('file://', '') cache_path = syspath.strip('/') cache_fs.makedir(os.path.dirname(cache_path), recursive=True, allow_recreate=True) if os.path.isabs(syspath): # FIXME! Probably should not be with open(syspath) as f: cache_fs.setcontents(cache_path, f) else: cache_fs.setcontents(cache_path, self.source_fs.getcontents(syspath)) elif url_type not in ('gs', 'socrata'): # FIXME. Need to clean up the logic for gs types. try: cache_path, download_time = do_download() spec.download_time = download_time except Exception as e: from ambry_sources.exceptions import DownloadError raise DownloadError("Failed to download {}; {}".format(spec.url, e)) else: cache_path, download_time = None, None if url_type == 'zip': try: fstor = extract_file_from_zip(cache_fs, cache_path, spec.url, spec.file) except ZipOpenError: # Try it again cache_fs.remove(cache_path) cache_path, spec.download_time = do_download() fstor = extract_file_from_zip(cache_fs, cache_path, spec.url, spec.file) file_type = spec.get_filetype(fstor.path) elif url_type == 'gs': fstor = get_gs(spec.url, spec.segment, account_accessor) file_type = 'gs' elif url_type == 'socrata': spec.encoding = 'utf8' spec.header_lines = [0] spec.start_line = 1 url = SocrataSource.download_url(spec) fstor = DelayedDownload(url, cache_fs) file_type = 'socrata' else: fstor = DelayedOpen(cache_fs, cache_path, 'rb') file_type = spec.get_filetype(fstor.path) spec.filetype = file_type TYPE_TO_SOURCE_MAP = { 'gs': GoogleSource, 'csv': CsvSource, 'tsv': TsvSource, 'fixed': FixedSource, 'txt': FixedSource, 'xls': ExcelSource, 'xlsx': ExcelSource, 'partition': PartitionSource, 'shape': ShapefileSource, 'socrata': SocrataSource } cls = TYPE_TO_SOURCE_MAP.get(file_type) if cls is None: raise SourceError( "Failed to determine file type for source '{}'; unknown type '{}' " .format(spec.name, file_type)) return cls(spec, fstor)
[ "def", "get_source", "(", "self", ",", "source", ",", "clean", "=", "False", ",", "callback", "=", "None", ")", ":", "from", "fs", ".", "zipfs", "import", "ZipOpenError", "import", "os", "from", "ambry_sources", ".", "sources", "import", "(", "GoogleSource...
Download a file from a URL and return it wrapped in a row-generating acessor object. :param spec: A SourceSpec that describes the source to fetch. :param account_accessor: A callable to return the username and password to use for access FTP and S3 URLs. :param clean: Delete files in cache and re-download. :param callback: A callback, called while reading files in download. signatire is f(read_len, total_len) :return: a SourceFile object.
[ "Download", "a", "file", "from", "a", "URL", "and", "return", "it", "wrapped", "in", "a", "row", "-", "generating", "acessor", "object", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1163-L1273
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.error_state
def error_state(self): """Set the error condition""" self.buildstate.state.lasttime = time() self.buildstate.commit() return self.buildstate.state.error
python
def error_state(self): """Set the error condition""" self.buildstate.state.lasttime = time() self.buildstate.commit() return self.buildstate.state.error
[ "def", "error_state", "(", "self", ")", ":", "self", ".", "buildstate", ".", "state", ".", "lasttime", "=", "time", "(", ")", "self", ".", "buildstate", ".", "commit", "(", ")", "return", "self", ".", "buildstate", ".", "state", ".", "error" ]
Set the error condition
[ "Set", "the", "error", "condition" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1286-L1290
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.state
def state(self, state): """Set the current build state and record the time to maintain history. Note! This is different from the dataset state. Setting the build set is commiteed to the progress table/database immediately. The dstate is also set, but is not committed until the bundle is committed. So, the dstate changes more slowly. """ assert state != 'build_bundle' self.buildstate.state.current = state self.buildstate.state[state] = time() self.buildstate.state.lasttime = time() self.buildstate.state.error = False self.buildstate.state.exception = None self.buildstate.state.exception_type = None self.buildstate.commit() if state in (self.STATES.NEW, self.STATES.CLEANED, self.STATES.BUILT, self.STATES.FINALIZED, self.STATES.SOURCE): state = state if state != self.STATES.CLEANED else self.STATES.NEW self.dstate = state
python
def state(self, state): """Set the current build state and record the time to maintain history. Note! This is different from the dataset state. Setting the build set is commiteed to the progress table/database immediately. The dstate is also set, but is not committed until the bundle is committed. So, the dstate changes more slowly. """ assert state != 'build_bundle' self.buildstate.state.current = state self.buildstate.state[state] = time() self.buildstate.state.lasttime = time() self.buildstate.state.error = False self.buildstate.state.exception = None self.buildstate.state.exception_type = None self.buildstate.commit() if state in (self.STATES.NEW, self.STATES.CLEANED, self.STATES.BUILT, self.STATES.FINALIZED, self.STATES.SOURCE): state = state if state != self.STATES.CLEANED else self.STATES.NEW self.dstate = state
[ "def", "state", "(", "self", ",", "state", ")", ":", "assert", "state", "!=", "'build_bundle'", "self", ".", "buildstate", ".", "state", ".", "current", "=", "state", "self", ".", "buildstate", ".", "state", "[", "state", "]", "=", "time", "(", ")", ...
Set the current build state and record the time to maintain history. Note! This is different from the dataset state. Setting the build set is commiteed to the progress table/database immediately. The dstate is also set, but is not committed until the bundle is committed. So, the dstate changes more slowly.
[ "Set", "the", "current", "build", "state", "and", "record", "the", "time", "to", "maintain", "history", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1307-L1329
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.record_stage_state
def record_stage_state(self, phase, stage): """Record the completion times of phases and stages""" key = '{}-{}'.format(phase, stage if stage else 1) self.buildstate.state[key] = time()
python
def record_stage_state(self, phase, stage): """Record the completion times of phases and stages""" key = '{}-{}'.format(phase, stage if stage else 1) self.buildstate.state[key] = time()
[ "def", "record_stage_state", "(", "self", ",", "phase", ",", "stage", ")", ":", "key", "=", "'{}-{}'", ".", "format", "(", "phase", ",", "stage", "if", "stage", "else", "1", ")", "self", ".", "buildstate", ".", "state", "[", "key", "]", "=", "time", ...
Record the completion times of phases and stages
[ "Record", "the", "completion", "times", "of", "phases", "and", "stages" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1347-L1352
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.set_last_access
def set_last_access(self, tag): """Mark the time that this bundle was last accessed""" import time # time defeats check that value didn't change self.buildstate.access.last = '{}-{}'.format(tag, time.time()) self.buildstate.commit()
python
def set_last_access(self, tag): """Mark the time that this bundle was last accessed""" import time # time defeats check that value didn't change self.buildstate.access.last = '{}-{}'.format(tag, time.time()) self.buildstate.commit()
[ "def", "set_last_access", "(", "self", ",", "tag", ")", ":", "import", "time", "# time defeats check that value didn't change", "self", ".", "buildstate", ".", "access", ".", "last", "=", "'{}-{}'", ".", "format", "(", "tag", ",", "time", ".", "time", "(", "...
Mark the time that this bundle was last accessed
[ "Mark", "the", "time", "that", "this", "bundle", "was", "last", "accessed" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1358-L1364
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.sync_in
def sync_in(self, force=False): """Synchronize from files to records, and records to objects""" self.log('---- Sync In ----') self.dstate = self.STATES.BUILDING for path_name in self.source_fs.listdir(): f = self.build_source_files.instance_from_name(path_name) if not f: self.warn('Ignoring unknown file: {}'.format(path_name)) continue if f and f.exists and (f.fs_is_newer or force): self.log('Sync: {}'.format(f.record.path)) f.fs_to_record() f.record_to_objects() self.commit() self.library.search.index_bundle(self, force=True)
python
def sync_in(self, force=False): """Synchronize from files to records, and records to objects""" self.log('---- Sync In ----') self.dstate = self.STATES.BUILDING for path_name in self.source_fs.listdir(): f = self.build_source_files.instance_from_name(path_name) if not f: self.warn('Ignoring unknown file: {}'.format(path_name)) continue if f and f.exists and (f.fs_is_newer or force): self.log('Sync: {}'.format(f.record.path)) f.fs_to_record() f.record_to_objects() self.commit() self.library.search.index_bundle(self, force=True)
[ "def", "sync_in", "(", "self", ",", "force", "=", "False", ")", ":", "self", ".", "log", "(", "'---- Sync In ----'", ")", "self", ".", "dstate", "=", "self", ".", "STATES", ".", "BUILDING", "for", "path_name", "in", "self", ".", "source_fs", ".", "list...
Synchronize from files to records, and records to objects
[ "Synchronize", "from", "files", "to", "records", "and", "records", "to", "objects" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1419-L1440
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.sync_in_files
def sync_in_files(self, force=False): """Synchronize from files to records""" self.log('---- Sync Files ----') self.dstate = self.STATES.BUILDING for f in self.build_source_files: if self.source_fs.exists(f.record.path): # print f.path, f.fs_modtime, f.record.modified, f.record.source_hash, f.fs_hash if f.fs_is_newer or force: self.log('Sync: {}'.format(f.record.path)) f.fs_to_record() self.commit()
python
def sync_in_files(self, force=False): """Synchronize from files to records""" self.log('---- Sync Files ----') self.dstate = self.STATES.BUILDING for f in self.build_source_files: if self.source_fs.exists(f.record.path): # print f.path, f.fs_modtime, f.record.modified, f.record.source_hash, f.fs_hash if f.fs_is_newer or force: self.log('Sync: {}'.format(f.record.path)) f.fs_to_record() self.commit()
[ "def", "sync_in_files", "(", "self", ",", "force", "=", "False", ")", ":", "self", ".", "log", "(", "'---- Sync Files ----'", ")", "self", ".", "dstate", "=", "self", ".", "STATES", ".", "BUILDING", "for", "f", "in", "self", ".", "build_source_files", ":...
Synchronize from files to records
[ "Synchronize", "from", "files", "to", "records" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1443-L1457
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.sync_in_records
def sync_in_records(self, force=False): """Synchronize from files to records""" self.log('---- Sync Files ----') for f in self.build_source_files: f.record_to_objects() # Only the metadata needs to be driven to the objects, since the other files are used as code, # directly from the file record. self.build_source_files.file(File.BSFILE.META).record_to_objects() self.commit()
python
def sync_in_records(self, force=False): """Synchronize from files to records""" self.log('---- Sync Files ----') for f in self.build_source_files: f.record_to_objects() # Only the metadata needs to be driven to the objects, since the other files are used as code, # directly from the file record. self.build_source_files.file(File.BSFILE.META).record_to_objects() self.commit()
[ "def", "sync_in_records", "(", "self", ",", "force", "=", "False", ")", ":", "self", ".", "log", "(", "'---- Sync Files ----'", ")", "for", "f", "in", "self", ".", "build_source_files", ":", "f", ".", "record_to_objects", "(", ")", "# Only the metadata needs t...
Synchronize from files to records
[ "Synchronize", "from", "files", "to", "records" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1459-L1470
CivicSpleen/ambry
ambry/bundle/bundle.py
Bundle.sync_out
def sync_out(self, file_name=None, force=False): """Synchronize from objects to records""" self.log('---- Sync Out ----') from ambry.bundle.files import BuildSourceFile self.dstate = self.STATES.BUILDING for f in self.build_source_files.list_records(): if (f.sync_dir() == BuildSourceFile.SYNC_DIR.RECORD_TO_FILE or f.record.path == file_name) or force: self.log('Sync: {}'.format(f.record.path)) f.record_to_fs() self.commit()
python
def sync_out(self, file_name=None, force=False): """Synchronize from objects to records""" self.log('---- Sync Out ----') from ambry.bundle.files import BuildSourceFile self.dstate = self.STATES.BUILDING for f in self.build_source_files.list_records(): if (f.sync_dir() == BuildSourceFile.SYNC_DIR.RECORD_TO_FILE or f.record.path == file_name) or force: self.log('Sync: {}'.format(f.record.path)) f.record_to_fs() self.commit()
[ "def", "sync_out", "(", "self", ",", "file_name", "=", "None", ",", "force", "=", "False", ")", ":", "self", ".", "log", "(", "'---- Sync Out ----'", ")", "from", "ambry", ".", "bundle", ".", "files", "import", "BuildSourceFile", "self", ".", "dstate", "...
Synchronize from objects to records
[ "Synchronize", "from", "objects", "to", "records" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1472-L1485