repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
edx/opaque-keys | opaque_keys/edx/locator.py | BlockUsageLocator.to_deprecated_son | def to_deprecated_son(self, prefix='', tag='i4x'):
"""
Returns a SON object that represents this location
"""
# This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'),
# because that format was used to store data historically in mongo
# ... | python | def to_deprecated_son(self, prefix='', tag='i4x'):
"""
Returns a SON object that represents this location
"""
# This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'),
# because that format was used to store data historically in mongo
# ... | Returns a SON object that represents this location | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L996-L1012 |
edx/opaque-keys | opaque_keys/edx/locator.py | BlockUsageLocator._from_deprecated_son | def _from_deprecated_son(cls, id_dict, run):
"""
Return the Location decoding this id_dict and run
"""
course_key = CourseLocator(
id_dict['org'],
id_dict['course'],
run,
id_dict['revision'],
deprecated=True,
)
r... | python | def _from_deprecated_son(cls, id_dict, run):
"""
Return the Location decoding this id_dict and run
"""
course_key = CourseLocator(
id_dict['org'],
id_dict['course'],
run,
id_dict['revision'],
deprecated=True,
)
r... | Return the Location decoding this id_dict and run | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1015-L1026 |
edx/opaque-keys | opaque_keys/edx/locator.py | LibraryUsageLocator._from_string | def _from_string(cls, serialized):
"""
Requests LibraryLocator to deserialize its part and then adds the local deserialization of block
"""
# Allow access to _from_string protected method
library_key = LibraryLocator._from_string(serialized) # pylint: disable=protected-access
... | python | def _from_string(cls, serialized):
"""
Requests LibraryLocator to deserialize its part and then adds the local deserialization of block
"""
# Allow access to _from_string protected method
library_key = LibraryLocator._from_string(serialized) # pylint: disable=protected-access
... | Requests LibraryLocator to deserialize its part and then adds the local deserialization of block | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1087-L1103 |
edx/opaque-keys | opaque_keys/edx/locator.py | LibraryUsageLocator.for_branch | def for_branch(self, branch):
"""
Return a UsageLocator for the same block in a different branch of the library.
"""
return self.replace(library_key=self.library_key.for_branch(branch)) | python | def for_branch(self, branch):
"""
Return a UsageLocator for the same block in a different branch of the library.
"""
return self.replace(library_key=self.library_key.for_branch(branch)) | Return a UsageLocator for the same block in a different branch of the library. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1116-L1120 |
edx/opaque-keys | opaque_keys/edx/locator.py | LibraryUsageLocator.for_version | def for_version(self, version_guid):
"""
Return a UsageLocator for the same block in a different version of the library.
"""
return self.replace(library_key=self.library_key.for_version(version_guid)) | python | def for_version(self, version_guid):
"""
Return a UsageLocator for the same block in a different version of the library.
"""
return self.replace(library_key=self.library_key.for_version(version_guid)) | Return a UsageLocator for the same block in a different version of the library. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1122-L1126 |
edx/opaque-keys | opaque_keys/edx/locator.py | DefinitionLocator._to_string | def _to_string(self):
"""
Return a string representing this location.
unicode(self) returns something like this: "519665f6223ebd6980884f2b+type+problem"
"""
return u"{}+{}@{}".format(text_type(self.definition_id), self.BLOCK_TYPE_PREFIX, self.block_type) | python | def _to_string(self):
"""
Return a string representing this location.
unicode(self) returns something like this: "519665f6223ebd6980884f2b+type+problem"
"""
return u"{}+{}@{}".format(text_type(self.definition_id), self.BLOCK_TYPE_PREFIX, self.block_type) | Return a string representing this location.
unicode(self) returns something like this: "519665f6223ebd6980884f2b+type+problem" | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1185-L1190 |
edx/opaque-keys | opaque_keys/edx/locator.py | DefinitionLocator._from_string | def _from_string(cls, serialized):
"""
Return a DefinitionLocator parsing the given serialized string
:param serialized: matches the string to
"""
parse = cls.URL_RE.match(serialized)
if not parse:
raise InvalidKeyError(cls, serialized)
parse = parse.... | python | def _from_string(cls, serialized):
"""
Return a DefinitionLocator parsing the given serialized string
:param serialized: matches the string to
"""
parse = cls.URL_RE.match(serialized)
if not parse:
raise InvalidKeyError(cls, serialized)
parse = parse.... | Return a DefinitionLocator parsing the given serialized string
:param serialized: matches the string to | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1200-L1213 |
edx/opaque-keys | opaque_keys/edx/locator.py | AssetLocator._to_deprecated_string | def _to_deprecated_string(self):
"""
Returns an old-style location, represented as:
/c4x/org/course/category/name
"""
# pylint: disable=missing-format-attribute
url = u"/{0.DEPRECATED_TAG}/{0.course_key.org}/{0.course_key.course}/{0.block_type}/{0.block_id}".format(self)... | python | def _to_deprecated_string(self):
"""
Returns an old-style location, represented as:
/c4x/org/course/category/name
"""
# pylint: disable=missing-format-attribute
url = u"/{0.DEPRECATED_TAG}/{0.course_key.org}/{0.course_key.course}/{0.block_type}/{0.block_id}".format(self)... | Returns an old-style location, represented as:
/c4x/org/course/category/name | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1284-L1294 |
edx/opaque-keys | opaque_keys/edx/locator.py | AssetLocator.to_deprecated_list_repr | def to_deprecated_list_repr(self):
"""
Thumbnail locations are stored as lists [c4x, org, course, thumbnail, path, None] in contentstore.mongo
That should be the only use of this method, but the method is general enough to provide the pre-opaque
Location fields as an array in the old ord... | python | def to_deprecated_list_repr(self):
"""
Thumbnail locations are stored as lists [c4x, org, course, thumbnail, path, None] in contentstore.mongo
That should be the only use of this method, but the method is general enough to provide the pre-opaque
Location fields as an array in the old ord... | Thumbnail locations are stored as lists [c4x, org, course, thumbnail, path, None] in contentstore.mongo
That should be the only use of this method, but the method is general enough to provide the pre-opaque
Location fields as an array in the old order with the tag. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1325-L1331 |
edx/opaque-keys | opaque_keys/edx/django/models.py | _strip_object | def _strip_object(key):
"""
Strips branch and version info if the given key supports those attributes.
"""
if hasattr(key, 'version_agnostic') and hasattr(key, 'for_branch'):
return key.for_branch(None).version_agnostic()
else:
return key | python | def _strip_object(key):
"""
Strips branch and version info if the given key supports those attributes.
"""
if hasattr(key, 'version_agnostic') and hasattr(key, 'for_branch'):
return key.for_branch(None).version_agnostic()
else:
return key | Strips branch and version info if the given key supports those attributes. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/django/models.py#L58-L65 |
edx/opaque-keys | opaque_keys/edx/django/models.py | _strip_value | def _strip_value(value, lookup='exact'):
"""
Helper function to remove the branch and version information from the given value,
which could be a single object or a list.
"""
if lookup == 'in':
stripped_value = [_strip_object(el) for el in value]
else:
stripped_value = _strip_obje... | python | def _strip_value(value, lookup='exact'):
"""
Helper function to remove the branch and version information from the given value,
which could be a single object or a list.
"""
if lookup == 'in':
stripped_value = [_strip_object(el) for el in value]
else:
stripped_value = _strip_obje... | Helper function to remove the branch and version information from the given value,
which could be a single object or a list. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/django/models.py#L68-L77 |
edx/opaque-keys | opaque_keys/edx/django/models.py | OpaqueKeyField.validate | def validate(self, value, model_instance):
"""Validate Empty values, otherwise defer to the parent"""
# raise validation error if the use of this field says it can't be blank but it is
if not self.blank and value is self.Empty:
raise ValidationError(self.error_messages['blank'])
... | python | def validate(self, value, model_instance):
"""Validate Empty values, otherwise defer to the parent"""
# raise validation error if the use of this field says it can't be blank but it is
if not self.blank and value is self.Empty:
raise ValidationError(self.error_messages['blank'])
... | Validate Empty values, otherwise defer to the parent | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/django/models.py#L148-L154 |
edx/opaque-keys | opaque_keys/edx/django/models.py | OpaqueKeyField.run_validators | def run_validators(self, value):
"""Validate Empty values, otherwise defer to the parent"""
if value is self.Empty:
return
return super(OpaqueKeyField, self).run_validators(value) | python | def run_validators(self, value):
"""Validate Empty values, otherwise defer to the parent"""
if value is self.Empty:
return
return super(OpaqueKeyField, self).run_validators(value) | Validate Empty values, otherwise defer to the parent | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/django/models.py#L156-L161 |
edx/opaque-keys | opaque_keys/edx/locations.py | SlashSeparatedCourseKey.from_string | def from_string(cls, serialized):
"""Deprecated. Use :meth:`locator.CourseLocator.from_string`."""
warnings.warn(
"SlashSeparatedCourseKey is deprecated! Please use locator.CourseLocator",
DeprecationWarning,
stacklevel=2
)
return CourseLocator.from_st... | python | def from_string(cls, serialized):
"""Deprecated. Use :meth:`locator.CourseLocator.from_string`."""
warnings.warn(
"SlashSeparatedCourseKey is deprecated! Please use locator.CourseLocator",
DeprecationWarning,
stacklevel=2
)
return CourseLocator.from_st... | Deprecated. Use :meth:`locator.CourseLocator.from_string`. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L52-L59 |
edx/opaque-keys | opaque_keys/edx/locations.py | SlashSeparatedCourseKey.replace | def replace(self, **kwargs):
"""
Return: a new :class:`SlashSeparatedCourseKey` with specific ``kwargs`` replacing
their corresponding values.
Using CourseLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate a SlashSe... | python | def replace(self, **kwargs):
"""
Return: a new :class:`SlashSeparatedCourseKey` with specific ``kwargs`` replacing
their corresponding values.
Using CourseLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate a SlashSe... | Return: a new :class:`SlashSeparatedCourseKey` with specific ``kwargs`` replacing
their corresponding values.
Using CourseLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate a SlashSeparatedCourseKey object with CourseLocator args a... | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L61-L75 |
edx/opaque-keys | opaque_keys/edx/locations.py | LocationBase._deprecation_warning | def _deprecation_warning(cls):
"""Display a deprecation warning for the given cls"""
if issubclass(cls, Location):
warnings.warn(
"Location is deprecated! Please use locator.BlockUsageLocator",
DeprecationWarning,
stacklevel=3
)
... | python | def _deprecation_warning(cls):
"""Display a deprecation warning for the given cls"""
if issubclass(cls, Location):
warnings.warn(
"Location is deprecated! Please use locator.BlockUsageLocator",
DeprecationWarning,
stacklevel=3
)
... | Display a deprecation warning for the given cls | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L84-L103 |
edx/opaque-keys | opaque_keys/edx/locations.py | LocationBase._check_location_part | def _check_location_part(cls, val, regexp):
"""Deprecated. See CourseLocator._check_location_part"""
cls._deprecation_warning()
return CourseLocator._check_location_part(val, regexp) | python | def _check_location_part(cls, val, regexp):
"""Deprecated. See CourseLocator._check_location_part"""
cls._deprecation_warning()
return CourseLocator._check_location_part(val, regexp) | Deprecated. See CourseLocator._check_location_part | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L116-L119 |
edx/opaque-keys | opaque_keys/edx/locations.py | LocationBase._clean | def _clean(cls, value, invalid):
"""Deprecated. See BlockUsageLocator._clean"""
cls._deprecation_warning()
return BlockUsageLocator._clean(value, invalid) | python | def _clean(cls, value, invalid):
"""Deprecated. See BlockUsageLocator._clean"""
cls._deprecation_warning()
return BlockUsageLocator._clean(value, invalid) | Deprecated. See BlockUsageLocator._clean | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L122-L125 |
edx/opaque-keys | opaque_keys/edx/locations.py | LocationBase._from_deprecated_son | def _from_deprecated_son(cls, id_dict, run):
"""Deprecated. See BlockUsageLocator._from_deprecated_son"""
cls._deprecation_warning()
return BlockUsageLocator._from_deprecated_son(id_dict, run) | python | def _from_deprecated_son(cls, id_dict, run):
"""Deprecated. See BlockUsageLocator._from_deprecated_son"""
cls._deprecation_warning()
return BlockUsageLocator._from_deprecated_son(id_dict, run) | Deprecated. See BlockUsageLocator._from_deprecated_son | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L176-L179 |
edx/opaque-keys | opaque_keys/edx/locations.py | Location.replace | def replace(self, **kwargs):
"""
Return: a new :class:`Location` with specific ``kwargs`` replacing
their corresponding values.
Using BlockUsageLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate a Location object wi... | python | def replace(self, **kwargs):
"""
Return: a new :class:`Location` with specific ``kwargs`` replacing
their corresponding values.
Using BlockUsageLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate a Location object wi... | Return: a new :class:`Location` with specific ``kwargs`` replacing
their corresponding values.
Using BlockUsageLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate a Location object with BlockUsageLocator's args and kwargs. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L187-L204 |
edx/opaque-keys | opaque_keys/edx/locations.py | DeprecatedLocation._from_string | def _from_string(cls, serialized):
"""
see super
"""
# Allow access to _from_string protected method
parsed_parts = cls.parse_url(serialized)
course_key = CourseLocator(
parsed_parts.get('org'), parsed_parts.get('course'), parsed_parts.get('run'),
... | python | def _from_string(cls, serialized):
"""
see super
"""
# Allow access to _from_string protected method
parsed_parts = cls.parse_url(serialized)
course_key = CourseLocator(
parsed_parts.get('org'), parsed_parts.get('course'), parsed_parts.get('run'),
... | see super | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L230-L241 |
edx/opaque-keys | opaque_keys/edx/locations.py | DeprecatedLocation._to_string | def _to_string(self):
"""
Return a string representing this location.
"""
parts = [self.org, self.course, self.run, self.block_type, self.block_id]
return u"+".join(parts) | python | def _to_string(self):
"""
Return a string representing this location.
"""
parts = [self.org, self.course, self.run, self.block_type, self.block_id]
return u"+".join(parts) | Return a string representing this location. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L243-L248 |
edx/opaque-keys | opaque_keys/edx/locations.py | AssetLocation.replace | def replace(self, **kwargs):
"""
Return: a new :class:`AssetLocation` with specific ``kwargs`` replacing
their corresponding values.
Using AssetLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate an AssetLocation obj... | python | def replace(self, **kwargs):
"""
Return: a new :class:`AssetLocation` with specific ``kwargs`` replacing
their corresponding values.
Using AssetLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate an AssetLocation obj... | Return: a new :class:`AssetLocation` with specific ``kwargs`` replacing
their corresponding values.
Using AssetLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate an AssetLocation object with AssetLocators args and kwargs. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L256-L273 |
edx/opaque-keys | opaque_keys/edx/locations.py | AssetLocation._from_deprecated_son | def _from_deprecated_son(cls, id_dict, run):
"""Deprecated. See BlockUsageLocator._from_deprecated_son"""
cls._deprecation_warning()
return AssetLocator._from_deprecated_son(id_dict, run) | python | def _from_deprecated_son(cls, id_dict, run):
"""Deprecated. See BlockUsageLocator._from_deprecated_son"""
cls._deprecation_warning()
return AssetLocator._from_deprecated_son(id_dict, run) | Deprecated. See BlockUsageLocator._from_deprecated_son | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L282-L285 |
edx/opaque-keys | opaque_keys/edx/block_types.py | BlockTypeKeyV1._from_string | def _from_string(cls, serialized):
"""
Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKe... | python | def _from_string(cls, serialized):
"""
Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKe... | Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKeyError: Should be raised if `serialized` is not a valid... | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/block_types.py#L40-L56 |
edx/opaque-keys | opaque_keys/edx/asides.py | _decode_v1 | def _decode_v1(value):
"""
Decode '::' and '$' characters encoded by `_encode`.
"""
decode_colons = value.replace('$::', '::')
decode_dollars = decode_colons.replace('$$', '$')
reencoded = _encode_v1(decode_dollars)
if reencoded != value:
raise ValueError('Ambiguous encoded value, {... | python | def _decode_v1(value):
"""
Decode '::' and '$' characters encoded by `_encode`.
"""
decode_colons = value.replace('$::', '::')
decode_dollars = decode_colons.replace('$$', '$')
reencoded = _encode_v1(decode_dollars)
if reencoded != value:
raise ValueError('Ambiguous encoded value, {... | Decode '::' and '$' characters encoded by `_encode`. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L35-L46 |
edx/opaque-keys | opaque_keys/edx/asides.py | _join_keys_v1 | def _join_keys_v1(left, right):
"""
Join two keys into a format separable by using _split_keys_v1.
"""
if left.endswith(':') or '::' in left:
raise ValueError("Can't join a left string ending in ':' or containing '::'")
return u"{}::{}".format(_encode_v1(left), _encode_v1(right)) | python | def _join_keys_v1(left, right):
"""
Join two keys into a format separable by using _split_keys_v1.
"""
if left.endswith(':') or '::' in left:
raise ValueError("Can't join a left string ending in ':' or containing '::'")
return u"{}::{}".format(_encode_v1(left), _encode_v1(right)) | Join two keys into a format separable by using _split_keys_v1. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L49-L55 |
edx/opaque-keys | opaque_keys/edx/asides.py | _split_keys_v1 | def _split_keys_v1(joined):
"""
Split two keys out a string created by _join_keys_v1.
"""
left, _, right = joined.partition('::')
return _decode_v1(left), _decode_v1(right) | python | def _split_keys_v1(joined):
"""
Split two keys out a string created by _join_keys_v1.
"""
left, _, right = joined.partition('::')
return _decode_v1(left), _decode_v1(right) | Split two keys out a string created by _join_keys_v1. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L58-L63 |
edx/opaque-keys | opaque_keys/edx/asides.py | _decode_v2 | def _decode_v2(value):
"""
Decode ':' and '$' characters encoded by `_encode`.
"""
if re.search(r'(?<!\$):', value):
raise ValueError("Unescaped ':' in the encoded string")
decode_colons = value.replace('$:', ':')
if re.search(r'(?<!\$)(\$\$)*\$([^$]|\Z)', decode_colons):
raise... | python | def _decode_v2(value):
"""
Decode ':' and '$' characters encoded by `_encode`.
"""
if re.search(r'(?<!\$):', value):
raise ValueError("Unescaped ':' in the encoded string")
decode_colons = value.replace('$:', ':')
if re.search(r'(?<!\$)(\$\$)*\$([^$]|\Z)', decode_colons):
raise... | Decode ':' and '$' characters encoded by `_encode`. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L76-L87 |
edx/opaque-keys | opaque_keys/edx/asides.py | _split_keys_v2 | def _split_keys_v2(joined):
"""
Split two keys out a string created by _join_keys_v2.
"""
left, _, right = joined.rpartition('::')
return _decode_v2(left), _decode_v2(right) | python | def _split_keys_v2(joined):
"""
Split two keys out a string created by _join_keys_v2.
"""
left, _, right = joined.rpartition('::')
return _decode_v2(left), _decode_v2(right) | Split two keys out a string created by _join_keys_v2. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L97-L102 |
edx/opaque-keys | opaque_keys/edx/asides.py | AsideDefinitionKeyV2.replace | def replace(self, **kwargs):
"""
Return: a new :class:`AsideDefinitionKeyV2` with ``KEY_FIELDS`` specified in ``kwargs`` replaced
with their corresponding values. Deprecation value is also preserved.
"""
if 'definition_key' in kwargs:
for attr in self.DEFINITION_K... | python | def replace(self, **kwargs):
"""
Return: a new :class:`AsideDefinitionKeyV2` with ``KEY_FIELDS`` specified in ``kwargs`` replaced
with their corresponding values. Deprecation value is also preserved.
"""
if 'definition_key' in kwargs:
for attr in self.DEFINITION_K... | Return: a new :class:`AsideDefinitionKeyV2` with ``KEY_FIELDS`` specified in ``kwargs`` replaced
with their corresponding values. Deprecation value is also preserved. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L124-L139 |
edx/opaque-keys | opaque_keys/edx/asides.py | AsideDefinitionKeyV2._from_string | def _from_string(cls, serialized):
"""
Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKe... | python | def _from_string(cls, serialized):
"""
Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKe... | Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKeyError: Should be raised if `serialized` is not a valid... | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L142-L158 |
edx/opaque-keys | opaque_keys/edx/asides.py | AsideUsageKeyV2.map_into_course | def map_into_course(self, course_key):
"""
Return a new :class:`UsageKey` or :class:`AssetKey` representing this usage inside the
course identified by the supplied :class:`CourseKey`. It returns the same type as
`self`
Args:
course_key (:class:`CourseKey`): The cours... | python | def map_into_course(self, course_key):
"""
Return a new :class:`UsageKey` or :class:`AssetKey` representing this usage inside the
course identified by the supplied :class:`CourseKey`. It returns the same type as
`self`
Args:
course_key (:class:`CourseKey`): The cours... | Return a new :class:`UsageKey` or :class:`AssetKey` representing this usage inside the
course identified by the supplied :class:`CourseKey`. It returns the same type as
`self`
Args:
course_key (:class:`CourseKey`): The course to map this object into.
Returns:
A ... | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L243-L255 |
edx/opaque-keys | opaque_keys/edx/asides.py | AsideUsageKeyV2.replace | def replace(self, **kwargs):
"""
Return: a new :class:`AsideUsageKeyV2` with ``KEY_FIELDS`` specified in ``kwargs`` replaced
with their corresponding values. Deprecation value is also preserved.
"""
if 'usage_key' in kwargs:
for attr in self.USAGE_KEY_ATTRS:
... | python | def replace(self, **kwargs):
"""
Return: a new :class:`AsideUsageKeyV2` with ``KEY_FIELDS`` specified in ``kwargs`` replaced
with their corresponding values. Deprecation value is also preserved.
"""
if 'usage_key' in kwargs:
for attr in self.USAGE_KEY_ATTRS:
... | Return: a new :class:`AsideUsageKeyV2` with ``KEY_FIELDS`` specified in ``kwargs`` replaced
with their corresponding values. Deprecation value is also preserved. | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L257-L272 |
edx/opaque-keys | opaque_keys/edx/asides.py | AsideUsageKeyV1._from_string | def _from_string(cls, serialized):
"""
Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKe... | python | def _from_string(cls, serialized):
"""
Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKe... | Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKeyError: Should be raised if `serialized` is not a valid... | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L315-L331 |
dbcli/athenacli | athenacli/completion_refresher.py | refresher | def refresher(name, refreshers=CompletionRefresher.refreshers):
"""Decorator to add the decorated function to the dictionary of
refreshers. Any function decorated with a @refresher will be executed as
part of the completion refresh routine."""
def wrapper(wrapped):
refreshers[name] = wrapped
... | python | def refresher(name, refreshers=CompletionRefresher.refreshers):
"""Decorator to add the decorated function to the dictionary of
refreshers. Any function decorated with a @refresher will be executed as
part of the completion refresh routine."""
def wrapper(wrapped):
refreshers[name] = wrapped
... | Decorator to add the decorated function to the dictionary of
refreshers. Any function decorated with a @refresher will be executed as
part of the completion refresh routine. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completion_refresher.py#L86-L93 |
dbcli/athenacli | athenacli/completion_refresher.py | CompletionRefresher.refresh | def refresh(self, executor, callbacks, completer_options=None):
"""Creates a SQLCompleter object and populates it with the relevant
completion suggestions in a background thread.
executor - SQLExecute object, used to extract the credentials to connect
to the database.
... | python | def refresh(self, executor, callbacks, completer_options=None):
"""Creates a SQLCompleter object and populates it with the relevant
completion suggestions in a background thread.
executor - SQLExecute object, used to extract the credentials to connect
to the database.
... | Creates a SQLCompleter object and populates it with the relevant
completion suggestions in a background thread.
executor - SQLExecute object, used to extract the credentials to connect
to the database.
callbacks - A function or a list of functions to call after the thread
... | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completion_refresher.py#L20-L45 |
dbcli/athenacli | athenacli/packages/special/utils.py | handle_cd_command | def handle_cd_command(arg):
"""Handles a `cd` shell command by calling python's os.chdir."""
CD_CMD = 'cd'
tokens = arg.split(CD_CMD + ' ')
directory = tokens[-1] if len(tokens) > 1 else None
if not directory:
return False, "No folder name was provided."
try:
os.chdir(directory)
... | python | def handle_cd_command(arg):
"""Handles a `cd` shell command by calling python's os.chdir."""
CD_CMD = 'cd'
tokens = arg.split(CD_CMD + ' ')
directory = tokens[-1] if len(tokens) > 1 else None
if not directory:
return False, "No folder name was provided."
try:
os.chdir(directory)
... | Handles a `cd` shell command by calling python's os.chdir. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/utils.py#L5-L17 |
dbcli/athenacli | athenacli/packages/special/utils.py | format_uptime | def format_uptime(uptime_in_seconds):
"""Format number of seconds into human-readable string.
:param uptime_in_seconds: The server uptime in seconds.
:returns: A human-readable string representing the uptime.
>>> uptime = format_uptime('56892')
>>> print(uptime)
15 hours 48 min 12 sec
"""
... | python | def format_uptime(uptime_in_seconds):
"""Format number of seconds into human-readable string.
:param uptime_in_seconds: The server uptime in seconds.
:returns: A human-readable string representing the uptime.
>>> uptime = format_uptime('56892')
>>> print(uptime)
15 hours 48 min 12 sec
"""
... | Format number of seconds into human-readable string.
:param uptime_in_seconds: The server uptime in seconds.
:returns: A human-readable string representing the uptime.
>>> uptime = format_uptime('56892')
>>> print(uptime)
15 hours 48 min 12 sec | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/utils.py#L20-L46 |
dbcli/athenacli | athenacli/packages/special/iocommands.py | get_editor_query | def get_editor_query(sql):
"""Get the query part of an editor command."""
sql = sql.strip()
# The reason we can't simply do .strip('\e') is that it strips characters,
# not a substring. So it'll strip "e" in the end of the sql also!
# Ex: "select * from style\e" -> "select * from styl".
pattern... | python | def get_editor_query(sql):
"""Get the query part of an editor command."""
sql = sql.strip()
# The reason we can't simply do .strip('\e') is that it strips characters,
# not a substring. So it'll strip "e" in the end of the sql also!
# Ex: "select * from style\e" -> "select * from styl".
pattern... | Get the query part of an editor command. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L108-L119 |
dbcli/athenacli | athenacli/packages/special/iocommands.py | open_external_editor | def open_external_editor(filename=None, sql=None):
"""Open external editor, wait for the user to type in their query, return
the query.
:return: list with one tuple, query as first element.
"""
message = None
filename = filename.strip().split(' ', 1)[0] if filename else None
sql = sql or '... | python | def open_external_editor(filename=None, sql=None):
"""Open external editor, wait for the user to type in their query, return
the query.
:return: list with one tuple, query as first element.
"""
message = None
filename = filename.strip().split(' ', 1)[0] if filename else None
sql = sql or '... | Open external editor, wait for the user to type in their query, return
the query.
:return: list with one tuple, query as first element. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L123-L154 |
dbcli/athenacli | athenacli/packages/special/iocommands.py | execute_favorite_query | def execute_favorite_query(cur, arg, **_):
"""Returns (title, rows, headers, status)"""
if arg == '':
for result in list_favorite_queries():
yield result
"""Parse out favorite name and optional substitution parameters"""
name, _, arg_str = arg.partition(' ')
args = shlex.split(a... | python | def execute_favorite_query(cur, arg, **_):
"""Returns (title, rows, headers, status)"""
if arg == '':
for result in list_favorite_queries():
yield result
"""Parse out favorite name and optional substitution parameters"""
name, _, arg_str = arg.partition(' ')
args = shlex.split(a... | Returns (title, rows, headers, status) | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L158-L186 |
dbcli/athenacli | athenacli/packages/special/iocommands.py | list_favorite_queries | def list_favorite_queries():
"""List of all favorite queries.
Returns (title, rows, headers, status)"""
headers = ["Name", "Query"]
rows = [(r, favoritequeries.get(r)) for r in favoritequeries.list()]
if not rows:
status = '\nNo favorite queries found.' + favoritequeries.usage
else:
... | python | def list_favorite_queries():
"""List of all favorite queries.
Returns (title, rows, headers, status)"""
headers = ["Name", "Query"]
rows = [(r, favoritequeries.get(r)) for r in favoritequeries.list()]
if not rows:
status = '\nNo favorite queries found.' + favoritequeries.usage
else:
... | List of all favorite queries.
Returns (title, rows, headers, status) | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L188-L199 |
dbcli/athenacli | athenacli/packages/special/iocommands.py | subst_favorite_query_args | def subst_favorite_query_args(query, args):
"""replace positional parameters ($1...$N) in query."""
for idx, val in enumerate(args):
subst_var = '$' + str(idx + 1)
if subst_var not in query:
return [None, 'query does not have substitution parameter ' + subst_var + ':\n ' + query]
... | python | def subst_favorite_query_args(query, args):
"""replace positional parameters ($1...$N) in query."""
for idx, val in enumerate(args):
subst_var = '$' + str(idx + 1)
if subst_var not in query:
return [None, 'query does not have substitution parameter ' + subst_var + ':\n ' + query]
... | replace positional parameters ($1...$N) in query. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L202-L215 |
dbcli/athenacli | athenacli/packages/special/iocommands.py | save_favorite_query | def save_favorite_query(arg, **_):
"""Save a new favorite query.
Returns (title, rows, headers, status)"""
usage = 'Syntax: \\fs name query.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)]
name, _, query = arg.partition(' ')
# If either name or query is mis... | python | def save_favorite_query(arg, **_):
"""Save a new favorite query.
Returns (title, rows, headers, status)"""
usage = 'Syntax: \\fs name query.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)]
name, _, query = arg.partition(' ')
# If either name or query is mis... | Save a new favorite query.
Returns (title, rows, headers, status) | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L219-L235 |
dbcli/athenacli | athenacli/packages/special/iocommands.py | delete_favorite_query | def delete_favorite_query(arg, **_):
"""Delete an existing favorite query.
"""
usage = 'Syntax: \\fd name.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)]
status = favoritequeries.delete(arg)
return [(None, None, None, status)] | python | def delete_favorite_query(arg, **_):
"""Delete an existing favorite query.
"""
usage = 'Syntax: \\fd name.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)]
status = favoritequeries.delete(arg)
return [(None, None, None, status)] | Delete an existing favorite query. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L239-L248 |
dbcli/athenacli | athenacli/packages/special/iocommands.py | execute_system_command | def execute_system_command(arg, **_):
"""Execute a system shell command."""
usage = "Syntax: system [command].\n"
if not arg:
return [(None, None, None, usage)]
try:
command = arg.strip()
if command.startswith('cd'):
ok, error_message = handle_cd_command(arg)
... | python | def execute_system_command(arg, **_):
"""Execute a system shell command."""
usage = "Syntax: system [command].\n"
if not arg:
return [(None, None, None, usage)]
try:
command = arg.strip()
if command.startswith('cd'):
ok, error_message = handle_cd_command(arg)
... | Execute a system shell command. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L253-L280 |
dbcli/athenacli | athenacli/main.py | need_completion_refresh | def need_completion_refresh(queries):
"""Determines if the completion needs a refresh by checking if the sql
statement is an alter, create, drop or change db."""
tokens = {
'use', '\\u',
'create',
'drop'
}
for query in sqlparse.split(queries):
try:
first_... | python | def need_completion_refresh(queries):
"""Determines if the completion needs a refresh by checking if the sql
statement is an alter, create, drop or change db."""
tokens = {
'use', '\\u',
'create',
'drop'
}
for query in sqlparse.split(queries):
try:
first_... | Determines if the completion needs a refresh by checking if the sql
statement is an alter, create, drop or change db. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L607-L622 |
dbcli/athenacli | athenacli/main.py | is_mutating | def is_mutating(status):
"""Determines if the statement is mutating based on the status."""
if not status:
return False
mutating = set(['insert', 'update', 'delete', 'alter', 'create', 'drop',
'replace', 'truncate', 'load'])
return status.split(None, 1)[0].lower() in mutatin... | python | def is_mutating(status):
"""Determines if the statement is mutating based on the status."""
if not status:
return False
mutating = set(['insert', 'update', 'delete', 'alter', 'create', 'drop',
'replace', 'truncate', 'load'])
return status.split(None, 1)[0].lower() in mutatin... | Determines if the statement is mutating based on the status. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L625-L632 |
dbcli/athenacli | athenacli/main.py | cli | def cli(execute, region, aws_access_key_id, aws_secret_access_key,
s3_staging_dir, athenaclirc, profile, database):
'''A Athena terminal client with auto-completion and syntax highlighting.
\b
Examples:
- athenacli
- athenacli my_database
'''
if (athenaclirc == ATHENACLIRC) and ... | python | def cli(execute, region, aws_access_key_id, aws_secret_access_key,
s3_staging_dir, athenaclirc, profile, database):
'''A Athena terminal client with auto-completion and syntax highlighting.
\b
Examples:
- athenacli
- athenacli my_database
'''
if (athenaclirc == ATHENACLIRC) and ... | A Athena terminal client with auto-completion and syntax highlighting.
\b
Examples:
- athenacli
- athenacli my_database | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L643-L693 |
dbcli/athenacli | athenacli/main.py | AthenaCli.change_prompt_format | def change_prompt_format(self, arg, **_):
"""
Change the prompt format.
"""
if not arg:
message = 'Missing required argument, format.'
return [(None, None, None, message)]
self.prompt = self.get_prompt(arg)
return [(None, None, None, "Changed prom... | python | def change_prompt_format(self, arg, **_):
"""
Change the prompt format.
"""
if not arg:
message = 'Missing required argument, format.'
return [(None, None, None, message)]
self.prompt = self.get_prompt(arg)
return [(None, None, None, "Changed prom... | Change the prompt format. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L184-L193 |
dbcli/athenacli | athenacli/main.py | AthenaCli.handle_editor_command | def handle_editor_command(self, cli, document):
"""
Editor command is any query that is prefixed or suffixed
by a '\e'. The reason for a while loop is because a user
might edit a query multiple times.
For eg:
"select * from \e"<enter> to edit it in vim, then come
... | python | def handle_editor_command(self, cli, document):
"""
Editor command is any query that is prefixed or suffixed
by a '\e'. The reason for a while loop is because a user
might edit a query multiple times.
For eg:
"select * from \e"<enter> to edit it in vim, then come
... | Editor command is any query that is prefixed or suffixed
by a '\e'. The reason for a while loop is because a user
might edit a query multiple times.
For eg:
"select * from \e"<enter> to edit it in vim, then come
back to the prompt with the edited query "select * from
blah... | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L204-L234 |
dbcli/athenacli | athenacli/main.py | AthenaCli.run_query | def run_query(self, query, new_line=True):
"""Runs *query*."""
if (self.destructive_warning and
confirm_destructive_query(query) is False):
message = 'Wise choice. Command execution stopped.'
click.echo(message)
return
results = self.sqlexecut... | python | def run_query(self, query, new_line=True):
"""Runs *query*."""
if (self.destructive_warning and
confirm_destructive_query(query) is False):
message = 'Wise choice. Command execution stopped.'
click.echo(message)
return
results = self.sqlexecut... | Runs *query*. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L236-L250 |
dbcli/athenacli | athenacli/main.py | AthenaCli.get_output_margin | def get_output_margin(self, status=None):
"""Get the output margin (number of rows for the prompt, footer and
timing message."""
margin = self.get_reserved_space() + self.get_prompt(self.prompt).count('\n') + 1
if special.is_timing_enabled():
margin += 1
if status:
... | python | def get_output_margin(self, status=None):
"""Get the output margin (number of rows for the prompt, footer and
timing message."""
margin = self.get_reserved_space() + self.get_prompt(self.prompt).count('\n') + 1
if special.is_timing_enabled():
margin += 1
if status:
... | Get the output margin (number of rows for the prompt, footer and
timing message. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L362-L371 |
dbcli/athenacli | athenacli/main.py | AthenaCli.output | def output(self, output, status=None):
"""Output text to stdout or a pager command.
The status text is not outputted to pager or files.
The message will be logged in the audit log, if enabled. The
message will be written to the tee file, if enabled. The
message will be written to... | python | def output(self, output, status=None):
"""Output text to stdout or a pager command.
The status text is not outputted to pager or files.
The message will be logged in the audit log, if enabled. The
message will be written to the tee file, if enabled. The
message will be written to... | Output text to stdout or a pager command.
The status text is not outputted to pager or files.
The message will be logged in the audit log, if enabled. The
message will be written to the tee file, if enabled. The
message will be written to the output file, if enabled. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L373-L418 |
dbcli/athenacli | athenacli/main.py | AthenaCli._on_completions_refreshed | def _on_completions_refreshed(self, new_completer):
"""Swap the completer object in cli with the newly created completer.
"""
with self._completer_lock:
self.completer = new_completer
# When cli is first launched we call refresh_completions before
# instantiat... | python | def _on_completions_refreshed(self, new_completer):
"""Swap the completer object in cli with the newly created completer.
"""
with self._completer_lock:
self.completer = new_completer
# When cli is first launched we call refresh_completions before
# instantiat... | Swap the completer object in cli with the newly created completer. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L497-L511 |
dbcli/athenacli | athenacli/main.py | AthenaCli.get_reserved_space | def get_reserved_space(self):
"""Get the number of lines to reserve for the completion menu."""
reserved_space_ratio = .45
max_reserved_space = 8
_, height = click.get_terminal_size()
return min(int(round(height * reserved_space_ratio)), max_reserved_space) | python | def get_reserved_space(self):
"""Get the number of lines to reserve for the completion menu."""
reserved_space_ratio = .45
max_reserved_space = 8
_, height = click.get_terminal_size()
return min(int(round(height * reserved_space_ratio)), max_reserved_space) | Get the number of lines to reserve for the completion menu. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L595-L600 |
dbcli/athenacli | athenacli/packages/filepaths.py | list_path | def list_path(root_dir):
"""List directory if exists.
:param dir: str
:return: list
"""
res = []
if os.path.isdir(root_dir):
for name in os.listdir(root_dir):
res.append(name)
return res | python | def list_path(root_dir):
"""List directory if exists.
:param dir: str
:return: list
"""
res = []
if os.path.isdir(root_dir):
for name in os.listdir(root_dir):
res.append(name)
return res | List directory if exists.
:param dir: str
:return: list | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/filepaths.py#L5-L14 |
dbcli/athenacli | athenacli/packages/filepaths.py | complete_path | def complete_path(curr_dir, last_dir):
"""Return the path to complete that matches the last entered component.
If the last entered component is ~, expanded path would not
match, so return all of the available paths.
:param curr_dir: str
:param last_dir: str
:return: str
"""
if not last_d... | python | def complete_path(curr_dir, last_dir):
"""Return the path to complete that matches the last entered component.
If the last entered component is ~, expanded path would not
match, so return all of the available paths.
:param curr_dir: str
:param last_dir: str
:return: str
"""
if not last_d... | Return the path to complete that matches the last entered component.
If the last entered component is ~, expanded path would not
match, so return all of the available paths.
:param curr_dir: str
:param last_dir: str
:return: str | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/filepaths.py#L17-L28 |
dbcli/athenacli | athenacli/packages/filepaths.py | parse_path | def parse_path(root_dir):
"""Split path into head and last component for the completer.
Also return position where last component starts.
:param root_dir: str path
:return: tuple of (string, string, int)
"""
base_dir, last_dir, position = '', '', 0
if root_dir:
base_dir, last_dir = o... | python | def parse_path(root_dir):
"""Split path into head and last component for the completer.
Also return position where last component starts.
:param root_dir: str path
:return: tuple of (string, string, int)
"""
base_dir, last_dir, position = '', '', 0
if root_dir:
base_dir, last_dir = o... | Split path into head and last component for the completer.
Also return position where last component starts.
:param root_dir: str path
:return: tuple of (string, string, int) | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/filepaths.py#L31-L41 |
dbcli/athenacli | athenacli/packages/filepaths.py | suggest_path | def suggest_path(root_dir):
"""List all files and subdirectories in a directory.
If the directory is not specified, suggest root directory,
user directory, current and parent directory.
:param root_dir: string: directory to list
:return: list
"""
if not root_dir:
return [os.path.absp... | python | def suggest_path(root_dir):
"""List all files and subdirectories in a directory.
If the directory is not specified, suggest root directory,
user directory, current and parent directory.
:param root_dir: string: directory to list
:return: list
"""
if not root_dir:
return [os.path.absp... | List all files and subdirectories in a directory.
If the directory is not specified, suggest root directory,
user directory, current and parent directory.
:param root_dir: string: directory to list
:return: list | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/filepaths.py#L44-L60 |
dbcli/athenacli | athenacli/completer.py | AthenaCompleter.extend_relations | def extend_relations(self, data, kind):
"""Extend metadata for tables or views
:param data: list of (rel_name, ) tuples
:param kind: either 'tables' or 'views'
:return:
"""
# 'data' is a generator object. It can throw an exception while being
# consumed. This coul... | python | def extend_relations(self, data, kind):
"""Extend metadata for tables or views
:param data: list of (rel_name, ) tuples
:param kind: either 'tables' or 'views'
:return:
"""
# 'data' is a generator object. It can throw an exception while being
# consumed. This coul... | Extend metadata for tables or views
:param data: list of (rel_name, ) tuples
:param kind: either 'tables' or 'views'
:return: | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completer.py#L83-L107 |
dbcli/athenacli | athenacli/completer.py | AthenaCompleter.extend_columns | def extend_columns(self, column_data, kind):
"""Extend column metadata
:param column_data: list of (rel_name, column_name) tuples
:param kind: either 'tables' or 'views'
:return:
"""
# 'column_data' is a generator object. It can throw an exception while
# being co... | python | def extend_columns(self, column_data, kind):
"""Extend column metadata
:param column_data: list of (rel_name, column_name) tuples
:param kind: either 'tables' or 'views'
:return:
"""
# 'column_data' is a generator object. It can throw an exception while
# being co... | Extend column metadata
:param column_data: list of (rel_name, column_name) tuples
:param kind: either 'tables' or 'views'
:return: | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completer.py#L109-L127 |
dbcli/athenacli | athenacli/completer.py | AthenaCompleter.find_matches | def find_matches(text, collection, start_only=False, fuzzy=True, casing=None):
"""Find completion matches for the given text.
Given the user's input text and a collection of available
completions, find completions matching the last word of the
text.
If `start_only` is True, the t... | python | def find_matches(text, collection, start_only=False, fuzzy=True, casing=None):
"""Find completion matches for the given text.
Given the user's input text and a collection of available
completions, find completions matching the last word of the
text.
If `start_only` is True, the t... | Find completion matches for the given text.
Given the user's input text and a collection of available
completions, find completions matching the last word of the
text.
If `start_only` is True, the text will match an available
completion only at the beginning. Otherwise, a complet... | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completer.py#L157-L196 |
dbcli/athenacli | athenacli/completer.py | AthenaCompleter.find_files | def find_files(self, word):
"""Yield matching directory or file names.
:param word:
:return: iterable
"""
base_path, last_path, position = parse_path(word)
paths = suggest_path(word)
for name in sorted(paths):
suggestion = complete_path(name, last_path... | python | def find_files(self, word):
"""Yield matching directory or file names.
:param word:
:return: iterable
"""
base_path, last_path, position = parse_path(word)
paths = suggest_path(word)
for name in sorted(paths):
suggestion = complete_path(name, last_path... | Yield matching directory or file names.
:param word:
:return: iterable | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completer.py#L338-L348 |
dbcli/athenacli | athenacli/completer.py | AthenaCompleter.populate_scoped_cols | def populate_scoped_cols(self, scoped_tbls):
"""Find all columns in a set of scoped_tables
:param scoped_tbls: list of (schema, table, alias) tuples
:return: list of column names
"""
columns = []
meta = self.dbmetadata
for tbl in scoped_tbls:
# A full... | python | def populate_scoped_cols(self, scoped_tbls):
"""Find all columns in a set of scoped_tables
:param scoped_tbls: list of (schema, table, alias) tuples
:return: list of column names
"""
columns = []
meta = self.dbmetadata
for tbl in scoped_tbls:
# A full... | Find all columns in a set of scoped_tables
:param scoped_tbls: list of (schema, table, alias) tuples
:return: list of column names | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completer.py#L350-L386 |
dbcli/athenacli | athenacli/completer.py | AthenaCompleter.populate_schema_objects | def populate_schema_objects(self, schema, obj_type):
"""Returns list of tables or functions for a (optional) schema"""
metadata = self.dbmetadata[obj_type]
schema = schema or self.dbname
try:
objects = metadata[schema].keys()
except KeyError:
# schema doe... | python | def populate_schema_objects(self, schema, obj_type):
"""Returns list of tables or functions for a (optional) schema"""
metadata = self.dbmetadata[obj_type]
schema = schema or self.dbname
try:
objects = metadata[schema].keys()
except KeyError:
# schema doe... | Returns list of tables or functions for a (optional) schema | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completer.py#L388-L399 |
dbcli/athenacli | athenacli/config.py | log | def log(logger, level, message):
"""Logs message to stderr if logging isn't initialized."""
if logger.parent.name != 'root':
logger.log(level, message)
else:
print(message, file=sys.stderr) | python | def log(logger, level, message):
"""Logs message to stderr if logging isn't initialized."""
if logger.parent.name != 'root':
logger.log(level, message)
else:
print(message, file=sys.stderr) | Logs message to stderr if logging isn't initialized. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/config.py#L42-L48 |
dbcli/athenacli | athenacli/config.py | read_config_file | def read_config_file(f):
"""Read a config file."""
if isinstance(f, basestring):
f = os.path.expanduser(f)
try:
config = ConfigObj(f, interpolation=False, encoding='utf8')
except ConfigObjError as e:
log(LOGGER, logging.ERROR, "Unable to parse line {0} of config file "
... | python | def read_config_file(f):
"""Read a config file."""
if isinstance(f, basestring):
f = os.path.expanduser(f)
try:
config = ConfigObj(f, interpolation=False, encoding='utf8')
except ConfigObjError as e:
log(LOGGER, logging.ERROR, "Unable to parse line {0} of config file "
... | Read a config file. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/config.py#L51-L69 |
dbcli/athenacli | athenacli/config.py | read_config_files | def read_config_files(files):
"""Read and merge a list of config files."""
config = ConfigObj()
for _file in files:
_config = read_config_file(_file)
if bool(_config) is True:
config.merge(_config)
config.filename = _config.filename
return config | python | def read_config_files(files):
"""Read and merge a list of config files."""
config = ConfigObj()
for _file in files:
_config = read_config_file(_file)
if bool(_config) is True:
config.merge(_config)
config.filename = _config.filename
return config | Read and merge a list of config files. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/config.py#L72-L83 |
dbcli/athenacli | athenacli/key_bindings.py | cli_bindings | def cli_bindings():
"""
Custom key bindings for cli.
"""
key_binding_manager = KeyBindingManager(
enable_open_in_editor=True,
enable_system_bindings=True,
enable_auto_suggest_bindings=True,
enable_search=True,
enable_abort_and_exit_bindings=True)
@key_binding... | python | def cli_bindings():
"""
Custom key bindings for cli.
"""
key_binding_manager = KeyBindingManager(
enable_open_in_editor=True,
enable_system_bindings=True,
enable_auto_suggest_bindings=True,
enable_search=True,
enable_abort_and_exit_bindings=True)
@key_binding... | Custom key bindings for cli. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/key_bindings.py#L10-L89 |
dbcli/athenacli | athenacli/packages/prompt_utils.py | confirm_destructive_query | def confirm_destructive_query(queries):
"""Check if the query is destructive and prompts the user to confirm.
Returns:
* None if the query is non-destructive or we can't prompt the user.
* True if the query is destructive and the user wants to proceed.
* False if the query is destructive and the use... | python | def confirm_destructive_query(queries):
"""Check if the query is destructive and prompts the user to confirm.
Returns:
* None if the query is non-destructive or we can't prompt the user.
* True if the query is destructive and the user wants to proceed.
* False if the query is destructive and the use... | Check if the query is destructive and prompts the user to confirm.
Returns:
* None if the query is non-destructive or we can't prompt the user.
* True if the query is destructive and the user wants to proceed.
* False if the query is destructive and the user doesn't want to proceed. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/prompt_utils.py#L9-L19 |
dbcli/athenacli | athenacli/packages/prompt_utils.py | confirm | def confirm(*args, **kwargs):
"""Prompt for confirmation (yes/no) and handle any abort exceptions."""
try:
return click.confirm(*args, **kwargs)
except click.Abort:
return False | python | def confirm(*args, **kwargs):
"""Prompt for confirmation (yes/no) and handle any abort exceptions."""
try:
return click.confirm(*args, **kwargs)
except click.Abort:
return False | Prompt for confirmation (yes/no) and handle any abort exceptions. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/prompt_utils.py#L22-L27 |
dbcli/athenacli | athenacli/packages/prompt_utils.py | prompt | def prompt(*args, **kwargs):
"""Prompt the user for input and handle any abort exceptions."""
try:
return click.prompt(*args, **kwargs)
except click.Abort:
return False | python | def prompt(*args, **kwargs):
"""Prompt the user for input and handle any abort exceptions."""
try:
return click.prompt(*args, **kwargs)
except click.Abort:
return False | Prompt the user for input and handle any abort exceptions. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/prompt_utils.py#L30-L35 |
dbcli/athenacli | athenacli/clistyle.py | style_factory | def style_factory(name, cli_style):
"""Create a Pygments Style class based on the user's preferences.
:param str name: The name of a built-in Pygments style.
:param dict cli_style: The user's token-type style preferences.
"""
try:
style = pygments.styles.get_style_by_name(name)
except Cl... | python | def style_factory(name, cli_style):
"""Create a Pygments Style class based on the user's preferences.
:param str name: The name of a built-in Pygments style.
:param dict cli_style: The user's token-type style preferences.
"""
try:
style = pygments.styles.get_style_by_name(name)
except Cl... | Create a Pygments Style class based on the user's preferences.
:param str name: The name of a built-in Pygments style.
:param dict cli_style: The user's token-type style preferences. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/clistyle.py#L7-L26 |
dbcli/athenacli | athenacli/sqlexecute.py | SQLExecute.run | def run(self, statement):
'''Execute the sql in the database and return the results.
The results are a list of tuples. Each tuple has 4 values
(title, rows, headers, status).
'''
# Remove spaces and EOL
statement = statement.strip()
if not statement: # Empty str... | python | def run(self, statement):
'''Execute the sql in the database and return the results.
The results are a list of tuples. Each tuple has 4 values
(title, rows, headers, status).
'''
# Remove spaces and EOL
statement = statement.strip()
if not statement: # Empty str... | Execute the sql in the database and return the results.
The results are a list of tuples. Each tuple has 4 values
(title, rows, headers, status). | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/sqlexecute.py#L52-L82 |
dbcli/athenacli | athenacli/sqlexecute.py | SQLExecute.get_result | def get_result(self, cursor):
'''Get the current result's data from the cursor.'''
title = headers = None
# cursor.description is not None for queries that return result sets,
# e.g. SELECT or SHOW.
if cursor.description is not None:
headers = [x[0] for x in cursor.d... | python | def get_result(self, cursor):
'''Get the current result's data from the cursor.'''
title = headers = None
# cursor.description is not None for queries that return result sets,
# e.g. SELECT or SHOW.
if cursor.description is not None:
headers = [x[0] for x in cursor.d... | Get the current result's data from the cursor. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/sqlexecute.py#L84-L98 |
dbcli/athenacli | athenacli/sqlexecute.py | SQLExecute.tables | def tables(self):
'''Yields table names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLES_QUERY)
for row in cur:
yield row | python | def tables(self):
'''Yields table names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLES_QUERY)
for row in cur:
yield row | Yields table names. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/sqlexecute.py#L100-L105 |
dbcli/athenacli | athenacli/sqlexecute.py | SQLExecute.table_columns | def table_columns(self):
'''Yields column names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLE_COLUMNS_QUERY % self.database)
for row in cur:
yield row | python | def table_columns(self):
'''Yields column names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLE_COLUMNS_QUERY % self.database)
for row in cur:
yield row | Yields column names. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/sqlexecute.py#L107-L112 |
dbcli/athenacli | athenacli/clitoolbar.py | create_toolbar_tokens_func | def create_toolbar_tokens_func(get_is_refreshing, show_fish_help):
"""
Return a function that generates the toolbar tokens.
"""
token = Token.Toolbar
def get_toolbar_tokens(cli):
result = []
result.append((token, ' '))
if cli.buffers[DEFAULT_BUFFER].always_multiline:
... | python | def create_toolbar_tokens_func(get_is_refreshing, show_fish_help):
"""
Return a function that generates the toolbar tokens.
"""
token = Token.Toolbar
def get_toolbar_tokens(cli):
result = []
result.append((token, ' '))
if cli.buffers[DEFAULT_BUFFER].always_multiline:
... | Return a function that generates the toolbar tokens. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/clitoolbar.py#L6-L38 |
dbcli/athenacli | athenacli/clitoolbar.py | _get_vi_mode | def _get_vi_mode(cli):
"""Get the current vi mode for display."""
return {
InputMode.INSERT: 'I',
InputMode.NAVIGATION: 'N',
InputMode.REPLACE: 'R',
InputMode.INSERT_MULTIPLE: 'M'
}[cli.vi_state.input_mode] | python | def _get_vi_mode(cli):
"""Get the current vi mode for display."""
return {
InputMode.INSERT: 'I',
InputMode.NAVIGATION: 'N',
InputMode.REPLACE: 'R',
InputMode.INSERT_MULTIPLE: 'M'
}[cli.vi_state.input_mode] | Get the current vi mode for display. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/clitoolbar.py#L41-L48 |
dbcli/athenacli | athenacli/packages/completion_engine.py | suggest_type | def suggest_type(full_text, text_before_cursor):
"""Takes the full_text that is typed so far and also the text before the
cursor to suggest completion type and scope.
Returns a tuple with a type of entity ('table', 'column' etc) and a scope.
A scope for a column category will be a list of tables.
""... | python | def suggest_type(full_text, text_before_cursor):
"""Takes the full_text that is typed so far and also the text before the
cursor to suggest completion type and scope.
Returns a tuple with a type of entity ('table', 'column' etc) and a scope.
A scope for a column category will be a list of tables.
""... | Takes the full_text that is typed so far and also the text before the
cursor to suggest completion type and scope.
Returns a tuple with a type of entity ('table', 'column' etc) and a scope.
A scope for a column category will be a list of tables. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/completion_engine.py#L48-L121 |
dbcli/athenacli | athenacli/packages/special/__init__.py | export | def export(defn):
"""Decorator to explicitly mark functions that are exposed in a lib."""
globals()[defn.__name__] = defn
__all__.append(defn.__name__)
return defn | python | def export(defn):
"""Decorator to explicitly mark functions that are exposed in a lib."""
globals()[defn.__name__] = defn
__all__.append(defn.__name__)
return defn | Decorator to explicitly mark functions that are exposed in a lib. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/__init__.py#L5-L9 |
dbcli/athenacli | release.py | run_step | def run_step(*args, prompt=None):
"""
Prints out the command and asks if it should be run.
If yes (default), runs it.
:param args: list of strings (command and args)
"""
global DRY_RUN
cmd = args
print(' '.join(cmd))
if skip_step():
print('--- Skipping...')
elif DRY_RUN:... | python | def run_step(*args, prompt=None):
"""
Prints out the command and asks if it should be run.
If yes (default), runs it.
:param args: list of strings (command and args)
"""
global DRY_RUN
cmd = args
print(' '.join(cmd))
if skip_step():
print('--- Skipping...')
elif DRY_RUN:... | Prints out the command and asks if it should be run.
If yes (default), runs it.
:param args: list of strings (command and args) | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/release.py#L30-L47 |
dbcli/athenacli | athenacli/packages/special/main.py | execute | def execute(cur, sql):
"""Execute a special command and return the results. If the special command
is not supported a KeyError will be raised.
"""
command, verbose, arg = parse_special_command(sql)
if (command not in COMMANDS) and (command.lower() not in COMMANDS):
raise CommandNotFound
... | python | def execute(cur, sql):
"""Execute a special command and return the results. If the special command
is not supported a KeyError will be raised.
"""
command, verbose, arg = parse_special_command(sql)
if (command not in COMMANDS) and (command.lower() not in COMMANDS):
raise CommandNotFound
... | Execute a special command and return the results. If the special command
is not supported a KeyError will be raised. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/main.py#L51-L76 |
dbcli/athenacli | athenacli/packages/special/main.py | show_keyword_help | def show_keyword_help(cur, arg):
"""
Call the built-in "show <command>", to display help for an SQL keyword.
:param cur: cursor
:param arg: string
:return: list
"""
keyword = arg.strip('"').strip("'")
query = "help '{0}'".format(keyword)
log.debug(query)
cur.execute(query)
if... | python | def show_keyword_help(cur, arg):
"""
Call the built-in "show <command>", to display help for an SQL keyword.
:param cur: cursor
:param arg: string
:return: list
"""
keyword = arg.strip('"').strip("'")
query = "help '{0}'".format(keyword)
log.debug(query)
cur.execute(query)
if... | Call the built-in "show <command>", to display help for an SQL keyword.
:param cur: cursor
:param arg: string
:return: list | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/main.py#L88-L103 |
dbcli/athenacli | athenacli/packages/parseutils.py | last_word | def last_word(text, include='alphanum_underscore'):
"""
Find the last word in a sentence.
>>> last_word('abc')
'abc'
>>> last_word(' abc')
'abc'
>>> last_word('')
''
>>> last_word(' ')
''
>>> last_word('abc ')
''
>>> last_word('abc def')
'def'
>>> last_word('a... | python | def last_word(text, include='alphanum_underscore'):
"""
Find the last word in a sentence.
>>> last_word('abc')
'abc'
>>> last_word(' abc')
'abc'
>>> last_word('')
''
>>> last_word(' ')
''
>>> last_word('abc ')
''
>>> last_word('abc def')
'def'
>>> last_word('a... | Find the last word in a sentence.
>>> last_word('abc')
'abc'
>>> last_word(' abc')
'abc'
>>> last_word('')
''
>>> last_word(' ')
''
>>> last_word('abc ')
''
>>> last_word('abc def')
'def'
>>> last_word('abc def ')
''
>>> last_word('abc def;')
''
>>> la... | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/parseutils.py#L18-L60 |
dbcli/athenacli | athenacli/packages/parseutils.py | extract_table_identifiers | def extract_table_identifiers(token_stream):
"""yields tuples of (schema_name, table_name, table_alias)"""
for item in token_stream:
if isinstance(item, IdentifierList):
for identifier in item.get_identifiers():
# Sometimes Keywords (such as FROM ) are classified as
... | python | def extract_table_identifiers(token_stream):
"""yields tuples of (schema_name, table_name, table_alias)"""
for item in token_stream:
if isinstance(item, IdentifierList):
for identifier in item.get_identifiers():
# Sometimes Keywords (such as FROM ) are classified as
... | yields tuples of (schema_name, table_name, table_alias) | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/parseutils.py#L109-L134 |
dbcli/athenacli | athenacli/packages/parseutils.py | extract_tables | def extract_tables(sql):
"""Extract the table names from an SQL statment.
Returns a list of (schema, table, alias) tuples
"""
parsed = sqlparse.parse(sql)
if not parsed:
return []
# INSERT statements must stop looking for tables at the sign of first
# Punctuation. eg: INSERT INTO ab... | python | def extract_tables(sql):
"""Extract the table names from an SQL statment.
Returns a list of (schema, table, alias) tuples
"""
parsed = sqlparse.parse(sql)
if not parsed:
return []
# INSERT statements must stop looking for tables at the sign of first
# Punctuation. eg: INSERT INTO ab... | Extract the table names from an SQL statment.
Returns a list of (schema, table, alias) tuples | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/parseutils.py#L137-L151 |
dbcli/athenacli | athenacli/packages/parseutils.py | find_prev_keyword | def find_prev_keyword(sql):
""" Find the last sql keyword in an SQL statement
Returns the value of the last keyword, and the text of the query with
everything after the last keyword stripped
"""
if not sql.strip():
return None, ''
parsed = sqlparse.parse(sql)[0]
flattened = list(par... | python | def find_prev_keyword(sql):
""" Find the last sql keyword in an SQL statement
Returns the value of the last keyword, and the text of the query with
everything after the last keyword stripped
"""
if not sql.strip():
return None, ''
parsed = sqlparse.parse(sql)[0]
flattened = list(par... | Find the last sql keyword in an SQL statement
Returns the value of the last keyword, and the text of the query with
everything after the last keyword stripped | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/parseutils.py#L153-L184 |
dbcli/athenacli | athenacli/packages/parseutils.py | query_starts_with | def query_starts_with(query, prefixes):
"""Check if the query starts with any item from *prefixes*."""
prefixes = [prefix.lower() for prefix in prefixes]
formatted_sql = sqlparse.format(query.lower(), strip_comments=True)
return bool(formatted_sql) and formatted_sql.split()[0] in prefixes | python | def query_starts_with(query, prefixes):
"""Check if the query starts with any item from *prefixes*."""
prefixes = [prefix.lower() for prefix in prefixes]
formatted_sql = sqlparse.format(query.lower(), strip_comments=True)
return bool(formatted_sql) and formatted_sql.split()[0] in prefixes | Check if the query starts with any item from *prefixes*. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/parseutils.py#L187-L191 |
dbcli/athenacli | athenacli/packages/parseutils.py | queries_start_with | def queries_start_with(queries, prefixes):
"""Check if any queries start with any item from *prefixes*."""
for query in sqlparse.split(queries):
if query and query_starts_with(query, prefixes) is True:
return True
return False | python | def queries_start_with(queries, prefixes):
"""Check if any queries start with any item from *prefixes*."""
for query in sqlparse.split(queries):
if query and query_starts_with(query, prefixes) is True:
return True
return False | Check if any queries start with any item from *prefixes*. | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/parseutils.py#L194-L199 |
divio/cmsplugin-filer | cmsplugin_filer_teaser/cms_plugins.py | FilerTeaserPlugin._get_thumbnail_options | def _get_thumbnail_options(self, context, instance):
"""
Return the size and options of the thumbnail that should be inserted
"""
width, height = None, None
subject_location = False
placeholder_width = context.get('width', None)
placeholder_height = context.get('h... | python | def _get_thumbnail_options(self, context, instance):
"""
Return the size and options of the thumbnail that should be inserted
"""
width, height = None, None
subject_location = False
placeholder_width = context.get('width', None)
placeholder_height = context.get('h... | Return the size and options of the thumbnail that should be inserted | https://github.com/divio/cmsplugin-filer/blob/4f9b0307dd768852ead64e651b743a165b3efccb/cmsplugin_filer_teaser/cms_plugins.py#L42-L75 |
divio/cmsplugin-filer | cmsplugin_filer_image/integrations/ckeditor.py | create_image_plugin | def create_image_plugin(filename, image, parent_plugin, **kwargs):
"""
Used for drag-n-drop image insertion with djangocms-text-ckeditor.
Set TEXT_SAVE_IMAGE_FUNCTION='cmsplugin_filer_image.integrations.ckeditor.create_image_plugin' to enable.
"""
from cmsplugin_filer_image.models import FilerImage
... | python | def create_image_plugin(filename, image, parent_plugin, **kwargs):
"""
Used for drag-n-drop image insertion with djangocms-text-ckeditor.
Set TEXT_SAVE_IMAGE_FUNCTION='cmsplugin_filer_image.integrations.ckeditor.create_image_plugin' to enable.
"""
from cmsplugin_filer_image.models import FilerImage
... | Used for drag-n-drop image insertion with djangocms-text-ckeditor.
Set TEXT_SAVE_IMAGE_FUNCTION='cmsplugin_filer_image.integrations.ckeditor.create_image_plugin' to enable. | https://github.com/divio/cmsplugin-filer/blob/4f9b0307dd768852ead64e651b743a165b3efccb/cmsplugin_filer_image/integrations/ckeditor.py#L6-L23 |
divio/cmsplugin-filer | cmsplugin_filer_utils/migration.py | rename_tables | def rename_tables(db, table_mapping, reverse=False):
"""
renames tables from source to destination name, if the source exists and the destination does
not exist yet.
"""
from django.db import connection
if reverse:
table_mapping = [(dst, src) for src, dst in table_mapping]
table_name... | python | def rename_tables(db, table_mapping, reverse=False):
"""
renames tables from source to destination name, if the source exists and the destination does
not exist yet.
"""
from django.db import connection
if reverse:
table_mapping = [(dst, src) for src, dst in table_mapping]
table_name... | renames tables from source to destination name, if the source exists and the destination does
not exist yet. | https://github.com/divio/cmsplugin-filer/blob/4f9b0307dd768852ead64e651b743a165b3efccb/cmsplugin_filer_utils/migration.py#L4-L18 |
sorgerlab/indra | indra/util/statement_presentation.py | group_and_sort_statements | def group_and_sort_statements(stmt_list, ev_totals=None):
"""Group statements by type and arguments, and sort by prevalence.
Parameters
----------
stmt_list : list[Statement]
A list of INDRA statements.
ev_totals : dict{int: int}
A dictionary, keyed by statement hash (shallow) with ... | python | def group_and_sort_statements(stmt_list, ev_totals=None):
"""Group statements by type and arguments, and sort by prevalence.
Parameters
----------
stmt_list : list[Statement]
A list of INDRA statements.
ev_totals : dict{int: int}
A dictionary, keyed by statement hash (shallow) with ... | Group statements by type and arguments, and sort by prevalence.
Parameters
----------
stmt_list : list[Statement]
A list of INDRA statements.
ev_totals : dict{int: int}
A dictionary, keyed by statement hash (shallow) with counts of total
evidence as the values. Including this wi... | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/statement_presentation.py#L40-L109 |
sorgerlab/indra | indra/util/statement_presentation.py | make_stmt_from_sort_key | def make_stmt_from_sort_key(key, verb):
"""Make a Statement from the sort key.
Specifically, the sort key used by `group_and_sort_statements`.
"""
def make_agent(name):
if name == 'None' or name is None:
return None
return Agent(name)
StmtClass = get_statement_by_name(v... | python | def make_stmt_from_sort_key(key, verb):
"""Make a Statement from the sort key.
Specifically, the sort key used by `group_and_sort_statements`.
"""
def make_agent(name):
if name == 'None' or name is None:
return None
return Agent(name)
StmtClass = get_statement_by_name(v... | Make a Statement from the sort key.
Specifically, the sort key used by `group_and_sort_statements`. | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/statement_presentation.py#L112-L134 |
sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | wait_for_complete | def wait_for_complete(queue_name, job_list=None, job_name_prefix=None,
poll_interval=10, idle_log_timeout=None,
kill_on_log_timeout=False, stash_log_method=None,
tag_instances=False, result_record=None):
"""Return when all jobs in the given list fini... | python | def wait_for_complete(queue_name, job_list=None, job_name_prefix=None,
poll_interval=10, idle_log_timeout=None,
kill_on_log_timeout=False, stash_log_method=None,
tag_instances=False, result_record=None):
"""Return when all jobs in the given list fini... | Return when all jobs in the given list finished.
If not job list is given, return when all jobs in queue finished.
Parameters
----------
queue_name : str
The name of the queue to wait for completion.
job_list : Optional[list(dict)]
A list of jobID-s in a dict, as returned by the su... | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L22-L208 |
sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | get_ecs_cluster_for_queue | def get_ecs_cluster_for_queue(queue_name, batch_client=None):
"""Get the name of the ecs cluster using the batch client."""
if batch_client is None:
batch_client = boto3.client('batch')
queue_resp = batch_client.describe_job_queues(jobQueues=[queue_name])
if len(queue_resp['jobQueues']) == 1:
... | python | def get_ecs_cluster_for_queue(queue_name, batch_client=None):
"""Get the name of the ecs cluster using the batch client."""
if batch_client is None:
batch_client = boto3.client('batch')
queue_resp = batch_client.describe_job_queues(jobQueues=[queue_name])
if len(queue_resp['jobQueues']) == 1:
... | Get the name of the ecs cluster using the batch client. | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L275-L306 |
sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | tag_instances_on_cluster | def tag_instances_on_cluster(cluster_name, project='cwc'):
"""Adds project tag to untagged instances in a given cluster.
Parameters
----------
cluster_name : str
The name of the AWS ECS cluster in which running instances
should be tagged.
project : str
The name of the projec... | python | def tag_instances_on_cluster(cluster_name, project='cwc'):
"""Adds project tag to untagged instances in a given cluster.
Parameters
----------
cluster_name : str
The name of the AWS ECS cluster in which running instances
should be tagged.
project : str
The name of the projec... | Adds project tag to untagged instances in a given cluster.
Parameters
----------
cluster_name : str
The name of the AWS ECS cluster in which running instances
should be tagged.
project : str
The name of the project to tag instances with. | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L309-L335 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.