partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
AuthModelMethodsMixin.get_authuser_by_name
Get user by username Used by Token-based auth. Is added as request method to populate `request.user`.
nefertari/authentication/models.py
def get_authuser_by_name(cls, request): """ Get user by username Used by Token-based auth. Is added as request method to populate `request.user`. """ username = authenticated_userid(request) if username: return cls.get_item(username=username)
def get_authuser_by_name(cls, request): """ Get user by username Used by Token-based auth. Is added as request method to populate `request.user`. """ username = authenticated_userid(request) if username: return cls.get_item(username=username)
[ "Get", "user", "by", "username" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L140-L148
[ "def", "get_authuser_by_name", "(", "cls", ",", "request", ")", ":", "username", "=", "authenticated_userid", "(", "request", ")", "if", "username", ":", "return", "cls", ".", "get_item", "(", "username", "=", "username", ")" ]
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
Dir.walk
Walk the directory like os.path (yields a 3-tuple (dirpath, dirnames, filenames) except it exclude all files/directories on the fly.
dirtools.py
def walk(self): """ Walk the directory like os.path (yields a 3-tuple (dirpath, dirnames, filenames) except it exclude all files/directories on the fly. """ for root, dirs, files in os.walk(self.path, topdown=True): # TODO relative walk, recursive call if root excluder found?...
def walk(self): """ Walk the directory like os.path (yields a 3-tuple (dirpath, dirnames, filenames) except it exclude all files/directories on the fly. """ for root, dirs, files in os.walk(self.path, topdown=True): # TODO relative walk, recursive call if root excluder found?...
[ "Walk", "the", "directory", "like", "os", ".", "path", "(", "yields", "a", "3", "-", "tuple", "(", "dirpath", "dirnames", "filenames", ")", "except", "it", "exclude", "all", "files", "/", "directories", "on", "the", "fly", "." ]
tsileo/dirtools
python
https://github.com/tsileo/dirtools/blob/34be55b20b4ef506869487b5fa5c6ea020604f80/dirtools.py#L245-L265
[ "def", "walk", "(", "self", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "self", ".", "path", ",", "topdown", "=", "True", ")", ":", "# TODO relative walk, recursive call if root excluder found???", "#root_excluder = get_root...
34be55b20b4ef506869487b5fa5c6ea020604f80
train
includeme
Set up event subscribers.
nefertari/authentication/__init__.py
def includeme(config): """ Set up event subscribers. """ from .models import ( AuthUserMixin, random_uuid, lower_strip, encrypt_password, ) add_proc = config.add_field_processors add_proc( [random_uuid, lower_strip], model=AuthUserMixin, field='usernam...
def includeme(config): """ Set up event subscribers. """ from .models import ( AuthUserMixin, random_uuid, lower_strip, encrypt_password, ) add_proc = config.add_field_processors add_proc( [random_uuid, lower_strip], model=AuthUserMixin, field='usernam...
[ "Set", "up", "event", "subscribers", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/__init__.py#L1-L14
[ "def", "includeme", "(", "config", ")", ":", "from", ".", "models", "import", "(", "AuthUserMixin", ",", "random_uuid", ",", "lower_strip", ",", "encrypt_password", ",", ")", "add_proc", "=", "config", ".", "add_field_processors", "add_proc", "(", "[", "random...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
SlackClient._make_request
Make request to API endpoint Note: Ignoring SSL cert validation due to intermittent failures http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification
pyslack/__init__.py
def _make_request(self, method, params): """Make request to API endpoint Note: Ignoring SSL cert validation due to intermittent failures http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification """ if self.blocked_until is not None and \ dat...
def _make_request(self, method, params): """Make request to API endpoint Note: Ignoring SSL cert validation due to intermittent failures http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification """ if self.blocked_until is not None and \ dat...
[ "Make", "request", "to", "API", "endpoint" ]
loisaidasam/pyslack
python
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L23-L49
[ "def", "_make_request", "(", "self", ",", "method", ",", "params", ")", ":", "if", "self", ".", "blocked_until", "is", "not", "None", "and", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "<", "self", ".", "blocked_until", ":", "raise", "SlackErro...
bce0dcbe830b95ba548b58c7ceea07923589a8ec
train
SlackClient.channels_list
channels.list This method returns a list of all channels in the team. This includes channels the caller is in, channels they are not currently in, and archived channels. The number of (non-deactivated) members in each channel is also returned. https://api.slack.com/methods/chan...
pyslack/__init__.py
def channels_list(self, exclude_archived=True, **params): """channels.list This method returns a list of all channels in the team. This includes channels the caller is in, channels they are not currently in, and archived channels. The number of (non-deactivated) members in each ...
def channels_list(self, exclude_archived=True, **params): """channels.list This method returns a list of all channels in the team. This includes channels the caller is in, channels they are not currently in, and archived channels. The number of (non-deactivated) members in each ...
[ "channels", ".", "list" ]
loisaidasam/pyslack
python
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L51-L63
[ "def", "channels_list", "(", "self", ",", "exclude_archived", "=", "True", ",", "*", "*", "params", ")", ":", "method", "=", "'channels.list'", "params", ".", "update", "(", "{", "'exclude_archived'", ":", "exclude_archived", "and", "1", "or", "0", "}", ")...
bce0dcbe830b95ba548b58c7ceea07923589a8ec
train
SlackClient.channel_name_to_id
Helper name for getting a channel's id from its name
pyslack/__init__.py
def channel_name_to_id(self, channel_name, force_lookup=False): """Helper name for getting a channel's id from its name """ if force_lookup or not self.channel_name_id_map: channels = self.channels_list()['channels'] self.channel_name_id_map = {channel['name']: channel['i...
def channel_name_to_id(self, channel_name, force_lookup=False): """Helper name for getting a channel's id from its name """ if force_lookup or not self.channel_name_id_map: channels = self.channels_list()['channels'] self.channel_name_id_map = {channel['name']: channel['i...
[ "Helper", "name", "for", "getting", "a", "channel", "s", "id", "from", "its", "name" ]
loisaidasam/pyslack
python
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L65-L72
[ "def", "channel_name_to_id", "(", "self", ",", "channel_name", ",", "force_lookup", "=", "False", ")", ":", "if", "force_lookup", "or", "not", "self", ".", "channel_name_id_map", ":", "channels", "=", "self", ".", "channels_list", "(", ")", "[", "'channels'", ...
bce0dcbe830b95ba548b58c7ceea07923589a8ec
train
SlackClient.chat_post_message
chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage
pyslack/__init__.py
def chat_post_message(self, channel, text, **params): """chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage """ method = 'chat.postMessage' params.update({ 'channel': channel, 'text': text, ...
def chat_post_message(self, channel, text, **params): """chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage """ method = 'chat.postMessage' params.update({ 'channel': channel, 'text': text, ...
[ "chat", ".", "postMessage" ]
loisaidasam/pyslack
python
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L74-L86
[ "def", "chat_post_message", "(", "self", ",", "channel", ",", "text", ",", "*", "*", "params", ")", ":", "method", "=", "'chat.postMessage'", "params", ".", "update", "(", "{", "'channel'", ":", "channel", ",", "'text'", ":", "text", ",", "}", ")", "re...
bce0dcbe830b95ba548b58c7ceea07923589a8ec
train
SlackClient.chat_update_message
chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default formatting rules. (e.g: "Hello world") `timestamp`: Timestamp of the me...
pyslack/__init__.py
def chat_update_message(self, channel, text, timestamp, **params): """chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default format...
def chat_update_message(self, channel, text, timestamp, **params): """chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default format...
[ "chat", ".", "update" ]
loisaidasam/pyslack
python
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L88-L109
[ "def", "chat_update_message", "(", "self", ",", "channel", ",", "text", ",", "timestamp", ",", "*", "*", "params", ")", ":", "method", "=", "'chat.update'", "if", "self", ".", "_channel_is_name", "(", "channel", ")", ":", "# chat.update only takes channel ids (n...
bce0dcbe830b95ba548b58c7ceea07923589a8ec
train
includeme
Connect view to route that catches all URIs like 'something,something,...'
nefertari/polymorphic.py
def includeme(config): """ Connect view to route that catches all URIs like 'something,something,...' """ root = config.get_root_resource() root.add('nef_polymorphic', '{collections:.+,.+}', view=PolymorphicESView, factory=PolymorphicACL)
def includeme(config): """ Connect view to route that catches all URIs like 'something,something,...' """ root = config.get_root_resource() root.add('nef_polymorphic', '{collections:.+,.+}', view=PolymorphicESView, factory=PolymorphicACL)
[ "Connect", "view", "to", "route", "that", "catches", "all", "URIs", "like", "something", "something", "..." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L37-L44
[ "def", "includeme", "(", "config", ")", ":", "root", "=", "config", ".", "get_root_resource", "(", ")", "root", ".", "add", "(", "'nef_polymorphic'", ",", "'{collections:.+,.+}'", ",", "view", "=", "PolymorphicESView", ",", "factory", "=", "PolymorphicACL", ")...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
PolymorphicHelperMixin.get_collections
Get names of collections from request matchdict. :return: Names of collections :rtype: list of str
nefertari/polymorphic.py
def get_collections(self): """ Get names of collections from request matchdict. :return: Names of collections :rtype: list of str """ collections = self.request.matchdict['collections'].split('/')[0] collections = [coll.strip() for coll in collections.split(',')] ...
def get_collections(self): """ Get names of collections from request matchdict. :return: Names of collections :rtype: list of str """ collections = self.request.matchdict['collections'].split('/')[0] collections = [coll.strip() for coll in collections.split(',')] ...
[ "Get", "names", "of", "collections", "from", "request", "matchdict", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L52-L60
[ "def", "get_collections", "(", "self", ")", ":", "collections", "=", "self", ".", "request", ".", "matchdict", "[", "'collections'", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", "collections", "=", "[", "coll", ".", "strip", "(", ")", "for", "c...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
PolymorphicHelperMixin.get_resources
Get resources that correspond to values from :collections:. :param collections: Collection names for which resources should be gathered :type collections: list of str :return: Gathered resources :rtype: list of Resource instances
nefertari/polymorphic.py
def get_resources(self, collections): """ Get resources that correspond to values from :collections:. :param collections: Collection names for which resources should be gathered :type collections: list of str :return: Gathered resources :rtype: list of Resource insta...
def get_resources(self, collections): """ Get resources that correspond to values from :collections:. :param collections: Collection names for which resources should be gathered :type collections: list of str :return: Gathered resources :rtype: list of Resource insta...
[ "Get", "resources", "that", "correspond", "to", "values", "from", ":", "collections", ":", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L62-L75
[ "def", "get_resources", "(", "self", ",", "collections", ")", ":", "res_map", "=", "self", ".", "request", ".", "registry", ".", "_model_collections", "resources", "=", "[", "res", "for", "res", "in", "res_map", ".", "values", "(", ")", "if", "res", ".",...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
PolymorphicACL._get_least_permissions_aces
Get ACEs with the least permissions that fit all resources. To have access to polymorph on N collections, user MUST have access to all of them. If this is true, ACEs are returned, that allows 'view' permissions to current request principals. Otherwise None is returned thus blocking all...
nefertari/polymorphic.py
def _get_least_permissions_aces(self, resources): """ Get ACEs with the least permissions that fit all resources. To have access to polymorph on N collections, user MUST have access to all of them. If this is true, ACEs are returned, that allows 'view' permissions to current request pri...
def _get_least_permissions_aces(self, resources): """ Get ACEs with the least permissions that fit all resources. To have access to polymorph on N collections, user MUST have access to all of them. If this is true, ACEs are returned, that allows 'view' permissions to current request pri...
[ "Get", "ACEs", "with", "the", "least", "permissions", "that", "fit", "all", "resources", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L89-L113
[ "def", "_get_least_permissions_aces", "(", "self", ",", "resources", ")", ":", "factories", "=", "[", "res", ".", "view", ".", "_factory", "for", "res", "in", "resources", "]", "contexts", "=", "[", "factory", "(", "self", ".", "request", ")", "for", "fa...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
PolymorphicACL.set_collections_acl
Calculate and set ACL valid for requested collections. DENY_ALL is added to ACL to make sure no access rules are inherited.
nefertari/polymorphic.py
def set_collections_acl(self): """ Calculate and set ACL valid for requested collections. DENY_ALL is added to ACL to make sure no access rules are inherited. """ acl = [(Allow, 'g:admin', ALL_PERMISSIONS)] collections = self.get_collections() resources = self.ge...
def set_collections_acl(self): """ Calculate and set ACL valid for requested collections. DENY_ALL is added to ACL to make sure no access rules are inherited. """ acl = [(Allow, 'g:admin', ALL_PERMISSIONS)] collections = self.get_collections() resources = self.ge...
[ "Calculate", "and", "set", "ACL", "valid", "for", "requested", "collections", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L115-L129
[ "def", "set_collections_acl", "(", "self", ")", ":", "acl", "=", "[", "(", "Allow", ",", "'g:admin'", ",", "ALL_PERMISSIONS", ")", "]", "collections", "=", "self", ".", "get_collections", "(", ")", "resources", "=", "self", ".", "get_resources", "(", "coll...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
PolymorphicESView.determine_types
Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its value is comma-separated sequence of collection names under which views have been registered.
nefertari/polymorphic.py
def determine_types(self): """ Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its value is comma-separated sequence of collection names under which views have been registered. """ from neferta...
def determine_types(self): """ Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its value is comma-separated sequence of collection names under which views have been registered. """ from neferta...
[ "Determine", "ES", "type", "names", "from", "request", "data", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L155-L169
[ "def", "determine_types", "(", "self", ")", ":", "from", "nefertari", ".", "elasticsearch", "import", "ES", "collections", "=", "self", ".", "get_collections", "(", ")", "resources", "=", "self", ".", "get_resources", "(", "collections", ")", "models", "=", ...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
get_command
Returns a closure function that dispatches message to the WebSocket.
cproto/domains/factory.py
def get_command(domain_name, command_name): """Returns a closure function that dispatches message to the WebSocket.""" def send_command(self, **kwargs): return self.ws.send_message( '{0}.{1}'.format(domain_name, command_name), kwargs ) return send_command
def get_command(domain_name, command_name): """Returns a closure function that dispatches message to the WebSocket.""" def send_command(self, **kwargs): return self.ws.send_message( '{0}.{1}'.format(domain_name, command_name), kwargs ) return send_command
[ "Returns", "a", "closure", "function", "that", "dispatches", "message", "to", "the", "WebSocket", "." ]
asyne/cproto
python
https://github.com/asyne/cproto/blob/9c5cf5b8565fe5f8369b06e21d1dd069b9322e4b/cproto/domains/factory.py#L5-L13
[ "def", "get_command", "(", "domain_name", ",", "command_name", ")", ":", "def", "send_command", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "ws", ".", "send_message", "(", "'{0}.{1}'", ".", "format", "(", "domain_name", ",", "c...
9c5cf5b8565fe5f8369b06e21d1dd069b9322e4b
train
DomainFactory
Dynamically create Domain class and set it's methods.
cproto/domains/factory.py
def DomainFactory(domain_name, cmds): """Dynamically create Domain class and set it's methods.""" klass = type(str(domain_name), (BaseDomain,), {}) for c in cmds: command = get_command(domain_name, c['name']) setattr(klass, c['name'], classmethod(command)) return klass
def DomainFactory(domain_name, cmds): """Dynamically create Domain class and set it's methods.""" klass = type(str(domain_name), (BaseDomain,), {}) for c in cmds: command = get_command(domain_name, c['name']) setattr(klass, c['name'], classmethod(command)) return klass
[ "Dynamically", "create", "Domain", "class", "and", "set", "it", "s", "methods", "." ]
asyne/cproto
python
https://github.com/asyne/cproto/blob/9c5cf5b8565fe5f8369b06e21d1dd069b9322e4b/cproto/domains/factory.py#L16-L24
[ "def", "DomainFactory", "(", "domain_name", ",", "cmds", ")", ":", "klass", "=", "type", "(", "str", "(", "domain_name", ")", ",", "(", "BaseDomain", ",", ")", ",", "{", "}", ")", "for", "c", "in", "cmds", ":", "command", "=", "get_command", "(", "...
9c5cf5b8565fe5f8369b06e21d1dd069b9322e4b
train
main
The entrypoint for the hairball command installed via setup.py.
hairball/__init__.py
def main(): """The entrypoint for the hairball command installed via setup.py.""" description = ('PATH can be either the path to a scratch file, or a ' 'directory containing scratch files. Multiple PATH ' 'arguments can be provided.') parser = OptionParser(usage='%prog ...
def main(): """The entrypoint for the hairball command installed via setup.py.""" description = ('PATH can be either the path to a scratch file, or a ' 'directory containing scratch files. Multiple PATH ' 'arguments can be provided.') parser = OptionParser(usage='%prog ...
[ "The", "entrypoint", "for", "the", "hairball", "command", "installed", "via", "setup", ".", "py", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L238-L281
[ "def", "main", "(", ")", ":", "description", "=", "(", "'PATH can be either the path to a scratch file, or a '", "'directory containing scratch files. Multiple PATH '", "'arguments can be provided.'", ")", "parser", "=", "OptionParser", "(", "usage", "=", "'%prog -p PLUGIN_NAME [...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
KurtCache.path_to_key
Return the sha1sum (key) belonging to the file at filepath.
hairball/__init__.py
def path_to_key(filepath): """Return the sha1sum (key) belonging to the file at filepath.""" tmp, last = os.path.split(filepath) tmp, middle = os.path.split(tmp) return '{}{}{}'.format(os.path.basename(tmp), middle, os.path.splitext(last)[0])
def path_to_key(filepath): """Return the sha1sum (key) belonging to the file at filepath.""" tmp, last = os.path.split(filepath) tmp, middle = os.path.split(tmp) return '{}{}{}'.format(os.path.basename(tmp), middle, os.path.splitext(last)[0])
[ "Return", "the", "sha1sum", "(", "key", ")", "belonging", "to", "the", "file", "at", "filepath", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L29-L34
[ "def", "path_to_key", "(", "filepath", ")", ":", "tmp", ",", "last", "=", "os", ".", "path", ".", "split", "(", "filepath", ")", "tmp", ",", "middle", "=", "os", ".", "path", ".", "split", "(", "tmp", ")", "return", "'{}{}{}'", ".", "format", "(", ...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
KurtCache.key_to_path
Return the fullpath to the file with sha1sum key.
hairball/__init__.py
def key_to_path(self, key): """Return the fullpath to the file with sha1sum key.""" return os.path.join(self.cache_dir, key[:2], key[2:4], key[4:] + '.pkl')
def key_to_path(self, key): """Return the fullpath to the file with sha1sum key.""" return os.path.join(self.cache_dir, key[:2], key[2:4], key[4:] + '.pkl')
[ "Return", "the", "fullpath", "to", "the", "file", "with", "sha1sum", "key", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L53-L56
[ "def", "key_to_path", "(", "self", ",", "key", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "cache_dir", ",", "key", "[", ":", "2", "]", ",", "key", "[", "2", ":", "4", "]", ",", "key", "[", "4", ":", "]", "+", "'.p...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
KurtCache.load
Optimized load and return the parsed version of filename. Uses the on-disk parse cache if the file is located in it.
hairball/__init__.py
def load(self, filename): """Optimized load and return the parsed version of filename. Uses the on-disk parse cache if the file is located in it. """ # Compute sha1 hash (key) with open(filename) as fp: key = sha1(fp.read()).hexdigest() path = self.key_to_pa...
def load(self, filename): """Optimized load and return the parsed version of filename. Uses the on-disk parse cache if the file is located in it. """ # Compute sha1 hash (key) with open(filename) as fp: key = sha1(fp.read()).hexdigest() path = self.key_to_pa...
[ "Optimized", "load", "and", "return", "the", "parsed", "version", "of", "filename", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L58-L91
[ "def", "load", "(", "self", ",", "filename", ")", ":", "# Compute sha1 hash (key)", "with", "open", "(", "filename", ")", "as", "fp", ":", "key", "=", "sha1", "(", "fp", ".", "read", "(", ")", ")", ".", "hexdigest", "(", ")", "path", "=", "self", "...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
Hairball.hairball_files
Yield filepath to files with the proper extension within paths.
hairball/__init__.py
def hairball_files(self, paths, extensions): """Yield filepath to files with the proper extension within paths.""" def add_file(filename): return os.path.splitext(filename)[1] in extensions while paths: arg_path = paths.pop(0) if os.path.isdir(arg_path): ...
def hairball_files(self, paths, extensions): """Yield filepath to files with the proper extension within paths.""" def add_file(filename): return os.path.splitext(filename)[1] in extensions while paths: arg_path = paths.pop(0) if os.path.isdir(arg_path): ...
[ "Yield", "filepath", "to", "files", "with", "the", "proper", "extension", "within", "paths", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L136-L158
[ "def", "hairball_files", "(", "self", ",", "paths", ",", "extensions", ")", ":", "def", "add_file", "(", "filename", ")", ":", "return", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "in", "extensions", "while", "paths", ":",...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
Hairball.initialize_plugins
Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr.
hairball/__init__.py
def initialize_plugins(self): """Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr. """ for plugin_name in self.options.plugin: parts = plugin_name.split('.') if len(parts) > 1: module_name = '.'....
def initialize_plugins(self): """Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr. """ for plugin_name in self.options.plugin: parts = plugin_name.split('.') if len(parts) > 1: module_name = '.'....
[ "Attempt", "to", "Load", "and", "initialize", "all", "the", "plugins", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L170-L212
[ "def", "initialize_plugins", "(", "self", ")", ":", "for", "plugin_name", "in", "self", ".", "options", ".", "plugin", ":", "parts", "=", "plugin_name", ".", "split", "(", "'.'", ")", "if", "len", "(", "parts", ")", ">", "1", ":", "module_name", "=", ...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
Hairball.process
Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run against it before loading the next file.
hairball/__init__.py
def process(self): """Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run against it before loading the next file. """ for filename in self.hairball_files(self.paths, self.extensions): if not self.options.quie...
def process(self): """Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run against it before loading the next file. """ for filename in self.hairball_files(self.paths, self.extensions): if not self.options.quie...
[ "Run", "the", "analysis", "across", "all", "files", "found", "in", "the", "given", "paths", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L214-L234
[ "def", "process", "(", "self", ")", ":", "for", "filename", "in", "self", ".", "hairball_files", "(", "self", ".", "paths", ",", "self", ".", "extensions", ")", ":", "if", "not", "self", ".", "options", ".", "quiet", ":", "print", "(", "filename", ")...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
maybe_dotted
If ``module`` is a dotted string pointing to the module, imports and returns the module object.
nefertari/utils/utils.py
def maybe_dotted(module, throw=True): """ If ``module`` is a dotted string pointing to the module, imports and returns the module object. """ try: return Configurator().maybe_dotted(module) except ImportError as e: err = '%s not found. %s' % (module, e) if throw: ...
def maybe_dotted(module, throw=True): """ If ``module`` is a dotted string pointing to the module, imports and returns the module object. """ try: return Configurator().maybe_dotted(module) except ImportError as e: err = '%s not found. %s' % (module, e) if throw: ...
[ "If", "module", "is", "a", "dotted", "string", "pointing", "to", "the", "module", "imports", "and", "returns", "the", "module", "object", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L95-L107
[ "def", "maybe_dotted", "(", "module", ",", "throw", "=", "True", ")", ":", "try", ":", "return", "Configurator", "(", ")", ".", "maybe_dotted", "(", "module", ")", "except", "ImportError", "as", "e", ":", "err", "=", "'%s not found. %s'", "%", "(", "modu...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
issequence
Return True if `arg` acts as a list and does not look like a string.
nefertari/utils/utils.py
def issequence(arg): """Return True if `arg` acts as a list and does not look like a string.""" string_behaviour = ( isinstance(arg, six.string_types) or isinstance(arg, six.text_type)) list_behaviour = hasattr(arg, '__getitem__') or hasattr(arg, '__iter__') return not string_behaviour a...
def issequence(arg): """Return True if `arg` acts as a list and does not look like a string.""" string_behaviour = ( isinstance(arg, six.string_types) or isinstance(arg, six.text_type)) list_behaviour = hasattr(arg, '__getitem__') or hasattr(arg, '__iter__') return not string_behaviour a...
[ "Return", "True", "if", "arg", "acts", "as", "a", "list", "and", "does", "not", "look", "like", "a", "string", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L127-L133
[ "def", "issequence", "(", "arg", ")", ":", "string_behaviour", "=", "(", "isinstance", "(", "arg", ",", "six", ".", "string_types", ")", "or", "isinstance", "(", "arg", ",", "six", ".", "text_type", ")", ")", "list_behaviour", "=", "hasattr", "(", "arg",...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
merge_dicts
Merge dict :b: into dict :a: Code snippet from http://stackoverflow.com/a/7205107
nefertari/utils/utils.py
def merge_dicts(a, b, path=None): """ Merge dict :b: into dict :a: Code snippet from http://stackoverflow.com/a/7205107 """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge_dicts(a[key]...
def merge_dicts(a, b, path=None): """ Merge dict :b: into dict :a: Code snippet from http://stackoverflow.com/a/7205107 """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge_dicts(a[key]...
[ "Merge", "dict", ":", "b", ":", "into", "dict", ":", "a", ":" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L136-L155
[ "def", "merge_dicts", "(", "a", ",", "b", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "[", "]", "for", "key", "in", "b", ":", "if", "key", "in", "a", ":", "if", "isinstance", "(", "a", "[", "key", "]", ...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
str2dict
Convert dotted string to dict splitting by :separator:
nefertari/utils/utils.py
def str2dict(dotted_str, value=None, separator='.'): """ Convert dotted string to dict splitting by :separator: """ dict_ = {} parts = dotted_str.split(separator) d, prev = dict_, None for part in parts: prev = d d = d.setdefault(part, {}) else: if value is not None: ...
def str2dict(dotted_str, value=None, separator='.'): """ Convert dotted string to dict splitting by :separator: """ dict_ = {} parts = dotted_str.split(separator) d, prev = dict_, None for part in parts: prev = d d = d.setdefault(part, {}) else: if value is not None: ...
[ "Convert", "dotted", "string", "to", "dict", "splitting", "by", ":", "separator", ":" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L158-L169
[ "def", "str2dict", "(", "dotted_str", ",", "value", "=", "None", ",", "separator", "=", "'.'", ")", ":", "dict_", "=", "{", "}", "parts", "=", "dotted_str", ".", "split", "(", "separator", ")", "d", ",", "prev", "=", "dict_", ",", "None", "for", "p...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
validate_data_privacy
Validate :data: contains only data allowed by privacy settings. :param request: Pyramid Request instance :param data: Dict containing request/response data which should be validated
nefertari/utils/utils.py
def validate_data_privacy(request, data, wrapper_kw=None): """ Validate :data: contains only data allowed by privacy settings. :param request: Pyramid Request instance :param data: Dict containing request/response data which should be validated """ from nefertari import wrappers if wrap...
def validate_data_privacy(request, data, wrapper_kw=None): """ Validate :data: contains only data allowed by privacy settings. :param request: Pyramid Request instance :param data: Dict containing request/response data which should be validated """ from nefertari import wrappers if wrap...
[ "Validate", ":", "data", ":", "contains", "only", "data", "allowed", "by", "privacy", "settings", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L172-L190
[ "def", "validate_data_privacy", "(", "request", ",", "data", ",", "wrapper_kw", "=", "None", ")", ":", "from", "nefertari", "import", "wrappers", "if", "wrapper_kw", "is", "None", ":", "wrapper_kw", "=", "{", "}", "wrapper", "=", "wrappers", ".", "apply_priv...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
drop_reserved_params
Drops reserved params
nefertari/utils/utils.py
def drop_reserved_params(params): """ Drops reserved params """ from nefertari import RESERVED_PARAMS params = params.copy() for reserved_param in RESERVED_PARAMS: if reserved_param in params: params.pop(reserved_param) return params
def drop_reserved_params(params): """ Drops reserved params """ from nefertari import RESERVED_PARAMS params = params.copy() for reserved_param in RESERVED_PARAMS: if reserved_param in params: params.pop(reserved_param) return params
[ "Drops", "reserved", "params" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L193-L200
[ "def", "drop_reserved_params", "(", "params", ")", ":", "from", "nefertari", "import", "RESERVED_PARAMS", "params", "=", "params", ".", "copy", "(", ")", "for", "reserved_param", "in", "RESERVED_PARAMS", ":", "if", "reserved_param", "in", "params", ":", "params"...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
TV._send_command_raw
Description: The TV doesn't handle long running connections very well, so we open a new connection every time. There might be a better way to do this, but it's pretty quick and resilient. Returns: If a value is being requested ( opt2 is "?" ), ...
sharp_aquos_rc/tv.py
def _send_command_raw(self, command, opt=''): """ Description: The TV doesn't handle long running connections very well, so we open a new connection every time. There might be a better way to do this, but it's pretty quick and resilient. Returns:...
def _send_command_raw(self, command, opt=''): """ Description: The TV doesn't handle long running connections very well, so we open a new connection every time. There might be a better way to do this, but it's pretty quick and resilient. Returns:...
[ "Description", ":" ]
jmoore987/sharp_aquos_rc
python
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L37-L95
[ "def", "_send_command_raw", "(", "self", ",", "command", ",", "opt", "=", "''", ")", ":", "# According to the documentation:", "# http://files.sharpusa.com/Downloads/ForHome/", "# HomeEntertainment/LCDTVs/Manuals/tel_man_LC40_46_52_60LE830U.pdf", "# Page 58 - Communication conditions f...
9a5a1140241a866150dea2d26555680dc8e7f057
train
TV.info
Description: Returns dict of information about the TV name, model, version
sharp_aquos_rc/tv.py
def info(self): """ Description: Returns dict of information about the TV name, model, version """ return {"name": self._send_command('name'), "model": self._send_command('model'), "version": self._send_command('version'), ...
def info(self): """ Description: Returns dict of information about the TV name, model, version """ return {"name": self._send_command('name'), "model": self._send_command('model'), "version": self._send_command('version'), ...
[ "Description", ":" ]
jmoore987/sharp_aquos_rc
python
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L115-L127
[ "def", "info", "(", "self", ")", ":", "return", "{", "\"name\"", ":", "self", ".", "_send_command", "(", "'name'", ")", ",", "\"model\"", ":", "self", ".", "_send_command", "(", "'model'", ")", ",", "\"version\"", ":", "self", ".", "_send_command", "(", ...
9a5a1140241a866150dea2d26555680dc8e7f057
train
TV.get_input_list
Description: Get input list Returns an ordered list of all available input keys and names
sharp_aquos_rc/tv.py
def get_input_list(self): """ Description: Get input list Returns an ordered list of all available input keys and names """ inputs = [' '] * len(self.command['input']) for key in self.command['input']: inputs[self.command['input'][key]['order...
def get_input_list(self): """ Description: Get input list Returns an ordered list of all available input keys and names """ inputs = [' '] * len(self.command['input']) for key in self.command['input']: inputs[self.command['input'][key]['order...
[ "Description", ":" ]
jmoore987/sharp_aquos_rc
python
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L158-L169
[ "def", "get_input_list", "(", "self", ")", ":", "inputs", "=", "[", "' '", "]", "*", "len", "(", "self", ".", "command", "[", "'input'", "]", ")", "for", "key", "in", "self", ".", "command", "[", "'input'", "]", ":", "inputs", "[", "self", ".", "...
9a5a1140241a866150dea2d26555680dc8e7f057
train
TV.input
Description: Set the input Call with no arguments to get current setting Arguments: opt: string Name provided from input list or key from yaml ("HDMI 1" or "hdmi_1")
sharp_aquos_rc/tv.py
def input(self, opt): """ Description: Set the input Call with no arguments to get current setting Arguments: opt: string Name provided from input list or key from yaml ("HDMI 1" or "hdmi_1") """ for key in self.command['inpu...
def input(self, opt): """ Description: Set the input Call with no arguments to get current setting Arguments: opt: string Name provided from input list or key from yaml ("HDMI 1" or "hdmi_1") """ for key in self.command['inpu...
[ "Description", ":" ]
jmoore987/sharp_aquos_rc
python
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L171-L186
[ "def", "input", "(", "self", ",", "opt", ")", ":", "for", "key", "in", "self", ".", "command", "[", "'input'", "]", ":", "if", "(", "key", "==", "opt", ")", "or", "(", "self", ".", "command", "[", "'input'", "]", "[", "key", "]", "[", "'name'",...
9a5a1140241a866150dea2d26555680dc8e7f057
train
TV.digital_channel_air
Description: Change Channel (Digital) Pass Channels "XX.YY" as TV.digital_channel_air(XX, YY) Arguments: opt1: integer 1-99: Major Channel opt2: integer (optional) 1-99: Minor Channel
sharp_aquos_rc/tv.py
def digital_channel_air(self, opt1='?', opt2='?'): """ Description: Change Channel (Digital) Pass Channels "XX.YY" as TV.digital_channel_air(XX, YY) Arguments: opt1: integer 1-99: Major Channel opt2: integer (optional) ...
def digital_channel_air(self, opt1='?', opt2='?'): """ Description: Change Channel (Digital) Pass Channels "XX.YY" as TV.digital_channel_air(XX, YY) Arguments: opt1: integer 1-99: Major Channel opt2: integer (optional) ...
[ "Description", ":" ]
jmoore987/sharp_aquos_rc
python
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L330-L349
[ "def", "digital_channel_air", "(", "self", ",", "opt1", "=", "'?'", ",", "opt2", "=", "'?'", ")", ":", "if", "opt1", "==", "'?'", ":", "parameter", "=", "'?'", "elif", "opt2", "==", "'?'", ":", "parameter", "=", "str", "(", "opt1", ")", ".", "rjust...
9a5a1140241a866150dea2d26555680dc8e7f057
train
TV.digital_channel_cable
Description: Change Channel (Digital) Pass Channels "XXX.YYY" as TV.digital_channel_cable(XXX, YYY) Arguments: opt1: integer 1-999: Major Channel opt2: integer (optional) 0-999: Minor Channel
sharp_aquos_rc/tv.py
def digital_channel_cable(self, opt1='?', opt2=0): """ Description: Change Channel (Digital) Pass Channels "XXX.YYY" as TV.digital_channel_cable(XXX, YYY) Arguments: opt1: integer 1-999: Major Channel opt2: integer (optional) ...
def digital_channel_cable(self, opt1='?', opt2=0): """ Description: Change Channel (Digital) Pass Channels "XXX.YYY" as TV.digital_channel_cable(XXX, YYY) Arguments: opt1: integer 1-999: Major Channel opt2: integer (optional) ...
[ "Description", ":" ]
jmoore987/sharp_aquos_rc
python
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L351-L371
[ "def", "digital_channel_cable", "(", "self", ",", "opt1", "=", "'?'", ",", "opt2", "=", "0", ")", ":", "if", "opt1", "==", "'?'", ":", "parameter", "=", "'?'", "elif", "self", ".", "command", "[", "'digital_channel_cable_minor'", "]", "==", "''", ":", ...
9a5a1140241a866150dea2d26555680dc8e7f057
train
TV.get_remote_button_list
Description: Get remote button list Returns an list of all available remote buttons
sharp_aquos_rc/tv.py
def get_remote_button_list(self): """ Description: Get remote button list Returns an list of all available remote buttons """ remote_buttons = [] for key in self.command['remote']: if self.command['remote'][key] != '': remote_...
def get_remote_button_list(self): """ Description: Get remote button list Returns an list of all available remote buttons """ remote_buttons = [] for key in self.command['remote']: if self.command['remote'][key] != '': remote_...
[ "Description", ":" ]
jmoore987/sharp_aquos_rc
python
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L387-L399
[ "def", "get_remote_button_list", "(", "self", ")", ":", "remote_buttons", "=", "[", "]", "for", "key", "in", "self", ".", "command", "[", "'remote'", "]", ":", "if", "self", ".", "command", "[", "'remote'", "]", "[", "key", "]", "!=", "''", ":", "rem...
9a5a1140241a866150dea2d26555680dc8e7f057
train
Animation.check_results
Return a 3 tuple for something.
hairball/plugins/checks.py
def check_results(tmp_): """Return a 3 tuple for something.""" # TODO: Fix this to work with more meaningful names if tmp_['t'] > 0: if tmp_['l'] > 0: if tmp_['rr'] > 0 or tmp_['ra'] > 1: print 1, 3, tmp_ return 3 ...
def check_results(tmp_): """Return a 3 tuple for something.""" # TODO: Fix this to work with more meaningful names if tmp_['t'] > 0: if tmp_['l'] > 0: if tmp_['rr'] > 0 or tmp_['ra'] > 1: print 1, 3, tmp_ return 3 ...
[ "Return", "a", "3", "tuple", "for", "something", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L28-L62
[ "def", "check_results", "(", "tmp_", ")", ":", "# TODO: Fix this to work with more meaningful names", "if", "tmp_", "[", "'t'", "]", ">", "0", ":", "if", "tmp_", "[", "'l'", "]", ">", "0", ":", "if", "tmp_", "[", "'rr'", "]", ">", "0", "or", "tmp_", "[...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
Animation._check_animation
Internal helper function to check the animation.
hairball/plugins/checks.py
def _check_animation(self, last, last_level, gen): """Internal helper function to check the animation.""" tmp_ = Counter() results = Counter() name, level, block = last, last_level, last others = False while name in self.ANIMATION and level >= last_level: if n...
def _check_animation(self, last, last_level, gen): """Internal helper function to check the animation.""" tmp_ = Counter() results = Counter() name, level, block = last, last_level, last others = False while name in self.ANIMATION and level >= last_level: if n...
[ "Internal", "helper", "function", "to", "check", "the", "animation", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L64-L99
[ "def", "_check_animation", "(", "self", ",", "last", ",", "last_level", ",", "gen", ")", ":", "tmp_", "=", "Counter", "(", ")", "results", "=", "Counter", "(", ")", "name", ",", "level", ",", "block", "=", "last", ",", "last_level", ",", "last", "oth...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
Animation.analyze
Run and return the results from the Animation plugin.
hairball/plugins/checks.py
def analyze(self, scratch, **kwargs): """Run and return the results from the Animation plugin.""" results = Counter() for script in self.iter_scripts(scratch): gen = self.iter_blocks(script.blocks) name = 'start' level = None while name != '': ...
def analyze(self, scratch, **kwargs): """Run and return the results from the Animation plugin.""" results = Counter() for script in self.iter_scripts(scratch): gen = self.iter_blocks(script.blocks) name = 'start' level = None while name != '': ...
[ "Run", "and", "return", "the", "results", "from", "the", "Animation", "plugin", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L101-L113
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "results", "=", "Counter", "(", ")", "for", "script", "in", "self", ".", "iter_scripts", "(", "scratch", ")", ":", "gen", "=", "self", ".", "iter_blocks", "(", "script"...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
BroadcastReceive.get_receive
Return a list of received events contained in script_list.
hairball/plugins/checks.py
def get_receive(self, script_list): """Return a list of received events contained in script_list.""" events = defaultdict(set) for script in script_list: if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE: event = script.blocks[0].args[0].lower() ...
def get_receive(self, script_list): """Return a list of received events contained in script_list.""" events = defaultdict(set) for script in script_list: if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE: event = script.blocks[0].args[0].lower() ...
[ "Return", "a", "list", "of", "received", "events", "contained", "in", "script_list", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L120-L127
[ "def", "get_receive", "(", "self", ",", "script_list", ")", ":", "events", "=", "defaultdict", "(", "set", ")", "for", "script", "in", "script_list", ":", "if", "self", ".", "script_start_type", "(", "script", ")", "==", "self", ".", "HAT_WHEN_I_RECEIVE", ...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
BroadcastReceive.analyze
Run and return the results from the BroadcastReceive plugin.
hairball/plugins/checks.py
def analyze(self, scratch, **kwargs): """Run and return the results from the BroadcastReceive plugin.""" all_scripts = list(self.iter_scripts(scratch)) results = defaultdict(set) broadcast = dict((x, self.get_broadcast_events(x)) # Events by script for x in all_...
def analyze(self, scratch, **kwargs): """Run and return the results from the BroadcastReceive plugin.""" all_scripts = list(self.iter_scripts(scratch)) results = defaultdict(set) broadcast = dict((x, self.get_broadcast_events(x)) # Events by script for x in all_...
[ "Run", "and", "return", "the", "results", "from", "the", "BroadcastReceive", "plugin", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L129-L175
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "all_scripts", "=", "list", "(", "self", ".", "iter_scripts", "(", "scratch", ")", ")", "results", "=", "defaultdict", "(", "set", ")", "broadcast", "=", "dict", "(", "...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
SaySoundSync.analyze
Categorize instances of attempted say and sound synchronization.
hairball/plugins/checks.py
def analyze(self, scratch, **kwargs): """Categorize instances of attempted say and sound synchronization.""" errors = Counter() for script in self.iter_scripts(scratch): prev_name, prev_depth, prev_block = '', 0, script.blocks[0] gen = self.iter_blocks(script.blocks) ...
def analyze(self, scratch, **kwargs): """Categorize instances of attempted say and sound synchronization.""" errors = Counter() for script in self.iter_scripts(scratch): prev_name, prev_depth, prev_block = '', 0, script.blocks[0] gen = self.iter_blocks(script.blocks) ...
[ "Categorize", "instances", "of", "attempted", "say", "and", "sound", "synchronization", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L203-L233
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "Counter", "(", ")", "for", "script", "in", "self", ".", "iter_scripts", "(", "scratch", ")", ":", "prev_name", ",", "prev_depth", ",", "prev_block", "=", ...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
SaySoundSync.check
Check that the last part of the chain matches. TODO: Fix to handle the following situation that appears to not work say 'message 1' play sound until done say 'message 2' say 'message 3' play sound until done say ''
hairball/plugins/checks.py
def check(self, gen): """Check that the last part of the chain matches. TODO: Fix to handle the following situation that appears to not work say 'message 1' play sound until done say 'message 2' say 'message 3' play sound until done say '' """ ...
def check(self, gen): """Check that the last part of the chain matches. TODO: Fix to handle the following situation that appears to not work say 'message 1' play sound until done say 'message 2' say 'message 3' play sound until done say '' """ ...
[ "Check", "that", "the", "last", "part", "of", "the", "chain", "matches", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L235-L265
[ "def", "check", "(", "self", ",", "gen", ")", ":", "retval", "=", "Counter", "(", ")", "name", ",", "_", ",", "block", "=", "next", "(", "gen", ",", "(", "''", ",", "0", ",", "''", ")", ")", "if", "name", "in", "self", ".", "SAY_THINK", ":", ...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
_format_exception
Converts a sys.exc_info()-style tuple of values into a string.
haas/result.py
def _format_exception(err, is_failure, stdout=None, stderr=None): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err # Skip test runner traceback levels while tb and _is_relevant_tb_level(tb): tb = tb.tb_next if is_failure: # Skip assert*()...
def _format_exception(err, is_failure, stdout=None, stderr=None): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err # Skip test runner traceback levels while tb and _is_relevant_tb_level(tb): tb = tb.tb_next if is_failure: # Skip assert*()...
[ "Converts", "a", "sys", ".", "exc_info", "()", "-", "style", "tuple", "of", "values", "into", "a", "string", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L76-L101
[ "def", "_format_exception", "(", "err", ",", "is_failure", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ")", ":", "exctype", ",", "value", ",", "tb", "=", "err", "# Skip test runner traceback levels", "while", "tb", "and", "_is_relevant_tb_level", "...
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
ResultCollector._setup_stdout
Hook stdout and stderr if buffering is enabled.
haas/result.py
def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer ...
def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer ...
[ "Hook", "stdout", "and", "stderr", "if", "buffering", "is", "enabled", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L365-L374
[ "def", "_setup_stdout", "(", "self", ")", ":", "if", "self", ".", "buffer", ":", "if", "self", ".", "_stderr_buffer", "is", "None", ":", "self", ".", "_stderr_buffer", "=", "StringIO", "(", ")", "self", ".", "_stdout_buffer", "=", "StringIO", "(", ")", ...
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
ResultCollector._restore_stdout
Unhook stdout and stderr if buffering is enabled.
haas/result.py
def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endsw...
def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endsw...
[ "Unhook", "stdout", "and", "stderr", "if", "buffering", "is", "enabled", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L376-L398
[ "def", "_restore_stdout", "(", "self", ")", ":", "if", "self", ".", "buffer", ":", "if", "self", ".", "_mirror_output", ":", "output", "=", "sys", ".", "stdout", ".", "getvalue", "(", ")", "error", "=", "sys", ".", "stderr", ".", "getvalue", "(", ")"...
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
ResultCollector.add_result_handler
Register a new result handler.
haas/result.py
def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None
def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None
[ "Register", "a", "new", "result", "handler", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L404-L411
[ "def", "add_result_handler", "(", "self", ",", "handler", ")", ":", "self", ".", "_result_handlers", ".", "append", "(", "handler", ")", "# Reset sorted handlers", "if", "self", ".", "_sorted_handlers", ":", "self", ".", "_sorted_handlers", "=", "None" ]
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
ResultCollector.add_result
Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses).
haas/result.py
def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). """ for handler in self._handlers: handle...
def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). """ for handler in self._handlers: handle...
[ "Add", "an", "already", "-", "constructed", ":", "class", ":", "~", ".", "TestResult", "to", "this", ":", "class", ":", "~", ".", "ResultCollector", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L462-L473
[ "def", "add_result", "(", "self", ",", "result", ")", ":", "for", "handler", "in", "self", ".", "_handlers", ":", "handler", "(", "result", ")", "if", "self", ".", "_successful", "and", "result", ".", "status", "not", "in", "_successful_results", ":", "s...
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
ResultCollector._handle_result
Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result.TestCompletionStatus The status of the test. exception : tup...
haas/result.py
def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result...
def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result...
[ "Create", "a", ":", "class", ":", "~", ".", "TestResult", "and", "add", "it", "to", "this", ":", "class", ":", "~ResultCollector", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L475-L518
[ "def", "_handle_result", "(", "self", ",", "test", ",", "status", ",", "exception", "=", "None", ",", "message", "=", "None", ")", ":", "if", "self", ".", "buffer", ":", "stderr", "=", "self", ".", "_stderr_buffer", ".", "getvalue", "(", ")", "stdout",...
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
ResultCollector.addError
Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``.
haas/result.py
def addError(self, test, exception): """Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = se...
def addError(self, test, exception): """Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = se...
[ "Register", "that", "a", "test", "ended", "in", "an", "error", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L521-L535
[ "def", "addError", "(", "self", ",", "test", ",", "exception", ")", ":", "result", "=", "self", ".", "_handle_result", "(", "test", ",", "TestCompletionStatus", ".", "error", ",", "exception", "=", "exception", ")", "self", ".", "errors", ".", "append", ...
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
ResultCollector.addFailure
Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``.
haas/result.py
def addFailure(self, test, exception): """Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result...
def addFailure(self, test, exception): """Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result...
[ "Register", "that", "a", "test", "ended", "with", "a", "failure", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L538-L552
[ "def", "addFailure", "(", "self", ",", "test", ",", "exception", ")", ":", "result", "=", "self", ".", "_handle_result", "(", "test", ",", "TestCompletionStatus", ".", "failure", ",", "exception", "=", "exception", ")", "self", ".", "failures", ".", "appen...
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
ResultCollector.addSkip
Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped.
haas/result.py
def addSkip(self, test, reason): """Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped. """ result = self._handle_result( ...
def addSkip(self, test, reason): """Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped. """ result = self._handle_result( ...
[ "Register", "that", "a", "test", "that", "was", "skipped", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L565-L578
[ "def", "addSkip", "(", "self", ",", "test", ",", "reason", ")", ":", "result", "=", "self", ".", "_handle_result", "(", "test", ",", "TestCompletionStatus", ".", "skipped", ",", "message", "=", "reason", ")", "self", ".", "skipped", ".", "append", "(", ...
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
ResultCollector.addExpectedFailure
Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``.
haas/result.py
def addExpectedFailure(self, test, exception): """Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. ...
def addExpectedFailure(self, test, exception): """Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. ...
[ "Register", "that", "a", "test", "that", "failed", "and", "was", "expected", "to", "fail", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L580-L593
[ "def", "addExpectedFailure", "(", "self", ",", "test", ",", "exception", ")", ":", "result", "=", "self", ".", "_handle_result", "(", "test", ",", "TestCompletionStatus", ".", "expected_failure", ",", "exception", "=", "exception", ")", "self", ".", "expectedF...
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
ResultCollector.addUnexpectedSuccess
Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed.
haas/result.py
def addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed. """ result = self._handle_result( test, TestCompletionStatus.unexpected_success) ...
def addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed. """ result = self._handle_result( test, TestCompletionStatus.unexpected_success) ...
[ "Register", "a", "test", "that", "passed", "unexpectedly", "." ]
scalative/haas
python
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L596-L607
[ "def", "addUnexpectedSuccess", "(", "self", ",", "test", ")", ":", "result", "=", "self", ".", "_handle_result", "(", "test", ",", "TestCompletionStatus", ".", "unexpected_success", ")", "self", ".", "unexpectedSuccesses", ".", "append", "(", "result", ")" ]
72c05216a2a80e5ee94d9cd8d05ed2b188725027
train
Terminal.set_terminal_key
Change the terminal key. The encrypted_key is a hex string. encrypted_key is expected to be encrypted under master key
bpc8583/terminal.py
def set_terminal_key(self, encrypted_key): """ Change the terminal key. The encrypted_key is a hex string. encrypted_key is expected to be encrypted under master key """ if encrypted_key: try: new_key = bytes.fromhex(encrypted_key) if l...
def set_terminal_key(self, encrypted_key): """ Change the terminal key. The encrypted_key is a hex string. encrypted_key is expected to be encrypted under master key """ if encrypted_key: try: new_key = bytes.fromhex(encrypted_key) if l...
[ "Change", "the", "terminal", "key", ".", "The", "encrypted_key", "is", "a", "hex", "string", ".", "encrypted_key", "is", "expected", "to", "be", "encrypted", "under", "master", "key" ]
timgabets/bpc8583
python
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/terminal.py#L144-L166
[ "def", "set_terminal_key", "(", "self", ",", "encrypted_key", ")", ":", "if", "encrypted_key", ":", "try", ":", "new_key", "=", "bytes", ".", "fromhex", "(", "encrypted_key", ")", "if", "len", "(", "self", ".", "terminal_key", ")", "!=", "len", "(", "new...
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
train
Terminal.get_encrypted_pin
Get PIN block in ISO 0 format, encrypted with the terminal key
bpc8583/terminal.py
def get_encrypted_pin(self, clear_pin, card_number): """ Get PIN block in ISO 0 format, encrypted with the terminal key """ if not self.terminal_key: print('Terminal key is not set') return '' if self.pinblock_format == '01': try: ...
def get_encrypted_pin(self, clear_pin, card_number): """ Get PIN block in ISO 0 format, encrypted with the terminal key """ if not self.terminal_key: print('Terminal key is not set') return '' if self.pinblock_format == '01': try: ...
[ "Get", "PIN", "block", "in", "ISO", "0", "format", "encrypted", "with", "the", "terminal", "key" ]
timgabets/bpc8583
python
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/terminal.py#L176-L196
[ "def", "get_encrypted_pin", "(", "self", ",", "clear_pin", ",", "card_number", ")", ":", "if", "not", "self", ".", "terminal_key", ":", "print", "(", "'Terminal key is not set'", ")", "return", "''", "if", "self", ".", "pinblock_format", "==", "'01'", ":", "...
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
train
is_url
Check if a string is a valid url. :param string: String to check. :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :return: True if url, false otherwise :rtype: bool
string_utils.py
def is_url(string, allowed_schemes=None): """ Check if a string is a valid url. :param string: String to check. :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :return: True if url, false otherwise :rtype: bool """ if not...
def is_url(string, allowed_schemes=None): """ Check if a string is a valid url. :param string: String to check. :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :return: True if url, false otherwise :rtype: bool """ if not...
[ "Check", "if", "a", "string", "is", "a", "valid", "url", "." ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L184-L198
[ "def", "is_url", "(", "string", ",", "allowed_schemes", "=", "None", ")", ":", "if", "not", "is_full_string", "(", "string", ")", ":", "return", "False", "valid", "=", "bool", "(", "URL_RE", ".", "search", "(", "string", ")", ")", "if", "allowed_schemes"...
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
is_credit_card
Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card type. :type card_type: str Can be one of these: ...
string_utils.py
def is_credit_card(string, card_type=None): """ Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card typ...
def is_credit_card(string, card_type=None): """ Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card typ...
[ "Checks", "if", "a", "string", "is", "a", "valid", "credit", "card", "number", ".", "If", "card", "type", "is", "provided", "then", "it", "checks", "that", "specific", "type", "otherwise", "any", "known", "credit", "card", "number", "will", "be", "accepted...
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L223-L259
[ "def", "is_credit_card", "(", "string", ",", "card_type", "=", "None", ")", ":", "if", "not", "is_full_string", "(", "string", ")", ":", "return", "False", "if", "card_type", ":", "if", "card_type", "not", "in", "CREDIT_CARDS", ":", "raise", "KeyError", "(...
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
is_snake_case
Checks if a string is formatted as snake case. A string is considered snake case when: * it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \ and optionally numbers ([0-9]) * it does not start/end with an underscore (or provided separator) * it does not start with ...
string_utils.py
def is_snake_case(string, separator='_'): """ Checks if a string is formatted as snake case. A string is considered snake case when: * it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \ and optionally numbers ([0-9]) * it does not start/end with an underscore...
def is_snake_case(string, separator='_'): """ Checks if a string is formatted as snake case. A string is considered snake case when: * it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \ and optionally numbers ([0-9]) * it does not start/end with an underscore...
[ "Checks", "if", "a", "string", "is", "formatted", "as", "snake", "case", ".", "A", "string", "is", "considered", "snake", "case", "when", ":" ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L280-L306
[ "def", "is_snake_case", "(", "string", ",", "separator", "=", "'_'", ")", ":", "if", "is_full_string", "(", "string", ")", ":", "re_map", "=", "{", "'_'", ":", "SNAKE_CASE_TEST_RE", ",", "'-'", ":", "SNAKE_CASE_TEST_DASH_RE", "}", "re_template", "=", "'^[a-z...
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
is_json
Check if a string is a valid json. :param string: String to check. :type string: str :return: True if json, false otherwise :rtype: bool
string_utils.py
def is_json(string): """ Check if a string is a valid json. :param string: String to check. :type string: str :return: True if json, false otherwise :rtype: bool """ if not is_full_string(string): return False if bool(JSON_WRAPPER_RE.search(string)): try: ...
def is_json(string): """ Check if a string is a valid json. :param string: String to check. :type string: str :return: True if json, false otherwise :rtype: bool """ if not is_full_string(string): return False if bool(JSON_WRAPPER_RE.search(string)): try: ...
[ "Check", "if", "a", "string", "is", "a", "valid", "json", "." ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L309-L325
[ "def", "is_json", "(", "string", ")", ":", "if", "not", "is_full_string", "(", "string", ")", ":", "return", "False", "if", "bool", "(", "JSON_WRAPPER_RE", ".", "search", "(", "string", ")", ")", ":", "try", ":", "return", "isinstance", "(", "json", "....
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
is_palindrome
Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome). :param string: String to check. :type string: str :param strict: True if white spaces matter (default), false otherwise. :type strict: bool :return: True if the string is a palindrome (like "otto", or "i topi non aveva...
string_utils.py
def is_palindrome(string, strict=True): """ Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome). :param string: String to check. :type string: str :param strict: True if white spaces matter (default), false otherwise. :type strict: bool :return: True if the strin...
def is_palindrome(string, strict=True): """ Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome). :param string: String to check. :type string: str :param strict: True if white spaces matter (default), false otherwise. :type strict: bool :return: True if the strin...
[ "Checks", "if", "the", "string", "is", "a", "palindrome", "(", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Palindrome", ")", "." ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L352-L367
[ "def", "is_palindrome", "(", "string", ",", "strict", "=", "True", ")", ":", "if", "is_full_string", "(", "string", ")", ":", "if", "strict", ":", "return", "reverse", "(", "string", ")", "==", "string", "return", "is_palindrome", "(", "SPACES_RE", ".", ...
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
is_pangram
Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). :param string: String to check. :type string: str :return: True if the string is a pangram, False otherwise.
string_utils.py
def is_pangram(string): """ Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). :param string: String to check. :type string: str :return: True if the string is a pangram, False otherwise. """ return is_full_string(string) and set(SPACES_RE.sub('', string)).issuperset...
def is_pangram(string): """ Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). :param string: String to check. :type string: str :return: True if the string is a pangram, False otherwise. """ return is_full_string(string) and set(SPACES_RE.sub('', string)).issuperset...
[ "Checks", "if", "the", "string", "is", "a", "pangram", "(", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Pangram", ")", "." ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L370-L378
[ "def", "is_pangram", "(", "string", ")", ":", "return", "is_full_string", "(", "string", ")", "and", "set", "(", "SPACES_RE", ".", "sub", "(", "''", ",", "string", ")", ")", ".", "issuperset", "(", "letters_set", ")" ]
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
is_slug
Checks if a given string is a slug. :param string: String to check. :type string: str :param sign: Join sign used by the slug. :type sign: str :return: True if slug, false otherwise.
string_utils.py
def is_slug(string, sign='-'): """ Checks if a given string is a slug. :param string: String to check. :type string: str :param sign: Join sign used by the slug. :type sign: str :return: True if slug, false otherwise. """ if not is_full_string(string): return False rex =...
def is_slug(string, sign='-'): """ Checks if a given string is a slug. :param string: String to check. :type string: str :param sign: Join sign used by the slug. :type sign: str :return: True if slug, false otherwise. """ if not is_full_string(string): return False rex =...
[ "Checks", "if", "a", "given", "string", "is", "a", "slug", "." ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L392-L405
[ "def", "is_slug", "(", "string", ",", "sign", "=", "'-'", ")", ":", "if", "not", "is_full_string", "(", "string", ")", ":", "return", "False", "rex", "=", "r'^([a-z\\d]+'", "+", "re", ".", "escape", "(", "sign", ")", "+", "r'?)*[a-z\\d]$'", "return", "...
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
camel_case_to_snake
Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) :param string: String to convert. :type string: str :param separator: Sign to use as separator. :type separator: str :return: Converted string. :rtype: str
string_utils.py
def camel_case_to_snake(string, separator='_'): """ Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) :param string: String to convert. :type string: str :param separator: Sign to use as separator. :type separator: str ...
def camel_case_to_snake(string, separator='_'): """ Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) :param string: String to convert. :type string: str :param separator: Sign to use as separator. :type separator: str ...
[ "Convert", "a", "camel", "case", "string", "into", "a", "snake", "case", "one", ".", "(", "The", "original", "string", "is", "returned", "if", "is", "not", "a", "valid", "camel", "case", "string", ")" ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L453-L469
[ "def", "camel_case_to_snake", "(", "string", ",", "separator", "=", "'_'", ")", ":", "if", "not", "is_string", "(", "string", ")", ":", "raise", "TypeError", "(", "'Expected string'", ")", "if", "not", "is_camel_case", "(", "string", ")", ":", "return", "s...
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
snake_case_to_camel
Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) :param string: String to convert. :type string: str :param upper_case_first: True to turn the first letter into uppercase (default). :type upper_case_first: bool :param separ...
string_utils.py
def snake_case_to_camel(string, upper_case_first=True, separator='_'): """ Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) :param string: String to convert. :type string: str :param upper_case_first: True to turn the first...
def snake_case_to_camel(string, upper_case_first=True, separator='_'): """ Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) :param string: String to convert. :type string: str :param upper_case_first: True to turn the first...
[ "Convert", "a", "snake", "case", "string", "into", "a", "camel", "case", "one", ".", "(", "The", "original", "string", "is", "returned", "if", "is", "not", "a", "valid", "snake", "case", "string", ")" ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L472-L498
[ "def", "snake_case_to_camel", "(", "string", ",", "upper_case_first", "=", "True", ",", "separator", "=", "'_'", ")", ":", "if", "not", "is_string", "(", "string", ")", ":", "raise", "TypeError", "(", "'Expected string'", ")", "if", "not", "is_snake_case", "...
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
shuffle
Return a new string containing shuffled items. :param string: String to shuffle :type string: str :return: Shuffled string :rtype: str
string_utils.py
def shuffle(string): """ Return a new string containing shuffled items. :param string: String to shuffle :type string: str :return: Shuffled string :rtype: str """ s = sorted(string) # turn the string into a list of chars random.shuffle(s) # shuffle the list return ''.join(s)
def shuffle(string): """ Return a new string containing shuffled items. :param string: String to shuffle :type string: str :return: Shuffled string :rtype: str """ s = sorted(string) # turn the string into a list of chars random.shuffle(s) # shuffle the list return ''.join(s)
[ "Return", "a", "new", "string", "containing", "shuffled", "items", "." ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L511-L522
[ "def", "shuffle", "(", "string", ")", ":", "s", "=", "sorted", "(", "string", ")", "# turn the string into a list of chars", "random", ".", "shuffle", "(", "s", ")", "# shuffle the list", "return", "''", ".", "join", "(", "s", ")" ]
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
strip_html
Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. :rtype: str
string_utils.py
def strip_html(string, keep_tag_content=False): """ Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool ...
def strip_html(string, keep_tag_content=False): """ Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool ...
[ "Remove", "html", "code", "contained", "into", "the", "given", "string", "." ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L525-L537
[ "def", "strip_html", "(", "string", ",", "keep_tag_content", "=", "False", ")", ":", "r", "=", "HTML_TAG_ONLY_RE", "if", "keep_tag_content", "else", "HTML_RE", "return", "r", ".", "sub", "(", "''", ",", "string", ")" ]
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
prettify
Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following: - String cannot start or end with spaces - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \*, =) must have one, ...
string_utils.py
def prettify(string): """ Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following: - String cannot start or end with spaces - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operator...
def prettify(string): """ Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following: - String cannot start or end with spaces - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operator...
[ "Turns", "an", "ugly", "text", "string", "into", "a", "beautiful", "one", "by", "applying", "a", "regex", "pipeline", "which", "ensures", "the", "following", ":" ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L540-L595
[ "def", "prettify", "(", "string", ")", ":", "def", "remove_duplicates", "(", "regex_match", ")", ":", "return", "regex_match", ".", "group", "(", "1", ")", "[", "0", "]", "def", "uppercase_first_letter_after_sign", "(", "regex_match", ")", ":", "match", "=",...
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
slugify
Converts a string into a slug using provided join sign. (**(This Is A "Test"!)** -> **this-is-a-test**) :param string: String to convert. :type string: str :param sign: Sign used to join string tokens (default to "-"). :type sign: str :return: Slugified string
string_utils.py
def slugify(string, sign='-'): """ Converts a string into a slug using provided join sign. (**(This Is A "Test"!)** -> **this-is-a-test**) :param string: String to convert. :type string: str :param sign: Sign used to join string tokens (default to "-"). :type sign: str :return: Slugifie...
def slugify(string, sign='-'): """ Converts a string into a slug using provided join sign. (**(This Is A "Test"!)** -> **this-is-a-test**) :param string: String to convert. :type string: str :param sign: Sign used to join string tokens (default to "-"). :type sign: str :return: Slugifie...
[ "Converts", "a", "string", "into", "a", "slug", "using", "provided", "join", "sign", ".", "(", "**", "(", "This", "Is", "A", "Test", "!", ")", "**", "-", ">", "**", "this", "-", "is", "-", "a", "-", "test", "**", ")" ]
daveoncode/python-string-utils
python
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L598-L630
[ "def", "slugify", "(", "string", ",", "sign", "=", "'-'", ")", ":", "if", "not", "is_string", "(", "string", ")", ":", "raise", "TypeError", "(", "'Expected string'", ")", "# unicode casting for python 2 (unicode is default for python 3)", "try", ":", "string", "=...
5dfe43c26aeecd01941c598316eb4eb7005a1492
train
setup
Initialize Sphinx extension.
nbsphinx_link/__init__.py
def setup(app): """Initialize Sphinx extension.""" app.setup_extension('nbsphinx') app.add_source_suffix('.nblink', 'linked_jupyter_notebook') app.add_source_parser(LinkedNotebookParser) app.add_config_value('nbsphinx_link_target_root', None, rebuild='env') return {'version': __version__, 'para...
def setup(app): """Initialize Sphinx extension.""" app.setup_extension('nbsphinx') app.add_source_suffix('.nblink', 'linked_jupyter_notebook') app.add_source_parser(LinkedNotebookParser) app.add_config_value('nbsphinx_link_target_root', None, rebuild='env') return {'version': __version__, 'para...
[ "Initialize", "Sphinx", "extension", "." ]
vidartf/nbsphinx-link
python
https://github.com/vidartf/nbsphinx-link/blob/d64288606a8cc50461792dd3033f5ff081602afc/nbsphinx_link/__init__.py#L100-L107
[ "def", "setup", "(", "app", ")", ":", "app", ".", "setup_extension", "(", "'nbsphinx'", ")", "app", ".", "add_source_suffix", "(", "'.nblink'", ",", "'linked_jupyter_notebook'", ")", "app", ".", "add_source_parser", "(", "LinkedNotebookParser", ")", "app", ".", ...
d64288606a8cc50461792dd3033f5ff081602afc
train
LinkedNotebookParser.parse
Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser.
nbsphinx_link/__init__.py
def parse(self, inputstring, document): """Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser. """ link = json.loads(inputstring) env = document.settings.env source_dir = os.path.dirname...
def parse(self, inputstring, document): """Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser. """ link = json.loads(inputstring) env = document.settings.env source_dir = os.path.dirname...
[ "Parse", "the", "nblink", "file", "." ]
vidartf/nbsphinx-link
python
https://github.com/vidartf/nbsphinx-link/blob/d64288606a8cc50461792dd3033f5ff081602afc/nbsphinx_link/__init__.py#L48-L96
[ "def", "parse", "(", "self", ",", "inputstring", ",", "document", ")", ":", "link", "=", "json", ".", "loads", "(", "inputstring", ")", "env", "=", "document", ".", "settings", ".", "env", "source_dir", "=", "os", ".", "path", ".", "dirname", "(", "e...
d64288606a8cc50461792dd3033f5ff081602afc
train
DuplicateScripts.finalize
Output the duplicate scripts detected.
hairball/plugins/duplicate.py
def finalize(self): """Output the duplicate scripts detected.""" if self.total_duplicate > 0: print('{} duplicate scripts found'.format(self.total_duplicate)) for duplicate in self.list_duplicate: print(duplicate)
def finalize(self): """Output the duplicate scripts detected.""" if self.total_duplicate > 0: print('{} duplicate scripts found'.format(self.total_duplicate)) for duplicate in self.list_duplicate: print(duplicate)
[ "Output", "the", "duplicate", "scripts", "detected", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/duplicate.py#L17-L22
[ "def", "finalize", "(", "self", ")", ":", "if", "self", ".", "total_duplicate", ">", "0", ":", "print", "(", "'{} duplicate scripts found'", ".", "format", "(", "self", ".", "total_duplicate", ")", ")", "for", "duplicate", "in", "self", ".", "list_duplicate"...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
DuplicateScripts.analyze
Run and return the results from the DuplicateScripts plugin. Only takes into account scripts with more than 3 blocks.
hairball/plugins/duplicate.py
def analyze(self, scratch, **kwargs): """Run and return the results from the DuplicateScripts plugin. Only takes into account scripts with more than 3 blocks. """ scripts_set = set() for script in self.iter_scripts(scratch): if script[0].type.text == 'define %s': ...
def analyze(self, scratch, **kwargs): """Run and return the results from the DuplicateScripts plugin. Only takes into account scripts with more than 3 blocks. """ scripts_set = set() for script in self.iter_scripts(scratch): if script[0].type.text == 'define %s': ...
[ "Run", "and", "return", "the", "results", "from", "the", "DuplicateScripts", "plugin", "." ]
ucsb-cs-education/hairball
python
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/duplicate.py#L24-L43
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "scripts_set", "=", "set", "(", ")", "for", "script", "in", "self", ".", "iter_scripts", "(", "scratch", ")", ":", "if", "script", "[", "0", "]", ".", "type", ".", ...
c6da8971f8a34e88ce401d36b51431715e1dff5b
train
JsonRendererFactory._set_content_type
Set response content type
nefertari/renderers.py
def _set_content_type(self, system): """ Set response content type """ request = system.get('request') if request: response = request.response ct = response.content_type if ct == response.default_content_type: response.content_type = 'applicati...
def _set_content_type(self, system): """ Set response content type """ request = system.get('request') if request: response = request.response ct = response.content_type if ct == response.default_content_type: response.content_type = 'applicati...
[ "Set", "response", "content", "type" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L35-L42
[ "def", "_set_content_type", "(", "self", ",", "system", ")", ":", "request", "=", "system", ".", "get", "(", "'request'", ")", "if", "request", ":", "response", "=", "request", ".", "response", "ct", "=", "response", ".", "content_type", "if", "ct", "=="...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
JsonRendererFactory._render_response
Render a response
nefertari/renderers.py
def _render_response(self, value, system): """ Render a response """ view = system['view'] enc_class = getattr(view, '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return json.dumps(value, cls=enc_class)
def _render_response(self, value, system): """ Render a response """ view = system['view'] enc_class = getattr(view, '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return json.dumps(value, cls=enc_class)
[ "Render", "a", "response" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L44-L50
[ "def", "_render_response", "(", "self", ",", "value", ",", "system", ")", ":", "view", "=", "system", "[", "'view'", "]", "enc_class", "=", "getattr", "(", "view", ",", "'_json_encoder'", ",", "None", ")", "if", "enc_class", "is", "None", ":", "enc_class...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
DefaultResponseRendererMixin._get_common_kwargs
Get kwargs common for all methods.
nefertari/renderers.py
def _get_common_kwargs(self, system): """ Get kwargs common for all methods. """ enc_class = getattr(system['view'], '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return { 'request': system['request'], 'encoder': enc_class...
def _get_common_kwargs(self, system): """ Get kwargs common for all methods. """ enc_class = getattr(system['view'], '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return { 'request': system['request'], 'encoder': enc_class...
[ "Get", "kwargs", "common", "for", "all", "methods", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L86-L94
[ "def", "_get_common_kwargs", "(", "self", ",", "system", ")", ":", "enc_class", "=", "getattr", "(", "system", "[", "'view'", "]", ",", "'_json_encoder'", ",", "None", ")", "if", "enc_class", "is", "None", ":", "enc_class", "=", "get_json_encoder", "(", ")...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
DefaultResponseRendererMixin._get_create_update_kwargs
Get kwargs common to create, update, replace.
nefertari/renderers.py
def _get_create_update_kwargs(self, value, common_kw): """ Get kwargs common to create, update, replace. """ kw = common_kw.copy() kw['body'] = value if '_self' in value: kw['headers'] = [('Location', value['_self'])] return kw
def _get_create_update_kwargs(self, value, common_kw): """ Get kwargs common to create, update, replace. """ kw = common_kw.copy() kw['body'] = value if '_self' in value: kw['headers'] = [('Location', value['_self'])] return kw
[ "Get", "kwargs", "common", "to", "create", "update", "replace", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L96-L102
[ "def", "_get_create_update_kwargs", "(", "self", ",", "value", ",", "common_kw", ")", ":", "kw", "=", "common_kw", ".", "copy", "(", ")", "kw", "[", "'body'", "]", "=", "value", "if", "'_self'", "in", "value", ":", "kw", "[", "'headers'", "]", "=", "...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
DefaultResponseRendererMixin.render_create
Render response for view `create` method (collection POST)
nefertari/renderers.py
def render_create(self, value, system, common_kw): """ Render response for view `create` method (collection POST) """ kw = self._get_create_update_kwargs(value, common_kw) return JHTTPCreated(**kw)
def render_create(self, value, system, common_kw): """ Render response for view `create` method (collection POST) """ kw = self._get_create_update_kwargs(value, common_kw) return JHTTPCreated(**kw)
[ "Render", "response", "for", "view", "create", "method", "(", "collection", "POST", ")" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L104-L107
[ "def", "render_create", "(", "self", ",", "value", ",", "system", ",", "common_kw", ")", ":", "kw", "=", "self", ".", "_get_create_update_kwargs", "(", "value", ",", "common_kw", ")", "return", "JHTTPCreated", "(", "*", "*", "kw", ")" ]
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
DefaultResponseRendererMixin.render_update
Render response for view `update` method (item PATCH)
nefertari/renderers.py
def render_update(self, value, system, common_kw): """ Render response for view `update` method (item PATCH) """ kw = self._get_create_update_kwargs(value, common_kw) return JHTTPOk('Updated', **kw)
def render_update(self, value, system, common_kw): """ Render response for view `update` method (item PATCH) """ kw = self._get_create_update_kwargs(value, common_kw) return JHTTPOk('Updated', **kw)
[ "Render", "response", "for", "view", "update", "method", "(", "item", "PATCH", ")" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L109-L112
[ "def", "render_update", "(", "self", ",", "value", ",", "system", ",", "common_kw", ")", ":", "kw", "=", "self", ".", "_get_create_update_kwargs", "(", "value", ",", "common_kw", ")", "return", "JHTTPOk", "(", "'Updated'", ",", "*", "*", "kw", ")" ]
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
DefaultResponseRendererMixin.render_delete_many
Render response for view `delete_many` method (collection DELETE)
nefertari/renderers.py
def render_delete_many(self, value, system, common_kw): """ Render response for view `delete_many` method (collection DELETE) """ if isinstance(value, dict): return JHTTPOk(extra=value) msg = 'Deleted {} {}(s) objects'.format( value, system['view'].Model.__name__)...
def render_delete_many(self, value, system, common_kw): """ Render response for view `delete_many` method (collection DELETE) """ if isinstance(value, dict): return JHTTPOk(extra=value) msg = 'Deleted {} {}(s) objects'.format( value, system['view'].Model.__name__)...
[ "Render", "response", "for", "view", "delete_many", "method", "(", "collection", "DELETE", ")" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L122-L129
[ "def", "render_delete_many", "(", "self", ",", "value", ",", "system", ",", "common_kw", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "JHTTPOk", "(", "extra", "=", "value", ")", "msg", "=", "'Deleted {} {}(s) objects'", ".",...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
DefaultResponseRendererMixin.render_update_many
Render response for view `update_many` method (collection PUT/PATCH)
nefertari/renderers.py
def render_update_many(self, value, system, common_kw): """ Render response for view `update_many` method (collection PUT/PATCH) """ msg = 'Updated {} {}(s) objects'.format( value, system['view'].Model.__name__) return JHTTPOk(msg, **common_kw.copy())
def render_update_many(self, value, system, common_kw): """ Render response for view `update_many` method (collection PUT/PATCH) """ msg = 'Updated {} {}(s) objects'.format( value, system['view'].Model.__name__) return JHTTPOk(msg, **common_kw.copy())
[ "Render", "response", "for", "view", "update_many", "method", "(", "collection", "PUT", "/", "PATCH", ")" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L131-L137
[ "def", "render_update_many", "(", "self", ",", "value", ",", "system", ",", "common_kw", ")", ":", "msg", "=", "'Updated {} {}(s) objects'", ".", "format", "(", "value", ",", "system", "[", "'view'", "]", ".", "Model", ".", "__name__", ")", "return", "JHTT...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
DefaultResponseRendererMixin._render_response
Handle response rendering. Calls mixin methods according to request.action value.
nefertari/renderers.py
def _render_response(self, value, system): """ Handle response rendering. Calls mixin methods according to request.action value. """ super_call = super(DefaultResponseRendererMixin, self)._render_response try: method_name = 'render_{}'.format(system['request'].action...
def _render_response(self, value, system): """ Handle response rendering. Calls mixin methods according to request.action value. """ super_call = super(DefaultResponseRendererMixin, self)._render_response try: method_name = 'render_{}'.format(system['request'].action...
[ "Handle", "response", "rendering", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L139-L155
[ "def", "_render_response", "(", "self", ",", "value", ",", "system", ")", ":", "super_call", "=", "super", "(", "DefaultResponseRendererMixin", ",", "self", ")", ".", "_render_response", "try", ":", "method_name", "=", "'render_{}'", ".", "format", "(", "syste...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
ApiKeyAuthenticationPolicy.remember
Returns 'WWW-Authenticate' header with a value that should be used in 'Authorization' header.
nefertari/authentication/policies.py
def remember(self, request, username, **kw): """ Returns 'WWW-Authenticate' header with a value that should be used in 'Authorization' header. """ if self.credentials_callback: token = self.credentials_callback(username, request) api_key = 'ApiKey {}:{}'.format(us...
def remember(self, request, username, **kw): """ Returns 'WWW-Authenticate' header with a value that should be used in 'Authorization' header. """ if self.credentials_callback: token = self.credentials_callback(username, request) api_key = 'ApiKey {}:{}'.format(us...
[ "Returns", "WWW", "-", "Authenticate", "header", "with", "a", "value", "that", "should", "be", "used", "in", "Authorization", "header", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/policies.py#L49-L56
[ "def", "remember", "(", "self", ",", "request", ",", "username", ",", "*", "*", "kw", ")", ":", "if", "self", ".", "credentials_callback", ":", "token", "=", "self", ".", "credentials_callback", "(", "username", ",", "request", ")", "api_key", "=", "'Api...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
ApiKeyAuthenticationPolicy.callback
Having :username: return user's identifiers or None.
nefertari/authentication/policies.py
def callback(self, username, request): """ Having :username: return user's identifiers or None. """ credentials = self._get_credentials(request) if credentials: username, api_key = credentials if self.check: return self.check(username, api_key, request)
def callback(self, username, request): """ Having :username: return user's identifiers or None. """ credentials = self._get_credentials(request) if credentials: username, api_key = credentials if self.check: return self.check(username, api_key, request)
[ "Having", ":", "username", ":", "return", "user", "s", "identifiers", "or", "None", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/policies.py#L69-L75
[ "def", "callback", "(", "self", ",", "username", ",", "request", ")", ":", "credentials", "=", "self", ".", "_get_credentials", "(", "request", ")", "if", "credentials", ":", "username", ",", "api_key", "=", "credentials", "if", "self", ".", "check", ":", ...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
ApiKeyAuthenticationPolicy._get_credentials
Extract username and api key token from 'Authorization' header
nefertari/authentication/policies.py
def _get_credentials(self, request): """ Extract username and api key token from 'Authorization' header """ authorization = request.headers.get('Authorization') if not authorization: return None try: authmeth, authbytes = authorization.split(' ', 1) except...
def _get_credentials(self, request): """ Extract username and api key token from 'Authorization' header """ authorization = request.headers.get('Authorization') if not authorization: return None try: authmeth, authbytes = authorization.split(' ', 1) except...
[ "Extract", "username", "and", "api", "key", "token", "from", "Authorization", "header" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/policies.py#L77-L101
[ "def", "_get_credentials", "(", "self", ",", "request", ")", ":", "authorization", "=", "request", ".", "headers", ".", "get", "(", "'Authorization'", ")", "if", "not", "authorization", ":", "return", "None", "try", ":", "authmeth", ",", "authbytes", "=", ...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
_get_event_kwargs
Helper function to get event kwargs. :param view_obj: Instance of View that processes the request. :returns dict: Containing event kwargs or None if events shouldn't be fired.
nefertari/events.py
def _get_event_kwargs(view_obj): """ Helper function to get event kwargs. :param view_obj: Instance of View that processes the request. :returns dict: Containing event kwargs or None if events shouldn't be fired. """ request = view_obj.request view_method = getattr(view_obj, request.ac...
def _get_event_kwargs(view_obj): """ Helper function to get event kwargs. :param view_obj: Instance of View that processes the request. :returns dict: Containing event kwargs or None if events shouldn't be fired. """ request = view_obj.request view_method = getattr(view_obj, request.ac...
[ "Helper", "function", "to", "get", "event", "kwargs", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L305-L330
[ "def", "_get_event_kwargs", "(", "view_obj", ")", ":", "request", "=", "view_obj", ".", "request", "view_method", "=", "getattr", "(", "view_obj", ",", "request", ".", "action", ")", "do_trigger", "=", "not", "(", "getattr", "(", "view_method", ",", "'_silen...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
_get_event_cls
Helper function to get event class. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Found event class.
nefertari/events.py
def _get_event_cls(view_obj, events_map): """ Helper function to get event class. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Found event class. """ request = view_obj.request view_...
def _get_event_cls(view_obj, events_map): """ Helper function to get event class. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Found event class. """ request = view_obj.request view_...
[ "Helper", "function", "to", "get", "event", "class", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L333-L346
[ "def", "_get_event_cls", "(", "view_obj", ",", "events_map", ")", ":", "request", "=", "view_obj", ".", "request", "view_method", "=", "getattr", "(", "view_obj", ",", "request", ".", "action", ")", "event_action", "=", "(", "getattr", "(", "view_method", ",...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
_trigger_events
Common logic to trigger before/after events. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Instance if triggered event.
nefertari/events.py
def _trigger_events(view_obj, events_map, additional_kw=None): """ Common logic to trigger before/after events. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Instance if triggered event. """ ...
def _trigger_events(view_obj, events_map, additional_kw=None): """ Common logic to trigger before/after events. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Instance if triggered event. """ ...
[ "Common", "logic", "to", "trigger", "before", "/", "after", "events", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L349-L368
[ "def", "_trigger_events", "(", "view_obj", ",", "events_map", ",", "additional_kw", "=", "None", ")", ":", "if", "additional_kw", "is", "None", ":", "additional_kw", "=", "{", "}", "event_kwargs", "=", "_get_event_kwargs", "(", "view_obj", ")", "if", "event_kw...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
subscribe_to_events
Helper function to subscribe to group of events. :param config: Pyramid contig instance. :param subscriber: Event subscriber function. :param events: Sequence of events to subscribe to. :param model: Model predicate value.
nefertari/events.py
def subscribe_to_events(config, subscriber, events, model=None): """ Helper function to subscribe to group of events. :param config: Pyramid contig instance. :param subscriber: Event subscriber function. :param events: Sequence of events to subscribe to. :param model: Model predicate value. """...
def subscribe_to_events(config, subscriber, events, model=None): """ Helper function to subscribe to group of events. :param config: Pyramid contig instance. :param subscriber: Event subscriber function. :param events: Sequence of events to subscribe to. :param model: Model predicate value. """...
[ "Helper", "function", "to", "subscribe", "to", "group", "of", "events", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L393-L406
[ "def", "subscribe_to_events", "(", "config", ",", "subscriber", ",", "events", ",", "model", "=", "None", ")", ":", "kwargs", "=", "{", "}", "if", "model", "is", "not", "None", ":", "kwargs", "[", "'model'", "]", "=", "model", "for", "evt", "in", "ev...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
add_field_processors
Add processors for model field. Under the hood, regular nefertari event subscribed is created which calls field processors in order passed to this function. Processors are passed following params: * **new_value**: New value of of field. * **instance**: Instance affected by request. Is None when s...
nefertari/events.py
def add_field_processors(config, processors, model, field): """ Add processors for model field. Under the hood, regular nefertari event subscribed is created which calls field processors in order passed to this function. Processors are passed following params: * **new_value**: New value of of fie...
def add_field_processors(config, processors, model, field): """ Add processors for model field. Under the hood, regular nefertari event subscribed is created which calls field processors in order passed to this function. Processors are passed following params: * **new_value**: New value of of fie...
[ "Add", "processors", "for", "model", "field", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L409-L459
[ "def", "add_field_processors", "(", "config", ",", "processors", ",", "model", ",", "field", ")", ":", "before_change_events", "=", "(", "BeforeCreate", ",", "BeforeUpdate", ",", "BeforeReplace", ",", "BeforeUpdateMany", ",", "BeforeRegister", ",", ")", "def", "...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
BeforeEvent.set_field_value
Set value of request field named `field_name`. Use this method to apply changes to object which is affected by request. Values are set on `view._json_params` dict. If `field_name` is not affected by request, it is added to `self.fields` which makes field processors which are connected ...
nefertari/events.py
def set_field_value(self, field_name, value): """ Set value of request field named `field_name`. Use this method to apply changes to object which is affected by request. Values are set on `view._json_params` dict. If `field_name` is not affected by request, it is added to `self...
def set_field_value(self, field_name, value): """ Set value of request field named `field_name`. Use this method to apply changes to object which is affected by request. Values are set on `view._json_params` dict. If `field_name` is not affected by request, it is added to `self...
[ "Set", "value", "of", "request", "field", "named", "field_name", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L46-L68
[ "def", "set_field_value", "(", "self", ",", "field_name", ",", "value", ")", ":", "self", ".", "view", ".", "_json_params", "[", "field_name", "]", "=", "value", "if", "field_name", "in", "self", ".", "fields", ":", "self", ".", "fields", "[", "field_nam...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
AfterEvent.set_field_value
Set value of response field named `field_name`. If response contains single item, its field is set. If response contains multiple items, all the items in response are edited. To edit response meta(e.g. 'count') edit response directly at `event.response`. :param field_na...
nefertari/events.py
def set_field_value(self, field_name, value): """ Set value of response field named `field_name`. If response contains single item, its field is set. If response contains multiple items, all the items in response are edited. To edit response meta(e.g. 'count') edit response dire...
def set_field_value(self, field_name, value): """ Set value of response field named `field_name`. If response contains single item, its field is set. If response contains multiple items, all the items in response are edited. To edit response meta(e.g. 'count') edit response dire...
[ "Set", "value", "of", "response", "field", "named", "field_name", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L76-L98
[ "def", "set_field_value", "(", "self", ",", "field_name", ",", "value", ")", ":", "if", "self", ".", "response", "is", "None", ":", "return", "if", "'data'", "in", "self", ".", "response", ":", "items", "=", "self", ".", "response", "[", "'data'", "]",...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
process_fields_param
Process 'fields' ES param. * Fields list is split if needed * '_type' field is added, if not present, so the actual value is displayed instead of 'None'
nefertari/elasticsearch.py
def process_fields_param(fields): """ Process 'fields' ES param. * Fields list is split if needed * '_type' field is added, if not present, so the actual value is displayed instead of 'None' """ if not fields: return fields if isinstance(fields, six.string_types): fields =...
def process_fields_param(fields): """ Process 'fields' ES param. * Fields list is split if needed * '_type' field is added, if not present, so the actual value is displayed instead of 'None' """ if not fields: return fields if isinstance(fields, six.string_types): fields =...
[ "Process", "fields", "ES", "param", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L98-L114
[ "def", "process_fields_param", "(", "fields", ")", ":", "if", "not", "fields", ":", "return", "fields", "if", "isinstance", "(", "fields", ",", "six", ".", "string_types", ")", ":", "fields", "=", "split_strip", "(", "fields", ")", "if", "'_type'", "not", ...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
ESHttpConnection._catch_index_error
Catch and raise index errors which are not critical and thus not raised by elasticsearch-py.
nefertari/elasticsearch.py
def _catch_index_error(self, response): """ Catch and raise index errors which are not critical and thus not raised by elasticsearch-py. """ code, headers, raw_data = response if not raw_data: return data = json.loads(raw_data) if not data or not data....
def _catch_index_error(self, response): """ Catch and raise index errors which are not critical and thus not raised by elasticsearch-py. """ code, headers, raw_data = response if not raw_data: return data = json.loads(raw_data) if not data or not data....
[ "Catch", "and", "raise", "index", "errors", "which", "are", "not", "critical", "and", "thus", "not", "raised", "by", "elasticsearch", "-", "py", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L25-L40
[ "def", "_catch_index_error", "(", "self", ",", "response", ")", ":", "code", ",", "headers", ",", "raw_data", "=", "response", "if", "not", "raw_data", ":", "return", "data", "=", "json", ".", "loads", "(", "raw_data", ")", "if", "not", "data", "or", "...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
ES.setup_mappings
Setup ES mappings for all existing models. This method is meant to be run once at application lauch. ES._mappings_setup flag is set to not run make mapping creation calls on subsequent runs. Use `force=True` to make subsequent calls perform mapping creation calls to ES.
nefertari/elasticsearch.py
def setup_mappings(cls, force=False): """ Setup ES mappings for all existing models. This method is meant to be run once at application lauch. ES._mappings_setup flag is set to not run make mapping creation calls on subsequent runs. Use `force=True` to make subsequent calls per...
def setup_mappings(cls, force=False): """ Setup ES mappings for all existing models. This method is meant to be run once at application lauch. ES._mappings_setup flag is set to not run make mapping creation calls on subsequent runs. Use `force=True` to make subsequent calls per...
[ "Setup", "ES", "mappings", "for", "all", "existing", "models", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L226-L250
[ "def", "setup_mappings", "(", "cls", ",", "force", "=", "False", ")", ":", "if", "getattr", "(", "cls", ",", "'_mappings_setup'", ",", "False", ")", "and", "not", "force", ":", "log", ".", "debug", "(", "'ES mappings have been already set up for currently '", ...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
ES.process_chunks
Apply `operation` to chunks of `documents` of size `self.chunk_size`.
nefertari/elasticsearch.py
def process_chunks(self, documents, operation): """ Apply `operation` to chunks of `documents` of size `self.chunk_size`. """ chunk_size = self.chunk_size start = end = 0 count = len(documents) while count: if count < chunk_size: chun...
def process_chunks(self, documents, operation): """ Apply `operation` to chunks of `documents` of size `self.chunk_size`. """ chunk_size = self.chunk_size start = end = 0 count = len(documents) while count: if count < chunk_size: chun...
[ "Apply", "operation", "to", "chunks", "of", "documents", "of", "size", "self", ".", "chunk_size", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L259-L277
[ "def", "process_chunks", "(", "self", ",", "documents", ",", "operation", ")", ":", "chunk_size", "=", "self", ".", "chunk_size", "start", "=", "end", "=", "0", "count", "=", "len", "(", "documents", ")", "while", "count", ":", "if", "count", "<", "chu...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
ES.index_missing_documents
Index documents that are missing from ES index. Determines which documents are missing using ES `mget` call which returns a list of document IDs as `documents`. Then missing `documents` from that list are indexed.
nefertari/elasticsearch.py
def index_missing_documents(self, documents, request=None): """ Index documents that are missing from ES index. Determines which documents are missing using ES `mget` call which returns a list of document IDs as `documents`. Then missing `documents` from that list are indexed. "...
def index_missing_documents(self, documents, request=None): """ Index documents that are missing from ES index. Determines which documents are missing using ES `mget` call which returns a list of document IDs as `documents`. Then missing `documents` from that list are indexed. "...
[ "Index", "documents", "that", "are", "missing", "from", "ES", "index", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L326-L358
[ "def", "index_missing_documents", "(", "self", ",", "documents", ",", "request", "=", "None", ")", ":", "log", ".", "info", "(", "'Trying to index documents of type `{}` missing from '", "'`{}` index'", ".", "format", "(", "self", ".", "doc_type", ",", "self", "."...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
ES.aggregate
Perform aggreration Arguments: :_aggregations_params: Dict of aggregation params. Root key is an aggregation name. Required. :_raise_on_empty: Boolean indicating whether to raise exception when IndexNotFoundException exception happens. Optional, ...
nefertari/elasticsearch.py
def aggregate(self, **params): """ Perform aggreration Arguments: :_aggregations_params: Dict of aggregation params. Root key is an aggregation name. Required. :_raise_on_empty: Boolean indicating whether to raise exception when IndexNotFoundExcep...
def aggregate(self, **params): """ Perform aggreration Arguments: :_aggregations_params: Dict of aggregation params. Root key is an aggregation name. Required. :_raise_on_empty: Boolean indicating whether to raise exception when IndexNotFoundExcep...
[ "Perform", "aggreration" ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L493-L530
[ "def", "aggregate", "(", "self", ",", "*", "*", "params", ")", ":", "_aggregations_params", "=", "params", ".", "pop", "(", "'_aggregations_params'", ",", "None", ")", "_raise_on_empty", "=", "params", ".", "pop", "(", "'_raise_on_empty'", ",", "False", ")",...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
ES.bulk_index_relations
Index objects related to :items: in bulk. Related items are first grouped in map {model_name: {item1, item2, ...}} and then indexed. :param items: Sequence of DB objects related objects if which should be indexed. :param request: Pyramid Request instance.
nefertari/elasticsearch.py
def bulk_index_relations(cls, items, request=None, **kwargs): """ Index objects related to :items: in bulk. Related items are first grouped in map {model_name: {item1, item2, ...}} and then indexed. :param items: Sequence of DB objects related objects if which should be ind...
def bulk_index_relations(cls, items, request=None, **kwargs): """ Index objects related to :items: in bulk. Related items are first grouped in map {model_name: {item1, item2, ...}} and then indexed. :param items: Sequence of DB objects related objects if which should be ind...
[ "Index", "objects", "related", "to", ":", "items", ":", "in", "bulk", "." ]
ramses-tech/nefertari
python
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L620-L639
[ "def", "bulk_index_relations", "(", "cls", ",", "items", ",", "request", "=", "None", ",", "*", "*", "kwargs", ")", ":", "index_map", "=", "defaultdict", "(", "set", ")", "for", "item", "in", "items", ":", "relations", "=", "item", ".", "get_related_docu...
c7caffe11576c11aa111adbdbadeff70ce66b1dd
train
get_version
Return the version of by with regex intead of importing it
setup.py
def get_version(path="src/devpy/__init__.py"): """ Return the version of by with regex intead of importing it""" init_content = open(path, "rt").read() pattern = r"^__version__ = ['\"]([^'\"]*)['\"]" return re.search(pattern, init_content, re.M).group(1)
def get_version(path="src/devpy/__init__.py"): """ Return the version of by with regex intead of importing it""" init_content = open(path, "rt").read() pattern = r"^__version__ = ['\"]([^'\"]*)['\"]" return re.search(pattern, init_content, re.M).group(1)
[ "Return", "the", "version", "of", "by", "with", "regex", "intead", "of", "importing", "it" ]
sametmax/devpy
python
https://github.com/sametmax/devpy/blob/66a150817644edf825d19b80f644e7d05b2a3e86/setup.py#L7-L11
[ "def", "get_version", "(", "path", "=", "\"src/devpy/__init__.py\"", ")", ":", "init_content", "=", "open", "(", "path", ",", "\"rt\"", ")", ".", "read", "(", ")", "pattern", "=", "r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"", "return", "re", ".", "search", "(...
66a150817644edf825d19b80f644e7d05b2a3e86