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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
adewes/blitzdb | blitzdb/backends/file/index.py | Index.get_all_keys | def get_all_keys(self):
"""Get all keys indexed.
:return: All keys
:rtype: list(str)
"""
all_keys = []
for keys in self._index.values():
all_keys.extend(keys)
return all_keys | python | def get_all_keys(self):
"""Get all keys indexed.
:return: All keys
:rtype: list(str)
"""
all_keys = []
for keys in self._index.values():
all_keys.extend(keys)
return all_keys | [
"def",
"get_all_keys",
"(",
"self",
")",
":",
"all_keys",
"=",
"[",
"]",
"for",
"keys",
"in",
"self",
".",
"_index",
".",
"values",
"(",
")",
":",
"all_keys",
".",
"extend",
"(",
"keys",
")",
"return",
"all_keys"
] | Get all keys indexed.
:return: All keys
:rtype: list(str) | [
"Get",
"all",
"keys",
"indexed",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L111-L121 | train | 52,800 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.load_from_store | def load_from_store(self):
"""Load index from store.
:return: Whether index was correctly loaded or not
:rtype: bool
:raise AttributeError: If no datastore is defined
"""
if not self._store:
raise AttributeError('No datastore defined!')
if self._store.has_blob('all_keys'):
data = Serializer.deserialize(self._store.get_blob('all_keys'))
self.load_from_data(data)
return True
elif self._store.has_blob('all_keys_with_undefined'):
blob = self._store.get_blob('all_keys_with_undefined')
data = Serializer.deserialize(blob)
self.load_from_data(data, with_undefined=True)
return True
else:
return False | python | def load_from_store(self):
"""Load index from store.
:return: Whether index was correctly loaded or not
:rtype: bool
:raise AttributeError: If no datastore is defined
"""
if not self._store:
raise AttributeError('No datastore defined!')
if self._store.has_blob('all_keys'):
data = Serializer.deserialize(self._store.get_blob('all_keys'))
self.load_from_data(data)
return True
elif self._store.has_blob('all_keys_with_undefined'):
blob = self._store.get_blob('all_keys_with_undefined')
data = Serializer.deserialize(blob)
self.load_from_data(data, with_undefined=True)
return True
else:
return False | [
"def",
"load_from_store",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_store",
":",
"raise",
"AttributeError",
"(",
"'No datastore defined!'",
")",
"if",
"self",
".",
"_store",
".",
"has_blob",
"(",
"'all_keys'",
")",
":",
"data",
"=",
"Serializer",
... | Load index from store.
:return: Whether index was correctly loaded or not
:rtype: bool
:raise AttributeError: If no datastore is defined | [
"Load",
"index",
"from",
"store",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L132-L152 | train | 52,801 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.sort_keys | def sort_keys(self, keys, order=QuerySet.ASCENDING):
"""Sort keys.
Keys are sorted based on the value they are indexing.
:param keys: Keys to be sorted
:type keys: list(str)
:param order: Order criteri (asending or descending)
:type order: int
:return: Sorted keys
:rtype: list(str)
:raise ValueError: If invalid order value is passed
"""
# to do: check that all reverse index values are unambiguous
missing_keys = [
key
for key in keys
if not len(self._reverse_index[key])
]
keys_and_values = [
(key, self._reverse_index[key][0])
for key in keys
if key not in missing_keys
]
sorted_keys = [
kv[0]
for kv in sorted(
keys_and_values,
key=lambda x: x[1],
reverse=True if order == QuerySet.DESCENDING else False)
]
if order == QuerySet.ASCENDING:
return missing_keys + sorted_keys
elif order == QuerySet.DESCENDING:
return sorted_keys + missing_keys
else:
raise ValueError('Unexpected order value: {:d}'.format(order)) | python | def sort_keys(self, keys, order=QuerySet.ASCENDING):
"""Sort keys.
Keys are sorted based on the value they are indexing.
:param keys: Keys to be sorted
:type keys: list(str)
:param order: Order criteri (asending or descending)
:type order: int
:return: Sorted keys
:rtype: list(str)
:raise ValueError: If invalid order value is passed
"""
# to do: check that all reverse index values are unambiguous
missing_keys = [
key
for key in keys
if not len(self._reverse_index[key])
]
keys_and_values = [
(key, self._reverse_index[key][0])
for key in keys
if key not in missing_keys
]
sorted_keys = [
kv[0]
for kv in sorted(
keys_and_values,
key=lambda x: x[1],
reverse=True if order == QuerySet.DESCENDING else False)
]
if order == QuerySet.ASCENDING:
return missing_keys + sorted_keys
elif order == QuerySet.DESCENDING:
return sorted_keys + missing_keys
else:
raise ValueError('Unexpected order value: {:d}'.format(order)) | [
"def",
"sort_keys",
"(",
"self",
",",
"keys",
",",
"order",
"=",
"QuerySet",
".",
"ASCENDING",
")",
":",
"# to do: check that all reverse index values are unambiguous",
"missing_keys",
"=",
"[",
"key",
"for",
"key",
"in",
"keys",
"if",
"not",
"len",
"(",
"self",... | Sort keys.
Keys are sorted based on the value they are indexing.
:param keys: Keys to be sorted
:type keys: list(str)
:param order: Order criteri (asending or descending)
:type order: int
:return: Sorted keys
:rtype: list(str)
:raise ValueError: If invalid order value is passed | [
"Sort",
"keys",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L154-L191 | train | 52,802 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.save_to_data | def save_to_data(self, in_place=False):
"""Save index to data structure.
:param in_place: Do not copy index value to a new list object
:type in_place: bool
:return: Index data structure
:rtype: list
"""
if in_place:
return [
list(self._index.items()),
list(self._undefined_keys.keys())
]
return (
[(key, values[:]) for key, values in self._index.items()],
list(self._undefined_keys.keys()),
) | python | def save_to_data(self, in_place=False):
"""Save index to data structure.
:param in_place: Do not copy index value to a new list object
:type in_place: bool
:return: Index data structure
:rtype: list
"""
if in_place:
return [
list(self._index.items()),
list(self._undefined_keys.keys())
]
return (
[(key, values[:]) for key, values in self._index.items()],
list(self._undefined_keys.keys()),
) | [
"def",
"save_to_data",
"(",
"self",
",",
"in_place",
"=",
"False",
")",
":",
"if",
"in_place",
":",
"return",
"[",
"list",
"(",
"self",
".",
"_index",
".",
"items",
"(",
")",
")",
",",
"list",
"(",
"self",
".",
"_undefined_keys",
".",
"keys",
"(",
... | Save index to data structure.
:param in_place: Do not copy index value to a new list object
:type in_place: bool
:return: Index data structure
:rtype: list | [
"Save",
"index",
"to",
"data",
"structure",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L193-L210 | train | 52,803 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.load_from_data | def load_from_data(self, data, with_undefined=False):
"""Load index structure.
:param with_undefined: Load undefined keys as well
:type with_undefined: bool
"""
if with_undefined:
defined_values, undefined_values = data
else:
defined_values = data
undefined_values = None
self._index = defaultdict(list, defined_values)
self._reverse_index = defaultdict(list)
for key, values in self._index.items():
for value in values:
self._reverse_index[value].append(key)
if undefined_values:
self._undefined_keys = {key: True for key in undefined_values}
else:
self._undefined_keys = {} | python | def load_from_data(self, data, with_undefined=False):
"""Load index structure.
:param with_undefined: Load undefined keys as well
:type with_undefined: bool
"""
if with_undefined:
defined_values, undefined_values = data
else:
defined_values = data
undefined_values = None
self._index = defaultdict(list, defined_values)
self._reverse_index = defaultdict(list)
for key, values in self._index.items():
for value in values:
self._reverse_index[value].append(key)
if undefined_values:
self._undefined_keys = {key: True for key in undefined_values}
else:
self._undefined_keys = {} | [
"def",
"load_from_data",
"(",
"self",
",",
"data",
",",
"with_undefined",
"=",
"False",
")",
":",
"if",
"with_undefined",
":",
"defined_values",
",",
"undefined_values",
"=",
"data",
"else",
":",
"defined_values",
"=",
"data",
"undefined_values",
"=",
"None",
... | Load index structure.
:param with_undefined: Load undefined keys as well
:type with_undefined: bool | [
"Load",
"index",
"structure",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L212-L232 | train | 52,804 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.get_hash_for | def get_hash_for(self, value):
"""Get hash for a given value.
:param value: The value to be indexed
:type value: object
:return: Hashed value
:rtype: str
"""
if isinstance(value,dict) and '__ref__' in value:
return self.get_hash_for(value['__ref__'])
serialized_value = self._serializer(value)
if isinstance(serialized_value, dict):
# Hash each item and return the hash of all the hashes
return hash(frozenset([
self.get_hash_for(x)
for x in serialized_value.items()
]))
elif isinstance(serialized_value, (list,tuple)):
# Hash each element and return the hash of all the hashes
return hash(tuple([
self.get_hash_for(x) for x in serialized_value
]))
return value | python | def get_hash_for(self, value):
"""Get hash for a given value.
:param value: The value to be indexed
:type value: object
:return: Hashed value
:rtype: str
"""
if isinstance(value,dict) and '__ref__' in value:
return self.get_hash_for(value['__ref__'])
serialized_value = self._serializer(value)
if isinstance(serialized_value, dict):
# Hash each item and return the hash of all the hashes
return hash(frozenset([
self.get_hash_for(x)
for x in serialized_value.items()
]))
elif isinstance(serialized_value, (list,tuple)):
# Hash each element and return the hash of all the hashes
return hash(tuple([
self.get_hash_for(x) for x in serialized_value
]))
return value | [
"def",
"get_hash_for",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"'__ref__'",
"in",
"value",
":",
"return",
"self",
".",
"get_hash_for",
"(",
"value",
"[",
"'__ref__'",
"]",
")",
"serialized_value",
"... | Get hash for a given value.
:param value: The value to be indexed
:type value: object
:return: Hashed value
:rtype: str | [
"Get",
"hash",
"for",
"a",
"given",
"value",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L234-L257 | train | 52,805 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.add_hashed_value | def add_hashed_value(self, hash_value, store_key):
"""Add hashed value to the index.
:param hash_value: The hashed value to be added to the index
:type hash_value: str
:param store_key: The key for the document in the store
:type store_key: object
"""
if self._unique and hash_value in self._index:
raise NonUnique('Hash value {} already in index'.format(hash_value))
if store_key not in self._index[hash_value]:
self._index[hash_value].append(store_key)
if hash_value not in self._reverse_index[store_key]:
self._reverse_index[store_key].append(hash_value) | python | def add_hashed_value(self, hash_value, store_key):
"""Add hashed value to the index.
:param hash_value: The hashed value to be added to the index
:type hash_value: str
:param store_key: The key for the document in the store
:type store_key: object
"""
if self._unique and hash_value in self._index:
raise NonUnique('Hash value {} already in index'.format(hash_value))
if store_key not in self._index[hash_value]:
self._index[hash_value].append(store_key)
if hash_value not in self._reverse_index[store_key]:
self._reverse_index[store_key].append(hash_value) | [
"def",
"add_hashed_value",
"(",
"self",
",",
"hash_value",
",",
"store_key",
")",
":",
"if",
"self",
".",
"_unique",
"and",
"hash_value",
"in",
"self",
".",
"_index",
":",
"raise",
"NonUnique",
"(",
"'Hash value {} already in index'",
".",
"format",
"(",
"hash... | Add hashed value to the index.
:param hash_value: The hashed value to be added to the index
:type hash_value: str
:param store_key: The key for the document in the store
:type store_key: object | [
"Add",
"hashed",
"value",
"to",
"the",
"index",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L284-L298 | train | 52,806 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.add_key | def add_key(self, attributes, store_key):
"""Add key to the index.
:param attributes: Attributes to be added to the index
:type attributes: dict(str)
:param store_key: The key for the document in the store
:type store_key: str
"""
undefined = False
try:
value = self.get_value(attributes)
except (KeyError, IndexError):
undefined = True
# We remove old values in _reverse_index
self.remove_key(store_key)
if not undefined:
if isinstance(value, (list,tuple)):
# We add an extra hash value for the list itself
# (this allows for querying the whole list)
values = value
hash_value = self.get_hash_for(value)
self.add_hashed_value(hash_value, store_key)
else:
values = [value]
for value in values:
hash_value = self.get_hash_for(value)
self.add_hashed_value(hash_value, store_key)
else:
self.add_undefined(store_key) | python | def add_key(self, attributes, store_key):
"""Add key to the index.
:param attributes: Attributes to be added to the index
:type attributes: dict(str)
:param store_key: The key for the document in the store
:type store_key: str
"""
undefined = False
try:
value = self.get_value(attributes)
except (KeyError, IndexError):
undefined = True
# We remove old values in _reverse_index
self.remove_key(store_key)
if not undefined:
if isinstance(value, (list,tuple)):
# We add an extra hash value for the list itself
# (this allows for querying the whole list)
values = value
hash_value = self.get_hash_for(value)
self.add_hashed_value(hash_value, store_key)
else:
values = [value]
for value in values:
hash_value = self.get_hash_for(value)
self.add_hashed_value(hash_value, store_key)
else:
self.add_undefined(store_key) | [
"def",
"add_key",
"(",
"self",
",",
"attributes",
",",
"store_key",
")",
":",
"undefined",
"=",
"False",
"try",
":",
"value",
"=",
"self",
".",
"get_value",
"(",
"attributes",
")",
"except",
"(",
"KeyError",
",",
"IndexError",
")",
":",
"undefined",
"=",... | Add key to the index.
:param attributes: Attributes to be added to the index
:type attributes: dict(str)
:param store_key: The key for the document in the store
:type store_key: str | [
"Add",
"key",
"to",
"the",
"index",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L300-L331 | train | 52,807 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.remove_key | def remove_key(self, store_key):
"""Remove key from the index.
:param store_key: The key for the document in the store
:type store_key: str
"""
if store_key in self._undefined_keys:
del self._undefined_keys[store_key]
if store_key in self._reverse_index:
for value in self._reverse_index[store_key]:
self._index[value].remove(store_key)
del self._reverse_index[store_key] | python | def remove_key(self, store_key):
"""Remove key from the index.
:param store_key: The key for the document in the store
:type store_key: str
"""
if store_key in self._undefined_keys:
del self._undefined_keys[store_key]
if store_key in self._reverse_index:
for value in self._reverse_index[store_key]:
self._index[value].remove(store_key)
del self._reverse_index[store_key] | [
"def",
"remove_key",
"(",
"self",
",",
"store_key",
")",
":",
"if",
"store_key",
"in",
"self",
".",
"_undefined_keys",
":",
"del",
"self",
".",
"_undefined_keys",
"[",
"store_key",
"]",
"if",
"store_key",
"in",
"self",
".",
"_reverse_index",
":",
"for",
"v... | Remove key from the index.
:param store_key: The key for the document in the store
:type store_key: str | [
"Remove",
"key",
"from",
"the",
"index",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L342-L354 | train | 52,808 |
adewes/blitzdb | blitzdb/backends/file/index.py | TransactionalIndex._init_cache | def _init_cache(self):
"""Initialize cache."""
self._add_cache = defaultdict(list)
self._reverse_add_cache = defaultdict(list)
self._undefined_cache = {}
self._remove_cache = {} | python | def _init_cache(self):
"""Initialize cache."""
self._add_cache = defaultdict(list)
self._reverse_add_cache = defaultdict(list)
self._undefined_cache = {}
self._remove_cache = {} | [
"def",
"_init_cache",
"(",
"self",
")",
":",
"self",
".",
"_add_cache",
"=",
"defaultdict",
"(",
"list",
")",
"self",
".",
"_reverse_add_cache",
"=",
"defaultdict",
"(",
"list",
")",
"self",
".",
"_undefined_cache",
"=",
"{",
"}",
"self",
".",
"_remove_cac... | Initialize cache. | [
"Initialize",
"cache",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L371-L376 | train | 52,809 |
adewes/blitzdb | blitzdb/backends/file/index.py | TransactionalIndex.commit | def commit(self):
"""Commit current transaction."""
if (not self._add_cache and
not self._remove_cache and
not self._undefined_cache):
return
for store_key, hash_values in self._add_cache.items():
for hash_value in hash_values:
super(TransactionalIndex, self).add_hashed_value(
hash_value, store_key)
for store_key in self._remove_cache:
super(TransactionalIndex, self).remove_key(store_key)
for store_key in self._undefined_cache:
super(TransactionalIndex, self).add_undefined(store_key)
if not self.ephemeral:
self.save_to_store()
self._init_cache()
self._in_transaction = True | python | def commit(self):
"""Commit current transaction."""
if (not self._add_cache and
not self._remove_cache and
not self._undefined_cache):
return
for store_key, hash_values in self._add_cache.items():
for hash_value in hash_values:
super(TransactionalIndex, self).add_hashed_value(
hash_value, store_key)
for store_key in self._remove_cache:
super(TransactionalIndex, self).remove_key(store_key)
for store_key in self._undefined_cache:
super(TransactionalIndex, self).add_undefined(store_key)
if not self.ephemeral:
self.save_to_store()
self._init_cache()
self._in_transaction = True | [
"def",
"commit",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"_add_cache",
"and",
"not",
"self",
".",
"_remove_cache",
"and",
"not",
"self",
".",
"_undefined_cache",
")",
":",
"return",
"for",
"store_key",
",",
"hash_values",
"in",
"self",
".",... | Commit current transaction. | [
"Commit",
"current",
"transaction",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L386-L405 | train | 52,810 |
adewes/blitzdb | blitzdb/backends/file/index.py | TransactionalIndex.rollback | def rollback(self):
"""Drop changes from current transaction."""
if not self._in_transaction:
raise NotInTransaction
self._init_cache()
self._in_transaction = False | python | def rollback(self):
"""Drop changes from current transaction."""
if not self._in_transaction:
raise NotInTransaction
self._init_cache()
self._in_transaction = False | [
"def",
"rollback",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_in_transaction",
":",
"raise",
"NotInTransaction",
"self",
".",
"_init_cache",
"(",
")",
"self",
".",
"_in_transaction",
"=",
"False"
] | Drop changes from current transaction. | [
"Drop",
"changes",
"from",
"current",
"transaction",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L407-L412 | train | 52,811 |
adewes/blitzdb | blitzdb/backends/file/index.py | TransactionalIndex.add_hashed_value | def add_hashed_value(self, hash_value, store_key):
"""Add hashed value in the context of the current transaction.
:param hash_value: The hashed value to be added to the index
:type hash_value: str
:param store_key: The key for the document in the store
:type store_key: object
"""
if hash_value not in self._add_cache[store_key]:
self._add_cache[store_key].append(hash_value)
if store_key not in self._reverse_add_cache[hash_value]:
self._reverse_add_cache[hash_value].append(store_key)
if store_key in self._remove_cache:
del self._remove_cache[store_key]
if store_key in self._undefined_cache:
del self._undefined_cache[store_key] | python | def add_hashed_value(self, hash_value, store_key):
"""Add hashed value in the context of the current transaction.
:param hash_value: The hashed value to be added to the index
:type hash_value: str
:param store_key: The key for the document in the store
:type store_key: object
"""
if hash_value not in self._add_cache[store_key]:
self._add_cache[store_key].append(hash_value)
if store_key not in self._reverse_add_cache[hash_value]:
self._reverse_add_cache[hash_value].append(store_key)
if store_key in self._remove_cache:
del self._remove_cache[store_key]
if store_key in self._undefined_cache:
del self._undefined_cache[store_key] | [
"def",
"add_hashed_value",
"(",
"self",
",",
"hash_value",
",",
"store_key",
")",
":",
"if",
"hash_value",
"not",
"in",
"self",
".",
"_add_cache",
"[",
"store_key",
"]",
":",
"self",
".",
"_add_cache",
"[",
"store_key",
"]",
".",
"append",
"(",
"hash_value... | Add hashed value in the context of the current transaction.
:param hash_value: The hashed value to be added to the index
:type hash_value: str
:param store_key: The key for the document in the store
:type store_key: object | [
"Add",
"hashed",
"value",
"in",
"the",
"context",
"of",
"the",
"current",
"transaction",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L424-L440 | train | 52,812 |
adewes/blitzdb | blitzdb/backends/file/index.py | TransactionalIndex.remove_key | def remove_key(self, store_key):
"""Remove key in the context of the current transaction.
:param store_key: The key for the document in the store
:type store_key: str
"""
self._remove_cache[store_key] = True
if store_key in self._add_cache:
for hash_value in self._add_cache[store_key]:
self._reverse_add_cache[hash_value].remove(store_key)
del self._add_cache[store_key]
if store_key in self._undefined_cache:
del self._undefined_cache[store_key] | python | def remove_key(self, store_key):
"""Remove key in the context of the current transaction.
:param store_key: The key for the document in the store
:type store_key: str
"""
self._remove_cache[store_key] = True
if store_key in self._add_cache:
for hash_value in self._add_cache[store_key]:
self._reverse_add_cache[hash_value].remove(store_key)
del self._add_cache[store_key]
if store_key in self._undefined_cache:
del self._undefined_cache[store_key] | [
"def",
"remove_key",
"(",
"self",
",",
"store_key",
")",
":",
"self",
".",
"_remove_cache",
"[",
"store_key",
"]",
"=",
"True",
"if",
"store_key",
"in",
"self",
".",
"_add_cache",
":",
"for",
"hash_value",
"in",
"self",
".",
"_add_cache",
"[",
"store_key",... | Remove key in the context of the current transaction.
:param store_key: The key for the document in the store
:type store_key: str | [
"Remove",
"key",
"in",
"the",
"context",
"of",
"the",
"current",
"transaction",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L442-L455 | train | 52,813 |
adewes/blitzdb | blitzdb/backends/file/queries.py | boolean_operator_query | def boolean_operator_query(boolean_operator):
"""Generate boolean operator checking function."""
def _boolean_operator_query(expressions):
"""Apply boolean operator to expressions."""
def _apply_boolean_operator(query_function, expressions=expressions):
"""Return if expressions with boolean operator are satisfied."""
compiled_expressions = [compile_query(e) for e in expressions]
return reduce(
boolean_operator,
[e(query_function) for e in compiled_expressions]
)
return _apply_boolean_operator
return _boolean_operator_query | python | def boolean_operator_query(boolean_operator):
"""Generate boolean operator checking function."""
def _boolean_operator_query(expressions):
"""Apply boolean operator to expressions."""
def _apply_boolean_operator(query_function, expressions=expressions):
"""Return if expressions with boolean operator are satisfied."""
compiled_expressions = [compile_query(e) for e in expressions]
return reduce(
boolean_operator,
[e(query_function) for e in compiled_expressions]
)
return _apply_boolean_operator
return _boolean_operator_query | [
"def",
"boolean_operator_query",
"(",
"boolean_operator",
")",
":",
"def",
"_boolean_operator_query",
"(",
"expressions",
")",
":",
"\"\"\"Apply boolean operator to expressions.\"\"\"",
"def",
"_apply_boolean_operator",
"(",
"query_function",
",",
"expressions",
"=",
"express... | Generate boolean operator checking function. | [
"Generate",
"boolean",
"operator",
"checking",
"function",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L11-L24 | train | 52,814 |
adewes/blitzdb | blitzdb/backends/file/queries.py | filter_query | def filter_query(key, expression):
"""Filter documents with a key that satisfies an expression."""
if (isinstance(expression, dict)
and len(expression) == 1
and list(expression.keys())[0].startswith('$')):
compiled_expression = compile_query(expression)
elif callable(expression):
def _filter(index, expression=expression):
result = [store_key
for value, store_keys in index.get_index().items()
if expression(value)
for store_key in store_keys]
return result
compiled_expression = _filter
else:
compiled_expression = expression
def _get(query_function, key=key, expression=compiled_expression):
"""Get document key and check against expression."""
return query_function(key, expression)
return _get | python | def filter_query(key, expression):
"""Filter documents with a key that satisfies an expression."""
if (isinstance(expression, dict)
and len(expression) == 1
and list(expression.keys())[0].startswith('$')):
compiled_expression = compile_query(expression)
elif callable(expression):
def _filter(index, expression=expression):
result = [store_key
for value, store_keys in index.get_index().items()
if expression(value)
for store_key in store_keys]
return result
compiled_expression = _filter
else:
compiled_expression = expression
def _get(query_function, key=key, expression=compiled_expression):
"""Get document key and check against expression."""
return query_function(key, expression)
return _get | [
"def",
"filter_query",
"(",
"key",
",",
"expression",
")",
":",
"if",
"(",
"isinstance",
"(",
"expression",
",",
"dict",
")",
"and",
"len",
"(",
"expression",
")",
"==",
"1",
"and",
"list",
"(",
"expression",
".",
"keys",
"(",
")",
")",
"[",
"0",
"... | Filter documents with a key that satisfies an expression. | [
"Filter",
"documents",
"with",
"a",
"key",
"that",
"satisfies",
"an",
"expression",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L27-L48 | train | 52,815 |
adewes/blitzdb | blitzdb/backends/file/queries.py | not_query | def not_query(expression):
"""Apply logical not operator to expression."""
compiled_expression = compile_query(expression)
def _not(index, expression=compiled_expression):
"""Return store key for documents that satisfy expression."""
all_keys = index.get_all_keys()
returned_keys = expression(index)
return [key for key in all_keys if key not in returned_keys]
return _not | python | def not_query(expression):
"""Apply logical not operator to expression."""
compiled_expression = compile_query(expression)
def _not(index, expression=compiled_expression):
"""Return store key for documents that satisfy expression."""
all_keys = index.get_all_keys()
returned_keys = expression(index)
return [key for key in all_keys if key not in returned_keys]
return _not | [
"def",
"not_query",
"(",
"expression",
")",
":",
"compiled_expression",
"=",
"compile_query",
"(",
"expression",
")",
"def",
"_not",
"(",
"index",
",",
"expression",
"=",
"compiled_expression",
")",
":",
"\"\"\"Return store key for documents that satisfy expression.\"\"\"... | Apply logical not operator to expression. | [
"Apply",
"logical",
"not",
"operator",
"to",
"expression",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L51-L61 | train | 52,816 |
adewes/blitzdb | blitzdb/backends/file/queries.py | comparison_operator_query | def comparison_operator_query(comparison_operator):
"""Generate comparison operator checking function."""
def _comparison_operator_query(expression):
"""Apply binary operator to expression."""
def _apply_comparison_operator(index, expression=expression):
"""Return store key for documents that satisfy expression."""
ev = expression() if callable(expression) else expression
return [
store_key
for value, store_keys
in index.get_index().items()
if comparison_operator(value, ev)
for store_key in store_keys
]
return _apply_comparison_operator
return _comparison_operator_query | python | def comparison_operator_query(comparison_operator):
"""Generate comparison operator checking function."""
def _comparison_operator_query(expression):
"""Apply binary operator to expression."""
def _apply_comparison_operator(index, expression=expression):
"""Return store key for documents that satisfy expression."""
ev = expression() if callable(expression) else expression
return [
store_key
for value, store_keys
in index.get_index().items()
if comparison_operator(value, ev)
for store_key in store_keys
]
return _apply_comparison_operator
return _comparison_operator_query | [
"def",
"comparison_operator_query",
"(",
"comparison_operator",
")",
":",
"def",
"_comparison_operator_query",
"(",
"expression",
")",
":",
"\"\"\"Apply binary operator to expression.\"\"\"",
"def",
"_apply_comparison_operator",
"(",
"index",
",",
"expression",
"=",
"expressi... | Generate comparison operator checking function. | [
"Generate",
"comparison",
"operator",
"checking",
"function",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L64-L79 | train | 52,817 |
adewes/blitzdb | blitzdb/backends/file/queries.py | exists_query | def exists_query(expression):
"""Check that documents have a key that satisfies expression."""
def _exists(index, expression=expression):
"""Return store key for documents that satisfy expression."""
ev = expression() if callable(expression) else expression
if ev:
return [
store_key
for store_keys
in index.get_index().values()
for store_key in store_keys
]
else:
return index.get_undefined_keys()
return _exists | python | def exists_query(expression):
"""Check that documents have a key that satisfies expression."""
def _exists(index, expression=expression):
"""Return store key for documents that satisfy expression."""
ev = expression() if callable(expression) else expression
if ev:
return [
store_key
for store_keys
in index.get_index().values()
for store_key in store_keys
]
else:
return index.get_undefined_keys()
return _exists | [
"def",
"exists_query",
"(",
"expression",
")",
":",
"def",
"_exists",
"(",
"index",
",",
"expression",
"=",
"expression",
")",
":",
"\"\"\"Return store key for documents that satisfy expression.\"\"\"",
"ev",
"=",
"expression",
"(",
")",
"if",
"callable",
"(",
"expr... | Check that documents have a key that satisfies expression. | [
"Check",
"that",
"documents",
"have",
"a",
"key",
"that",
"satisfies",
"expression",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L82-L97 | train | 52,818 |
adewes/blitzdb | blitzdb/backends/file/queries.py | regex_query | def regex_query(expression):
"""Apply regular expression to result of expression."""
def _regex(index, expression=expression):
"""Return store key for documents that satisfy expression."""
pattern = re.compile(expression)
return [
store_key
for value, store_keys
in index.get_index().items()
if (isinstance(value, six.string_types)
and re.match(pattern, value))
for store_key in store_keys
]
return _regex | python | def regex_query(expression):
"""Apply regular expression to result of expression."""
def _regex(index, expression=expression):
"""Return store key for documents that satisfy expression."""
pattern = re.compile(expression)
return [
store_key
for value, store_keys
in index.get_index().items()
if (isinstance(value, six.string_types)
and re.match(pattern, value))
for store_key in store_keys
]
return _regex | [
"def",
"regex_query",
"(",
"expression",
")",
":",
"def",
"_regex",
"(",
"index",
",",
"expression",
"=",
"expression",
")",
":",
"\"\"\"Return store key for documents that satisfy expression.\"\"\"",
"pattern",
"=",
"re",
".",
"compile",
"(",
"expression",
")",
"re... | Apply regular expression to result of expression. | [
"Apply",
"regular",
"expression",
"to",
"result",
"of",
"expression",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L100-L114 | train | 52,819 |
adewes/blitzdb | blitzdb/backends/file/queries.py | all_query | def all_query(expression):
"""Match arrays that contain all elements in the query."""
def _all(index, expression=expression):
"""Return store key for documents that satisfy expression."""
ev = expression() if callable(expression) else expression
try:
iter(ev)
except TypeError:
raise AttributeError('$all argument must be an iterable!')
hashed_ev = [index.get_hash_for(v) for v in ev]
store_keys = set()
if len(hashed_ev) == 0:
return []
store_keys = set(index.get_keys_for(hashed_ev[0]))
for value in hashed_ev[1:]:
store_keys &= set(index.get_keys_for(value))
return list(store_keys)
return _all | python | def all_query(expression):
"""Match arrays that contain all elements in the query."""
def _all(index, expression=expression):
"""Return store key for documents that satisfy expression."""
ev = expression() if callable(expression) else expression
try:
iter(ev)
except TypeError:
raise AttributeError('$all argument must be an iterable!')
hashed_ev = [index.get_hash_for(v) for v in ev]
store_keys = set()
if len(hashed_ev) == 0:
return []
store_keys = set(index.get_keys_for(hashed_ev[0]))
for value in hashed_ev[1:]:
store_keys &= set(index.get_keys_for(value))
return list(store_keys)
return _all | [
"def",
"all_query",
"(",
"expression",
")",
":",
"def",
"_all",
"(",
"index",
",",
"expression",
"=",
"expression",
")",
":",
"\"\"\"Return store key for documents that satisfy expression.\"\"\"",
"ev",
"=",
"expression",
"(",
")",
"if",
"callable",
"(",
"expression... | Match arrays that contain all elements in the query. | [
"Match",
"arrays",
"that",
"contain",
"all",
"elements",
"in",
"the",
"query",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L117-L137 | train | 52,820 |
adewes/blitzdb | blitzdb/backends/file/queries.py | in_query | def in_query(expression):
"""Match any of the values that exist in an array specified in query."""
def _in(index, expression=expression):
"""Return store key for documents that satisfy expression."""
ev = expression() if callable(expression) else expression
try:
iter(ev)
except TypeError:
raise AttributeError('$in argument must be an iterable!')
hashed_ev = [index.get_hash_for(v) for v in ev]
store_keys = set()
for value in hashed_ev:
store_keys |= set(index.get_keys_for(value))
return list(store_keys)
return _in | python | def in_query(expression):
"""Match any of the values that exist in an array specified in query."""
def _in(index, expression=expression):
"""Return store key for documents that satisfy expression."""
ev = expression() if callable(expression) else expression
try:
iter(ev)
except TypeError:
raise AttributeError('$in argument must be an iterable!')
hashed_ev = [index.get_hash_for(v) for v in ev]
store_keys = set()
for value in hashed_ev:
store_keys |= set(index.get_keys_for(value))
return list(store_keys)
return _in | [
"def",
"in_query",
"(",
"expression",
")",
":",
"def",
"_in",
"(",
"index",
",",
"expression",
"=",
"expression",
")",
":",
"\"\"\"Return store key for documents that satisfy expression.\"\"\"",
"ev",
"=",
"expression",
"(",
")",
"if",
"callable",
"(",
"expression",... | Match any of the values that exist in an array specified in query. | [
"Match",
"any",
"of",
"the",
"values",
"that",
"exist",
"in",
"an",
"array",
"specified",
"in",
"query",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L150-L167 | train | 52,821 |
adewes/blitzdb | blitzdb/backends/file/queries.py | compile_query | def compile_query(query):
"""Compile each expression in query recursively."""
if isinstance(query, dict):
expressions = []
for key, value in query.items():
if key.startswith('$'):
if key not in query_funcs:
raise AttributeError('Invalid operator: {}'.format(key))
expressions.append(query_funcs[key](value))
else:
expressions.append(filter_query(key, value))
if len(expressions) > 1:
return boolean_operator_query(operator.and_)(expressions)
else:
return (
expressions[0]
if len(expressions)
else lambda query_function: query_function(None, None)
)
else:
return query | python | def compile_query(query):
"""Compile each expression in query recursively."""
if isinstance(query, dict):
expressions = []
for key, value in query.items():
if key.startswith('$'):
if key not in query_funcs:
raise AttributeError('Invalid operator: {}'.format(key))
expressions.append(query_funcs[key](value))
else:
expressions.append(filter_query(key, value))
if len(expressions) > 1:
return boolean_operator_query(operator.and_)(expressions)
else:
return (
expressions[0]
if len(expressions)
else lambda query_function: query_function(None, None)
)
else:
return query | [
"def",
"compile_query",
"(",
"query",
")",
":",
"if",
"isinstance",
"(",
"query",
",",
"dict",
")",
":",
"expressions",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"query",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'$'... | Compile each expression in query recursively. | [
"Compile",
"each",
"expression",
"in",
"query",
"recursively",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L169-L189 | train | 52,822 |
seantis/suitable | suitable/module_runner.py | environment_variable | def environment_variable(key, value):
""" Temporarily overrides an environment variable. """
if key not in os.environ:
previous = None
else:
previous = os.environ[key]
os.environ[key] = value
yield
if previous is None:
del os.environ[key]
else:
os.environ[key] = previous | python | def environment_variable(key, value):
""" Temporarily overrides an environment variable. """
if key not in os.environ:
previous = None
else:
previous = os.environ[key]
os.environ[key] = value
yield
if previous is None:
del os.environ[key]
else:
os.environ[key] = previous | [
"def",
"environment_variable",
"(",
"key",
",",
"value",
")",
":",
"if",
"key",
"not",
"in",
"os",
".",
"environ",
":",
"previous",
"=",
"None",
"else",
":",
"previous",
"=",
"os",
".",
"environ",
"[",
"key",
"]",
"os",
".",
"environ",
"[",
"key",
... | Temporarily overrides an environment variable. | [
"Temporarily",
"overrides",
"an",
"environment",
"variable",
"."
] | b056afb753f2b89909edfb6e00ec7c55691135ff | https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L50-L65 | train | 52,823 |
seantis/suitable | suitable/module_runner.py | host_key_checking | def host_key_checking(enable):
""" Temporarily disables host_key_checking, which is set globally. """
def as_string(b):
return b and 'True' or 'False'
with environment_variable('ANSIBLE_HOST_KEY_CHECKING', as_string(enable)):
previous = ansible.constants.HOST_KEY_CHECKING
ansible.constants.HOST_KEY_CHECKING = enable
yield
ansible.constants.HOST_KEY_CHECKING = previous | python | def host_key_checking(enable):
""" Temporarily disables host_key_checking, which is set globally. """
def as_string(b):
return b and 'True' or 'False'
with environment_variable('ANSIBLE_HOST_KEY_CHECKING', as_string(enable)):
previous = ansible.constants.HOST_KEY_CHECKING
ansible.constants.HOST_KEY_CHECKING = enable
yield
ansible.constants.HOST_KEY_CHECKING = previous | [
"def",
"host_key_checking",
"(",
"enable",
")",
":",
"def",
"as_string",
"(",
"b",
")",
":",
"return",
"b",
"and",
"'True'",
"or",
"'False'",
"with",
"environment_variable",
"(",
"'ANSIBLE_HOST_KEY_CHECKING'",
",",
"as_string",
"(",
"enable",
")",
")",
":",
... | Temporarily disables host_key_checking, which is set globally. | [
"Temporarily",
"disables",
"host_key_checking",
"which",
"is",
"set",
"globally",
"."
] | b056afb753f2b89909edfb6e00ec7c55691135ff | https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L69-L80 | train | 52,824 |
seantis/suitable | suitable/module_runner.py | ModuleRunner.execute | def execute(self, *args, **kwargs):
""" Puts args and kwargs in a way ansible can understand. Calls ansible
and interprets the result.
"""
assert self.is_hooked_up, "the module should be hooked up to the api"
if set_global_context:
set_global_context(self.api.options)
# legacy key=value pairs shorthand approach
if args:
self.module_args = module_args = self.get_module_args(args, kwargs)
else:
self.module_args = module_args = kwargs
loader = DataLoader()
inventory_manager = SourcelessInventoryManager(loader=loader)
for host, port in self.api.hosts_with_ports:
inventory_manager._inventory.add_host(host, group='all', port=port)
for key, value in self.api.options.extra_vars.items():
inventory_manager._inventory.set_variable('all', key, value)
variable_manager = VariableManager(
loader=loader, inventory=inventory_manager)
play_source = {
'name': "Suitable Play",
'hosts': 'all',
'gather_facts': 'no',
'tasks': [{
'action': {
'module': self.module_name,
'args': module_args,
},
'environment': self.api.environment,
}]
}
try:
play = Play.load(
play_source,
variable_manager=variable_manager,
loader=loader,
)
if self.api.strategy:
play.strategy = self.api.strategy
log.info(
u'running {}'.format(u'- {module_name}: {module_args}'.format(
module_name=self.module_name,
module_args=module_args
))
)
start = datetime.utcnow()
task_queue_manager = None
callback = SilentCallbackModule()
# ansible uses various levels of verbosity (from -v to -vvvvvv)
# offering various amounts of debug information
#
# we keep it a bit simpler by activating all of it during debug,
# and falling back to the default of 0 otherwise
verbosity = self.api.options.verbosity == logging.DEBUG and 6 or 0
with ansible_verbosity(verbosity):
# host_key_checking is special, since not each connection
# plugin handles it the same way, we need to apply both
# environment variable and Ansible constant when running a
# command in the runner to be successful
with host_key_checking(self.api.host_key_checking):
kwargs = dict(
inventory=inventory_manager,
variable_manager=variable_manager,
loader=loader,
options=self.api.options,
passwords=getattr(self.api.options, 'passwords', {}),
stdout_callback=callback
)
if set_global_context:
del kwargs['options']
task_queue_manager = TaskQueueManager(**kwargs)
try:
task_queue_manager.run(play)
except SystemExit:
# Mitogen forks our process and exits it in one
# instance before returning
#
# This is fine, but it does lead to a very messy exit
# by py.test which will essentially return with a test
# that is first successful and then failed as each
# forked process dies.
#
# To avoid this we commit suicide if we are run inside
# a pytest session. Normally this would just result
# in a exit code of zero, which is good.
if 'pytest' in sys.modules:
try:
atexit._run_exitfuncs()
except Exception:
pass
os.kill(os.getpid(), signal.SIGKILL)
raise
finally:
if task_queue_manager is not None:
task_queue_manager.cleanup()
if set_global_context:
# Ansible 2.8 introduces a global context which persists
# during the lifetime of the process - for Suitable this
# singleton/cache needs to be cleared after each call
# to make sure that API calls do not carry over state.
#
# The docs hint at a future inclusion of local contexts, which
# would of course be preferable.
from ansible.utils.context_objects import GlobalCLIArgs
GlobalCLIArgs._Singleton__instance = None
log.debug(u'took {} to complete'.format(datetime.utcnow() - start))
return self.evaluate_results(callback) | python | def execute(self, *args, **kwargs):
""" Puts args and kwargs in a way ansible can understand. Calls ansible
and interprets the result.
"""
assert self.is_hooked_up, "the module should be hooked up to the api"
if set_global_context:
set_global_context(self.api.options)
# legacy key=value pairs shorthand approach
if args:
self.module_args = module_args = self.get_module_args(args, kwargs)
else:
self.module_args = module_args = kwargs
loader = DataLoader()
inventory_manager = SourcelessInventoryManager(loader=loader)
for host, port in self.api.hosts_with_ports:
inventory_manager._inventory.add_host(host, group='all', port=port)
for key, value in self.api.options.extra_vars.items():
inventory_manager._inventory.set_variable('all', key, value)
variable_manager = VariableManager(
loader=loader, inventory=inventory_manager)
play_source = {
'name': "Suitable Play",
'hosts': 'all',
'gather_facts': 'no',
'tasks': [{
'action': {
'module': self.module_name,
'args': module_args,
},
'environment': self.api.environment,
}]
}
try:
play = Play.load(
play_source,
variable_manager=variable_manager,
loader=loader,
)
if self.api.strategy:
play.strategy = self.api.strategy
log.info(
u'running {}'.format(u'- {module_name}: {module_args}'.format(
module_name=self.module_name,
module_args=module_args
))
)
start = datetime.utcnow()
task_queue_manager = None
callback = SilentCallbackModule()
# ansible uses various levels of verbosity (from -v to -vvvvvv)
# offering various amounts of debug information
#
# we keep it a bit simpler by activating all of it during debug,
# and falling back to the default of 0 otherwise
verbosity = self.api.options.verbosity == logging.DEBUG and 6 or 0
with ansible_verbosity(verbosity):
# host_key_checking is special, since not each connection
# plugin handles it the same way, we need to apply both
# environment variable and Ansible constant when running a
# command in the runner to be successful
with host_key_checking(self.api.host_key_checking):
kwargs = dict(
inventory=inventory_manager,
variable_manager=variable_manager,
loader=loader,
options=self.api.options,
passwords=getattr(self.api.options, 'passwords', {}),
stdout_callback=callback
)
if set_global_context:
del kwargs['options']
task_queue_manager = TaskQueueManager(**kwargs)
try:
task_queue_manager.run(play)
except SystemExit:
# Mitogen forks our process and exits it in one
# instance before returning
#
# This is fine, but it does lead to a very messy exit
# by py.test which will essentially return with a test
# that is first successful and then failed as each
# forked process dies.
#
# To avoid this we commit suicide if we are run inside
# a pytest session. Normally this would just result
# in a exit code of zero, which is good.
if 'pytest' in sys.modules:
try:
atexit._run_exitfuncs()
except Exception:
pass
os.kill(os.getpid(), signal.SIGKILL)
raise
finally:
if task_queue_manager is not None:
task_queue_manager.cleanup()
if set_global_context:
# Ansible 2.8 introduces a global context which persists
# during the lifetime of the process - for Suitable this
# singleton/cache needs to be cleared after each call
# to make sure that API calls do not carry over state.
#
# The docs hint at a future inclusion of local contexts, which
# would of course be preferable.
from ansible.utils.context_objects import GlobalCLIArgs
GlobalCLIArgs._Singleton__instance = None
log.debug(u'took {} to complete'.format(datetime.utcnow() - start))
return self.evaluate_results(callback) | [
"def",
"execute",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"is_hooked_up",
",",
"\"the module should be hooked up to the api\"",
"if",
"set_global_context",
":",
"set_global_context",
"(",
"self",
".",
"api",
".",
... | Puts args and kwargs in a way ansible can understand. Calls ansible
and interprets the result. | [
"Puts",
"args",
"and",
"kwargs",
"in",
"a",
"way",
"ansible",
"can",
"understand",
".",
"Calls",
"ansible",
"and",
"interprets",
"the",
"result",
"."
] | b056afb753f2b89909edfb6e00ec7c55691135ff | https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L140-L271 | train | 52,825 |
seantis/suitable | suitable/module_runner.py | ModuleRunner.ignore_further_calls_to_server | def ignore_further_calls_to_server(self, server):
""" Takes a server out of the list. """
log.error(u'ignoring further calls to {}'.format(server))
self.api.servers.remove(server) | python | def ignore_further_calls_to_server(self, server):
""" Takes a server out of the list. """
log.error(u'ignoring further calls to {}'.format(server))
self.api.servers.remove(server) | [
"def",
"ignore_further_calls_to_server",
"(",
"self",
",",
"server",
")",
":",
"log",
".",
"error",
"(",
"u'ignoring further calls to {}'",
".",
"format",
"(",
"server",
")",
")",
"self",
".",
"api",
".",
"servers",
".",
"remove",
"(",
"server",
")"
] | Takes a server out of the list. | [
"Takes",
"a",
"server",
"out",
"of",
"the",
"list",
"."
] | b056afb753f2b89909edfb6e00ec7c55691135ff | https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L273-L276 | train | 52,826 |
seantis/suitable | suitable/module_runner.py | ModuleRunner.evaluate_results | def evaluate_results(self, callback):
""" prepare the result of runner call for use with RunnerResults. """
for server, result in callback.unreachable.items():
log.error(u'{} could not be reached'.format(server))
log.debug(u'ansible-output =>\n{}'.format(pformat(result)))
if self.api.ignore_unreachable:
continue
self.trigger_event(server, 'on_unreachable_host', (
self, server
))
for server, answer in callback.contacted.items():
success = answer['success']
result = answer['result']
# none of the modules in our tests hit the 'failed' result
# codepath (which seems to not be implemented by all modules)
# seo we ignore this branch since it's rather trivial
if result.get('failed'): # pragma: no cover
success = False
if 'rc' in result:
if self.api.is_valid_return_code(result['rc']):
success = True
if not success:
log.error(u'{} failed on {}'.format(self, server))
log.debug(u'ansible-output =>\n{}'.format(pformat(result)))
if self.api.ignore_errors:
continue
self.trigger_event(server, 'on_module_error', (
self, server, result
))
# XXX this is a weird structure because RunnerResults still works
# like it did with Ansible 1.x, where the results where structured
# like this
return RunnerResults({
'contacted': {
server: answer['result']
for server, answer in callback.contacted.items()
}
}) | python | def evaluate_results(self, callback):
""" prepare the result of runner call for use with RunnerResults. """
for server, result in callback.unreachable.items():
log.error(u'{} could not be reached'.format(server))
log.debug(u'ansible-output =>\n{}'.format(pformat(result)))
if self.api.ignore_unreachable:
continue
self.trigger_event(server, 'on_unreachable_host', (
self, server
))
for server, answer in callback.contacted.items():
success = answer['success']
result = answer['result']
# none of the modules in our tests hit the 'failed' result
# codepath (which seems to not be implemented by all modules)
# seo we ignore this branch since it's rather trivial
if result.get('failed'): # pragma: no cover
success = False
if 'rc' in result:
if self.api.is_valid_return_code(result['rc']):
success = True
if not success:
log.error(u'{} failed on {}'.format(self, server))
log.debug(u'ansible-output =>\n{}'.format(pformat(result)))
if self.api.ignore_errors:
continue
self.trigger_event(server, 'on_module_error', (
self, server, result
))
# XXX this is a weird structure because RunnerResults still works
# like it did with Ansible 1.x, where the results where structured
# like this
return RunnerResults({
'contacted': {
server: answer['result']
for server, answer in callback.contacted.items()
}
}) | [
"def",
"evaluate_results",
"(",
"self",
",",
"callback",
")",
":",
"for",
"server",
",",
"result",
"in",
"callback",
".",
"unreachable",
".",
"items",
"(",
")",
":",
"log",
".",
"error",
"(",
"u'{} could not be reached'",
".",
"format",
"(",
"server",
")",... | prepare the result of runner call for use with RunnerResults. | [
"prepare",
"the",
"result",
"of",
"runner",
"call",
"for",
"use",
"with",
"RunnerResults",
"."
] | b056afb753f2b89909edfb6e00ec7c55691135ff | https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L288-L336 | train | 52,827 |
seantis/suitable | suitable/api.py | install_strategy_plugins | def install_strategy_plugins(directories):
""" Loads the given strategy plugins, which is a list of directories,
a string with a single directory or a string with multiple directories
separated by colon.
As these plugins are globally loaded and cached by Ansible we do the same
here. We could try to bind those plugins to the Api instance, but that's
probably not something we'd ever have much of a use for.
Call this function before using custom strategies on the :class:`Api`
class.
"""
if isinstance(directories, str):
directories = directories.split(':')
for directory in directories:
strategy_loader.add_directory(directory) | python | def install_strategy_plugins(directories):
""" Loads the given strategy plugins, which is a list of directories,
a string with a single directory or a string with multiple directories
separated by colon.
As these plugins are globally loaded and cached by Ansible we do the same
here. We could try to bind those plugins to the Api instance, but that's
probably not something we'd ever have much of a use for.
Call this function before using custom strategies on the :class:`Api`
class.
"""
if isinstance(directories, str):
directories = directories.split(':')
for directory in directories:
strategy_loader.add_directory(directory) | [
"def",
"install_strategy_plugins",
"(",
"directories",
")",
":",
"if",
"isinstance",
"(",
"directories",
",",
"str",
")",
":",
"directories",
"=",
"directories",
".",
"split",
"(",
"':'",
")",
"for",
"directory",
"in",
"directories",
":",
"strategy_loader",
".... | Loads the given strategy plugins, which is a list of directories,
a string with a single directory or a string with multiple directories
separated by colon.
As these plugins are globally loaded and cached by Ansible we do the same
here. We could try to bind those plugins to the Api instance, but that's
probably not something we'd ever have much of a use for.
Call this function before using custom strategies on the :class:`Api`
class. | [
"Loads",
"the",
"given",
"strategy",
"plugins",
"which",
"is",
"a",
"list",
"of",
"directories",
"a",
"string",
"with",
"a",
"single",
"directory",
"or",
"a",
"string",
"with",
"multiple",
"directories",
"separated",
"by",
"colon",
"."
] | b056afb753f2b89909edfb6e00ec7c55691135ff | https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/api.py#L298-L315 | train | 52,828 |
nielstron/pysyncthru | pysyncthru/__init__.py | construct_url | def construct_url(ip_address: str) -> str:
"""Construct the URL with a given IP address."""
if 'http://' not in ip_address and 'https://' not in ip_address:
ip_address = '{}{}'.format('http://', ip_address)
if ip_address[-1] == '/':
ip_address = ip_address[:-1]
return ip_address | python | def construct_url(ip_address: str) -> str:
"""Construct the URL with a given IP address."""
if 'http://' not in ip_address and 'https://' not in ip_address:
ip_address = '{}{}'.format('http://', ip_address)
if ip_address[-1] == '/':
ip_address = ip_address[:-1]
return ip_address | [
"def",
"construct_url",
"(",
"ip_address",
":",
"str",
")",
"->",
"str",
":",
"if",
"'http://'",
"not",
"in",
"ip_address",
"and",
"'https://'",
"not",
"in",
"ip_address",
":",
"ip_address",
"=",
"'{}{}'",
".",
"format",
"(",
"'http://'",
",",
"ip_address",
... | Construct the URL with a given IP address. | [
"Construct",
"the",
"URL",
"with",
"a",
"given",
"IP",
"address",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L12-L18 | train | 52,829 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.update | async def update(self) -> None:
"""
Retrieve the data from the printer.
Throws ValueError if host does not support SyncThru
"""
url = '{}{}'.format(self.url, ENDPOINT)
try:
async with self._session.get(url) as response:
json_dict = demjson.decode(await response.text(), strict=False)
except aiohttp.ClientError:
json_dict = {'status': {'status1': SyncThru.OFFLINE}}
except demjson.JSONDecodeError:
raise ValueError("Invalid host, does not support SyncThru.")
self.data = json_dict | python | async def update(self) -> None:
"""
Retrieve the data from the printer.
Throws ValueError if host does not support SyncThru
"""
url = '{}{}'.format(self.url, ENDPOINT)
try:
async with self._session.get(url) as response:
json_dict = demjson.decode(await response.text(), strict=False)
except aiohttp.ClientError:
json_dict = {'status': {'status1': SyncThru.OFFLINE}}
except demjson.JSONDecodeError:
raise ValueError("Invalid host, does not support SyncThru.")
self.data = json_dict | [
"async",
"def",
"update",
"(",
"self",
")",
"->",
"None",
":",
"url",
"=",
"'{}{}'",
".",
"format",
"(",
"self",
".",
"url",
",",
"ENDPOINT",
")",
"try",
":",
"async",
"with",
"self",
".",
"_session",
".",
"get",
"(",
"url",
")",
"as",
"response",
... | Retrieve the data from the printer.
Throws ValueError if host does not support SyncThru | [
"Retrieve",
"the",
"data",
"from",
"the",
"printer",
".",
"Throws",
"ValueError",
"if",
"host",
"does",
"not",
"support",
"SyncThru"
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L35-L49 | train | 52,830 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.model | def model(self):
"""Return the model name of the printer."""
try:
return self.data.get('identity').get('model_name')
except (KeyError, AttributeError):
return self.device_status_simple('') | python | def model(self):
"""Return the model name of the printer."""
try:
return self.data.get('identity').get('model_name')
except (KeyError, AttributeError):
return self.device_status_simple('') | [
"def",
"model",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"get",
"(",
"'identity'",
")",
".",
"get",
"(",
"'model_name'",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"return",
"self",
".",
"device_statu... | Return the model name of the printer. | [
"Return",
"the",
"model",
"name",
"of",
"the",
"printer",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L66-L71 | train | 52,831 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.location | def location(self):
"""Return the location of the printer."""
try:
return self.data.get('identity').get('location')
except (KeyError, AttributeError):
return self.device_status_simple('') | python | def location(self):
"""Return the location of the printer."""
try:
return self.data.get('identity').get('location')
except (KeyError, AttributeError):
return self.device_status_simple('') | [
"def",
"location",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"get",
"(",
"'identity'",
")",
".",
"get",
"(",
"'location'",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"return",
"self",
".",
"device_stat... | Return the location of the printer. | [
"Return",
"the",
"location",
"of",
"the",
"printer",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L73-L78 | train | 52,832 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.serial_number | def serial_number(self):
"""Return the serial number of the printer."""
try:
return self.data.get('identity').get('serial_num')
except (KeyError, AttributeError):
return self.device_status_simple('') | python | def serial_number(self):
"""Return the serial number of the printer."""
try:
return self.data.get('identity').get('serial_num')
except (KeyError, AttributeError):
return self.device_status_simple('') | [
"def",
"serial_number",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"get",
"(",
"'identity'",
")",
".",
"get",
"(",
"'serial_num'",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"return",
"self",
".",
"devi... | Return the serial number of the printer. | [
"Return",
"the",
"serial",
"number",
"of",
"the",
"printer",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L80-L85 | train | 52,833 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.hostname | def hostname(self):
"""Return the hostname of the printer."""
try:
return self.data.get('identity').get('host_name')
except (KeyError, AttributeError):
return self.device_status_simple('') | python | def hostname(self):
"""Return the hostname of the printer."""
try:
return self.data.get('identity').get('host_name')
except (KeyError, AttributeError):
return self.device_status_simple('') | [
"def",
"hostname",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"get",
"(",
"'identity'",
")",
".",
"get",
"(",
"'host_name'",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"return",
"self",
".",
"device_sta... | Return the hostname of the printer. | [
"Return",
"the",
"hostname",
"of",
"the",
"printer",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L87-L92 | train | 52,834 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.device_status | def device_status(self):
"""Return the status of the device as string."""
try:
return self.device_status_simple(
self.data.get('status').get('status1'))
except (KeyError, AttributeError):
return self.device_status_simple('') | python | def device_status(self):
"""Return the status of the device as string."""
try:
return self.device_status_simple(
self.data.get('status').get('status1'))
except (KeyError, AttributeError):
return self.device_status_simple('') | [
"def",
"device_status",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"device_status_simple",
"(",
"self",
".",
"data",
".",
"get",
"(",
"'status'",
")",
".",
"get",
"(",
"'status1'",
")",
")",
"except",
"(",
"KeyError",
",",
"AttributeError"... | Return the status of the device as string. | [
"Return",
"the",
"status",
"of",
"the",
"device",
"as",
"string",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L94-L100 | train | 52,835 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.capability | def capability(self) -> Dict[str, Any]:
"""Return the capabilities of the printer."""
try:
return self.data.get('capability', {})
except (KeyError, AttributeError):
return {} | python | def capability(self) -> Dict[str, Any]:
"""Return the capabilities of the printer."""
try:
return self.data.get('capability', {})
except (KeyError, AttributeError):
return {} | [
"def",
"capability",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"get",
"(",
"'capability'",
",",
"{",
"}",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"retu... | Return the capabilities of the printer. | [
"Return",
"the",
"capabilities",
"of",
"the",
"printer",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L102-L107 | train | 52,836 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.toner_status | def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]:
"""Return the state of all toners cartridges."""
toner_status = {}
for color in self.COLOR_NAMES:
try:
toner_stat = self.data.get(
'{}_{}'.format(SyncThru.TONER, color), {})
if filter_supported and toner_stat.get('opt', 0) == 0:
continue
else:
toner_status[color] = toner_stat
except (KeyError, AttributeError):
toner_status[color] = {}
return toner_status | python | def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]:
"""Return the state of all toners cartridges."""
toner_status = {}
for color in self.COLOR_NAMES:
try:
toner_stat = self.data.get(
'{}_{}'.format(SyncThru.TONER, color), {})
if filter_supported and toner_stat.get('opt', 0) == 0:
continue
else:
toner_status[color] = toner_stat
except (KeyError, AttributeError):
toner_status[color] = {}
return toner_status | [
"def",
"toner_status",
"(",
"self",
",",
"filter_supported",
":",
"bool",
"=",
"True",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"toner_status",
"=",
"{",
"}",
"for",
"color",
"in",
"self",
".",
"COLOR_NAMES",
":",
"try",
":",
"toner_stat",
... | Return the state of all toners cartridges. | [
"Return",
"the",
"state",
"of",
"all",
"toners",
"cartridges",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L116-L129 | train | 52,837 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.input_tray_status | def input_tray_status(self,
filter_supported: bool = True) -> Dict[int, Any]:
"""Return the state of all input trays."""
tray_status = {}
for i in range(1, 5):
try:
tray_stat = self.data.get('{}{}'.format(SyncThru.TRAY, i), {})
if filter_supported and tray_stat.get('opt', 0) == 0:
continue
else:
tray_status[i] = tray_stat
except (KeyError, AttributeError):
tray_status[i] = {}
return tray_status | python | def input_tray_status(self,
filter_supported: bool = True) -> Dict[int, Any]:
"""Return the state of all input trays."""
tray_status = {}
for i in range(1, 5):
try:
tray_stat = self.data.get('{}{}'.format(SyncThru.TRAY, i), {})
if filter_supported and tray_stat.get('opt', 0) == 0:
continue
else:
tray_status[i] = tray_stat
except (KeyError, AttributeError):
tray_status[i] = {}
return tray_status | [
"def",
"input_tray_status",
"(",
"self",
",",
"filter_supported",
":",
"bool",
"=",
"True",
")",
"->",
"Dict",
"[",
"int",
",",
"Any",
"]",
":",
"tray_status",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"5",
")",
":",
"try",
":",
"t... | Return the state of all input trays. | [
"Return",
"the",
"state",
"of",
"all",
"input",
"trays",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L131-L144 | train | 52,838 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.output_tray_status | def output_tray_status(self) -> Dict[int, Dict[str, str]]:
"""Return the state of all output trays."""
tray_status = {}
try:
tray_stat = self.data.get('outputTray', [])
for i, stat in enumerate(tray_stat):
tray_status[i] = {
'name': stat[0],
'capacity': stat[1],
'status': stat[2],
}
except (KeyError, AttributeError):
tray_status = {}
return tray_status | python | def output_tray_status(self) -> Dict[int, Dict[str, str]]:
"""Return the state of all output trays."""
tray_status = {}
try:
tray_stat = self.data.get('outputTray', [])
for i, stat in enumerate(tray_stat):
tray_status[i] = {
'name': stat[0],
'capacity': stat[1],
'status': stat[2],
}
except (KeyError, AttributeError):
tray_status = {}
return tray_status | [
"def",
"output_tray_status",
"(",
"self",
")",
"->",
"Dict",
"[",
"int",
",",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"tray_status",
"=",
"{",
"}",
"try",
":",
"tray_stat",
"=",
"self",
".",
"data",
".",
"get",
"(",
"'outputTray'",
",",
"[",... | Return the state of all output trays. | [
"Return",
"the",
"state",
"of",
"all",
"output",
"trays",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L146-L159 | train | 52,839 |
nielstron/pysyncthru | pysyncthru/__init__.py | SyncThru.drum_status | def drum_status(self, filter_supported: bool = True) -> Dict[str, Any]:
"""Return the state of all drums."""
drum_status = {}
for color in self.COLOR_NAMES:
try:
drum_stat = self.data.get('{}_{}'.format(SyncThru.DRUM, color),
{})
if filter_supported and drum_stat.get('opt', 0) == 0:
continue
else:
drum_status[color] = drum_stat
except (KeyError, AttributeError):
drum_status[color] = {}
return drum_status | python | def drum_status(self, filter_supported: bool = True) -> Dict[str, Any]:
"""Return the state of all drums."""
drum_status = {}
for color in self.COLOR_NAMES:
try:
drum_stat = self.data.get('{}_{}'.format(SyncThru.DRUM, color),
{})
if filter_supported and drum_stat.get('opt', 0) == 0:
continue
else:
drum_status[color] = drum_stat
except (KeyError, AttributeError):
drum_status[color] = {}
return drum_status | [
"def",
"drum_status",
"(",
"self",
",",
"filter_supported",
":",
"bool",
"=",
"True",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"drum_status",
"=",
"{",
"}",
"for",
"color",
"in",
"self",
".",
"COLOR_NAMES",
":",
"try",
":",
"drum_stat",
"... | Return the state of all drums. | [
"Return",
"the",
"state",
"of",
"all",
"drums",
"."
] | 850a85ba0a74cbd5c408102bb02fd005d8b61ffb | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L161-L174 | train | 52,840 |
RudolfCardinal/pythonlib | cardinal_pythonlib/debugging.py | get_caller_stack_info | def get_caller_stack_info(start_back: int = 1) -> List[str]:
r"""
Retrieves a textual representation of the call stack.
Args:
start_back: number of calls back in the frame stack (starting
from the frame stack as seen by :func:`get_caller_stack_info`)
to begin with
Returns:
list of descriptions
Example:
.. code-block:: python
from cardinal_pythonlib.debugging import get_caller_stack_info
def who_am_i():
return get_caller_name()
class MyClass(object):
def classfunc(self):
print("Stack info:\n" + "\n".join(get_caller_stack_info()))
def f2():
x = MyClass()
x.classfunc()
def f1():
f2()
f1()
if called from the Python prompt will produce:
.. code-block:: none
Stack info:
<module>()
... defined at <stdin>:1
... line 1 calls next in stack; code is:
f1()
... defined at <stdin>:1
... line 2 calls next in stack; code is:
f2()
... defined at <stdin>:1
... line 3 calls next in stack; code is:
classfunc(self=<__main__.MyClass object at 0x7f86a009c6d8>)
... defined at <stdin>:2
... line 3 calls next in stack; code is:
and if called from a Python file will produce:
.. code-block:: none
Stack info:
<module>()
... defined at /home/rudolf/tmp/stack.py:1
... line 17 calls next in stack; code is:
f1()
f1()
... defined at /home/rudolf/tmp/stack.py:14
... line 15 calls next in stack; code is:
f2()
f2()
... defined at /home/rudolf/tmp/stack.py:10
... line 12 calls next in stack; code is:
x.classfunc()
classfunc(self=<__main__.MyClass object at 0x7fd7a731f358>)
... defined at /home/rudolf/tmp/stack.py:7
... line 8 calls next in stack; code is:
print("Stack info:\n" + "\n".join(get_caller_stack_info()))
"""
# "0 back" is debug_callers, so "1 back" its caller
# https://docs.python.org/3/library/inspect.html
callers = [] # type: List[str]
frameinfolist = inspect.stack() # type: List[FrameInfo] # noqa
frameinfolist = frameinfolist[start_back:]
for frameinfo in frameinfolist:
frame = frameinfo.frame
function_defined_at = "... defined at {filename}:{line}".format(
filename=frame.f_code.co_filename,
line=frame.f_code.co_firstlineno,
)
argvalues = inspect.getargvalues(frame)
formatted_argvalues = inspect.formatargvalues(*argvalues)
function_call = "{funcname}{argvals}".format(
funcname=frame.f_code.co_name,
argvals=formatted_argvalues,
)
code_context = frameinfo.code_context
code = "".join(code_context) if code_context else ""
onwards = "... line {line} calls next in stack; code is:\n{c}".format(
line=frame.f_lineno,
c=code,
)
description = "\n".join([function_call, function_defined_at, onwards])
callers.append(description)
return list(reversed(callers)) | python | def get_caller_stack_info(start_back: int = 1) -> List[str]:
r"""
Retrieves a textual representation of the call stack.
Args:
start_back: number of calls back in the frame stack (starting
from the frame stack as seen by :func:`get_caller_stack_info`)
to begin with
Returns:
list of descriptions
Example:
.. code-block:: python
from cardinal_pythonlib.debugging import get_caller_stack_info
def who_am_i():
return get_caller_name()
class MyClass(object):
def classfunc(self):
print("Stack info:\n" + "\n".join(get_caller_stack_info()))
def f2():
x = MyClass()
x.classfunc()
def f1():
f2()
f1()
if called from the Python prompt will produce:
.. code-block:: none
Stack info:
<module>()
... defined at <stdin>:1
... line 1 calls next in stack; code is:
f1()
... defined at <stdin>:1
... line 2 calls next in stack; code is:
f2()
... defined at <stdin>:1
... line 3 calls next in stack; code is:
classfunc(self=<__main__.MyClass object at 0x7f86a009c6d8>)
... defined at <stdin>:2
... line 3 calls next in stack; code is:
and if called from a Python file will produce:
.. code-block:: none
Stack info:
<module>()
... defined at /home/rudolf/tmp/stack.py:1
... line 17 calls next in stack; code is:
f1()
f1()
... defined at /home/rudolf/tmp/stack.py:14
... line 15 calls next in stack; code is:
f2()
f2()
... defined at /home/rudolf/tmp/stack.py:10
... line 12 calls next in stack; code is:
x.classfunc()
classfunc(self=<__main__.MyClass object at 0x7fd7a731f358>)
... defined at /home/rudolf/tmp/stack.py:7
... line 8 calls next in stack; code is:
print("Stack info:\n" + "\n".join(get_caller_stack_info()))
"""
# "0 back" is debug_callers, so "1 back" its caller
# https://docs.python.org/3/library/inspect.html
callers = [] # type: List[str]
frameinfolist = inspect.stack() # type: List[FrameInfo] # noqa
frameinfolist = frameinfolist[start_back:]
for frameinfo in frameinfolist:
frame = frameinfo.frame
function_defined_at = "... defined at {filename}:{line}".format(
filename=frame.f_code.co_filename,
line=frame.f_code.co_firstlineno,
)
argvalues = inspect.getargvalues(frame)
formatted_argvalues = inspect.formatargvalues(*argvalues)
function_call = "{funcname}{argvals}".format(
funcname=frame.f_code.co_name,
argvals=formatted_argvalues,
)
code_context = frameinfo.code_context
code = "".join(code_context) if code_context else ""
onwards = "... line {line} calls next in stack; code is:\n{c}".format(
line=frame.f_lineno,
c=code,
)
description = "\n".join([function_call, function_defined_at, onwards])
callers.append(description)
return list(reversed(callers)) | [
"def",
"get_caller_stack_info",
"(",
"start_back",
":",
"int",
"=",
"1",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# \"0 back\" is debug_callers, so \"1 back\" its caller",
"# https://docs.python.org/3/library/inspect.html",
"callers",
"=",
"[",
"]",
"# type: List[str]",
... | r"""
Retrieves a textual representation of the call stack.
Args:
start_back: number of calls back in the frame stack (starting
from the frame stack as seen by :func:`get_caller_stack_info`)
to begin with
Returns:
list of descriptions
Example:
.. code-block:: python
from cardinal_pythonlib.debugging import get_caller_stack_info
def who_am_i():
return get_caller_name()
class MyClass(object):
def classfunc(self):
print("Stack info:\n" + "\n".join(get_caller_stack_info()))
def f2():
x = MyClass()
x.classfunc()
def f1():
f2()
f1()
if called from the Python prompt will produce:
.. code-block:: none
Stack info:
<module>()
... defined at <stdin>:1
... line 1 calls next in stack; code is:
f1()
... defined at <stdin>:1
... line 2 calls next in stack; code is:
f2()
... defined at <stdin>:1
... line 3 calls next in stack; code is:
classfunc(self=<__main__.MyClass object at 0x7f86a009c6d8>)
... defined at <stdin>:2
... line 3 calls next in stack; code is:
and if called from a Python file will produce:
.. code-block:: none
Stack info:
<module>()
... defined at /home/rudolf/tmp/stack.py:1
... line 17 calls next in stack; code is:
f1()
f1()
... defined at /home/rudolf/tmp/stack.py:14
... line 15 calls next in stack; code is:
f2()
f2()
... defined at /home/rudolf/tmp/stack.py:10
... line 12 calls next in stack; code is:
x.classfunc()
classfunc(self=<__main__.MyClass object at 0x7fd7a731f358>)
... defined at /home/rudolf/tmp/stack.py:7
... line 8 calls next in stack; code is:
print("Stack info:\n" + "\n".join(get_caller_stack_info())) | [
"r",
"Retrieves",
"a",
"textual",
"representation",
"of",
"the",
"call",
"stack",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L158-L264 | train | 52,841 |
AndrewWalker/glud | glud/matchers.py | cxxRecordDecl | def cxxRecordDecl(*args):
"""Matches C++ class declarations.
>>> from glud import *
>>> config = '''
... class W;
... template<typename T> class X {};
... struct Y {};
... union Z {};
... '''
>>> m = cxxRecordDecl()
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)
W
X
"""
kinds = [
CursorKind.CLASS_DECL,
CursorKind.CLASS_TEMPLATE,
]
inner = [ PredMatcher(is_kind(k)) for k in kinds ]
return allOf(anyOf(*inner), *args) | python | def cxxRecordDecl(*args):
"""Matches C++ class declarations.
>>> from glud import *
>>> config = '''
... class W;
... template<typename T> class X {};
... struct Y {};
... union Z {};
... '''
>>> m = cxxRecordDecl()
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)
W
X
"""
kinds = [
CursorKind.CLASS_DECL,
CursorKind.CLASS_TEMPLATE,
]
inner = [ PredMatcher(is_kind(k)) for k in kinds ]
return allOf(anyOf(*inner), *args) | [
"def",
"cxxRecordDecl",
"(",
"*",
"args",
")",
":",
"kinds",
"=",
"[",
"CursorKind",
".",
"CLASS_DECL",
",",
"CursorKind",
".",
"CLASS_TEMPLATE",
",",
"]",
"inner",
"=",
"[",
"PredMatcher",
"(",
"is_kind",
"(",
"k",
")",
")",
"for",
"k",
"in",
"kinds",... | Matches C++ class declarations.
>>> from glud import *
>>> config = '''
... class W;
... template<typename T> class X {};
... struct Y {};
... union Z {};
... '''
>>> m = cxxRecordDecl()
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)
W
X | [
"Matches",
"C",
"++",
"class",
"declarations",
"."
] | 57de000627fed13d0c383f131163795b09549257 | https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/matchers.py#L167-L188 | train | 52,842 |
AndrewWalker/glud | glud/matchers.py | recordDecl | def recordDecl(*args):
"""Matches class, struct, and union declarations.
>>> from glud import *
>>> config = '''
... class W;
... template<typename T> class X {};
... struct Y {};
... union Z {};
... '''
>>> m = recordDecl()
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)
W
X
Y
Z
"""
kinds = [
CursorKind.STRUCT_DECL,
CursorKind.UNION_DECL,
CursorKind.CLASS_DECL,
CursorKind.CLASS_TEMPLATE,
]
inner = [ PredMatcher(is_kind(k)) for k in kinds ]
return allOf(anyOf(*inner), *args) | python | def recordDecl(*args):
"""Matches class, struct, and union declarations.
>>> from glud import *
>>> config = '''
... class W;
... template<typename T> class X {};
... struct Y {};
... union Z {};
... '''
>>> m = recordDecl()
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)
W
X
Y
Z
"""
kinds = [
CursorKind.STRUCT_DECL,
CursorKind.UNION_DECL,
CursorKind.CLASS_DECL,
CursorKind.CLASS_TEMPLATE,
]
inner = [ PredMatcher(is_kind(k)) for k in kinds ]
return allOf(anyOf(*inner), *args) | [
"def",
"recordDecl",
"(",
"*",
"args",
")",
":",
"kinds",
"=",
"[",
"CursorKind",
".",
"STRUCT_DECL",
",",
"CursorKind",
".",
"UNION_DECL",
",",
"CursorKind",
".",
"CLASS_DECL",
",",
"CursorKind",
".",
"CLASS_TEMPLATE",
",",
"]",
"inner",
"=",
"[",
"PredMa... | Matches class, struct, and union declarations.
>>> from glud import *
>>> config = '''
... class W;
... template<typename T> class X {};
... struct Y {};
... union Z {};
... '''
>>> m = recordDecl()
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)
W
X
Y
Z | [
"Matches",
"class",
"struct",
"and",
"union",
"declarations",
"."
] | 57de000627fed13d0c383f131163795b09549257 | https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/matchers.py#L679-L704 | train | 52,843 |
RudolfCardinal/pythonlib | cardinal_pythonlib/convert.py | convert_to_int | def convert_to_int(x: Any, default: int = None) -> int:
"""
Transforms its input into an integer, or returns ``default``.
"""
try:
return int(x)
except (TypeError, ValueError):
return default | python | def convert_to_int(x: Any, default: int = None) -> int:
"""
Transforms its input into an integer, or returns ``default``.
"""
try:
return int(x)
except (TypeError, ValueError):
return default | [
"def",
"convert_to_int",
"(",
"x",
":",
"Any",
",",
"default",
":",
"int",
"=",
"None",
")",
"->",
"int",
":",
"try",
":",
"return",
"int",
"(",
"x",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"default"
] | Transforms its input into an integer, or returns ``default``. | [
"Transforms",
"its",
"input",
"into",
"an",
"integer",
"or",
"returns",
"default",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L76-L83 | train | 52,844 |
RudolfCardinal/pythonlib | cardinal_pythonlib/convert.py | convert_attrs_to_uppercase | def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to upper case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.upper()) | python | def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to upper case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.upper()) | [
"def",
"convert_attrs_to_uppercase",
"(",
"obj",
":",
"Any",
",",
"attrs",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"a",
"in",
"attrs",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"a",
")",
"if",
"value",
"is",
"None",
":... | Converts the specified attributes of an object to upper case, modifying
the object in place. | [
"Converts",
"the",
"specified",
"attributes",
"of",
"an",
"object",
"to",
"upper",
"case",
"modifying",
"the",
"object",
"in",
"place",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L101-L110 | train | 52,845 |
RudolfCardinal/pythonlib | cardinal_pythonlib/convert.py | convert_attrs_to_lowercase | def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to lower case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.lower()) | python | def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to lower case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.lower()) | [
"def",
"convert_attrs_to_lowercase",
"(",
"obj",
":",
"Any",
",",
"attrs",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"a",
"in",
"attrs",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"a",
")",
"if",
"value",
"is",
"None",
":... | Converts the specified attributes of an object to lower case, modifying
the object in place. | [
"Converts",
"the",
"specified",
"attributes",
"of",
"an",
"object",
"to",
"lower",
"case",
"modifying",
"the",
"object",
"in",
"place",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L113-L122 | train | 52,846 |
bbengfort/confire | confire/config.py | Configuration.load | def load(klass):
"""
Insantiates the configuration by attempting to load the
configuration from YAML files specified by the CONF_PATH module
variable. This should be the main entry point for configuration.
"""
config = klass()
for path in klass.CONF_PATHS:
if os.path.exists(path):
with open(path, 'r') as conf:
config.configure(yaml.safe_load(conf))
return config | python | def load(klass):
"""
Insantiates the configuration by attempting to load the
configuration from YAML files specified by the CONF_PATH module
variable. This should be the main entry point for configuration.
"""
config = klass()
for path in klass.CONF_PATHS:
if os.path.exists(path):
with open(path, 'r') as conf:
config.configure(yaml.safe_load(conf))
return config | [
"def",
"load",
"(",
"klass",
")",
":",
"config",
"=",
"klass",
"(",
")",
"for",
"path",
"in",
"klass",
".",
"CONF_PATHS",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"c... | Insantiates the configuration by attempting to load the
configuration from YAML files specified by the CONF_PATH module
variable. This should be the main entry point for configuration. | [
"Insantiates",
"the",
"configuration",
"by",
"attempting",
"to",
"load",
"the",
"configuration",
"from",
"YAML",
"files",
"specified",
"by",
"the",
"CONF_PATH",
"module",
"variable",
".",
"This",
"should",
"be",
"the",
"main",
"entry",
"point",
"for",
"configura... | 0879aea2516b39a438e202dcc0c6882ca64eb613 | https://github.com/bbengfort/confire/blob/0879aea2516b39a438e202dcc0c6882ca64eb613/confire/config.py#L136-L147 | train | 52,847 |
bbengfort/confire | confire/config.py | Configuration.configure | def configure(self, conf={}):
"""
Allows updating of the configuration via a dictionary of
configuration terms or a configuration object. Generally speaking,
this method is utilized to configure the object from a JSON or
YAML parsing.
"""
if not conf: return
if isinstance(conf, Configuration):
conf = dict(conf.options())
for key, value in conf.items():
opt = self.get(key, None)
if isinstance(opt, Configuration):
opt.configure(value)
else:
setattr(self, key, value) | python | def configure(self, conf={}):
"""
Allows updating of the configuration via a dictionary of
configuration terms or a configuration object. Generally speaking,
this method is utilized to configure the object from a JSON or
YAML parsing.
"""
if not conf: return
if isinstance(conf, Configuration):
conf = dict(conf.options())
for key, value in conf.items():
opt = self.get(key, None)
if isinstance(opt, Configuration):
opt.configure(value)
else:
setattr(self, key, value) | [
"def",
"configure",
"(",
"self",
",",
"conf",
"=",
"{",
"}",
")",
":",
"if",
"not",
"conf",
":",
"return",
"if",
"isinstance",
"(",
"conf",
",",
"Configuration",
")",
":",
"conf",
"=",
"dict",
"(",
"conf",
".",
"options",
"(",
")",
")",
"for",
"k... | Allows updating of the configuration via a dictionary of
configuration terms or a configuration object. Generally speaking,
this method is utilized to configure the object from a JSON or
YAML parsing. | [
"Allows",
"updating",
"of",
"the",
"configuration",
"via",
"a",
"dictionary",
"of",
"configuration",
"terms",
"or",
"a",
"configuration",
"object",
".",
"Generally",
"speaking",
"this",
"method",
"is",
"utilized",
"to",
"configure",
"the",
"object",
"from",
"a",... | 0879aea2516b39a438e202dcc0c6882ca64eb613 | https://github.com/bbengfort/confire/blob/0879aea2516b39a438e202dcc0c6882ca64eb613/confire/config.py#L149-L164 | train | 52,848 |
bbengfort/confire | confire/config.py | Configuration.options | def options(self):
"""
Returns an iterable of sorted option names in order to loop
through all the configuration directives specified in the class.
"""
keys = self.__class__.__dict__.copy()
keys.update(self.__dict__)
keys = sorted(keys.keys())
for opt in keys:
val = self.get(opt)
if val is not None:
yield opt, val | python | def options(self):
"""
Returns an iterable of sorted option names in order to loop
through all the configuration directives specified in the class.
"""
keys = self.__class__.__dict__.copy()
keys.update(self.__dict__)
keys = sorted(keys.keys())
for opt in keys:
val = self.get(opt)
if val is not None:
yield opt, val | [
"def",
"options",
"(",
"self",
")",
":",
"keys",
"=",
"self",
".",
"__class__",
".",
"__dict__",
".",
"copy",
"(",
")",
"keys",
".",
"update",
"(",
"self",
".",
"__dict__",
")",
"keys",
"=",
"sorted",
"(",
"keys",
".",
"keys",
"(",
")",
")",
"for... | Returns an iterable of sorted option names in order to loop
through all the configuration directives specified in the class. | [
"Returns",
"an",
"iterable",
"of",
"sorted",
"option",
"names",
"in",
"order",
"to",
"loop",
"through",
"all",
"the",
"configuration",
"directives",
"specified",
"in",
"the",
"class",
"."
] | 0879aea2516b39a438e202dcc0c6882ca64eb613 | https://github.com/bbengfort/confire/blob/0879aea2516b39a438e202dcc0c6882ca64eb613/confire/config.py#L166-L178 | train | 52,849 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | Interval.overlaps | def overlaps(self, other: "Interval") -> bool:
"""
Does this interval overlap the other?
Overlap:
.. code-block:: none
S--------S S---S S---S
O---O O---O O---O
Simpler method of testing is for non-overlap!
.. code-block:: none
S---S S---S
O---O O---O
"""
return not(self.end <= other.start or self.start >= other.end) | python | def overlaps(self, other: "Interval") -> bool:
"""
Does this interval overlap the other?
Overlap:
.. code-block:: none
S--------S S---S S---S
O---O O---O O---O
Simpler method of testing is for non-overlap!
.. code-block:: none
S---S S---S
O---O O---O
"""
return not(self.end <= other.start or self.start >= other.end) | [
"def",
"overlaps",
"(",
"self",
",",
"other",
":",
"\"Interval\"",
")",
"->",
"bool",
":",
"return",
"not",
"(",
"self",
".",
"end",
"<=",
"other",
".",
"start",
"or",
"self",
".",
"start",
">=",
"other",
".",
"end",
")"
] | Does this interval overlap the other?
Overlap:
.. code-block:: none
S--------S S---S S---S
O---O O---O O---O
Simpler method of testing is for non-overlap!
.. code-block:: none
S---S S---S
O---O O---O | [
"Does",
"this",
"interval",
"overlap",
"the",
"other?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L270-L288 | train | 52,850 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | Interval.contiguous | def contiguous(self, other: "Interval") -> bool:
"""
Does this interval overlap or touch the other?
"""
return not(self.end < other.start or self.start > other.end) | python | def contiguous(self, other: "Interval") -> bool:
"""
Does this interval overlap or touch the other?
"""
return not(self.end < other.start or self.start > other.end) | [
"def",
"contiguous",
"(",
"self",
",",
"other",
":",
"\"Interval\"",
")",
"->",
"bool",
":",
"return",
"not",
"(",
"self",
".",
"end",
"<",
"other",
".",
"start",
"or",
"self",
".",
"start",
">",
"other",
".",
"end",
")"
] | Does this interval overlap or touch the other? | [
"Does",
"this",
"interval",
"overlap",
"or",
"touch",
"the",
"other?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L290-L294 | train | 52,851 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | Interval.contains | def contains(self, time: datetime.datetime,
inclusive: bool = True) -> bool:
"""
Does the interval contain a momentary time?
Args:
time: the ``datetime.datetime`` to check
inclusive: use inclusive rather than exclusive range checks?
"""
if inclusive:
return self.start <= time <= self.end
else:
return self.start < time < self.end | python | def contains(self, time: datetime.datetime,
inclusive: bool = True) -> bool:
"""
Does the interval contain a momentary time?
Args:
time: the ``datetime.datetime`` to check
inclusive: use inclusive rather than exclusive range checks?
"""
if inclusive:
return self.start <= time <= self.end
else:
return self.start < time < self.end | [
"def",
"contains",
"(",
"self",
",",
"time",
":",
"datetime",
".",
"datetime",
",",
"inclusive",
":",
"bool",
"=",
"True",
")",
"->",
"bool",
":",
"if",
"inclusive",
":",
"return",
"self",
".",
"start",
"<=",
"time",
"<=",
"self",
".",
"end",
"else",... | Does the interval contain a momentary time?
Args:
time: the ``datetime.datetime`` to check
inclusive: use inclusive rather than exclusive range checks? | [
"Does",
"the",
"interval",
"contain",
"a",
"momentary",
"time?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L296-L308 | train | 52,852 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | Interval.within | def within(self, other: "Interval", inclusive: bool = True) -> bool:
"""
Is this interval contained within the other?
Args:
other: the :class:`Interval` to check
inclusive: use inclusive rather than exclusive range checks?
"""
if not other:
return False
if inclusive:
return self.start >= other.start and self.end <= other.end
else:
return self.start > other.start and self.end < other.end | python | def within(self, other: "Interval", inclusive: bool = True) -> bool:
"""
Is this interval contained within the other?
Args:
other: the :class:`Interval` to check
inclusive: use inclusive rather than exclusive range checks?
"""
if not other:
return False
if inclusive:
return self.start >= other.start and self.end <= other.end
else:
return self.start > other.start and self.end < other.end | [
"def",
"within",
"(",
"self",
",",
"other",
":",
"\"Interval\"",
",",
"inclusive",
":",
"bool",
"=",
"True",
")",
"->",
"bool",
":",
"if",
"not",
"other",
":",
"return",
"False",
"if",
"inclusive",
":",
"return",
"self",
".",
"start",
">=",
"other",
... | Is this interval contained within the other?
Args:
other: the :class:`Interval` to check
inclusive: use inclusive rather than exclusive range checks? | [
"Is",
"this",
"interval",
"contained",
"within",
"the",
"other?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L310-L323 | train | 52,853 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | Interval.component_on_date | def component_on_date(self, date: datetime.date) -> Optional["Interval"]:
"""
Returns the part of this interval that falls on the date given, or
``None`` if the interval doesn't have any part during that date.
"""
return self.intersection(Interval.wholeday(date)) | python | def component_on_date(self, date: datetime.date) -> Optional["Interval"]:
"""
Returns the part of this interval that falls on the date given, or
``None`` if the interval doesn't have any part during that date.
"""
return self.intersection(Interval.wholeday(date)) | [
"def",
"component_on_date",
"(",
"self",
",",
"date",
":",
"datetime",
".",
"date",
")",
"->",
"Optional",
"[",
"\"Interval\"",
"]",
":",
"return",
"self",
".",
"intersection",
"(",
"Interval",
".",
"wholeday",
"(",
"date",
")",
")"
] | Returns the part of this interval that falls on the date given, or
``None`` if the interval doesn't have any part during that date. | [
"Returns",
"the",
"part",
"of",
"this",
"interval",
"that",
"falls",
"on",
"the",
"date",
"given",
"or",
"None",
"if",
"the",
"interval",
"doesn",
"t",
"have",
"any",
"part",
"during",
"that",
"date",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L433-L438 | train | 52,854 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | Interval.n_weekends | def n_weekends(self) -> int:
"""
Returns the number of weekends that this interval covers. Includes
partial weekends.
"""
startdate = self.start.date()
enddate = self.end.date()
ndays = (enddate - startdate).days + 1
in_weekend = False
n_weekends = 0
for i in range(ndays):
date = startdate + datetime.timedelta(days=i)
if not in_weekend and is_weekend(date):
in_weekend = True
n_weekends += 1
elif in_weekend and not is_weekend(date):
in_weekend = False
return n_weekends | python | def n_weekends(self) -> int:
"""
Returns the number of weekends that this interval covers. Includes
partial weekends.
"""
startdate = self.start.date()
enddate = self.end.date()
ndays = (enddate - startdate).days + 1
in_weekend = False
n_weekends = 0
for i in range(ndays):
date = startdate + datetime.timedelta(days=i)
if not in_weekend and is_weekend(date):
in_weekend = True
n_weekends += 1
elif in_weekend and not is_weekend(date):
in_weekend = False
return n_weekends | [
"def",
"n_weekends",
"(",
"self",
")",
"->",
"int",
":",
"startdate",
"=",
"self",
".",
"start",
".",
"date",
"(",
")",
"enddate",
"=",
"self",
".",
"end",
".",
"date",
"(",
")",
"ndays",
"=",
"(",
"enddate",
"-",
"startdate",
")",
".",
"days",
"... | Returns the number of weekends that this interval covers. Includes
partial weekends. | [
"Returns",
"the",
"number",
"of",
"weekends",
"that",
"this",
"interval",
"covers",
".",
"Includes",
"partial",
"weekends",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L509-L526 | train | 52,855 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.add | def add(self, interval: Interval) -> None:
"""
Adds an interval to the list. If ``self.no_overlap`` is True, as is the
default, it will merge any overlapping intervals thus created.
"""
if interval is None:
return
if not isinstance(interval, Interval):
raise TypeError(
"Attempt to insert non-Interval into IntervalList")
self.intervals.append(interval)
self._tidy() | python | def add(self, interval: Interval) -> None:
"""
Adds an interval to the list. If ``self.no_overlap`` is True, as is the
default, it will merge any overlapping intervals thus created.
"""
if interval is None:
return
if not isinstance(interval, Interval):
raise TypeError(
"Attempt to insert non-Interval into IntervalList")
self.intervals.append(interval)
self._tidy() | [
"def",
"add",
"(",
"self",
",",
"interval",
":",
"Interval",
")",
"->",
"None",
":",
"if",
"interval",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"interval",
",",
"Interval",
")",
":",
"raise",
"TypeError",
"(",
"\"Attempt to insert non-I... | Adds an interval to the list. If ``self.no_overlap`` is True, as is the
default, it will merge any overlapping intervals thus created. | [
"Adds",
"an",
"interval",
"to",
"the",
"list",
".",
"If",
"self",
".",
"no_overlap",
"is",
"True",
"as",
"is",
"the",
"default",
"it",
"will",
"merge",
"any",
"overlapping",
"intervals",
"thus",
"created",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L634-L645 | train | 52,856 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList._tidy | def _tidy(self) -> None:
"""
Removes overlaps, etc., and sorts.
"""
if self.no_overlap:
self.remove_overlap(self.no_contiguous) # will sort
else:
self._sort() | python | def _tidy(self) -> None:
"""
Removes overlaps, etc., and sorts.
"""
if self.no_overlap:
self.remove_overlap(self.no_contiguous) # will sort
else:
self._sort() | [
"def",
"_tidy",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"no_overlap",
":",
"self",
".",
"remove_overlap",
"(",
"self",
".",
"no_contiguous",
")",
"# will sort",
"else",
":",
"self",
".",
"_sort",
"(",
")"
] | Removes overlaps, etc., and sorts. | [
"Removes",
"overlaps",
"etc",
".",
"and",
"sorts",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L651-L658 | train | 52,857 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.remove_overlap | def remove_overlap(self, also_remove_contiguous: bool = False) -> None:
"""
Merges any overlapping intervals.
Args:
also_remove_contiguous: treat contiguous (as well as overlapping)
intervals as worthy of merging?
"""
overlap = True
while overlap:
overlap = self._remove_overlap_sub(also_remove_contiguous)
self._sort() | python | def remove_overlap(self, also_remove_contiguous: bool = False) -> None:
"""
Merges any overlapping intervals.
Args:
also_remove_contiguous: treat contiguous (as well as overlapping)
intervals as worthy of merging?
"""
overlap = True
while overlap:
overlap = self._remove_overlap_sub(also_remove_contiguous)
self._sort() | [
"def",
"remove_overlap",
"(",
"self",
",",
"also_remove_contiguous",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"overlap",
"=",
"True",
"while",
"overlap",
":",
"overlap",
"=",
"self",
".",
"_remove_overlap_sub",
"(",
"also_remove_contiguous",
")",
"se... | Merges any overlapping intervals.
Args:
also_remove_contiguous: treat contiguous (as well as overlapping)
intervals as worthy of merging? | [
"Merges",
"any",
"overlapping",
"intervals",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L695-L706 | train | 52,858 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList._any_overlap_or_contiguous | def _any_overlap_or_contiguous(self, test_overlap: bool) -> bool:
"""
Do any of the intervals overlap?
Args:
test_overlap: if ``True``, test for overlapping intervals; if
``False``, test for contiguous intervals.
"""
for i in range(len(self.intervals)):
for j in range(i + 1, len(self.intervals)):
first = self.intervals[i]
second = self.intervals[j]
if test_overlap:
test = first.overlaps(second)
else:
test = first.contiguous(second)
if test:
return True
return False | python | def _any_overlap_or_contiguous(self, test_overlap: bool) -> bool:
"""
Do any of the intervals overlap?
Args:
test_overlap: if ``True``, test for overlapping intervals; if
``False``, test for contiguous intervals.
"""
for i in range(len(self.intervals)):
for j in range(i + 1, len(self.intervals)):
first = self.intervals[i]
second = self.intervals[j]
if test_overlap:
test = first.overlaps(second)
else:
test = first.contiguous(second)
if test:
return True
return False | [
"def",
"_any_overlap_or_contiguous",
"(",
"self",
",",
"test_overlap",
":",
"bool",
")",
"->",
"bool",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"intervals",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"le... | Do any of the intervals overlap?
Args:
test_overlap: if ``True``, test for overlapping intervals; if
``False``, test for contiguous intervals. | [
"Do",
"any",
"of",
"the",
"intervals",
"overlap?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L708-L726 | train | 52,859 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.total_duration | def total_duration(self) -> datetime.timedelta:
"""
Returns a ``datetime.timedelta`` object with the total sum of
durations. If there is overlap, time will be double-counted, so beware!
"""
total = datetime.timedelta()
for interval in self.intervals:
total += interval.duration()
return total | python | def total_duration(self) -> datetime.timedelta:
"""
Returns a ``datetime.timedelta`` object with the total sum of
durations. If there is overlap, time will be double-counted, so beware!
"""
total = datetime.timedelta()
for interval in self.intervals:
total += interval.duration()
return total | [
"def",
"total_duration",
"(",
"self",
")",
"->",
"datetime",
".",
"timedelta",
":",
"total",
"=",
"datetime",
".",
"timedelta",
"(",
")",
"for",
"interval",
"in",
"self",
".",
"intervals",
":",
"total",
"+=",
"interval",
".",
"duration",
"(",
")",
"retur... | Returns a ``datetime.timedelta`` object with the total sum of
durations. If there is overlap, time will be double-counted, so beware! | [
"Returns",
"a",
"datetime",
".",
"timedelta",
"object",
"with",
"the",
"total",
"sum",
"of",
"durations",
".",
"If",
"there",
"is",
"overlap",
"time",
"will",
"be",
"double",
"-",
"counted",
"so",
"beware!"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L797-L805 | train | 52,860 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.durations | def durations(self) -> List[datetime.timedelta]:
"""
Returns a list of ``datetime.timedelta`` objects representing the
durations of each interval in our list.
"""
return [x.duration() for x in self.intervals] | python | def durations(self) -> List[datetime.timedelta]:
"""
Returns a list of ``datetime.timedelta`` objects representing the
durations of each interval in our list.
"""
return [x.duration() for x in self.intervals] | [
"def",
"durations",
"(",
"self",
")",
"->",
"List",
"[",
"datetime",
".",
"timedelta",
"]",
":",
"return",
"[",
"x",
".",
"duration",
"(",
")",
"for",
"x",
"in",
"self",
".",
"intervals",
"]"
] | Returns a list of ``datetime.timedelta`` objects representing the
durations of each interval in our list. | [
"Returns",
"a",
"list",
"of",
"datetime",
".",
"timedelta",
"objects",
"representing",
"the",
"durations",
"of",
"each",
"interval",
"in",
"our",
"list",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L826-L831 | train | 52,861 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.longest_duration | def longest_duration(self) -> Optional[datetime.timedelta]:
"""
Returns the duration of the longest interval, or None if none.
"""
if not self.intervals:
return None
return max(self.durations()) | python | def longest_duration(self) -> Optional[datetime.timedelta]:
"""
Returns the duration of the longest interval, or None if none.
"""
if not self.intervals:
return None
return max(self.durations()) | [
"def",
"longest_duration",
"(",
"self",
")",
"->",
"Optional",
"[",
"datetime",
".",
"timedelta",
"]",
":",
"if",
"not",
"self",
".",
"intervals",
":",
"return",
"None",
"return",
"max",
"(",
"self",
".",
"durations",
"(",
")",
")"
] | Returns the duration of the longest interval, or None if none. | [
"Returns",
"the",
"duration",
"of",
"the",
"longest",
"interval",
"or",
"None",
"if",
"none",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L833-L839 | train | 52,862 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.longest_interval | def longest_interval(self) -> Optional[Interval]:
"""
Returns the longest interval, or ``None`` if none.
"""
longest_duration = self.longest_duration()
for i in self.intervals:
if i.duration() == longest_duration:
return i
return None | python | def longest_interval(self) -> Optional[Interval]:
"""
Returns the longest interval, or ``None`` if none.
"""
longest_duration = self.longest_duration()
for i in self.intervals:
if i.duration() == longest_duration:
return i
return None | [
"def",
"longest_interval",
"(",
"self",
")",
"->",
"Optional",
"[",
"Interval",
"]",
":",
"longest_duration",
"=",
"self",
".",
"longest_duration",
"(",
")",
"for",
"i",
"in",
"self",
".",
"intervals",
":",
"if",
"i",
".",
"duration",
"(",
")",
"==",
"... | Returns the longest interval, or ``None`` if none. | [
"Returns",
"the",
"longest",
"interval",
"or",
"None",
"if",
"none",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L841-L849 | train | 52,863 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.first_interval_starting | def first_interval_starting(self, start: datetime.datetime) -> \
Optional[Interval]:
"""
Returns our first interval that starts with the ``start`` parameter, or
``None``.
"""
for i in self.intervals:
if i.start == start:
return i
return None | python | def first_interval_starting(self, start: datetime.datetime) -> \
Optional[Interval]:
"""
Returns our first interval that starts with the ``start`` parameter, or
``None``.
"""
for i in self.intervals:
if i.start == start:
return i
return None | [
"def",
"first_interval_starting",
"(",
"self",
",",
"start",
":",
"datetime",
".",
"datetime",
")",
"->",
"Optional",
"[",
"Interval",
"]",
":",
"for",
"i",
"in",
"self",
".",
"intervals",
":",
"if",
"i",
".",
"start",
"==",
"start",
":",
"return",
"i"... | Returns our first interval that starts with the ``start`` parameter, or
``None``. | [
"Returns",
"our",
"first",
"interval",
"that",
"starts",
"with",
"the",
"start",
"parameter",
"or",
"None",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L869-L878 | train | 52,864 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.first_interval_ending | def first_interval_ending(self, end: datetime.datetime) \
-> Optional[Interval]:
"""
Returns our first interval that ends with the ``end`` parameter, or
``None``.
"""
for i in self.intervals:
if i.end == end:
return i
return None | python | def first_interval_ending(self, end: datetime.datetime) \
-> Optional[Interval]:
"""
Returns our first interval that ends with the ``end`` parameter, or
``None``.
"""
for i in self.intervals:
if i.end == end:
return i
return None | [
"def",
"first_interval_ending",
"(",
"self",
",",
"end",
":",
"datetime",
".",
"datetime",
")",
"->",
"Optional",
"[",
"Interval",
"]",
":",
"for",
"i",
"in",
"self",
".",
"intervals",
":",
"if",
"i",
".",
"end",
"==",
"end",
":",
"return",
"i",
"ret... | Returns our first interval that ends with the ``end`` parameter, or
``None``. | [
"Returns",
"our",
"first",
"interval",
"that",
"ends",
"with",
"the",
"end",
"parameter",
"or",
"None",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L880-L889 | train | 52,865 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.subset | def subset(self, interval: Interval,
flexibility: int = 2) -> "IntervalList":
"""
Returns an IntervalList that's a subset of this one, only containing
intervals that meet the "interval" parameter criterion. What "meet"
means is defined by the ``flexibility`` parameter.
``flexibility == 0``: permits only wholly contained intervals:
.. code-block:: none
interval:
I----------------I
intervals in self that will/won't be returned:
N---N N---N Y---Y N---N N---N
N---N N---N
``flexibility == 1``: permits overlapping intervals as well:
.. code-block:: none
I----------------I
N---N Y---Y Y---Y Y---Y N---N
N---N N---N
``flexibility == 2``: permits adjoining intervals as well:
.. code-block:: none
I----------------I
N---N Y---Y Y---Y Y---Y N---N
Y---Y Y---Y
"""
if flexibility not in [0, 1, 2]:
raise ValueError("subset: bad flexibility value")
permitted = []
for i in self.intervals:
if flexibility == 0:
ok = i.start > interval.start and i.end < interval.end
elif flexibility == 1:
ok = i.end > interval.start and i.start < interval.end
else:
ok = i.end >= interval.start and i.start <= interval.end
if ok:
permitted.append(i)
return IntervalList(permitted) | python | def subset(self, interval: Interval,
flexibility: int = 2) -> "IntervalList":
"""
Returns an IntervalList that's a subset of this one, only containing
intervals that meet the "interval" parameter criterion. What "meet"
means is defined by the ``flexibility`` parameter.
``flexibility == 0``: permits only wholly contained intervals:
.. code-block:: none
interval:
I----------------I
intervals in self that will/won't be returned:
N---N N---N Y---Y N---N N---N
N---N N---N
``flexibility == 1``: permits overlapping intervals as well:
.. code-block:: none
I----------------I
N---N Y---Y Y---Y Y---Y N---N
N---N N---N
``flexibility == 2``: permits adjoining intervals as well:
.. code-block:: none
I----------------I
N---N Y---Y Y---Y Y---Y N---N
Y---Y Y---Y
"""
if flexibility not in [0, 1, 2]:
raise ValueError("subset: bad flexibility value")
permitted = []
for i in self.intervals:
if flexibility == 0:
ok = i.start > interval.start and i.end < interval.end
elif flexibility == 1:
ok = i.end > interval.start and i.start < interval.end
else:
ok = i.end >= interval.start and i.start <= interval.end
if ok:
permitted.append(i)
return IntervalList(permitted) | [
"def",
"subset",
"(",
"self",
",",
"interval",
":",
"Interval",
",",
"flexibility",
":",
"int",
"=",
"2",
")",
"->",
"\"IntervalList\"",
":",
"if",
"flexibility",
"not",
"in",
"[",
"0",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"\"sub... | Returns an IntervalList that's a subset of this one, only containing
intervals that meet the "interval" parameter criterion. What "meet"
means is defined by the ``flexibility`` parameter.
``flexibility == 0``: permits only wholly contained intervals:
.. code-block:: none
interval:
I----------------I
intervals in self that will/won't be returned:
N---N N---N Y---Y N---N N---N
N---N N---N
``flexibility == 1``: permits overlapping intervals as well:
.. code-block:: none
I----------------I
N---N Y---Y Y---Y Y---Y N---N
N---N N---N
``flexibility == 2``: permits adjoining intervals as well:
.. code-block:: none
I----------------I
N---N Y---Y Y---Y Y---Y N---N
Y---Y Y---Y | [
"Returns",
"an",
"IntervalList",
"that",
"s",
"a",
"subset",
"of",
"this",
"one",
"only",
"containing",
"intervals",
"that",
"meet",
"the",
"interval",
"parameter",
"criterion",
".",
"What",
"meet",
"means",
"is",
"defined",
"by",
"the",
"flexibility",
"parame... | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L925-L974 | train | 52,866 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.max_consecutive_days | def max_consecutive_days(self) -> Optional[Tuple[int, Interval]]:
"""
The length of the longest sequence of days in which all days include
an interval.
Returns:
tuple:
``(longest_length, longest_interval)`` where
``longest_interval`` is a :class:`Interval` containing the
start and end date of the longest span -- or ``None`` if we
contain no intervals.
"""
if len(self.intervals) == 0:
return None
startdate = self.start_date()
enddate = self.end_date()
seq = ''
ndays = (enddate - startdate).days + 1
for i in range(ndays):
date = startdate + datetime.timedelta(days=i)
wholeday = Interval.wholeday(date)
if any([x.overlaps(wholeday) for x in self.intervals]):
seq += '+'
else:
seq += ' '
# noinspection PyTypeChecker
longest = max(seq.split(), key=len)
longest_len = len(longest)
longest_idx = seq.index(longest)
longest_interval = Interval.dayspan(
startdate + datetime.timedelta(days=longest_idx),
startdate + datetime.timedelta(days=longest_idx + longest_len)
)
return longest_len, longest_interval | python | def max_consecutive_days(self) -> Optional[Tuple[int, Interval]]:
"""
The length of the longest sequence of days in which all days include
an interval.
Returns:
tuple:
``(longest_length, longest_interval)`` where
``longest_interval`` is a :class:`Interval` containing the
start and end date of the longest span -- or ``None`` if we
contain no intervals.
"""
if len(self.intervals) == 0:
return None
startdate = self.start_date()
enddate = self.end_date()
seq = ''
ndays = (enddate - startdate).days + 1
for i in range(ndays):
date = startdate + datetime.timedelta(days=i)
wholeday = Interval.wholeday(date)
if any([x.overlaps(wholeday) for x in self.intervals]):
seq += '+'
else:
seq += ' '
# noinspection PyTypeChecker
longest = max(seq.split(), key=len)
longest_len = len(longest)
longest_idx = seq.index(longest)
longest_interval = Interval.dayspan(
startdate + datetime.timedelta(days=longest_idx),
startdate + datetime.timedelta(days=longest_idx + longest_len)
)
return longest_len, longest_interval | [
"def",
"max_consecutive_days",
"(",
"self",
")",
"->",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"Interval",
"]",
"]",
":",
"if",
"len",
"(",
"self",
".",
"intervals",
")",
"==",
"0",
":",
"return",
"None",
"startdate",
"=",
"self",
".",
"start_date",... | The length of the longest sequence of days in which all days include
an interval.
Returns:
tuple:
``(longest_length, longest_interval)`` where
``longest_interval`` is a :class:`Interval` containing the
start and end date of the longest span -- or ``None`` if we
contain no intervals. | [
"The",
"length",
"of",
"the",
"longest",
"sequence",
"of",
"days",
"in",
"which",
"all",
"days",
"include",
"an",
"interval",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1015-L1048 | train | 52,867 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.cumulative_time_to | def cumulative_time_to(self,
when: datetime.datetime) -> datetime.timedelta:
"""
Returns the cumulative time contained in our intervals up to the
specified time point.
"""
assert self.no_overlap, self._ONLY_FOR_NO_INTERVAL
cumulative = datetime.timedelta()
for interval in self.intervals:
if interval.start >= when:
break
elif interval.end <= when:
# complete interval precedes "when"
cumulative += interval.duration()
else: # start < when < end
cumulative += when - interval.start
return cumulative | python | def cumulative_time_to(self,
when: datetime.datetime) -> datetime.timedelta:
"""
Returns the cumulative time contained in our intervals up to the
specified time point.
"""
assert self.no_overlap, self._ONLY_FOR_NO_INTERVAL
cumulative = datetime.timedelta()
for interval in self.intervals:
if interval.start >= when:
break
elif interval.end <= when:
# complete interval precedes "when"
cumulative += interval.duration()
else: # start < when < end
cumulative += when - interval.start
return cumulative | [
"def",
"cumulative_time_to",
"(",
"self",
",",
"when",
":",
"datetime",
".",
"datetime",
")",
"->",
"datetime",
".",
"timedelta",
":",
"assert",
"self",
".",
"no_overlap",
",",
"self",
".",
"_ONLY_FOR_NO_INTERVAL",
"cumulative",
"=",
"datetime",
".",
"timedelt... | Returns the cumulative time contained in our intervals up to the
specified time point. | [
"Returns",
"the",
"cumulative",
"time",
"contained",
"in",
"our",
"intervals",
"up",
"to",
"the",
"specified",
"time",
"point",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1136-L1152 | train | 52,868 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.cumulative_gaps_to | def cumulative_gaps_to(self,
when: datetime.datetime) -> datetime.timedelta:
"""
Return the cumulative time within our gaps, up to ``when``.
"""
gaps = self.gaps()
return gaps.cumulative_time_to(when) | python | def cumulative_gaps_to(self,
when: datetime.datetime) -> datetime.timedelta:
"""
Return the cumulative time within our gaps, up to ``when``.
"""
gaps = self.gaps()
return gaps.cumulative_time_to(when) | [
"def",
"cumulative_gaps_to",
"(",
"self",
",",
"when",
":",
"datetime",
".",
"datetime",
")",
"->",
"datetime",
".",
"timedelta",
":",
"gaps",
"=",
"self",
".",
"gaps",
"(",
")",
"return",
"gaps",
".",
"cumulative_time_to",
"(",
"when",
")"
] | Return the cumulative time within our gaps, up to ``when``. | [
"Return",
"the",
"cumulative",
"time",
"within",
"our",
"gaps",
"up",
"to",
"when",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1154-L1160 | train | 52,869 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | IntervalList.time_afterwards_preceding | def time_afterwards_preceding(
self, when: datetime.datetime) -> Optional[datetime.timedelta]:
"""
Returns the time after our last interval, but before ``when``.
If ``self`` is an empty list, returns ``None``.
"""
if self.is_empty():
return None
end_time = self.end_datetime()
if when <= end_time:
return datetime.timedelta()
else:
return when - end_time | python | def time_afterwards_preceding(
self, when: datetime.datetime) -> Optional[datetime.timedelta]:
"""
Returns the time after our last interval, but before ``when``.
If ``self`` is an empty list, returns ``None``.
"""
if self.is_empty():
return None
end_time = self.end_datetime()
if when <= end_time:
return datetime.timedelta()
else:
return when - end_time | [
"def",
"time_afterwards_preceding",
"(",
"self",
",",
"when",
":",
"datetime",
".",
"datetime",
")",
"->",
"Optional",
"[",
"datetime",
".",
"timedelta",
"]",
":",
"if",
"self",
".",
"is_empty",
"(",
")",
":",
"return",
"None",
"end_time",
"=",
"self",
"... | Returns the time after our last interval, but before ``when``.
If ``self`` is an empty list, returns ``None``. | [
"Returns",
"the",
"time",
"after",
"our",
"last",
"interval",
"but",
"before",
"when",
".",
"If",
"self",
"is",
"an",
"empty",
"list",
"returns",
"None",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1162-L1174 | train | 52,870 |
RudolfCardinal/pythonlib | cardinal_pythonlib/dogpile_cache.py | repr_parameter | def repr_parameter(param: inspect.Parameter) -> str:
"""
Provides a ``repr``-style representation of a function parameter.
"""
return (
"Parameter(name={name}, annotation={annotation}, kind={kind}, "
"default={default}".format(
name=param.name, annotation=param.annotation, kind=param.kind,
default=param.default)
) | python | def repr_parameter(param: inspect.Parameter) -> str:
"""
Provides a ``repr``-style representation of a function parameter.
"""
return (
"Parameter(name={name}, annotation={annotation}, kind={kind}, "
"default={default}".format(
name=param.name, annotation=param.annotation, kind=param.kind,
default=param.default)
) | [
"def",
"repr_parameter",
"(",
"param",
":",
"inspect",
".",
"Parameter",
")",
"->",
"str",
":",
"return",
"(",
"\"Parameter(name={name}, annotation={annotation}, kind={kind}, \"",
"\"default={default}\"",
".",
"format",
"(",
"name",
"=",
"param",
".",
"name",
",",
"... | Provides a ``repr``-style representation of a function parameter. | [
"Provides",
"a",
"repr",
"-",
"style",
"representation",
"of",
"a",
"function",
"parameter",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dogpile_cache.py#L109-L118 | train | 52,871 |
Autodesk/cryptorito | cryptorito/__init__.py | gpg_version | def gpg_version():
"""Returns the GPG version"""
cmd = flatten([gnupg_bin(), "--version"])
output = stderr_output(cmd)
output = output \
.split('\n')[0] \
.split(" ")[2] \
.split('.')
return tuple([int(x) for x in output]) | python | def gpg_version():
"""Returns the GPG version"""
cmd = flatten([gnupg_bin(), "--version"])
output = stderr_output(cmd)
output = output \
.split('\n')[0] \
.split(" ")[2] \
.split('.')
return tuple([int(x) for x in output]) | [
"def",
"gpg_version",
"(",
")",
":",
"cmd",
"=",
"flatten",
"(",
"[",
"gnupg_bin",
"(",
")",
",",
"\"--version\"",
"]",
")",
"output",
"=",
"stderr_output",
"(",
"cmd",
")",
"output",
"=",
"output",
".",
"split",
"(",
"'\\n'",
")",
"[",
"0",
"]",
"... | Returns the GPG version | [
"Returns",
"the",
"GPG",
"version"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L51-L59 | train | 52,872 |
Autodesk/cryptorito | cryptorito/__init__.py | passphrase_file | def passphrase_file(passphrase=None):
"""Read passphrase from a file. This should only ever be
used by our built in integration tests. At this time,
during normal operation, only pinentry is supported for
entry of passwords."""
cmd = []
pass_file = None
if not passphrase and 'CRYPTORITO_PASSPHRASE_FILE' in os.environ:
pass_file = os.environ['CRYPTORITO_PASSPHRASE_FILE']
if not os.path.isfile(pass_file):
raise CryptoritoError('CRYPTORITO_PASSPHRASE_FILE is invalid')
elif passphrase:
tmpdir = ensure_tmpdir()
pass_file = "%s/p_pass" % tmpdir
p_handle = open(pass_file, 'w')
p_handle.write(passphrase)
p_handle.close()
if pass_file:
cmd = cmd + ["--batch", "--passphrase-file", pass_file]
vsn = gpg_version()
if vsn[0] >= 2 and vsn[1] >= 1:
cmd = cmd + ["--pinentry-mode", "loopback"]
return cmd | python | def passphrase_file(passphrase=None):
"""Read passphrase from a file. This should only ever be
used by our built in integration tests. At this time,
during normal operation, only pinentry is supported for
entry of passwords."""
cmd = []
pass_file = None
if not passphrase and 'CRYPTORITO_PASSPHRASE_FILE' in os.environ:
pass_file = os.environ['CRYPTORITO_PASSPHRASE_FILE']
if not os.path.isfile(pass_file):
raise CryptoritoError('CRYPTORITO_PASSPHRASE_FILE is invalid')
elif passphrase:
tmpdir = ensure_tmpdir()
pass_file = "%s/p_pass" % tmpdir
p_handle = open(pass_file, 'w')
p_handle.write(passphrase)
p_handle.close()
if pass_file:
cmd = cmd + ["--batch", "--passphrase-file", pass_file]
vsn = gpg_version()
if vsn[0] >= 2 and vsn[1] >= 1:
cmd = cmd + ["--pinentry-mode", "loopback"]
return cmd | [
"def",
"passphrase_file",
"(",
"passphrase",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"]",
"pass_file",
"=",
"None",
"if",
"not",
"passphrase",
"and",
"'CRYPTORITO_PASSPHRASE_FILE'",
"in",
"os",
".",
"environ",
":",
"pass_file",
"=",
"os",
".",
"environ",
"... | Read passphrase from a file. This should only ever be
used by our built in integration tests. At this time,
during normal operation, only pinentry is supported for
entry of passwords. | [
"Read",
"passphrase",
"from",
"a",
"file",
".",
"This",
"should",
"only",
"ever",
"be",
"used",
"by",
"our",
"built",
"in",
"integration",
"tests",
".",
"At",
"this",
"time",
"during",
"normal",
"operation",
"only",
"pinentry",
"is",
"supported",
"for",
"e... | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L131-L156 | train | 52,873 |
Autodesk/cryptorito | cryptorito/__init__.py | gnupg_home | def gnupg_home():
"""Returns appropriate arguments if GNUPGHOME is set"""
if 'GNUPGHOME' in os.environ:
gnupghome = os.environ['GNUPGHOME']
if not os.path.isdir(gnupghome):
raise CryptoritoError("Invalid GNUPGHOME directory")
return ["--homedir", gnupghome]
else:
return [] | python | def gnupg_home():
"""Returns appropriate arguments if GNUPGHOME is set"""
if 'GNUPGHOME' in os.environ:
gnupghome = os.environ['GNUPGHOME']
if not os.path.isdir(gnupghome):
raise CryptoritoError("Invalid GNUPGHOME directory")
return ["--homedir", gnupghome]
else:
return [] | [
"def",
"gnupg_home",
"(",
")",
":",
"if",
"'GNUPGHOME'",
"in",
"os",
".",
"environ",
":",
"gnupghome",
"=",
"os",
".",
"environ",
"[",
"'GNUPGHOME'",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"gnupghome",
")",
":",
"raise",
"CryptoritoErr... | Returns appropriate arguments if GNUPGHOME is set | [
"Returns",
"appropriate",
"arguments",
"if",
"GNUPGHOME",
"is",
"set"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L159-L168 | train | 52,874 |
Autodesk/cryptorito | cryptorito/__init__.py | fingerprint_from_keybase | def fingerprint_from_keybase(fingerprint, kb_obj):
"""Extracts a key matching a specific fingerprint from a
Keybase API response"""
if 'public_keys' in kb_obj and \
'pgp_public_keys' in kb_obj['public_keys']:
for key in kb_obj['public_keys']['pgp_public_keys']:
keyprint = fingerprint_from_var(key).lower()
fingerprint = fingerprint.lower()
if fingerprint == keyprint or \
keyprint.startswith(fingerprint) or \
keyprint.endswith(fingerprint):
return {
'fingerprint': keyprint,
'bundle': key
}
return None | python | def fingerprint_from_keybase(fingerprint, kb_obj):
"""Extracts a key matching a specific fingerprint from a
Keybase API response"""
if 'public_keys' in kb_obj and \
'pgp_public_keys' in kb_obj['public_keys']:
for key in kb_obj['public_keys']['pgp_public_keys']:
keyprint = fingerprint_from_var(key).lower()
fingerprint = fingerprint.lower()
if fingerprint == keyprint or \
keyprint.startswith(fingerprint) or \
keyprint.endswith(fingerprint):
return {
'fingerprint': keyprint,
'bundle': key
}
return None | [
"def",
"fingerprint_from_keybase",
"(",
"fingerprint",
",",
"kb_obj",
")",
":",
"if",
"'public_keys'",
"in",
"kb_obj",
"and",
"'pgp_public_keys'",
"in",
"kb_obj",
"[",
"'public_keys'",
"]",
":",
"for",
"key",
"in",
"kb_obj",
"[",
"'public_keys'",
"]",
"[",
"'p... | Extracts a key matching a specific fingerprint from a
Keybase API response | [
"Extracts",
"a",
"key",
"matching",
"a",
"specific",
"fingerprint",
"from",
"a",
"Keybase",
"API",
"response"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L214-L230 | train | 52,875 |
Autodesk/cryptorito | cryptorito/__init__.py | key_from_keybase | def key_from_keybase(username, fingerprint=None):
"""Look up a public key from a username"""
url = keybase_lookup_url(username)
resp = requests.get(url)
if resp.status_code == 200:
j_resp = json.loads(polite_string(resp.content))
if 'them' in j_resp and len(j_resp['them']) == 1:
kb_obj = j_resp['them'][0]
if fingerprint:
return fingerprint_from_keybase(fingerprint, kb_obj)
else:
if 'public_keys' in kb_obj \
and 'pgp_public_keys' in kb_obj['public_keys']:
key = kb_obj['public_keys']['primary']
return massage_key(key)
return None | python | def key_from_keybase(username, fingerprint=None):
"""Look up a public key from a username"""
url = keybase_lookup_url(username)
resp = requests.get(url)
if resp.status_code == 200:
j_resp = json.loads(polite_string(resp.content))
if 'them' in j_resp and len(j_resp['them']) == 1:
kb_obj = j_resp['them'][0]
if fingerprint:
return fingerprint_from_keybase(fingerprint, kb_obj)
else:
if 'public_keys' in kb_obj \
and 'pgp_public_keys' in kb_obj['public_keys']:
key = kb_obj['public_keys']['primary']
return massage_key(key)
return None | [
"def",
"key_from_keybase",
"(",
"username",
",",
"fingerprint",
"=",
"None",
")",
":",
"url",
"=",
"keybase_lookup_url",
"(",
"username",
")",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"j_re... | Look up a public key from a username | [
"Look",
"up",
"a",
"public",
"key",
"from",
"a",
"username"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L233-L249 | train | 52,876 |
Autodesk/cryptorito | cryptorito/__init__.py | has_gpg_key | def has_gpg_key(fingerprint):
"""Checks to see if we have this gpg fingerprint"""
if len(fingerprint) > 8:
fingerprint = fingerprint[-8:]
fingerprint = fingerprint.upper()
cmd = flatten([gnupg_bin(), gnupg_home(), "--list-public-keys"])
lines = stderr_output(cmd).split('\n')
return len([key for key in lines if key.find(fingerprint) > -1]) == 1 | python | def has_gpg_key(fingerprint):
"""Checks to see if we have this gpg fingerprint"""
if len(fingerprint) > 8:
fingerprint = fingerprint[-8:]
fingerprint = fingerprint.upper()
cmd = flatten([gnupg_bin(), gnupg_home(), "--list-public-keys"])
lines = stderr_output(cmd).split('\n')
return len([key for key in lines if key.find(fingerprint) > -1]) == 1 | [
"def",
"has_gpg_key",
"(",
"fingerprint",
")",
":",
"if",
"len",
"(",
"fingerprint",
")",
">",
"8",
":",
"fingerprint",
"=",
"fingerprint",
"[",
"-",
"8",
":",
"]",
"fingerprint",
"=",
"fingerprint",
".",
"upper",
"(",
")",
"cmd",
"=",
"flatten",
"(",
... | Checks to see if we have this gpg fingerprint | [
"Checks",
"to",
"see",
"if",
"we",
"have",
"this",
"gpg",
"fingerprint"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L252-L260 | train | 52,877 |
Autodesk/cryptorito | cryptorito/__init__.py | fingerprint_from_var | def fingerprint_from_var(var):
"""Extract a fingerprint from a GPG public key"""
vsn = gpg_version()
cmd = flatten([gnupg_bin(), gnupg_home()])
if vsn[0] >= 2 and vsn[1] < 1:
cmd.append("--with-fingerprint")
output = polite_string(stderr_with_input(cmd, var)).split('\n')
if not output[0].startswith('pub'):
raise CryptoritoError('probably an invalid gpg key')
if vsn[0] >= 2 and vsn[1] < 1:
return output[1] \
.split('=')[1] \
.replace(' ', '')
return output[1].strip() | python | def fingerprint_from_var(var):
"""Extract a fingerprint from a GPG public key"""
vsn = gpg_version()
cmd = flatten([gnupg_bin(), gnupg_home()])
if vsn[0] >= 2 and vsn[1] < 1:
cmd.append("--with-fingerprint")
output = polite_string(stderr_with_input(cmd, var)).split('\n')
if not output[0].startswith('pub'):
raise CryptoritoError('probably an invalid gpg key')
if vsn[0] >= 2 and vsn[1] < 1:
return output[1] \
.split('=')[1] \
.replace(' ', '')
return output[1].strip() | [
"def",
"fingerprint_from_var",
"(",
"var",
")",
":",
"vsn",
"=",
"gpg_version",
"(",
")",
"cmd",
"=",
"flatten",
"(",
"[",
"gnupg_bin",
"(",
")",
",",
"gnupg_home",
"(",
")",
"]",
")",
"if",
"vsn",
"[",
"0",
"]",
">=",
"2",
"and",
"vsn",
"[",
"1"... | Extract a fingerprint from a GPG public key | [
"Extract",
"a",
"fingerprint",
"from",
"a",
"GPG",
"public",
"key"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L263-L279 | train | 52,878 |
Autodesk/cryptorito | cryptorito/__init__.py | fingerprint_from_file | def fingerprint_from_file(filename):
"""Extract a fingerprint from a GPG public key file"""
cmd = flatten([gnupg_bin(), gnupg_home(), filename])
outp = stderr_output(cmd).split('\n')
if not outp[0].startswith('pub'):
raise CryptoritoError('probably an invalid gpg key')
return outp[1].strip() | python | def fingerprint_from_file(filename):
"""Extract a fingerprint from a GPG public key file"""
cmd = flatten([gnupg_bin(), gnupg_home(), filename])
outp = stderr_output(cmd).split('\n')
if not outp[0].startswith('pub'):
raise CryptoritoError('probably an invalid gpg key')
return outp[1].strip() | [
"def",
"fingerprint_from_file",
"(",
"filename",
")",
":",
"cmd",
"=",
"flatten",
"(",
"[",
"gnupg_bin",
"(",
")",
",",
"gnupg_home",
"(",
")",
",",
"filename",
"]",
")",
"outp",
"=",
"stderr_output",
"(",
"cmd",
")",
".",
"split",
"(",
"'\\n'",
")",
... | Extract a fingerprint from a GPG public key file | [
"Extract",
"a",
"fingerprint",
"from",
"a",
"GPG",
"public",
"key",
"file"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L282-L289 | train | 52,879 |
Autodesk/cryptorito | cryptorito/__init__.py | stderr_output | def stderr_output(cmd):
"""Wraps the execution of check_output in a way that
ignores stderr when not in debug mode"""
handle, gpg_stderr = stderr_handle()
try:
output = subprocess.check_output(cmd, stderr=gpg_stderr) # nosec
if handle:
handle.close()
return str(polite_string(output))
except subprocess.CalledProcessError as exception:
LOGGER.debug("GPG Command %s", ' '.join(exception.cmd))
LOGGER.debug("GPG Output %s", exception.output)
raise CryptoritoError('GPG Execution') | python | def stderr_output(cmd):
"""Wraps the execution of check_output in a way that
ignores stderr when not in debug mode"""
handle, gpg_stderr = stderr_handle()
try:
output = subprocess.check_output(cmd, stderr=gpg_stderr) # nosec
if handle:
handle.close()
return str(polite_string(output))
except subprocess.CalledProcessError as exception:
LOGGER.debug("GPG Command %s", ' '.join(exception.cmd))
LOGGER.debug("GPG Output %s", exception.output)
raise CryptoritoError('GPG Execution') | [
"def",
"stderr_output",
"(",
"cmd",
")",
":",
"handle",
",",
"gpg_stderr",
"=",
"stderr_handle",
"(",
")",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"gpg_stderr",
")",
"# nosec",
"if",
"handle",
":",
"h... | Wraps the execution of check_output in a way that
ignores stderr when not in debug mode | [
"Wraps",
"the",
"execution",
"of",
"check_output",
"in",
"a",
"way",
"that",
"ignores",
"stderr",
"when",
"not",
"in",
"debug",
"mode"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L305-L319 | train | 52,880 |
Autodesk/cryptorito | cryptorito/__init__.py | stderr_with_input | def stderr_with_input(cmd, stdin):
"""Runs a command, passing something in stdin, and returning
whatever came out from stdout"""
handle, gpg_stderr = stderr_handle()
LOGGER.debug("GPG command %s", ' '.join(cmd))
try:
gpg_proc = subprocess.Popen(cmd, # nosec
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=gpg_stderr)
output, _err = gpg_proc.communicate(polite_bytes(stdin))
if handle:
handle.close()
return output
except subprocess.CalledProcessError as exception:
return gpg_error(exception, 'GPG variable encryption error')
except OSError as exception:
raise CryptoritoError("File %s not found" % exception.filename) | python | def stderr_with_input(cmd, stdin):
"""Runs a command, passing something in stdin, and returning
whatever came out from stdout"""
handle, gpg_stderr = stderr_handle()
LOGGER.debug("GPG command %s", ' '.join(cmd))
try:
gpg_proc = subprocess.Popen(cmd, # nosec
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=gpg_stderr)
output, _err = gpg_proc.communicate(polite_bytes(stdin))
if handle:
handle.close()
return output
except subprocess.CalledProcessError as exception:
return gpg_error(exception, 'GPG variable encryption error')
except OSError as exception:
raise CryptoritoError("File %s not found" % exception.filename) | [
"def",
"stderr_with_input",
"(",
"cmd",
",",
"stdin",
")",
":",
"handle",
",",
"gpg_stderr",
"=",
"stderr_handle",
"(",
")",
"LOGGER",
".",
"debug",
"(",
"\"GPG command %s\"",
",",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"try",
":",
"gpg_proc",
"=",
... | Runs a command, passing something in stdin, and returning
whatever came out from stdout | [
"Runs",
"a",
"command",
"passing",
"something",
"in",
"stdin",
"and",
"returning",
"whatever",
"came",
"out",
"from",
"stdout"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L322-L342 | train | 52,881 |
Autodesk/cryptorito | cryptorito/__init__.py | import_gpg_key | def import_gpg_key(key):
"""Imports a GPG key"""
if not key:
raise CryptoritoError('Invalid GPG Key')
key_fd, key_filename = mkstemp("cryptorito-gpg-import")
key_handle = os.fdopen(key_fd, 'w')
key_handle.write(polite_string(key))
key_handle.close()
cmd = flatten([gnupg_bin(), gnupg_home(), "--import", key_filename])
output = stderr_output(cmd)
msg = 'gpg: Total number processed: 1'
output_bits = polite_string(output).split('\n')
return len([line for line in output_bits if line == msg]) == 1 | python | def import_gpg_key(key):
"""Imports a GPG key"""
if not key:
raise CryptoritoError('Invalid GPG Key')
key_fd, key_filename = mkstemp("cryptorito-gpg-import")
key_handle = os.fdopen(key_fd, 'w')
key_handle.write(polite_string(key))
key_handle.close()
cmd = flatten([gnupg_bin(), gnupg_home(), "--import", key_filename])
output = stderr_output(cmd)
msg = 'gpg: Total number processed: 1'
output_bits = polite_string(output).split('\n')
return len([line for line in output_bits if line == msg]) == 1 | [
"def",
"import_gpg_key",
"(",
"key",
")",
":",
"if",
"not",
"key",
":",
"raise",
"CryptoritoError",
"(",
"'Invalid GPG Key'",
")",
"key_fd",
",",
"key_filename",
"=",
"mkstemp",
"(",
"\"cryptorito-gpg-import\"",
")",
"key_handle",
"=",
"os",
".",
"fdopen",
"("... | Imports a GPG key | [
"Imports",
"a",
"GPG",
"key"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L345-L359 | train | 52,882 |
Autodesk/cryptorito | cryptorito/__init__.py | export_gpg_key | def export_gpg_key(key):
"""Exports a GPG key and returns it"""
cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(),
"--export", key])
handle, gpg_stderr = stderr_handle()
try:
gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, # nosec
stderr=gpg_stderr)
output, _err = gpg_proc.communicate()
if handle:
handle.close()
return portable_b64encode(output)
except subprocess.CalledProcessError as exception:
LOGGER.debug("GPG Command %s", ' '.join(exception.cmd))
LOGGER.debug("GPG Output %s", exception.output)
raise CryptoritoError('GPG encryption error') | python | def export_gpg_key(key):
"""Exports a GPG key and returns it"""
cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(),
"--export", key])
handle, gpg_stderr = stderr_handle()
try:
gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, # nosec
stderr=gpg_stderr)
output, _err = gpg_proc.communicate()
if handle:
handle.close()
return portable_b64encode(output)
except subprocess.CalledProcessError as exception:
LOGGER.debug("GPG Command %s", ' '.join(exception.cmd))
LOGGER.debug("GPG Output %s", exception.output)
raise CryptoritoError('GPG encryption error') | [
"def",
"export_gpg_key",
"(",
"key",
")",
":",
"cmd",
"=",
"flatten",
"(",
"[",
"gnupg_bin",
"(",
")",
",",
"gnupg_verbose",
"(",
")",
",",
"gnupg_home",
"(",
")",
",",
"\"--export\"",
",",
"key",
"]",
")",
"handle",
",",
"gpg_stderr",
"=",
"stderr_han... | Exports a GPG key and returns it | [
"Exports",
"a",
"GPG",
"key",
"and",
"returns",
"it"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L362-L378 | train | 52,883 |
Autodesk/cryptorito | cryptorito/__init__.py | encrypt | def encrypt(source, dest, keys):
"""Encrypts a file using the given keys"""
cmd = flatten([gnupg_bin(), "--armor", "--output", dest, gnupg_verbose(),
gnupg_home(), recipients_args(keys),
"--encrypt", source])
stderr_output(cmd)
return True | python | def encrypt(source, dest, keys):
"""Encrypts a file using the given keys"""
cmd = flatten([gnupg_bin(), "--armor", "--output", dest, gnupg_verbose(),
gnupg_home(), recipients_args(keys),
"--encrypt", source])
stderr_output(cmd)
return True | [
"def",
"encrypt",
"(",
"source",
",",
"dest",
",",
"keys",
")",
":",
"cmd",
"=",
"flatten",
"(",
"[",
"gnupg_bin",
"(",
")",
",",
"\"--armor\"",
",",
"\"--output\"",
",",
"dest",
",",
"gnupg_verbose",
"(",
")",
",",
"gnupg_home",
"(",
")",
",",
"reci... | Encrypts a file using the given keys | [
"Encrypts",
"a",
"file",
"using",
"the",
"given",
"keys"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L387-L394 | train | 52,884 |
Autodesk/cryptorito | cryptorito/__init__.py | encrypt_var | def encrypt_var(source, keys):
"""Attempts to encrypt a variable"""
cmd = flatten([gnupg_bin(), "--armor", "--encrypt", gnupg_verbose(),
recipients_args(keys)])
output = stderr_with_input(cmd, source)
return output | python | def encrypt_var(source, keys):
"""Attempts to encrypt a variable"""
cmd = flatten([gnupg_bin(), "--armor", "--encrypt", gnupg_verbose(),
recipients_args(keys)])
output = stderr_with_input(cmd, source)
return output | [
"def",
"encrypt_var",
"(",
"source",
",",
"keys",
")",
":",
"cmd",
"=",
"flatten",
"(",
"[",
"gnupg_bin",
"(",
")",
",",
"\"--armor\"",
",",
"\"--encrypt\"",
",",
"gnupg_verbose",
"(",
")",
",",
"recipients_args",
"(",
"keys",
")",
"]",
")",
"output",
... | Attempts to encrypt a variable | [
"Attempts",
"to",
"encrypt",
"a",
"variable"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L397-L402 | train | 52,885 |
Autodesk/cryptorito | cryptorito/__init__.py | gpg_error | def gpg_error(exception, message):
"""Handles the output of subprocess errors
in a way that is compatible with the log level"""
LOGGER.debug("GPG Command %s", ' '.join([str(x) for x in exception.cmd]))
LOGGER.debug("GPG Output %s", exception.output)
raise CryptoritoError(message) | python | def gpg_error(exception, message):
"""Handles the output of subprocess errors
in a way that is compatible with the log level"""
LOGGER.debug("GPG Command %s", ' '.join([str(x) for x in exception.cmd]))
LOGGER.debug("GPG Output %s", exception.output)
raise CryptoritoError(message) | [
"def",
"gpg_error",
"(",
"exception",
",",
"message",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"GPG Command %s\"",
",",
"' '",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"exception",
".",
"cmd",
"]",
")",
")",
"LOGGER",
".",
"de... | Handles the output of subprocess errors
in a way that is compatible with the log level | [
"Handles",
"the",
"output",
"of",
"subprocess",
"errors",
"in",
"a",
"way",
"that",
"is",
"compatible",
"with",
"the",
"log",
"level"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L405-L410 | train | 52,886 |
Autodesk/cryptorito | cryptorito/__init__.py | decrypt_var | def decrypt_var(source, passphrase=None):
"""Attempts to decrypt a variable"""
cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(),
passphrase_file(passphrase)]
return stderr_with_input(flatten(cmd), source) | python | def decrypt_var(source, passphrase=None):
"""Attempts to decrypt a variable"""
cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(),
passphrase_file(passphrase)]
return stderr_with_input(flatten(cmd), source) | [
"def",
"decrypt_var",
"(",
"source",
",",
"passphrase",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"gnupg_bin",
"(",
")",
",",
"\"--decrypt\"",
",",
"gnupg_home",
"(",
")",
",",
"gnupg_verbose",
"(",
")",
",",
"passphrase_file",
"(",
"passphrase",
")",
"]",... | Attempts to decrypt a variable | [
"Attempts",
"to",
"decrypt",
"a",
"variable"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L413-L418 | train | 52,887 |
Autodesk/cryptorito | cryptorito/__init__.py | decrypt | def decrypt(source, dest=None, passphrase=None):
"""Attempts to decrypt a file"""
if not os.path.exists(source):
raise CryptoritoError("Encrypted file %s not found" % source)
cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(),
passphrase_file(passphrase)]
if dest:
cmd.append(["--output", dest])
cmd.append([source])
stderr_output(flatten(cmd))
return True | python | def decrypt(source, dest=None, passphrase=None):
"""Attempts to decrypt a file"""
if not os.path.exists(source):
raise CryptoritoError("Encrypted file %s not found" % source)
cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(),
passphrase_file(passphrase)]
if dest:
cmd.append(["--output", dest])
cmd.append([source])
stderr_output(flatten(cmd))
return True | [
"def",
"decrypt",
"(",
"source",
",",
"dest",
"=",
"None",
",",
"passphrase",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",
":",
"raise",
"CryptoritoError",
"(",
"\"Encrypted file %s not found\"",
"%",
"source",
... | Attempts to decrypt a file | [
"Attempts",
"to",
"decrypt",
"a",
"file"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L421-L434 | train | 52,888 |
Autodesk/cryptorito | cryptorito/__init__.py | is_base64 | def is_base64(string):
"""Determines whether or not a string is likely to
be base64 encoded binary nonsense"""
return (not re.match('^[0-9]+$', string)) and \
(len(string) % 4 == 0) and \
re.match('^[A-Za-z0-9+/]+[=]{0,2}$', string) | python | def is_base64(string):
"""Determines whether or not a string is likely to
be base64 encoded binary nonsense"""
return (not re.match('^[0-9]+$', string)) and \
(len(string) % 4 == 0) and \
re.match('^[A-Za-z0-9+/]+[=]{0,2}$', string) | [
"def",
"is_base64",
"(",
"string",
")",
":",
"return",
"(",
"not",
"re",
".",
"match",
"(",
"'^[0-9]+$'",
",",
"string",
")",
")",
"and",
"(",
"len",
"(",
"string",
")",
"%",
"4",
"==",
"0",
")",
"and",
"re",
".",
"match",
"(",
"'^[A-Za-z0-9+/]+[=]... | Determines whether or not a string is likely to
be base64 encoded binary nonsense | [
"Determines",
"whether",
"or",
"not",
"a",
"string",
"is",
"likely",
"to",
"be",
"base64",
"encoded",
"binary",
"nonsense"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L437-L442 | train | 52,889 |
Autodesk/cryptorito | cryptorito/__init__.py | portable_b64encode | def portable_b64encode(thing):
"""Wrap b64encode for Python 2 & 3"""
if is_py3():
try:
some_bits = bytes(thing, 'utf-8')
except TypeError:
some_bits = thing
return polite_string(b64encode(some_bits).decode('utf-8'))
return polite_string(b64encode(thing)) | python | def portable_b64encode(thing):
"""Wrap b64encode for Python 2 & 3"""
if is_py3():
try:
some_bits = bytes(thing, 'utf-8')
except TypeError:
some_bits = thing
return polite_string(b64encode(some_bits).decode('utf-8'))
return polite_string(b64encode(thing)) | [
"def",
"portable_b64encode",
"(",
"thing",
")",
":",
"if",
"is_py3",
"(",
")",
":",
"try",
":",
"some_bits",
"=",
"bytes",
"(",
"thing",
",",
"'utf-8'",
")",
"except",
"TypeError",
":",
"some_bits",
"=",
"thing",
"return",
"polite_string",
"(",
"b64encode"... | Wrap b64encode for Python 2 & 3 | [
"Wrap",
"b64encode",
"for",
"Python",
"2",
"&",
"3"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L445-L455 | train | 52,890 |
RudolfCardinal/pythonlib | cardinal_pythonlib/buildfunc.py | download_if_not_exists | def download_if_not_exists(url: str, filename: str,
skip_cert_verify: bool = True,
mkdir: bool = True) -> None:
"""
Downloads a URL to a file, unless the file already exists.
"""
if os.path.isfile(filename):
log.info("No need to download, already have: {}", filename)
return
if mkdir:
directory, basename = os.path.split(os.path.abspath(filename))
mkdir_p(directory)
download(url=url,
filename=filename,
skip_cert_verify=skip_cert_verify) | python | def download_if_not_exists(url: str, filename: str,
skip_cert_verify: bool = True,
mkdir: bool = True) -> None:
"""
Downloads a URL to a file, unless the file already exists.
"""
if os.path.isfile(filename):
log.info("No need to download, already have: {}", filename)
return
if mkdir:
directory, basename = os.path.split(os.path.abspath(filename))
mkdir_p(directory)
download(url=url,
filename=filename,
skip_cert_verify=skip_cert_verify) | [
"def",
"download_if_not_exists",
"(",
"url",
":",
"str",
",",
"filename",
":",
"str",
",",
"skip_cert_verify",
":",
"bool",
"=",
"True",
",",
"mkdir",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fil... | Downloads a URL to a file, unless the file already exists. | [
"Downloads",
"a",
"URL",
"to",
"a",
"file",
"unless",
"the",
"file",
"already",
"exists",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L56-L70 | train | 52,891 |
RudolfCardinal/pythonlib | cardinal_pythonlib/buildfunc.py | git_clone | def git_clone(prettyname: str, url: str, directory: str,
branch: str = None,
commit: str = None,
clone_options: List[str] = None,
run_func: Callable[[List[str]], Any] = None) -> bool:
"""
Fetches a Git repository, unless we have it already.
Args:
prettyname: name to display to user
url: URL
directory: destination directory
branch: repository branch
commit: repository commit tag
clone_options: additional options to pass to ``git clone``
run_func: function to use to call an external command
Returns:
did we need to do anything?
"""
run_func = run_func or subprocess.check_call
clone_options = clone_options or [] # type: List[str]
if os.path.isdir(directory):
log.info("Not re-cloning {} Git repository: using existing source "
"in {}".format(prettyname, directory))
return False
log.info("Fetching {} source from {} into {}",
prettyname, url, directory)
require_executable(GIT)
gitargs = [GIT, "clone"] + clone_options
if branch:
gitargs += ["--branch", branch]
gitargs += [url, directory]
run_func(gitargs)
if commit:
log.info("Resetting {} local Git repository to commit {}",
prettyname, commit)
run_func([GIT,
"-C", directory,
"reset", "--hard", commit])
# Using a Git repository that's not in the working directory:
# https://stackoverflow.com/questions/1386291/git-git-dir-not-working-as-expected # noqa
return True | python | def git_clone(prettyname: str, url: str, directory: str,
branch: str = None,
commit: str = None,
clone_options: List[str] = None,
run_func: Callable[[List[str]], Any] = None) -> bool:
"""
Fetches a Git repository, unless we have it already.
Args:
prettyname: name to display to user
url: URL
directory: destination directory
branch: repository branch
commit: repository commit tag
clone_options: additional options to pass to ``git clone``
run_func: function to use to call an external command
Returns:
did we need to do anything?
"""
run_func = run_func or subprocess.check_call
clone_options = clone_options or [] # type: List[str]
if os.path.isdir(directory):
log.info("Not re-cloning {} Git repository: using existing source "
"in {}".format(prettyname, directory))
return False
log.info("Fetching {} source from {} into {}",
prettyname, url, directory)
require_executable(GIT)
gitargs = [GIT, "clone"] + clone_options
if branch:
gitargs += ["--branch", branch]
gitargs += [url, directory]
run_func(gitargs)
if commit:
log.info("Resetting {} local Git repository to commit {}",
prettyname, commit)
run_func([GIT,
"-C", directory,
"reset", "--hard", commit])
# Using a Git repository that's not in the working directory:
# https://stackoverflow.com/questions/1386291/git-git-dir-not-working-as-expected # noqa
return True | [
"def",
"git_clone",
"(",
"prettyname",
":",
"str",
",",
"url",
":",
"str",
",",
"directory",
":",
"str",
",",
"branch",
":",
"str",
"=",
"None",
",",
"commit",
":",
"str",
"=",
"None",
",",
"clone_options",
":",
"List",
"[",
"str",
"]",
"=",
"None"... | Fetches a Git repository, unless we have it already.
Args:
prettyname: name to display to user
url: URL
directory: destination directory
branch: repository branch
commit: repository commit tag
clone_options: additional options to pass to ``git clone``
run_func: function to use to call an external command
Returns:
did we need to do anything? | [
"Fetches",
"a",
"Git",
"repository",
"unless",
"we",
"have",
"it",
"already",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L77-L119 | train | 52,892 |
RudolfCardinal/pythonlib | cardinal_pythonlib/buildfunc.py | untar_to_directory | def untar_to_directory(tarfile: str,
directory: str,
verbose: bool = False,
gzipped: bool = False,
skip_if_dir_exists: bool = True,
run_func: Callable[[List[str]], Any] = None,
chdir_via_python: bool = True) -> None:
"""
Unpacks a TAR file into a specified directory.
Args:
tarfile: filename of the ``.tar`` file
directory: destination directory
verbose: be verbose?
gzipped: is the ``.tar`` also gzipped, e.g. a ``.tar.gz`` file?
skip_if_dir_exists: don't do anything if the destrination directory
exists?
run_func: function to use to call an external command
chdir_via_python: change directory via Python, not via ``tar``.
Consider using this via Windows, because Cygwin ``tar`` v1.29 falls
over when given a Windows path for its ``-C`` (or ``--directory``)
option.
"""
if skip_if_dir_exists and os.path.isdir(directory):
log.info("Skipping extraction of {} as directory {} exists",
tarfile, directory)
return
log.info("Extracting {} -> {}", tarfile, directory)
require_executable(TAR)
mkdir_p(directory)
args = [TAR, "-x"] # -x: extract
if verbose:
args.append("-v") # -v: verbose
if gzipped:
args.append("-z") # -z: decompress using gzip
if platform.system() != "Darwin": # OS/X tar doesn't support --force-local
args.append("--force-local") # allows filenames with colons in (Windows!) # noqa
args.extend(["-f", tarfile]) # -f: filename follows
if chdir_via_python:
with pushd(directory):
run_func(args)
else:
# chdir via tar
args.extend(["-C", directory]) # -C: change to directory
run_func(args) | python | def untar_to_directory(tarfile: str,
directory: str,
verbose: bool = False,
gzipped: bool = False,
skip_if_dir_exists: bool = True,
run_func: Callable[[List[str]], Any] = None,
chdir_via_python: bool = True) -> None:
"""
Unpacks a TAR file into a specified directory.
Args:
tarfile: filename of the ``.tar`` file
directory: destination directory
verbose: be verbose?
gzipped: is the ``.tar`` also gzipped, e.g. a ``.tar.gz`` file?
skip_if_dir_exists: don't do anything if the destrination directory
exists?
run_func: function to use to call an external command
chdir_via_python: change directory via Python, not via ``tar``.
Consider using this via Windows, because Cygwin ``tar`` v1.29 falls
over when given a Windows path for its ``-C`` (or ``--directory``)
option.
"""
if skip_if_dir_exists and os.path.isdir(directory):
log.info("Skipping extraction of {} as directory {} exists",
tarfile, directory)
return
log.info("Extracting {} -> {}", tarfile, directory)
require_executable(TAR)
mkdir_p(directory)
args = [TAR, "-x"] # -x: extract
if verbose:
args.append("-v") # -v: verbose
if gzipped:
args.append("-z") # -z: decompress using gzip
if platform.system() != "Darwin": # OS/X tar doesn't support --force-local
args.append("--force-local") # allows filenames with colons in (Windows!) # noqa
args.extend(["-f", tarfile]) # -f: filename follows
if chdir_via_python:
with pushd(directory):
run_func(args)
else:
# chdir via tar
args.extend(["-C", directory]) # -C: change to directory
run_func(args) | [
"def",
"untar_to_directory",
"(",
"tarfile",
":",
"str",
",",
"directory",
":",
"str",
",",
"verbose",
":",
"bool",
"=",
"False",
",",
"gzipped",
":",
"bool",
"=",
"False",
",",
"skip_if_dir_exists",
":",
"bool",
"=",
"True",
",",
"run_func",
":",
"Calla... | Unpacks a TAR file into a specified directory.
Args:
tarfile: filename of the ``.tar`` file
directory: destination directory
verbose: be verbose?
gzipped: is the ``.tar`` also gzipped, e.g. a ``.tar.gz`` file?
skip_if_dir_exists: don't do anything if the destrination directory
exists?
run_func: function to use to call an external command
chdir_via_python: change directory via Python, not via ``tar``.
Consider using this via Windows, because Cygwin ``tar`` v1.29 falls
over when given a Windows path for its ``-C`` (or ``--directory``)
option. | [
"Unpacks",
"a",
"TAR",
"file",
"into",
"a",
"specified",
"directory",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L136-L180 | train | 52,893 |
RudolfCardinal/pythonlib | cardinal_pythonlib/buildfunc.py | run | def run(args: List[str],
env: Dict[str, str] = None,
capture_stdout: bool = False,
echo_stdout: bool = True,
capture_stderr: bool = False,
echo_stderr: bool = True,
debug_show_env: bool = True,
encoding: str = sys.getdefaultencoding(),
allow_failure: bool = False,
**kwargs) -> Tuple[str, str]:
"""
Runs an external process, announcing it.
Optionally, retrieves its ``stdout`` and/or ``stderr`` output (if not
retrieved, the output will be visible to the user).
Args:
args: list of command-line arguments (the first being the executable)
env: operating system environment to use (if ``None``, the current OS
environment will be used)
capture_stdout: capture the command's ``stdout``?
echo_stdout: allow the command's ``stdout`` to go to ``sys.stdout``?
capture_stderr: capture the command's ``stderr``?
echo_stderr: allow the command's ``stderr`` to go to ``sys.stderr``?
debug_show_env: be verbose and show the environment used before calling
encoding: encoding to use to translate the command's output
allow_failure: if ``True``, continues if the command returns a
non-zero (failure) exit code; if ``False``, raises an error if
that happens
kwargs: additional arguments to :func:`teed_call`
Returns:
a tuple: ``(stdout, stderr)``. If the output wasn't captured, an empty
string will take its place in this tuple.
"""
cwd = os.getcwd()
# log.debug("External command Python form: {}", args)
copy_paste_cmd = subprocess.list2cmdline(args)
csep = "=" * 79
esep = "-" * 79
effective_env = env or os.environ
if debug_show_env:
log.debug(
"Environment for the command that follows:\n"
"{esep}\n"
"{env}\n"
"{esep}".format(esep=esep, env=make_copy_paste_env(effective_env))
)
log.info(
"Launching external command:\n"
"{csep}\n"
"WORKING DIRECTORY: {cwd}\n"
"PYTHON ARGS: {args!r}\n"
"COMMAND: {cmd}\n"
"{csep}".format(csep=csep, cwd=cwd, cmd=copy_paste_cmd,
args=args)
)
try:
with io.StringIO() as out, io.StringIO() as err:
stdout_targets = [] # type: List[TextIO]
stderr_targets = [] # type: List[TextIO]
if capture_stdout:
stdout_targets.append(out)
if echo_stdout:
stdout_targets.append(sys.stdout)
if capture_stderr:
stderr_targets.append(err)
if echo_stderr:
stderr_targets.append(sys.stderr)
retcode = teed_call(args,
stdout_targets=stdout_targets,
stderr_targets=stderr_targets,
encoding=encoding,
env=env,
**kwargs)
stdout = out.getvalue()
stderr = err.getvalue()
if retcode != 0 and not allow_failure:
# subprocess.check_call() and check_output() raise
# CalledProcessError if the called process returns a non-zero
# return code.
raise subprocess.CalledProcessError(returncode=retcode,
cmd=args,
output=stdout,
stderr=stderr)
log.debug("\n{csep}\nFINISHED SUCCESSFULLY: {cmd}\n{csep}",
cmd=copy_paste_cmd, csep=csep)
return stdout, stderr
except FileNotFoundError:
require_executable(args[0]) # which is missing, so we'll see some help
raise
except subprocess.CalledProcessError:
log.critical(
"Command that failed:\n"
"[ENVIRONMENT]\n"
"{env}\n"
"\n"
"[DIRECTORY] {cwd}\n"
"[PYTHON ARGS] {args}\n"
"[COMMAND] {cmd}".format(
cwd=cwd,
env=make_copy_paste_env(effective_env),
cmd=copy_paste_cmd,
args=args
)
)
raise | python | def run(args: List[str],
env: Dict[str, str] = None,
capture_stdout: bool = False,
echo_stdout: bool = True,
capture_stderr: bool = False,
echo_stderr: bool = True,
debug_show_env: bool = True,
encoding: str = sys.getdefaultencoding(),
allow_failure: bool = False,
**kwargs) -> Tuple[str, str]:
"""
Runs an external process, announcing it.
Optionally, retrieves its ``stdout`` and/or ``stderr`` output (if not
retrieved, the output will be visible to the user).
Args:
args: list of command-line arguments (the first being the executable)
env: operating system environment to use (if ``None``, the current OS
environment will be used)
capture_stdout: capture the command's ``stdout``?
echo_stdout: allow the command's ``stdout`` to go to ``sys.stdout``?
capture_stderr: capture the command's ``stderr``?
echo_stderr: allow the command's ``stderr`` to go to ``sys.stderr``?
debug_show_env: be verbose and show the environment used before calling
encoding: encoding to use to translate the command's output
allow_failure: if ``True``, continues if the command returns a
non-zero (failure) exit code; if ``False``, raises an error if
that happens
kwargs: additional arguments to :func:`teed_call`
Returns:
a tuple: ``(stdout, stderr)``. If the output wasn't captured, an empty
string will take its place in this tuple.
"""
cwd = os.getcwd()
# log.debug("External command Python form: {}", args)
copy_paste_cmd = subprocess.list2cmdline(args)
csep = "=" * 79
esep = "-" * 79
effective_env = env or os.environ
if debug_show_env:
log.debug(
"Environment for the command that follows:\n"
"{esep}\n"
"{env}\n"
"{esep}".format(esep=esep, env=make_copy_paste_env(effective_env))
)
log.info(
"Launching external command:\n"
"{csep}\n"
"WORKING DIRECTORY: {cwd}\n"
"PYTHON ARGS: {args!r}\n"
"COMMAND: {cmd}\n"
"{csep}".format(csep=csep, cwd=cwd, cmd=copy_paste_cmd,
args=args)
)
try:
with io.StringIO() as out, io.StringIO() as err:
stdout_targets = [] # type: List[TextIO]
stderr_targets = [] # type: List[TextIO]
if capture_stdout:
stdout_targets.append(out)
if echo_stdout:
stdout_targets.append(sys.stdout)
if capture_stderr:
stderr_targets.append(err)
if echo_stderr:
stderr_targets.append(sys.stderr)
retcode = teed_call(args,
stdout_targets=stdout_targets,
stderr_targets=stderr_targets,
encoding=encoding,
env=env,
**kwargs)
stdout = out.getvalue()
stderr = err.getvalue()
if retcode != 0 and not allow_failure:
# subprocess.check_call() and check_output() raise
# CalledProcessError if the called process returns a non-zero
# return code.
raise subprocess.CalledProcessError(returncode=retcode,
cmd=args,
output=stdout,
stderr=stderr)
log.debug("\n{csep}\nFINISHED SUCCESSFULLY: {cmd}\n{csep}",
cmd=copy_paste_cmd, csep=csep)
return stdout, stderr
except FileNotFoundError:
require_executable(args[0]) # which is missing, so we'll see some help
raise
except subprocess.CalledProcessError:
log.critical(
"Command that failed:\n"
"[ENVIRONMENT]\n"
"{env}\n"
"\n"
"[DIRECTORY] {cwd}\n"
"[PYTHON ARGS] {args}\n"
"[COMMAND] {cmd}".format(
cwd=cwd,
env=make_copy_paste_env(effective_env),
cmd=copy_paste_cmd,
args=args
)
)
raise | [
"def",
"run",
"(",
"args",
":",
"List",
"[",
"str",
"]",
",",
"env",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"capture_stdout",
":",
"bool",
"=",
"False",
",",
"echo_stdout",
":",
"bool",
"=",
"True",
",",
"capture_stderr",
":",
... | Runs an external process, announcing it.
Optionally, retrieves its ``stdout`` and/or ``stderr`` output (if not
retrieved, the output will be visible to the user).
Args:
args: list of command-line arguments (the first being the executable)
env: operating system environment to use (if ``None``, the current OS
environment will be used)
capture_stdout: capture the command's ``stdout``?
echo_stdout: allow the command's ``stdout`` to go to ``sys.stdout``?
capture_stderr: capture the command's ``stderr``?
echo_stderr: allow the command's ``stderr`` to go to ``sys.stderr``?
debug_show_env: be verbose and show the environment used before calling
encoding: encoding to use to translate the command's output
allow_failure: if ``True``, continues if the command returns a
non-zero (failure) exit code; if ``False``, raises an error if
that happens
kwargs: additional arguments to :func:`teed_call`
Returns:
a tuple: ``(stdout, stderr)``. If the output wasn't captured, an empty
string will take its place in this tuple. | [
"Runs",
"an",
"external",
"process",
"announcing",
"it",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L213-L328 | train | 52,894 |
RudolfCardinal/pythonlib | cardinal_pythonlib/buildfunc.py | fetch | def fetch(args: List[str], env: Dict[str, str] = None,
encoding: str = sys.getdefaultencoding()) -> str:
"""
Run a command and returns its stdout.
Args:
args: the command-line arguments
env: the operating system environment to use
encoding: the encoding to use for ``stdout``
Returns:
the command's ``stdout`` output
"""
stdout, _ = run(args, env=env, capture_stdout=True,
echo_stdout=False, encoding=encoding)
log.debug(stdout)
return stdout | python | def fetch(args: List[str], env: Dict[str, str] = None,
encoding: str = sys.getdefaultencoding()) -> str:
"""
Run a command and returns its stdout.
Args:
args: the command-line arguments
env: the operating system environment to use
encoding: the encoding to use for ``stdout``
Returns:
the command's ``stdout`` output
"""
stdout, _ = run(args, env=env, capture_stdout=True,
echo_stdout=False, encoding=encoding)
log.debug(stdout)
return stdout | [
"def",
"fetch",
"(",
"args",
":",
"List",
"[",
"str",
"]",
",",
"env",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"encoding",
":",
"str",
"=",
"sys",
".",
"getdefaultencoding",
"(",
")",
")",
"->",
"str",
":",
"stdout",
",",
"_... | Run a command and returns its stdout.
Args:
args: the command-line arguments
env: the operating system environment to use
encoding: the encoding to use for ``stdout``
Returns:
the command's ``stdout`` output | [
"Run",
"a",
"command",
"and",
"returns",
"its",
"stdout",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L331-L348 | train | 52,895 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dump.py | dump_connection_info | def dump_connection_info(engine: Engine, fileobj: TextIO = sys.stdout) -> None:
"""
Dumps some connection info, as an SQL comment. Obscures passwords.
Args:
engine: the SQLAlchemy :class:`Engine` to dump metadata information
from
fileobj: the file-like object (default ``sys.stdout``) to write
information to
"""
meta = MetaData(bind=engine)
writeline_nl(fileobj, sql_comment('Database info: {}'.format(meta))) | python | def dump_connection_info(engine: Engine, fileobj: TextIO = sys.stdout) -> None:
"""
Dumps some connection info, as an SQL comment. Obscures passwords.
Args:
engine: the SQLAlchemy :class:`Engine` to dump metadata information
from
fileobj: the file-like object (default ``sys.stdout``) to write
information to
"""
meta = MetaData(bind=engine)
writeline_nl(fileobj, sql_comment('Database info: {}'.format(meta))) | [
"def",
"dump_connection_info",
"(",
"engine",
":",
"Engine",
",",
"fileobj",
":",
"TextIO",
"=",
"sys",
".",
"stdout",
")",
"->",
"None",
":",
"meta",
"=",
"MetaData",
"(",
"bind",
"=",
"engine",
")",
"writeline_nl",
"(",
"fileobj",
",",
"sql_comment",
"... | Dumps some connection info, as an SQL comment. Obscures passwords.
Args:
engine: the SQLAlchemy :class:`Engine` to dump metadata information
from
fileobj: the file-like object (default ``sys.stdout``) to write
information to | [
"Dumps",
"some",
"connection",
"info",
"as",
"an",
"SQL",
"comment",
".",
"Obscures",
"passwords",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L65-L76 | train | 52,896 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dump.py | dump_ddl | def dump_ddl(metadata: MetaData,
dialect_name: str,
fileobj: TextIO = sys.stdout,
checkfirst: bool = True) -> None:
"""
Sends schema-creating DDL from the metadata to the dump engine.
This makes ``CREATE TABLE`` statements.
Args:
metadata: SQLAlchemy :class:`MetaData`
dialect_name: string name of SQL dialect to generate DDL in
fileobj: file-like object to send DDL to
checkfirst: if ``True``, use ``CREATE TABLE IF NOT EXISTS`` or
equivalent.
"""
# http://docs.sqlalchemy.org/en/rel_0_8/faq.html#how-can-i-get-the-create-table-drop-table-output-as-a-string # noqa
# http://stackoverflow.com/questions/870925/how-to-generate-a-file-with-ddl-in-the-engines-sql-dialect-in-sqlalchemy # noqa
# https://github.com/plq/scripts/blob/master/pg_dump.py
# noinspection PyUnusedLocal
def dump(querysql, *multiparams, **params):
compsql = querysql.compile(dialect=engine.dialect)
writeline_nl(fileobj, "{sql};".format(sql=compsql))
writeline_nl(fileobj,
sql_comment("Schema (for dialect {}):".format(dialect_name)))
engine = create_engine('{dialect}://'.format(dialect=dialect_name),
strategy='mock', executor=dump)
metadata.create_all(engine, checkfirst=checkfirst) | python | def dump_ddl(metadata: MetaData,
dialect_name: str,
fileobj: TextIO = sys.stdout,
checkfirst: bool = True) -> None:
"""
Sends schema-creating DDL from the metadata to the dump engine.
This makes ``CREATE TABLE`` statements.
Args:
metadata: SQLAlchemy :class:`MetaData`
dialect_name: string name of SQL dialect to generate DDL in
fileobj: file-like object to send DDL to
checkfirst: if ``True``, use ``CREATE TABLE IF NOT EXISTS`` or
equivalent.
"""
# http://docs.sqlalchemy.org/en/rel_0_8/faq.html#how-can-i-get-the-create-table-drop-table-output-as-a-string # noqa
# http://stackoverflow.com/questions/870925/how-to-generate-a-file-with-ddl-in-the-engines-sql-dialect-in-sqlalchemy # noqa
# https://github.com/plq/scripts/blob/master/pg_dump.py
# noinspection PyUnusedLocal
def dump(querysql, *multiparams, **params):
compsql = querysql.compile(dialect=engine.dialect)
writeline_nl(fileobj, "{sql};".format(sql=compsql))
writeline_nl(fileobj,
sql_comment("Schema (for dialect {}):".format(dialect_name)))
engine = create_engine('{dialect}://'.format(dialect=dialect_name),
strategy='mock', executor=dump)
metadata.create_all(engine, checkfirst=checkfirst) | [
"def",
"dump_ddl",
"(",
"metadata",
":",
"MetaData",
",",
"dialect_name",
":",
"str",
",",
"fileobj",
":",
"TextIO",
"=",
"sys",
".",
"stdout",
",",
"checkfirst",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"# http://docs.sqlalchemy.org/en/rel_0_8/faq.ht... | Sends schema-creating DDL from the metadata to the dump engine.
This makes ``CREATE TABLE`` statements.
Args:
metadata: SQLAlchemy :class:`MetaData`
dialect_name: string name of SQL dialect to generate DDL in
fileobj: file-like object to send DDL to
checkfirst: if ``True``, use ``CREATE TABLE IF NOT EXISTS`` or
equivalent. | [
"Sends",
"schema",
"-",
"creating",
"DDL",
"from",
"the",
"metadata",
"to",
"the",
"dump",
"engine",
".",
"This",
"makes",
"CREATE",
"TABLE",
"statements",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L79-L106 | train | 52,897 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dump.py | dump_table_as_insert_sql | def dump_table_as_insert_sql(engine: Engine,
table_name: str,
fileobj: TextIO,
wheredict: Dict[str, Any] = None,
include_ddl: bool = False,
multirow: bool = False) -> None:
"""
Reads a table from the database, and writes SQL to replicate the table's
data to the output ``fileobj``.
Args:
engine: SQLAlchemy :class:`Engine`
table_name: name of the table
fileobj: file-like object to write to
wheredict: optional dictionary of ``{column_name: value}`` to use as
``WHERE`` filters
include_ddl: if ``True``, include the DDL to create the table as well
multirow: write multi-row ``INSERT`` statements
"""
# http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query # noqa
# http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
# http://www.tylerlesmann.com/2009/apr/27/copying-databases-across-platforms-sqlalchemy/ # noqa
# https://github.com/plq/scripts/blob/master/pg_dump.py
log.info("dump_data_as_insert_sql: table_name={}", table_name)
writelines_nl(fileobj, [
SEP1,
sql_comment("Data for table: {}".format(table_name)),
SEP2,
sql_comment("Filters: {}".format(wheredict)),
])
dialect = engine.dialect
if not dialect.supports_multivalues_insert:
multirow = False
if multirow:
log.warning("dump_data_as_insert_sql: multirow parameter substitution "
"not working yet")
multirow = False
# literal_query = make_literal_query_fn(dialect)
meta = MetaData(bind=engine)
log.debug("... retrieving schema")
table = Table(table_name, meta, autoload=True)
if include_ddl:
log.debug("... producing DDL")
dump_ddl(table.metadata, dialect_name=engine.dialect.name,
fileobj=fileobj)
# NewRecord = quick_mapper(table)
# columns = table.columns.keys()
log.debug("... fetching records")
# log.debug("meta: {}", meta) # obscures password
# log.debug("table: {}", table)
# log.debug("table.columns: {!r}", table.columns)
# log.debug("multirow: {}", multirow)
query = select(table.columns)
if wheredict:
for k, v in wheredict.items():
col = table.columns.get(k)
query = query.where(col == v)
# log.debug("query: {}", query)
cursor = engine.execute(query)
if multirow:
row_dict_list = []
for r in cursor:
row_dict_list.append(dict(r))
# log.debug("row_dict_list: {}", row_dict_list)
if row_dict_list:
statement = table.insert().values(row_dict_list)
# log.debug("statement: {!r}", statement)
# insert_str = literal_query(statement)
insert_str = get_literal_query(statement, bind=engine)
# NOT WORKING FOR MULTIROW INSERTS. ONLY SUBSTITUTES FIRST ROW.
writeline_nl(fileobj, insert_str)
else:
writeline_nl(fileobj, sql_comment("No data!"))
else:
found_one = False
for r in cursor:
found_one = True
row_dict = dict(r)
statement = table.insert(values=row_dict)
# insert_str = literal_query(statement)
insert_str = get_literal_query(statement, bind=engine)
# log.debug("row_dict: {}", row_dict)
# log.debug("insert_str: {}", insert_str)
writeline_nl(fileobj, insert_str)
if not found_one:
writeline_nl(fileobj, sql_comment("No data!"))
writeline_nl(fileobj, SEP2)
log.debug("... done") | python | def dump_table_as_insert_sql(engine: Engine,
table_name: str,
fileobj: TextIO,
wheredict: Dict[str, Any] = None,
include_ddl: bool = False,
multirow: bool = False) -> None:
"""
Reads a table from the database, and writes SQL to replicate the table's
data to the output ``fileobj``.
Args:
engine: SQLAlchemy :class:`Engine`
table_name: name of the table
fileobj: file-like object to write to
wheredict: optional dictionary of ``{column_name: value}`` to use as
``WHERE`` filters
include_ddl: if ``True``, include the DDL to create the table as well
multirow: write multi-row ``INSERT`` statements
"""
# http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query # noqa
# http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
# http://www.tylerlesmann.com/2009/apr/27/copying-databases-across-platforms-sqlalchemy/ # noqa
# https://github.com/plq/scripts/blob/master/pg_dump.py
log.info("dump_data_as_insert_sql: table_name={}", table_name)
writelines_nl(fileobj, [
SEP1,
sql_comment("Data for table: {}".format(table_name)),
SEP2,
sql_comment("Filters: {}".format(wheredict)),
])
dialect = engine.dialect
if not dialect.supports_multivalues_insert:
multirow = False
if multirow:
log.warning("dump_data_as_insert_sql: multirow parameter substitution "
"not working yet")
multirow = False
# literal_query = make_literal_query_fn(dialect)
meta = MetaData(bind=engine)
log.debug("... retrieving schema")
table = Table(table_name, meta, autoload=True)
if include_ddl:
log.debug("... producing DDL")
dump_ddl(table.metadata, dialect_name=engine.dialect.name,
fileobj=fileobj)
# NewRecord = quick_mapper(table)
# columns = table.columns.keys()
log.debug("... fetching records")
# log.debug("meta: {}", meta) # obscures password
# log.debug("table: {}", table)
# log.debug("table.columns: {!r}", table.columns)
# log.debug("multirow: {}", multirow)
query = select(table.columns)
if wheredict:
for k, v in wheredict.items():
col = table.columns.get(k)
query = query.where(col == v)
# log.debug("query: {}", query)
cursor = engine.execute(query)
if multirow:
row_dict_list = []
for r in cursor:
row_dict_list.append(dict(r))
# log.debug("row_dict_list: {}", row_dict_list)
if row_dict_list:
statement = table.insert().values(row_dict_list)
# log.debug("statement: {!r}", statement)
# insert_str = literal_query(statement)
insert_str = get_literal_query(statement, bind=engine)
# NOT WORKING FOR MULTIROW INSERTS. ONLY SUBSTITUTES FIRST ROW.
writeline_nl(fileobj, insert_str)
else:
writeline_nl(fileobj, sql_comment("No data!"))
else:
found_one = False
for r in cursor:
found_one = True
row_dict = dict(r)
statement = table.insert(values=row_dict)
# insert_str = literal_query(statement)
insert_str = get_literal_query(statement, bind=engine)
# log.debug("row_dict: {}", row_dict)
# log.debug("insert_str: {}", insert_str)
writeline_nl(fileobj, insert_str)
if not found_one:
writeline_nl(fileobj, sql_comment("No data!"))
writeline_nl(fileobj, SEP2)
log.debug("... done") | [
"def",
"dump_table_as_insert_sql",
"(",
"engine",
":",
"Engine",
",",
"table_name",
":",
"str",
",",
"fileobj",
":",
"TextIO",
",",
"wheredict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"include_ddl",
":",
"bool",
"=",
"False",
",",
... | Reads a table from the database, and writes SQL to replicate the table's
data to the output ``fileobj``.
Args:
engine: SQLAlchemy :class:`Engine`
table_name: name of the table
fileobj: file-like object to write to
wheredict: optional dictionary of ``{column_name: value}`` to use as
``WHERE`` filters
include_ddl: if ``True``, include the DDL to create the table as well
multirow: write multi-row ``INSERT`` statements | [
"Reads",
"a",
"table",
"from",
"the",
"database",
"and",
"writes",
"SQL",
"to",
"replicate",
"the",
"table",
"s",
"data",
"to",
"the",
"output",
"fileobj",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L284-L373 | train | 52,898 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dump.py | dump_database_as_insert_sql | def dump_database_as_insert_sql(engine: Engine,
fileobj: TextIO = sys.stdout,
include_ddl: bool = False,
multirow: bool = False) -> None:
"""
Reads an entire database and writes SQL to replicate it to the output
file-like object.
Args:
engine: SQLAlchemy :class:`Engine`
fileobj: file-like object to write to
include_ddl: if ``True``, include the DDL to create the table as well
multirow: write multi-row ``INSERT`` statements
"""
for tablename in get_table_names(engine):
dump_table_as_insert_sql(
engine=engine,
table_name=tablename,
fileobj=fileobj,
include_ddl=include_ddl,
multirow=multirow
) | python | def dump_database_as_insert_sql(engine: Engine,
fileobj: TextIO = sys.stdout,
include_ddl: bool = False,
multirow: bool = False) -> None:
"""
Reads an entire database and writes SQL to replicate it to the output
file-like object.
Args:
engine: SQLAlchemy :class:`Engine`
fileobj: file-like object to write to
include_ddl: if ``True``, include the DDL to create the table as well
multirow: write multi-row ``INSERT`` statements
"""
for tablename in get_table_names(engine):
dump_table_as_insert_sql(
engine=engine,
table_name=tablename,
fileobj=fileobj,
include_ddl=include_ddl,
multirow=multirow
) | [
"def",
"dump_database_as_insert_sql",
"(",
"engine",
":",
"Engine",
",",
"fileobj",
":",
"TextIO",
"=",
"sys",
".",
"stdout",
",",
"include_ddl",
":",
"bool",
"=",
"False",
",",
"multirow",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"for",
"table... | Reads an entire database and writes SQL to replicate it to the output
file-like object.
Args:
engine: SQLAlchemy :class:`Engine`
fileobj: file-like object to write to
include_ddl: if ``True``, include the DDL to create the table as well
multirow: write multi-row ``INSERT`` statements | [
"Reads",
"an",
"entire",
"database",
"and",
"writes",
"SQL",
"to",
"replicate",
"it",
"to",
"the",
"output",
"file",
"-",
"like",
"object",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L376-L397 | train | 52,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.