repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
sdispater/orator | orator/query/builder.py | QueryBuilder.get | def get(self, columns=None):
"""
Execute the query as a "select" statement
:param columns: The columns to get
:type columns: list
:return: The result
:rtype: Collection
"""
if not columns:
columns = ["*"]
original = self.columns
if not original:
self.columns = columns
results = self._processor.process_select(self, self._run_select())
self.columns = original
return Collection(results) | python | def get(self, columns=None):
"""
Execute the query as a "select" statement
:param columns: The columns to get
:type columns: list
:return: The result
:rtype: Collection
"""
if not columns:
columns = ["*"]
original = self.columns
if not original:
self.columns = columns
results = self._processor.process_select(self, self._run_select())
self.columns = original
return Collection(results) | [
"def",
"get",
"(",
"self",
",",
"columns",
"=",
"None",
")",
":",
"if",
"not",
"columns",
":",
"columns",
"=",
"[",
"\"*\"",
"]",
"original",
"=",
"self",
".",
"columns",
"if",
"not",
"original",
":",
"self",
".",
"columns",
"=",
"columns",
"results"... | Execute the query as a "select" statement
:param columns: The columns to get
:type columns: list
:return: The result
:rtype: Collection | [
"Execute",
"the",
"query",
"as",
"a",
"select",
"statement"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1032-L1054 | train | 225,900 |
sdispater/orator | orator/query/builder.py | QueryBuilder._run_select | def _run_select(self):
"""
Run the query as a "select" statement against the connection.
:return: The result
:rtype: list
"""
return self._connection.select(
self.to_sql(), self.get_bindings(), not self._use_write_connection
) | python | def _run_select(self):
"""
Run the query as a "select" statement against the connection.
:return: The result
:rtype: list
"""
return self._connection.select(
self.to_sql(), self.get_bindings(), not self._use_write_connection
) | [
"def",
"_run_select",
"(",
"self",
")",
":",
"return",
"self",
".",
"_connection",
".",
"select",
"(",
"self",
".",
"to_sql",
"(",
")",
",",
"self",
".",
"get_bindings",
"(",
")",
",",
"not",
"self",
".",
"_use_write_connection",
")"
] | Run the query as a "select" statement against the connection.
:return: The result
:rtype: list | [
"Run",
"the",
"query",
"as",
"a",
"select",
"statement",
"against",
"the",
"connection",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1056-L1065 | train | 225,901 |
sdispater/orator | orator/query/builder.py | QueryBuilder.exists | def exists(self):
"""
Determine if any rows exist for the current query.
:return: Whether the rows exist or not
:rtype: bool
"""
limit = self.limit_
result = self.limit(1).count() > 0
self.limit(limit)
return result | python | def exists(self):
"""
Determine if any rows exist for the current query.
:return: Whether the rows exist or not
:rtype: bool
"""
limit = self.limit_
result = self.limit(1).count() > 0
self.limit(limit)
return result | [
"def",
"exists",
"(",
"self",
")",
":",
"limit",
"=",
"self",
".",
"limit_",
"result",
"=",
"self",
".",
"limit",
"(",
"1",
")",
".",
"count",
"(",
")",
">",
"0",
"self",
".",
"limit",
"(",
"limit",
")",
"return",
"result"
] | Determine if any rows exist for the current query.
:return: Whether the rows exist or not
:rtype: bool | [
"Determine",
"if",
"any",
"rows",
"exist",
"for",
"the",
"current",
"query",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1229-L1242 | train | 225,902 |
sdispater/orator | orator/query/builder.py | QueryBuilder.count | def count(self, *columns):
"""
Retrieve the "count" result of the query
:param columns: The columns to get
:type columns: tuple
:return: The count
:rtype: int
"""
if not columns and self.distinct_:
columns = self.columns
if not columns:
columns = ["*"]
return int(self.aggregate("count", *columns)) | python | def count(self, *columns):
"""
Retrieve the "count" result of the query
:param columns: The columns to get
:type columns: tuple
:return: The count
:rtype: int
"""
if not columns and self.distinct_:
columns = self.columns
if not columns:
columns = ["*"]
return int(self.aggregate("count", *columns)) | [
"def",
"count",
"(",
"self",
",",
"*",
"columns",
")",
":",
"if",
"not",
"columns",
"and",
"self",
".",
"distinct_",
":",
"columns",
"=",
"self",
".",
"columns",
"if",
"not",
"columns",
":",
"columns",
"=",
"[",
"\"*\"",
"]",
"return",
"int",
"(",
... | Retrieve the "count" result of the query
:param columns: The columns to get
:type columns: tuple
:return: The count
:rtype: int | [
"Retrieve",
"the",
"count",
"result",
"of",
"the",
"query"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1244-L1260 | train | 225,903 |
sdispater/orator | orator/query/builder.py | QueryBuilder.aggregate | def aggregate(self, func, *columns):
"""
Execute an aggregate function against the database
:param func: The aggregate function
:type func: str
:param columns: The columns to execute the fnction for
:type columns: tuple
:return: The aggregate result
:rtype: mixed
"""
if not columns:
columns = ["*"]
self.aggregate_ = {"function": func, "columns": columns}
previous_columns = self.columns
results = self.get(*columns).all()
self.aggregate_ = None
self.columns = previous_columns
if len(results) > 0:
return dict((k.lower(), v) for k, v in results[0].items())["aggregate"] | python | def aggregate(self, func, *columns):
"""
Execute an aggregate function against the database
:param func: The aggregate function
:type func: str
:param columns: The columns to execute the fnction for
:type columns: tuple
:return: The aggregate result
:rtype: mixed
"""
if not columns:
columns = ["*"]
self.aggregate_ = {"function": func, "columns": columns}
previous_columns = self.columns
results = self.get(*columns).all()
self.aggregate_ = None
self.columns = previous_columns
if len(results) > 0:
return dict((k.lower(), v) for k, v in results[0].items())["aggregate"] | [
"def",
"aggregate",
"(",
"self",
",",
"func",
",",
"*",
"columns",
")",
":",
"if",
"not",
"columns",
":",
"columns",
"=",
"[",
"\"*\"",
"]",
"self",
".",
"aggregate_",
"=",
"{",
"\"function\"",
":",
"func",
",",
"\"columns\"",
":",
"columns",
"}",
"p... | Execute an aggregate function against the database
:param func: The aggregate function
:type func: str
:param columns: The columns to execute the fnction for
:type columns: tuple
:return: The aggregate result
:rtype: mixed | [
"Execute",
"an",
"aggregate",
"function",
"against",
"the",
"database"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1314-L1341 | train | 225,904 |
sdispater/orator | orator/query/builder.py | QueryBuilder.insert | def insert(self, _values=None, **values):
"""
Insert a new record into the database
:param _values: The new record values
:type _values: dict or list
:param values: The new record values as keyword arguments
:type values: dict
:return: The result
:rtype: bool
"""
if not values and not _values:
return True
if not isinstance(_values, list):
if _values is not None:
values.update(_values)
values = [values]
else:
values = _values
for i, value in enumerate(values):
values[i] = OrderedDict(sorted(value.items()))
bindings = []
for record in values:
for value in record.values():
bindings.append(value)
sql = self._grammar.compile_insert(self, values)
bindings = self._clean_bindings(bindings)
return self._connection.insert(sql, bindings) | python | def insert(self, _values=None, **values):
"""
Insert a new record into the database
:param _values: The new record values
:type _values: dict or list
:param values: The new record values as keyword arguments
:type values: dict
:return: The result
:rtype: bool
"""
if not values and not _values:
return True
if not isinstance(_values, list):
if _values is not None:
values.update(_values)
values = [values]
else:
values = _values
for i, value in enumerate(values):
values[i] = OrderedDict(sorted(value.items()))
bindings = []
for record in values:
for value in record.values():
bindings.append(value)
sql = self._grammar.compile_insert(self, values)
bindings = self._clean_bindings(bindings)
return self._connection.insert(sql, bindings) | [
"def",
"insert",
"(",
"self",
",",
"_values",
"=",
"None",
",",
"*",
"*",
"values",
")",
":",
"if",
"not",
"values",
"and",
"not",
"_values",
":",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"_values",
",",
"list",
")",
":",
"if",
"_values",
... | Insert a new record into the database
:param _values: The new record values
:type _values: dict or list
:param values: The new record values as keyword arguments
:type values: dict
:return: The result
:rtype: bool | [
"Insert",
"a",
"new",
"record",
"into",
"the",
"database"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1343-L1379 | train | 225,905 |
sdispater/orator | orator/query/builder.py | QueryBuilder.insert_get_id | def insert_get_id(self, values, sequence=None):
"""
Insert a new record and get the value of the primary key
:param values: The new record values
:type values: dict
:param sequence: The name of the primary key
:type sequence: str
:return: The value of the primary key
:rtype: int
"""
values = OrderedDict(sorted(values.items()))
sql = self._grammar.compile_insert_get_id(self, values, sequence)
values = self._clean_bindings(values.values())
return self._processor.process_insert_get_id(self, sql, values, sequence) | python | def insert_get_id(self, values, sequence=None):
"""
Insert a new record and get the value of the primary key
:param values: The new record values
:type values: dict
:param sequence: The name of the primary key
:type sequence: str
:return: The value of the primary key
:rtype: int
"""
values = OrderedDict(sorted(values.items()))
sql = self._grammar.compile_insert_get_id(self, values, sequence)
values = self._clean_bindings(values.values())
return self._processor.process_insert_get_id(self, sql, values, sequence) | [
"def",
"insert_get_id",
"(",
"self",
",",
"values",
",",
"sequence",
"=",
"None",
")",
":",
"values",
"=",
"OrderedDict",
"(",
"sorted",
"(",
"values",
".",
"items",
"(",
")",
")",
")",
"sql",
"=",
"self",
".",
"_grammar",
".",
"compile_insert_get_id",
... | Insert a new record and get the value of the primary key
:param values: The new record values
:type values: dict
:param sequence: The name of the primary key
:type sequence: str
:return: The value of the primary key
:rtype: int | [
"Insert",
"a",
"new",
"record",
"and",
"get",
"the",
"value",
"of",
"the",
"primary",
"key"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1381-L1400 | train | 225,906 |
sdispater/orator | orator/query/builder.py | QueryBuilder.truncate | def truncate(self):
"""
Run a truncate statement on the table
:rtype: None
"""
for sql, bindings in self._grammar.compile_truncate(self).items():
self._connection.statement(sql, bindings) | python | def truncate(self):
"""
Run a truncate statement on the table
:rtype: None
"""
for sql, bindings in self._grammar.compile_truncate(self).items():
self._connection.statement(sql, bindings) | [
"def",
"truncate",
"(",
"self",
")",
":",
"for",
"sql",
",",
"bindings",
"in",
"self",
".",
"_grammar",
".",
"compile_truncate",
"(",
"self",
")",
".",
"items",
"(",
")",
":",
"self",
".",
"_connection",
".",
"statement",
"(",
"sql",
",",
"bindings",
... | Run a truncate statement on the table
:rtype: None | [
"Run",
"a",
"truncate",
"statement",
"on",
"the",
"table"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1492-L1499 | train | 225,907 |
sdispater/orator | orator/query/builder.py | QueryBuilder._clean_bindings | def _clean_bindings(self, bindings):
"""
Remove all of the expressions from bindings
:param bindings: The bindings to clean
:type bindings: list
:return: The cleaned bindings
:rtype: list
"""
return list(filter(lambda b: not isinstance(b, QueryExpression), bindings)) | python | def _clean_bindings(self, bindings):
"""
Remove all of the expressions from bindings
:param bindings: The bindings to clean
:type bindings: list
:return: The cleaned bindings
:rtype: list
"""
return list(filter(lambda b: not isinstance(b, QueryExpression), bindings)) | [
"def",
"_clean_bindings",
"(",
"self",
",",
"bindings",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"b",
":",
"not",
"isinstance",
"(",
"b",
",",
"QueryExpression",
")",
",",
"bindings",
")",
")"
] | Remove all of the expressions from bindings
:param bindings: The bindings to clean
:type bindings: list
:return: The cleaned bindings
:rtype: list | [
"Remove",
"all",
"of",
"the",
"expressions",
"from",
"bindings"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1525-L1535 | train | 225,908 |
sdispater/orator | orator/query/builder.py | QueryBuilder.merge | def merge(self, query):
"""
Merge current query with another.
:param query: The query to merge with
:type query: QueryBuilder
"""
self.columns += query.columns
self.joins += query.joins
self.wheres += query.wheres
self.groups += query.groups
self.havings += query.havings
self.orders += query.orders
self.distinct_ = query.distinct_
if self.columns:
self.columns = Collection(self.columns).unique().all()
if query.limit_:
self.limit_ = query.limit_
if query.offset_:
self.offset_ = None
self.unions += query.unions
if query.union_limit:
self.union_limit = query.union_limit
if query.union_offset:
self.union_offset = query.union_offset
self.union_orders += query.union_orders
self.merge_bindings(query) | python | def merge(self, query):
"""
Merge current query with another.
:param query: The query to merge with
:type query: QueryBuilder
"""
self.columns += query.columns
self.joins += query.joins
self.wheres += query.wheres
self.groups += query.groups
self.havings += query.havings
self.orders += query.orders
self.distinct_ = query.distinct_
if self.columns:
self.columns = Collection(self.columns).unique().all()
if query.limit_:
self.limit_ = query.limit_
if query.offset_:
self.offset_ = None
self.unions += query.unions
if query.union_limit:
self.union_limit = query.union_limit
if query.union_offset:
self.union_offset = query.union_offset
self.union_orders += query.union_orders
self.merge_bindings(query) | [
"def",
"merge",
"(",
"self",
",",
"query",
")",
":",
"self",
".",
"columns",
"+=",
"query",
".",
"columns",
"self",
".",
"joins",
"+=",
"query",
".",
"joins",
"self",
".",
"wheres",
"+=",
"query",
".",
"wheres",
"self",
".",
"groups",
"+=",
"query",
... | Merge current query with another.
:param query: The query to merge with
:type query: QueryBuilder | [
"Merge",
"current",
"query",
"with",
"another",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1590-L1624 | train | 225,909 |
sdispater/orator | orator/dbal/abstract_asset.py | AbstractAsset._set_name | def _set_name(self, name):
"""
Sets the name of this asset.
:param name: The name of the asset
:type name: str
"""
if self._is_identifier_quoted(name):
self._quoted = True
name = self._trim_quotes(name)
if "." in name:
parts = name.split(".", 1)
self._namespace = parts[0]
name = parts[1]
self._name = name | python | def _set_name(self, name):
"""
Sets the name of this asset.
:param name: The name of the asset
:type name: str
"""
if self._is_identifier_quoted(name):
self._quoted = True
name = self._trim_quotes(name)
if "." in name:
parts = name.split(".", 1)
self._namespace = parts[0]
name = parts[1]
self._name = name | [
"def",
"_set_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_is_identifier_quoted",
"(",
"name",
")",
":",
"self",
".",
"_quoted",
"=",
"True",
"name",
"=",
"self",
".",
"_trim_quotes",
"(",
"name",
")",
"if",
"\".\"",
"in",
"name",
"... | Sets the name of this asset.
:param name: The name of the asset
:type name: str | [
"Sets",
"the",
"name",
"of",
"this",
"asset",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/dbal/abstract_asset.py#L16-L32 | train | 225,910 |
sdispater/orator | orator/dbal/abstract_asset.py | AbstractAsset._generate_identifier_name | def _generate_identifier_name(self, columns, prefix="", max_size=30):
"""
Generates an identifier from a list of column names obeying a certain string length.
"""
hash = ""
for column in columns:
hash += "%x" % binascii.crc32(encode(str(column)))
return (prefix + "_" + hash)[:max_size] | python | def _generate_identifier_name(self, columns, prefix="", max_size=30):
"""
Generates an identifier from a list of column names obeying a certain string length.
"""
hash = ""
for column in columns:
hash += "%x" % binascii.crc32(encode(str(column)))
return (prefix + "_" + hash)[:max_size] | [
"def",
"_generate_identifier_name",
"(",
"self",
",",
"columns",
",",
"prefix",
"=",
"\"\"",
",",
"max_size",
"=",
"30",
")",
":",
"hash",
"=",
"\"\"",
"for",
"column",
"in",
"columns",
":",
"hash",
"+=",
"\"%x\"",
"%",
"binascii",
".",
"crc32",
"(",
"... | Generates an identifier from a list of column names obeying a certain string length. | [
"Generates",
"an",
"identifier",
"from",
"a",
"list",
"of",
"column",
"names",
"obeying",
"a",
"certain",
"string",
"length",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/dbal/abstract_asset.py#L80-L88 | train | 225,911 |
sdispater/orator | orator/orm/mixins/soft_deletes.py | SoftDeletes.only_trashed | def only_trashed(cls):
"""
Get a new query builder that only includes soft deletes
:type cls: orator.orm.model.Model
:rtype: orator.orm.builder.Builder
"""
instance = cls()
column = instance.get_qualified_deleted_at_column()
return instance.new_query_without_scope(SoftDeletingScope()).where_not_null(
column
) | python | def only_trashed(cls):
"""
Get a new query builder that only includes soft deletes
:type cls: orator.orm.model.Model
:rtype: orator.orm.builder.Builder
"""
instance = cls()
column = instance.get_qualified_deleted_at_column()
return instance.new_query_without_scope(SoftDeletingScope()).where_not_null(
column
) | [
"def",
"only_trashed",
"(",
"cls",
")",
":",
"instance",
"=",
"cls",
"(",
")",
"column",
"=",
"instance",
".",
"get_qualified_deleted_at_column",
"(",
")",
"return",
"instance",
".",
"new_query_without_scope",
"(",
"SoftDeletingScope",
"(",
")",
")",
".",
"whe... | Get a new query builder that only includes soft deletes
:type cls: orator.orm.model.Model
:rtype: orator.orm.builder.Builder | [
"Get",
"a",
"new",
"query",
"builder",
"that",
"only",
"includes",
"soft",
"deletes"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/mixins/soft_deletes.py#L92-L106 | train | 225,912 |
sdispater/orator | orator/database_manager.py | BaseDatabaseManager.connection | def connection(self, name=None):
"""
Get a database connection instance
:param name: The connection name
:type name: str
:return: A Connection instance
:rtype: orator.connections.connection.Connection
"""
name, type = self._parse_connection_name(name)
if name not in self._connections:
logger.debug("Initiating connection %s" % name)
connection = self._make_connection(name)
self._set_connection_for_type(connection, type)
self._connections[name] = self._prepare(connection)
return self._connections[name] | python | def connection(self, name=None):
"""
Get a database connection instance
:param name: The connection name
:type name: str
:return: A Connection instance
:rtype: orator.connections.connection.Connection
"""
name, type = self._parse_connection_name(name)
if name not in self._connections:
logger.debug("Initiating connection %s" % name)
connection = self._make_connection(name)
self._set_connection_for_type(connection, type)
self._connections[name] = self._prepare(connection)
return self._connections[name] | [
"def",
"connection",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"name",
",",
"type",
"=",
"self",
".",
"_parse_connection_name",
"(",
"name",
")",
"if",
"name",
"not",
"in",
"self",
".",
"_connections",
":",
"logger",
".",
"debug",
"(",
"\"Initia... | Get a database connection instance
:param name: The connection name
:type name: str
:return: A Connection instance
:rtype: orator.connections.connection.Connection | [
"Get",
"a",
"database",
"connection",
"instance"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/database_manager.py#L28-L48 | train | 225,913 |
sdispater/orator | orator/orm/scopes/soft_deleting.py | SoftDeletingScope.apply | def apply(self, builder, model):
"""
Apply the scope to a given query builder.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
:param model: The model
:type model: orator.orm.Model
"""
builder.where_null(model.get_qualified_deleted_at_column())
self.extend(builder) | python | def apply(self, builder, model):
"""
Apply the scope to a given query builder.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
:param model: The model
:type model: orator.orm.Model
"""
builder.where_null(model.get_qualified_deleted_at_column())
self.extend(builder) | [
"def",
"apply",
"(",
"self",
",",
"builder",
",",
"model",
")",
":",
"builder",
".",
"where_null",
"(",
"model",
".",
"get_qualified_deleted_at_column",
"(",
")",
")",
"self",
".",
"extend",
"(",
"builder",
")"
] | Apply the scope to a given query builder.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
:param model: The model
:type model: orator.orm.Model | [
"Apply",
"the",
"scope",
"to",
"a",
"given",
"query",
"builder",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/scopes/soft_deleting.py#L10-L22 | train | 225,914 |
sdispater/orator | orator/orm/scopes/soft_deleting.py | SoftDeletingScope._on_delete | def _on_delete(self, builder):
"""
The delete replacement function.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
"""
column = self._get_deleted_at_column(builder)
return builder.update({column: builder.get_model().fresh_timestamp()}) | python | def _on_delete(self, builder):
"""
The delete replacement function.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
"""
column = self._get_deleted_at_column(builder)
return builder.update({column: builder.get_model().fresh_timestamp()}) | [
"def",
"_on_delete",
"(",
"self",
",",
"builder",
")",
":",
"column",
"=",
"self",
".",
"_get_deleted_at_column",
"(",
"builder",
")",
"return",
"builder",
".",
"update",
"(",
"{",
"column",
":",
"builder",
".",
"get_model",
"(",
")",
".",
"fresh_timestamp... | The delete replacement function.
:param builder: The query builder
:type builder: orator.orm.builder.Builder | [
"The",
"delete",
"replacement",
"function",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/scopes/soft_deleting.py#L36-L45 | train | 225,915 |
sdispater/orator | orator/orm/scopes/soft_deleting.py | SoftDeletingScope._get_deleted_at_column | def _get_deleted_at_column(self, builder):
"""
Get the "deleted at" column for the builder.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
:rtype: str
"""
if len(builder.get_query().joins) > 0:
return builder.get_model().get_qualified_deleted_at_column()
else:
return builder.get_model().get_deleted_at_column() | python | def _get_deleted_at_column(self, builder):
"""
Get the "deleted at" column for the builder.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
:rtype: str
"""
if len(builder.get_query().joins) > 0:
return builder.get_model().get_qualified_deleted_at_column()
else:
return builder.get_model().get_deleted_at_column() | [
"def",
"_get_deleted_at_column",
"(",
"self",
",",
"builder",
")",
":",
"if",
"len",
"(",
"builder",
".",
"get_query",
"(",
")",
".",
"joins",
")",
">",
"0",
":",
"return",
"builder",
".",
"get_model",
"(",
")",
".",
"get_qualified_deleted_at_column",
"(",... | Get the "deleted at" column for the builder.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
:rtype: str | [
"Get",
"the",
"deleted",
"at",
"column",
"for",
"the",
"builder",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/scopes/soft_deleting.py#L47-L59 | train | 225,916 |
sdispater/orator | orator/orm/scopes/soft_deleting.py | SoftDeletingScope._restore | def _restore(self, builder):
"""
The restore extension.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
"""
builder.with_trashed()
return builder.update({builder.get_model().get_deleted_at_column(): None}) | python | def _restore(self, builder):
"""
The restore extension.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
"""
builder.with_trashed()
return builder.update({builder.get_model().get_deleted_at_column(): None}) | [
"def",
"_restore",
"(",
"self",
",",
"builder",
")",
":",
"builder",
".",
"with_trashed",
"(",
")",
"return",
"builder",
".",
"update",
"(",
"{",
"builder",
".",
"get_model",
"(",
")",
".",
"get_deleted_at_column",
"(",
")",
":",
"None",
"}",
")"
] | The restore extension.
:param builder: The query builder
:type builder: orator.orm.builder.Builder | [
"The",
"restore",
"extension",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/scopes/soft_deleting.py#L88-L97 | train | 225,917 |
sdispater/orator | orator/schema/builder.py | SchemaBuilder.has_table | def has_table(self, table):
"""
Determine if the given table exists.
:param table: The table
:type table: str
:rtype: bool
"""
sql = self._grammar.compile_table_exists()
table = self._connection.get_table_prefix() + table
return len(self._connection.select(sql, [table])) > 0 | python | def has_table(self, table):
"""
Determine if the given table exists.
:param table: The table
:type table: str
:rtype: bool
"""
sql = self._grammar.compile_table_exists()
table = self._connection.get_table_prefix() + table
return len(self._connection.select(sql, [table])) > 0 | [
"def",
"has_table",
"(",
"self",
",",
"table",
")",
":",
"sql",
"=",
"self",
".",
"_grammar",
".",
"compile_table_exists",
"(",
")",
"table",
"=",
"self",
".",
"_connection",
".",
"get_table_prefix",
"(",
")",
"+",
"table",
"return",
"len",
"(",
"self",
... | Determine if the given table exists.
:param table: The table
:type table: str
:rtype: bool | [
"Determine",
"if",
"the",
"given",
"table",
"exists",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/builder.py#L16-L29 | train | 225,918 |
sdispater/orator | orator/schema/builder.py | SchemaBuilder.has_column | def has_column(self, table, column):
"""
Determine if the given table has a given column.
:param table: The table
:type table: str
:type column: str
:rtype: bool
"""
column = column.lower()
return column in list(map(lambda x: x.lower(), self.get_column_listing(table))) | python | def has_column(self, table, column):
"""
Determine if the given table has a given column.
:param table: The table
:type table: str
:type column: str
:rtype: bool
"""
column = column.lower()
return column in list(map(lambda x: x.lower(), self.get_column_listing(table))) | [
"def",
"has_column",
"(",
"self",
",",
"table",
",",
"column",
")",
":",
"column",
"=",
"column",
".",
"lower",
"(",
")",
"return",
"column",
"in",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"lower",
"(",
")",
",",
"self",
".",
"get_c... | Determine if the given table has a given column.
:param table: The table
:type table: str
:type column: str
:rtype: bool | [
"Determine",
"if",
"the",
"given",
"table",
"has",
"a",
"given",
"column",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/builder.py#L31-L44 | train | 225,919 |
sdispater/orator | orator/schema/builder.py | SchemaBuilder.table | def table(self, table):
"""
Modify a table on the schema.
:param table: The table
"""
try:
blueprint = self._create_blueprint(table)
yield blueprint
except Exception as e:
raise
try:
self._build(blueprint)
except Exception:
raise | python | def table(self, table):
"""
Modify a table on the schema.
:param table: The table
"""
try:
blueprint = self._create_blueprint(table)
yield blueprint
except Exception as e:
raise
try:
self._build(blueprint)
except Exception:
raise | [
"def",
"table",
"(",
"self",
",",
"table",
")",
":",
"try",
":",
"blueprint",
"=",
"self",
".",
"_create_blueprint",
"(",
"table",
")",
"yield",
"blueprint",
"except",
"Exception",
"as",
"e",
":",
"raise",
"try",
":",
"self",
".",
"_build",
"(",
"bluep... | Modify a table on the schema.
:param table: The table | [
"Modify",
"a",
"table",
"on",
"the",
"schema",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/builder.py#L62-L78 | train | 225,920 |
sdispater/orator | orator/schema/builder.py | SchemaBuilder.rename | def rename(self, from_, to):
"""
Rename a table on the schema.
"""
blueprint = self._create_blueprint(from_)
blueprint.rename(to)
self._build(blueprint) | python | def rename(self, from_, to):
"""
Rename a table on the schema.
"""
blueprint = self._create_blueprint(from_)
blueprint.rename(to)
self._build(blueprint) | [
"def",
"rename",
"(",
"self",
",",
"from_",
",",
"to",
")",
":",
"blueprint",
"=",
"self",
".",
"_create_blueprint",
"(",
"from_",
")",
"blueprint",
".",
"rename",
"(",
"to",
")",
"self",
".",
"_build",
"(",
"blueprint",
")"
] | Rename a table on the schema. | [
"Rename",
"a",
"table",
"on",
"the",
"schema",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/builder.py#L129-L137 | train | 225,921 |
sdispater/orator | orator/commands/migrations/make_command.py | MigrateMakeCommand._write_migration | def _write_migration(self, creator, name, table, create, path):
"""
Write the migration file to disk.
"""
file_ = os.path.basename(creator.create(name, path, table, create))
return file_ | python | def _write_migration(self, creator, name, table, create, path):
"""
Write the migration file to disk.
"""
file_ = os.path.basename(creator.create(name, path, table, create))
return file_ | [
"def",
"_write_migration",
"(",
"self",
",",
"creator",
",",
"name",
",",
"table",
",",
"create",
",",
"path",
")",
":",
"file_",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"creator",
".",
"create",
"(",
"name",
",",
"path",
",",
"table",
",",
"... | Write the migration file to disk. | [
"Write",
"the",
"migration",
"file",
"to",
"disk",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/commands/migrations/make_command.py#L42-L48 | train | 225,922 |
sdispater/orator | orator/query/grammars/mysql_grammar.py | MySQLQueryGrammar.compile_delete | def compile_delete(self, query):
"""
Compile a delete statement into SQL
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled update
:rtype: str
"""
table = self.wrap_table(query.from__)
if isinstance(query.wheres, list):
wheres = self._compile_wheres(query)
else:
wheres = ""
if query.joins:
joins = " %s" % self._compile_joins(query, query.joins)
sql = "DELETE %s FROM %s%s %s" % (table, table, joins, wheres)
else:
sql = "DELETE FROM %s %s" % (table, wheres)
sql = sql.strip()
if query.orders:
sql += " %s" % self._compile_orders(query, query.orders)
if query.limit_:
sql += " %s" % self._compile_limit(query, query.limit_)
return sql | python | def compile_delete(self, query):
"""
Compile a delete statement into SQL
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled update
:rtype: str
"""
table = self.wrap_table(query.from__)
if isinstance(query.wheres, list):
wheres = self._compile_wheres(query)
else:
wheres = ""
if query.joins:
joins = " %s" % self._compile_joins(query, query.joins)
sql = "DELETE %s FROM %s%s %s" % (table, table, joins, wheres)
else:
sql = "DELETE FROM %s %s" % (table, wheres)
sql = sql.strip()
if query.orders:
sql += " %s" % self._compile_orders(query, query.orders)
if query.limit_:
sql += " %s" % self._compile_limit(query, query.limit_)
return sql | [
"def",
"compile_delete",
"(",
"self",
",",
"query",
")",
":",
"table",
"=",
"self",
".",
"wrap_table",
"(",
"query",
".",
"from__",
")",
"if",
"isinstance",
"(",
"query",
".",
"wheres",
",",
"list",
")",
":",
"wheres",
"=",
"self",
".",
"_compile_where... | Compile a delete statement into SQL
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled update
:rtype: str | [
"Compile",
"a",
"delete",
"statement",
"into",
"SQL"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/grammars/mysql_grammar.py#L103-L135 | train | 225,923 |
sdispater/orator | orator/commands/command.py | Command._check_config | def _check_config(self):
"""
Check presence of default config files.
:rtype: bool
"""
current_path = os.path.relpath(os.getcwd())
accepted_files = ["orator.yml", "orator.py"]
for accepted_file in accepted_files:
config_file = os.path.join(current_path, accepted_file)
if os.path.exists(config_file):
if self._handle_config(config_file):
return True
return False | python | def _check_config(self):
"""
Check presence of default config files.
:rtype: bool
"""
current_path = os.path.relpath(os.getcwd())
accepted_files = ["orator.yml", "orator.py"]
for accepted_file in accepted_files:
config_file = os.path.join(current_path, accepted_file)
if os.path.exists(config_file):
if self._handle_config(config_file):
return True
return False | [
"def",
"_check_config",
"(",
"self",
")",
":",
"current_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"accepted_files",
"=",
"[",
"\"orator.yml\"",
",",
"\"orator.py\"",
"]",
"for",
"accepted_file",
"in",
"accepted... | Check presence of default config files.
:rtype: bool | [
"Check",
"presence",
"of",
"default",
"config",
"files",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/commands/command.py#L72-L87 | train | 225,924 |
sdispater/orator | orator/commands/command.py | Command._handle_config | def _handle_config(self, config_file):
"""
Check and handle a config file.
:param config_file: The path to the config file
:type config_file: str
:rtype: bool
"""
config = self._get_config(config_file)
self.resolver = DatabaseManager(
config.get("databases", config.get("DATABASES", {}))
)
return True | python | def _handle_config(self, config_file):
"""
Check and handle a config file.
:param config_file: The path to the config file
:type config_file: str
:rtype: bool
"""
config = self._get_config(config_file)
self.resolver = DatabaseManager(
config.get("databases", config.get("DATABASES", {}))
)
return True | [
"def",
"_handle_config",
"(",
"self",
",",
"config_file",
")",
":",
"config",
"=",
"self",
".",
"_get_config",
"(",
"config_file",
")",
"self",
".",
"resolver",
"=",
"DatabaseManager",
"(",
"config",
".",
"get",
"(",
"\"databases\"",
",",
"config",
".",
"g... | Check and handle a config file.
:param config_file: The path to the config file
:type config_file: str
:rtype: bool | [
"Check",
"and",
"handle",
"a",
"config",
"file",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/commands/command.py#L89-L104 | train | 225,925 |
sdispater/orator | orator/migrations/database_migration_repository.py | DatabaseMigrationRepository.log | def log(self, file, batch):
"""
Log that a migration was run.
:type file: str
:type batch: int
"""
record = {"migration": file, "batch": batch}
self.table().insert(**record) | python | def log(self, file, batch):
"""
Log that a migration was run.
:type file: str
:type batch: int
"""
record = {"migration": file, "batch": batch}
self.table().insert(**record) | [
"def",
"log",
"(",
"self",
",",
"file",
",",
"batch",
")",
":",
"record",
"=",
"{",
"\"migration\"",
":",
"file",
",",
"\"batch\"",
":",
"batch",
"}",
"self",
".",
"table",
"(",
")",
".",
"insert",
"(",
"*",
"*",
"record",
")"
] | Log that a migration was run.
:type file: str
:type batch: int | [
"Log",
"that",
"a",
"migration",
"was",
"run",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/database_migration_repository.py#L34-L43 | train | 225,926 |
sdispater/orator | orator/migrations/database_migration_repository.py | DatabaseMigrationRepository.create_repository | def create_repository(self):
"""
Create the migration repository data store.
"""
schema = self.get_connection().get_schema_builder()
with schema.create(self._table) as table:
# The migrations table is responsible for keeping track of which of the
# migrations have actually run for the application. We'll create the
# table to hold the migration file's path as well as the batch ID.
table.string("migration")
table.integer("batch") | python | def create_repository(self):
"""
Create the migration repository data store.
"""
schema = self.get_connection().get_schema_builder()
with schema.create(self._table) as table:
# The migrations table is responsible for keeping track of which of the
# migrations have actually run for the application. We'll create the
# table to hold the migration file's path as well as the batch ID.
table.string("migration")
table.integer("batch") | [
"def",
"create_repository",
"(",
"self",
")",
":",
"schema",
"=",
"self",
".",
"get_connection",
"(",
")",
".",
"get_schema_builder",
"(",
")",
"with",
"schema",
".",
"create",
"(",
"self",
".",
"_table",
")",
"as",
"table",
":",
"# The migrations table is r... | Create the migration repository data store. | [
"Create",
"the",
"migration",
"repository",
"data",
"store",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/database_migration_repository.py#L69-L80 | train | 225,927 |
sdispater/orator | orator/migrations/database_migration_repository.py | DatabaseMigrationRepository.repository_exists | def repository_exists(self):
"""
Determine if the repository exists.
:rtype: bool
"""
schema = self.get_connection().get_schema_builder()
return schema.has_table(self._table) | python | def repository_exists(self):
"""
Determine if the repository exists.
:rtype: bool
"""
schema = self.get_connection().get_schema_builder()
return schema.has_table(self._table) | [
"def",
"repository_exists",
"(",
"self",
")",
":",
"schema",
"=",
"self",
".",
"get_connection",
"(",
")",
".",
"get_schema_builder",
"(",
")",
"return",
"schema",
".",
"has_table",
"(",
"self",
".",
"_table",
")"
] | Determine if the repository exists.
:rtype: bool | [
"Determine",
"if",
"the",
"repository",
"exists",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/database_migration_repository.py#L82-L90 | train | 225,928 |
sdispater/orator | orator/migrations/migration_creator.py | MigrationCreator.create | def create(self, name, path, table=None, create=False):
"""
Create a new migration at the given path.
:param name: The name of the migration
:type name: str
:param path: The path of the migrations
:type path: str
:param table: The table name
:type table: str
:param create: Whether it's a create migration or not
:type create: bool
:rtype: str
"""
path = self._get_path(name, path)
if not os.path.exists(os.path.dirname(path)):
mkdir_p(os.path.dirname(path))
parent = os.path.join(os.path.dirname(path), "__init__.py")
if not os.path.exists(parent):
with open(parent, "w"):
pass
stub = self._get_stub(table, create)
with open(path, "w") as fh:
fh.write(self._populate_stub(name, stub, table))
return path | python | def create(self, name, path, table=None, create=False):
"""
Create a new migration at the given path.
:param name: The name of the migration
:type name: str
:param path: The path of the migrations
:type path: str
:param table: The table name
:type table: str
:param create: Whether it's a create migration or not
:type create: bool
:rtype: str
"""
path = self._get_path(name, path)
if not os.path.exists(os.path.dirname(path)):
mkdir_p(os.path.dirname(path))
parent = os.path.join(os.path.dirname(path), "__init__.py")
if not os.path.exists(parent):
with open(parent, "w"):
pass
stub = self._get_stub(table, create)
with open(path, "w") as fh:
fh.write(self._populate_stub(name, stub, table))
return path | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"path",
",",
"table",
"=",
"None",
",",
"create",
"=",
"False",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"name",
",",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
... | Create a new migration at the given path.
:param name: The name of the migration
:type name: str
:param path: The path of the migrations
:type path: str
:param table: The table name
:type table: str
:param create: Whether it's a create migration or not
:type create: bool
:rtype: str | [
"Create",
"a",
"new",
"migration",
"at",
"the",
"given",
"path",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/migration_creator.py#L21-L50 | train | 225,929 |
sdispater/orator | orator/migrations/migration_creator.py | MigrationCreator._get_stub | def _get_stub(self, table, create):
"""
Get the migration stub template
:param table: The table name
:type table: str
:param create: Whether it's a create migration or not
:type create: bool
:rtype: str
"""
if table is None:
return BLANK_STUB
else:
if create:
stub = CREATE_STUB
else:
stub = UPDATE_STUB
return stub | python | def _get_stub(self, table, create):
"""
Get the migration stub template
:param table: The table name
:type table: str
:param create: Whether it's a create migration or not
:type create: bool
:rtype: str
"""
if table is None:
return BLANK_STUB
else:
if create:
stub = CREATE_STUB
else:
stub = UPDATE_STUB
return stub | [
"def",
"_get_stub",
"(",
"self",
",",
"table",
",",
"create",
")",
":",
"if",
"table",
"is",
"None",
":",
"return",
"BLANK_STUB",
"else",
":",
"if",
"create",
":",
"stub",
"=",
"CREATE_STUB",
"else",
":",
"stub",
"=",
"UPDATE_STUB",
"return",
"stub"
] | Get the migration stub template
:param table: The table name
:type table: str
:param create: Whether it's a create migration or not
:type create: bool
:rtype: str | [
"Get",
"the",
"migration",
"stub",
"template"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/migration_creator.py#L52-L72 | train | 225,930 |
sdispater/orator | orator/dbal/foreign_key_constraint.py | ForeignKeyConstraint.get_quoted_local_columns | def get_quoted_local_columns(self, platform):
"""
Returns the quoted representation of the referencing table column names
the foreign key constraint is associated with.
But only if they were defined with one or the referencing table column name
is a keyword reserved by the platform.
Otherwise the plain unquoted value as inserted is returned.
:param platform: The platform to use for quotation.
:type platform: Platform
:rtype: list
"""
columns = []
for column in self._local_column_names.values():
columns.append(column.get_quoted_name(platform))
return columns | python | def get_quoted_local_columns(self, platform):
"""
Returns the quoted representation of the referencing table column names
the foreign key constraint is associated with.
But only if they were defined with one or the referencing table column name
is a keyword reserved by the platform.
Otherwise the plain unquoted value as inserted is returned.
:param platform: The platform to use for quotation.
:type platform: Platform
:rtype: list
"""
columns = []
for column in self._local_column_names.values():
columns.append(column.get_quoted_name(platform))
return columns | [
"def",
"get_quoted_local_columns",
"(",
"self",
",",
"platform",
")",
":",
"columns",
"=",
"[",
"]",
"for",
"column",
"in",
"self",
".",
"_local_column_names",
".",
"values",
"(",
")",
":",
"columns",
".",
"append",
"(",
"column",
".",
"get_quoted_name",
"... | Returns the quoted representation of the referencing table column names
the foreign key constraint is associated with.
But only if they were defined with one or the referencing table column name
is a keyword reserved by the platform.
Otherwise the plain unquoted value as inserted is returned.
:param platform: The platform to use for quotation.
:type platform: Platform
:rtype: list | [
"Returns",
"the",
"quoted",
"representation",
"of",
"the",
"referencing",
"table",
"column",
"names",
"the",
"foreign",
"key",
"constraint",
"is",
"associated",
"with",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/dbal/foreign_key_constraint.py#L96-L115 | train | 225,931 |
sdispater/orator | orator/dbal/foreign_key_constraint.py | ForeignKeyConstraint.get_quoted_foreign_columns | def get_quoted_foreign_columns(self, platform):
"""
Returns the quoted representation of the referenced table column names
the foreign key constraint is associated with.
But only if they were defined with one or the referenced table column name
is a keyword reserved by the platform.
Otherwise the plain unquoted value as inserted is returned.
:param platform: The platform to use for quotation.
:type platform: Platform
:rtype: list
"""
columns = []
for column in self._foreign_column_names.values():
columns.append(column.get_quoted_name(platform))
return columns | python | def get_quoted_foreign_columns(self, platform):
"""
Returns the quoted representation of the referenced table column names
the foreign key constraint is associated with.
But only if they were defined with one or the referenced table column name
is a keyword reserved by the platform.
Otherwise the plain unquoted value as inserted is returned.
:param platform: The platform to use for quotation.
:type platform: Platform
:rtype: list
"""
columns = []
for column in self._foreign_column_names.values():
columns.append(column.get_quoted_name(platform))
return columns | [
"def",
"get_quoted_foreign_columns",
"(",
"self",
",",
"platform",
")",
":",
"columns",
"=",
"[",
"]",
"for",
"column",
"in",
"self",
".",
"_foreign_column_names",
".",
"values",
"(",
")",
":",
"columns",
".",
"append",
"(",
"column",
".",
"get_quoted_name",... | Returns the quoted representation of the referenced table column names
the foreign key constraint is associated with.
But only if they were defined with one or the referenced table column name
is a keyword reserved by the platform.
Otherwise the plain unquoted value as inserted is returned.
:param platform: The platform to use for quotation.
:type platform: Platform
:rtype: list | [
"Returns",
"the",
"quoted",
"representation",
"of",
"the",
"referenced",
"table",
"column",
"names",
"the",
"foreign",
"key",
"constraint",
"is",
"associated",
"with",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/dbal/foreign_key_constraint.py#L189-L208 | train | 225,932 |
sdispater/orator | orator/dbal/foreign_key_constraint.py | ForeignKeyConstraint._on_event | def _on_event(self, event):
"""
Returns the referential action for a given database operation
on the referenced table the foreign key constraint is associated with.
:param event: Name of the database operation/event to return the referential action for.
:type event: str
:rtype: str or None
"""
if self.has_option(event):
on_event = self.get_option(event).upper()
if on_event not in ["NO ACTION", "RESTRICT"]:
return on_event
return False | python | def _on_event(self, event):
"""
Returns the referential action for a given database operation
on the referenced table the foreign key constraint is associated with.
:param event: Name of the database operation/event to return the referential action for.
:type event: str
:rtype: str or None
"""
if self.has_option(event):
on_event = self.get_option(event).upper()
if on_event not in ["NO ACTION", "RESTRICT"]:
return on_event
return False | [
"def",
"_on_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"has_option",
"(",
"event",
")",
":",
"on_event",
"=",
"self",
".",
"get_option",
"(",
"event",
")",
".",
"upper",
"(",
")",
"if",
"on_event",
"not",
"in",
"[",
"\"NO ACTION\... | Returns the referential action for a given database operation
on the referenced table the foreign key constraint is associated with.
:param event: Name of the database operation/event to return the referential action for.
:type event: str
:rtype: str or None | [
"Returns",
"the",
"referential",
"action",
"for",
"a",
"given",
"database",
"operation",
"on",
"the",
"referenced",
"table",
"the",
"foreign",
"key",
"constraint",
"is",
"associated",
"with",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/dbal/foreign_key_constraint.py#L246-L262 | train | 225,933 |
sdispater/orator | orator/migrations/migrator.py | Migrator.run | def run(self, path, pretend=False):
"""
Run the outstanding migrations for a given path.
:param path: The path
:type path: str
:param pretend: Whether we execute the migrations as dry-run
:type pretend: bool
"""
self._notes = []
files = self._get_migration_files(path)
ran = self._repository.get_ran()
migrations = [f for f in files if f not in ran]
self.run_migration_list(path, migrations, pretend) | python | def run(self, path, pretend=False):
"""
Run the outstanding migrations for a given path.
:param path: The path
:type path: str
:param pretend: Whether we execute the migrations as dry-run
:type pretend: bool
"""
self._notes = []
files = self._get_migration_files(path)
ran = self._repository.get_ran()
migrations = [f for f in files if f not in ran]
self.run_migration_list(path, migrations, pretend) | [
"def",
"run",
"(",
"self",
",",
"path",
",",
"pretend",
"=",
"False",
")",
":",
"self",
".",
"_notes",
"=",
"[",
"]",
"files",
"=",
"self",
".",
"_get_migration_files",
"(",
"path",
")",
"ran",
"=",
"self",
".",
"_repository",
".",
"get_ran",
"(",
... | Run the outstanding migrations for a given path.
:param path: The path
:type path: str
:param pretend: Whether we execute the migrations as dry-run
:type pretend: bool | [
"Run",
"the",
"outstanding",
"migrations",
"for",
"a",
"given",
"path",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/migrator.py#L34-L51 | train | 225,934 |
sdispater/orator | orator/migrations/migrator.py | Migrator.run_migration_list | def run_migration_list(self, path, migrations, pretend=False):
"""
Run a list of migrations.
:type migrations: list
:type pretend: bool
"""
if not migrations:
self._note("<info>Nothing to migrate</info>")
return
batch = self._repository.get_next_batch_number()
for f in migrations:
self._run_up(path, f, batch, pretend) | python | def run_migration_list(self, path, migrations, pretend=False):
"""
Run a list of migrations.
:type migrations: list
:type pretend: bool
"""
if not migrations:
self._note("<info>Nothing to migrate</info>")
return
batch = self._repository.get_next_batch_number()
for f in migrations:
self._run_up(path, f, batch, pretend) | [
"def",
"run_migration_list",
"(",
"self",
",",
"path",
",",
"migrations",
",",
"pretend",
"=",
"False",
")",
":",
"if",
"not",
"migrations",
":",
"self",
".",
"_note",
"(",
"\"<info>Nothing to migrate</info>\"",
")",
"return",
"batch",
"=",
"self",
".",
"_re... | Run a list of migrations.
:type migrations: list
:type pretend: bool | [
"Run",
"a",
"list",
"of",
"migrations",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/migrator.py#L53-L69 | train | 225,935 |
sdispater/orator | orator/migrations/migrator.py | Migrator.reset | def reset(self, path, pretend=False):
"""
Rolls all of the currently applied migrations back.
:param path: The path
:type path: str
:param pretend: Whether we execute the migrations as dry-run
:type pretend: bool
:rtype: count
"""
self._notes = []
migrations = sorted(self._repository.get_ran(), reverse=True)
count = len(migrations)
if count == 0:
self._note("<info>Nothing to rollback.</info>")
else:
for migration in migrations:
self._run_down(path, {"migration": migration}, pretend)
return count | python | def reset(self, path, pretend=False):
"""
Rolls all of the currently applied migrations back.
:param path: The path
:type path: str
:param pretend: Whether we execute the migrations as dry-run
:type pretend: bool
:rtype: count
"""
self._notes = []
migrations = sorted(self._repository.get_ran(), reverse=True)
count = len(migrations)
if count == 0:
self._note("<info>Nothing to rollback.</info>")
else:
for migration in migrations:
self._run_down(path, {"migration": migration}, pretend)
return count | [
"def",
"reset",
"(",
"self",
",",
"path",
",",
"pretend",
"=",
"False",
")",
":",
"self",
".",
"_notes",
"=",
"[",
"]",
"migrations",
"=",
"sorted",
"(",
"self",
".",
"_repository",
".",
"get_ran",
"(",
")",
",",
"reverse",
"=",
"True",
")",
"count... | Rolls all of the currently applied migrations back.
:param path: The path
:type path: str
:param pretend: Whether we execute the migrations as dry-run
:type pretend: bool
:rtype: count | [
"Rolls",
"all",
"of",
"the",
"currently",
"applied",
"migrations",
"back",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/migrator.py#L125-L149 | train | 225,936 |
sdispater/orator | orator/migrations/migrator.py | Migrator._get_migration_files | def _get_migration_files(self, path):
"""
Get all of the migration files in a given path.
:type path: str
:rtype: list
"""
files = glob.glob(os.path.join(path, "[0-9]*_*.py"))
if not files:
return []
files = list(map(lambda f: os.path.basename(f).replace(".py", ""), files))
files = sorted(files)
return files | python | def _get_migration_files(self, path):
"""
Get all of the migration files in a given path.
:type path: str
:rtype: list
"""
files = glob.glob(os.path.join(path, "[0-9]*_*.py"))
if not files:
return []
files = list(map(lambda f: os.path.basename(f).replace(".py", ""), files))
files = sorted(files)
return files | [
"def",
"_get_migration_files",
"(",
"self",
",",
"path",
")",
":",
"files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"[0-9]*_*.py\"",
")",
")",
"if",
"not",
"files",
":",
"return",
"[",
"]",
"files",
"=",
"... | Get all of the migration files in a given path.
:type path: str
:rtype: list | [
"Get",
"all",
"of",
"the",
"migration",
"files",
"in",
"a",
"given",
"path",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/migrator.py#L175-L192 | train | 225,937 |
sdispater/orator | orator/query/grammars/postgres_grammar.py | PostgresQueryGrammar._compile_update_columns | def _compile_update_columns(self, values):
"""
Compile the columns for the update statement
:param values: The columns
:type values: dict
:return: The compiled columns
:rtype: str
"""
columns = []
for key, value in values.items():
columns.append("%s = %s" % (self.wrap(key), self.parameter(value)))
return ", ".join(columns) | python | def _compile_update_columns(self, values):
"""
Compile the columns for the update statement
:param values: The columns
:type values: dict
:return: The compiled columns
:rtype: str
"""
columns = []
for key, value in values.items():
columns.append("%s = %s" % (self.wrap(key), self.parameter(value)))
return ", ".join(columns) | [
"def",
"_compile_update_columns",
"(",
"self",
",",
"values",
")",
":",
"columns",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"values",
".",
"items",
"(",
")",
":",
"columns",
".",
"append",
"(",
"\"%s = %s\"",
"%",
"(",
"self",
".",
"wrap",
"(... | Compile the columns for the update statement
:param values: The columns
:type values: dict
:return: The compiled columns
:rtype: str | [
"Compile",
"the",
"columns",
"for",
"the",
"update",
"statement"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/grammars/postgres_grammar.py#L74-L89 | train | 225,938 |
sdispater/orator | orator/query/grammars/postgres_grammar.py | PostgresQueryGrammar._compile_update_from | def _compile_update_from(self, query):
"""
Compile the "from" clause for an update with a join.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str
"""
if not query.joins:
return ""
froms = []
for join in query.joins:
froms.append(self.wrap_table(join.table))
if len(froms):
return " FROM %s" % ", ".join(froms)
return "" | python | def _compile_update_from(self, query):
"""
Compile the "from" clause for an update with a join.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str
"""
if not query.joins:
return ""
froms = []
for join in query.joins:
froms.append(self.wrap_table(join.table))
if len(froms):
return " FROM %s" % ", ".join(froms)
return "" | [
"def",
"_compile_update_from",
"(",
"self",
",",
"query",
")",
":",
"if",
"not",
"query",
".",
"joins",
":",
"return",
"\"\"",
"froms",
"=",
"[",
"]",
"for",
"join",
"in",
"query",
".",
"joins",
":",
"froms",
".",
"append",
"(",
"self",
".",
"wrap_ta... | Compile the "from" clause for an update with a join.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str | [
"Compile",
"the",
"from",
"clause",
"for",
"an",
"update",
"with",
"a",
"join",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/grammars/postgres_grammar.py#L91-L112 | train | 225,939 |
sdispater/orator | orator/query/grammars/postgres_grammar.py | PostgresQueryGrammar._compile_update_wheres | def _compile_update_wheres(self, query):
"""
Compile the additional where clauses for updates with joins.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str
"""
base_where = self._compile_wheres(query)
if not query.joins:
return base_where
join_where = self._compile_update_join_wheres(query)
if not base_where.strip():
return "WHERE %s" % self._remove_leading_boolean(join_where)
return "%s %s" % (base_where, join_where) | python | def _compile_update_wheres(self, query):
"""
Compile the additional where clauses for updates with joins.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str
"""
base_where = self._compile_wheres(query)
if not query.joins:
return base_where
join_where = self._compile_update_join_wheres(query)
if not base_where.strip():
return "WHERE %s" % self._remove_leading_boolean(join_where)
return "%s %s" % (base_where, join_where) | [
"def",
"_compile_update_wheres",
"(",
"self",
",",
"query",
")",
":",
"base_where",
"=",
"self",
".",
"_compile_wheres",
"(",
"query",
")",
"if",
"not",
"query",
".",
"joins",
":",
"return",
"base_where",
"join_where",
"=",
"self",
".",
"_compile_update_join_w... | Compile the additional where clauses for updates with joins.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str | [
"Compile",
"the",
"additional",
"where",
"clauses",
"for",
"updates",
"with",
"joins",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/grammars/postgres_grammar.py#L114-L134 | train | 225,940 |
sdispater/orator | orator/query/grammars/postgres_grammar.py | PostgresQueryGrammar._compile_update_join_wheres | def _compile_update_join_wheres(self, query):
"""
Compile the "join" clauses for an update.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str
"""
join_wheres = []
for join in query.joins:
for clause in join.clauses:
join_wheres.append(self._compile_join_constraints(clause))
return " ".join(join_wheres) | python | def _compile_update_join_wheres(self, query):
"""
Compile the "join" clauses for an update.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str
"""
join_wheres = []
for join in query.joins:
for clause in join.clauses:
join_wheres.append(self._compile_join_constraints(clause))
return " ".join(join_wheres) | [
"def",
"_compile_update_join_wheres",
"(",
"self",
",",
"query",
")",
":",
"join_wheres",
"=",
"[",
"]",
"for",
"join",
"in",
"query",
".",
"joins",
":",
"for",
"clause",
"in",
"join",
".",
"clauses",
":",
"join_wheres",
".",
"append",
"(",
"self",
".",
... | Compile the "join" clauses for an update.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str | [
"Compile",
"the",
"join",
"clauses",
"for",
"an",
"update",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/grammars/postgres_grammar.py#L136-L152 | train | 225,941 |
sdispater/orator | orator/query/grammars/postgres_grammar.py | PostgresQueryGrammar.compile_insert_get_id | def compile_insert_get_id(self, query, values, sequence=None):
"""
Compile an insert and get ID statement into SQL.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param values: The values to insert
:type values: dict
:param sequence: The id sequence
:type sequence: str
:return: The compiled statement
:rtype: str
"""
if sequence is None:
sequence = "id"
return "%s RETURNING %s" % (
self.compile_insert(query, values),
self.wrap(sequence),
) | python | def compile_insert_get_id(self, query, values, sequence=None):
"""
Compile an insert and get ID statement into SQL.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param values: The values to insert
:type values: dict
:param sequence: The id sequence
:type sequence: str
:return: The compiled statement
:rtype: str
"""
if sequence is None:
sequence = "id"
return "%s RETURNING %s" % (
self.compile_insert(query, values),
self.wrap(sequence),
) | [
"def",
"compile_insert_get_id",
"(",
"self",
",",
"query",
",",
"values",
",",
"sequence",
"=",
"None",
")",
":",
"if",
"sequence",
"is",
"None",
":",
"sequence",
"=",
"\"id\"",
"return",
"\"%s RETURNING %s\"",
"%",
"(",
"self",
".",
"compile_insert",
"(",
... | Compile an insert and get ID statement into SQL.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param values: The values to insert
:type values: dict
:param sequence: The id sequence
:type sequence: str
:return: The compiled statement
:rtype: str | [
"Compile",
"an",
"insert",
"and",
"get",
"ID",
"statement",
"into",
"SQL",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/grammars/postgres_grammar.py#L154-L176 | train | 225,942 |
sdispater/orator | orator/utils/qmarker.py | Qmarker.qmark | def qmark(cls, query):
"""
Convert a "qmark" query into "format" style.
"""
def sub_sequence(m):
s = m.group(0)
if s == "??":
return "?"
if s == "%":
return "%%"
else:
return "%s"
return cls.RE_QMARK.sub(sub_sequence, query) | python | def qmark(cls, query):
"""
Convert a "qmark" query into "format" style.
"""
def sub_sequence(m):
s = m.group(0)
if s == "??":
return "?"
if s == "%":
return "%%"
else:
return "%s"
return cls.RE_QMARK.sub(sub_sequence, query) | [
"def",
"qmark",
"(",
"cls",
",",
"query",
")",
":",
"def",
"sub_sequence",
"(",
"m",
")",
":",
"s",
"=",
"m",
".",
"group",
"(",
"0",
")",
"if",
"s",
"==",
"\"??\"",
":",
"return",
"\"?\"",
"if",
"s",
"==",
"\"%\"",
":",
"return",
"\"%%\"",
"el... | Convert a "qmark" query into "format" style. | [
"Convert",
"a",
"qmark",
"query",
"into",
"format",
"style",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/utils/qmarker.py#L11-L25 | train | 225,943 |
sdispater/orator | orator/orm/relations/relation.py | Relation.touch | def touch(self):
"""
Touch all of the related models for the relationship.
"""
column = self.get_related().get_updated_at_column()
self.raw_update({column: self.get_related().fresh_timestamp()}) | python | def touch(self):
"""
Touch all of the related models for the relationship.
"""
column = self.get_related().get_updated_at_column()
self.raw_update({column: self.get_related().fresh_timestamp()}) | [
"def",
"touch",
"(",
"self",
")",
":",
"column",
"=",
"self",
".",
"get_related",
"(",
")",
".",
"get_updated_at_column",
"(",
")",
"self",
".",
"raw_update",
"(",
"{",
"column",
":",
"self",
".",
"get_related",
"(",
")",
".",
"fresh_timestamp",
"(",
"... | Touch all of the related models for the relationship. | [
"Touch",
"all",
"of",
"the",
"related",
"models",
"for",
"the",
"relationship",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/relation.py#L77-L83 | train | 225,944 |
sdispater/orator | orator/orm/relations/relation.py | Relation.raw_update | def raw_update(self, attributes=None):
"""
Run a raw update against the base query.
:type attributes: dict
:rtype: int
"""
if attributes is None:
attributes = {}
if self._query is not None:
return self._query.update(attributes) | python | def raw_update(self, attributes=None):
"""
Run a raw update against the base query.
:type attributes: dict
:rtype: int
"""
if attributes is None:
attributes = {}
if self._query is not None:
return self._query.update(attributes) | [
"def",
"raw_update",
"(",
"self",
",",
"attributes",
"=",
"None",
")",
":",
"if",
"attributes",
"is",
"None",
":",
"attributes",
"=",
"{",
"}",
"if",
"self",
".",
"_query",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_query",
".",
"update",
"("... | Run a raw update against the base query.
:type attributes: dict
:rtype: int | [
"Run",
"a",
"raw",
"update",
"against",
"the",
"base",
"query",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/relation.py#L85-L97 | train | 225,945 |
sdispater/orator | orator/orm/relations/relation.py | Relation.wrap | def wrap(self, value):
"""
Wrap the given value with the parent's query grammar.
:rtype: str
"""
return self._parent.new_query().get_query().get_grammar().wrap(value) | python | def wrap(self, value):
"""
Wrap the given value with the parent's query grammar.
:rtype: str
"""
return self._parent.new_query().get_query().get_grammar().wrap(value) | [
"def",
"wrap",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"_parent",
".",
"new_query",
"(",
")",
".",
"get_query",
"(",
")",
".",
"get_grammar",
"(",
")",
".",
"wrap",
"(",
"value",
")"
] | Wrap the given value with the parent's query grammar.
:rtype: str | [
"Wrap",
"the",
"given",
"value",
"with",
"the",
"parent",
"s",
"query",
"grammar",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/relation.py#L199-L205 | train | 225,946 |
awslabs/aws-cfn-template-flip | cfn_flip/__init__.py | load | def load(template):
"""
Try to guess the input format
"""
try:
data = load_json(template)
return data, "json"
except ValueError as e:
try:
data = load_yaml(template)
return data, "yaml"
except Exception:
raise e | python | def load(template):
"""
Try to guess the input format
"""
try:
data = load_json(template)
return data, "json"
except ValueError as e:
try:
data = load_yaml(template)
return data, "yaml"
except Exception:
raise e | [
"def",
"load",
"(",
"template",
")",
":",
"try",
":",
"data",
"=",
"load_json",
"(",
"template",
")",
"return",
"data",
",",
"\"json\"",
"except",
"ValueError",
"as",
"e",
":",
"try",
":",
"data",
"=",
"load_yaml",
"(",
"template",
")",
"return",
"data... | Try to guess the input format | [
"Try",
"to",
"guess",
"the",
"input",
"format"
] | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_flip/__init__.py#L21-L34 | train | 225,947 |
awslabs/aws-cfn-template-flip | cfn_flip/__init__.py | dump_yaml | def dump_yaml(data, clean_up=False, long_form=False):
"""
Output some YAML
"""
return yaml.dump(
data,
Dumper=get_dumper(clean_up, long_form),
default_flow_style=False,
allow_unicode=True
) | python | def dump_yaml(data, clean_up=False, long_form=False):
"""
Output some YAML
"""
return yaml.dump(
data,
Dumper=get_dumper(clean_up, long_form),
default_flow_style=False,
allow_unicode=True
) | [
"def",
"dump_yaml",
"(",
"data",
",",
"clean_up",
"=",
"False",
",",
"long_form",
"=",
"False",
")",
":",
"return",
"yaml",
".",
"dump",
"(",
"data",
",",
"Dumper",
"=",
"get_dumper",
"(",
"clean_up",
",",
"long_form",
")",
",",
"default_flow_style",
"="... | Output some YAML | [
"Output",
"some",
"YAML"
] | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_flip/__init__.py#L37-L47 | train | 225,948 |
awslabs/aws-cfn-template-flip | cfn_flip/__init__.py | to_json | def to_json(template, clean_up=False):
"""
Assume the input is YAML and convert to JSON
"""
data = load_yaml(template)
if clean_up:
data = clean(data)
return dump_json(data) | python | def to_json(template, clean_up=False):
"""
Assume the input is YAML and convert to JSON
"""
data = load_yaml(template)
if clean_up:
data = clean(data)
return dump_json(data) | [
"def",
"to_json",
"(",
"template",
",",
"clean_up",
"=",
"False",
")",
":",
"data",
"=",
"load_yaml",
"(",
"template",
")",
"if",
"clean_up",
":",
"data",
"=",
"clean",
"(",
"data",
")",
"return",
"dump_json",
"(",
"data",
")"
] | Assume the input is YAML and convert to JSON | [
"Assume",
"the",
"input",
"is",
"YAML",
"and",
"convert",
"to",
"JSON"
] | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_flip/__init__.py#L50-L60 | train | 225,949 |
awslabs/aws-cfn-template-flip | cfn_flip/__init__.py | to_yaml | def to_yaml(template, clean_up=False, long_form=False):
"""
Assume the input is JSON and convert to YAML
"""
data = load_json(template)
if clean_up:
data = clean(data)
return dump_yaml(data, clean_up, long_form) | python | def to_yaml(template, clean_up=False, long_form=False):
"""
Assume the input is JSON and convert to YAML
"""
data = load_json(template)
if clean_up:
data = clean(data)
return dump_yaml(data, clean_up, long_form) | [
"def",
"to_yaml",
"(",
"template",
",",
"clean_up",
"=",
"False",
",",
"long_form",
"=",
"False",
")",
":",
"data",
"=",
"load_json",
"(",
"template",
")",
"if",
"clean_up",
":",
"data",
"=",
"clean",
"(",
"data",
")",
"return",
"dump_yaml",
"(",
"data... | Assume the input is JSON and convert to YAML | [
"Assume",
"the",
"input",
"is",
"JSON",
"and",
"convert",
"to",
"YAML"
] | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_flip/__init__.py#L63-L73 | train | 225,950 |
awslabs/aws-cfn-template-flip | cfn_flip/__init__.py | flip | def flip(template, in_format=None, out_format=None, clean_up=False, no_flip=False, long_form=False):
"""
Figure out the input format and convert the data to the opposing output format
"""
# Do we need to figure out the input format?
if not in_format:
# Load the template as JSON?
if (out_format == "json" and no_flip) or (out_format == "yaml" and not no_flip):
in_format = "json"
elif (out_format == "yaml" and no_flip) or (out_format == "json" and not no_flip):
in_format = "yaml"
# Load the data
if in_format == "json":
data = load_json(template)
elif in_format == "yaml":
data = load_yaml(template)
else:
data, in_format = load(template)
# Clean up?
if clean_up:
data = clean(data)
# Figure out the output format
if not out_format:
if (in_format == "json" and no_flip) or (in_format == "yaml" and not no_flip):
out_format = "json"
else:
out_format = "yaml"
# Finished!
if out_format == "json":
if sys.version[0] == "3":
return dump_json(data)
else:
return dump_json(data).encode('utf-8')
return dump_yaml(data, clean_up, long_form) | python | def flip(template, in_format=None, out_format=None, clean_up=False, no_flip=False, long_form=False):
"""
Figure out the input format and convert the data to the opposing output format
"""
# Do we need to figure out the input format?
if not in_format:
# Load the template as JSON?
if (out_format == "json" and no_flip) or (out_format == "yaml" and not no_flip):
in_format = "json"
elif (out_format == "yaml" and no_flip) or (out_format == "json" and not no_flip):
in_format = "yaml"
# Load the data
if in_format == "json":
data = load_json(template)
elif in_format == "yaml":
data = load_yaml(template)
else:
data, in_format = load(template)
# Clean up?
if clean_up:
data = clean(data)
# Figure out the output format
if not out_format:
if (in_format == "json" and no_flip) or (in_format == "yaml" and not no_flip):
out_format = "json"
else:
out_format = "yaml"
# Finished!
if out_format == "json":
if sys.version[0] == "3":
return dump_json(data)
else:
return dump_json(data).encode('utf-8')
return dump_yaml(data, clean_up, long_form) | [
"def",
"flip",
"(",
"template",
",",
"in_format",
"=",
"None",
",",
"out_format",
"=",
"None",
",",
"clean_up",
"=",
"False",
",",
"no_flip",
"=",
"False",
",",
"long_form",
"=",
"False",
")",
":",
"# Do we need to figure out the input format?",
"if",
"not",
... | Figure out the input format and convert the data to the opposing output format | [
"Figure",
"out",
"the",
"input",
"format",
"and",
"convert",
"the",
"data",
"to",
"the",
"opposing",
"output",
"format"
] | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_flip/__init__.py#L76-L115 | train | 225,951 |
awslabs/aws-cfn-template-flip | cfn_clean/__init__.py | convert_join | def convert_join(value):
"""
Fix a Join ;)
"""
if not isinstance(value, list) or len(value) != 2:
# Cowardly refuse
return value
sep, parts = value[0], value[1]
if isinstance(parts, six.string_types):
return parts
if not isinstance(parts, list):
# This looks tricky, just return the join as it was
return {
"Fn::Join": value,
}
plain_string = True
args = ODict()
new_parts = []
for part in parts:
part = clean(part)
if isinstance(part, dict):
plain_string = False
if "Ref" in part:
new_parts.append("${{{}}}".format(part["Ref"]))
elif "Fn::GetAtt" in part:
params = part["Fn::GetAtt"]
new_parts.append("${{{}}}".format(".".join(params)))
else:
for key, val in args.items():
# we want to bail if a conditional can evaluate to AWS::NoValue
if isinstance(val, dict):
if "Fn::If" in val and "AWS::NoValue" in str(val["Fn::If"]):
return {
"Fn::Join": value,
}
if val == part:
param_name = key
break
else:
param_name = "Param{}".format(len(args) + 1)
args[param_name] = part
new_parts.append("${{{}}}".format(param_name))
elif isinstance(part, six.string_types):
new_parts.append(part.replace("${", "${!"))
else:
# Doing something weird; refuse
return {
"Fn::Join": value
}
source = sep.join(new_parts)
if plain_string:
return source
if args:
return ODict((
("Fn::Sub", [source, args]),
))
return ODict((
("Fn::Sub", source),
)) | python | def convert_join(value):
"""
Fix a Join ;)
"""
if not isinstance(value, list) or len(value) != 2:
# Cowardly refuse
return value
sep, parts = value[0], value[1]
if isinstance(parts, six.string_types):
return parts
if not isinstance(parts, list):
# This looks tricky, just return the join as it was
return {
"Fn::Join": value,
}
plain_string = True
args = ODict()
new_parts = []
for part in parts:
part = clean(part)
if isinstance(part, dict):
plain_string = False
if "Ref" in part:
new_parts.append("${{{}}}".format(part["Ref"]))
elif "Fn::GetAtt" in part:
params = part["Fn::GetAtt"]
new_parts.append("${{{}}}".format(".".join(params)))
else:
for key, val in args.items():
# we want to bail if a conditional can evaluate to AWS::NoValue
if isinstance(val, dict):
if "Fn::If" in val and "AWS::NoValue" in str(val["Fn::If"]):
return {
"Fn::Join": value,
}
if val == part:
param_name = key
break
else:
param_name = "Param{}".format(len(args) + 1)
args[param_name] = part
new_parts.append("${{{}}}".format(param_name))
elif isinstance(part, six.string_types):
new_parts.append(part.replace("${", "${!"))
else:
# Doing something weird; refuse
return {
"Fn::Join": value
}
source = sep.join(new_parts)
if plain_string:
return source
if args:
return ODict((
("Fn::Sub", [source, args]),
))
return ODict((
("Fn::Sub", source),
)) | [
"def",
"convert_join",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
"or",
"len",
"(",
"value",
")",
"!=",
"2",
":",
"# Cowardly refuse",
"return",
"value",
"sep",
",",
"parts",
"=",
"value",
"[",
"0",
"]",
",",
... | Fix a Join ;) | [
"Fix",
"a",
"Join",
";",
")"
] | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_clean/__init__.py#L18-L93 | train | 225,952 |
awslabs/aws-cfn-template-flip | cfn_flip/yaml_dumper.py | map_representer | def map_representer(dumper, value):
"""
Deal with !Ref style function format and OrderedDict
"""
value = ODict(value.items())
if len(value.keys()) == 1:
key = list(value.keys())[0]
if key in CONVERTED_SUFFIXES:
return fn_representer(dumper, key, value[key])
if key.startswith(FN_PREFIX):
return fn_representer(dumper, key[4:], value[key])
return dumper.represent_mapping(TAG_MAP, value, flow_style=False) | python | def map_representer(dumper, value):
"""
Deal with !Ref style function format and OrderedDict
"""
value = ODict(value.items())
if len(value.keys()) == 1:
key = list(value.keys())[0]
if key in CONVERTED_SUFFIXES:
return fn_representer(dumper, key, value[key])
if key.startswith(FN_PREFIX):
return fn_representer(dumper, key[4:], value[key])
return dumper.represent_mapping(TAG_MAP, value, flow_style=False) | [
"def",
"map_representer",
"(",
"dumper",
",",
"value",
")",
":",
"value",
"=",
"ODict",
"(",
"value",
".",
"items",
"(",
")",
")",
"if",
"len",
"(",
"value",
".",
"keys",
"(",
")",
")",
"==",
"1",
":",
"key",
"=",
"list",
"(",
"value",
".",
"ke... | Deal with !Ref style function format and OrderedDict | [
"Deal",
"with",
"!Ref",
"style",
"function",
"format",
"and",
"OrderedDict"
] | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_flip/yaml_dumper.py#L84-L100 | train | 225,953 |
awslabs/aws-cfn-template-flip | cfn_tools/yaml_loader.py | multi_constructor | def multi_constructor(loader, tag_suffix, node):
"""
Deal with !Ref style function format
"""
if tag_suffix not in UNCONVERTED_SUFFIXES:
tag_suffix = "{}{}".format(FN_PREFIX, tag_suffix)
constructor = None
if tag_suffix == "Fn::GetAtt":
constructor = construct_getatt
elif isinstance(node, yaml.ScalarNode):
constructor = loader.construct_scalar
elif isinstance(node, yaml.SequenceNode):
constructor = loader.construct_sequence
elif isinstance(node, yaml.MappingNode):
constructor = loader.construct_mapping
else:
raise Exception("Bad tag: !{}".format(tag_suffix))
return ODict((
(tag_suffix, constructor(node)),
)) | python | def multi_constructor(loader, tag_suffix, node):
"""
Deal with !Ref style function format
"""
if tag_suffix not in UNCONVERTED_SUFFIXES:
tag_suffix = "{}{}".format(FN_PREFIX, tag_suffix)
constructor = None
if tag_suffix == "Fn::GetAtt":
constructor = construct_getatt
elif isinstance(node, yaml.ScalarNode):
constructor = loader.construct_scalar
elif isinstance(node, yaml.SequenceNode):
constructor = loader.construct_sequence
elif isinstance(node, yaml.MappingNode):
constructor = loader.construct_mapping
else:
raise Exception("Bad tag: !{}".format(tag_suffix))
return ODict((
(tag_suffix, constructor(node)),
)) | [
"def",
"multi_constructor",
"(",
"loader",
",",
"tag_suffix",
",",
"node",
")",
":",
"if",
"tag_suffix",
"not",
"in",
"UNCONVERTED_SUFFIXES",
":",
"tag_suffix",
"=",
"\"{}{}\"",
".",
"format",
"(",
"FN_PREFIX",
",",
"tag_suffix",
")",
"constructor",
"=",
"None... | Deal with !Ref style function format | [
"Deal",
"with",
"!Ref",
"style",
"function",
"format"
] | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_tools/yaml_loader.py#L24-L47 | train | 225,954 |
awslabs/aws-cfn-template-flip | cfn_tools/yaml_loader.py | construct_getatt | def construct_getatt(node):
"""
Reconstruct !GetAtt into a list
"""
if isinstance(node.value, six.text_type):
return node.value.split(".", 1)
elif isinstance(node.value, list):
return [s.value for s in node.value]
else:
raise ValueError("Unexpected node type: {}".format(type(node.value))) | python | def construct_getatt(node):
"""
Reconstruct !GetAtt into a list
"""
if isinstance(node.value, six.text_type):
return node.value.split(".", 1)
elif isinstance(node.value, list):
return [s.value for s in node.value]
else:
raise ValueError("Unexpected node type: {}".format(type(node.value))) | [
"def",
"construct_getatt",
"(",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"value",
",",
"six",
".",
"text_type",
")",
":",
"return",
"node",
".",
"value",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"elif",
"isinstance",
"(",
"node",
"."... | Reconstruct !GetAtt into a list | [
"Reconstruct",
"!GetAtt",
"into",
"a",
"list"
] | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_tools/yaml_loader.py#L50-L60 | train | 225,955 |
awslabs/aws-cfn-template-flip | cfn_tools/yaml_loader.py | construct_mapping | def construct_mapping(self, node, deep=False):
"""
Use ODict for maps
"""
mapping = ODict()
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
value = self.construct_object(value_node, deep=deep)
mapping[key] = value
return mapping | python | def construct_mapping(self, node, deep=False):
"""
Use ODict for maps
"""
mapping = ODict()
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
value = self.construct_object(value_node, deep=deep)
mapping[key] = value
return mapping | [
"def",
"construct_mapping",
"(",
"self",
",",
"node",
",",
"deep",
"=",
"False",
")",
":",
"mapping",
"=",
"ODict",
"(",
")",
"for",
"key_node",
",",
"value_node",
"in",
"node",
".",
"value",
":",
"key",
"=",
"self",
".",
"construct_object",
"(",
"key_... | Use ODict for maps | [
"Use",
"ODict",
"for",
"maps"
] | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_tools/yaml_loader.py#L63-L76 | train | 225,956 |
awslabs/aws-cfn-template-flip | cfn_flip/main.py | main | def main(ctx, **kwargs):
"""
AWS CloudFormation Template Flip is a tool that converts
AWS CloudFormation templates between JSON and YAML formats,
making use of the YAML format's short function syntax where possible.
"""
in_format = kwargs.pop('in_format')
out_format = kwargs.pop('out_format') or kwargs.pop('out_flag')
no_flip = kwargs.pop('no_flip')
clean = kwargs.pop('clean')
long_form = kwargs.pop('long')
input_file = kwargs.pop('input')
output_file = kwargs.pop('output')
if not in_format:
if input_file.name.endswith(".json"):
in_format = "json"
elif input_file.name.endswith(".yaml") or input_file.name.endswith(".yml"):
in_format = "yaml"
if input_file.name == "<stdin>" and sys.stdin.isatty():
click.echo(ctx.get_help())
ctx.exit()
try:
output_file.write(flip(
input_file.read(),
in_format=in_format,
out_format=out_format,
clean_up=clean,
no_flip=no_flip,
long_form=long_form
))
except Exception as e:
raise click.ClickException("{}".format(e)) | python | def main(ctx, **kwargs):
"""
AWS CloudFormation Template Flip is a tool that converts
AWS CloudFormation templates between JSON and YAML formats,
making use of the YAML format's short function syntax where possible.
"""
in_format = kwargs.pop('in_format')
out_format = kwargs.pop('out_format') or kwargs.pop('out_flag')
no_flip = kwargs.pop('no_flip')
clean = kwargs.pop('clean')
long_form = kwargs.pop('long')
input_file = kwargs.pop('input')
output_file = kwargs.pop('output')
if not in_format:
if input_file.name.endswith(".json"):
in_format = "json"
elif input_file.name.endswith(".yaml") or input_file.name.endswith(".yml"):
in_format = "yaml"
if input_file.name == "<stdin>" and sys.stdin.isatty():
click.echo(ctx.get_help())
ctx.exit()
try:
output_file.write(flip(
input_file.read(),
in_format=in_format,
out_format=out_format,
clean_up=clean,
no_flip=no_flip,
long_form=long_form
))
except Exception as e:
raise click.ClickException("{}".format(e)) | [
"def",
"main",
"(",
"ctx",
",",
"*",
"*",
"kwargs",
")",
":",
"in_format",
"=",
"kwargs",
".",
"pop",
"(",
"'in_format'",
")",
"out_format",
"=",
"kwargs",
".",
"pop",
"(",
"'out_format'",
")",
"or",
"kwargs",
".",
"pop",
"(",
"'out_flag'",
")",
"no_... | AWS CloudFormation Template Flip is a tool that converts
AWS CloudFormation templates between JSON and YAML formats,
making use of the YAML format's short function syntax where possible. | [
"AWS",
"CloudFormation",
"Template",
"Flip",
"is",
"a",
"tool",
"that",
"converts",
"AWS",
"CloudFormation",
"templates",
"between",
"JSON",
"and",
"YAML",
"formats",
"making",
"use",
"of",
"the",
"YAML",
"format",
"s",
"short",
"function",
"syntax",
"where",
... | 837576bea243e3f5efb0a20b84802371272e2d33 | https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_flip/main.py#L31-L65 | train | 225,957 |
fugue/credstash | credstash-migrate-autoversion.py | updateVersions | def updateVersions(region="us-east-1", table="credential-store"):
'''
do a full-table scan of the credential-store,
and update the version format of every credential if it is an integer
'''
dynamodb = boto3.resource('dynamodb', region_name=region)
secrets = dynamodb.Table(table)
response = secrets.scan(ProjectionExpression="#N, version, #K, contents, hmac",
ExpressionAttributeNames={"#N": "name", "#K": "key"})
items = response["Items"]
for old_item in items:
if isInt(old_item['version']):
new_item = copy.copy(old_item)
new_item['version'] = credstash.paddedInt(new_item['version'])
if new_item['version'] != old_item['version']:
secrets.put_item(Item=new_item)
secrets.delete_item(Key={'name': old_item['name'], 'version': old_item['version']})
else:
print "Skipping item: %s, %s" % (old_item['name'], old_item['version']) | python | def updateVersions(region="us-east-1", table="credential-store"):
'''
do a full-table scan of the credential-store,
and update the version format of every credential if it is an integer
'''
dynamodb = boto3.resource('dynamodb', region_name=region)
secrets = dynamodb.Table(table)
response = secrets.scan(ProjectionExpression="#N, version, #K, contents, hmac",
ExpressionAttributeNames={"#N": "name", "#K": "key"})
items = response["Items"]
for old_item in items:
if isInt(old_item['version']):
new_item = copy.copy(old_item)
new_item['version'] = credstash.paddedInt(new_item['version'])
if new_item['version'] != old_item['version']:
secrets.put_item(Item=new_item)
secrets.delete_item(Key={'name': old_item['name'], 'version': old_item['version']})
else:
print "Skipping item: %s, %s" % (old_item['name'], old_item['version']) | [
"def",
"updateVersions",
"(",
"region",
"=",
"\"us-east-1\"",
",",
"table",
"=",
"\"credential-store\"",
")",
":",
"dynamodb",
"=",
"boto3",
".",
"resource",
"(",
"'dynamodb'",
",",
"region_name",
"=",
"region",
")",
"secrets",
"=",
"dynamodb",
".",
"Table",
... | do a full-table scan of the credential-store,
and update the version format of every credential if it is an integer | [
"do",
"a",
"full",
"-",
"table",
"scan",
"of",
"the",
"credential",
"-",
"store",
"and",
"update",
"the",
"version",
"format",
"of",
"every",
"credential",
"if",
"it",
"is",
"an",
"integer"
] | 56df8e051fc4c8d15d5e7e373e88bf5bc13f3346 | https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash-migrate-autoversion.py#L16-L37 | train | 225,958 |
fugue/credstash | credstash.py | paddedInt | def paddedInt(i):
'''
return a string that contains `i`, left-padded with 0's up to PAD_LEN digits
'''
i_str = str(i)
pad = PAD_LEN - len(i_str)
return (pad * "0") + i_str | python | def paddedInt(i):
'''
return a string that contains `i`, left-padded with 0's up to PAD_LEN digits
'''
i_str = str(i)
pad = PAD_LEN - len(i_str)
return (pad * "0") + i_str | [
"def",
"paddedInt",
"(",
"i",
")",
":",
"i_str",
"=",
"str",
"(",
"i",
")",
"pad",
"=",
"PAD_LEN",
"-",
"len",
"(",
"i_str",
")",
"return",
"(",
"pad",
"*",
"\"0\"",
")",
"+",
"i_str"
] | return a string that contains `i`, left-padded with 0's up to PAD_LEN digits | [
"return",
"a",
"string",
"that",
"contains",
"i",
"left",
"-",
"padded",
"with",
"0",
"s",
"up",
"to",
"PAD_LEN",
"digits"
] | 56df8e051fc4c8d15d5e7e373e88bf5bc13f3346 | https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash.py#L207-L213 | train | 225,959 |
fugue/credstash | credstash.py | getHighestVersion | def getHighestVersion(name, region=None, table="credential-store",
**kwargs):
'''
Return the highest version of `name` in the table
'''
session = get_session(**kwargs)
dynamodb = session.resource('dynamodb', region_name=region)
secrets = dynamodb.Table(table)
response = secrets.query(Limit=1,
ScanIndexForward=False,
ConsistentRead=True,
KeyConditionExpression=boto3.dynamodb.conditions.Key(
"name").eq(name),
ProjectionExpression="version")
if response["Count"] == 0:
return 0
return response["Items"][0]["version"] | python | def getHighestVersion(name, region=None, table="credential-store",
**kwargs):
'''
Return the highest version of `name` in the table
'''
session = get_session(**kwargs)
dynamodb = session.resource('dynamodb', region_name=region)
secrets = dynamodb.Table(table)
response = secrets.query(Limit=1,
ScanIndexForward=False,
ConsistentRead=True,
KeyConditionExpression=boto3.dynamodb.conditions.Key(
"name").eq(name),
ProjectionExpression="version")
if response["Count"] == 0:
return 0
return response["Items"][0]["version"] | [
"def",
"getHighestVersion",
"(",
"name",
",",
"region",
"=",
"None",
",",
"table",
"=",
"\"credential-store\"",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"get_session",
"(",
"*",
"*",
"kwargs",
")",
"dynamodb",
"=",
"session",
".",
"resource",
"... | Return the highest version of `name` in the table | [
"Return",
"the",
"highest",
"version",
"of",
"name",
"in",
"the",
"table"
] | 56df8e051fc4c8d15d5e7e373e88bf5bc13f3346 | https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash.py#L216-L235 | train | 225,960 |
fugue/credstash | credstash.py | clean_fail | def clean_fail(func):
'''
A decorator to cleanly exit on a failed call to AWS.
catch a `botocore.exceptions.ClientError` raised from an action.
This sort of error is raised if you are targeting a region that
isn't set up (see, `credstash setup`.
'''
def func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except botocore.exceptions.ClientError as e:
print(str(e), file=sys.stderr)
sys.exit(1)
return func_wrapper | python | def clean_fail(func):
'''
A decorator to cleanly exit on a failed call to AWS.
catch a `botocore.exceptions.ClientError` raised from an action.
This sort of error is raised if you are targeting a region that
isn't set up (see, `credstash setup`.
'''
def func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except botocore.exceptions.ClientError as e:
print(str(e), file=sys.stderr)
sys.exit(1)
return func_wrapper | [
"def",
"clean_fail",
"(",
"func",
")",
":",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"botocore",
".",
"exceptions",
".",
"Cli... | A decorator to cleanly exit on a failed call to AWS.
catch a `botocore.exceptions.ClientError` raised from an action.
This sort of error is raised if you are targeting a region that
isn't set up (see, `credstash setup`. | [
"A",
"decorator",
"to",
"cleanly",
"exit",
"on",
"a",
"failed",
"call",
"to",
"AWS",
".",
"catch",
"a",
"botocore",
".",
"exceptions",
".",
"ClientError",
"raised",
"from",
"an",
"action",
".",
"This",
"sort",
"of",
"error",
"is",
"raised",
"if",
"you",
... | 56df8e051fc4c8d15d5e7e373e88bf5bc13f3346 | https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash.py#L238-L251 | train | 225,961 |
fugue/credstash | credstash.py | listSecrets | def listSecrets(region=None, table="credential-store", **kwargs):
'''
do a full-table scan of the credential-store,
and return the names and versions of every credential
'''
session = get_session(**kwargs)
dynamodb = session.resource('dynamodb', region_name=region)
secrets = dynamodb.Table(table)
last_evaluated_key = True
items = []
while last_evaluated_key:
params = dict(
ProjectionExpression="#N, version, #C",
ExpressionAttributeNames={"#N": "name", "#C": "comment"}
)
if last_evaluated_key is not True:
params['ExclusiveStartKey'] = last_evaluated_key
response = secrets.scan(**params)
last_evaluated_key = response.get('LastEvaluatedKey') # will set last evaluated key to a number
items.extend(response['Items'])
return items | python | def listSecrets(region=None, table="credential-store", **kwargs):
'''
do a full-table scan of the credential-store,
and return the names and versions of every credential
'''
session = get_session(**kwargs)
dynamodb = session.resource('dynamodb', region_name=region)
secrets = dynamodb.Table(table)
last_evaluated_key = True
items = []
while last_evaluated_key:
params = dict(
ProjectionExpression="#N, version, #C",
ExpressionAttributeNames={"#N": "name", "#C": "comment"}
)
if last_evaluated_key is not True:
params['ExclusiveStartKey'] = last_evaluated_key
response = secrets.scan(**params)
last_evaluated_key = response.get('LastEvaluatedKey') # will set last evaluated key to a number
items.extend(response['Items'])
return items | [
"def",
"listSecrets",
"(",
"region",
"=",
"None",
",",
"table",
"=",
"\"credential-store\"",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"get_session",
"(",
"*",
"*",
"kwargs",
")",
"dynamodb",
"=",
"session",
".",
"resource",
"(",
"'dynamodb'",
"... | do a full-table scan of the credential-store,
and return the names and versions of every credential | [
"do",
"a",
"full",
"-",
"table",
"scan",
"of",
"the",
"credential",
"-",
"store",
"and",
"return",
"the",
"names",
"and",
"versions",
"of",
"every",
"credential"
] | 56df8e051fc4c8d15d5e7e373e88bf5bc13f3346 | https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash.py#L254-L280 | train | 225,962 |
fugue/credstash | credstash.py | putSecret | def putSecret(name, secret, version="", kms_key="alias/credstash",
region=None, table="credential-store", context=None,
digest=DEFAULT_DIGEST, comment="", **kwargs):
'''
put a secret called `name` into the secret-store,
protected by the key kms_key
'''
if not context:
context = {}
session = get_session(**kwargs)
kms = session.client('kms', region_name=region)
key_service = KeyService(kms, kms_key, context)
sealed = seal_aes_ctr_legacy(
key_service,
secret,
digest_method=digest,
)
dynamodb = session.resource('dynamodb', region_name=region)
secrets = dynamodb.Table(table)
data = {
'name': name,
'version': paddedInt(version),
}
if comment:
data['comment'] = comment
data.update(sealed)
return secrets.put_item(Item=data, ConditionExpression=Attr('name').not_exists()) | python | def putSecret(name, secret, version="", kms_key="alias/credstash",
region=None, table="credential-store", context=None,
digest=DEFAULT_DIGEST, comment="", **kwargs):
'''
put a secret called `name` into the secret-store,
protected by the key kms_key
'''
if not context:
context = {}
session = get_session(**kwargs)
kms = session.client('kms', region_name=region)
key_service = KeyService(kms, kms_key, context)
sealed = seal_aes_ctr_legacy(
key_service,
secret,
digest_method=digest,
)
dynamodb = session.resource('dynamodb', region_name=region)
secrets = dynamodb.Table(table)
data = {
'name': name,
'version': paddedInt(version),
}
if comment:
data['comment'] = comment
data.update(sealed)
return secrets.put_item(Item=data, ConditionExpression=Attr('name').not_exists()) | [
"def",
"putSecret",
"(",
"name",
",",
"secret",
",",
"version",
"=",
"\"\"",
",",
"kms_key",
"=",
"\"alias/credstash\"",
",",
"region",
"=",
"None",
",",
"table",
"=",
"\"credential-store\"",
",",
"context",
"=",
"None",
",",
"digest",
"=",
"DEFAULT_DIGEST",... | put a secret called `name` into the secret-store,
protected by the key kms_key | [
"put",
"a",
"secret",
"called",
"name",
"into",
"the",
"secret",
"-",
"store",
"protected",
"by",
"the",
"key",
"kms_key"
] | 56df8e051fc4c8d15d5e7e373e88bf5bc13f3346 | https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash.py#L283-L312 | train | 225,963 |
fugue/credstash | credstash.py | getAllSecrets | def getAllSecrets(version="", region=None, table="credential-store",
context=None, credential=None, session=None, **kwargs):
'''
fetch and decrypt all secrets
'''
if session is None:
session = get_session(**kwargs)
dynamodb = session.resource('dynamodb', region_name=region)
kms = session.client('kms', region_name=region)
secrets = listSecrets(region, table, **kwargs)
# Only return the secrets that match the pattern in `credential`
# This already works out of the box with the CLI get action,
# but that action doesn't support wildcards when using as library
if credential and WILDCARD_CHAR in credential:
names = set(expand_wildcard(credential,
[x["name"]
for x in secrets]))
else:
names = set(x["name"] for x in secrets)
pool = ThreadPool(min(len(names), THREAD_POOL_MAX_SIZE))
results = pool.map(
lambda credential: getSecret(credential, version, region, table, context, dynamodb, kms, **kwargs),
names)
pool.close()
pool.join()
return dict(zip(names, results)) | python | def getAllSecrets(version="", region=None, table="credential-store",
context=None, credential=None, session=None, **kwargs):
'''
fetch and decrypt all secrets
'''
if session is None:
session = get_session(**kwargs)
dynamodb = session.resource('dynamodb', region_name=region)
kms = session.client('kms', region_name=region)
secrets = listSecrets(region, table, **kwargs)
# Only return the secrets that match the pattern in `credential`
# This already works out of the box with the CLI get action,
# but that action doesn't support wildcards when using as library
if credential and WILDCARD_CHAR in credential:
names = set(expand_wildcard(credential,
[x["name"]
for x in secrets]))
else:
names = set(x["name"] for x in secrets)
pool = ThreadPool(min(len(names), THREAD_POOL_MAX_SIZE))
results = pool.map(
lambda credential: getSecret(credential, version, region, table, context, dynamodb, kms, **kwargs),
names)
pool.close()
pool.join()
return dict(zip(names, results)) | [
"def",
"getAllSecrets",
"(",
"version",
"=",
"\"\"",
",",
"region",
"=",
"None",
",",
"table",
"=",
"\"credential-store\"",
",",
"context",
"=",
"None",
",",
"credential",
"=",
"None",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if... | fetch and decrypt all secrets | [
"fetch",
"and",
"decrypt",
"all",
"secrets"
] | 56df8e051fc4c8d15d5e7e373e88bf5bc13f3346 | https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash.py#L315-L342 | train | 225,964 |
fugue/credstash | credstash.py | getSecret | def getSecret(name, version="", region=None,
table="credential-store", context=None,
dynamodb=None, kms=None, **kwargs):
'''
fetch and decrypt the secret called `name`
'''
if not context:
context = {}
# Can we cache
if dynamodb is None or kms is None:
session = get_session(**kwargs)
if dynamodb is None:
dynamodb = session.resource('dynamodb', region_name=region)
if kms is None:
kms = session.client('kms', region_name=region)
secrets = dynamodb.Table(table)
if version == "":
# do a consistent fetch of the credential with the highest version
response = secrets.query(Limit=1,
ScanIndexForward=False,
ConsistentRead=True,
KeyConditionExpression=boto3.dynamodb.conditions.Key("name").eq(name))
if response["Count"] == 0:
raise ItemNotFound("Item {'name': '%s'} couldn't be found." % name)
material = response["Items"][0]
else:
response = secrets.get_item(Key={"name": name, "version": version})
if "Item" not in response:
raise ItemNotFound(
"Item {'name': '%s', 'version': '%s'} couldn't be found." % (name, version))
material = response["Item"]
key_service = KeyService(kms, None, context)
return open_aes_ctr_legacy(key_service, material) | python | def getSecret(name, version="", region=None,
table="credential-store", context=None,
dynamodb=None, kms=None, **kwargs):
'''
fetch and decrypt the secret called `name`
'''
if not context:
context = {}
# Can we cache
if dynamodb is None or kms is None:
session = get_session(**kwargs)
if dynamodb is None:
dynamodb = session.resource('dynamodb', region_name=region)
if kms is None:
kms = session.client('kms', region_name=region)
secrets = dynamodb.Table(table)
if version == "":
# do a consistent fetch of the credential with the highest version
response = secrets.query(Limit=1,
ScanIndexForward=False,
ConsistentRead=True,
KeyConditionExpression=boto3.dynamodb.conditions.Key("name").eq(name))
if response["Count"] == 0:
raise ItemNotFound("Item {'name': '%s'} couldn't be found." % name)
material = response["Items"][0]
else:
response = secrets.get_item(Key={"name": name, "version": version})
if "Item" not in response:
raise ItemNotFound(
"Item {'name': '%s', 'version': '%s'} couldn't be found." % (name, version))
material = response["Item"]
key_service = KeyService(kms, None, context)
return open_aes_ctr_legacy(key_service, material) | [
"def",
"getSecret",
"(",
"name",
",",
"version",
"=",
"\"\"",
",",
"region",
"=",
"None",
",",
"table",
"=",
"\"credential-store\"",
",",
"context",
"=",
"None",
",",
"dynamodb",
"=",
"None",
",",
"kms",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":"... | fetch and decrypt the secret called `name` | [
"fetch",
"and",
"decrypt",
"the",
"secret",
"called",
"name"
] | 56df8e051fc4c8d15d5e7e373e88bf5bc13f3346 | https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash.py#L468-L505 | train | 225,965 |
fugue/credstash | credstash.py | createDdbTable | def createDdbTable(region=None, table="credential-store", **kwargs):
'''
create the secret store table in DDB in the specified region
'''
session = get_session(**kwargs)
dynamodb = session.resource("dynamodb", region_name=region)
if table in (t.name for t in dynamodb.tables.all()):
print("Credential Store table already exists")
return
print("Creating table...")
dynamodb.create_table(
TableName=table,
KeySchema=[
{
"AttributeName": "name",
"KeyType": "HASH",
},
{
"AttributeName": "version",
"KeyType": "RANGE",
}
],
AttributeDefinitions=[
{
"AttributeName": "name",
"AttributeType": "S",
},
{
"AttributeName": "version",
"AttributeType": "S",
},
],
ProvisionedThroughput={
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1,
}
)
print("Waiting for table to be created...")
client = session.client("dynamodb", region_name=region)
response = client.describe_table(TableName=table)
client.get_waiter("table_exists").wait(TableName=table)
print("Adding tag...")
client.tag_resource(
ResourceArn=response["Table"]["TableArn"],
Tags=[
{
'Key': "Name",
'Value': "credstash"
},
]
)
print("Table has been created. "
"Go read the README about how to create your KMS key") | python | def createDdbTable(region=None, table="credential-store", **kwargs):
'''
create the secret store table in DDB in the specified region
'''
session = get_session(**kwargs)
dynamodb = session.resource("dynamodb", region_name=region)
if table in (t.name for t in dynamodb.tables.all()):
print("Credential Store table already exists")
return
print("Creating table...")
dynamodb.create_table(
TableName=table,
KeySchema=[
{
"AttributeName": "name",
"KeyType": "HASH",
},
{
"AttributeName": "version",
"KeyType": "RANGE",
}
],
AttributeDefinitions=[
{
"AttributeName": "name",
"AttributeType": "S",
},
{
"AttributeName": "version",
"AttributeType": "S",
},
],
ProvisionedThroughput={
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1,
}
)
print("Waiting for table to be created...")
client = session.client("dynamodb", region_name=region)
response = client.describe_table(TableName=table)
client.get_waiter("table_exists").wait(TableName=table)
print("Adding tag...")
client.tag_resource(
ResourceArn=response["Table"]["TableArn"],
Tags=[
{
'Key': "Name",
'Value': "credstash"
},
]
)
print("Table has been created. "
"Go read the README about how to create your KMS key") | [
"def",
"createDdbTable",
"(",
"region",
"=",
"None",
",",
"table",
"=",
"\"credential-store\"",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"get_session",
"(",
"*",
"*",
"kwargs",
")",
"dynamodb",
"=",
"session",
".",
"resource",
"(",
"\"dynamodb\""... | create the secret store table in DDB in the specified region | [
"create",
"the",
"secret",
"store",
"table",
"in",
"DDB",
"in",
"the",
"specified",
"region"
] | 56df8e051fc4c8d15d5e7e373e88bf5bc13f3346 | https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash.py#L526-L585 | train | 225,966 |
fugue/credstash | credstash.py | seal_aes_ctr_legacy | def seal_aes_ctr_legacy(key_service, secret, digest_method=DEFAULT_DIGEST):
"""
Encrypts `secret` using the key service.
You can decrypt with the companion method `open_aes_ctr_legacy`.
"""
# generate a a 64 byte key.
# Half will be for data encryption, the other half for HMAC
key, encoded_key = key_service.generate_key_data(64)
ciphertext, hmac = _seal_aes_ctr(
secret, key, LEGACY_NONCE, digest_method,
)
return {
'key': b64encode(encoded_key).decode('utf-8'),
'contents': b64encode(ciphertext).decode('utf-8'),
'hmac': codecs.encode(hmac, "hex_codec"),
'digest': digest_method,
} | python | def seal_aes_ctr_legacy(key_service, secret, digest_method=DEFAULT_DIGEST):
"""
Encrypts `secret` using the key service.
You can decrypt with the companion method `open_aes_ctr_legacy`.
"""
# generate a a 64 byte key.
# Half will be for data encryption, the other half for HMAC
key, encoded_key = key_service.generate_key_data(64)
ciphertext, hmac = _seal_aes_ctr(
secret, key, LEGACY_NONCE, digest_method,
)
return {
'key': b64encode(encoded_key).decode('utf-8'),
'contents': b64encode(ciphertext).decode('utf-8'),
'hmac': codecs.encode(hmac, "hex_codec"),
'digest': digest_method,
} | [
"def",
"seal_aes_ctr_legacy",
"(",
"key_service",
",",
"secret",
",",
"digest_method",
"=",
"DEFAULT_DIGEST",
")",
":",
"# generate a a 64 byte key.",
"# Half will be for data encryption, the other half for HMAC",
"key",
",",
"encoded_key",
"=",
"key_service",
".",
"generate_... | Encrypts `secret` using the key service.
You can decrypt with the companion method `open_aes_ctr_legacy`. | [
"Encrypts",
"secret",
"using",
"the",
"key",
"service",
".",
"You",
"can",
"decrypt",
"with",
"the",
"companion",
"method",
"open_aes_ctr_legacy",
"."
] | 56df8e051fc4c8d15d5e7e373e88bf5bc13f3346 | https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash.py#L625-L641 | train | 225,967 |
KristianOellegaard/django-health-check | health_check/contrib/rabbitmq/backends.py | RabbitMQHealthCheck.check_status | def check_status(self):
"""Check RabbitMQ service by opening and closing a broker channel."""
logger.debug("Checking for a broker_url on django settings...")
broker_url = getattr(settings, "BROKER_URL", None)
logger.debug("Got %s as the broker_url. Connecting to rabbit...", broker_url)
logger.debug("Attempting to connect to rabbit...")
try:
# conn is used as a context to release opened resources later
with Connection(broker_url) as conn:
conn.connect() # exceptions may be raised upon calling connect
except ConnectionRefusedError as e:
self.add_error(ServiceUnavailable("Unable to connect to RabbitMQ: Connection was refused."), e)
except AccessRefused as e:
self.add_error(ServiceUnavailable("Unable to connect to RabbitMQ: Authentication error."), e)
except IOError as e:
self.add_error(ServiceUnavailable("IOError"), e)
except BaseException as e:
self.add_error(ServiceUnavailable("Unknown error"), e)
else:
logger.debug("Connection estabilished. RabbitMQ is healthy.") | python | def check_status(self):
"""Check RabbitMQ service by opening and closing a broker channel."""
logger.debug("Checking for a broker_url on django settings...")
broker_url = getattr(settings, "BROKER_URL", None)
logger.debug("Got %s as the broker_url. Connecting to rabbit...", broker_url)
logger.debug("Attempting to connect to rabbit...")
try:
# conn is used as a context to release opened resources later
with Connection(broker_url) as conn:
conn.connect() # exceptions may be raised upon calling connect
except ConnectionRefusedError as e:
self.add_error(ServiceUnavailable("Unable to connect to RabbitMQ: Connection was refused."), e)
except AccessRefused as e:
self.add_error(ServiceUnavailable("Unable to connect to RabbitMQ: Authentication error."), e)
except IOError as e:
self.add_error(ServiceUnavailable("IOError"), e)
except BaseException as e:
self.add_error(ServiceUnavailable("Unknown error"), e)
else:
logger.debug("Connection estabilished. RabbitMQ is healthy.") | [
"def",
"check_status",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Checking for a broker_url on django settings...\"",
")",
"broker_url",
"=",
"getattr",
"(",
"settings",
",",
"\"BROKER_URL\"",
",",
"None",
")",
"logger",
".",
"debug",
"(",
"\"Got %s as... | Check RabbitMQ service by opening and closing a broker channel. | [
"Check",
"RabbitMQ",
"service",
"by",
"opening",
"and",
"closing",
"a",
"broker",
"channel",
"."
] | 575f811b7224dba0ef5f113791ca6aab20711041 | https://github.com/KristianOellegaard/django-health-check/blob/575f811b7224dba0ef5f113791ca6aab20711041/health_check/contrib/rabbitmq/backends.py#L16-L41 | train | 225,968 |
KristianOellegaard/django-health-check | health_check/views.py | MediaType.from_string | def from_string(cls, value):
"""Return single instance parsed from given accept header string."""
match = cls.pattern.search(value)
if match is None:
raise ValueError('"%s" is not a valid media type' % value)
try:
return cls(match.group('mime_type'), float(match.group('weight') or 1))
except ValueError:
return cls(value) | python | def from_string(cls, value):
"""Return single instance parsed from given accept header string."""
match = cls.pattern.search(value)
if match is None:
raise ValueError('"%s" is not a valid media type' % value)
try:
return cls(match.group('mime_type'), float(match.group('weight') or 1))
except ValueError:
return cls(value) | [
"def",
"from_string",
"(",
"cls",
",",
"value",
")",
":",
"match",
"=",
"cls",
".",
"pattern",
".",
"search",
"(",
"value",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'\"%s\" is not a valid media type'",
"%",
"value",
")",
"try",
... | Return single instance parsed from given accept header string. | [
"Return",
"single",
"instance",
"parsed",
"from",
"given",
"accept",
"header",
"string",
"."
] | 575f811b7224dba0ef5f113791ca6aab20711041 | https://github.com/KristianOellegaard/django-health-check/blob/575f811b7224dba0ef5f113791ca6aab20711041/health_check/views.py#L28-L36 | train | 225,969 |
KristianOellegaard/django-health-check | health_check/views.py | MediaType.parse_header | def parse_header(cls, value='*/*'):
"""Parse HTTP accept header and return instances sorted by weight."""
yield from sorted((
cls.from_string(token.strip())
for token in value.split(',')
if token.strip()
), reverse=True) | python | def parse_header(cls, value='*/*'):
"""Parse HTTP accept header and return instances sorted by weight."""
yield from sorted((
cls.from_string(token.strip())
for token in value.split(',')
if token.strip()
), reverse=True) | [
"def",
"parse_header",
"(",
"cls",
",",
"value",
"=",
"'*/*'",
")",
":",
"yield",
"from",
"sorted",
"(",
"(",
"cls",
".",
"from_string",
"(",
"token",
".",
"strip",
"(",
")",
")",
"for",
"token",
"in",
"value",
".",
"split",
"(",
"','",
")",
"if",
... | Parse HTTP accept header and return instances sorted by weight. | [
"Parse",
"HTTP",
"accept",
"header",
"and",
"return",
"instances",
"sorted",
"by",
"weight",
"."
] | 575f811b7224dba0ef5f113791ca6aab20711041 | https://github.com/KristianOellegaard/django-health-check/blob/575f811b7224dba0ef5f113791ca6aab20711041/health_check/views.py#L39-L45 | train | 225,970 |
spulec/freezegun | freezegun/api.py | convert_to_timezone_naive | def convert_to_timezone_naive(time_to_freeze):
"""
Converts a potentially timezone-aware datetime to be a naive UTC datetime
"""
if time_to_freeze.tzinfo:
time_to_freeze -= time_to_freeze.utcoffset()
time_to_freeze = time_to_freeze.replace(tzinfo=None)
return time_to_freeze | python | def convert_to_timezone_naive(time_to_freeze):
"""
Converts a potentially timezone-aware datetime to be a naive UTC datetime
"""
if time_to_freeze.tzinfo:
time_to_freeze -= time_to_freeze.utcoffset()
time_to_freeze = time_to_freeze.replace(tzinfo=None)
return time_to_freeze | [
"def",
"convert_to_timezone_naive",
"(",
"time_to_freeze",
")",
":",
"if",
"time_to_freeze",
".",
"tzinfo",
":",
"time_to_freeze",
"-=",
"time_to_freeze",
".",
"utcoffset",
"(",
")",
"time_to_freeze",
"=",
"time_to_freeze",
".",
"replace",
"(",
"tzinfo",
"=",
"Non... | Converts a potentially timezone-aware datetime to be a naive UTC datetime | [
"Converts",
"a",
"potentially",
"timezone",
"-",
"aware",
"datetime",
"to",
"be",
"a",
"naive",
"UTC",
"datetime"
] | 9347d133f33f675c87bb0569d70d9d95abef737f | https://github.com/spulec/freezegun/blob/9347d133f33f675c87bb0569d70d9d95abef737f/freezegun/api.py#L364-L371 | train | 225,971 |
spulec/freezegun | freezegun/api.py | FrozenDateTimeFactory.move_to | def move_to(self, target_datetime):
"""Moves frozen date to the given ``target_datetime``"""
target_datetime = _parse_time_to_freeze(target_datetime)
delta = target_datetime - self.time_to_freeze
self.tick(delta=delta) | python | def move_to(self, target_datetime):
"""Moves frozen date to the given ``target_datetime``"""
target_datetime = _parse_time_to_freeze(target_datetime)
delta = target_datetime - self.time_to_freeze
self.tick(delta=delta) | [
"def",
"move_to",
"(",
"self",
",",
"target_datetime",
")",
":",
"target_datetime",
"=",
"_parse_time_to_freeze",
"(",
"target_datetime",
")",
"delta",
"=",
"target_datetime",
"-",
"self",
".",
"time_to_freeze",
"self",
".",
"tick",
"(",
"delta",
"=",
"delta",
... | Moves frozen date to the given ``target_datetime`` | [
"Moves",
"frozen",
"date",
"to",
"the",
"given",
"target_datetime"
] | 9347d133f33f675c87bb0569d70d9d95abef737f | https://github.com/spulec/freezegun/blob/9347d133f33f675c87bb0569d70d9d95abef737f/freezegun/api.py#L448-L452 | train | 225,972 |
mbj4668/pyang | pyang/plugins/jsonxsl.py | JsonXslPlugin.process_module | def process_module(self, yam):
"""Process data nodes, RPCs and notifications in a single module."""
for ann in yam.search(("ietf-yang-metadata", "annotation")):
self.process_annotation(ann)
for ch in yam.i_children[:]:
if ch.keyword == "rpc":
self.process_rpc(ch)
elif ch.keyword == "notification":
self.process_notification(ch)
else:
continue
yam.i_children.remove(ch)
self.process_children(yam, "//nc:*", 1) | python | def process_module(self, yam):
"""Process data nodes, RPCs and notifications in a single module."""
for ann in yam.search(("ietf-yang-metadata", "annotation")):
self.process_annotation(ann)
for ch in yam.i_children[:]:
if ch.keyword == "rpc":
self.process_rpc(ch)
elif ch.keyword == "notification":
self.process_notification(ch)
else:
continue
yam.i_children.remove(ch)
self.process_children(yam, "//nc:*", 1) | [
"def",
"process_module",
"(",
"self",
",",
"yam",
")",
":",
"for",
"ann",
"in",
"yam",
".",
"search",
"(",
"(",
"\"ietf-yang-metadata\"",
",",
"\"annotation\"",
")",
")",
":",
"self",
".",
"process_annotation",
"(",
"ann",
")",
"for",
"ch",
"in",
"yam",
... | Process data nodes, RPCs and notifications in a single module. | [
"Process",
"data",
"nodes",
"RPCs",
"and",
"notifications",
"in",
"a",
"single",
"module",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/jsonxsl.py#L101-L113 | train | 225,973 |
mbj4668/pyang | pyang/plugins/jsonxsl.py | JsonXslPlugin.process_annotation | def process_annotation(self, ann):
"""Process metadata annotation."""
tmpl = self.xsl_template("@" + self.qname(ann))
ET.SubElement(tmpl, "param", name="level", select="0")
ct = self.xsl_calltemplate("leaf", tmpl)
ET.SubElement(ct, "with-param", name="level", select="$level")
self.xsl_withparam("nsid", ann.i_module.i_modulename + ":", ct)
self.type_param(ann, ct) | python | def process_annotation(self, ann):
"""Process metadata annotation."""
tmpl = self.xsl_template("@" + self.qname(ann))
ET.SubElement(tmpl, "param", name="level", select="0")
ct = self.xsl_calltemplate("leaf", tmpl)
ET.SubElement(ct, "with-param", name="level", select="$level")
self.xsl_withparam("nsid", ann.i_module.i_modulename + ":", ct)
self.type_param(ann, ct) | [
"def",
"process_annotation",
"(",
"self",
",",
"ann",
")",
":",
"tmpl",
"=",
"self",
".",
"xsl_template",
"(",
"\"@\"",
"+",
"self",
".",
"qname",
"(",
"ann",
")",
")",
"ET",
".",
"SubElement",
"(",
"tmpl",
",",
"\"param\"",
",",
"name",
"=",
"\"leve... | Process metadata annotation. | [
"Process",
"metadata",
"annotation",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/jsonxsl.py#L115-L122 | train | 225,974 |
mbj4668/pyang | pyang/plugins/jsonxsl.py | JsonXslPlugin.process_rpc | def process_rpc(self, rpc):
"""Process input and output parts of `rpc`."""
p = "/nc:rpc/" + self.qname(rpc)
tmpl = self.xsl_template(p)
inp = rpc.search_one("input")
if inp is not None:
ct = self.xsl_calltemplate("rpc-input", tmpl)
self.xsl_withparam("nsid", rpc.i_module.i_modulename + ":", ct)
self.process_children(inp, p, 2)
outp = rpc.search_one("output")
if outp is not None:
self.process_children(outp, "/nc:rpc-reply", 1) | python | def process_rpc(self, rpc):
"""Process input and output parts of `rpc`."""
p = "/nc:rpc/" + self.qname(rpc)
tmpl = self.xsl_template(p)
inp = rpc.search_one("input")
if inp is not None:
ct = self.xsl_calltemplate("rpc-input", tmpl)
self.xsl_withparam("nsid", rpc.i_module.i_modulename + ":", ct)
self.process_children(inp, p, 2)
outp = rpc.search_one("output")
if outp is not None:
self.process_children(outp, "/nc:rpc-reply", 1) | [
"def",
"process_rpc",
"(",
"self",
",",
"rpc",
")",
":",
"p",
"=",
"\"/nc:rpc/\"",
"+",
"self",
".",
"qname",
"(",
"rpc",
")",
"tmpl",
"=",
"self",
".",
"xsl_template",
"(",
"p",
")",
"inp",
"=",
"rpc",
".",
"search_one",
"(",
"\"input\"",
")",
"if... | Process input and output parts of `rpc`. | [
"Process",
"input",
"and",
"output",
"parts",
"of",
"rpc",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/jsonxsl.py#L124-L135 | train | 225,975 |
mbj4668/pyang | pyang/plugins/jsonxsl.py | JsonXslPlugin.process_notification | def process_notification(self, ntf):
"""Process event notification `ntf`."""
p = "/en:notification/" + self.qname(ntf)
tmpl = self.xsl_template(p)
ct = self.xsl_calltemplate("container", tmpl)
self.xsl_withparam("level", "1", ct)
if ntf.arg == "eventTime": # local name collision
self.xsl_withparam("nsid", ntf.i_module.i_modulename + ":", ct)
self.process_children(ntf, p, 2) | python | def process_notification(self, ntf):
"""Process event notification `ntf`."""
p = "/en:notification/" + self.qname(ntf)
tmpl = self.xsl_template(p)
ct = self.xsl_calltemplate("container", tmpl)
self.xsl_withparam("level", "1", ct)
if ntf.arg == "eventTime": # local name collision
self.xsl_withparam("nsid", ntf.i_module.i_modulename + ":", ct)
self.process_children(ntf, p, 2) | [
"def",
"process_notification",
"(",
"self",
",",
"ntf",
")",
":",
"p",
"=",
"\"/en:notification/\"",
"+",
"self",
".",
"qname",
"(",
"ntf",
")",
"tmpl",
"=",
"self",
".",
"xsl_template",
"(",
"p",
")",
"ct",
"=",
"self",
".",
"xsl_calltemplate",
"(",
"... | Process event notification `ntf`. | [
"Process",
"event",
"notification",
"ntf",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/jsonxsl.py#L137-L145 | train | 225,976 |
mbj4668/pyang | pyang/plugins/jsonxsl.py | JsonXslPlugin.process_children | def process_children(self, node, path, level, parent=None):
"""Process all children of `node`.
`path` is the Xpath of `node` which is used in the 'select'
attribute of XSLT templates.
"""
data_parent = parent if parent else node
chs = node.i_children
for ch in chs:
if ch.keyword in ["choice", "case"]:
self.process_children(ch, path, level, node)
continue
p = path + "/" + self.qname(ch)
tmpl = self.xsl_template(p)
ct = self.xsl_calltemplate(ch.keyword, tmpl)
self.xsl_withparam("level", "%d" % level, ct)
if (data_parent.i_module is None or
ch.i_module.i_modulename != data_parent.i_module.i_modulename):
self.xsl_withparam("nsid", ch.i_module.i_modulename + ":", ct)
if ch.keyword in ["leaf", "leaf-list"]:
self.type_param(ch, ct)
elif ch.keyword != "anyxml":
offset = 2 if ch.keyword == "list" else 1
self.process_children(ch, p, level + offset) | python | def process_children(self, node, path, level, parent=None):
"""Process all children of `node`.
`path` is the Xpath of `node` which is used in the 'select'
attribute of XSLT templates.
"""
data_parent = parent if parent else node
chs = node.i_children
for ch in chs:
if ch.keyword in ["choice", "case"]:
self.process_children(ch, path, level, node)
continue
p = path + "/" + self.qname(ch)
tmpl = self.xsl_template(p)
ct = self.xsl_calltemplate(ch.keyword, tmpl)
self.xsl_withparam("level", "%d" % level, ct)
if (data_parent.i_module is None or
ch.i_module.i_modulename != data_parent.i_module.i_modulename):
self.xsl_withparam("nsid", ch.i_module.i_modulename + ":", ct)
if ch.keyword in ["leaf", "leaf-list"]:
self.type_param(ch, ct)
elif ch.keyword != "anyxml":
offset = 2 if ch.keyword == "list" else 1
self.process_children(ch, p, level + offset) | [
"def",
"process_children",
"(",
"self",
",",
"node",
",",
"path",
",",
"level",
",",
"parent",
"=",
"None",
")",
":",
"data_parent",
"=",
"parent",
"if",
"parent",
"else",
"node",
"chs",
"=",
"node",
".",
"i_children",
"for",
"ch",
"in",
"chs",
":",
... | Process all children of `node`.
`path` is the Xpath of `node` which is used in the 'select'
attribute of XSLT templates. | [
"Process",
"all",
"children",
"of",
"node",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/jsonxsl.py#L147-L170 | train | 225,977 |
mbj4668/pyang | pyang/plugins/jsonxsl.py | JsonXslPlugin.type_param | def type_param(self, node, ct):
"""Resolve the type of a leaf or leaf-list node for JSON.
"""
types = self.get_types(node)
ftyp = types[0]
if len(types) == 1:
if ftyp in type_class:
jtyp = type_class[ftyp]
else:
jtyp = "other"
self.xsl_withparam("type", jtyp, ct)
elif ftyp in ["string", "enumeration", "bits", "binary",
"identityref", "instance-identifier"]:
self.xsl_withparam("type", "string", ct)
else:
opts = []
for t in types:
if t in union_class:
ut = union_class[t]
elif t in ["int64", "uint64"] or t.startswith("decimal@"):
ut = t
else:
ut = "other"
if ut not in opts:
opts.append(ut)
if ut == "other": break
if ut == "decimal" and "integer" not in opts:
opts.append("integer")
self.xsl_withparam("type", "union", ct)
self.xsl_withparam("options", ",".join(opts) + ",", ct) | python | def type_param(self, node, ct):
"""Resolve the type of a leaf or leaf-list node for JSON.
"""
types = self.get_types(node)
ftyp = types[0]
if len(types) == 1:
if ftyp in type_class:
jtyp = type_class[ftyp]
else:
jtyp = "other"
self.xsl_withparam("type", jtyp, ct)
elif ftyp in ["string", "enumeration", "bits", "binary",
"identityref", "instance-identifier"]:
self.xsl_withparam("type", "string", ct)
else:
opts = []
for t in types:
if t in union_class:
ut = union_class[t]
elif t in ["int64", "uint64"] or t.startswith("decimal@"):
ut = t
else:
ut = "other"
if ut not in opts:
opts.append(ut)
if ut == "other": break
if ut == "decimal" and "integer" not in opts:
opts.append("integer")
self.xsl_withparam("type", "union", ct)
self.xsl_withparam("options", ",".join(opts) + ",", ct) | [
"def",
"type_param",
"(",
"self",
",",
"node",
",",
"ct",
")",
":",
"types",
"=",
"self",
".",
"get_types",
"(",
"node",
")",
"ftyp",
"=",
"types",
"[",
"0",
"]",
"if",
"len",
"(",
"types",
")",
"==",
"1",
":",
"if",
"ftyp",
"in",
"type_class",
... | Resolve the type of a leaf or leaf-list node for JSON. | [
"Resolve",
"the",
"type",
"of",
"a",
"leaf",
"or",
"leaf",
"-",
"list",
"node",
"for",
"JSON",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/jsonxsl.py#L172-L201 | train | 225,978 |
mbj4668/pyang | pyang/plugins/jsonxsl.py | JsonXslPlugin.xsl_text | def xsl_text(self, text, parent):
"""Construct an XSLT 'text' element containing `text`.
`parent` is this element's parent.
"""
res = ET.SubElement(parent, "text")
res.text = text
return res | python | def xsl_text(self, text, parent):
"""Construct an XSLT 'text' element containing `text`.
`parent` is this element's parent.
"""
res = ET.SubElement(parent, "text")
res.text = text
return res | [
"def",
"xsl_text",
"(",
"self",
",",
"text",
",",
"parent",
")",
":",
"res",
"=",
"ET",
".",
"SubElement",
"(",
"parent",
",",
"\"text\"",
")",
"res",
".",
"text",
"=",
"text",
"return",
"res"
] | Construct an XSLT 'text' element containing `text`.
`parent` is this element's parent. | [
"Construct",
"an",
"XSLT",
"text",
"element",
"containing",
"text",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/jsonxsl.py#L233-L240 | train | 225,979 |
mbj4668/pyang | pyang/plugins/jsonxsl.py | JsonXslPlugin.xsl_withparam | def xsl_withparam(self, name, value, parent):
"""Construct an XSLT 'with-param' element.
`parent` is this element's parent.
`name` is the parameter name.
`value` is the parameter value.
"""
res = ET.SubElement(parent, "with-param", name=name)
res.text = value
return res | python | def xsl_withparam(self, name, value, parent):
"""Construct an XSLT 'with-param' element.
`parent` is this element's parent.
`name` is the parameter name.
`value` is the parameter value.
"""
res = ET.SubElement(parent, "with-param", name=name)
res.text = value
return res | [
"def",
"xsl_withparam",
"(",
"self",
",",
"name",
",",
"value",
",",
"parent",
")",
":",
"res",
"=",
"ET",
".",
"SubElement",
"(",
"parent",
",",
"\"with-param\"",
",",
"name",
"=",
"name",
")",
"res",
".",
"text",
"=",
"value",
"return",
"res"
] | Construct an XSLT 'with-param' element.
`parent` is this element's parent.
`name` is the parameter name.
`value` is the parameter value. | [
"Construct",
"an",
"XSLT",
"with",
"-",
"param",
"element",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/jsonxsl.py#L250-L259 | train | 225,980 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.element | def element(cls, name, parent=None, interleave=None, occur=0):
"""Create an element node."""
node = cls("element", parent, interleave=interleave)
node.attr["name"] = name
node.occur = occur
return node | python | def element(cls, name, parent=None, interleave=None, occur=0):
"""Create an element node."""
node = cls("element", parent, interleave=interleave)
node.attr["name"] = name
node.occur = occur
return node | [
"def",
"element",
"(",
"cls",
",",
"name",
",",
"parent",
"=",
"None",
",",
"interleave",
"=",
"None",
",",
"occur",
"=",
"0",
")",
":",
"node",
"=",
"cls",
"(",
"\"element\"",
",",
"parent",
",",
"interleave",
"=",
"interleave",
")",
"node",
".",
... | Create an element node. | [
"Create",
"an",
"element",
"node",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L63-L68 | train | 225,981 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.leaf_list | def leaf_list(cls, name, parent=None, interleave=None):
"""Create _list_ node for a leaf-list."""
node = cls("_list_", parent, interleave=interleave)
node.attr["name"] = name
node.keys = None
node.minEl = "0"
node.maxEl = None
node.occur = 3
return node | python | def leaf_list(cls, name, parent=None, interleave=None):
"""Create _list_ node for a leaf-list."""
node = cls("_list_", parent, interleave=interleave)
node.attr["name"] = name
node.keys = None
node.minEl = "0"
node.maxEl = None
node.occur = 3
return node | [
"def",
"leaf_list",
"(",
"cls",
",",
"name",
",",
"parent",
"=",
"None",
",",
"interleave",
"=",
"None",
")",
":",
"node",
"=",
"cls",
"(",
"\"_list_\"",
",",
"parent",
",",
"interleave",
"=",
"interleave",
")",
"node",
".",
"attr",
"[",
"\"name\"",
... | Create _list_ node for a leaf-list. | [
"Create",
"_list_",
"node",
"for",
"a",
"leaf",
"-",
"list",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L71-L79 | train | 225,982 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.list | def list(cls, name, parent=None, interleave=None):
"""Create _list_ node for a list."""
node = cls.leaf_list(name, parent, interleave=interleave)
node.keys = []
node.keymap = {}
return node | python | def list(cls, name, parent=None, interleave=None):
"""Create _list_ node for a list."""
node = cls.leaf_list(name, parent, interleave=interleave)
node.keys = []
node.keymap = {}
return node | [
"def",
"list",
"(",
"cls",
",",
"name",
",",
"parent",
"=",
"None",
",",
"interleave",
"=",
"None",
")",
":",
"node",
"=",
"cls",
".",
"leaf_list",
"(",
"name",
",",
"parent",
",",
"interleave",
"=",
"interleave",
")",
"node",
".",
"keys",
"=",
"["... | Create _list_ node for a list. | [
"Create",
"_list_",
"node",
"for",
"a",
"list",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L82-L87 | train | 225,983 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.choice | def choice(cls, parent=None, occur=0):
"""Create choice node."""
node = cls("choice", parent)
node.occur = occur
node.default_case = None
return node | python | def choice(cls, parent=None, occur=0):
"""Create choice node."""
node = cls("choice", parent)
node.occur = occur
node.default_case = None
return node | [
"def",
"choice",
"(",
"cls",
",",
"parent",
"=",
"None",
",",
"occur",
"=",
"0",
")",
":",
"node",
"=",
"cls",
"(",
"\"choice\"",
",",
"parent",
")",
"node",
".",
"occur",
"=",
"occur",
"node",
".",
"default_case",
"=",
"None",
"return",
"node"
] | Create choice node. | [
"Create",
"choice",
"node",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L90-L95 | train | 225,984 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.define | def define(cls, name, parent=None, interleave=False):
"""Create define node."""
node = cls("define", parent, interleave=interleave)
node.occur = 0
node.attr["name"] = name
return node | python | def define(cls, name, parent=None, interleave=False):
"""Create define node."""
node = cls("define", parent, interleave=interleave)
node.occur = 0
node.attr["name"] = name
return node | [
"def",
"define",
"(",
"cls",
",",
"name",
",",
"parent",
"=",
"None",
",",
"interleave",
"=",
"False",
")",
":",
"node",
"=",
"cls",
"(",
"\"define\"",
",",
"parent",
",",
"interleave",
"=",
"interleave",
")",
"node",
".",
"occur",
"=",
"0",
"node",
... | Create define node. | [
"Create",
"define",
"node",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L105-L110 | train | 225,985 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.adjust_interleave | def adjust_interleave(self, interleave):
"""Inherit interleave status from parent if undefined."""
if interleave == None and self.parent:
self.interleave = self.parent.interleave
else:
self.interleave = interleave | python | def adjust_interleave(self, interleave):
"""Inherit interleave status from parent if undefined."""
if interleave == None and self.parent:
self.interleave = self.parent.interleave
else:
self.interleave = interleave | [
"def",
"adjust_interleave",
"(",
"self",
",",
"interleave",
")",
":",
"if",
"interleave",
"==",
"None",
"and",
"self",
".",
"parent",
":",
"self",
".",
"interleave",
"=",
"self",
".",
"parent",
".",
"interleave",
"else",
":",
"self",
".",
"interleave",
"... | Inherit interleave status from parent if undefined. | [
"Inherit",
"interleave",
"status",
"from",
"parent",
"if",
"undefined",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L139-L144 | train | 225,986 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.subnode | def subnode(self, node):
"""Make `node` receiver's child."""
self.children.append(node)
node.parent = self
node.adjust_interleave(node.interleave) | python | def subnode(self, node):
"""Make `node` receiver's child."""
self.children.append(node)
node.parent = self
node.adjust_interleave(node.interleave) | [
"def",
"subnode",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"children",
".",
"append",
"(",
"node",
")",
"node",
".",
"parent",
"=",
"self",
"node",
".",
"adjust_interleave",
"(",
"node",
".",
"interleave",
")"
] | Make `node` receiver's child. | [
"Make",
"node",
"receiver",
"s",
"child",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L146-L150 | train | 225,987 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.annot | def annot(self, node):
"""Add `node` as an annotation of the receiver."""
self.annots.append(node)
node.parent = self | python | def annot(self, node):
"""Add `node` as an annotation of the receiver."""
self.annots.append(node)
node.parent = self | [
"def",
"annot",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"annots",
".",
"append",
"(",
"node",
")",
"node",
".",
"parent",
"=",
"self"
] | Add `node` as an annotation of the receiver. | [
"Add",
"node",
"as",
"an",
"annotation",
"of",
"the",
"receiver",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L152-L155 | train | 225,988 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.start_tag | def start_tag(self, alt=None, empty=False):
"""Return XML start tag for the receiver."""
if alt:
name = alt
else:
name = self.name
result = "<" + name
for it in self.attr:
result += ' %s="%s"' % (it, escape(self.attr[it], {'"':""", '%': "%%"}))
if empty:
return result + "/>%s"
else:
return result + ">" | python | def start_tag(self, alt=None, empty=False):
"""Return XML start tag for the receiver."""
if alt:
name = alt
else:
name = self.name
result = "<" + name
for it in self.attr:
result += ' %s="%s"' % (it, escape(self.attr[it], {'"':""", '%': "%%"}))
if empty:
return result + "/>%s"
else:
return result + ">" | [
"def",
"start_tag",
"(",
"self",
",",
"alt",
"=",
"None",
",",
"empty",
"=",
"False",
")",
":",
"if",
"alt",
":",
"name",
"=",
"alt",
"else",
":",
"name",
"=",
"self",
".",
"name",
"result",
"=",
"\"<\"",
"+",
"name",
"for",
"it",
"in",
"self",
... | Return XML start tag for the receiver. | [
"Return",
"XML",
"start",
"tag",
"for",
"the",
"receiver",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L162-L174 | train | 225,989 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.end_tag | def end_tag(self, alt=None):
"""Return XML end tag for the receiver."""
if alt:
name = alt
else:
name = self.name
return "</" + name + ">" | python | def end_tag(self, alt=None):
"""Return XML end tag for the receiver."""
if alt:
name = alt
else:
name = self.name
return "</" + name + ">" | [
"def",
"end_tag",
"(",
"self",
",",
"alt",
"=",
"None",
")",
":",
"if",
"alt",
":",
"name",
"=",
"alt",
"else",
":",
"name",
"=",
"self",
".",
"name",
"return",
"\"</\"",
"+",
"name",
"+",
"\">\""
] | Return XML end tag for the receiver. | [
"Return",
"XML",
"end",
"tag",
"for",
"the",
"receiver",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L176-L182 | train | 225,990 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode.serialize | def serialize(self, occur=None):
"""Return RELAX NG representation of the receiver and subtree.
"""
fmt = self.ser_format.get(self.name, SchemaNode._default_format)
return fmt(self, occur) % (escape(self.text) +
self.serialize_children()) | python | def serialize(self, occur=None):
"""Return RELAX NG representation of the receiver and subtree.
"""
fmt = self.ser_format.get(self.name, SchemaNode._default_format)
return fmt(self, occur) % (escape(self.text) +
self.serialize_children()) | [
"def",
"serialize",
"(",
"self",
",",
"occur",
"=",
"None",
")",
":",
"fmt",
"=",
"self",
".",
"ser_format",
".",
"get",
"(",
"self",
".",
"name",
",",
"SchemaNode",
".",
"_default_format",
")",
"return",
"fmt",
"(",
"self",
",",
"occur",
")",
"%",
... | Return RELAX NG representation of the receiver and subtree. | [
"Return",
"RELAX",
"NG",
"representation",
"of",
"the",
"receiver",
"and",
"subtree",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L184-L189 | train | 225,991 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode._default_format | def _default_format(self, occur):
"""Return the default serialization format."""
if self.text or self.children:
return self.start_tag() + "%s" + self.end_tag()
return self.start_tag(empty=True) | python | def _default_format(self, occur):
"""Return the default serialization format."""
if self.text or self.children:
return self.start_tag() + "%s" + self.end_tag()
return self.start_tag(empty=True) | [
"def",
"_default_format",
"(",
"self",
",",
"occur",
")",
":",
"if",
"self",
".",
"text",
"or",
"self",
".",
"children",
":",
"return",
"self",
".",
"start_tag",
"(",
")",
"+",
"\"%s\"",
"+",
"self",
".",
"end_tag",
"(",
")",
"return",
"self",
".",
... | Return the default serialization format. | [
"Return",
"the",
"default",
"serialization",
"format",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L191-L195 | train | 225,992 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode._define_format | def _define_format(self, occur):
"""Return the serialization format for a define node."""
if hasattr(self, "default"):
self.attr["nma:default"] = self.default
middle = self._chorder() if self.rng_children() else "<empty/>%s"
return (self.start_tag() + self.serialize_annots().replace("%", "%%")
+ middle + self.end_tag()) | python | def _define_format(self, occur):
"""Return the serialization format for a define node."""
if hasattr(self, "default"):
self.attr["nma:default"] = self.default
middle = self._chorder() if self.rng_children() else "<empty/>%s"
return (self.start_tag() + self.serialize_annots().replace("%", "%%")
+ middle + self.end_tag()) | [
"def",
"_define_format",
"(",
"self",
",",
"occur",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"default\"",
")",
":",
"self",
".",
"attr",
"[",
"\"nma:default\"",
"]",
"=",
"self",
".",
"default",
"middle",
"=",
"self",
".",
"_chorder",
"(",
")",
... | Return the serialization format for a define node. | [
"Return",
"the",
"serialization",
"format",
"for",
"a",
"define",
"node",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L201-L207 | train | 225,993 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode._element_format | def _element_format(self, occur):
"""Return the serialization format for an element node."""
if occur:
occ = occur
else:
occ = self.occur
if occ == 1:
if hasattr(self, "default"):
self.attr["nma:default"] = self.default
else:
self.attr["nma:implicit"] = "true"
middle = self._chorder() if self.rng_children() else "<empty/>%s"
fmt = (self.start_tag() + self.serialize_annots().replace("%", "%%") +
middle + self.end_tag())
if (occ == 2 or self.parent.name == "choice"
or self.parent.name == "case" and len(self.parent.children) == 1):
return fmt
else:
return "<optional>" + fmt + "</optional>" | python | def _element_format(self, occur):
"""Return the serialization format for an element node."""
if occur:
occ = occur
else:
occ = self.occur
if occ == 1:
if hasattr(self, "default"):
self.attr["nma:default"] = self.default
else:
self.attr["nma:implicit"] = "true"
middle = self._chorder() if self.rng_children() else "<empty/>%s"
fmt = (self.start_tag() + self.serialize_annots().replace("%", "%%") +
middle + self.end_tag())
if (occ == 2 or self.parent.name == "choice"
or self.parent.name == "case" and len(self.parent.children) == 1):
return fmt
else:
return "<optional>" + fmt + "</optional>" | [
"def",
"_element_format",
"(",
"self",
",",
"occur",
")",
":",
"if",
"occur",
":",
"occ",
"=",
"occur",
"else",
":",
"occ",
"=",
"self",
".",
"occur",
"if",
"occ",
"==",
"1",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"default\"",
")",
":",
"self",
... | Return the serialization format for an element node. | [
"Return",
"the",
"serialization",
"format",
"for",
"an",
"element",
"node",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L209-L227 | train | 225,994 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode._list_format | def _list_format(self, occur):
"""Return the serialization format for a _list_ node."""
if self.keys:
self.attr["nma:key"] = " ".join(self.keys)
keys = ''.join([self.keymap[k].serialize(occur=2)
for k in self.keys])
else:
keys = ""
if self.maxEl:
self.attr["nma:max-elements"] = self.maxEl
if int(self.minEl) == 0:
ord_ = "zeroOrMore"
else:
ord_ = "oneOrMore"
if int(self.minEl) > 1:
self.attr["nma:min-elements"] = self.minEl
middle = self._chorder() if self.rng_children() else "<empty/>%s"
return ("<" + ord_ + ">" + self.start_tag("element") +
(self.serialize_annots() + keys).replace("%", "%%") +
middle + self.end_tag("element") + "</" + ord_ + ">") | python | def _list_format(self, occur):
"""Return the serialization format for a _list_ node."""
if self.keys:
self.attr["nma:key"] = " ".join(self.keys)
keys = ''.join([self.keymap[k].serialize(occur=2)
for k in self.keys])
else:
keys = ""
if self.maxEl:
self.attr["nma:max-elements"] = self.maxEl
if int(self.minEl) == 0:
ord_ = "zeroOrMore"
else:
ord_ = "oneOrMore"
if int(self.minEl) > 1:
self.attr["nma:min-elements"] = self.minEl
middle = self._chorder() if self.rng_children() else "<empty/>%s"
return ("<" + ord_ + ">" + self.start_tag("element") +
(self.serialize_annots() + keys).replace("%", "%%") +
middle + self.end_tag("element") + "</" + ord_ + ">") | [
"def",
"_list_format",
"(",
"self",
",",
"occur",
")",
":",
"if",
"self",
".",
"keys",
":",
"self",
".",
"attr",
"[",
"\"nma:key\"",
"]",
"=",
"\" \"",
".",
"join",
"(",
"self",
".",
"keys",
")",
"keys",
"=",
"''",
".",
"join",
"(",
"[",
"self",
... | Return the serialization format for a _list_ node. | [
"Return",
"the",
"serialization",
"format",
"for",
"a",
"_list_",
"node",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L236-L255 | train | 225,995 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode._choice_format | def _choice_format(self, occur):
"""Return the serialization format for a choice node."""
middle = "%s" if self.rng_children() else "<empty/>%s"
fmt = self.start_tag() + middle + self.end_tag()
if self.occur != 2:
return "<optional>" + fmt + "</optional>"
else:
return fmt | python | def _choice_format(self, occur):
"""Return the serialization format for a choice node."""
middle = "%s" if self.rng_children() else "<empty/>%s"
fmt = self.start_tag() + middle + self.end_tag()
if self.occur != 2:
return "<optional>" + fmt + "</optional>"
else:
return fmt | [
"def",
"_choice_format",
"(",
"self",
",",
"occur",
")",
":",
"middle",
"=",
"\"%s\"",
"if",
"self",
".",
"rng_children",
"(",
")",
"else",
"\"<empty/>%s\"",
"fmt",
"=",
"self",
".",
"start_tag",
"(",
")",
"+",
"middle",
"+",
"self",
".",
"end_tag",
"(... | Return the serialization format for a choice node. | [
"Return",
"the",
"serialization",
"format",
"for",
"a",
"choice",
"node",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L257-L264 | train | 225,996 |
mbj4668/pyang | pyang/translators/schemanode.py | SchemaNode._case_format | def _case_format(self, occur):
"""Return the serialization format for a case node."""
if self.occur == 1:
self.attr["nma:implicit"] = "true"
ccnt = len(self.rng_children())
if ccnt == 0: return "<empty/>%s"
if ccnt == 1 or not self.interleave:
return self.start_tag("group") + "%s" + self.end_tag("group")
return (self.start_tag("interleave") + "%s" +
self.end_tag("interleave")) | python | def _case_format(self, occur):
"""Return the serialization format for a case node."""
if self.occur == 1:
self.attr["nma:implicit"] = "true"
ccnt = len(self.rng_children())
if ccnt == 0: return "<empty/>%s"
if ccnt == 1 or not self.interleave:
return self.start_tag("group") + "%s" + self.end_tag("group")
return (self.start_tag("interleave") + "%s" +
self.end_tag("interleave")) | [
"def",
"_case_format",
"(",
"self",
",",
"occur",
")",
":",
"if",
"self",
".",
"occur",
"==",
"1",
":",
"self",
".",
"attr",
"[",
"\"nma:implicit\"",
"]",
"=",
"\"true\"",
"ccnt",
"=",
"len",
"(",
"self",
".",
"rng_children",
"(",
")",
")",
"if",
"... | Return the serialization format for a case node. | [
"Return",
"the",
"serialization",
"format",
"for",
"a",
"case",
"node",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L266-L275 | train | 225,997 |
mbj4668/pyang | pyang/plugins/jtox.py | JtoXPlugin.process_children | def process_children(self, node, parent, pmod):
"""Process all children of `node`, except "rpc" and "notification".
"""
for ch in node.i_children:
if ch.keyword in ["rpc", "notification"]: continue
if ch.keyword in ["choice", "case"]:
self.process_children(ch, parent, pmod)
continue
if ch.i_module.i_modulename == pmod:
nmod = pmod
nodename = ch.arg
else:
nmod = ch.i_module.i_modulename
nodename = "%s:%s" % (nmod, ch.arg)
ndata = [ch.keyword]
if ch.keyword == "container":
ndata.append({})
self.process_children(ch, ndata[1], nmod)
elif ch.keyword == "list":
ndata.append({})
self.process_children(ch, ndata[1], nmod)
ndata.append([(k.i_module.i_modulename, k.arg)
for k in ch.i_key])
elif ch.keyword in ["leaf", "leaf-list"]:
ndata.append(self.base_type(ch.search_one("type")))
modname = ch.i_module.i_modulename
parent[nodename] = ndata | python | def process_children(self, node, parent, pmod):
"""Process all children of `node`, except "rpc" and "notification".
"""
for ch in node.i_children:
if ch.keyword in ["rpc", "notification"]: continue
if ch.keyword in ["choice", "case"]:
self.process_children(ch, parent, pmod)
continue
if ch.i_module.i_modulename == pmod:
nmod = pmod
nodename = ch.arg
else:
nmod = ch.i_module.i_modulename
nodename = "%s:%s" % (nmod, ch.arg)
ndata = [ch.keyword]
if ch.keyword == "container":
ndata.append({})
self.process_children(ch, ndata[1], nmod)
elif ch.keyword == "list":
ndata.append({})
self.process_children(ch, ndata[1], nmod)
ndata.append([(k.i_module.i_modulename, k.arg)
for k in ch.i_key])
elif ch.keyword in ["leaf", "leaf-list"]:
ndata.append(self.base_type(ch.search_one("type")))
modname = ch.i_module.i_modulename
parent[nodename] = ndata | [
"def",
"process_children",
"(",
"self",
",",
"node",
",",
"parent",
",",
"pmod",
")",
":",
"for",
"ch",
"in",
"node",
".",
"i_children",
":",
"if",
"ch",
".",
"keyword",
"in",
"[",
"\"rpc\"",
",",
"\"notification\"",
"]",
":",
"continue",
"if",
"ch",
... | Process all children of `node`, except "rpc" and "notification". | [
"Process",
"all",
"children",
"of",
"node",
"except",
"rpc",
"and",
"notification",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/jtox.py#L61-L87 | train | 225,998 |
mbj4668/pyang | pyang/plugins/jtox.py | JtoXPlugin.base_type | def base_type(self, type):
"""Return the base type of `type`."""
while 1:
if type.arg == "leafref":
node = type.i_type_spec.i_target_node
elif type.i_typedef is None:
break
else:
node = type.i_typedef
type = node.search_one("type")
if type.arg == "decimal64":
return [type.arg, int(type.search_one("fraction-digits").arg)]
elif type.arg == "union":
return [type.arg, [self.base_type(x) for x in type.i_type_spec.types]]
else:
return type.arg | python | def base_type(self, type):
"""Return the base type of `type`."""
while 1:
if type.arg == "leafref":
node = type.i_type_spec.i_target_node
elif type.i_typedef is None:
break
else:
node = type.i_typedef
type = node.search_one("type")
if type.arg == "decimal64":
return [type.arg, int(type.search_one("fraction-digits").arg)]
elif type.arg == "union":
return [type.arg, [self.base_type(x) for x in type.i_type_spec.types]]
else:
return type.arg | [
"def",
"base_type",
"(",
"self",
",",
"type",
")",
":",
"while",
"1",
":",
"if",
"type",
".",
"arg",
"==",
"\"leafref\"",
":",
"node",
"=",
"type",
".",
"i_type_spec",
".",
"i_target_node",
"elif",
"type",
".",
"i_typedef",
"is",
"None",
":",
"break",
... | Return the base type of `type`. | [
"Return",
"the",
"base",
"type",
"of",
"type",
"."
] | f2a5cc3142162e5b9ee4e18d154568d939ff63dd | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/jtox.py#L89-L104 | train | 225,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.