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
CivicSpleen/ambry
ambry/library/search_backends/postgres_backend.py
IdentifierPostgreSQLIndex._index_document
def _index_document(self, identifier, force=False): """ Adds identifier document to the index. """ query = text(""" INSERT INTO identifier_index(identifier, type, name) VALUES(:identifier, :type, :name); """) self.execute(query, **identifier)
python
def _index_document(self, identifier, force=False): """ Adds identifier document to the index. """ query = text(""" INSERT INTO identifier_index(identifier, type, name) VALUES(:identifier, :type, :name); """) self.execute(query, **identifier)
[ "def", "_index_document", "(", "self", ",", "identifier", ",", "force", "=", "False", ")", ":", "query", "=", "text", "(", "\"\"\"\n INSERT INTO identifier_index(identifier, type, name)\n VALUES(:identifier, :type, :name);\n \"\"\"", ")", "self", "....
Adds identifier document to the index.
[ "Adds", "identifier", "document", "to", "the", "index", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/postgres_backend.py#L586-L593
CivicSpleen/ambry
ambry/library/search_backends/postgres_backend.py
IdentifierPostgreSQLIndex._delete
def _delete(self, identifier=None): """ Deletes given identifier from index. Args: identifier (str): identifier of the document to delete. """ query = text(""" DELETE FROM identifier_index WHERE identifier = :identifier; """) self.execute(query, identifier=identifier)
python
def _delete(self, identifier=None): """ Deletes given identifier from index. Args: identifier (str): identifier of the document to delete. """ query = text(""" DELETE FROM identifier_index WHERE identifier = :identifier; """) self.execute(query, identifier=identifier)
[ "def", "_delete", "(", "self", ",", "identifier", "=", "None", ")", ":", "query", "=", "text", "(", "\"\"\"\n DELETE FROM identifier_index\n WHERE identifier = :identifier;\n \"\"\"", ")", "self", ".", "execute", "(", "query", ",", "identifier...
Deletes given identifier from index. Args: identifier (str): identifier of the document to delete.
[ "Deletes", "given", "identifier", "from", "index", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/postgres_backend.py#L623-L634
CivicSpleen/ambry
ambry/library/search_backends/postgres_backend.py
IdentifierPostgreSQLIndex.is_indexed
def is_indexed(self, identifier): """ Returns True if identifier is already indexed. Otherwise returns False. """ query = text(""" SELECT identifier FROM identifier_index WHERE identifier = :identifier; """) result = self.execute(query, identifier=identifier['identifier']) return bool(result.fetchall())
python
def is_indexed(self, identifier): """ Returns True if identifier is already indexed. Otherwise returns False. """ query = text(""" SELECT identifier FROM identifier_index WHERE identifier = :identifier; """) result = self.execute(query, identifier=identifier['identifier']) return bool(result.fetchall())
[ "def", "is_indexed", "(", "self", ",", "identifier", ")", ":", "query", "=", "text", "(", "\"\"\"\n SELECT identifier\n FROM identifier_index\n WHERE identifier = :identifier;\n \"\"\"", ")", "result", "=", "self", ".", "execute", "(", ...
Returns True if identifier is already indexed. Otherwise returns False.
[ "Returns", "True", "if", "identifier", "is", "already", "indexed", ".", "Otherwise", "returns", "False", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/postgres_backend.py#L636-L644
CivicSpleen/ambry
ambry/library/search_backends/postgres_backend.py
IdentifierPostgreSQLIndex.all
def all(self): """ Returns list with all indexed identifiers. """ identifiers = [] query = text(""" SELECT identifier, type, name FROM identifier_index;""") for result in self.execute(query): vid, type_, name = result res = IdentifierSearchResult( score=1, vid=vid, type=type_, name=name) identifiers.append(res) return identifiers
python
def all(self): """ Returns list with all indexed identifiers. """ identifiers = [] query = text(""" SELECT identifier, type, name FROM identifier_index;""") for result in self.execute(query): vid, type_, name = result res = IdentifierSearchResult( score=1, vid=vid, type=type_, name=name) identifiers.append(res) return identifiers
[ "def", "all", "(", "self", ")", ":", "identifiers", "=", "[", "]", "query", "=", "text", "(", "\"\"\"\n SELECT identifier, type, name\n FROM identifier_index;\"\"\"", ")", "for", "result", "in", "self", ".", "execute", "(", "query", ")", ":", ...
Returns list with all indexed identifiers.
[ "Returns", "list", "with", "all", "indexed", "identifiers", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/postgres_backend.py#L646-L659
SmartTeleMax/iktomi
iktomi/utils/text.py
pare
def pare(text, size, etc='...'): '''Pare text to have maximum size and add etc to the end if it's changed''' size = int(size) text = text.strip() if len(text)>size: # strip the last word or not to_be_stripped = not whitespace_re.findall(text[size-1:size+2]) text = text[:size] if to_be_stripped: half = size//2 last = None for mo in whitespace_re.finditer(text[half:]): last = mo if last is not None: text = text[:half+last.start()+1] return text.rstrip() + etc else: return text
python
def pare(text, size, etc='...'): '''Pare text to have maximum size and add etc to the end if it's changed''' size = int(size) text = text.strip() if len(text)>size: # strip the last word or not to_be_stripped = not whitespace_re.findall(text[size-1:size+2]) text = text[:size] if to_be_stripped: half = size//2 last = None for mo in whitespace_re.finditer(text[half:]): last = mo if last is not None: text = text[:half+last.start()+1] return text.rstrip() + etc else: return text
[ "def", "pare", "(", "text", ",", "size", ",", "etc", "=", "'...'", ")", ":", "size", "=", "int", "(", "size", ")", "text", "=", "text", ".", "strip", "(", ")", "if", "len", "(", "text", ")", ">", "size", ":", "# strip the last word or not", "to_be_...
Pare text to have maximum size and add etc to the end if it's changed
[ "Pare", "text", "to", "have", "maximum", "size", "and", "add", "etc", "to", "the", "end", "if", "it", "s", "changed" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/utils/text.py#L6-L27
project-ncl/pnc-cli
pnc_cli/environments.py
get_environment
def get_environment(id=None, name=None): """ Get a specific Environment by name or ID """ data = get_environment_raw(id, name) if data: return utils.format_json(data)
python
def get_environment(id=None, name=None): """ Get a specific Environment by name or ID """ data = get_environment_raw(id, name) if data: return utils.format_json(data)
[ "def", "get_environment", "(", "id", "=", "None", ",", "name", "=", "None", ")", ":", "data", "=", "get_environment_raw", "(", "id", ",", "name", ")", "if", "data", ":", "return", "utils", ".", "format_json", "(", "data", ")" ]
Get a specific Environment by name or ID
[ "Get", "a", "specific", "Environment", "by", "name", "or", "ID" ]
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/environments.py#L18-L24
project-ncl/pnc-cli
pnc_cli/environments.py
list_environments_raw
def list_environments_raw(page_size=200, page_index=0, sort="", q=""): """ List all Environments """ response = utils.checked_api_call(pnc_api.environments, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q) if response: return response.content
python
def list_environments_raw(page_size=200, page_index=0, sort="", q=""): """ List all Environments """ response = utils.checked_api_call(pnc_api.environments, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q) if response: return response.content
[ "def", "list_environments_raw", "(", "page_size", "=", "200", ",", "page_index", "=", "0", ",", "sort", "=", "\"\"", ",", "q", "=", "\"\"", ")", ":", "response", "=", "utils", ".", "checked_api_call", "(", "pnc_api", ".", "environments", ",", "'get_all'", ...
List all Environments
[ "List", "all", "Environments" ]
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/environments.py#L43-L49
CivicSpleen/ambry
ambry/orm/table.py
Table.dimensions
def dimensions(self): """Iterate over the dimension columns, regardless of parent/child status """ from ambry.valuetype.core import ROLE for c in self.columns: if c.role == ROLE.DIMENSION: yield c
python
def dimensions(self): """Iterate over the dimension columns, regardless of parent/child status """ from ambry.valuetype.core import ROLE for c in self.columns: if c.role == ROLE.DIMENSION: yield c
[ "def", "dimensions", "(", "self", ")", ":", "from", "ambry", ".", "valuetype", ".", "core", "import", "ROLE", "for", "c", "in", "self", ".", "columns", ":", "if", "c", ".", "role", "==", "ROLE", ".", "DIMENSION", ":", "yield", "c" ]
Iterate over the dimension columns, regardless of parent/child status
[ "Iterate", "over", "the", "dimension", "columns", "regardless", "of", "parent", "/", "child", "status" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L82-L91
CivicSpleen/ambry
ambry/orm/table.py
Table.primary_dimensions
def primary_dimensions(self): """Iterate over the primary dimension columns, columns which do not have a parent """ from ambry.valuetype.core import ROLE for c in self.columns: if not c.parent and c.role == ROLE.DIMENSION: yield c
python
def primary_dimensions(self): """Iterate over the primary dimension columns, columns which do not have a parent """ from ambry.valuetype.core import ROLE for c in self.columns: if not c.parent and c.role == ROLE.DIMENSION: yield c
[ "def", "primary_dimensions", "(", "self", ")", ":", "from", "ambry", ".", "valuetype", ".", "core", "import", "ROLE", "for", "c", "in", "self", ".", "columns", ":", "if", "not", "c", ".", "parent", "and", "c", ".", "role", "==", "ROLE", ".", "DIMENSI...
Iterate over the primary dimension columns, columns which do not have a parent
[ "Iterate", "over", "the", "primary", "dimension", "columns", "columns", "which", "do", "not", "have", "a", "parent" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L94-L103
CivicSpleen/ambry
ambry/orm/table.py
Table.primary_measures
def primary_measures(self): """Iterate over the primary columns, columns which do not have a parent Also sets the property partition_stats to the stats collection for the partition and column. """ from ambry.valuetype.core import ROLE for c in self.columns: if not c.parent and c.role == ROLE.MEASURE: yield c
python
def primary_measures(self): """Iterate over the primary columns, columns which do not have a parent Also sets the property partition_stats to the stats collection for the partition and column. """ from ambry.valuetype.core import ROLE for c in self.columns: if not c.parent and c.role == ROLE.MEASURE: yield c
[ "def", "primary_measures", "(", "self", ")", ":", "from", "ambry", ".", "valuetype", ".", "core", "import", "ROLE", "for", "c", "in", "self", ".", "columns", ":", "if", "not", "c", ".", "parent", "and", "c", ".", "role", "==", "ROLE", ".", "MEASURE",...
Iterate over the primary columns, columns which do not have a parent Also sets the property partition_stats to the stats collection for the partition and column.
[ "Iterate", "over", "the", "primary", "columns", "columns", "which", "do", "not", "have", "a", "parent" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L106-L116
CivicSpleen/ambry
ambry/orm/table.py
Table.add_column
def add_column(self, name, update_existing=False, **kwargs): """ Add a column to the table, or update an existing one. :param name: Name of the new or existing column. :param update_existing: If True, alter existing column values. Defaults to False :param kwargs: Other arguments for the the Column() constructor :return: a Column object """ from ..identity import ColumnNumber try: c = self.column(name) extant = True if not update_existing: return c except NotFoundError: sequence_id = len(self.columns) + 1 assert sequence_id c = Column(t_vid=self.vid, sequence_id=sequence_id, vid=str(ColumnNumber(ObjectNumber.parse(self.vid), sequence_id)), name=name, datatype='str') extant = False # Update possibly existing data c.data = dict((list(c.data.items()) if c.data else []) + list(kwargs.get('data', {}).items())) for key, value in list(kwargs.items()): if key[0] != '_' and key not in ['t_vid', 'name', 'sequence_id', 'data']: # Don't update the type if the user has specfied a custom type if key == 'datatype' and not c.type_is_builtin(): continue # Don't change a datatype if the value is set and the new value is unknown if key == 'datatype' and value == 'unknown' and c.datatype: continue # Don't change a datatype if the value is set and the new value is unknown if key == 'description' and not value: continue try: setattr(c, key, value) except AttributeError: raise AttributeError("Column record has no attribute {}".format(key)) if key == 'is_primary_key' and isinstance(value, str) and len(value) == 0: value = False setattr(c, key, value) # If the id column has a description and the table does not, add it to # the table. if c.name == 'id' and c.is_primary_key and not self.description: self.description = c.description if not extant: self.columns.append(c) return c
python
def add_column(self, name, update_existing=False, **kwargs): """ Add a column to the table, or update an existing one. :param name: Name of the new or existing column. :param update_existing: If True, alter existing column values. Defaults to False :param kwargs: Other arguments for the the Column() constructor :return: a Column object """ from ..identity import ColumnNumber try: c = self.column(name) extant = True if not update_existing: return c except NotFoundError: sequence_id = len(self.columns) + 1 assert sequence_id c = Column(t_vid=self.vid, sequence_id=sequence_id, vid=str(ColumnNumber(ObjectNumber.parse(self.vid), sequence_id)), name=name, datatype='str') extant = False # Update possibly existing data c.data = dict((list(c.data.items()) if c.data else []) + list(kwargs.get('data', {}).items())) for key, value in list(kwargs.items()): if key[0] != '_' and key not in ['t_vid', 'name', 'sequence_id', 'data']: # Don't update the type if the user has specfied a custom type if key == 'datatype' and not c.type_is_builtin(): continue # Don't change a datatype if the value is set and the new value is unknown if key == 'datatype' and value == 'unknown' and c.datatype: continue # Don't change a datatype if the value is set and the new value is unknown if key == 'description' and not value: continue try: setattr(c, key, value) except AttributeError: raise AttributeError("Column record has no attribute {}".format(key)) if key == 'is_primary_key' and isinstance(value, str) and len(value) == 0: value = False setattr(c, key, value) # If the id column has a description and the table does not, add it to # the table. if c.name == 'id' and c.is_primary_key and not self.description: self.description = c.description if not extant: self.columns.append(c) return c
[ "def", "add_column", "(", "self", ",", "name", ",", "update_existing", "=", "False", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", "identity", "import", "ColumnNumber", "try", ":", "c", "=", "self", ".", "column", "(", "name", ")", "extant", "...
Add a column to the table, or update an existing one. :param name: Name of the new or existing column. :param update_existing: If True, alter existing column values. Defaults to False :param kwargs: Other arguments for the the Column() constructor :return: a Column object
[ "Add", "a", "column", "to", "the", "table", "or", "update", "an", "existing", "one", ".", ":", "param", "name", ":", "Name", "of", "the", "new", "or", "existing", "column", ".", ":", "param", "update_existing", ":", "If", "True", "alter", "existing", "...
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L133-L199
CivicSpleen/ambry
ambry/orm/table.py
Table.is_empty
def is_empty(self): """Return True if the table has no columns or the only column is the id""" if len(self.columns) == 0: return True if len(self.columns) == 1 and self.columns[0].name == 'id': return True return False
python
def is_empty(self): """Return True if the table has no columns or the only column is the id""" if len(self.columns) == 0: return True if len(self.columns) == 1 and self.columns[0].name == 'id': return True return False
[ "def", "is_empty", "(", "self", ")", ":", "if", "len", "(", "self", ".", "columns", ")", "==", "0", ":", "return", "True", "if", "len", "(", "self", ".", "columns", ")", "==", "1", "and", "self", ".", "columns", "[", "0", "]", ".", "name", "=="...
Return True if the table has no columns or the only column is the id
[ "Return", "True", "if", "the", "table", "has", "no", "columns", "or", "the", "only", "column", "is", "the", "id" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L206-L214
CivicSpleen/ambry
ambry/orm/table.py
Table.update_from_stats
def update_from_stats(self, stats): """Update columns based on partition statistics""" sd = dict(stats) for c in self.columns: if c not in sd: continue stat = sd[c] if stat.size and stat.size > c.size: c.size = stat.size c.lom = stat.lom
python
def update_from_stats(self, stats): """Update columns based on partition statistics""" sd = dict(stats) for c in self.columns: if c not in sd: continue stat = sd[c] if stat.size and stat.size > c.size: c.size = stat.size c.lom = stat.lom
[ "def", "update_from_stats", "(", "self", ",", "stats", ")", ":", "sd", "=", "dict", "(", "stats", ")", "for", "c", "in", "self", ".", "columns", ":", "if", "c", "not", "in", "sd", ":", "continue", "stat", "=", "sd", "[", "c", "]", "if", "stat", ...
Update columns based on partition statistics
[ "Update", "columns", "based", "on", "partition", "statistics" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L251-L266
CivicSpleen/ambry
ambry/orm/table.py
Table.update_id
def update_id(self, sequence_id=None, force=True): """Alter the sequence id, and all of the names and ids derived from it. This often needs to be don after an IntegrityError in a multiprocessing run""" from ..identity import ObjectNumber if sequence_id: self.sequence_id = sequence_id assert self.d_vid if self.id is None or force: dataset_id = ObjectNumber.parse(self.d_vid).rev(None) self.d_id = str(dataset_id) self.id = str(TableNumber(dataset_id, self.sequence_id)) if self.vid is None or force: dataset_vid = ObjectNumber.parse(self.d_vid) self.vid = str(TableNumber(dataset_vid, self.sequence_id))
python
def update_id(self, sequence_id=None, force=True): """Alter the sequence id, and all of the names and ids derived from it. This often needs to be don after an IntegrityError in a multiprocessing run""" from ..identity import ObjectNumber if sequence_id: self.sequence_id = sequence_id assert self.d_vid if self.id is None or force: dataset_id = ObjectNumber.parse(self.d_vid).rev(None) self.d_id = str(dataset_id) self.id = str(TableNumber(dataset_id, self.sequence_id)) if self.vid is None or force: dataset_vid = ObjectNumber.parse(self.d_vid) self.vid = str(TableNumber(dataset_vid, self.sequence_id))
[ "def", "update_id", "(", "self", ",", "sequence_id", "=", "None", ",", "force", "=", "True", ")", ":", "from", ".", ".", "identity", "import", "ObjectNumber", "if", "sequence_id", ":", "self", ".", "sequence_id", "=", "sequence_id", "assert", "self", ".", ...
Alter the sequence id, and all of the names and ids derived from it. This often needs to be don after an IntegrityError in a multiprocessing run
[ "Alter", "the", "sequence", "id", "and", "all", "of", "the", "names", "and", "ids", "derived", "from", "it", ".", "This", "often", "needs", "to", "be", "don", "after", "an", "IntegrityError", "in", "a", "multiprocessing", "run" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L268-L285
CivicSpleen/ambry
ambry/orm/table.py
Table.transforms
def transforms(self): """Return an array of arrays of column transforms. #The return value is an list of list, with each list being a segment of column transformations, and #each segment having one entry per column. """ tr = [] for c in self.columns: tr.append(c.expanded_transform) return six.moves.zip_longest(*tr)
python
def transforms(self): """Return an array of arrays of column transforms. #The return value is an list of list, with each list being a segment of column transformations, and #each segment having one entry per column. """ tr = [] for c in self.columns: tr.append(c.expanded_transform) return six.moves.zip_longest(*tr)
[ "def", "transforms", "(", "self", ")", ":", "tr", "=", "[", "]", "for", "c", "in", "self", ".", "columns", ":", "tr", ".", "append", "(", "c", ".", "expanded_transform", ")", "return", "six", ".", "moves", ".", "zip_longest", "(", "*", "tr", ")" ]
Return an array of arrays of column transforms. #The return value is an list of list, with each list being a segment of column transformations, and #each segment having one entry per column.
[ "Return", "an", "array", "of", "arrays", "of", "column", "transforms", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L288-L300
CivicSpleen/ambry
ambry/orm/table.py
Table.before_insert
def before_insert(mapper, conn, target): """event.listen method for Sqlalchemy to set the seqience_id for this object and create an ObjectNumber value for the id""" if target.sequence_id is None: from ambry.orm.exc import DatabaseError raise DatabaseError('Must have sequence id before insertion') Table.before_update(mapper, conn, target)
python
def before_insert(mapper, conn, target): """event.listen method for Sqlalchemy to set the seqience_id for this object and create an ObjectNumber value for the id""" if target.sequence_id is None: from ambry.orm.exc import DatabaseError raise DatabaseError('Must have sequence id before insertion') Table.before_update(mapper, conn, target)
[ "def", "before_insert", "(", "mapper", ",", "conn", ",", "target", ")", ":", "if", "target", ".", "sequence_id", "is", "None", ":", "from", "ambry", ".", "orm", ".", "exc", "import", "DatabaseError", "raise", "DatabaseError", "(", "'Must have sequence id befor...
event.listen method for Sqlalchemy to set the seqience_id for this object and create an ObjectNumber value for the id
[ "event", ".", "listen", "method", "for", "Sqlalchemy", "to", "set", "the", "seqience_id", "for", "this", "object", "and", "create", "an", "ObjectNumber", "value", "for", "the", "id" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L344-L351
CivicSpleen/ambry
ambry/orm/table.py
Table.before_update
def before_update(mapper, conn, target): """Set the Table ID based on the dataset number and the sequence number for the table.""" target.name = Table.mangle_name(target.name) if isinstance(target, Column): raise TypeError('Got a column instead of a table') target.update_id(target.sequence_id, False)
python
def before_update(mapper, conn, target): """Set the Table ID based on the dataset number and the sequence number for the table.""" target.name = Table.mangle_name(target.name) if isinstance(target, Column): raise TypeError('Got a column instead of a table') target.update_id(target.sequence_id, False)
[ "def", "before_update", "(", "mapper", ",", "conn", ",", "target", ")", ":", "target", ".", "name", "=", "Table", ".", "mangle_name", "(", "target", ".", "name", ")", "if", "isinstance", "(", "target", ",", "Column", ")", ":", "raise", "TypeError", "("...
Set the Table ID based on the dataset number and the sequence number for the table.
[ "Set", "the", "Table", "ID", "based", "on", "the", "dataset", "number", "and", "the", "sequence", "number", "for", "the", "table", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L354-L363
alvations/lazyme
lazyme/wikipedia.py
iter_paragraph
def iter_paragraph(filename, filetype): """ A helper function to iterate through the diff types of Wikipedia data inputs. :param arguments: The docopt arguments :type arguments: dict :return: A generator yielding a pargraph of text for each iteration. """ assert filetype in ['jsonzip', 'jsondir', 'wikidump'] # Iterating through paragraphes from the Anntoated Wikipedia zipfile. if filetype == 'jsonzip': with ZipFile(filename, 'r') as zip_in: # Iterate through the individual files. for infile in zip_in.namelist(): if infile.endswith('/'): # Skip the directories. continue print(infile, end='\n', file=sys.stderr) # Logging progress. with zip_in.open(infile) as f_in: for line in io.TextIOWrapper(f_in, 'utf8'): # Each line is a separate json. data = json.loads(line) # The useful text under 'text' key. yield data['text'].strip() # Iterating through paragraphes from the Anntoated Wikipedia directory. elif filetype == 'jsondir': for root, dirs, files in os.walk(filename): for wiki_file in files: infile = os.path.join(root, wiki_file) print(infile, end='\n', file=sys.stderr) # Logging progress. with io.open(infile, 'r', encoding='utf8') as f_in: for line in f_in: # Each line is a separate json. data = json.loads(line) # The useful text under 'text' key. yield data['text'].strip() # Iterating through paragraphes from the Wikipedia dump. elif filetype == 'wikidump': # Simply iterate through every line in the dump # and treat each line as a paragraph. with io.open(filename, 'r', encoding='utf8') as f_in: for line_count, paragraph in enumerate(f_in): if line_count % 100000: _msg = 'Processing line {}\n'.format(line_count) print(_msg, file=sys.stderr) # Logging progress. if pargraph: yield paragraph
python
def iter_paragraph(filename, filetype): """ A helper function to iterate through the diff types of Wikipedia data inputs. :param arguments: The docopt arguments :type arguments: dict :return: A generator yielding a pargraph of text for each iteration. """ assert filetype in ['jsonzip', 'jsondir', 'wikidump'] # Iterating through paragraphes from the Anntoated Wikipedia zipfile. if filetype == 'jsonzip': with ZipFile(filename, 'r') as zip_in: # Iterate through the individual files. for infile in zip_in.namelist(): if infile.endswith('/'): # Skip the directories. continue print(infile, end='\n', file=sys.stderr) # Logging progress. with zip_in.open(infile) as f_in: for line in io.TextIOWrapper(f_in, 'utf8'): # Each line is a separate json. data = json.loads(line) # The useful text under 'text' key. yield data['text'].strip() # Iterating through paragraphes from the Anntoated Wikipedia directory. elif filetype == 'jsondir': for root, dirs, files in os.walk(filename): for wiki_file in files: infile = os.path.join(root, wiki_file) print(infile, end='\n', file=sys.stderr) # Logging progress. with io.open(infile, 'r', encoding='utf8') as f_in: for line in f_in: # Each line is a separate json. data = json.loads(line) # The useful text under 'text' key. yield data['text'].strip() # Iterating through paragraphes from the Wikipedia dump. elif filetype == 'wikidump': # Simply iterate through every line in the dump # and treat each line as a paragraph. with io.open(filename, 'r', encoding='utf8') as f_in: for line_count, paragraph in enumerate(f_in): if line_count % 100000: _msg = 'Processing line {}\n'.format(line_count) print(_msg, file=sys.stderr) # Logging progress. if pargraph: yield paragraph
[ "def", "iter_paragraph", "(", "filename", ",", "filetype", ")", ":", "assert", "filetype", "in", "[", "'jsonzip'", ",", "'jsondir'", ",", "'wikidump'", "]", "# Iterating through paragraphes from the Anntoated Wikipedia zipfile.", "if", "filetype", "==", "'jsonzip'", ":"...
A helper function to iterate through the diff types of Wikipedia data inputs. :param arguments: The docopt arguments :type arguments: dict :return: A generator yielding a pargraph of text for each iteration.
[ "A", "helper", "function", "to", "iterate", "through", "the", "diff", "types", "of", "Wikipedia", "data", "inputs", ".", ":", "param", "arguments", ":", "The", "docopt", "arguments", ":", "type", "arguments", ":", "dict", ":", "return", ":", "A", "generato...
train
https://github.com/alvations/lazyme/blob/961a8282198588ff72e15643f725ce895e51d06d/lazyme/wikipedia.py#L17-L64
alvations/lazyme
lazyme/string.py
deduplicate
def deduplicate(s, ch): """ From http://stackoverflow.com/q/42216559/610569 s = 'this is an irritating string with random spacing .' deduplicate(s) 'this is an irritating string with random spacing .' """ return ch.join([substring for substring in s.strip().split(ch) if substring])
python
def deduplicate(s, ch): """ From http://stackoverflow.com/q/42216559/610569 s = 'this is an irritating string with random spacing .' deduplicate(s) 'this is an irritating string with random spacing .' """ return ch.join([substring for substring in s.strip().split(ch) if substring])
[ "def", "deduplicate", "(", "s", ",", "ch", ")", ":", "return", "ch", ".", "join", "(", "[", "substring", "for", "substring", "in", "s", ".", "strip", "(", ")", ".", "split", "(", "ch", ")", "if", "substring", "]", ")" ]
From http://stackoverflow.com/q/42216559/610569 s = 'this is an irritating string with random spacing .' deduplicate(s) 'this is an irritating string with random spacing .'
[ "From", "http", ":", "//", "stackoverflow", ".", "com", "/", "q", "/", "42216559", "/", "610569" ]
train
https://github.com/alvations/lazyme/blob/961a8282198588ff72e15643f725ce895e51d06d/lazyme/string.py#L45-L53
alvations/lazyme
lazyme/string.py
remove_text_inside_brackets
def remove_text_inside_brackets(s, brackets="()[]"): """ From http://stackoverflow.com/a/14603508/610569 """ count = [0] * (len(brackets) // 2) # count open/close brackets saved_chars = [] for character in s: for i, b in enumerate(brackets): if character == b: # found bracket kind, is_close = divmod(i, 2) count[kind] += (-1)**is_close # `+1`: open, `-1`: close if count[kind] < 0: # unbalanced bracket count[kind] = 0 break else: # character is not a bracket if not any(count): # outside brackets saved_chars.append(character) return ''.join(saved_chars)
python
def remove_text_inside_brackets(s, brackets="()[]"): """ From http://stackoverflow.com/a/14603508/610569 """ count = [0] * (len(brackets) // 2) # count open/close brackets saved_chars = [] for character in s: for i, b in enumerate(brackets): if character == b: # found bracket kind, is_close = divmod(i, 2) count[kind] += (-1)**is_close # `+1`: open, `-1`: close if count[kind] < 0: # unbalanced bracket count[kind] = 0 break else: # character is not a bracket if not any(count): # outside brackets saved_chars.append(character) return ''.join(saved_chars)
[ "def", "remove_text_inside_brackets", "(", "s", ",", "brackets", "=", "\"()[]\"", ")", ":", "count", "=", "[", "0", "]", "*", "(", "len", "(", "brackets", ")", "//", "2", ")", "# count open/close brackets", "saved_chars", "=", "[", "]", "for", "character",...
From http://stackoverflow.com/a/14603508/610569
[ "From", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "14603508", "/", "610569" ]
train
https://github.com/alvations/lazyme/blob/961a8282198588ff72e15643f725ce895e51d06d/lazyme/string.py#L70-L87
alvations/lazyme
lazyme/string.py
color_print
def color_print(s, color=None, highlight=None, end='\n', file=sys.stdout, **kwargs): """ From http://stackoverflow.com/a/287944/610569 See also https://gist.github.com/Sheljohn/68ca3be74139f66dbc6127784f638920 """ if color in palette and color != 'default': s = palette[color] + s # Highlight / Background color. if highlight and highlight in highlighter: s = highlighter[highlight] + s # Custom string format. for name, value in kwargs.items(): if name in formatter and value == True: s = formatter[name] + s print(s + palette['default'], end=end, file=file)
python
def color_print(s, color=None, highlight=None, end='\n', file=sys.stdout, **kwargs): """ From http://stackoverflow.com/a/287944/610569 See also https://gist.github.com/Sheljohn/68ca3be74139f66dbc6127784f638920 """ if color in palette and color != 'default': s = palette[color] + s # Highlight / Background color. if highlight and highlight in highlighter: s = highlighter[highlight] + s # Custom string format. for name, value in kwargs.items(): if name in formatter and value == True: s = formatter[name] + s print(s + palette['default'], end=end, file=file)
[ "def", "color_print", "(", "s", ",", "color", "=", "None", ",", "highlight", "=", "None", ",", "end", "=", "'\\n'", ",", "file", "=", "sys", ".", "stdout", ",", "*", "*", "kwargs", ")", ":", "if", "color", "in", "palette", "and", "color", "!=", "...
From http://stackoverflow.com/a/287944/610569 See also https://gist.github.com/Sheljohn/68ca3be74139f66dbc6127784f638920
[ "From", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "287944", "/", "610569", "See", "also", "https", ":", "//", "gist", ".", "github", ".", "com", "/", "Sheljohn", "/", "68ca3be74139f66dbc6127784f638920" ]
train
https://github.com/alvations/lazyme/blob/961a8282198588ff72e15643f725ce895e51d06d/lazyme/string.py#L90-L105
parkouss/rcontrol
rcontrol/core.py
SessionManager.wait_for_tasks
def wait_for_tasks(self, raise_if_error=True): """ Wait for the running tasks lauched from the sessions. Note that it also wait for tasks that are started from other tasks callbacks, like on_finished. :param raise_if_error: if True, raise all possible encountered errors using :class:`TaskErrors`. Else the errors are returned as a list. """ errors = [] tasks_seen = TaskCache() while True: for session in self.values(): errs = session.wait_for_tasks(raise_if_error=False) errors.extend(errs) # look for tasks created after the wait (in callbacks of # tasks from different sessions) tasks = [] for session in self.values(): tasks.extend(session.tasks()) # if none, then just break - else loop to wait for them if not any(t for t in tasks if t not in tasks_seen): break if raise_if_error and errors: raise TaskErrors(errors) return errors
python
def wait_for_tasks(self, raise_if_error=True): """ Wait for the running tasks lauched from the sessions. Note that it also wait for tasks that are started from other tasks callbacks, like on_finished. :param raise_if_error: if True, raise all possible encountered errors using :class:`TaskErrors`. Else the errors are returned as a list. """ errors = [] tasks_seen = TaskCache() while True: for session in self.values(): errs = session.wait_for_tasks(raise_if_error=False) errors.extend(errs) # look for tasks created after the wait (in callbacks of # tasks from different sessions) tasks = [] for session in self.values(): tasks.extend(session.tasks()) # if none, then just break - else loop to wait for them if not any(t for t in tasks if t not in tasks_seen): break if raise_if_error and errors: raise TaskErrors(errors) return errors
[ "def", "wait_for_tasks", "(", "self", ",", "raise_if_error", "=", "True", ")", ":", "errors", "=", "[", "]", "tasks_seen", "=", "TaskCache", "(", ")", "while", "True", ":", "for", "session", "in", "self", ".", "values", "(", ")", ":", "errs", "=", "s...
Wait for the running tasks lauched from the sessions. Note that it also wait for tasks that are started from other tasks callbacks, like on_finished. :param raise_if_error: if True, raise all possible encountered errors using :class:`TaskErrors`. Else the errors are returned as a list.
[ "Wait", "for", "the", "running", "tasks", "lauched", "from", "the", "sessions", "." ]
train
https://github.com/parkouss/rcontrol/blob/1764c1492f00d3f1a57dabe09983ed369aade828/rcontrol/core.py#L387-L414
parkouss/rcontrol
rcontrol/core.py
CommandTask.error
def error(self): """ Return an instance of Exception if any, else None. Actually check for a :class:`TimeoutError` or a :class:`ExitCodeError`. """ if self.__timed_out: return TimeoutError(self.session, self, "timeout") if self.__exit_code is not None and \ self.__expected_exit_code is not None and \ self.__exit_code != self.__expected_exit_code: return ExitCodeError(self.session, self, 'bad exit code: Got %s' % self.__exit_code)
python
def error(self): """ Return an instance of Exception if any, else None. Actually check for a :class:`TimeoutError` or a :class:`ExitCodeError`. """ if self.__timed_out: return TimeoutError(self.session, self, "timeout") if self.__exit_code is not None and \ self.__expected_exit_code is not None and \ self.__exit_code != self.__expected_exit_code: return ExitCodeError(self.session, self, 'bad exit code: Got %s' % self.__exit_code)
[ "def", "error", "(", "self", ")", ":", "if", "self", ".", "__timed_out", ":", "return", "TimeoutError", "(", "self", ".", "session", ",", "self", ",", "\"timeout\"", ")", "if", "self", ".", "__exit_code", "is", "not", "None", "and", "self", ".", "__exp...
Return an instance of Exception if any, else None. Actually check for a :class:`TimeoutError` or a :class:`ExitCodeError`.
[ "Return", "an", "instance", "of", "Exception", "if", "any", "else", "None", "." ]
train
https://github.com/parkouss/rcontrol/blob/1764c1492f00d3f1a57dabe09983ed369aade828/rcontrol/core.py#L557-L570
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/licenses_api.py
LicensesApi.create_new
def create_new(self, **kwargs): """ Creates a new License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_new(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param LicenseRest body: :return: LicenseSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.create_new_with_http_info(**kwargs) else: (data) = self.create_new_with_http_info(**kwargs) return data
python
def create_new(self, **kwargs): """ Creates a new License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_new(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param LicenseRest body: :return: LicenseSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.create_new_with_http_info(**kwargs) else: (data) = self.create_new_with_http_info(**kwargs) return data
[ "def", "create_new", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "create_new_with_http_info", "(", "*", "*", ...
Creates a new License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_new(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param LicenseRest body: :return: LicenseSingleton If the method is called asynchronously, returns the request thread.
[ "Creates", "a", "new", "License", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", "when", "...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/licenses_api.py#L42-L66
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/licenses_api.py
LicensesApi.delete
def delete(self, id, **kwargs): """ Deletes an existing License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: License id (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.delete_with_http_info(id, **kwargs) else: (data) = self.delete_with_http_info(id, **kwargs) return data
python
def delete(self, id, **kwargs): """ Deletes an existing License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: License id (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.delete_with_http_info(id, **kwargs) else: (data) = self.delete_with_http_info(id, **kwargs) return data
[ "def", "delete", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "delete_with_http_info", "(", "id", ...
Deletes an existing License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: License id (required) :return: None If the method is called asynchronously, returns the request thread.
[ "Deletes", "an", "existing", "License", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", "when...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/licenses_api.py#L145-L169
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/licenses_api.py
LicensesApi.get_all
def get_all(self, **kwargs): """ Gets all Licenses This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: LicensePage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_with_http_info(**kwargs) else: (data) = self.get_all_with_http_info(**kwargs) return data
python
def get_all(self, **kwargs): """ Gets all Licenses This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: LicensePage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_with_http_info(**kwargs) else: (data) = self.get_all_with_http_info(**kwargs) return data
[ "def", "get_all", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_all_with_http_info", "(", "*", "*", "kwarg...
Gets all Licenses This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: LicensePage If the method is called asynchronously, returns the request thread.
[ "Gets", "all", "Licenses", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", "when", "receiving...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/licenses_api.py#L251-L278
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/licenses_api.py
LicensesApi.get_specific
def get_specific(self, id, **kwargs): """ Get specific License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_specific(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: License id (required) :return: LicenseSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_specific_with_http_info(id, **kwargs) else: (data) = self.get_specific_with_http_info(id, **kwargs) return data
python
def get_specific(self, id, **kwargs): """ Get specific License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_specific(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: License id (required) :return: LicenseSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_specific_with_http_info(id, **kwargs) else: (data) = self.get_specific_with_http_info(id, **kwargs) return data
[ "def", "get_specific", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_specific_with_http_info", "(...
Get specific License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_specific(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: License id (required) :return: LicenseSingleton If the method is called asynchronously, returns the request thread.
[ "Get", "specific", "License", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", "when", "receiv...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/licenses_api.py#L366-L390
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/licenses_api.py
LicensesApi.update
def update(self, id, **kwargs): """ Updates an existing License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: License id (required) :param LicenseRest body: :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.update_with_http_info(id, **kwargs) else: (data) = self.update_with_http_info(id, **kwargs) return data
python
def update(self, id, **kwargs): """ Updates an existing License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: License id (required) :param LicenseRest body: :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.update_with_http_info(id, **kwargs) else: (data) = self.update_with_http_info(id, **kwargs) return data
[ "def", "update", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "update_with_http_info", "(", "id", ...
Updates an existing License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: License id (required) :param LicenseRest body: :return: None If the method is called asynchronously, returns the request thread.
[ "Updates", "an", "existing", "License", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", "when...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/licenses_api.py#L472-L497
CivicSpleen/ambry
ambry/orm/dataset.py
Dataset.incver
def incver(self): """Increment all of the version numbers""" d = {} for p in self.__mapper__.attrs: if p.key in ['vid','vname','fqname', 'version', 'cache_key']: continue if p.key == 'revision': d[p.key] = self.revision + 1 else: d[p.key] = getattr(self, p.key) n = Dataset(**d) return n
python
def incver(self): """Increment all of the version numbers""" d = {} for p in self.__mapper__.attrs: if p.key in ['vid','vname','fqname', 'version', 'cache_key']: continue if p.key == 'revision': d[p.key] = self.revision + 1 else: d[p.key] = getattr(self, p.key) n = Dataset(**d) return n
[ "def", "incver", "(", "self", ")", ":", "d", "=", "{", "}", "for", "p", "in", "self", ".", "__mapper__", ".", "attrs", ":", "if", "p", ".", "key", "in", "[", "'vid'", ",", "'vname'", ",", "'fqname'", ",", "'version'", ",", "'cache_key'", "]", ":"...
Increment all of the version numbers
[ "Increment", "all", "of", "the", "version", "numbers" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L118-L131
CivicSpleen/ambry
ambry/orm/dataset.py
Dataset.next_sequence_id
def next_sequence_id(self, table_class, force_query=False): """Return the next sequence id for a object, identified by the vid of the parent object, and the database prefix for the child object. On the first call, will load the max sequence number from the database, but subsequence calls will run in process, so this isn't suitable for multi-process operation -- all of the tables in a dataset should be created by one process The child table must have a sequence_id value. """ from . import next_sequence_id from sqlalchemy.orm import object_session # NOTE: This next_sequence_id uses a different algorithm than dataset.next_sequence_id # FIXME replace this one with dataset.next_sequence_id return next_sequence_id(object_session(self), self._sequence_ids, self.vid, table_class, force_query=force_query)
python
def next_sequence_id(self, table_class, force_query=False): """Return the next sequence id for a object, identified by the vid of the parent object, and the database prefix for the child object. On the first call, will load the max sequence number from the database, but subsequence calls will run in process, so this isn't suitable for multi-process operation -- all of the tables in a dataset should be created by one process The child table must have a sequence_id value. """ from . import next_sequence_id from sqlalchemy.orm import object_session # NOTE: This next_sequence_id uses a different algorithm than dataset.next_sequence_id # FIXME replace this one with dataset.next_sequence_id return next_sequence_id(object_session(self), self._sequence_ids, self.vid, table_class, force_query=force_query)
[ "def", "next_sequence_id", "(", "self", ",", "table_class", ",", "force_query", "=", "False", ")", ":", "from", ".", "import", "next_sequence_id", "from", "sqlalchemy", ".", "orm", "import", "object_session", "# NOTE: This next_sequence_id uses a different algorithm than ...
Return the next sequence id for a object, identified by the vid of the parent object, and the database prefix for the child object. On the first call, will load the max sequence number from the database, but subsequence calls will run in process, so this isn't suitable for multi-process operation -- all of the tables in a dataset should be created by one process The child table must have a sequence_id value.
[ "Return", "the", "next", "sequence", "id", "for", "a", "object", "identified", "by", "the", "vid", "of", "the", "parent", "object", "and", "the", "database", "prefix", "for", "the", "child", "object", ".", "On", "the", "first", "call", "will", "load", "t...
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L165-L180
CivicSpleen/ambry
ambry/orm/dataset.py
Dataset.new_unique_object
def new_unique_object(self, table_class, sequence_id=None, force_query=False, **kwargs): """Use next_sequence_id to create a new child of the dataset, with a unique id""" from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import FlushError # If a sequence ID was specified, the caller is certain # that there is no potential for conflicts, # so there is no need to commit here. if not sequence_id: commit = True sequence_id = self.next_sequence_id(table_class, force_query=force_query) else: commit = False o = table_class( d_vid=self.vid, **kwargs ) o.update_id(sequence_id) if commit is False: return o self.commit() if self._database.driver == 'sqlite': # The Sqlite database can't have concurrency, so there no problem. self.session.add(o) self.commit() return o else: # Postgres. Concurrency is a bitch. table_name = table_class.__tablename__ child_sequence_id = table_class.sequence_id.property.columns[0].name try: self.session.add(o) self.commit() return o except (IntegrityError, FlushError) as e: self.rollback() self.session.merge(self) print 'Failed' return None return # This is horrible, but it's the only thing that has worked for both # Sqlite and Postgres in both single processes and multiprocesses. d_vid = self.vid while True: try: self.session.add(o) self.commit() return o except (IntegrityError, FlushError) as e: self.rollback() self.session.expunge_all() ds = self._database.dataset(d_vid) sequence_id = ds.next_sequence_id(table_class, force_query=True) o.update_id(sequence_id) except Exception as e: print('Completely failed to get a new {} sequence_id; {}'.format(table_class, e)) self.rollback() import traceback # This bit is helpful in a multiprocessing run. tb = traceback.format_exc() print(tb) raise
python
def new_unique_object(self, table_class, sequence_id=None, force_query=False, **kwargs): """Use next_sequence_id to create a new child of the dataset, with a unique id""" from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import FlushError # If a sequence ID was specified, the caller is certain # that there is no potential for conflicts, # so there is no need to commit here. if not sequence_id: commit = True sequence_id = self.next_sequence_id(table_class, force_query=force_query) else: commit = False o = table_class( d_vid=self.vid, **kwargs ) o.update_id(sequence_id) if commit is False: return o self.commit() if self._database.driver == 'sqlite': # The Sqlite database can't have concurrency, so there no problem. self.session.add(o) self.commit() return o else: # Postgres. Concurrency is a bitch. table_name = table_class.__tablename__ child_sequence_id = table_class.sequence_id.property.columns[0].name try: self.session.add(o) self.commit() return o except (IntegrityError, FlushError) as e: self.rollback() self.session.merge(self) print 'Failed' return None return # This is horrible, but it's the only thing that has worked for both # Sqlite and Postgres in both single processes and multiprocesses. d_vid = self.vid while True: try: self.session.add(o) self.commit() return o except (IntegrityError, FlushError) as e: self.rollback() self.session.expunge_all() ds = self._database.dataset(d_vid) sequence_id = ds.next_sequence_id(table_class, force_query=True) o.update_id(sequence_id) except Exception as e: print('Completely failed to get a new {} sequence_id; {}'.format(table_class, e)) self.rollback() import traceback # This bit is helpful in a multiprocessing run. tb = traceback.format_exc() print(tb) raise
[ "def", "new_unique_object", "(", "self", ",", "table_class", ",", "sequence_id", "=", "None", ",", "force_query", "=", "False", ",", "*", "*", "kwargs", ")", ":", "from", "sqlalchemy", ".", "exc", "import", "IntegrityError", "from", "sqlalchemy", ".", "orm",...
Use next_sequence_id to create a new child of the dataset, with a unique id
[ "Use", "next_sequence_id", "to", "create", "a", "new", "child", "of", "the", "dataset", "with", "a", "unique", "id" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L182-L259
CivicSpleen/ambry
ambry/orm/dataset.py
Dataset.new_table
def new_table(self, name, add_id=True, **kwargs): '''Add a table to the schema, or update it it already exists. If updating, will only update data. ''' from . import Table from .exc import NotFoundError try: table = self.table(name) extant = True except NotFoundError: extant = False if 'sequence_id' not in kwargs: kwargs['sequence_id'] = self._database.next_sequence_id(Dataset, self.vid, Table) table = Table(name=name, d_vid=self.vid, **kwargs) table.update_id() # Update possibly extant data table.data = dict( (list(table.data.items()) if table.data else []) + list(kwargs.get('data', {}).items())) for key, value in list(kwargs.items()): if not key: continue if key[0] != '_' and key not in ['vid', 'id', 'id_', 'd_id', 'name', 'sequence_id', 'table', 'column', 'data']: setattr(table, key, value) if add_id: table.add_id_column() if not extant: self.tables.append(table) return table
python
def new_table(self, name, add_id=True, **kwargs): '''Add a table to the schema, or update it it already exists. If updating, will only update data. ''' from . import Table from .exc import NotFoundError try: table = self.table(name) extant = True except NotFoundError: extant = False if 'sequence_id' not in kwargs: kwargs['sequence_id'] = self._database.next_sequence_id(Dataset, self.vid, Table) table = Table(name=name, d_vid=self.vid, **kwargs) table.update_id() # Update possibly extant data table.data = dict( (list(table.data.items()) if table.data else []) + list(kwargs.get('data', {}).items())) for key, value in list(kwargs.items()): if not key: continue if key[0] != '_' and key not in ['vid', 'id', 'id_', 'd_id', 'name', 'sequence_id', 'table', 'column', 'data']: setattr(table, key, value) if add_id: table.add_id_column() if not extant: self.tables.append(table) return table
[ "def", "new_table", "(", "self", ",", "name", ",", "add_id", "=", "True", ",", "*", "*", "kwargs", ")", ":", "from", ".", "import", "Table", "from", ".", "exc", "import", "NotFoundError", "try", ":", "table", "=", "self", ".", "table", "(", "name", ...
Add a table to the schema, or update it it already exists. If updating, will only update data.
[ "Add", "a", "table", "to", "the", "schema", "or", "update", "it", "it", "already", "exists", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L273-L312
CivicSpleen/ambry
ambry/orm/dataset.py
Dataset.new_partition
def new_partition(self, table, **kwargs): """ Creates new partition and returns it. Args: table (orm.Table): Returns: orm.Partition """ from . import Partition # Create the basic partition record, with a sequence ID. if isinstance(table, string_types): table = self.table(table) if 'sequence_id' in kwargs: sequence_id = kwargs['sequence_id'] del kwargs['sequence_id'] else: sequence_id = self._database.next_sequence_id(Dataset, self.vid, Partition) p = Partition( t_vid=table.vid, table_name=table.name, sequence_id=sequence_id, dataset=self, d_vid=self.vid, **kwargs ) p.update_id() return p
python
def new_partition(self, table, **kwargs): """ Creates new partition and returns it. Args: table (orm.Table): Returns: orm.Partition """ from . import Partition # Create the basic partition record, with a sequence ID. if isinstance(table, string_types): table = self.table(table) if 'sequence_id' in kwargs: sequence_id = kwargs['sequence_id'] del kwargs['sequence_id'] else: sequence_id = self._database.next_sequence_id(Dataset, self.vid, Partition) p = Partition( t_vid=table.vid, table_name=table.name, sequence_id=sequence_id, dataset=self, d_vid=self.vid, **kwargs ) p.update_id() return p
[ "def", "new_partition", "(", "self", ",", "table", ",", "*", "*", "kwargs", ")", ":", "from", ".", "import", "Partition", "# Create the basic partition record, with a sequence ID.", "if", "isinstance", "(", "table", ",", "string_types", ")", ":", "table", "=", "...
Creates new partition and returns it. Args: table (orm.Table): Returns: orm.Partition
[ "Creates", "new", "partition", "and", "returns", "it", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L314-L349
CivicSpleen/ambry
ambry/orm/dataset.py
Dataset.partition
def partition(self, ref=None, **kwargs): """ Returns partition by ref. """ from .exc import NotFoundError from six import text_type if ref: for p in self.partitions: # This is slow for large datasets, like Census years. if (text_type(ref) == text_type(p.name) or text_type(ref) == text_type(p.id) or text_type(ref) == text_type(p.vid)): return p raise NotFoundError("Failed to find partition for ref '{}' in dataset '{}'".format(ref, self.name)) elif kwargs: from ..identity import PartitionNameQuery pnq = PartitionNameQuery(**kwargs) return self._find_orm
python
def partition(self, ref=None, **kwargs): """ Returns partition by ref. """ from .exc import NotFoundError from six import text_type if ref: for p in self.partitions: # This is slow for large datasets, like Census years. if (text_type(ref) == text_type(p.name) or text_type(ref) == text_type(p.id) or text_type(ref) == text_type(p.vid)): return p raise NotFoundError("Failed to find partition for ref '{}' in dataset '{}'".format(ref, self.name)) elif kwargs: from ..identity import PartitionNameQuery pnq = PartitionNameQuery(**kwargs) return self._find_orm
[ "def", "partition", "(", "self", ",", "ref", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", ".", "exc", "import", "NotFoundError", "from", "six", "import", "text_type", "if", "ref", ":", "for", "p", "in", "self", ".", "partitions", ":", "# T...
Returns partition by ref.
[ "Returns", "partition", "by", "ref", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L351-L369
CivicSpleen/ambry
ambry/orm/dataset.py
Dataset.bsfile
def bsfile(self, path): """Return a Build Source file ref, creating a new one if the one requested does not exist""" from sqlalchemy.orm.exc import NoResultFound from ambry.orm.exc import NotFoundError try: f = object_session(self)\ .query(File)\ .filter(File.d_vid == self.vid)\ .filter(File.major_type == File.MAJOR_TYPE.BUILDSOURCE)\ .filter(File.path == path)\ .one() return f except NoResultFound: raise NotFoundError("Failed to find file for path '{}' ".format(path))
python
def bsfile(self, path): """Return a Build Source file ref, creating a new one if the one requested does not exist""" from sqlalchemy.orm.exc import NoResultFound from ambry.orm.exc import NotFoundError try: f = object_session(self)\ .query(File)\ .filter(File.d_vid == self.vid)\ .filter(File.major_type == File.MAJOR_TYPE.BUILDSOURCE)\ .filter(File.path == path)\ .one() return f except NoResultFound: raise NotFoundError("Failed to find file for path '{}' ".format(path))
[ "def", "bsfile", "(", "self", ",", "path", ")", ":", "from", "sqlalchemy", ".", "orm", ".", "exc", "import", "NoResultFound", "from", "ambry", ".", "orm", ".", "exc", "import", "NotFoundError", "try", ":", "f", "=", "object_session", "(", "self", ")", ...
Return a Build Source file ref, creating a new one if the one requested does not exist
[ "Return", "a", "Build", "Source", "file", "ref", "creating", "a", "new", "one", "if", "the", "one", "requested", "does", "not", "exist" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L523-L540
CivicSpleen/ambry
ambry/orm/dataset.py
Dataset.row
def row(self, fields): """Return a row for fields, for CSV files, pretty printing, etc, give a set of fields to return""" d = self.dict row = [None] * len(fields) for i, f in enumerate(fields): if f in d: row[i] = d[f] return row
python
def row(self, fields): """Return a row for fields, for CSV files, pretty printing, etc, give a set of fields to return""" d = self.dict row = [None] * len(fields) for i, f in enumerate(fields): if f in d: row[i] = d[f] return row
[ "def", "row", "(", "self", ",", "fields", ")", ":", "d", "=", "self", ".", "dict", "row", "=", "[", "None", "]", "*", "len", "(", "fields", ")", "for", "i", ",", "f", "in", "enumerate", "(", "fields", ")", ":", "if", "f", "in", "d", ":", "r...
Return a row for fields, for CSV files, pretty printing, etc, give a set of fields to return
[ "Return", "a", "row", "for", "fields", "for", "CSV", "files", "pretty", "printing", "etc", "give", "a", "set", "of", "fields", "to", "return" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L595-L606
CivicSpleen/ambry
ambry/orm/dataset.py
ConfigAccessor.metadata
def metadata(self): """Access process configuarion values as attributes. """ from ambry.metadata.schema import Top # cross-module import top = Top() top.build_from_db(self.dataset) return top
python
def metadata(self): """Access process configuarion values as attributes. """ from ambry.metadata.schema import Top # cross-module import top = Top() top.build_from_db(self.dataset) return top
[ "def", "metadata", "(", "self", ")", ":", "from", "ambry", ".", "metadata", ".", "schema", "import", "Top", "# cross-module import", "top", "=", "Top", "(", ")", "top", ".", "build_from_db", "(", "self", ".", "dataset", ")", "return", "top" ]
Access process configuarion values as attributes.
[ "Access", "process", "configuarion", "values", "as", "attributes", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L626-L631
CivicSpleen/ambry
ambry/orm/dataset.py
ConfigAccessor.rows
def rows(self): """Return configuration in a form that can be used to reconstitute a Metadata object. Returns all of the rows for a dataset. This is distinct from get_config_value, which returns the value for the library. """ from ambry.orm import Config as SAConfig from sqlalchemy import or_ rows = [] configs = self.dataset.session\ .query(SAConfig)\ .filter(or_(SAConfig.group == 'config', SAConfig.group == 'process'), SAConfig.d_vid == self.dataset.vid)\ .all() for r in configs: parts = r.key.split('.', 3) if r.group == 'process': parts = ['process'] + parts cr = ((parts[0] if len(parts) > 0 else None, parts[1] if len(parts) > 1 else None, parts[2] if len(parts) > 2 else None ), r.value) rows.append(cr) return rows
python
def rows(self): """Return configuration in a form that can be used to reconstitute a Metadata object. Returns all of the rows for a dataset. This is distinct from get_config_value, which returns the value for the library. """ from ambry.orm import Config as SAConfig from sqlalchemy import or_ rows = [] configs = self.dataset.session\ .query(SAConfig)\ .filter(or_(SAConfig.group == 'config', SAConfig.group == 'process'), SAConfig.d_vid == self.dataset.vid)\ .all() for r in configs: parts = r.key.split('.', 3) if r.group == 'process': parts = ['process'] + parts cr = ((parts[0] if len(parts) > 0 else None, parts[1] if len(parts) > 1 else None, parts[2] if len(parts) > 2 else None ), r.value) rows.append(cr) return rows
[ "def", "rows", "(", "self", ")", ":", "from", "ambry", ".", "orm", "import", "Config", "as", "SAConfig", "from", "sqlalchemy", "import", "or_", "rows", "=", "[", "]", "configs", "=", "self", ".", "dataset", ".", "session", ".", "query", "(", "SAConfig"...
Return configuration in a form that can be used to reconstitute a Metadata object. Returns all of the rows for a dataset. This is distinct from get_config_value, which returns the value for the library.
[ "Return", "configuration", "in", "a", "form", "that", "can", "be", "used", "to", "reconstitute", "a", "Metadata", "object", ".", "Returns", "all", "of", "the", "rows", "for", "a", "dataset", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/dataset.py#L649-L680
CivicSpleen/ambry
ambry/metadata/proptree.py
_set_value
def _set_value(instance_to_path_map, path_to_instance_map, prop_tree, config_instance): """ Finds appropriate term in the prop_tree and sets its value from config_instance. Args: configs_map (dict): key is id of the config, value is Config instance (AKA cache of the configs) prop_tree (PropertyDictTree): poperty tree to populate. config_instance (Config): """ path = instance_to_path_map[config_instance] # find group group = prop_tree for elem in path[:-1]: group = getattr(group, elem) assert group._key == config_instance.parent.key setattr(group, config_instance.key, config_instance.value) # # bind config to the term # # FIXME: Make all the terms to store config instance the same way. term = getattr(group, config_instance.key) try: if hasattr(term, '_term'): # ScalarTermS and ScalarTermU case term._term._config = config_instance return except KeyError: # python3 case. TODO: Find the way to make it simple. pass try: if hasattr(term, '_config'): term._config = config_instance return except KeyError: # python3 case. TODO: Find the way to make it simple. pass else: pass
python
def _set_value(instance_to_path_map, path_to_instance_map, prop_tree, config_instance): """ Finds appropriate term in the prop_tree and sets its value from config_instance. Args: configs_map (dict): key is id of the config, value is Config instance (AKA cache of the configs) prop_tree (PropertyDictTree): poperty tree to populate. config_instance (Config): """ path = instance_to_path_map[config_instance] # find group group = prop_tree for elem in path[:-1]: group = getattr(group, elem) assert group._key == config_instance.parent.key setattr(group, config_instance.key, config_instance.value) # # bind config to the term # # FIXME: Make all the terms to store config instance the same way. term = getattr(group, config_instance.key) try: if hasattr(term, '_term'): # ScalarTermS and ScalarTermU case term._term._config = config_instance return except KeyError: # python3 case. TODO: Find the way to make it simple. pass try: if hasattr(term, '_config'): term._config = config_instance return except KeyError: # python3 case. TODO: Find the way to make it simple. pass else: pass
[ "def", "_set_value", "(", "instance_to_path_map", ",", "path_to_instance_map", ",", "prop_tree", ",", "config_instance", ")", ":", "path", "=", "instance_to_path_map", "[", "config_instance", "]", "# find group", "group", "=", "prop_tree", "for", "elem", "in", "path...
Finds appropriate term in the prop_tree and sets its value from config_instance. Args: configs_map (dict): key is id of the config, value is Config instance (AKA cache of the configs) prop_tree (PropertyDictTree): poperty tree to populate. config_instance (Config):
[ "Finds", "appropriate", "term", "in", "the", "prop_tree", "and", "sets", "its", "value", "from", "config_instance", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L1148-L1189
CivicSpleen/ambry
ambry/metadata/proptree.py
get_or_create
def get_or_create(session, model, **kwargs): """ Get or create sqlalchemy instance. Args: session (Sqlalchemy session): model (sqlalchemy model): kwargs (dict): kwargs to lookup or create instance. Returns: Tuple: first element is found or created instance, second is boolean - True if instance created, False if instance found. """ instance = session.query(model).filter_by(**kwargs).first() if instance: return instance, False else: instance = model(**kwargs) if 'dataset' in kwargs: instance.update_sequence_id(session, kwargs['dataset']) session.add(instance) session.commit() return instance, True
python
def get_or_create(session, model, **kwargs): """ Get or create sqlalchemy instance. Args: session (Sqlalchemy session): model (sqlalchemy model): kwargs (dict): kwargs to lookup or create instance. Returns: Tuple: first element is found or created instance, second is boolean - True if instance created, False if instance found. """ instance = session.query(model).filter_by(**kwargs).first() if instance: return instance, False else: instance = model(**kwargs) if 'dataset' in kwargs: instance.update_sequence_id(session, kwargs['dataset']) session.add(instance) session.commit() return instance, True
[ "def", "get_or_create", "(", "session", ",", "model", ",", "*", "*", "kwargs", ")", ":", "instance", "=", "session", ".", "query", "(", "model", ")", ".", "filter_by", "(", "*", "*", "kwargs", ")", ".", "first", "(", ")", "if", "instance", ":", "re...
Get or create sqlalchemy instance. Args: session (Sqlalchemy session): model (sqlalchemy model): kwargs (dict): kwargs to lookup or create instance. Returns: Tuple: first element is found or created instance, second is boolean - True if instance created, False if instance found.
[ "Get", "or", "create", "sqlalchemy", "instance", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L1192-L1213
CivicSpleen/ambry
ambry/metadata/proptree.py
_get_config_instance
def _get_config_instance(group_or_term, session, **kwargs): """ Finds appropriate config instance and returns it. Args: group_or_term (Group or Term): session (Sqlalchemy session): kwargs (dict): kwargs to pass to get_or_create. Returns: tuple of (Config, bool): """ path = group_or_term._get_path() cached = group_or_term._top._cached_configs.get(path) if cached: config = cached created = False else: # does not exist or not yet cached config, created = get_or_create(session, Config, **kwargs) return config, created
python
def _get_config_instance(group_or_term, session, **kwargs): """ Finds appropriate config instance and returns it. Args: group_or_term (Group or Term): session (Sqlalchemy session): kwargs (dict): kwargs to pass to get_or_create. Returns: tuple of (Config, bool): """ path = group_or_term._get_path() cached = group_or_term._top._cached_configs.get(path) if cached: config = cached created = False else: # does not exist or not yet cached config, created = get_or_create(session, Config, **kwargs) return config, created
[ "def", "_get_config_instance", "(", "group_or_term", ",", "session", ",", "*", "*", "kwargs", ")", ":", "path", "=", "group_or_term", ".", "_get_path", "(", ")", "cached", "=", "group_or_term", ".", "_top", ".", "_cached_configs", ".", "get", "(", "path", ...
Finds appropriate config instance and returns it. Args: group_or_term (Group or Term): session (Sqlalchemy session): kwargs (dict): kwargs to pass to get_or_create. Returns: tuple of (Config, bool):
[ "Finds", "appropriate", "config", "instance", "and", "returns", "it", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L1216-L1235
CivicSpleen/ambry
ambry/metadata/proptree.py
StructuredPropertyTree.register_members
def register_members(self): """Collect the names of the class member and convert them to object members. Unlike Terms, the Group class members are converted into object members, so the configuration data """ self._members = { name: attr for name, attr in iteritems(type(self).__dict__) if isinstance(attr, Group)} for name, m in iteritems(self._members): m.init_descriptor(name, self)
python
def register_members(self): """Collect the names of the class member and convert them to object members. Unlike Terms, the Group class members are converted into object members, so the configuration data """ self._members = { name: attr for name, attr in iteritems(type(self).__dict__) if isinstance(attr, Group)} for name, m in iteritems(self._members): m.init_descriptor(name, self)
[ "def", "register_members", "(", "self", ")", ":", "self", ".", "_members", "=", "{", "name", ":", "attr", "for", "name", ",", "attr", "in", "iteritems", "(", "type", "(", "self", ")", ".", "__dict__", ")", "if", "isinstance", "(", "attr", ",", "Group...
Collect the names of the class member and convert them to object members. Unlike Terms, the Group class members are converted into object members, so the configuration data
[ "Collect", "the", "names", "of", "the", "class", "member", "and", "convert", "them", "to", "object", "members", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L304-L317
CivicSpleen/ambry
ambry/metadata/proptree.py
StructuredPropertyTree.add_error
def add_error(self, group, term, sub_term, value): """For records that are not defined as terms, either add it to the errors list.""" self._errors[(group, term, sub_term)] = value
python
def add_error(self, group, term, sub_term, value): """For records that are not defined as terms, either add it to the errors list.""" self._errors[(group, term, sub_term)] = value
[ "def", "add_error", "(", "self", ",", "group", ",", "term", ",", "sub_term", ",", "value", ")", ":", "self", ".", "_errors", "[", "(", "group", ",", "term", ",", "sub_term", ")", "]", "=", "value" ]
For records that are not defined as terms, either add it to the errors list.
[ "For", "records", "that", "are", "not", "defined", "as", "terms", "either", "add", "it", "to", "the", "errors", "list", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L357-L361
CivicSpleen/ambry
ambry/metadata/proptree.py
StructuredPropertyTree._jinja_sub
def _jinja_sub(self, st): """Create a Jina template engine, then perform substitutions on a string""" if isinstance(st, string_types): from jinja2 import Template try: for i in range(5): # Only do 5 recursive substitutions. st = Template(st).render(**(self._top.dict)) if '{{' not in st: break return st except Exception as e: return st #raise ValueError( # "Failed to render jinja template for metadata value '{}': {}".format(st, e)) return st
python
def _jinja_sub(self, st): """Create a Jina template engine, then perform substitutions on a string""" if isinstance(st, string_types): from jinja2 import Template try: for i in range(5): # Only do 5 recursive substitutions. st = Template(st).render(**(self._top.dict)) if '{{' not in st: break return st except Exception as e: return st #raise ValueError( # "Failed to render jinja template for metadata value '{}': {}".format(st, e)) return st
[ "def", "_jinja_sub", "(", "self", ",", "st", ")", ":", "if", "isinstance", "(", "st", ",", "string_types", ")", ":", "from", "jinja2", "import", "Template", "try", ":", "for", "i", "in", "range", "(", "5", ")", ":", "# Only do 5 recursive substitutions.", ...
Create a Jina template engine, then perform substitutions on a string
[ "Create", "a", "Jina", "template", "engine", "then", "perform", "substitutions", "on", "a", "string" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L371-L388
CivicSpleen/ambry
ambry/metadata/proptree.py
StructuredPropertyTree.scalar_term
def scalar_term(self, st): """Return a _ScalarTermS or _ScalarTermU from a string, to perform text and HTML substitutions""" if isinstance(st, binary_type): return _ScalarTermS(st, self._jinja_sub) elif isinstance(st, text_type): return _ScalarTermU(st, self._jinja_sub) elif st is None: return _ScalarTermU(u(''), self._jinja_sub) else: return st
python
def scalar_term(self, st): """Return a _ScalarTermS or _ScalarTermU from a string, to perform text and HTML substitutions""" if isinstance(st, binary_type): return _ScalarTermS(st, self._jinja_sub) elif isinstance(st, text_type): return _ScalarTermU(st, self._jinja_sub) elif st is None: return _ScalarTermU(u(''), self._jinja_sub) else: return st
[ "def", "scalar_term", "(", "self", ",", "st", ")", ":", "if", "isinstance", "(", "st", ",", "binary_type", ")", ":", "return", "_ScalarTermS", "(", "st", ",", "self", ".", "_jinja_sub", ")", "elif", "isinstance", "(", "st", ",", "text_type", ")", ":", ...
Return a _ScalarTermS or _ScalarTermU from a string, to perform text and HTML substitutions
[ "Return", "a", "_ScalarTermS", "or", "_ScalarTermU", "from", "a", "string", "to", "perform", "text", "and", "HTML", "substitutions" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L390-L399
CivicSpleen/ambry
ambry/metadata/proptree.py
Group.update_config
def update_config(self): """ Updates or creates config of that group. Requires tree bound to db. """ dataset = self._top._config.dataset session = object_session(self._top._config) logger.debug( 'Updating group config. dataset: {}, type: {}, key: {}'.format(dataset.vid, self._top._type, self._key)) self._config, created = _get_config_instance( self, session, parent_id=self._parent._config.id, d_vid=dataset.vid, group=self._key, key=self._key, type=self._top._type, dataset = dataset) if created: self._top._cached_configs[self._get_path()] = self._config self._top._add_valid(self._config) if created: logger.debug( 'New group config created and linked. config: {}'.format(self._config)) else: logger.debug( 'Existing group config linked. config: {}'.format(self._config))
python
def update_config(self): """ Updates or creates config of that group. Requires tree bound to db. """ dataset = self._top._config.dataset session = object_session(self._top._config) logger.debug( 'Updating group config. dataset: {}, type: {}, key: {}'.format(dataset.vid, self._top._type, self._key)) self._config, created = _get_config_instance( self, session, parent_id=self._parent._config.id, d_vid=dataset.vid, group=self._key, key=self._key, type=self._top._type, dataset = dataset) if created: self._top._cached_configs[self._get_path()] = self._config self._top._add_valid(self._config) if created: logger.debug( 'New group config created and linked. config: {}'.format(self._config)) else: logger.debug( 'Existing group config linked. config: {}'.format(self._config))
[ "def", "update_config", "(", "self", ")", ":", "dataset", "=", "self", ".", "_top", ".", "_config", ".", "dataset", "session", "=", "object_session", "(", "self", ".", "_top", ".", "_config", ")", "logger", ".", "debug", "(", "'Updating group config. dataset...
Updates or creates config of that group. Requires tree bound to db.
[ "Updates", "or", "creates", "config", "of", "that", "group", ".", "Requires", "tree", "bound", "to", "db", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L446-L466
CivicSpleen/ambry
ambry/metadata/proptree.py
Group.get_group_instance
def get_group_instance(self, parent): """Create an instance object""" o = copy.copy(self) o.init_instance(parent) return o
python
def get_group_instance(self, parent): """Create an instance object""" o = copy.copy(self) o.init_instance(parent) return o
[ "def", "get_group_instance", "(", "self", ",", "parent", ")", ":", "o", "=", "copy", ".", "copy", "(", "self", ")", "o", ".", "init_instance", "(", "parent", ")", "return", "o" ]
Create an instance object
[ "Create", "an", "instance", "object" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L489-L493
CivicSpleen/ambry
ambry/metadata/proptree.py
VarDictGroup.update_config
def update_config(self, key, value): """ Creates or updates db config of the VarDictGroup. Requires bound to db tree. """ dataset = self._top._config.dataset session = object_session(self._top._config) logger.debug( 'Updating VarDictGroup config. dataset: {}, type: {}, key: {}, value: {}'.format( dataset, self._top._type, key, value)) if not self._parent._config: self._parent.update_config() # create or update group config self._config, created = get_or_create( session, Config, d_vid=dataset.vid, type=self._top._type, parent=self._parent._config, group=self._key, key=self._key,dataset=dataset) self._top._add_valid(self._config) # create or update value config config, created = get_or_create( session, Config, parent=self._config, d_vid=dataset.vid, type=self._top._type, key=key,dataset=dataset) if config.value != value: # sync db value with term value. config.value = value session.merge(config) session.commit() logger.debug( 'Config bound to the VarDictGroup key updated. config: {}'.format(config)) self._top._add_valid(config)
python
def update_config(self, key, value): """ Creates or updates db config of the VarDictGroup. Requires bound to db tree. """ dataset = self._top._config.dataset session = object_session(self._top._config) logger.debug( 'Updating VarDictGroup config. dataset: {}, type: {}, key: {}, value: {}'.format( dataset, self._top._type, key, value)) if not self._parent._config: self._parent.update_config() # create or update group config self._config, created = get_or_create( session, Config, d_vid=dataset.vid, type=self._top._type, parent=self._parent._config, group=self._key, key=self._key,dataset=dataset) self._top._add_valid(self._config) # create or update value config config, created = get_or_create( session, Config, parent=self._config, d_vid=dataset.vid, type=self._top._type, key=key,dataset=dataset) if config.value != value: # sync db value with term value. config.value = value session.merge(config) session.commit() logger.debug( 'Config bound to the VarDictGroup key updated. config: {}'.format(config)) self._top._add_valid(config)
[ "def", "update_config", "(", "self", ",", "key", ",", "value", ")", ":", "dataset", "=", "self", ".", "_top", ".", "_config", ".", "dataset", "session", "=", "object_session", "(", "self", ".", "_top", ".", "_config", ")", "logger", ".", "debug", "(", ...
Creates or updates db config of the VarDictGroup. Requires bound to db tree.
[ "Creates", "or", "updates", "db", "config", "of", "the", "VarDictGroup", ".", "Requires", "bound", "to", "db", "tree", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L720-L751
CivicSpleen/ambry
ambry/metadata/proptree.py
Term.update_config
def update_config(self): """ Creates or updates db config of the term. Requires bound to db tree. """ dataset = self._top._config.dataset session = object_session(self._top._config) #logger.debug('Updating term config. dataset: {}, type: {}, key: {}, value: {}'.format( # dataset, self._top._type, self._key, self.get())) if not self._parent._config: self._parent.update_config() self._config, created = _get_config_instance( self, session, parent=self._parent._config, d_vid=dataset.vid, type=self._top._type, key=self._key, dataset=dataset) if created: self._top._cached_configs[self._get_path()] = self._config # We update ScalarTerm and ListTerm values only. Composite terms (DictTerm for example) # should not contain value. if isinstance(self, (ScalarTerm, ListTerm)): if self._config.value != self.get(): self._config.value = self.get() session.merge(self._config) session.commit() self._top._add_valid(self._config)
python
def update_config(self): """ Creates or updates db config of the term. Requires bound to db tree. """ dataset = self._top._config.dataset session = object_session(self._top._config) #logger.debug('Updating term config. dataset: {}, type: {}, key: {}, value: {}'.format( # dataset, self._top._type, self._key, self.get())) if not self._parent._config: self._parent.update_config() self._config, created = _get_config_instance( self, session, parent=self._parent._config, d_vid=dataset.vid, type=self._top._type, key=self._key, dataset=dataset) if created: self._top._cached_configs[self._get_path()] = self._config # We update ScalarTerm and ListTerm values only. Composite terms (DictTerm for example) # should not contain value. if isinstance(self, (ScalarTerm, ListTerm)): if self._config.value != self.get(): self._config.value = self.get() session.merge(self._config) session.commit() self._top._add_valid(self._config)
[ "def", "update_config", "(", "self", ")", ":", "dataset", "=", "self", ".", "_top", ".", "_config", ".", "dataset", "session", "=", "object_session", "(", "self", ".", "_top", ".", "_config", ")", "#logger.debug('Updating term config. dataset: {}, type: {}, key: {},...
Creates or updates db config of the term. Requires bound to db tree.
[ "Creates", "or", "updates", "db", "config", "of", "the", "term", ".", "Requires", "bound", "to", "db", "tree", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L792-L817
CivicSpleen/ambry
ambry/metadata/proptree.py
_ScalarTermS.text
def text(self): """Interpret the scalar as Markdown, strip the HTML and return text""" s = MLStripper() s.feed(self.html) return s.get_data()
python
def text(self): """Interpret the scalar as Markdown, strip the HTML and return text""" s = MLStripper() s.feed(self.html) return s.get_data()
[ "def", "text", "(", "self", ")", ":", "s", "=", "MLStripper", "(", ")", "s", ".", "feed", "(", "self", ".", "html", ")", "return", "s", ".", "get_data", "(", ")" ]
Interpret the scalar as Markdown, strip the HTML and return text
[ "Interpret", "the", "scalar", "as", "Markdown", "strip", "the", "HTML", "and", "return", "text" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/metadata/proptree.py#L890-L895
parkouss/rcontrol
rcontrol/streamreader.py
StreamsReader.start
def start(self, *args, **kwargs): """ Start to read the stream(s). """ queue = Queue() stdout_reader, stderr_reader = \ self._create_readers(queue, *args, **kwargs) self.thread = threading.Thread(target=self._read, args=(stdout_reader, stderr_reader, queue)) self.thread.daemon = True self.thread.start()
python
def start(self, *args, **kwargs): """ Start to read the stream(s). """ queue = Queue() stdout_reader, stderr_reader = \ self._create_readers(queue, *args, **kwargs) self.thread = threading.Thread(target=self._read, args=(stdout_reader, stderr_reader, queue)) self.thread.daemon = True self.thread.start()
[ "def", "start", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "queue", "=", "Queue", "(", ")", "stdout_reader", ",", "stderr_reader", "=", "self", ".", "_create_readers", "(", "queue", ",", "*", "args", ",", "*", "*", "kwargs", ...
Start to read the stream(s).
[ "Start", "to", "read", "the", "stream", "(", "s", ")", "." ]
train
https://github.com/parkouss/rcontrol/blob/1764c1492f00d3f1a57dabe09983ed369aade828/rcontrol/streamreader.py#L52-L65
SmartTeleMax/iktomi
iktomi/utils/__init__.py
quoteattrs
def quoteattrs(data): '''Takes dict of attributes and returns their HTML representation''' items = [] for key, value in data.items(): items.append('{}={}'.format(key, quoteattr(value))) return ' '.join(items)
python
def quoteattrs(data): '''Takes dict of attributes and returns their HTML representation''' items = [] for key, value in data.items(): items.append('{}={}'.format(key, quoteattr(value))) return ' '.join(items)
[ "def", "quoteattrs", "(", "data", ")", ":", "items", "=", "[", "]", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "items", ".", "append", "(", "'{}={}'", ".", "format", "(", "key", ",", "quoteattr", "(", "value", ")", ")"...
Takes dict of attributes and returns their HTML representation
[ "Takes", "dict", "of", "attributes", "and", "returns", "their", "HTML", "representation" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/utils/__init__.py#L16-L21
SmartTeleMax/iktomi
iktomi/utils/__init__.py
quote_js
def quote_js(text): '''Quotes text to be used as JavaScript string in HTML templates. The result doesn't contain surrounding quotes.''' if isinstance(text, six.binary_type): text = text.decode('utf-8') # for Jinja2 Markup text = text.replace('\\', '\\\\'); text = text.replace('\n', '\\n'); text = text.replace('\r', ''); for char in '\'"<>&': text = text.replace(char, '\\x{:02x}'.format(ord(char))) return text
python
def quote_js(text): '''Quotes text to be used as JavaScript string in HTML templates. The result doesn't contain surrounding quotes.''' if isinstance(text, six.binary_type): text = text.decode('utf-8') # for Jinja2 Markup text = text.replace('\\', '\\\\'); text = text.replace('\n', '\\n'); text = text.replace('\r', ''); for char in '\'"<>&': text = text.replace(char, '\\x{:02x}'.format(ord(char))) return text
[ "def", "quote_js", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "six", ".", "binary_type", ")", ":", "text", "=", "text", ".", "decode", "(", "'utf-8'", ")", "# for Jinja2 Markup", "text", "=", "text", ".", "replace", "(", "'\\\\'", ","...
Quotes text to be used as JavaScript string in HTML templates. The result doesn't contain surrounding quotes.
[ "Quotes", "text", "to", "be", "used", "as", "JavaScript", "string", "in", "HTML", "templates", ".", "The", "result", "doesn", "t", "contain", "surrounding", "quotes", "." ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/utils/__init__.py#L23-L33
sailthru/relay
relay/runner.py
create_ramp_plan
def create_ramp_plan(err, ramp): """ Formulate and execute on a plan to slowly add heat or cooling to the system `err` initial error (PV - SP) `ramp` the size of the ramp A ramp plan might yield MVs in this order at every timestep: [5, 0, 4, 0, 3, 0, 2, 0, 1] where err == 5 + 4 + 3 + 2 + 1 """ if ramp == 1: # basecase yield int(err) while True: yield 0 # np.arange(n).sum() == err # --> solve for n # err = (n - 1) * (n // 2) == .5 * n**2 - .5 * n # 0 = n**2 - n --> solve for n n = np.abs(np.roots([.5, -.5, 0]).max()) niter = int(ramp // (2 * n)) # 2 means add all MV in first half of ramp MV = n log.info('Initializing a ramp plan', extra=dict( ramp_size=ramp, err=err, niter=niter)) for x in range(int(n)): budget = MV for x in range(niter): budget -= MV // niter yield int(np.sign(err) * (MV // niter)) yield int(budget * np.sign(err)) MV -= 1 while True: yield 0
python
def create_ramp_plan(err, ramp): """ Formulate and execute on a plan to slowly add heat or cooling to the system `err` initial error (PV - SP) `ramp` the size of the ramp A ramp plan might yield MVs in this order at every timestep: [5, 0, 4, 0, 3, 0, 2, 0, 1] where err == 5 + 4 + 3 + 2 + 1 """ if ramp == 1: # basecase yield int(err) while True: yield 0 # np.arange(n).sum() == err # --> solve for n # err = (n - 1) * (n // 2) == .5 * n**2 - .5 * n # 0 = n**2 - n --> solve for n n = np.abs(np.roots([.5, -.5, 0]).max()) niter = int(ramp // (2 * n)) # 2 means add all MV in first half of ramp MV = n log.info('Initializing a ramp plan', extra=dict( ramp_size=ramp, err=err, niter=niter)) for x in range(int(n)): budget = MV for x in range(niter): budget -= MV // niter yield int(np.sign(err) * (MV // niter)) yield int(budget * np.sign(err)) MV -= 1 while True: yield 0
[ "def", "create_ramp_plan", "(", "err", ",", "ramp", ")", ":", "if", "ramp", "==", "1", ":", "# basecase", "yield", "int", "(", "err", ")", "while", "True", ":", "yield", "0", "# np.arange(n).sum() == err", "# --> solve for n", "# err = (n - 1) * (n // 2) == .5 * n...
Formulate and execute on a plan to slowly add heat or cooling to the system `err` initial error (PV - SP) `ramp` the size of the ramp A ramp plan might yield MVs in this order at every timestep: [5, 0, 4, 0, 3, 0, 2, 0, 1] where err == 5 + 4 + 3 + 2 + 1
[ "Formulate", "and", "execute", "on", "a", "plan", "to", "slowly", "add", "heat", "or", "cooling", "to", "the", "system" ]
train
https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/relay/runner.py#L69-L101
sailthru/relay
relay/runner.py
evaluate_stop_condition
def evaluate_stop_condition(errdata, stop_condition): """ Call the user-defined function: stop_condition(errdata) If the function returns -1, do nothing. Otherwise, sys.exit. """ if stop_condition: return_code = stop_condition(list(errdata)) if return_code != -1: log.info( 'Stop condition triggered! Relay is terminating.', extra=dict(return_code=return_code)) sys.exit(return_code)
python
def evaluate_stop_condition(errdata, stop_condition): """ Call the user-defined function: stop_condition(errdata) If the function returns -1, do nothing. Otherwise, sys.exit. """ if stop_condition: return_code = stop_condition(list(errdata)) if return_code != -1: log.info( 'Stop condition triggered! Relay is terminating.', extra=dict(return_code=return_code)) sys.exit(return_code)
[ "def", "evaluate_stop_condition", "(", "errdata", ",", "stop_condition", ")", ":", "if", "stop_condition", ":", "return_code", "=", "stop_condition", "(", "list", "(", "errdata", ")", ")", "if", "return_code", "!=", "-", "1", ":", "log", ".", "info", "(", ...
Call the user-defined function: stop_condition(errdata) If the function returns -1, do nothing. Otherwise, sys.exit.
[ "Call", "the", "user", "-", "defined", "function", ":", "stop_condition", "(", "errdata", ")", "If", "the", "function", "returns", "-", "1", "do", "nothing", ".", "Otherwise", "sys", ".", "exit", "." ]
train
https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/relay/runner.py#L117-L128
sailthru/relay
bin/code_linter.py
check
def check(codeString, filename): """ Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filename: C{str} @return: The number of warnings emitted. @rtype: C{int} """ # First, compile into an AST and handle syntax errors. try: tree = compile(codeString, filename, "exec", ast.PyCF_ONLY_AST) except SyntaxError, value: msg = value.args[0] (lineno, offset, text) = value.lineno, value.offset, value.text # If there's an encoding problem with the file, the text is None. if text is None: # Avoid using msg, since for the only known case, it contains a # bogus message that claims the encoding the file declared was # unknown. sys.stderr.write("%s: problem decoding source\n" % (filename, )) else: line = text.splitlines()[-1] if offset is not None: offset = offset - (len(text) - len(line)) sys.stderr.write('%s:%d: %s' % (filename, lineno, msg)) sys.stderr.write(line + '\n') if offset is not None: sys.stderr.write(" " * offset + "^\n") return 1 else: # Okay, it's syntactically valid. Now check it. w = checker.Checker(tree, filename) lines = codeString.split('\n') messages = [message for message in w.messages if lines[message.lineno - 1].find('pyflakes:ignore') < 0] messages.sort(lambda a, b: cmp(a.lineno, b.lineno)) false_positives = 0 for warning in messages: if not (re.match('.*__init__.py', str(warning)) and isinstance(warning, (UnusedImport, ImportStarUsed))): print(warning) else: false_positives += 1 return len(messages) - false_positives
python
def check(codeString, filename): """ Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filename: C{str} @return: The number of warnings emitted. @rtype: C{int} """ # First, compile into an AST and handle syntax errors. try: tree = compile(codeString, filename, "exec", ast.PyCF_ONLY_AST) except SyntaxError, value: msg = value.args[0] (lineno, offset, text) = value.lineno, value.offset, value.text # If there's an encoding problem with the file, the text is None. if text is None: # Avoid using msg, since for the only known case, it contains a # bogus message that claims the encoding the file declared was # unknown. sys.stderr.write("%s: problem decoding source\n" % (filename, )) else: line = text.splitlines()[-1] if offset is not None: offset = offset - (len(text) - len(line)) sys.stderr.write('%s:%d: %s' % (filename, lineno, msg)) sys.stderr.write(line + '\n') if offset is not None: sys.stderr.write(" " * offset + "^\n") return 1 else: # Okay, it's syntactically valid. Now check it. w = checker.Checker(tree, filename) lines = codeString.split('\n') messages = [message for message in w.messages if lines[message.lineno - 1].find('pyflakes:ignore') < 0] messages.sort(lambda a, b: cmp(a.lineno, b.lineno)) false_positives = 0 for warning in messages: if not (re.match('.*__init__.py', str(warning)) and isinstance(warning, (UnusedImport, ImportStarUsed))): print(warning) else: false_positives += 1 return len(messages) - false_positives
[ "def", "check", "(", "codeString", ",", "filename", ")", ":", "# First, compile into an AST and handle syntax errors.", "try", ":", "tree", "=", "compile", "(", "codeString", ",", "filename", ",", "\"exec\"", ",", "ast", ".", "PyCF_ONLY_AST", ")", "except", "Synta...
Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filename: C{str} @return: The number of warnings emitted. @rtype: C{int}
[ "Check", "the", "Python", "source", "given", "by", "C", "{", "codeString", "}", "for", "flakes", "." ]
train
https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/bin/code_linter.py#L22-L77
sailthru/relay
bin/code_linter.py
checkPath
def checkPath(filename): """ Check the given path, printing out any warnings detected. @return: the number of warnings printed """ try: return check(file(filename, 'U').read() + '\n', filename) except IOError, msg: sys.stderr.write("%s: %s\n" % (filename, msg.args[1])) return 1
python
def checkPath(filename): """ Check the given path, printing out any warnings detected. @return: the number of warnings printed """ try: return check(file(filename, 'U').read() + '\n', filename) except IOError, msg: sys.stderr.write("%s: %s\n" % (filename, msg.args[1])) return 1
[ "def", "checkPath", "(", "filename", ")", ":", "try", ":", "return", "check", "(", "file", "(", "filename", ",", "'U'", ")", ".", "read", "(", ")", "+", "'\\n'", ",", "filename", ")", "except", "IOError", ",", "msg", ":", "sys", ".", "stderr", ".",...
Check the given path, printing out any warnings detected. @return: the number of warnings printed
[ "Check", "the", "given", "path", "printing", "out", "any", "warnings", "detected", "." ]
train
https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/bin/code_linter.py#L80-L90
SmartTeleMax/iktomi
iktomi/forms/fields.py
BaseField.clean_value
def clean_value(self): ''' Current field's converted value from form's python_data. ''' # XXX cached_property is used only for set initial state # this property should be set every time field data # has been changed, for instance, in accept method python_data = self.parent.python_data if self.name in python_data: return python_data[self.name] return self.get_initial()
python
def clean_value(self): ''' Current field's converted value from form's python_data. ''' # XXX cached_property is used only for set initial state # this property should be set every time field data # has been changed, for instance, in accept method python_data = self.parent.python_data if self.name in python_data: return python_data[self.name] return self.get_initial()
[ "def", "clean_value", "(", "self", ")", ":", "# XXX cached_property is used only for set initial state", "# this property should be set every time field data", "# has been changed, for instance, in accept method", "python_data", "=", "self", ".", "parent", ".", "python_data", ...
Current field's converted value from form's python_data.
[ "Current", "field", "s", "converted", "value", "from", "form", "s", "python_data", "." ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/fields.py#L105-L115
SmartTeleMax/iktomi
iktomi/forms/fields.py
Field.accept
def accept(self): '''Extracts raw value from form's raw data and passes it to converter''' value = self.raw_value if not self._check_value_type(value): # XXX should this be silent or TypeError? value = [] if self.multiple else self._null_value self.clean_value = self.conv.accept(value) return {self.name: self.clean_value}
python
def accept(self): '''Extracts raw value from form's raw data and passes it to converter''' value = self.raw_value if not self._check_value_type(value): # XXX should this be silent or TypeError? value = [] if self.multiple else self._null_value self.clean_value = self.conv.accept(value) return {self.name: self.clean_value}
[ "def", "accept", "(", "self", ")", ":", "value", "=", "self", ".", "raw_value", "if", "not", "self", ".", "_check_value_type", "(", "value", ")", ":", "# XXX should this be silent or TypeError?", "value", "=", "[", "]", "if", "self", ".", "multiple", "else",...
Extracts raw value from form's raw data and passes it to converter
[ "Extracts", "raw", "value", "from", "form", "s", "raw", "data", "and", "passes", "it", "to", "converter" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/fields.py#L202-L209
SmartTeleMax/iktomi
iktomi/forms/fields.py
AggregateField.python_data
def python_data(self): '''Representation of aggregate value as dictionary.''' try: value = self.clean_value except LookupError: # XXX is this necessary? value = self.get_initial() return self.from_python(value)
python
def python_data(self): '''Representation of aggregate value as dictionary.''' try: value = self.clean_value except LookupError: # XXX is this necessary? value = self.get_initial() return self.from_python(value)
[ "def", "python_data", "(", "self", ")", ":", "try", ":", "value", "=", "self", ".", "clean_value", "except", "LookupError", ":", "# XXX is this necessary?", "value", "=", "self", ".", "get_initial", "(", ")", "return", "self", ".", "from_python", "(", "value...
Representation of aggregate value as dictionary.
[ "Representation", "of", "aggregate", "value", "as", "dictionary", "." ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/fields.py#L215-L222
SmartTeleMax/iktomi
iktomi/forms/fields.py
FieldSet.accept
def accept(self): ''' Accepts all children fields, collects resulting values into dict and passes that dict to converter. Returns result of converter as separate value in parent `python_data` ''' result = dict(self.python_data) for field in self.fields: if field.writable: result.update(field.accept()) else: # readonly field field.set_raw_value(self.form.raw_data, field.from_python(result[field.name])) self.clean_value = self.conv.accept(result) return {self.name: self.clean_value}
python
def accept(self): ''' Accepts all children fields, collects resulting values into dict and passes that dict to converter. Returns result of converter as separate value in parent `python_data` ''' result = dict(self.python_data) for field in self.fields: if field.writable: result.update(field.accept()) else: # readonly field field.set_raw_value(self.form.raw_data, field.from_python(result[field.name])) self.clean_value = self.conv.accept(result) return {self.name: self.clean_value}
[ "def", "accept", "(", "self", ")", ":", "result", "=", "dict", "(", "self", ".", "python_data", ")", "for", "field", "in", "self", ".", "fields", ":", "if", "field", ".", "writable", ":", "result", ".", "update", "(", "field", ".", "accept", "(", "...
Accepts all children fields, collects resulting values into dict and passes that dict to converter. Returns result of converter as separate value in parent `python_data`
[ "Accepts", "all", "children", "fields", "collects", "resulting", "values", "into", "dict", "and", "passes", "that", "dict", "to", "converter", "." ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/fields.py#L282-L298
SmartTeleMax/iktomi
iktomi/forms/fields.py
FieldBlock.accept
def accept(self): ''' Acts as `Field.accepts` but returns result of every child field as value in parent `python_data`. ''' result = FieldSet.accept(self) self.clean_value = result[self.name] return self.clean_value
python
def accept(self): ''' Acts as `Field.accepts` but returns result of every child field as value in parent `python_data`. ''' result = FieldSet.accept(self) self.clean_value = result[self.name] return self.clean_value
[ "def", "accept", "(", "self", ")", ":", "result", "=", "FieldSet", ".", "accept", "(", "self", ")", "self", ".", "clean_value", "=", "result", "[", "self", ".", "name", "]", "return", "self", ".", "clean_value" ]
Acts as `Field.accepts` but returns result of every child field as value in parent `python_data`.
[ "Acts", "as", "Field", ".", "accepts", "but", "returns", "result", "of", "every", "child", "field", "as", "value", "in", "parent", "python_data", "." ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/fields.py#L327-L334
cosven/feeluown-core
fuocore/pubsub.py
handle
def handle(conn, addr, gateway, *args, **kwargs): """ NOTE: use tcp instead of udp because some operations need ack """ conn.sendall(b'OK pubsub 1.0\n') while True: try: s = conn.recv(1024).decode('utf-8').strip() if not s: conn.close() break except ConnectionResetError: logger.debug('Client close the connection.') break parts = s.split(' ') if len(parts) != 2: conn.send(b"Invalid command\n") continue cmd, topic = parts if cmd.lower() != 'sub': conn.send(bytes("Unknown command '{}'\n".format(cmd.lower()), 'utf-8')) continue if topic not in gateway.topics: conn.send(bytes("Unknown topic '{}'\n".format(topic), 'utf-8')) continue conn.sendall(bytes('ACK {} {}\n'.format(cmd, topic), 'utf-8')) subscriber = Subscriber(addr, conn) gateway.link(topic, subscriber) break
python
def handle(conn, addr, gateway, *args, **kwargs): """ NOTE: use tcp instead of udp because some operations need ack """ conn.sendall(b'OK pubsub 1.0\n') while True: try: s = conn.recv(1024).decode('utf-8').strip() if not s: conn.close() break except ConnectionResetError: logger.debug('Client close the connection.') break parts = s.split(' ') if len(parts) != 2: conn.send(b"Invalid command\n") continue cmd, topic = parts if cmd.lower() != 'sub': conn.send(bytes("Unknown command '{}'\n".format(cmd.lower()), 'utf-8')) continue if topic not in gateway.topics: conn.send(bytes("Unknown topic '{}'\n".format(topic), 'utf-8')) continue conn.sendall(bytes('ACK {} {}\n'.format(cmd, topic), 'utf-8')) subscriber = Subscriber(addr, conn) gateway.link(topic, subscriber) break
[ "def", "handle", "(", "conn", ",", "addr", ",", "gateway", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "conn", ".", "sendall", "(", "b'OK pubsub 1.0\\n'", ")", "while", "True", ":", "try", ":", "s", "=", "conn", ".", "recv", "(", "1024", ...
NOTE: use tcp instead of udp because some operations need ack
[ "NOTE", ":", "use", "tcp", "instead", "of", "udp", "because", "some", "operations", "need", "ack" ]
train
https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/pubsub.py#L72-L101
alvations/lazyme
lazyme/fileio.py
find_files
def find_files(dir_path, extension="*"): """ From https://stackoverflow.com/a/2186565/610569 """ if sys.version_info.major == 3 and sys.version_info.minor >= 5: pattern = '/'.join([dir_path, '**', extension]) for filename in glob.iglob(pattern, recursive=True): yield filename else: for root, dirnames, filenames in os.walk(dir_path): for filename in fnmatch.filter(filenames, extension): yield os.path.join(root, filename)
python
def find_files(dir_path, extension="*"): """ From https://stackoverflow.com/a/2186565/610569 """ if sys.version_info.major == 3 and sys.version_info.minor >= 5: pattern = '/'.join([dir_path, '**', extension]) for filename in glob.iglob(pattern, recursive=True): yield filename else: for root, dirnames, filenames in os.walk(dir_path): for filename in fnmatch.filter(filenames, extension): yield os.path.join(root, filename)
[ "def", "find_files", "(", "dir_path", ",", "extension", "=", "\"*\"", ")", ":", "if", "sys", ".", "version_info", ".", "major", "==", "3", "and", "sys", ".", "version_info", ".", "minor", ">=", "5", ":", "pattern", "=", "'/'", ".", "join", "(", "[", ...
From https://stackoverflow.com/a/2186565/610569
[ "From", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "2186565", "/", "610569" ]
train
https://github.com/alvations/lazyme/blob/961a8282198588ff72e15643f725ce895e51d06d/lazyme/fileio.py#L9-L20
CodeReclaimers/btce-api
btceapi/public.py
getTicker
def getTicker(pair, connection=None, info=None): """Retrieve the ticker for the given pair. Returns a Ticker instance.""" if info is not None: info.validate_pair(pair) if connection is None: connection = common.BTCEConnection() response = connection.makeJSONRequest("/api/3/ticker/%s" % pair) if type(response) is not dict: raise TypeError("The response is a %r, not a dict." % type(response)) elif u'error' in response: print("There is a error \"%s\" while obtaining ticker %s" % (response['error'], pair)) ticker = None else: ticker = Ticker(**response[pair]) return ticker
python
def getTicker(pair, connection=None, info=None): """Retrieve the ticker for the given pair. Returns a Ticker instance.""" if info is not None: info.validate_pair(pair) if connection is None: connection = common.BTCEConnection() response = connection.makeJSONRequest("/api/3/ticker/%s" % pair) if type(response) is not dict: raise TypeError("The response is a %r, not a dict." % type(response)) elif u'error' in response: print("There is a error \"%s\" while obtaining ticker %s" % (response['error'], pair)) ticker = None else: ticker = Ticker(**response[pair]) return ticker
[ "def", "getTicker", "(", "pair", ",", "connection", "=", "None", ",", "info", "=", "None", ")", ":", "if", "info", "is", "not", "None", ":", "info", ".", "validate_pair", "(", "pair", ")", "if", "connection", "is", "None", ":", "connection", "=", "co...
Retrieve the ticker for the given pair. Returns a Ticker instance.
[ "Retrieve", "the", "ticker", "for", "the", "given", "pair", ".", "Returns", "a", "Ticker", "instance", "." ]
train
https://github.com/CodeReclaimers/btce-api/blob/cdf7da694261edf64b32af46e7ce9b701cad7dee/btceapi/public.py#L124-L143
CodeReclaimers/btce-api
btceapi/public.py
getDepth
def getDepth(pair, connection=None, info=None): """Retrieve the depth for the given pair. Returns a tuple (asks, bids); each of these is a list of (price, volume) tuples.""" if info is not None: info.validate_pair(pair) if connection is None: connection = common.BTCEConnection() response = connection.makeJSONRequest("/api/3/depth/%s" % pair) if type(response) is not dict: raise TypeError("The response is not a dict.") depth = response.get(pair) if type(depth) is not dict: raise TypeError("The pair depth is not a dict.") asks = depth.get(u'asks') if type(asks) is not list: raise TypeError("The response does not contain an asks list.") bids = depth.get(u'bids') if type(bids) is not list: raise TypeError("The response does not contain a bids list.") return asks, bids
python
def getDepth(pair, connection=None, info=None): """Retrieve the depth for the given pair. Returns a tuple (asks, bids); each of these is a list of (price, volume) tuples.""" if info is not None: info.validate_pair(pair) if connection is None: connection = common.BTCEConnection() response = connection.makeJSONRequest("/api/3/depth/%s" % pair) if type(response) is not dict: raise TypeError("The response is not a dict.") depth = response.get(pair) if type(depth) is not dict: raise TypeError("The pair depth is not a dict.") asks = depth.get(u'asks') if type(asks) is not list: raise TypeError("The response does not contain an asks list.") bids = depth.get(u'bids') if type(bids) is not list: raise TypeError("The response does not contain a bids list.") return asks, bids
[ "def", "getDepth", "(", "pair", ",", "connection", "=", "None", ",", "info", "=", "None", ")", ":", "if", "info", "is", "not", "None", ":", "info", ".", "validate_pair", "(", "pair", ")", "if", "connection", "is", "None", ":", "connection", "=", "com...
Retrieve the depth for the given pair. Returns a tuple (asks, bids); each of these is a list of (price, volume) tuples.
[ "Retrieve", "the", "depth", "for", "the", "given", "pair", ".", "Returns", "a", "tuple", "(", "asks", "bids", ")", ";", "each", "of", "these", "is", "a", "list", "of", "(", "price", "volume", ")", "tuples", "." ]
train
https://github.com/CodeReclaimers/btce-api/blob/cdf7da694261edf64b32af46e7ce9b701cad7dee/btceapi/public.py#L146-L172
CodeReclaimers/btce-api
btceapi/public.py
getTradeHistory
def getTradeHistory(pair, connection=None, info=None, count=None): """Retrieve the trade history for the given pair. Returns a list of Trade instances. If count is not None, it should be an integer, and specifies the number of items from the trade history that will be processed and returned.""" if info is not None: info.validate_pair(pair) if connection is None: connection = common.BTCEConnection() response = connection.makeJSONRequest("/api/3/trades/%s" % pair) if type(response) is not dict: raise TypeError("The response is not a dict.") history = response.get(pair) if type(history) is not list: raise TypeError("The response is a %r, not a list." % type(history)) result = [] # Limit the number of items returned if requested. if count is not None: history = history[:count] for h in history: h["pair"] = pair t = Trade(**h) result.append(t) return result
python
def getTradeHistory(pair, connection=None, info=None, count=None): """Retrieve the trade history for the given pair. Returns a list of Trade instances. If count is not None, it should be an integer, and specifies the number of items from the trade history that will be processed and returned.""" if info is not None: info.validate_pair(pair) if connection is None: connection = common.BTCEConnection() response = connection.makeJSONRequest("/api/3/trades/%s" % pair) if type(response) is not dict: raise TypeError("The response is not a dict.") history = response.get(pair) if type(history) is not list: raise TypeError("The response is a %r, not a list." % type(history)) result = [] # Limit the number of items returned if requested. if count is not None: history = history[:count] for h in history: h["pair"] = pair t = Trade(**h) result.append(t) return result
[ "def", "getTradeHistory", "(", "pair", ",", "connection", "=", "None", ",", "info", "=", "None", ",", "count", "=", "None", ")", ":", "if", "info", "is", "not", "None", ":", "info", ".", "validate_pair", "(", "pair", ")", "if", "connection", "is", "N...
Retrieve the trade history for the given pair. Returns a list of Trade instances. If count is not None, it should be an integer, and specifies the number of items from the trade history that will be processed and returned.
[ "Retrieve", "the", "trade", "history", "for", "the", "given", "pair", ".", "Returns", "a", "list", "of", "Trade", "instances", ".", "If", "count", "is", "not", "None", "it", "should", "be", "an", "integer", "and", "specifies", "the", "number", "of", "ite...
train
https://github.com/CodeReclaimers/btce-api/blob/cdf7da694261edf64b32af46e7ce9b701cad7dee/btceapi/public.py#L178-L208
CivicSpleen/ambry
ambry/bundle/files.py
BuildSourceFile.default
def default(self): """Return default contents""" import ambry.bundle.default_files as df import os path = os.path.join(os.path.dirname(df.__file__), self.file_name) if six.PY2: with open(path, 'rb') as f: return f.read() else: # py3 with open(path, 'rt', encoding='utf-8') as f: return f.read()
python
def default(self): """Return default contents""" import ambry.bundle.default_files as df import os path = os.path.join(os.path.dirname(df.__file__), self.file_name) if six.PY2: with open(path, 'rb') as f: return f.read() else: # py3 with open(path, 'rt', encoding='utf-8') as f: return f.read()
[ "def", "default", "(", "self", ")", ":", "import", "ambry", ".", "bundle", ".", "default_files", "as", "df", "import", "os", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "df", ".", "__file__", ")", ",", ...
Return default contents
[ "Return", "default", "contents" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L136-L150
CivicSpleen/ambry
ambry/bundle/files.py
BuildSourceFile.remove
def remove(self): """ Removes file from filesystem. """ from fs.errors import ResourceNotFoundError try: self._fs.remove(self.file_name) except ResourceNotFoundError: pass
python
def remove(self): """ Removes file from filesystem. """ from fs.errors import ResourceNotFoundError try: self._fs.remove(self.file_name) except ResourceNotFoundError: pass
[ "def", "remove", "(", "self", ")", ":", "from", "fs", ".", "errors", "import", "ResourceNotFoundError", "try", ":", "self", ".", "_fs", ".", "remove", "(", "self", ".", "file_name", ")", "except", "ResourceNotFoundError", ":", "pass" ]
Removes file from filesystem.
[ "Removes", "file", "from", "filesystem", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L160-L167
CivicSpleen/ambry
ambry/bundle/files.py
BuildSourceFile.sync_dir
def sync_dir(self): """ Report on which direction a synchronization should be done. :return: """ # NOTE: These are ordered so the FILE_TO_RECORD has preference over RECORD_TO_FILE # if there is a conflict. if self.exists() and bool(self.size()) and not self.record.size: # The fs exists, but the record is empty return self.SYNC_DIR.FILE_TO_RECORD if (self.fs_modtime or 0) > (self.record.modified or 0) and self.record.source_hash != self.fs_hash: # Filesystem is newer return self.SYNC_DIR.FILE_TO_RECORD if self.record.size and not self.exists(): # Record exists, but not the FS return self.SYNC_DIR.RECORD_TO_FILE if (self.record.modified or 0) > (self.fs_modtime or 0): # Record is newer return self.SYNC_DIR.RECORD_TO_FILE return None
python
def sync_dir(self): """ Report on which direction a synchronization should be done. :return: """ # NOTE: These are ordered so the FILE_TO_RECORD has preference over RECORD_TO_FILE # if there is a conflict. if self.exists() and bool(self.size()) and not self.record.size: # The fs exists, but the record is empty return self.SYNC_DIR.FILE_TO_RECORD if (self.fs_modtime or 0) > (self.record.modified or 0) and self.record.source_hash != self.fs_hash: # Filesystem is newer return self.SYNC_DIR.FILE_TO_RECORD if self.record.size and not self.exists(): # Record exists, but not the FS return self.SYNC_DIR.RECORD_TO_FILE if (self.record.modified or 0) > (self.fs_modtime or 0): # Record is newer return self.SYNC_DIR.RECORD_TO_FILE return None
[ "def", "sync_dir", "(", "self", ")", ":", "# NOTE: These are ordered so the FILE_TO_RECORD has preference over RECORD_TO_FILE", "# if there is a conflict.", "if", "self", ".", "exists", "(", ")", "and", "bool", "(", "self", ".", "size", "(", ")", ")", "and", "not", ...
Report on which direction a synchronization should be done. :return:
[ "Report", "on", "which", "direction", "a", "synchronization", "should", "be", "done", ".", ":", "return", ":" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L219-L245
CivicSpleen/ambry
ambry/bundle/files.py
BuildSourceFile.sync
def sync(self, force=None): """Synchronize between the file in the file system and the field record""" try: if force: sd = force else: sd = self.sync_dir() if sd == self.SYNC_DIR.FILE_TO_RECORD: if force and not self.exists(): return None self.fs_to_record() elif sd == self.SYNC_DIR.RECORD_TO_FILE: self.record_to_fs() else: return None self._dataset.config.sync[self.file_const][sd] = time.time() return sd except Exception as e: self._bundle.rollback() self._bundle.error("Failed to sync '{}': {}".format(self.file_const, e)) raise
python
def sync(self, force=None): """Synchronize between the file in the file system and the field record""" try: if force: sd = force else: sd = self.sync_dir() if sd == self.SYNC_DIR.FILE_TO_RECORD: if force and not self.exists(): return None self.fs_to_record() elif sd == self.SYNC_DIR.RECORD_TO_FILE: self.record_to_fs() else: return None self._dataset.config.sync[self.file_const][sd] = time.time() return sd except Exception as e: self._bundle.rollback() self._bundle.error("Failed to sync '{}': {}".format(self.file_const, e)) raise
[ "def", "sync", "(", "self", ",", "force", "=", "None", ")", ":", "try", ":", "if", "force", ":", "sd", "=", "force", "else", ":", "sd", "=", "self", ".", "sync_dir", "(", ")", "if", "sd", "==", "self", ".", "SYNC_DIR", ".", "FILE_TO_RECORD", ":",...
Synchronize between the file in the file system and the field record
[ "Synchronize", "between", "the", "file", "in", "the", "file", "system", "and", "the", "field", "record" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L247-L274
CivicSpleen/ambry
ambry/bundle/files.py
RowBuildSourceFile.fh_to_record
def fh_to_record(self, f): """Load a file in the filesystem into the file record""" import unicodecsv as csv fn_path = self.file_name fr = self.record fr.path = fn_path rows = [] # NOTE. There were two cases here, for PY2 and PY3. Py two had # encoding='utf-8' in the reader. I've combined them b/c that's the default for # unicode csv, so it shouldn't be necessary. # Should probably be something like this: #if sys.version_info[0] >= 3: # Python 3 # import csv # f = open(self._fstor.syspath, 'rtU', encoding=encoding) # reader = csv.reader(f) #else: # Python 2 # import unicodecsv as csv # f = open(self._fstor.syspath, 'rbU') # reader = csv.reader(f, encoding=encoding) for row in csv.reader(f): row = [e if e.strip() != '' else None for e in row] if any(bool(e) for e in row): rows.append(row) try: fr.update_contents(msgpack.packb(rows), 'application/msgpack') except AssertionError: raise fr.source_hash = self.fs_hash fr.synced_fs = self.fs_modtime fr.modified = self.fs_modtime
python
def fh_to_record(self, f): """Load a file in the filesystem into the file record""" import unicodecsv as csv fn_path = self.file_name fr = self.record fr.path = fn_path rows = [] # NOTE. There were two cases here, for PY2 and PY3. Py two had # encoding='utf-8' in the reader. I've combined them b/c that's the default for # unicode csv, so it shouldn't be necessary. # Should probably be something like this: #if sys.version_info[0] >= 3: # Python 3 # import csv # f = open(self._fstor.syspath, 'rtU', encoding=encoding) # reader = csv.reader(f) #else: # Python 2 # import unicodecsv as csv # f = open(self._fstor.syspath, 'rbU') # reader = csv.reader(f, encoding=encoding) for row in csv.reader(f): row = [e if e.strip() != '' else None for e in row] if any(bool(e) for e in row): rows.append(row) try: fr.update_contents(msgpack.packb(rows), 'application/msgpack') except AssertionError: raise fr.source_hash = self.fs_hash fr.synced_fs = self.fs_modtime fr.modified = self.fs_modtime
[ "def", "fh_to_record", "(", "self", ",", "f", ")", ":", "import", "unicodecsv", "as", "csv", "fn_path", "=", "self", ".", "file_name", "fr", "=", "self", ".", "record", "fr", ".", "path", "=", "fn_path", "rows", "=", "[", "]", "# NOTE. There were two cas...
Load a file in the filesystem into the file record
[ "Load", "a", "file", "in", "the", "filesystem", "into", "the", "file", "record" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L353-L388
CivicSpleen/ambry
ambry/bundle/files.py
RowBuildSourceFile.record_to_fs
def record_to_fs(self): """Create a filesystem file from a File""" fr = self.record fn_path = self.file_name if fr.contents: if six.PY2: with self._fs.open(fn_path, 'wb') as f: self.record_to_fh(f) else: # py3 with self._fs.open(fn_path, 'w', newline='') as f: self.record_to_fh(f)
python
def record_to_fs(self): """Create a filesystem file from a File""" fr = self.record fn_path = self.file_name if fr.contents: if six.PY2: with self._fs.open(fn_path, 'wb') as f: self.record_to_fh(f) else: # py3 with self._fs.open(fn_path, 'w', newline='') as f: self.record_to_fh(f)
[ "def", "record_to_fs", "(", "self", ")", ":", "fr", "=", "self", ".", "record", "fn_path", "=", "self", ".", "file_name", "if", "fr", ".", "contents", ":", "if", "six", ".", "PY2", ":", "with", "self", ".", "_fs", ".", "open", "(", "fn_path", ",", ...
Create a filesystem file from a File
[ "Create", "a", "filesystem", "file", "from", "a", "File" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L414-L428
CivicSpleen/ambry
ambry/bundle/files.py
DictBuildSourceFile.record_to_fh
def record_to_fh(self, f): """Write the record, in filesystem format, to a file handle or file object""" fr = self.record if fr.contents: yaml.safe_dump(fr.unpacked_contents, f, default_flow_style=False, encoding='utf-8') fr.source_hash = self.fs_hash fr.modified = self.fs_modtime
python
def record_to_fh(self, f): """Write the record, in filesystem format, to a file handle or file object""" fr = self.record if fr.contents: yaml.safe_dump(fr.unpacked_contents, f, default_flow_style=False, encoding='utf-8') fr.source_hash = self.fs_hash fr.modified = self.fs_modtime
[ "def", "record_to_fh", "(", "self", ",", "f", ")", ":", "fr", "=", "self", ".", "record", "if", "fr", ".", "contents", ":", "yaml", ".", "safe_dump", "(", "fr", ".", "unpacked_contents", ",", "f", ",", "default_flow_style", "=", "False", ",", "encoding...
Write the record, in filesystem format, to a file handle or file object
[ "Write", "the", "record", "in", "filesystem", "format", "to", "a", "file", "handle", "or", "file", "object" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L458-L466
CivicSpleen/ambry
ambry/bundle/files.py
StringSourceFile.fh_to_record
def fh_to_record(self, f): """Load a file in the filesystem into the file record""" fn_path = self.file_name fr = self.record fr.path = fn_path fr.update_contents(f.read(), 'text/plain') fr.source_hash = self.fs_hash fr.synced_fs = self.fs_modtime fr.modified = self.fs_modtime
python
def fh_to_record(self, f): """Load a file in the filesystem into the file record""" fn_path = self.file_name fr = self.record fr.path = fn_path fr.update_contents(f.read(), 'text/plain') fr.source_hash = self.fs_hash fr.synced_fs = self.fs_modtime fr.modified = self.fs_modtime
[ "def", "fh_to_record", "(", "self", ",", "f", ")", ":", "fn_path", "=", "self", ".", "file_name", "fr", "=", "self", ".", "record", "fr", ".", "path", "=", "fn_path", "fr", ".", "update_contents", "(", "f", ".", "read", "(", ")", ",", "'text/plain'",...
Load a file in the filesystem into the file record
[ "Load", "a", "file", "in", "the", "filesystem", "into", "the", "file", "record" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L501-L512
CivicSpleen/ambry
ambry/bundle/files.py
MetadataFile.record_to_objects
def record_to_objects(self): """Create config records to match the file metadata""" from ..util import AttrDict fr = self.record contents = fr.unpacked_contents if not contents: return ad = AttrDict(contents) # Get time that filessystem was synchronized to the File record. # Maybe use this to avoid overwriting configs that changed by bundle program. # fs_sync_time = self._dataset.config.sync[self.file_const][self.file_to_record] self._dataset.config.metadata.set(ad) self._dataset._database.commit() return ad
python
def record_to_objects(self): """Create config records to match the file metadata""" from ..util import AttrDict fr = self.record contents = fr.unpacked_contents if not contents: return ad = AttrDict(contents) # Get time that filessystem was synchronized to the File record. # Maybe use this to avoid overwriting configs that changed by bundle program. # fs_sync_time = self._dataset.config.sync[self.file_const][self.file_to_record] self._dataset.config.metadata.set(ad) self._dataset._database.commit() return ad
[ "def", "record_to_objects", "(", "self", ")", ":", "from", ".", ".", "util", "import", "AttrDict", "fr", "=", "self", ".", "record", "contents", "=", "fr", ".", "unpacked_contents", "if", "not", "contents", ":", "return", "ad", "=", "AttrDict", "(", "con...
Create config records to match the file metadata
[ "Create", "config", "records", "to", "match", "the", "file", "metadata" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L549-L571
CivicSpleen/ambry
ambry/bundle/files.py
MetadataFile.objects_to_record
def objects_to_record(self): """Write from object metadata to the record. Note that we don't write everything""" o = self.get_object() o.about = self._bundle.metadata.about o.identity = self._dataset.identity.ident_dict o.names = self._dataset.identity.names_dict o.contacts = self._bundle.metadata.contacts self.set_object(o)
python
def objects_to_record(self): """Write from object metadata to the record. Note that we don't write everything""" o = self.get_object() o.about = self._bundle.metadata.about o.identity = self._dataset.identity.ident_dict o.names = self._dataset.identity.names_dict o.contacts = self._bundle.metadata.contacts self.set_object(o)
[ "def", "objects_to_record", "(", "self", ")", ":", "o", "=", "self", ".", "get_object", "(", ")", "o", ".", "about", "=", "self", ".", "_bundle", ".", "metadata", ".", "about", "o", ".", "identity", "=", "self", ".", "_dataset", ".", "identity", ".",...
Write from object metadata to the record. Note that we don't write everything
[ "Write", "from", "object", "metadata", "to", "the", "record", ".", "Note", "that", "we", "don", "t", "write", "everything" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L573-L583
CivicSpleen/ambry
ambry/bundle/files.py
MetadataFile.update_identity
def update_identity(self): """Update the identity and names to match the dataset id and version""" fr = self.record d = fr.unpacked_contents d['identity'] = self._dataset.identity.ident_dict d['names'] = self._dataset.identity.names_dict fr.update_contents(msgpack.packb(d), 'application/msgpack')
python
def update_identity(self): """Update the identity and names to match the dataset id and version""" fr = self.record d = fr.unpacked_contents d['identity'] = self._dataset.identity.ident_dict d['names'] = self._dataset.identity.names_dict fr.update_contents(msgpack.packb(d), 'application/msgpack')
[ "def", "update_identity", "(", "self", ")", ":", "fr", "=", "self", ".", "record", "d", "=", "fr", ".", "unpacked_contents", "d", "[", "'identity'", "]", "=", "self", ".", "_dataset", ".", "identity", ".", "ident_dict", "d", "[", "'names'", "]", "=", ...
Update the identity and names to match the dataset id and version
[ "Update", "the", "identity", "and", "names", "to", "match", "the", "dataset", "id", "and", "version" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L613-L623
CivicSpleen/ambry
ambry/bundle/files.py
MetadataFile.get_object
def get_object(self): """Return contents in object form, an AttrDict""" from ..util import AttrDict c = self.record.unpacked_contents if not c: c = yaml.safe_load(self.default) return AttrDict(c)
python
def get_object(self): """Return contents in object form, an AttrDict""" from ..util import AttrDict c = self.record.unpacked_contents if not c: c = yaml.safe_load(self.default) return AttrDict(c)
[ "def", "get_object", "(", "self", ")", ":", "from", ".", ".", "util", "import", "AttrDict", "c", "=", "self", ".", "record", ".", "unpacked_contents", "if", "not", "c", ":", "c", "=", "yaml", ".", "safe_load", "(", "self", ".", "default", ")", "retur...
Return contents in object form, an AttrDict
[ "Return", "contents", "in", "object", "form", "an", "AttrDict" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L625-L635
CivicSpleen/ambry
ambry/bundle/files.py
NotebookFile.default
def default(self): """Return default contents""" import json import ambry.bundle.default_files as df import os path = os.path.join(os.path.dirname(df.__file__), 'notebook.ipynb') if six.PY2: with open(path, 'rb') as f: content_str = f.read() else: # py3 with open(path, 'rt', encoding='utf-8') as f: content_str = f.read() c = json.loads(content_str) context = { 'title': self._bundle.metadata.about.title, 'summary': self._bundle.metadata.about.title, 'bundle_vname': self._bundle.identity.vname } for cell in c['cells']: for i in range(len(cell['source'])): cell['source'][i] = cell['source'][i].format(**context) c['metadata']['ambry'] = { 'identity': self._bundle.identity.dict } return json.dumps(c, indent=4)
python
def default(self): """Return default contents""" import json import ambry.bundle.default_files as df import os path = os.path.join(os.path.dirname(df.__file__), 'notebook.ipynb') if six.PY2: with open(path, 'rb') as f: content_str = f.read() else: # py3 with open(path, 'rt', encoding='utf-8') as f: content_str = f.read() c = json.loads(content_str) context = { 'title': self._bundle.metadata.about.title, 'summary': self._bundle.metadata.about.title, 'bundle_vname': self._bundle.identity.vname } for cell in c['cells']: for i in range(len(cell['source'])): cell['source'][i] = cell['source'][i].format(**context) c['metadata']['ambry'] = { 'identity': self._bundle.identity.dict } return json.dumps(c, indent=4)
[ "def", "default", "(", "self", ")", ":", "import", "json", "import", "ambry", ".", "bundle", ".", "default_files", "as", "df", "import", "os", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "df", ".", "__f...
Return default contents
[ "Return", "default", "contents" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L650-L683
CivicSpleen/ambry
ambry/bundle/files.py
NotebookFile.execute
def execute(self): """Convert the notebook to a python script and execute it, returning the local context as a dict""" from nbformat import read from nbconvert.exporters import export_script from cStringIO import StringIO notebook = read(StringIO(self.record.unpacked_contents), 4) script, resources = export_script(notebook) env_dict = {} exec (compile(script.replace('# coding: utf-8', ''), 'script', 'exec'), env_dict) return env_dict
python
def execute(self): """Convert the notebook to a python script and execute it, returning the local context as a dict""" from nbformat import read from nbconvert.exporters import export_script from cStringIO import StringIO notebook = read(StringIO(self.record.unpacked_contents), 4) script, resources = export_script(notebook) env_dict = {} exec (compile(script.replace('# coding: utf-8', ''), 'script', 'exec'), env_dict) return env_dict
[ "def", "execute", "(", "self", ")", ":", "from", "nbformat", "import", "read", "from", "nbconvert", ".", "exporters", "import", "export_script", "from", "cStringIO", "import", "StringIO", "notebook", "=", "read", "(", "StringIO", "(", "self", ".", "record", ...
Convert the notebook to a python script and execute it, returning the local context as a dict
[ "Convert", "the", "notebook", "to", "a", "python", "script", "and", "execute", "it", "returning", "the", "local", "context", "as", "a", "dict" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L685-L701
CivicSpleen/ambry
ambry/bundle/files.py
PythonSourceFile.record_to_fs
def record_to_fs(self): """Create a filesystem file from a File""" fr = self.record if fr.contents: with self._fs.open(self.file_name, 'w', encoding='utf-8') as f: self.record_to_fh(f)
python
def record_to_fs(self): """Create a filesystem file from a File""" fr = self.record if fr.contents: with self._fs.open(self.file_name, 'w', encoding='utf-8') as f: self.record_to_fh(f)
[ "def", "record_to_fs", "(", "self", ")", ":", "fr", "=", "self", ".", "record", "if", "fr", ".", "contents", ":", "with", "self", ".", "_fs", ".", "open", "(", "self", ".", "file_name", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ...
Create a filesystem file from a File
[ "Create", "a", "filesystem", "file", "from", "a", "File" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L710-L717
CivicSpleen/ambry
ambry/bundle/files.py
PythonSourceFile.import_module
def import_module(self, module_path = 'ambry.build', **kwargs): """ Import the contents of the file into the ambry.build module :param kwargs: items to add to the module globals :return: """ from fs.errors import NoSysPathError if module_path in sys.modules: module = sys.modules[module_path] else: module = imp.new_module(module_path) sys.modules[module_path] = module bf = self.record if not bf.contents: return module module.__dict__.update(**kwargs) try: abs_path = self._fs.getsyspath(self.file_name) except NoSysPathError: abs_path = '<string>' import re if re.search(r'-\*-\s+coding:', bf.contents): # Has encoding, so don't decode contents = bf.contents else: contents = bf.unpacked_contents # Assumes utf-8 exec(compile(contents, abs_path, 'exec'), module.__dict__) return module
python
def import_module(self, module_path = 'ambry.build', **kwargs): """ Import the contents of the file into the ambry.build module :param kwargs: items to add to the module globals :return: """ from fs.errors import NoSysPathError if module_path in sys.modules: module = sys.modules[module_path] else: module = imp.new_module(module_path) sys.modules[module_path] = module bf = self.record if not bf.contents: return module module.__dict__.update(**kwargs) try: abs_path = self._fs.getsyspath(self.file_name) except NoSysPathError: abs_path = '<string>' import re if re.search(r'-\*-\s+coding:', bf.contents): # Has encoding, so don't decode contents = bf.contents else: contents = bf.unpacked_contents # Assumes utf-8 exec(compile(contents, abs_path, 'exec'), module.__dict__) return module
[ "def", "import_module", "(", "self", ",", "module_path", "=", "'ambry.build'", ",", "*", "*", "kwargs", ")", ":", "from", "fs", ".", "errors", "import", "NoSysPathError", "if", "module_path", "in", "sys", ".", "modules", ":", "module", "=", "sys", ".", "...
Import the contents of the file into the ambry.build module :param kwargs: items to add to the module globals :return:
[ "Import", "the", "contents", "of", "the", "file", "into", "the", "ambry", ".", "build", "module" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L719-L756
CivicSpleen/ambry
ambry/bundle/files.py
PythonSourceFile.import_bundle
def import_bundle(self): """Add the filesystem to the Python sys path with an import hook, then import to file as Python""" from fs.errors import NoSysPathError try: import ambry.build module = sys.modules['ambry.build'] except ImportError: module = imp.new_module('ambry.build') sys.modules['ambry.build'] = module bf = self.record if not bf.has_contents: from ambry.bundle import Bundle return Bundle try: abs_path = self._fs.getsyspath(self.file_name) except NoSysPathError: abs_path = '<string>' exec(compile(bf.contents, abs_path, 'exec'), module.__dict__) return module.Bundle
python
def import_bundle(self): """Add the filesystem to the Python sys path with an import hook, then import to file as Python""" from fs.errors import NoSysPathError try: import ambry.build module = sys.modules['ambry.build'] except ImportError: module = imp.new_module('ambry.build') sys.modules['ambry.build'] = module bf = self.record if not bf.has_contents: from ambry.bundle import Bundle return Bundle try: abs_path = self._fs.getsyspath(self.file_name) except NoSysPathError: abs_path = '<string>' exec(compile(bf.contents, abs_path, 'exec'), module.__dict__) return module.Bundle
[ "def", "import_bundle", "(", "self", ")", ":", "from", "fs", ".", "errors", "import", "NoSysPathError", "try", ":", "import", "ambry", ".", "build", "module", "=", "sys", ".", "modules", "[", "'ambry.build'", "]", "except", "ImportError", ":", "module", "=...
Add the filesystem to the Python sys path with an import hook, then import to file as Python
[ "Add", "the", "filesystem", "to", "the", "Python", "sys", "path", "with", "an", "import", "hook", "then", "import", "to", "file", "as", "Python" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L758-L783
CivicSpleen/ambry
ambry/bundle/files.py
PythonSourceFile.import_lib
def import_lib(self): """Import the lib.py file into the bundle module""" try: import ambry.build module = sys.modules['ambry.build'] except ImportError: module = imp.new_module('ambry.build') sys.modules['ambry.build'] = module bf = self.record if not bf.has_contents: return try: exec (compile(bf.contents, self.path, 'exec'), module.__dict__) except Exception: self._bundle.error("Failed to load code from {}".format(self.path)) raise # print(self.file_const, bundle.__dict__.keys()) # print(bf.contents) return module
python
def import_lib(self): """Import the lib.py file into the bundle module""" try: import ambry.build module = sys.modules['ambry.build'] except ImportError: module = imp.new_module('ambry.build') sys.modules['ambry.build'] = module bf = self.record if not bf.has_contents: return try: exec (compile(bf.contents, self.path, 'exec'), module.__dict__) except Exception: self._bundle.error("Failed to load code from {}".format(self.path)) raise # print(self.file_const, bundle.__dict__.keys()) # print(bf.contents) return module
[ "def", "import_lib", "(", "self", ")", ":", "try", ":", "import", "ambry", ".", "build", "module", "=", "sys", ".", "modules", "[", "'ambry.build'", "]", "except", "ImportError", ":", "module", "=", "imp", ".", "new_module", "(", "'ambry.build'", ")", "s...
Import the lib.py file into the bundle module
[ "Import", "the", "lib", ".", "py", "file", "into", "the", "bundle", "module" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L785-L810
CivicSpleen/ambry
ambry/bundle/files.py
SourcesFile.record_to_objects
def record_to_objects(self): """Create config records to match the file metadata""" from ambry.orm.exc import NotFoundError fr = self.record contents = fr.unpacked_contents if not contents: return # Zip transposes an array when in the form of a list of lists, so this transposes so # each row starts with the heading and the rest of the row are the values # for that row. The bool and filter return false when none of the values # are non-empty. Then zip again to transpose to original form. non_empty_rows = drop_empty(contents) s = self._dataset._database.session for i, row in enumerate(non_empty_rows): if i == 0: header = row else: d = dict(six.moves.zip(header, row)) if 'widths' in d: del d['widths'] # Obsolete column in old spreadsheets. if 'table' in d: d['dest_table_name'] = d['table'] del d['table'] if 'order' in d: d['stage'] = d['order'] del d['order'] if 'dest_table' in d: d['dest_table_name'] = d['dest_table'] del d['dest_table'] if 'source_table' in d: d['source_table_name'] = d['source_table'] del d['source_table'] d['d_vid'] = self._dataset.vid d['state'] = 'synced' try: ds = self._dataset.source_file(str(d['name'])) ds.update(**d) except NotFoundError: name = d['name'] del d['name'] try: ds = self._dataset.new_source(name, **d) except: print(name, d) import pprint pprint.pprint(d) raise except: # Odd error with 'none' in keys for d print('!!!', header) print('!!!', row) raise s.merge(ds) self._dataset._database.commit()
python
def record_to_objects(self): """Create config records to match the file metadata""" from ambry.orm.exc import NotFoundError fr = self.record contents = fr.unpacked_contents if not contents: return # Zip transposes an array when in the form of a list of lists, so this transposes so # each row starts with the heading and the rest of the row are the values # for that row. The bool and filter return false when none of the values # are non-empty. Then zip again to transpose to original form. non_empty_rows = drop_empty(contents) s = self._dataset._database.session for i, row in enumerate(non_empty_rows): if i == 0: header = row else: d = dict(six.moves.zip(header, row)) if 'widths' in d: del d['widths'] # Obsolete column in old spreadsheets. if 'table' in d: d['dest_table_name'] = d['table'] del d['table'] if 'order' in d: d['stage'] = d['order'] del d['order'] if 'dest_table' in d: d['dest_table_name'] = d['dest_table'] del d['dest_table'] if 'source_table' in d: d['source_table_name'] = d['source_table'] del d['source_table'] d['d_vid'] = self._dataset.vid d['state'] = 'synced' try: ds = self._dataset.source_file(str(d['name'])) ds.update(**d) except NotFoundError: name = d['name'] del d['name'] try: ds = self._dataset.new_source(name, **d) except: print(name, d) import pprint pprint.pprint(d) raise except: # Odd error with 'none' in keys for d print('!!!', header) print('!!!', row) raise s.merge(ds) self._dataset._database.commit()
[ "def", "record_to_objects", "(", "self", ")", ":", "from", "ambry", ".", "orm", ".", "exc", "import", "NotFoundError", "fr", "=", "self", ".", "record", "contents", "=", "fr", ".", "unpacked_contents", "if", "not", "contents", ":", "return", "# Zip transpose...
Create config records to match the file metadata
[ "Create", "config", "records", "to", "match", "the", "file", "metadata" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L838-L909
CivicSpleen/ambry
ambry/bundle/files.py
SchemaFile.record_to_objects
def record_to_objects(self): """Create config records to match the file metadata""" from ambry.orm import Column, Table, Dataset def _clean_int(i): if i is None: return None elif isinstance(i, int): return i elif isinstance(i, string_types): if len(i) == 0: return None return int(i.strip()) bsfile = self.record contents = bsfile.unpacked_contents if not contents: return line_no = 1 # Accounts for file header. Data starts on line 2 errors = [] warnings = [] extant_tables = {t.name: t for t in self._dataset.tables} old_types_map = { 'varchar': Column.DATATYPE_STR, 'integer': Column.DATATYPE_INTEGER, 'real': Column.DATATYPE_FLOAT, } def run_progress_f(line_no): self._bundle.log('Loading tables from file. Line #{}'.format(line_no)) from ambry.bundle.process import CallInterval run_progress_f = CallInterval(run_progress_f, 10) table_number = self._dataset._database.next_sequence_id(Dataset, self._dataset.vid, Table) for row in bsfile.dict_row_reader: line_no += 1 run_progress_f(line_no) # Skip blank lines if not row.get('column', False) and not row.get('table', False): continue if not row.get('column', False): raise ConfigurationError('Row error: no column on line {}'.format(line_no)) if not row.get('table', False): raise ConfigurationError('Row error: no table on line {}'.format(line_no)) if not row.get('datatype', False) and not row.get('valuetype', False): raise ConfigurationError('Row error: no type on line {}'.format(line_no)) value_type = row.get('valuetype', '').strip() if row.get('valuetype', False) else None data_type = row.get('datatype', '').strip() if row.get('datatype', False) else None def resolve_data_type(value_type): from ambry.valuetype import resolve_value_type vt_class = resolve_value_type(value_type) if not vt_class: raise ConfigurationError("Row error: unknown valuetype '{}'".format(value_type)) return vt_class.python_type().__name__ # If we have a value type field, and not the datatype, # the value type is as specified, and the data type is derived from it. if value_type and not data_type: data_type = resolve_data_type(value_type) elif data_type and not value_type: value_type = data_type data_type = resolve_data_type(value_type) # There are still some old data types hanging around data_type = old_types_map.get(data_type.lower(), data_type) table_name = row['table'] try: table = extant_tables[table_name] except KeyError: table = self._dataset.new_table( table_name, sequence_id=table_number, description=row.get('description') if row['column'] == 'id' else '' ) table_number += 1 extant_tables[table_name] = table data = {k.replace('d_', '', 1): v for k, v in list(row.items()) if k and k.startswith('d_') and v} if row['column'] == 'id': table.data.update(data) data = {} table.add_column( row['column'], fk_vid=row['is_fk'] if row.get('is_fk', False) else None, description=(row.get('description', '') or '').strip(), datatype=data_type, valuetype=value_type, parent=row.get('parent'), proto_vid=row.get('proto_vid'), size=_clean_int(row.get('size', None)), width=_clean_int(row.get('width', None)), data=data, keywords=row.get('keywords'), measure=row.get('measure'), transform=row.get('transform'), derivedfrom=row.get('derivedfrom'), units=row.get('units', None), universe=row.get('universe'), update_existing= True) self._dataset.t_sequence_id = table_number return warnings, errors
python
def record_to_objects(self): """Create config records to match the file metadata""" from ambry.orm import Column, Table, Dataset def _clean_int(i): if i is None: return None elif isinstance(i, int): return i elif isinstance(i, string_types): if len(i) == 0: return None return int(i.strip()) bsfile = self.record contents = bsfile.unpacked_contents if not contents: return line_no = 1 # Accounts for file header. Data starts on line 2 errors = [] warnings = [] extant_tables = {t.name: t for t in self._dataset.tables} old_types_map = { 'varchar': Column.DATATYPE_STR, 'integer': Column.DATATYPE_INTEGER, 'real': Column.DATATYPE_FLOAT, } def run_progress_f(line_no): self._bundle.log('Loading tables from file. Line #{}'.format(line_no)) from ambry.bundle.process import CallInterval run_progress_f = CallInterval(run_progress_f, 10) table_number = self._dataset._database.next_sequence_id(Dataset, self._dataset.vid, Table) for row in bsfile.dict_row_reader: line_no += 1 run_progress_f(line_no) # Skip blank lines if not row.get('column', False) and not row.get('table', False): continue if not row.get('column', False): raise ConfigurationError('Row error: no column on line {}'.format(line_no)) if not row.get('table', False): raise ConfigurationError('Row error: no table on line {}'.format(line_no)) if not row.get('datatype', False) and not row.get('valuetype', False): raise ConfigurationError('Row error: no type on line {}'.format(line_no)) value_type = row.get('valuetype', '').strip() if row.get('valuetype', False) else None data_type = row.get('datatype', '').strip() if row.get('datatype', False) else None def resolve_data_type(value_type): from ambry.valuetype import resolve_value_type vt_class = resolve_value_type(value_type) if not vt_class: raise ConfigurationError("Row error: unknown valuetype '{}'".format(value_type)) return vt_class.python_type().__name__ # If we have a value type field, and not the datatype, # the value type is as specified, and the data type is derived from it. if value_type and not data_type: data_type = resolve_data_type(value_type) elif data_type and not value_type: value_type = data_type data_type = resolve_data_type(value_type) # There are still some old data types hanging around data_type = old_types_map.get(data_type.lower(), data_type) table_name = row['table'] try: table = extant_tables[table_name] except KeyError: table = self._dataset.new_table( table_name, sequence_id=table_number, description=row.get('description') if row['column'] == 'id' else '' ) table_number += 1 extant_tables[table_name] = table data = {k.replace('d_', '', 1): v for k, v in list(row.items()) if k and k.startswith('d_') and v} if row['column'] == 'id': table.data.update(data) data = {} table.add_column( row['column'], fk_vid=row['is_fk'] if row.get('is_fk', False) else None, description=(row.get('description', '') or '').strip(), datatype=data_type, valuetype=value_type, parent=row.get('parent'), proto_vid=row.get('proto_vid'), size=_clean_int(row.get('size', None)), width=_clean_int(row.get('width', None)), data=data, keywords=row.get('keywords'), measure=row.get('measure'), transform=row.get('transform'), derivedfrom=row.get('derivedfrom'), units=row.get('units', None), universe=row.get('universe'), update_existing= True) self._dataset.t_sequence_id = table_number return warnings, errors
[ "def", "record_to_objects", "(", "self", ")", ":", "from", "ambry", ".", "orm", "import", "Column", ",", "Table", ",", "Dataset", "def", "_clean_int", "(", "i", ")", ":", "if", "i", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "i", ...
Create config records to match the file metadata
[ "Create", "config", "records", "to", "match", "the", "file", "metadata" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L941-L1068
CivicSpleen/ambry
ambry/bundle/files.py
SourceSchemaFile.record_to_objects
def record_to_objects(self): """Write from the stored file data to the source records""" from ambry.orm import SourceTable bsfile = self.record failures = set() # Clear out all of the columns from existing tables. We don't clear out the # tables, since they may be referenced by sources for row in bsfile.dict_row_reader: st = self._dataset.source_table(row['table']) if st: st.columns[:] = [] self._dataset.commit() for row in bsfile.dict_row_reader: st = self._dataset.source_table(row['table']) if not st: st = self._dataset.new_source_table(row['table']) # table_number += 1 if 'datatype' not in row: row['datatype'] = 'unknown' del row['table'] st.add_column(**row) # Create or update if failures: raise ConfigurationError('Failed to load source schema, missing sources: {} '.format(failures)) self._dataset.commit()
python
def record_to_objects(self): """Write from the stored file data to the source records""" from ambry.orm import SourceTable bsfile = self.record failures = set() # Clear out all of the columns from existing tables. We don't clear out the # tables, since they may be referenced by sources for row in bsfile.dict_row_reader: st = self._dataset.source_table(row['table']) if st: st.columns[:] = [] self._dataset.commit() for row in bsfile.dict_row_reader: st = self._dataset.source_table(row['table']) if not st: st = self._dataset.new_source_table(row['table']) # table_number += 1 if 'datatype' not in row: row['datatype'] = 'unknown' del row['table'] st.add_column(**row) # Create or update if failures: raise ConfigurationError('Failed to load source schema, missing sources: {} '.format(failures)) self._dataset.commit()
[ "def", "record_to_objects", "(", "self", ")", ":", "from", "ambry", ".", "orm", "import", "SourceTable", "bsfile", "=", "self", ".", "record", "failures", "=", "set", "(", ")", "# Clear out all of the columns from existing tables. We don't clear out the", "# tables, sin...
Write from the stored file data to the source records
[ "Write", "from", "the", "stored", "file", "data", "to", "the", "source", "records" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L1133-L1169
CivicSpleen/ambry
ambry/bundle/files.py
ASQLSourceFile.execute
def execute(self): """ Executes all sql statements from bundle.sql. """ from ambry.mprlib import execute_sql execute_sql(self._bundle.library, self.record_content)
python
def execute(self): """ Executes all sql statements from bundle.sql. """ from ambry.mprlib import execute_sql execute_sql(self._bundle.library, self.record_content)
[ "def", "execute", "(", "self", ")", ":", "from", "ambry", ".", "mprlib", "import", "execute_sql", "execute_sql", "(", "self", ".", "_bundle", ".", "library", ",", "self", ".", "record_content", ")" ]
Executes all sql statements from bundle.sql.
[ "Executes", "all", "sql", "statements", "from", "bundle", ".", "sql", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L1204-L1208
CivicSpleen/ambry
ambry/bundle/files.py
BuildSourceFileAccessor.list_records
def list_records(self, file_const=None): """Iterate through the file records""" for r in self._dataset.files: if file_const and r.minor_type != file_const: continue yield self.instance_from_name(r.path)
python
def list_records(self, file_const=None): """Iterate through the file records""" for r in self._dataset.files: if file_const and r.minor_type != file_const: continue yield self.instance_from_name(r.path)
[ "def", "list_records", "(", "self", ",", "file_const", "=", "None", ")", ":", "for", "r", "in", "self", ".", "_dataset", ".", "files", ":", "if", "file_const", "and", "r", ".", "minor_type", "!=", "file_const", ":", "continue", "yield", "self", ".", "i...
Iterate through the file records
[ "Iterate", "through", "the", "file", "records" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L1295-L1300
CivicSpleen/ambry
ambry/bundle/files.py
BuildSourceFileAccessor.record_to_objects
def record_to_objects(self, preference=None): """Create objects from files, or merge the files into the objects. """ from ambry.orm.file import File for f in self.list_records(): pref = preference if preference else f.record.preference if pref == File.PREFERENCE.FILE: self._bundle.logger.debug(' Cleaning objects for file {}'.format(f.path)) f.clean_objects() if pref in (File.PREFERENCE.FILE, File.PREFERENCE.MERGE): self._bundle.logger.debug(' rto {}'.format(f.path)) f.record_to_objects()
python
def record_to_objects(self, preference=None): """Create objects from files, or merge the files into the objects. """ from ambry.orm.file import File for f in self.list_records(): pref = preference if preference else f.record.preference if pref == File.PREFERENCE.FILE: self._bundle.logger.debug(' Cleaning objects for file {}'.format(f.path)) f.clean_objects() if pref in (File.PREFERENCE.FILE, File.PREFERENCE.MERGE): self._bundle.logger.debug(' rto {}'.format(f.path)) f.record_to_objects()
[ "def", "record_to_objects", "(", "self", ",", "preference", "=", "None", ")", ":", "from", "ambry", ".", "orm", ".", "file", "import", "File", "for", "f", "in", "self", ".", "list_records", "(", ")", ":", "pref", "=", "preference", "if", "preference", ...
Create objects from files, or merge the files into the objects.
[ "Create", "objects", "from", "files", "or", "merge", "the", "files", "into", "the", "objects", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L1338-L1352
CivicSpleen/ambry
ambry/bundle/files.py
BuildSourceFileAccessor.objects_to_record
def objects_to_record(self, preference=None): """Create file records from objects. """ from ambry.orm.file import File raise NotImplementedError("Still uses obsolete file_info_map") for file_const, (file_name, clz) in iteritems(file_info_map): f = self.file(file_const) pref = preference if preference else f.record.preference if pref in (File.PREFERENCE.MERGE, File.PREFERENCE.OBJECT): self._bundle.logger.debug(' otr {}'.format(file_const)) f.objects_to_record()
python
def objects_to_record(self, preference=None): """Create file records from objects. """ from ambry.orm.file import File raise NotImplementedError("Still uses obsolete file_info_map") for file_const, (file_name, clz) in iteritems(file_info_map): f = self.file(file_const) pref = preference if preference else f.record.preference if pref in (File.PREFERENCE.MERGE, File.PREFERENCE.OBJECT): self._bundle.logger.debug(' otr {}'.format(file_const)) f.objects_to_record()
[ "def", "objects_to_record", "(", "self", ",", "preference", "=", "None", ")", ":", "from", "ambry", ".", "orm", ".", "file", "import", "File", "raise", "NotImplementedError", "(", "\"Still uses obsolete file_info_map\"", ")", "for", "file_const", ",", "(", "file...
Create file records from objects.
[ "Create", "file", "records", "from", "objects", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L1354-L1366
CivicSpleen/ambry
ambry/bundle/files.py
BuildSourceFileAccessor.set_defaults
def set_defaults(self): """Add default content to any file record that is empty""" for const_name, c in file_classes.items(): if c.multiplicity == '1': f = self.file(const_name) if not f.record.unpacked_contents: f.setcontent(f.default)
python
def set_defaults(self): """Add default content to any file record that is empty""" for const_name, c in file_classes.items(): if c.multiplicity == '1': f = self.file(const_name) if not f.record.unpacked_contents: f.setcontent(f.default)
[ "def", "set_defaults", "(", "self", ")", ":", "for", "const_name", ",", "c", "in", "file_classes", ".", "items", "(", ")", ":", "if", "c", ".", "multiplicity", "==", "'1'", ":", "f", "=", "self", ".", "file", "(", "const_name", ")", "if", "not", "f...
Add default content to any file record that is empty
[ "Add", "default", "content", "to", "any", "file", "record", "that", "is", "empty" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L1368-L1375
PythonRails/rails
rails/__init__.py
run
def run(host='127.0.0.1', port=8000): """ Run web server. """ print("Server running on {}:{}".format(host, port)) app_router = Router() server = make_server(host, port, app_router) server.serve_forever()
python
def run(host='127.0.0.1', port=8000): """ Run web server. """ print("Server running on {}:{}".format(host, port)) app_router = Router() server = make_server(host, port, app_router) server.serve_forever()
[ "def", "run", "(", "host", "=", "'127.0.0.1'", ",", "port", "=", "8000", ")", ":", "print", "(", "\"Server running on {}:{}\"", ".", "format", "(", "host", ",", "port", ")", ")", "app_router", "=", "Router", "(", ")", "server", "=", "make_server", "(", ...
Run web server.
[ "Run", "web", "server", "." ]
train
https://github.com/PythonRails/rails/blob/1e199b9da4da5b24fef39fc6212d71fc9fbb18a5/rails/__init__.py#L5-L12
twisted/epsilon
epsilon/scripts/certcreate.py
main
def main(args=None): """ Create a private key and a certificate and write them to a file. """ if args is None: args = sys.argv[1:] o = Options() try: o.parseOptions(args) except usage.UsageError, e: raise SystemExit(str(e)) else: return createSSLCertificate(o)
python
def main(args=None): """ Create a private key and a certificate and write them to a file. """ if args is None: args = sys.argv[1:] o = Options() try: o.parseOptions(args) except usage.UsageError, e: raise SystemExit(str(e)) else: return createSSLCertificate(o)
[ "def", "main", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "o", "=", "Options", "(", ")", "try", ":", "o", ".", "parseOptions", "(", "args", ")", "except", "usage", ...
Create a private key and a certificate and write them to a file.
[ "Create", "a", "private", "key", "and", "a", "certificate", "and", "write", "them", "to", "a", "file", "." ]
train
https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/scripts/certcreate.py#L49-L62
CivicSpleen/ambry
ambry/orm/code.py
Code.update
def update(self, f): """Copy another files properties into this one.""" for p in self.__mapper__.attrs: if p.key == 'oid': continue try: setattr(self, p.key, getattr(f, p.key)) except AttributeError: # The dict() method copies data property values into the main dict, # and these don't have associated class properties. continue
python
def update(self, f): """Copy another files properties into this one.""" for p in self.__mapper__.attrs: if p.key == 'oid': continue try: setattr(self, p.key, getattr(f, p.key)) except AttributeError: # The dict() method copies data property values into the main dict, # and these don't have associated class properties. continue
[ "def", "update", "(", "self", ",", "f", ")", ":", "for", "p", "in", "self", ".", "__mapper__", ".", "attrs", ":", "if", "p", ".", "key", "==", "'oid'", ":", "continue", "try", ":", "setattr", "(", "self", ",", "p", ".", "key", ",", "getattr", "...
Copy another files properties into this one.
[ "Copy", "another", "files", "properties", "into", "this", "one", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/code.py#L54-L67
twisted/epsilon
epsilon/hotfixes/timeoutmixin_calllater.py
TimeoutMixin.resetTimeout
def resetTimeout(self): """Reset the timeout count down""" if self.__timeoutCall is not None and self.timeOut is not None: self.__timeoutCall.reset(self.timeOut)
python
def resetTimeout(self): """Reset the timeout count down""" if self.__timeoutCall is not None and self.timeOut is not None: self.__timeoutCall.reset(self.timeOut)
[ "def", "resetTimeout", "(", "self", ")", ":", "if", "self", ".", "__timeoutCall", "is", "not", "None", "and", "self", ".", "timeOut", "is", "not", "None", ":", "self", ".", "__timeoutCall", ".", "reset", "(", "self", ".", "timeOut", ")" ]
Reset the timeout count down
[ "Reset", "the", "timeout", "count", "down" ]
train
https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/hotfixes/timeoutmixin_calllater.py#L17-L20
twisted/epsilon
epsilon/hotfixes/timeoutmixin_calllater.py
TimeoutMixin.setTimeout
def setTimeout(self, period): """Change the timeout period @type period: C{int} or C{NoneType} @param period: The period, in seconds, to change the timeout to, or C{None} to disable the timeout. """ prev = self.timeOut self.timeOut = period if self.__timeoutCall is not None: if period is None: self.__timeoutCall.cancel() self.__timeoutCall = None else: self.__timeoutCall.reset(period) elif period is not None: self.__timeoutCall = self.callLater(period, self.__timedOut) return prev
python
def setTimeout(self, period): """Change the timeout period @type period: C{int} or C{NoneType} @param period: The period, in seconds, to change the timeout to, or C{None} to disable the timeout. """ prev = self.timeOut self.timeOut = period if self.__timeoutCall is not None: if period is None: self.__timeoutCall.cancel() self.__timeoutCall = None else: self.__timeoutCall.reset(period) elif period is not None: self.__timeoutCall = self.callLater(period, self.__timedOut) return prev
[ "def", "setTimeout", "(", "self", ",", "period", ")", ":", "prev", "=", "self", ".", "timeOut", "self", ".", "timeOut", "=", "period", "if", "self", ".", "__timeoutCall", "is", "not", "None", ":", "if", "period", "is", "None", ":", "self", ".", "__ti...
Change the timeout period @type period: C{int} or C{NoneType} @param period: The period, in seconds, to change the timeout to, or C{None} to disable the timeout.
[ "Change", "the", "timeout", "period" ]
train
https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/hotfixes/timeoutmixin_calllater.py#L22-L41
PythonRails/rails
rails/router.py
Router._load_controllers
def _load_controllers(self): """ Load all controllers from folder 'controllers'. Ignore files with leading underscore (for example: controllers/_blogs.py) """ for file_name in os.listdir(os.path.join(self._project_dir, 'controllers')): # ignore disabled controllers if not file_name.startswith('_'): module_name = file_name.split('.', 1)[0] module_path = "controllers.{}".format(module_name) module = import_module(module_path) # transform 'blog_articles' file name to 'BlogArticles' class controller_class_name = module_name.title().replace('_', '') controller_class = getattr(module, controller_class_name) controller = controller_class() for action_name in dir(controller): action = getattr(controller, action_name) if action_name.startswith('_') or not callable(action): continue url_path = "/".join([module_name, action_name]) self._controllers[url_path] = action return self._controllers
python
def _load_controllers(self): """ Load all controllers from folder 'controllers'. Ignore files with leading underscore (for example: controllers/_blogs.py) """ for file_name in os.listdir(os.path.join(self._project_dir, 'controllers')): # ignore disabled controllers if not file_name.startswith('_'): module_name = file_name.split('.', 1)[0] module_path = "controllers.{}".format(module_name) module = import_module(module_path) # transform 'blog_articles' file name to 'BlogArticles' class controller_class_name = module_name.title().replace('_', '') controller_class = getattr(module, controller_class_name) controller = controller_class() for action_name in dir(controller): action = getattr(controller, action_name) if action_name.startswith('_') or not callable(action): continue url_path = "/".join([module_name, action_name]) self._controllers[url_path] = action return self._controllers
[ "def", "_load_controllers", "(", "self", ")", ":", "for", "file_name", "in", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_project_dir", ",", "'controllers'", ")", ")", ":", "# ignore disabled controllers", "if", "not", "fi...
Load all controllers from folder 'controllers'. Ignore files with leading underscore (for example: controllers/_blogs.py)
[ "Load", "all", "controllers", "from", "folder", "controllers", "." ]
train
https://github.com/PythonRails/rails/blob/1e199b9da4da5b24fef39fc6212d71fc9fbb18a5/rails/router.py#L73-L95
PythonRails/rails
rails/router.py
Router._init_view
def _init_view(self): """ Initialize View with project settings. """ views_engine = get_config('rails.views.engine', 'jinja') templates_dir = os.path.join(self._project_dir, "views", "templates") self._view = View(views_engine, templates_dir)
python
def _init_view(self): """ Initialize View with project settings. """ views_engine = get_config('rails.views.engine', 'jinja') templates_dir = os.path.join(self._project_dir, "views", "templates") self._view = View(views_engine, templates_dir)
[ "def", "_init_view", "(", "self", ")", ":", "views_engine", "=", "get_config", "(", "'rails.views.engine'", ",", "'jinja'", ")", "templates_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_project_dir", ",", "\"views\"", ",", "\"templates\"", "...
Initialize View with project settings.
[ "Initialize", "View", "with", "project", "settings", "." ]
train
https://github.com/PythonRails/rails/blob/1e199b9da4da5b24fef39fc6212d71fc9fbb18a5/rails/router.py#L97-L103