repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
inspirehep/inspire-utils
inspire_utils/helpers.py
force_list
def force_list(data): """Force ``data`` to become a list. You should use this method whenever you don't want to deal with the fact that ``NoneType`` can't be iterated over. For example, instead of writing:: bar = foo.get('bar') if bar is not None: for el in bar: ...
python
def force_list(data): """Force ``data`` to become a list. You should use this method whenever you don't want to deal with the fact that ``NoneType`` can't be iterated over. For example, instead of writing:: bar = foo.get('bar') if bar is not None: for el in bar: ...
[ "def", "force_list", "(", "data", ")", ":", "if", "data", "is", "None", ":", "return", "[", "]", "elif", "not", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "return", "[", "data", "]", "elif", "isinstance", ...
Force ``data`` to become a list. You should use this method whenever you don't want to deal with the fact that ``NoneType`` can't be iterated over. For example, instead of writing:: bar = foo.get('bar') if bar is not None: for el in bar: ... you can write::...
[ "Force", "data", "to", "become", "a", "list", "." ]
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/helpers.py#L30-L70
inspirehep/inspire-utils
inspire_utils/helpers.py
remove_tags
def remove_tags(dirty, allowed_tags=(), allowed_trees=(), strip=None): """Selectively remove tags. This removes all tags in ``dirty``, stripping also the contents of tags matching the XPath selector in ``strip``, and keeping all tags that are subtags of tags in ``allowed_trees`` and tags in ``allowed_t...
python
def remove_tags(dirty, allowed_tags=(), allowed_trees=(), strip=None): """Selectively remove tags. This removes all tags in ``dirty``, stripping also the contents of tags matching the XPath selector in ``strip``, and keeping all tags that are subtags of tags in ``allowed_trees`` and tags in ``allowed_t...
[ "def", "remove_tags", "(", "dirty", ",", "allowed_tags", "=", "(", ")", ",", "allowed_trees", "=", "(", ")", ",", "strip", "=", "None", ")", ":", "if", "isinstance", "(", "dirty", ",", "six", ".", "string_types", ")", ":", "element", "=", "etree", "....
Selectively remove tags. This removes all tags in ``dirty``, stripping also the contents of tags matching the XPath selector in ``strip``, and keeping all tags that are subtags of tags in ``allowed_trees`` and tags in ``allowed_tags``. Args: dirty(Union[str, scrapy.selector.Selector, lxml.etre...
[ "Selectively", "remove", "tags", "." ]
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/helpers.py#L113-L171
conchoecia/gloTK
gloTK/scripts/glotk_project.py
main
def main(): """ 1. Reads in a meraculous config file and outputs glotk project files """ parser = CommandLine() #this block from here: http://stackoverflow.com/a/4042861/5843327 if len(sys.argv)==1: parser.parser.print_help() sys.exit(1) parser.parse() myArgs = parser.arg...
python
def main(): """ 1. Reads in a meraculous config file and outputs glotk project files """ parser = CommandLine() #this block from here: http://stackoverflow.com/a/4042861/5843327 if len(sys.argv)==1: parser.parser.print_help() sys.exit(1) parser.parse() myArgs = parser.arg...
[ "def", "main", "(", ")", ":", "parser", "=", "CommandLine", "(", ")", "#this block from here: http://stackoverflow.com/a/4042861/5843327", "if", "len", "(", "sys", ".", "argv", ")", "==", "1", ":", "parser", ".", "parser", ".", "print_help", "(", ")", "sys", ...
1. Reads in a meraculous config file and outputs glotk project files
[ "1", ".", "Reads", "in", "a", "meraculous", "config", "file", "and", "outputs", "glotk", "project", "files" ]
train
https://github.com/conchoecia/gloTK/blob/58abee663fcfbbd09f4863c3ca3ae054e33184a8/gloTK/scripts/glotk_project.py#L91-L129
jkehler/redisqueue
redisqueue/__init__.py
RedisQueue.connect
def connect(self, **kwargs): """ Connect to the Redis Server :param kwargs: Parameters passed directly to redis library :return: Boolean indicating if connection successful :kwarg host: Hostname of the Redis server :kwarg port: Port of the Redis server :kwarg pa...
python
def connect(self, **kwargs): """ Connect to the Redis Server :param kwargs: Parameters passed directly to redis library :return: Boolean indicating if connection successful :kwarg host: Hostname of the Redis server :kwarg port: Port of the Redis server :kwarg pa...
[ "def", "connect", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__db", "=", "redis", ".", "Redis", "(", "*", "*", "kwargs", ")", "try", ":", "self", ".", "__db", ".", "info", "(", ")", "self", ".", "connected", "=", "True", "exc...
Connect to the Redis Server :param kwargs: Parameters passed directly to redis library :return: Boolean indicating if connection successful :kwarg host: Hostname of the Redis server :kwarg port: Port of the Redis server :kwarg password: Auth key for the Redis server
[ "Connect", "to", "the", "Redis", "Server" ]
train
https://github.com/jkehler/redisqueue/blob/feac4dfc30837e0ab1a55a8479443ea74b2793f2/redisqueue/__init__.py#L55-L75
jkehler/redisqueue
redisqueue/__init__.py
RedisQueue.clear
def clear(self): """ Clear all Tasks in the queue. """ if not self.connected: raise QueueNotConnectedError("Queue is not Connected") self.__db.delete(self._key) self.__db.delete(self._lock_key)
python
def clear(self): """ Clear all Tasks in the queue. """ if not self.connected: raise QueueNotConnectedError("Queue is not Connected") self.__db.delete(self._key) self.__db.delete(self._lock_key)
[ "def", "clear", "(", "self", ")", ":", "if", "not", "self", ".", "connected", ":", "raise", "QueueNotConnectedError", "(", "\"Queue is not Connected\"", ")", "self", ".", "__db", ".", "delete", "(", "self", ".", "_key", ")", "self", ".", "__db", ".", "de...
Clear all Tasks in the queue.
[ "Clear", "all", "Tasks", "in", "the", "queue", "." ]
train
https://github.com/jkehler/redisqueue/blob/feac4dfc30837e0ab1a55a8479443ea74b2793f2/redisqueue/__init__.py#L77-L86
jkehler/redisqueue
redisqueue/__init__.py
RedisQueue.qsize
def qsize(self): """ Returns the number of items currently in the queue :return: Integer containing size of the queue :exception: ConnectionError if queue is not connected """ if not self.connected: raise QueueNotConnectedError("Queue is not Connected") ...
python
def qsize(self): """ Returns the number of items currently in the queue :return: Integer containing size of the queue :exception: ConnectionError if queue is not connected """ if not self.connected: raise QueueNotConnectedError("Queue is not Connected") ...
[ "def", "qsize", "(", "self", ")", ":", "if", "not", "self", ".", "connected", ":", "raise", "QueueNotConnectedError", "(", "\"Queue is not Connected\"", ")", "try", ":", "size", "=", "self", ".", "__db", ".", "llen", "(", "self", ".", "_key", ")", "excep...
Returns the number of items currently in the queue :return: Integer containing size of the queue :exception: ConnectionError if queue is not connected
[ "Returns", "the", "number", "of", "items", "currently", "in", "the", "queue" ]
train
https://github.com/jkehler/redisqueue/blob/feac4dfc30837e0ab1a55a8479443ea74b2793f2/redisqueue/__init__.py#L89-L103
jkehler/redisqueue
redisqueue/__init__.py
RedisQueue.put
def put(self, task): """ Inserts a Task into the queue :param task: :class:`~redisqueue.AbstractTask` instance :return: Boolean insert success state :exception: ConnectionError if queue is not connected """ if not self.connected: raise QueueNotConnec...
python
def put(self, task): """ Inserts a Task into the queue :param task: :class:`~redisqueue.AbstractTask` instance :return: Boolean insert success state :exception: ConnectionError if queue is not connected """ if not self.connected: raise QueueNotConnec...
[ "def", "put", "(", "self", ",", "task", ")", ":", "if", "not", "self", ".", "connected", ":", "raise", "QueueNotConnectedError", "(", "\"Queue is not Connected\"", ")", "if", "task", ".", "unique", ":", "# first lets check if we have this hash already in our queue", ...
Inserts a Task into the queue :param task: :class:`~redisqueue.AbstractTask` instance :return: Boolean insert success state :exception: ConnectionError if queue is not connected
[ "Inserts", "a", "Task", "into", "the", "queue" ]
train
https://github.com/jkehler/redisqueue/blob/feac4dfc30837e0ab1a55a8479443ea74b2793f2/redisqueue/__init__.py#L105-L128
jkehler/redisqueue
redisqueue/__init__.py
RedisQueue.get
def get(self, block=True, timeout=None): """ Get a Task from the queue :param block: Block application until a Task is received :param timeout: Timeout after n seconds :return: :class:`~redisqueue.AbstractTask` instance :exception: ConnectionError if queue is not connect...
python
def get(self, block=True, timeout=None): """ Get a Task from the queue :param block: Block application until a Task is received :param timeout: Timeout after n seconds :return: :class:`~redisqueue.AbstractTask` instance :exception: ConnectionError if queue is not connect...
[ "def", "get", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "connected", ":", "raise", "QueueNotConnectedError", "(", "\"Queue is not Connected\"", ")", "if", "block", ":", "payload", "=", "self", ...
Get a Task from the queue :param block: Block application until a Task is received :param timeout: Timeout after n seconds :return: :class:`~redisqueue.AbstractTask` instance :exception: ConnectionError if queue is not connected
[ "Get", "a", "Task", "from", "the", "queue" ]
train
https://github.com/jkehler/redisqueue/blob/feac4dfc30837e0ab1a55a8479443ea74b2793f2/redisqueue/__init__.py#L130-L157
jkehler/redisqueue
redisqueue/__init__.py
AbstractTask.from_json
def from_json(self, json_data): """ Load JSON data into this Task """ try: data = json_data.decode() except Exception: data = json_data self.__dict__ = json.loads(data)
python
def from_json(self, json_data): """ Load JSON data into this Task """ try: data = json_data.decode() except Exception: data = json_data self.__dict__ = json.loads(data)
[ "def", "from_json", "(", "self", ",", "json_data", ")", ":", "try", ":", "data", "=", "json_data", ".", "decode", "(", ")", "except", "Exception", ":", "data", "=", "json_data", "self", ".", "__dict__", "=", "json", ".", "loads", "(", "data", ")" ]
Load JSON data into this Task
[ "Load", "JSON", "data", "into", "this", "Task" ]
train
https://github.com/jkehler/redisqueue/blob/feac4dfc30837e0ab1a55a8479443ea74b2793f2/redisqueue/__init__.py#L194-L202
mmoussallam/bird
bird/_bird.py
_single_mp_run
def _single_mp_run(x, Phi, bound, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): """ run of the RSSMP algorithm """ rng = check_random_state(random_state) pad = int(pad) x = np.concatenate((np.zeros(pad), x, np.zeros(pad))) n = x.size m = Phi.doth(x...
python
def _single_mp_run(x, Phi, bound, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): """ run of the RSSMP algorithm """ rng = check_random_state(random_state) pad = int(pad) x = np.concatenate((np.zeros(pad), x, np.zeros(pad))) n = x.size m = Phi.doth(x...
[ "def", "_single_mp_run", "(", "x", ",", "Phi", ",", "bound", ",", "max_iter", ",", "verbose", "=", "False", ",", "pad", "=", "0", ",", "random_state", "=", "None", ",", "memory", "=", "Memory", "(", "None", ")", ")", ":", "rng", "=", "check_random_st...
run of the RSSMP algorithm
[ "run", "of", "the", "RSSMP", "algorithm" ]
train
https://github.com/mmoussallam/bird/blob/1c726e6569db4f3b00804ab7ac063acaa3965987/bird/_bird.py#L42-L108
mmoussallam/bird
bird/_bird.py
_single_multichannel_mp_run
def _single_multichannel_mp_run(X, Phi, bound, selection_rule, stop_crit, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): """ run of the structured variant of the RSSMP algorithm """ rng = check_random_state(random_state) ...
python
def _single_multichannel_mp_run(X, Phi, bound, selection_rule, stop_crit, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): """ run of the structured variant of the RSSMP algorithm """ rng = check_random_state(random_state) ...
[ "def", "_single_multichannel_mp_run", "(", "X", ",", "Phi", ",", "bound", ",", "selection_rule", ",", "stop_crit", ",", "max_iter", ",", "verbose", "=", "False", ",", "pad", "=", "0", ",", "random_state", "=", "None", ",", "memory", "=", "Memory", "(", "...
run of the structured variant of the RSSMP algorithm
[ "run", "of", "the", "structured", "variant", "of", "the", "RSSMP", "algorithm" ]
train
https://github.com/mmoussallam/bird/blob/1c726e6569db4f3b00804ab7ac063acaa3965987/bird/_bird.py#L111-L196
mmoussallam/bird
bird/_bird.py
_pad
def _pad(X): """ add zeroes on the border to make sure the signal length is a power of two """ p_above = int(np.floor(np.log2(X.shape[1]))) M = 2 ** (p_above + 1) - X.shape[1] X = np.hstack((np.zeros((X.shape[0], M)), X)) return X, M
python
def _pad(X): """ add zeroes on the border to make sure the signal length is a power of two """ p_above = int(np.floor(np.log2(X.shape[1]))) M = 2 ** (p_above + 1) - X.shape[1] X = np.hstack((np.zeros((X.shape[0], M)), X)) return X, M
[ "def", "_pad", "(", "X", ")", ":", "p_above", "=", "int", "(", "np", ".", "floor", "(", "np", ".", "log2", "(", "X", ".", "shape", "[", "1", "]", ")", ")", ")", "M", "=", "2", "**", "(", "p_above", "+", "1", ")", "-", "X", ".", "shape", ...
add zeroes on the border to make sure the signal length is a power of two
[ "add", "zeroes", "on", "the", "border", "to", "make", "sure", "the", "signal", "length", "is", "a", "power", "of", "two" ]
train
https://github.com/mmoussallam/bird/blob/1c726e6569db4f3b00804ab7ac063acaa3965987/bird/_bird.py#L199-L206
mmoussallam/bird
bird/_bird.py
_denoise
def _denoise(seeds, x, dico, sup_bound, n_atoms, verbose=False, indep=True, stop_crit=None, selection_rule=None, pad=0, memory=Memory(None)): """ multiple rssmp runs with a smart stopping criterion using the convergence decay monitoring """ approx = [] for seed in seeds: ...
python
def _denoise(seeds, x, dico, sup_bound, n_atoms, verbose=False, indep=True, stop_crit=None, selection_rule=None, pad=0, memory=Memory(None)): """ multiple rssmp runs with a smart stopping criterion using the convergence decay monitoring """ approx = [] for seed in seeds: ...
[ "def", "_denoise", "(", "seeds", ",", "x", ",", "dico", ",", "sup_bound", ",", "n_atoms", ",", "verbose", "=", "False", ",", "indep", "=", "True", ",", "stop_crit", "=", "None", ",", "selection_rule", "=", "None", ",", "pad", "=", "0", ",", "memory",...
multiple rssmp runs with a smart stopping criterion using the convergence decay monitoring
[ "multiple", "rssmp", "runs", "with", "a", "smart", "stopping", "criterion", "using", "the", "convergence", "decay", "monitoring" ]
train
https://github.com/mmoussallam/bird/blob/1c726e6569db4f3b00804ab7ac063acaa3965987/bird/_bird.py#L209-L232
mmoussallam/bird
bird/_bird.py
_bird_core
def _bird_core(X, scales, n_runs, Lambda_W, max_iter=100, stop_crit=np.mean, selection_rule=np.sum, n_jobs=1, indep=True, random_state=None, memory=Memory(None), verbose=False): """Automatically detect when noise zone has been reached and stop MP at th...
python
def _bird_core(X, scales, n_runs, Lambda_W, max_iter=100, stop_crit=np.mean, selection_rule=np.sum, n_jobs=1, indep=True, random_state=None, memory=Memory(None), verbose=False): """Automatically detect when noise zone has been reached and stop MP at th...
[ "def", "_bird_core", "(", "X", ",", "scales", ",", "n_runs", ",", "Lambda_W", ",", "max_iter", "=", "100", ",", "stop_crit", "=", "np", ".", "mean", ",", "selection_rule", "=", "np", ".", "sum", ",", "n_jobs", "=", "1", ",", "indep", "=", "True", "...
Automatically detect when noise zone has been reached and stop MP at this point Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-N array to be denoised where n_channels is number of sensors and N the dimension scales : list The list of MDC...
[ "Automatically", "detect", "when", "noise", "zone", "has", "been", "reached", "and", "stop", "MP", "at", "this", "point" ]
train
https://github.com/mmoussallam/bird/blob/1c726e6569db4f3b00804ab7ac063acaa3965987/bird/_bird.py#L235-L320
mmoussallam/bird
bird/_bird.py
bird
def bird(X, scales, n_runs, p_above, max_iter=100, random_state=None, n_jobs=1, memory=Memory(None), verbose=False): """ The BIRD algorithm as described in the paper Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-N array to be X_denoised where n_ch...
python
def bird(X, scales, n_runs, p_above, max_iter=100, random_state=None, n_jobs=1, memory=Memory(None), verbose=False): """ The BIRD algorithm as described in the paper Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-N array to be X_denoised where n_ch...
[ "def", "bird", "(", "X", ",", "scales", ",", "n_runs", ",", "p_above", ",", "max_iter", "=", "100", ",", "random_state", "=", "None", ",", "n_jobs", "=", "1", ",", "memory", "=", "Memory", "(", "None", ")", ",", "verbose", "=", "False", ")", ":", ...
The BIRD algorithm as described in the paper Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-N array to be X_denoised where n_channels is number of sensors and n_times the dimension scales : list The list of MDCT scales that will be used to b...
[ "The", "BIRD", "algorithm", "as", "described", "in", "the", "paper" ]
train
https://github.com/mmoussallam/bird/blob/1c726e6569db4f3b00804ab7ac063acaa3965987/bird/_bird.py#L323-L372
mmoussallam/bird
bird/_bird.py
s_bird
def s_bird(X, scales, n_runs, p_above, p_active=1, max_iter=100, random_state=None, n_jobs=1, memory=Memory(None), verbose=False): """ Multichannel version of BIRD (S-BIRD) seeking Structured Sparsity Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-...
python
def s_bird(X, scales, n_runs, p_above, p_active=1, max_iter=100, random_state=None, n_jobs=1, memory=Memory(None), verbose=False): """ Multichannel version of BIRD (S-BIRD) seeking Structured Sparsity Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-...
[ "def", "s_bird", "(", "X", ",", "scales", ",", "n_runs", ",", "p_above", ",", "p_active", "=", "1", ",", "max_iter", "=", "100", ",", "random_state", "=", "None", ",", "n_jobs", "=", "1", ",", "memory", "=", "Memory", "(", "None", ")", ",", "verbos...
Multichannel version of BIRD (S-BIRD) seeking Structured Sparsity Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-n_samples array to be denoised where n_channels is the number of sensors and n_samples the dimension scales : list of int The ...
[ "Multichannel", "version", "of", "BIRD", "(", "S", "-", "BIRD", ")", "seeking", "Structured", "Sparsity" ]
train
https://github.com/mmoussallam/bird/blob/1c726e6569db4f3b00804ab7ac063acaa3965987/bird/_bird.py#L386-L445
liminspace/dju-common
dju_common/validators.py
validate_email_domain
def validate_email_domain(email): """ Validates email domain by blacklist. """ try: domain = email.split('@', 1)[1].lower().strip() except IndexError: return if domain in dju_settings.DJU_EMAIL_DOMAIN_BLACK_LIST: raise ValidationError(_(u'Email with domain "%(domain)s" is disallo...
python
def validate_email_domain(email): """ Validates email domain by blacklist. """ try: domain = email.split('@', 1)[1].lower().strip() except IndexError: return if domain in dju_settings.DJU_EMAIL_DOMAIN_BLACK_LIST: raise ValidationError(_(u'Email with domain "%(domain)s" is disallo...
[ "def", "validate_email_domain", "(", "email", ")", ":", "try", ":", "domain", "=", "email", ".", "split", "(", "'@'", ",", "1", ")", "[", "1", "]", ".", "lower", "(", ")", ".", "strip", "(", ")", "except", "IndexError", ":", "return", "if", "domain...
Validates email domain by blacklist.
[ "Validates", "email", "domain", "by", "blacklist", "." ]
train
https://github.com/liminspace/dju-common/blob/c68860bb84d454a35e66275841c20f38375c2135/dju_common/validators.py#L6-L14
roll/interest-py
interest/router/router.py
Router.match
def match(self, request, *, root=None, path=None, methods=None): """Return match or None for the request/constraints pair. Parameters ---------- request: :class:`.http.Request` Request instance. root: str HTTP path root. path: str HTTP...
python
def match(self, request, *, root=None, path=None, methods=None): """Return match or None for the request/constraints pair. Parameters ---------- request: :class:`.http.Request` Request instance. root: str HTTP path root. path: str HTTP...
[ "def", "match", "(", "self", ",", "request", ",", "*", ",", "root", "=", "None", ",", "path", "=", "None", ",", "methods", "=", "None", ")", ":", "match", "=", "Match", "(", ")", "if", "path", "is", "not", "None", ":", "pattern", "=", "self", "...
Return match or None for the request/constraints pair. Parameters ---------- request: :class:`.http.Request` Request instance. root: str HTTP path root. path: str HTTP path. methods: list HTTP methods. Returns ...
[ "Return", "match", "or", "None", "for", "the", "request", "/", "constraints", "pair", "." ]
train
https://github.com/roll/interest-py/blob/e6e1def4f2999222aac2fb1d290ae94250673b89/interest/router/router.py#L62-L94
roll/interest-py
interest/router/router.py
Router.url
def url(self, name, *, base=None, query=None, **match): """Construct an url for the given parameters. Parameters ---------- name: str Nested middleware's name separated by dots. base: :class:`.Middleware` Base middleware to start searching from. q...
python
def url(self, name, *, base=None, query=None, **match): """Construct an url for the given parameters. Parameters ---------- name: str Nested middleware's name separated by dots. base: :class:`.Middleware` Base middleware to start searching from. q...
[ "def", "url", "(", "self", ",", "name", ",", "*", ",", "base", "=", "None", ",", "query", "=", "None", ",", "*", "*", "match", ")", ":", "if", "base", "is", "None", ":", "base", "=", "self", ".", "service", "for", "name", "in", "name", ".", "...
Construct an url for the given parameters. Parameters ---------- name: str Nested middleware's name separated by dots. base: :class:`.Middleware` Base middleware to start searching from. query: dict Query string data. match: dict ...
[ "Construct", "an", "url", "for", "the", "given", "parameters", "." ]
train
https://github.com/roll/interest-py/blob/e6e1def4f2999222aac2fb1d290ae94250673b89/interest/router/router.py#L96-L123
Robpol86/sphinxcontrib-imgur
sphinxcontrib/imgur/directives.py
ImgurEmbedDirective.run
def run(self): """Called by Sphinx. :returns: ImgurEmbedNode and ImgurJavaScriptNode instances with config values passed as arguments. :rtype: list """ # Get Imgur ID. imgur_id = self.arguments[0] if not RE_IMGUR_ID.match(imgur_id): raise ImgurError('...
python
def run(self): """Called by Sphinx. :returns: ImgurEmbedNode and ImgurJavaScriptNode instances with config values passed as arguments. :rtype: list """ # Get Imgur ID. imgur_id = self.arguments[0] if not RE_IMGUR_ID.match(imgur_id): raise ImgurError('...
[ "def", "run", "(", "self", ")", ":", "# Get Imgur ID.", "imgur_id", "=", "self", ".", "arguments", "[", "0", "]", "if", "not", "RE_IMGUR_ID", ".", "match", "(", "imgur_id", ")", ":", "raise", "ImgurError", "(", "'Invalid Imgur ID specified. Must be 5-10 letters ...
Called by Sphinx. :returns: ImgurEmbedNode and ImgurJavaScriptNode instances with config values passed as arguments. :rtype: list
[ "Called", "by", "Sphinx", "." ]
train
https://github.com/Robpol86/sphinxcontrib-imgur/blob/5c178481d645147d10acb096793eda41c12c57af/sphinxcontrib/imgur/directives.py#L37-L52
Robpol86/sphinxcontrib-imgur
sphinxcontrib/imgur/directives.py
ImgurImageDirective.run
def run(self): """Called by Sphinx. :returns: ImgurEmbedNode and ImgurJavaScriptNode instances with config values passed as arguments. :rtype: list """ # Get Imgur ID. imgur_id = self.arguments[0] if not RE_IMGUR_ID.match(imgur_id): raise ImgurError('...
python
def run(self): """Called by Sphinx. :returns: ImgurEmbedNode and ImgurJavaScriptNode instances with config values passed as arguments. :rtype: list """ # Get Imgur ID. imgur_id = self.arguments[0] if not RE_IMGUR_ID.match(imgur_id): raise ImgurError('...
[ "def", "run", "(", "self", ")", ":", "# Get Imgur ID.", "imgur_id", "=", "self", ".", "arguments", "[", "0", "]", "if", "not", "RE_IMGUR_ID", ".", "match", "(", "imgur_id", ")", ":", "raise", "ImgurError", "(", "'Invalid Imgur ID specified. Must be 5-10 letters ...
Called by Sphinx. :returns: ImgurEmbedNode and ImgurJavaScriptNode instances with config values passed as arguments. :rtype: list
[ "Called", "by", "Sphinx", "." ]
train
https://github.com/Robpol86/sphinxcontrib-imgur/blob/5c178481d645147d10acb096793eda41c12c57af/sphinxcontrib/imgur/directives.py#L61-L93
HydrelioxGitHub/pybbox
pybbox/bboxAuth.py
BboxAuth.check_auth
def check_auth(self): """ Check if you can make the API call with your current level of authentification :return: true if you can and false if you can't """ if self.type_of_auth == BboxConstant.AUTHENTICATION_TYPE_LOCAL: access_level_required = self.get_auth_access_ne...
python
def check_auth(self): """ Check if you can make the API call with your current level of authentification :return: true if you can and false if you can't """ if self.type_of_auth == BboxConstant.AUTHENTICATION_TYPE_LOCAL: access_level_required = self.get_auth_access_ne...
[ "def", "check_auth", "(", "self", ")", ":", "if", "self", ".", "type_of_auth", "==", "BboxConstant", ".", "AUTHENTICATION_TYPE_LOCAL", ":", "access_level_required", "=", "self", ".", "get_auth_access_needed_for_local", "(", ")", "else", ":", "access_level_required", ...
Check if you can make the API call with your current level of authentification :return: true if you can and false if you can't
[ "Check", "if", "you", "can", "make", "the", "API", "call", "with", "your", "current", "level", "of", "authentification", ":", "return", ":", "true", "if", "you", "can", "and", "false", "if", "you", "can", "t" ]
train
https://github.com/HydrelioxGitHub/pybbox/blob/bedcdccab5d18d36890ef8bf414845f2dec18b5c/pybbox/bboxAuth.py#L50-L65
timstaley/voeventdb
voeventdb/server/bin/voeventdb_ingest_packet.py
handle_args
def handle_args(): """ Default values are defined here. """ default_database_name = os.environ.get( 'VOEVENTDB_DBNAME', dbconfig.testdb_corpus_url.database) default_logfile_path = os.path.expanduser("~/voeventdb_packet_ingest.log") parser = argparse.ArgumentParser( prog...
python
def handle_args(): """ Default values are defined here. """ default_database_name = os.environ.get( 'VOEVENTDB_DBNAME', dbconfig.testdb_corpus_url.database) default_logfile_path = os.path.expanduser("~/voeventdb_packet_ingest.log") parser = argparse.ArgumentParser( prog...
[ "def", "handle_args", "(", ")", ":", "default_database_name", "=", "os", ".", "environ", ".", "get", "(", "'VOEVENTDB_DBNAME'", ",", "dbconfig", ".", "testdb_corpus_url", ".", "database", ")", "default_logfile_path", "=", "os", ".", "path", ".", "expanduser", ...
Default values are defined here.
[ "Default", "values", "are", "defined", "here", "." ]
train
https://github.com/timstaley/voeventdb/blob/e37b176d65fced4ca4f059109a95d6974bb8a091/voeventdb/server/bin/voeventdb_ingest_packet.py#L19-L49
timstaley/voeventdb
voeventdb/server/bin/voeventdb_ingest_packet.py
setup_logging
def setup_logging(logfile_path): """ Set up basic (INFO level) and debug logfiles """ date_fmt = "%y-%m-%d (%a) %H:%M:%S" std_formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s', date_fmt) # Get to the following size before splitting log ...
python
def setup_logging(logfile_path): """ Set up basic (INFO level) and debug logfiles """ date_fmt = "%y-%m-%d (%a) %H:%M:%S" std_formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s', date_fmt) # Get to the following size before splitting log ...
[ "def", "setup_logging", "(", "logfile_path", ")", ":", "date_fmt", "=", "\"%y-%m-%d (%a) %H:%M:%S\"", "std_formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s:%(levelname)s:%(message)s'", ",", "date_fmt", ")", "# Get to the following size before splitting log into ...
Set up basic (INFO level) and debug logfiles
[ "Set", "up", "basic", "(", "INFO", "level", ")", "and", "debug", "logfiles" ]
train
https://github.com/timstaley/voeventdb/blob/e37b176d65fced4ca4f059109a95d6974bb8a091/voeventdb/server/bin/voeventdb_ingest_packet.py#L52-L82
The-Politico/politico-civic-ap-loader
aploader/management/commands/reup_to_db.py
Command.process_result
def process_result(self, result, tabulated, no_bots, election_slug): """ Processes top-level (state) results for candidate races, loads data into the database and sends alerts for winning results. """ # Deconstruct result in variables ( ID, RACE_I...
python
def process_result(self, result, tabulated, no_bots, election_slug): """ Processes top-level (state) results for candidate races, loads data into the database and sends alerts for winning results. """ # Deconstruct result in variables ( ID, RACE_I...
[ "def", "process_result", "(", "self", ",", "result", ",", "tabulated", ",", "no_bots", ",", "election_slug", ")", ":", "# Deconstruct result in variables", "(", "ID", ",", "RACE_ID", ",", "IS_BALLOT_MEASURE", ",", "ELEX_ELECTION_DATE", ",", "LEVEL", ",", "STATE_PO...
Processes top-level (state) results for candidate races, loads data into the database and sends alerts for winning results.
[ "Processes", "top", "-", "level", "(", "state", ")", "results", "for", "candidate", "races", "loads", "data", "into", "the", "database", "and", "sends", "alerts", "for", "winning", "results", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/reup_to_db.py#L189-L395
scizzorz/bumpy
bumpy.py
_get_task
def _get_task(name): '''Look up a task by name.''' matches = [x for x in TASKS if x.match(name)] if matches: return matches[0]
python
def _get_task(name): '''Look up a task by name.''' matches = [x for x in TASKS if x.match(name)] if matches: return matches[0]
[ "def", "_get_task", "(", "name", ")", ":", "matches", "=", "[", "x", "for", "x", "in", "TASKS", "if", "x", ".", "match", "(", "name", ")", "]", "if", "matches", ":", "return", "matches", "[", "0", "]" ]
Look up a task by name.
[ "Look", "up", "a", "task", "by", "name", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L51-L55
scizzorz/bumpy
bumpy.py
_opts_to_dict
def _opts_to_dict(*opts): '''Convert a tuple of options returned from getopt into a dictionary.''' ret = {} for key, val in opts: if key[:2] == '--': key = key[2:] elif key[:1] == '-': key = key[1:] if val == '': val = True ret[key.replace('-','_')] = val return ret
python
def _opts_to_dict(*opts): '''Convert a tuple of options returned from getopt into a dictionary.''' ret = {} for key, val in opts: if key[:2] == '--': key = key[2:] elif key[:1] == '-': key = key[1:] if val == '': val = True ret[key.replace('-','_')] = val return ret
[ "def", "_opts_to_dict", "(", "*", "opts", ")", ":", "ret", "=", "{", "}", "for", "key", ",", "val", "in", "opts", ":", "if", "key", "[", ":", "2", "]", "==", "'--'", ":", "key", "=", "key", "[", "2", ":", "]", "elif", "key", "[", ":", "1", ...
Convert a tuple of options returned from getopt into a dictionary.
[ "Convert", "a", "tuple", "of", "options", "returned", "from", "getopt", "into", "a", "dictionary", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L57-L68
scizzorz/bumpy
bumpy.py
_highlight
def _highlight(string, color): '''Return a string highlighted for a terminal.''' if CONFIG['color']: if color < 8: return '\033[{color}m{string}\033[0m'.format(string = string, color = color+30) else: return '\033[{color}m{string}\033[0m'.format(string = string, color = color+82) else: return string
python
def _highlight(string, color): '''Return a string highlighted for a terminal.''' if CONFIG['color']: if color < 8: return '\033[{color}m{string}\033[0m'.format(string = string, color = color+30) else: return '\033[{color}m{string}\033[0m'.format(string = string, color = color+82) else: return string
[ "def", "_highlight", "(", "string", ",", "color", ")", ":", "if", "CONFIG", "[", "'color'", "]", ":", "if", "color", "<", "8", ":", "return", "'\\033[{color}m{string}\\033[0m'", ".", "format", "(", "string", "=", "string", ",", "color", "=", "color", "+"...
Return a string highlighted for a terminal.
[ "Return", "a", "string", "highlighted", "for", "a", "terminal", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L70-L78
scizzorz/bumpy
bumpy.py
_taskify
def _taskify(func): '''Convert a function into a task.''' if not isinstance(func, _Task): func = _Task(func) spec = inspect.getargspec(func.func) if spec.args: num_args = len(spec.args) num_kwargs = len(spec.defaults or []) isflag = lambda x, y: '' if x.defaults[y] is False else '=' func.args = sp...
python
def _taskify(func): '''Convert a function into a task.''' if not isinstance(func, _Task): func = _Task(func) spec = inspect.getargspec(func.func) if spec.args: num_args = len(spec.args) num_kwargs = len(spec.defaults or []) isflag = lambda x, y: '' if x.defaults[y] is False else '=' func.args = sp...
[ "def", "_taskify", "(", "func", ")", ":", "if", "not", "isinstance", "(", "func", ",", "_Task", ")", ":", "func", "=", "_Task", "(", "func", ")", "spec", "=", "inspect", ".", "getargspec", "(", "func", ".", "func", ")", "if", "spec", ".", "args", ...
Convert a function into a task.
[ "Convert", "a", "function", "into", "a", "task", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L80-L98
scizzorz/bumpy
bumpy.py
task
def task(*args, **kwargs): '''Register a function as a task, as well as applying any attributes. ''' # support @task if args and hasattr(args[0], '__call__'): return _taskify(args[0]) # as well as @task(), @task('default'), etc. else: def wrapper(func): global DEFAULT, SETUP, TEARDOWN func = _taskify(f...
python
def task(*args, **kwargs): '''Register a function as a task, as well as applying any attributes. ''' # support @task if args and hasattr(args[0], '__call__'): return _taskify(args[0]) # as well as @task(), @task('default'), etc. else: def wrapper(func): global DEFAULT, SETUP, TEARDOWN func = _taskify(f...
[ "def", "task", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# support @task", "if", "args", "and", "hasattr", "(", "args", "[", "0", "]", ",", "'__call__'", ")", ":", "return", "_taskify", "(", "args", "[", "0", "]", ")", "# as well as @task...
Register a function as a task, as well as applying any attributes.
[ "Register", "a", "function", "as", "a", "task", "as", "well", "as", "applying", "any", "attributes", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L217-L266
scizzorz/bumpy
bumpy.py
require
def require(*reqs): '''Require tasks or files at runtime.''' for req in reqs: if type(req) is str: # does not exist and unknown generator if not os.path.exists(req) and req not in GENERATES: abort(LOCALE['abort_bad_file'].format(req)) # exists but unknown generator if req not in GENERATES: retu...
python
def require(*reqs): '''Require tasks or files at runtime.''' for req in reqs: if type(req) is str: # does not exist and unknown generator if not os.path.exists(req) and req not in GENERATES: abort(LOCALE['abort_bad_file'].format(req)) # exists but unknown generator if req not in GENERATES: retu...
[ "def", "require", "(", "*", "reqs", ")", ":", "for", "req", "in", "reqs", ":", "if", "type", "(", "req", ")", "is", "str", ":", "# does not exist and unknown generator", "if", "not", "os", ".", "path", ".", "exists", "(", "req", ")", "and", "req", "n...
Require tasks or files at runtime.
[ "Require", "tasks", "or", "files", "at", "runtime", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L270-L293
scizzorz/bumpy
bumpy.py
valid
def valid(*things): '''Return True if all tasks or files are valid. Valid tasks have been completed already. Valid files exist on the disk.''' for thing in things: if type(thing) is str and not os.path.exists(thing): return False if thing.valid is None: return False return True
python
def valid(*things): '''Return True if all tasks or files are valid. Valid tasks have been completed already. Valid files exist on the disk.''' for thing in things: if type(thing) is str and not os.path.exists(thing): return False if thing.valid is None: return False return True
[ "def", "valid", "(", "*", "things", ")", ":", "for", "thing", "in", "things", ":", "if", "type", "(", "thing", ")", "is", "str", "and", "not", "os", ".", "path", ".", "exists", "(", "thing", ")", ":", "return", "False", "if", "thing", ".", "valid...
Return True if all tasks or files are valid. Valid tasks have been completed already. Valid files exist on the disk.
[ "Return", "True", "if", "all", "tasks", "or", "files", "are", "valid", ".", "Valid", "tasks", "have", "been", "completed", "already", ".", "Valid", "files", "exist", "on", "the", "disk", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L295-L303
scizzorz/bumpy
bumpy.py
shell
def shell(command, *args): '''Pass a command into the shell.''' if args: command = command.format(*args) print LOCALE['shell'].format(command) try: return subprocess.check_output(command, shell=True) except subprocess.CalledProcessError, ex: return ex
python
def shell(command, *args): '''Pass a command into the shell.''' if args: command = command.format(*args) print LOCALE['shell'].format(command) try: return subprocess.check_output(command, shell=True) except subprocess.CalledProcessError, ex: return ex
[ "def", "shell", "(", "command", ",", "*", "args", ")", ":", "if", "args", ":", "command", "=", "command", ".", "format", "(", "*", "args", ")", "print", "LOCALE", "[", "'shell'", "]", ".", "format", "(", "command", ")", "try", ":", "return", "subpr...
Pass a command into the shell.
[ "Pass", "a", "command", "into", "the", "shell", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L305-L315
scizzorz/bumpy
bumpy.py
age
def age(*paths): '''Return the minimum age of a set of files. Returns 0 if no paths are given. Returns time.time() if a path does not exist.''' if not paths: return 0 for path in paths: if not os.path.exists(path): return time.time() return min([(time.time() - os.path.getmtime(path)) for path in paths])
python
def age(*paths): '''Return the minimum age of a set of files. Returns 0 if no paths are given. Returns time.time() if a path does not exist.''' if not paths: return 0 for path in paths: if not os.path.exists(path): return time.time() return min([(time.time() - os.path.getmtime(path)) for path in paths])
[ "def", "age", "(", "*", "paths", ")", ":", "if", "not", "paths", ":", "return", "0", "for", "path", "in", "paths", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "time", ".", "time", "(", ")", "return", "mi...
Return the minimum age of a set of files. Returns 0 if no paths are given. Returns time.time() if a path does not exist.
[ "Return", "the", "minimum", "age", "of", "a", "set", "of", "files", ".", "Returns", "0", "if", "no", "paths", "are", "given", ".", "Returns", "time", ".", "time", "()", "if", "a", "path", "does", "not", "exist", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L317-L328
scizzorz/bumpy
bumpy.py
abort
def abort(message, *args): '''Raise an AbortException, halting task execution and exiting.''' if args: raise _AbortException(message.format(*args)) raise _AbortException(message)
python
def abort(message, *args): '''Raise an AbortException, halting task execution and exiting.''' if args: raise _AbortException(message.format(*args)) raise _AbortException(message)
[ "def", "abort", "(", "message", ",", "*", "args", ")", ":", "if", "args", ":", "raise", "_AbortException", "(", "message", ".", "format", "(", "*", "args", ")", ")", "raise", "_AbortException", "(", "message", ")" ]
Raise an AbortException, halting task execution and exiting.
[ "Raise", "an", "AbortException", "halting", "task", "execution", "and", "exiting", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L334-L339
scizzorz/bumpy
bumpy.py
_help
def _help(): '''Print all available tasks and descriptions.''' for task in sorted(TASKS, key=lambda x: (x.ns or '000') + x.name): tags = '' if task is DEFAULT: tags += '*' if task is SETUP: tags += '+' if task is TEARDOWN: tags += '-' print LOCALE['help_command'].format(task, tags, task.help) i...
python
def _help(): '''Print all available tasks and descriptions.''' for task in sorted(TASKS, key=lambda x: (x.ns or '000') + x.name): tags = '' if task is DEFAULT: tags += '*' if task is SETUP: tags += '+' if task is TEARDOWN: tags += '-' print LOCALE['help_command'].format(task, tags, task.help) i...
[ "def", "_help", "(", ")", ":", "for", "task", "in", "sorted", "(", "TASKS", ",", "key", "=", "lambda", "x", ":", "(", "x", ".", "ns", "or", "'000'", ")", "+", "x", ".", "name", ")", ":", "tags", "=", "''", "if", "task", "is", "DEFAULT", ":", ...
Print all available tasks and descriptions.
[ "Print", "all", "available", "tasks", "and", "descriptions", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L342-L362
scizzorz/bumpy
bumpy.py
_invoke
def _invoke(task, args): '''Invoke a task with the appropriate args; return the remaining args.''' kwargs = task.defaults.copy() if task.kwargs: temp_kwargs, args = getopt.getopt(args, '', task.kwargs) temp_kwargs = _opts_to_dict(*temp_kwargs) kwargs.update(temp_kwargs) if task.args: for arg in task.args: ...
python
def _invoke(task, args): '''Invoke a task with the appropriate args; return the remaining args.''' kwargs = task.defaults.copy() if task.kwargs: temp_kwargs, args = getopt.getopt(args, '', task.kwargs) temp_kwargs = _opts_to_dict(*temp_kwargs) kwargs.update(temp_kwargs) if task.args: for arg in task.args: ...
[ "def", "_invoke", "(", "task", ",", "args", ")", ":", "kwargs", "=", "task", ".", "defaults", ".", "copy", "(", ")", "if", "task", ".", "kwargs", ":", "temp_kwargs", ",", "args", "=", "getopt", ".", "getopt", "(", "args", ",", "''", ",", "task", ...
Invoke a task with the appropriate args; return the remaining args.
[ "Invoke", "a", "task", "with", "the", "appropriate", "args", ";", "return", "the", "remaining", "args", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L366-L386
scizzorz/bumpy
bumpy.py
main
def main(args): '''Do everything awesome.''' if SETUP: args = _invoke(SETUP, args) if not args and DEFAULT: DEFAULT() else: while args: task = _get_task(args[0]) if task is None: abort(LOCALE['error_no_task'], args[0]) args = _invoke(task, args[1:]) if TEARDOWN: TEARDOWN()
python
def main(args): '''Do everything awesome.''' if SETUP: args = _invoke(SETUP, args) if not args and DEFAULT: DEFAULT() else: while args: task = _get_task(args[0]) if task is None: abort(LOCALE['error_no_task'], args[0]) args = _invoke(task, args[1:]) if TEARDOWN: TEARDOWN()
[ "def", "main", "(", "args", ")", ":", "if", "SETUP", ":", "args", "=", "_invoke", "(", "SETUP", ",", "args", ")", "if", "not", "args", "and", "DEFAULT", ":", "DEFAULT", "(", ")", "else", ":", "while", "args", ":", "task", "=", "_get_task", "(", "...
Do everything awesome.
[ "Do", "everything", "awesome", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L389-L405
scizzorz/bumpy
bumpy.py
_Task.match
def match(self, name): '''Compare an argument string to the task name.''' if (self.ns + self.name).startswith(name): return True for alias in self.aliases: if (self.ns + alias).startswith(name): return True
python
def match(self, name): '''Compare an argument string to the task name.''' if (self.ns + self.name).startswith(name): return True for alias in self.aliases: if (self.ns + alias).startswith(name): return True
[ "def", "match", "(", "self", ",", "name", ")", ":", "if", "(", "self", ".", "ns", "+", "self", ".", "name", ")", ".", "startswith", "(", "name", ")", ":", "return", "True", "for", "alias", "in", "self", ".", "aliases", ":", "if", "(", "self", "...
Compare an argument string to the task name.
[ "Compare", "an", "argument", "string", "to", "the", "task", "name", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L189-L196
scizzorz/bumpy
bumpy.py
_Task.aliasstr
def aliasstr(self): '''Concatenate the aliases tuple into a string.''' return ', '.join(repr(self.ns + x) for x in self.aliases)
python
def aliasstr(self): '''Concatenate the aliases tuple into a string.''' return ', '.join(repr(self.ns + x) for x in self.aliases)
[ "def", "aliasstr", "(", "self", ")", ":", "return", "', '", ".", "join", "(", "repr", "(", "self", ".", "ns", "+", "x", ")", "for", "x", "in", "self", ".", "aliases", ")" ]
Concatenate the aliases tuple into a string.
[ "Concatenate", "the", "aliases", "tuple", "into", "a", "string", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L202-L204
scizzorz/bumpy
bumpy.py
_Task.kwargstr
def kwargstr(self): '''Concatenate keyword arguments into a string.''' temp = [' [--' + k + (' ' + str(v) if v is not False else '') + ']' for k, v in self.defaults.items()] return ''.join(temp)
python
def kwargstr(self): '''Concatenate keyword arguments into a string.''' temp = [' [--' + k + (' ' + str(v) if v is not False else '') + ']' for k, v in self.defaults.items()] return ''.join(temp)
[ "def", "kwargstr", "(", "self", ")", ":", "temp", "=", "[", "' [--'", "+", "k", "+", "(", "' '", "+", "str", "(", "v", ")", "if", "v", "is", "not", "False", "else", "''", ")", "+", "']'", "for", "k", ",", "v", "in", "self", ".", "defaults", ...
Concatenate keyword arguments into a string.
[ "Concatenate", "keyword", "arguments", "into", "a", "string", "." ]
train
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L206-L209
klen/adrest
adrest/utils/emitter.py
BaseEmitter.emit
def emit(self): """ Serialize response. :return response: Instance of django.http.Response """ # Skip serialize if not isinstance(self.response, SerializedHttpResponse): return self.response self.response.content = self.serialize(self.response.response) ...
python
def emit(self): """ Serialize response. :return response: Instance of django.http.Response """ # Skip serialize if not isinstance(self.response, SerializedHttpResponse): return self.response self.response.content = self.serialize(self.response.response) ...
[ "def", "emit", "(", "self", ")", ":", "# Skip serialize", "if", "not", "isinstance", "(", "self", ".", "response", ",", "SerializedHttpResponse", ")", ":", "return", "self", ".", "response", "self", ".", "response", ".", "content", "=", "self", ".", "seria...
Serialize response. :return response: Instance of django.http.Response
[ "Serialize", "response", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/utils/emitter.py#L53-L65
klen/adrest
adrest/utils/emitter.py
JSONEmitter.serialize
def serialize(self, content): """ Serialize to JSON. :return string: serializaed JSON """ worker = JSONSerializer( scheme=self.resource, options=self.resource._meta.emit_options, format=self.resource._meta.emit_format, **self.resource._me...
python
def serialize(self, content): """ Serialize to JSON. :return string: serializaed JSON """ worker = JSONSerializer( scheme=self.resource, options=self.resource._meta.emit_options, format=self.resource._meta.emit_format, **self.resource._me...
[ "def", "serialize", "(", "self", ",", "content", ")", ":", "worker", "=", "JSONSerializer", "(", "scheme", "=", "self", ".", "resource", ",", "options", "=", "self", ".", "resource", ".", "_meta", ".", "emit_options", ",", "format", "=", "self", ".", "...
Serialize to JSON. :return string: serializaed JSON
[ "Serialize", "to", "JSON", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/utils/emitter.py#L114-L126
klen/adrest
adrest/utils/emitter.py
JSONPEmitter.serialize
def serialize(self, content): """ Serialize to JSONP. :return string: serializaed JSONP """ content = super(JSONPEmitter, self).serialize(content) callback = self.request.GET.get('callback', 'callback') return u'%s(%s)' % (callback, content)
python
def serialize(self, content): """ Serialize to JSONP. :return string: serializaed JSONP """ content = super(JSONPEmitter, self).serialize(content) callback = self.request.GET.get('callback', 'callback') return u'%s(%s)' % (callback, content)
[ "def", "serialize", "(", "self", ",", "content", ")", ":", "content", "=", "super", "(", "JSONPEmitter", ",", "self", ")", ".", "serialize", "(", "content", ")", "callback", "=", "self", ".", "request", ".", "GET", ".", "get", "(", "'callback'", ",", ...
Serialize to JSONP. :return string: serializaed JSONP
[ "Serialize", "to", "JSONP", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/utils/emitter.py#L135-L143
klen/adrest
adrest/utils/emitter.py
XMLEmitter.serialize
def serialize(self, content): """ Serialize to XML. :return string: serialized XML """ worker = XMLSerializer( scheme=self.resource, format=self.resource._meta.emit_format, options=self.resource._meta.emit_options, **self.resource._meta.e...
python
def serialize(self, content): """ Serialize to XML. :return string: serialized XML """ worker = XMLSerializer( scheme=self.resource, format=self.resource._meta.emit_format, options=self.resource._meta.emit_options, **self.resource._meta.e...
[ "def", "serialize", "(", "self", ",", "content", ")", ":", "worker", "=", "XMLSerializer", "(", "scheme", "=", "self", ".", "resource", ",", "format", "=", "self", ".", "resource", ".", "_meta", ".", "emit_format", ",", "options", "=", "self", ".", "re...
Serialize to XML. :return string: serialized XML
[ "Serialize", "to", "XML", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/utils/emitter.py#L153-L170
klen/adrest
adrest/utils/emitter.py
TemplateEmitter.serialize
def serialize(self, content): """ Render Django template. :return string: rendered content """ if self.response.error: template_name = op.join('api', 'error.%s' % self.format) else: template_name = (self.resource._meta.emit_template ...
python
def serialize(self, content): """ Render Django template. :return string: rendered content """ if self.response.error: template_name = op.join('api', 'error.%s' % self.format) else: template_name = (self.resource._meta.emit_template ...
[ "def", "serialize", "(", "self", ",", "content", ")", ":", "if", "self", ".", "response", ".", "error", ":", "template_name", "=", "op", ".", "join", "(", "'api'", ",", "'error.%s'", "%", "self", ".", "format", ")", "else", ":", "template_name", "=", ...
Render Django template. :return string: rendered content
[ "Render", "Django", "template", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/utils/emitter.py#L177-L194
klen/adrest
adrest/utils/emitter.py
TemplateEmitter.get_template_path
def get_template_path(self, content=None): """ Find template. :return string: remplate path """ if isinstance(content, Paginator): return op.join('api', 'paginator.%s' % self.format) if isinstance(content, UpdatedList): return op.join('api', 'updated.%s...
python
def get_template_path(self, content=None): """ Find template. :return string: remplate path """ if isinstance(content, Paginator): return op.join('api', 'paginator.%s' % self.format) if isinstance(content, UpdatedList): return op.join('api', 'updated.%s...
[ "def", "get_template_path", "(", "self", ",", "content", "=", "None", ")", ":", "if", "isinstance", "(", "content", ",", "Paginator", ")", ":", "return", "op", ".", "join", "(", "'api'", ",", "'paginator.%s'", "%", "self", ".", "format", ")", "if", "is...
Find template. :return string: remplate path
[ "Find", "template", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/utils/emitter.py#L196-L225
klen/adrest
adrest/utils/emitter.py
JSONPTemplateEmitter.serialize
def serialize(self, content): """ Move rendered content to callback. :return string: JSONP """ content = super(JSONPTemplateEmitter, self).serialize(content) callback = self.request.GET.get('callback', 'callback') return '%s(%s)' % (callback, content)
python
def serialize(self, content): """ Move rendered content to callback. :return string: JSONP """ content = super(JSONPTemplateEmitter, self).serialize(content) callback = self.request.GET.get('callback', 'callback') return '%s(%s)' % (callback, content)
[ "def", "serialize", "(", "self", ",", "content", ")", ":", "content", "=", "super", "(", "JSONPTemplateEmitter", ",", "self", ")", ".", "serialize", "(", "content", ")", "callback", "=", "self", ".", "request", ".", "GET", ".", "get", "(", "'callback'", ...
Move rendered content to callback. :return string: JSONP
[ "Move", "rendered", "content", "to", "callback", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/utils/emitter.py#L242-L250
klen/adrest
adrest/utils/emitter.py
XMLTemplateEmitter.serialize
def serialize(self, content): """ Serialize to xml. :return string: """ return self.xmldoc_tpl % ( 'true' if self.response.status_code == HTTP_200_OK else 'false', str(self.resource.api or ''), int(mktime(datetime.now().timetuple())), sup...
python
def serialize(self, content): """ Serialize to xml. :return string: """ return self.xmldoc_tpl % ( 'true' if self.response.status_code == HTTP_200_OK else 'false', str(self.resource.api or ''), int(mktime(datetime.now().timetuple())), sup...
[ "def", "serialize", "(", "self", ",", "content", ")", ":", "return", "self", ".", "xmldoc_tpl", "%", "(", "'true'", "if", "self", ".", "response", ".", "status_code", "==", "HTTP_200_OK", "else", "'false'", ",", "str", "(", "self", ".", "resource", ".", ...
Serialize to xml. :return string:
[ "Serialize", "to", "xml", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/utils/emitter.py#L267-L278
Stranger6667/browserstacker
browserstacker/screenshots.py
match_item
def match_item(key, value, item): """ Check if some item matches criteria. """ if isinstance(value, (list, tuple)): return any(match_item(key, sub_value, item) for sub_value in value) else: return key not in item or str(item.get(key)).lower() == str(value).lower()
python
def match_item(key, value, item): """ Check if some item matches criteria. """ if isinstance(value, (list, tuple)): return any(match_item(key, sub_value, item) for sub_value in value) else: return key not in item or str(item.get(key)).lower() == str(value).lower()
[ "def", "match_item", "(", "key", ",", "value", ",", "item", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "any", "(", "match_item", "(", "key", ",", "sub_value", ",", "item", ")", "for", "sub_v...
Check if some item matches criteria.
[ "Check", "if", "some", "item", "matches", "criteria", "." ]
train
https://github.com/Stranger6667/browserstacker/blob/1c98870c3f112bb8b59b864896fd0752bd397c9e/browserstacker/screenshots.py#L43-L50
Stranger6667/browserstacker
browserstacker/screenshots.py
ScreenShotsAPI.browsers
def browsers(self, browser=None, browser_version=None, device=None, os=None, os_version=None): """ Returns list of available browsers & OS. """ response = self.execute('GET', '/screenshots/browsers.json') for key, value in list(locals().items()): if key in ('self', 'r...
python
def browsers(self, browser=None, browser_version=None, device=None, os=None, os_version=None): """ Returns list of available browsers & OS. """ response = self.execute('GET', '/screenshots/browsers.json') for key, value in list(locals().items()): if key in ('self', 'r...
[ "def", "browsers", "(", "self", ",", "browser", "=", "None", ",", "browser_version", "=", "None", ",", "device", "=", "None", ",", "os", "=", "None", ",", "os_version", "=", "None", ")", ":", "response", "=", "self", ".", "execute", "(", "'GET'", ","...
Returns list of available browsers & OS.
[ "Returns", "list", "of", "available", "browsers", "&", "OS", "." ]
train
https://github.com/Stranger6667/browserstacker/blob/1c98870c3f112bb8b59b864896fd0752bd397c9e/browserstacker/screenshots.py#L88-L97
Stranger6667/browserstacker
browserstacker/screenshots.py
ScreenShotsAPI.make
def make(self, url, browsers=None, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES, **kwargs): """ Generates screenshots for given settings and saves it to specified destination. """ response = self.generate(url, browsers, **kwargs) return self.download(respons...
python
def make(self, url, browsers=None, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES, **kwargs): """ Generates screenshots for given settings and saves it to specified destination. """ response = self.generate(url, browsers, **kwargs) return self.download(respons...
[ "def", "make", "(", "self", ",", "url", ",", "browsers", "=", "None", ",", "destination", "=", "None", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "retries", "=", "DEFAULT_RETRIES", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "gen...
Generates screenshots for given settings and saves it to specified destination.
[ "Generates", "screenshots", "for", "given", "settings", "and", "saves", "it", "to", "specified", "destination", "." ]
train
https://github.com/Stranger6667/browserstacker/blob/1c98870c3f112bb8b59b864896fd0752bd397c9e/browserstacker/screenshots.py#L99-L104
Stranger6667/browserstacker
browserstacker/screenshots.py
ScreenShotsAPI.generate
def generate(self, url, browsers=None, orientation=None, mac_res=None, win_res=None, quality=None, local=None, wait_time=None, callback_url=None): """ Generates screenshots for a URL. """ if isinstance(browsers, dict): browsers = [browsers] ...
python
def generate(self, url, browsers=None, orientation=None, mac_res=None, win_res=None, quality=None, local=None, wait_time=None, callback_url=None): """ Generates screenshots for a URL. """ if isinstance(browsers, dict): browsers = [browsers] ...
[ "def", "generate", "(", "self", ",", "url", ",", "browsers", "=", "None", ",", "orientation", "=", "None", ",", "mac_res", "=", "None", ",", "win_res", "=", "None", ",", "quality", "=", "None", ",", "local", "=", "None", ",", "wait_time", "=", "None"...
Generates screenshots for a URL.
[ "Generates", "screenshots", "for", "a", "URL", "." ]
train
https://github.com/Stranger6667/browserstacker/blob/1c98870c3f112bb8b59b864896fd0752bd397c9e/browserstacker/screenshots.py#L106-L116
Stranger6667/browserstacker
browserstacker/screenshots.py
ScreenShotsAPI.download
def download(self, job_id, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES): """ Downloads all screenshots for given job_id to `destination` folder. If `destination` is None, then screenshots will be saved in current directory. """ self._retries_num = 0 ...
python
def download(self, job_id, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES): """ Downloads all screenshots for given job_id to `destination` folder. If `destination` is None, then screenshots will be saved in current directory. """ self._retries_num = 0 ...
[ "def", "download", "(", "self", ",", "job_id", ",", "destination", "=", "None", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "retries", "=", "DEFAULT_RETRIES", ")", ":", "self", ".", "_retries_num", "=", "0", "sleep", "(", "timeout", ")", "self", ".", "s...
Downloads all screenshots for given job_id to `destination` folder. If `destination` is None, then screenshots will be saved in current directory.
[ "Downloads", "all", "screenshots", "for", "given", "job_id", "to", "destination", "folder", ".", "If", "destination", "is", "None", "then", "screenshots", "will", "be", "saved", "in", "current", "directory", "." ]
train
https://github.com/Stranger6667/browserstacker/blob/1c98870c3f112bb8b59b864896fd0752bd397c9e/browserstacker/screenshots.py#L124-L132
Stranger6667/browserstacker
browserstacker/screenshots.py
ScreenShotsAPI.save_file
def save_file(self, filename, content): """ Saves file on local filesystem. """ with open(filename, 'wb') as f: for chunk in content.iter_content(chunk_size=1024): if chunk: f.write(chunk)
python
def save_file(self, filename, content): """ Saves file on local filesystem. """ with open(filename, 'wb') as f: for chunk in content.iter_content(chunk_size=1024): if chunk: f.write(chunk)
[ "def", "save_file", "(", "self", ",", "filename", ",", "content", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "for", "chunk", "in", "content", ".", "iter_content", "(", "chunk_size", "=", "1024", ")", ":", "if", "chun...
Saves file on local filesystem.
[ "Saves", "file", "on", "local", "filesystem", "." ]
train
https://github.com/Stranger6667/browserstacker/blob/1c98870c3f112bb8b59b864896fd0752bd397c9e/browserstacker/screenshots.py#L172-L179
thekashifmalik/packer
packer/packer.py
Packer.install
def install(cls): """Create the required directories in the home directory""" [os.makedirs('{}/{}'.format(cls.home, cls.dirs[d])) for d in cls.dirs]
python
def install(cls): """Create the required directories in the home directory""" [os.makedirs('{}/{}'.format(cls.home, cls.dirs[d])) for d in cls.dirs]
[ "def", "install", "(", "cls", ")", ":", "[", "os", ".", "makedirs", "(", "'{}/{}'", ".", "format", "(", "cls", ".", "home", ",", "cls", ".", "dirs", "[", "d", "]", ")", ")", "for", "d", "in", "cls", ".", "dirs", "]" ]
Create the required directories in the home directory
[ "Create", "the", "required", "directories", "in", "the", "home", "directory" ]
train
https://github.com/thekashifmalik/packer/blob/736d052d2536ada7733f4b8459e32fb771af2e1c/packer/packer.py#L54-L56
thekashifmalik/packer
packer/packer.py
Packer.uninstall
def uninstall(cls): """Remove the package manager from the system.""" if os.path.exists(cls.home): shutil.rmtree(cls.home)
python
def uninstall(cls): """Remove the package manager from the system.""" if os.path.exists(cls.home): shutil.rmtree(cls.home)
[ "def", "uninstall", "(", "cls", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "cls", ".", "home", ")", ":", "shutil", ".", "rmtree", "(", "cls", ".", "home", ")" ]
Remove the package manager from the system.
[ "Remove", "the", "package", "manager", "from", "the", "system", "." ]
train
https://github.com/thekashifmalik/packer/blob/736d052d2536ada7733f4b8459e32fb771af2e1c/packer/packer.py#L59-L62
saxix/django-sysinfo
src/django_sysinfo/compat.py
get_installed_distributions
def get_installed_distributions(skip=stdlib_pkgs): """ Return a list of installed Distribution objects. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs """ return [d for d in pkg_resources.working_set if d.key not in skip]
python
def get_installed_distributions(skip=stdlib_pkgs): """ Return a list of installed Distribution objects. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs """ return [d for d in pkg_resources.working_set if d.key not in skip]
[ "def", "get_installed_distributions", "(", "skip", "=", "stdlib_pkgs", ")", ":", "return", "[", "d", "for", "d", "in", "pkg_resources", ".", "working_set", "if", "d", ".", "key", "not", "in", "skip", "]" ]
Return a list of installed Distribution objects. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs
[ "Return", "a", "list", "of", "installed", "Distribution", "objects", ".", "skip", "argument", "is", "an", "iterable", "of", "lower", "-", "case", "project", "names", "to", "ignore", ";", "defaults", "to", "stdlib_pkgs" ]
train
https://github.com/saxix/django-sysinfo/blob/c743e0f18a95dc9a92e7309abe871d72b97fcdb4/src/django_sysinfo/compat.py#L27-L35
j3ffhubb/pymarshal
pymarshal/bson.py
marshal_bson
def marshal_bson( obj, types=BSON_TYPES, fields=None, ): """ Recursively marshal a Python object to a BSON-compatible dict that can be passed to PyMongo, Motor, etc... Args: obj: object, It's members can be nested Python objects which will be converted to dictiona...
python
def marshal_bson( obj, types=BSON_TYPES, fields=None, ): """ Recursively marshal a Python object to a BSON-compatible dict that can be passed to PyMongo, Motor, etc... Args: obj: object, It's members can be nested Python objects which will be converted to dictiona...
[ "def", "marshal_bson", "(", "obj", ",", "types", "=", "BSON_TYPES", ",", "fields", "=", "None", ",", ")", ":", "return", "marshal_dict", "(", "obj", ",", "types", ",", "fields", "=", "fields", ",", ")" ]
Recursively marshal a Python object to a BSON-compatible dict that can be passed to PyMongo, Motor, etc... Args: obj: object, It's members can be nested Python objects which will be converted to dictionaries types: tuple-of-types, The BSON primitive types, typically ...
[ "Recursively", "marshal", "a", "Python", "object", "to", "a", "BSON", "-", "compatible", "dict", "that", "can", "be", "passed", "to", "PyMongo", "Motor", "etc", "..." ]
train
https://github.com/j3ffhubb/pymarshal/blob/42cd1cccfabfdce5af633358a641fcd5183ee192/pymarshal/bson.py#L143-L164
j3ffhubb/pymarshal
pymarshal/bson.py
unmarshal_bson
def unmarshal_bson( obj, cls, allow_extra_keys=True, ctor=None, ): """ Unmarshal @obj into @cls Args: obj: dict, A BSON object cls: type, The class to unmarshal into allow_extra_keys: bool, False to raise an exception when extra ...
python
def unmarshal_bson( obj, cls, allow_extra_keys=True, ctor=None, ): """ Unmarshal @obj into @cls Args: obj: dict, A BSON object cls: type, The class to unmarshal into allow_extra_keys: bool, False to raise an exception when extra ...
[ "def", "unmarshal_bson", "(", "obj", ",", "cls", ",", "allow_extra_keys", "=", "True", ",", "ctor", "=", "None", ",", ")", ":", "return", "unmarshal_dict", "(", "obj", ",", "cls", ",", "allow_extra_keys", ",", "ctor", "=", "ctor", ",", ")" ]
Unmarshal @obj into @cls Args: obj: dict, A BSON object cls: type, The class to unmarshal into allow_extra_keys: bool, False to raise an exception when extra keys are present, True to ignore ctor: None-or-static-method:...
[ "Unmarshal", "@obj", "into", "@cls" ]
train
https://github.com/j3ffhubb/pymarshal/blob/42cd1cccfabfdce5af633358a641fcd5183ee192/pymarshal/bson.py#L167-L194
j3ffhubb/pymarshal
pymarshal/bson.py
MongoDocument.json
def json( self, include_id=False, date_fmt=None, object_id_fmt=str, ): """ Helper method to convert to MongoDB documents to JSON This includes helpers to convert non-JSON compatible types to valid JSON types. HOWEVER, it cannot recurse into nested ...
python
def json( self, include_id=False, date_fmt=None, object_id_fmt=str, ): """ Helper method to convert to MongoDB documents to JSON This includes helpers to convert non-JSON compatible types to valid JSON types. HOWEVER, it cannot recurse into nested ...
[ "def", "json", "(", "self", ",", "include_id", "=", "False", ",", "date_fmt", "=", "None", ",", "object_id_fmt", "=", "str", ",", ")", ":", "has_slots", ",", "d", "=", "_get_dict", "(", "self", ")", "_id", "=", "self", ".", "_id", "if", "not", "inc...
Helper method to convert to MongoDB documents to JSON This includes helpers to convert non-JSON compatible types to valid JSON types. HOWEVER, it cannot recurse into nested classes. Args: include_id: bool, True to cast _id to a str, ...
[ "Helper", "method", "to", "convert", "to", "MongoDB", "documents", "to", "JSON" ]
train
https://github.com/j3ffhubb/pymarshal/blob/42cd1cccfabfdce5af633358a641fcd5183ee192/pymarshal/bson.py#L66-L140
klen/adrest
adrest/mixin/parser.py
ParserMixin.parse
def parse(self, request): """ Parse request content. :return dict: parsed data. """ if request.method in ('POST', 'PUT', 'PATCH'): content_type = self.determine_content(request) if content_type: split = content_type.split(';', 1) ...
python
def parse(self, request): """ Parse request content. :return dict: parsed data. """ if request.method in ('POST', 'PUT', 'PATCH'): content_type = self.determine_content(request) if content_type: split = content_type.split(';', 1) ...
[ "def", "parse", "(", "self", ",", "request", ")", ":", "if", "request", ".", "method", "in", "(", "'POST'", ",", "'PUT'", ",", "'PATCH'", ")", ":", "content_type", "=", "self", ".", "determine_content", "(", "request", ")", "if", "content_type", ":", "...
Parse request content. :return dict: parsed data.
[ "Parse", "request", "content", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/mixin/parser.py#L42-L60
klen/adrest
adrest/mixin/parser.py
ParserMixin.determine_content
def determine_content(request): """ Determine request content. :return str: request content type """ if not request.META.get('CONTENT_LENGTH', None) \ and not request.META.get('TRANSFER_ENCODING', None): return None return request.META.get('CONTENT_TYPE...
python
def determine_content(request): """ Determine request content. :return str: request content type """ if not request.META.get('CONTENT_LENGTH', None) \ and not request.META.get('TRANSFER_ENCODING', None): return None return request.META.get('CONTENT_TYPE...
[ "def", "determine_content", "(", "request", ")", ":", "if", "not", "request", ".", "META", ".", "get", "(", "'CONTENT_LENGTH'", ",", "None", ")", "and", "not", "request", ".", "META", ".", "get", "(", "'TRANSFER_ENCODING'", ",", "None", ")", ":", "return...
Determine request content. :return str: request content type
[ "Determine", "request", "content", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/mixin/parser.py#L63-L74
fusionbox/django-backupdb
backupdb/utils/log.py
bar
def bar(msg='', width=40, position=None): r""" Returns a string with text centered in a bar caption. Examples: >>> bar('test', width=10) '== test ==' >>> bar(width=10) '==========' >>> bar('Richard Dean Anderson is...', position='top', width=50) '//========= Richard Dean Anderson is...
python
def bar(msg='', width=40, position=None): r""" Returns a string with text centered in a bar caption. Examples: >>> bar('test', width=10) '== test ==' >>> bar(width=10) '==========' >>> bar('Richard Dean Anderson is...', position='top', width=50) '//========= Richard Dean Anderson is...
[ "def", "bar", "(", "msg", "=", "''", ",", "width", "=", "40", ",", "position", "=", "None", ")", ":", "if", "position", "==", "'top'", ":", "start_bar", "=", "'//'", "end_bar", "=", "r'\\\\'", "elif", "position", "==", "'bottom'", ":", "start_bar", "...
r""" Returns a string with text centered in a bar caption. Examples: >>> bar('test', width=10) '== test ==' >>> bar(width=10) '==========' >>> bar('Richard Dean Anderson is...', position='top', width=50) '//========= Richard Dean Anderson is... ========\\\\' >>> bar('...MacGyver', p...
[ "r", "Returns", "a", "string", "with", "text", "centered", "in", "a", "bar", "caption", "." ]
train
https://github.com/fusionbox/django-backupdb/blob/db4aa73049303245ef0182cda5c76b1dd194cd00/backupdb/utils/log.py#L7-L35
fusionbox/django-backupdb
backupdb/utils/log.py
section
def section(msg): """ Context manager that prints a top bar to stderr upon entering and a bottom bar upon exiting. The caption of the top bar is specified by `msg`. The caption of the bottom bar is '...done!' if the context manager exits successfully. If a SectionError or SectionWarning is raised...
python
def section(msg): """ Context manager that prints a top bar to stderr upon entering and a bottom bar upon exiting. The caption of the top bar is specified by `msg`. The caption of the bottom bar is '...done!' if the context manager exits successfully. If a SectionError or SectionWarning is raised...
[ "def", "section", "(", "msg", ")", ":", "logger", ".", "info", "(", "bar", "(", "msg", ",", "position", "=", "'top'", ")", ")", "try", ":", "yield", "except", "SectionError", "as", "e", ":", "logger", ".", "error", "(", "e", ")", "logger", ".", "...
Context manager that prints a top bar to stderr upon entering and a bottom bar upon exiting. The caption of the top bar is specified by `msg`. The caption of the bottom bar is '...done!' if the context manager exits successfully. If a SectionError or SectionWarning is raised inside of the context man...
[ "Context", "manager", "that", "prints", "a", "top", "bar", "to", "stderr", "upon", "entering", "and", "a", "bottom", "bar", "upon", "exiting", ".", "The", "caption", "of", "the", "top", "bar", "is", "specified", "by", "msg", ".", "The", "caption", "of", ...
train
https://github.com/fusionbox/django-backupdb/blob/db4aa73049303245ef0182cda5c76b1dd194cd00/backupdb/utils/log.py#L47-L67
Robpol86/sphinxcontrib-imgur
sphinxcontrib/imgur/roles.py
imgur_role
def imgur_role(name, rawtext, text, *_): """Imgur ":imgur-title:`a/abc1234`" or ":imgur-description:`abc1234`" rst inline roles. "Schedules" an API query. :raises ImgurError: if text has invalid Imgur ID. :param str name: Role name (e.g. 'imgur-title'). :param str rawtext: Entire role and value m...
python
def imgur_role(name, rawtext, text, *_): """Imgur ":imgur-title:`a/abc1234`" or ":imgur-description:`abc1234`" rst inline roles. "Schedules" an API query. :raises ImgurError: if text has invalid Imgur ID. :param str name: Role name (e.g. 'imgur-title'). :param str rawtext: Entire role and value m...
[ "def", "imgur_role", "(", "name", ",", "rawtext", ",", "text", ",", "*", "_", ")", ":", "if", "not", "RE_IMGUR_ID", ".", "match", "(", "text", ")", ":", "message", "=", "'Invalid Imgur ID specified. Must be 5-10 letters and numbers. Got \"{}\" from \"{}\".'", "raise...
Imgur ":imgur-title:`a/abc1234`" or ":imgur-description:`abc1234`" rst inline roles. "Schedules" an API query. :raises ImgurError: if text has invalid Imgur ID. :param str name: Role name (e.g. 'imgur-title'). :param str rawtext: Entire role and value markup (e.g. ':imgur-title:`hWyW0`'). :param ...
[ "Imgur", ":", "imgur", "-", "title", ":", "a", "/", "abc1234", "or", ":", "imgur", "-", "description", ":", "abc1234", "rst", "inline", "roles", "." ]
train
https://github.com/Robpol86/sphinxcontrib-imgur/blob/5c178481d645147d10acb096793eda41c12c57af/sphinxcontrib/imgur/roles.py#L7-L25
klen/muffin-session
example.py
update
def update(request): """Update a current user's session.""" session = yield from app.ps.session.load(request) session['random'] = random.random() return session
python
def update(request): """Update a current user's session.""" session = yield from app.ps.session.load(request) session['random'] = random.random() return session
[ "def", "update", "(", "request", ")", ":", "session", "=", "yield", "from", "app", ".", "ps", ".", "session", ".", "load", "(", "request", ")", "session", "[", "'random'", "]", "=", "random", ".", "random", "(", ")", "return", "session" ]
Update a current user's session.
[ "Update", "a", "current", "user", "s", "session", "." ]
train
https://github.com/klen/muffin-session/blob/f1d14d12b7d09d8cc40be14b0dfa0b1e2f4ae8e9/example.py#L23-L27
jeffh/pyconstraints
pyconstraints/solvers.py
Solution.keys
def keys(self): "Returns all the keys this object can return proper values for." return tuple(set(self.new.keys()).union(self.old.keys()))
python
def keys(self): "Returns all the keys this object can return proper values for." return tuple(set(self.new.keys()).union(self.old.keys()))
[ "def", "keys", "(", "self", ")", ":", "return", "tuple", "(", "set", "(", "self", ".", "new", ".", "keys", "(", ")", ")", ".", "union", "(", "self", ".", "old", ".", "keys", "(", ")", ")", ")" ]
Returns all the keys this object can return proper values for.
[ "Returns", "all", "the", "keys", "this", "object", "can", "return", "proper", "values", "for", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L66-L68
jeffh/pyconstraints
pyconstraints/solvers.py
Solution.values
def values(self): "Returns all values this object can return via keys." return tuple(set(self.new.values()).union(self.old.values()))
python
def values(self): "Returns all values this object can return via keys." return tuple(set(self.new.values()).union(self.old.values()))
[ "def", "values", "(", "self", ")", ":", "return", "tuple", "(", "set", "(", "self", ".", "new", ".", "values", "(", ")", ")", ".", "union", "(", "self", ".", "old", ".", "values", "(", ")", ")", ")" ]
Returns all values this object can return via keys.
[ "Returns", "all", "values", "this", "object", "can", "return", "via", "keys", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L70-L72
jeffh/pyconstraints
pyconstraints/solvers.py
BruteForceSolver._compute_search_spaces
def _compute_search_spaces(self, used_variables): """Returns the size of each domain for a simple constraint size computation. This is used to pick the most constraining constraint first. """ return tuple(len(domain) for name, domain in self._vars.iteritems())
python
def _compute_search_spaces(self, used_variables): """Returns the size of each domain for a simple constraint size computation. This is used to pick the most constraining constraint first. """ return tuple(len(domain) for name, domain in self._vars.iteritems())
[ "def", "_compute_search_spaces", "(", "self", ",", "used_variables", ")", ":", "return", "tuple", "(", "len", "(", "domain", ")", "for", "name", ",", "domain", "in", "self", ".", "_vars", ".", "iteritems", "(", ")", ")" ]
Returns the size of each domain for a simple constraint size computation. This is used to pick the most constraining constraint first.
[ "Returns", "the", "size", "of", "each", "domain", "for", "a", "simple", "constraint", "size", "computation", ".", "This", "is", "used", "to", "pick", "the", "most", "constraining", "constraint", "first", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L155-L159
jeffh/pyconstraints
pyconstraints/solvers.py
BruteForceSolver.satisfies_constraints
def satisfies_constraints(self, possible_solution): """Return True if the given solution is satisfied by all the constraints.""" for c in self._constraints: values = c.extract_values(possible_solution) if values is None or not c(*values): return False retu...
python
def satisfies_constraints(self, possible_solution): """Return True if the given solution is satisfied by all the constraints.""" for c in self._constraints: values = c.extract_values(possible_solution) if values is None or not c(*values): return False retu...
[ "def", "satisfies_constraints", "(", "self", ",", "possible_solution", ")", ":", "for", "c", "in", "self", ".", "_constraints", ":", "values", "=", "c", ".", "extract_values", "(", "possible_solution", ")", "if", "values", "is", "None", "or", "not", "c", "...
Return True if the given solution is satisfied by all the constraints.
[ "Return", "True", "if", "the", "given", "solution", "is", "satisfied", "by", "all", "the", "constraints", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L161-L167
jeffh/pyconstraints
pyconstraints/solvers.py
BruteForceSolver.set_conditions
def set_conditions(self, variables, constraints): """Problem provided data. variables = {variable-name: list-of-domain-values} constraints = [(constraint_function, variable-names, default-variable-values)] """ self._vars, self._constraints = variables, [] # build constra...
python
def set_conditions(self, variables, constraints): """Problem provided data. variables = {variable-name: list-of-domain-values} constraints = [(constraint_function, variable-names, default-variable-values)] """ self._vars, self._constraints = variables, [] # build constra...
[ "def", "set_conditions", "(", "self", ",", "variables", ",", "constraints", ")", ":", "self", ".", "_vars", ",", "self", ".", "_constraints", "=", "variables", ",", "[", "]", "# build constraint objects", "for", "func", ",", "variables", ",", "values", "in",...
Problem provided data. variables = {variable-name: list-of-domain-values} constraints = [(constraint_function, variable-names, default-variable-values)]
[ "Problem", "provided", "data", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L175-L187
jeffh/pyconstraints
pyconstraints/solvers.py
BruteForceSolver.combinations
def combinations(self): """Returns a generator of all possible combinations. """ keys = self._vars.keys() for result in product(*self._vars.values()): possible_solution = {} for i, v in enumerate(result): possible_solution[keys[i]] = v ...
python
def combinations(self): """Returns a generator of all possible combinations. """ keys = self._vars.keys() for result in product(*self._vars.values()): possible_solution = {} for i, v in enumerate(result): possible_solution[keys[i]] = v ...
[ "def", "combinations", "(", "self", ")", ":", "keys", "=", "self", ".", "_vars", ".", "keys", "(", ")", "for", "result", "in", "product", "(", "*", "self", ".", "_vars", ".", "values", "(", ")", ")", ":", "possible_solution", "=", "{", "}", "for", ...
Returns a generator of all possible combinations.
[ "Returns", "a", "generator", "of", "all", "possible", "combinations", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L190-L198
jeffh/pyconstraints
pyconstraints/solvers.py
BacktrackingSolver.set_conditions
def set_conditions(self, variables, constraints): """Problem provided data. variables = {variable-name: list-of-domain-values} constraints = [(constraint_function, variable-names, variable-default-values)] """ self._vars, self._constraints = variables, [] self._constrain...
python
def set_conditions(self, variables, constraints): """Problem provided data. variables = {variable-name: list-of-domain-values} constraints = [(constraint_function, variable-names, variable-default-values)] """ self._vars, self._constraints = variables, [] self._constrain...
[ "def", "set_conditions", "(", "self", ",", "variables", ",", "constraints", ")", ":", "self", ".", "_vars", ",", "self", ".", "_constraints", "=", "variables", ",", "[", "]", "self", ".", "_constraints_for_var", "=", "{", "}", "vars_constraint_count", "=", ...
Problem provided data. variables = {variable-name: list-of-domain-values} constraints = [(constraint_function, variable-names, variable-default-values)]
[ "Problem", "provided", "data", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L224-L243
jeffh/pyconstraints
pyconstraints/solvers.py
BacktrackingSolver.satisfies_constraints
def satisfies_constraints(self, possible_solution): """Return True if the given solution is satisfied by all the constraints.""" for c in self._constraints: values = c.extract_values(possible_solution) if any(type(v) is NilObject for v in values) or not c(*values): ...
python
def satisfies_constraints(self, possible_solution): """Return True if the given solution is satisfied by all the constraints.""" for c in self._constraints: values = c.extract_values(possible_solution) if any(type(v) is NilObject for v in values) or not c(*values): ...
[ "def", "satisfies_constraints", "(", "self", ",", "possible_solution", ")", ":", "for", "c", "in", "self", ".", "_constraints", ":", "values", "=", "c", ".", "extract_values", "(", "possible_solution", ")", "if", "any", "(", "type", "(", "v", ")", "is", ...
Return True if the given solution is satisfied by all the constraints.
[ "Return", "True", "if", "the", "given", "solution", "is", "satisfied", "by", "all", "the", "constraints", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L245-L251
jeffh/pyconstraints
pyconstraints/solvers.py
BacktrackingSolver.derived_solutions
def derived_solutions(self, solution=None): """Returns all possible solutions based on the provide solution. This assumes that the given solution is incomplete. """ solution = solution or Solution() used_variables = solution.keys() unused_variables = (v for v in self._va...
python
def derived_solutions(self, solution=None): """Returns all possible solutions based on the provide solution. This assumes that the given solution is incomplete. """ solution = solution or Solution() used_variables = solution.keys() unused_variables = (v for v in self._va...
[ "def", "derived_solutions", "(", "self", ",", "solution", "=", "None", ")", ":", "solution", "=", "solution", "or", "Solution", "(", ")", "used_variables", "=", "solution", ".", "keys", "(", ")", "unused_variables", "=", "(", "v", "for", "v", "in", "self...
Returns all possible solutions based on the provide solution. This assumes that the given solution is incomplete.
[ "Returns", "all", "possible", "solutions", "based", "on", "the", "provide", "solution", ".", "This", "assumes", "that", "the", "given", "solution", "is", "incomplete", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L253-L263
jeffh/pyconstraints
pyconstraints/solvers.py
BacktrackingSolver.is_feasible
def is_feasible(self, solution): """Returns True if the given solution's derivatives may have potential valid, complete solutions. """ newvars = solution.new.keys() for newvar in newvars: for c in self._constraints_for_var.get(newvar, []): values = c.e...
python
def is_feasible(self, solution): """Returns True if the given solution's derivatives may have potential valid, complete solutions. """ newvars = solution.new.keys() for newvar in newvars: for c in self._constraints_for_var.get(newvar, []): values = c.e...
[ "def", "is_feasible", "(", "self", ",", "solution", ")", ":", "newvars", "=", "solution", ".", "new", ".", "keys", "(", ")", "for", "newvar", "in", "newvars", ":", "for", "c", "in", "self", ".", "_constraints_for_var", ".", "get", "(", "newvar", ",", ...
Returns True if the given solution's derivatives may have potential valid, complete solutions.
[ "Returns", "True", "if", "the", "given", "solution", "s", "derivatives", "may", "have", "potential", "valid", "complete", "solutions", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L265-L275
jeffh/pyconstraints
pyconstraints/solvers.py
BacktrackingSolver._next
def _next(self, possible_solution): """Where the magic happens. Produces a generator that returns all solutions given a base solution to start searching. """ # bail out if we have seen it already. See __iter__ to where seen is initially set. # A complete solution has all its vari...
python
def _next(self, possible_solution): """Where the magic happens. Produces a generator that returns all solutions given a base solution to start searching. """ # bail out if we have seen it already. See __iter__ to where seen is initially set. # A complete solution has all its vari...
[ "def", "_next", "(", "self", ",", "possible_solution", ")", ":", "# bail out if we have seen it already. See __iter__ to where seen is initially set.", "# A complete solution has all its variables set to a particular value.", "is_complete", "=", "(", "len", "(", "possible_solution", ...
Where the magic happens. Produces a generator that returns all solutions given a base solution to start searching.
[ "Where", "the", "magic", "happens", ".", "Produces", "a", "generator", "that", "returns", "all", "solutions", "given", "a", "base", "solution", "to", "start", "searching", "." ]
train
https://github.com/jeffh/pyconstraints/blob/923abce2f9ba484d1964165616a253bbccd1a630/pyconstraints/solvers.py#L277-L293
nicholasbishop/shaderdef
shaderdef/ast_util.py
dedent
def dedent(lines): """De-indent based on the first line's indentation.""" if len(lines) != 0: first_lstrip = lines[0].lstrip() strip_len = len(lines[0]) - len(first_lstrip) for line in lines: if len(line[:strip_len].strip()) != 0: raise ValueError('less indent...
python
def dedent(lines): """De-indent based on the first line's indentation.""" if len(lines) != 0: first_lstrip = lines[0].lstrip() strip_len = len(lines[0]) - len(first_lstrip) for line in lines: if len(line[:strip_len].strip()) != 0: raise ValueError('less indent...
[ "def", "dedent", "(", "lines", ")", ":", "if", "len", "(", "lines", ")", "!=", "0", ":", "first_lstrip", "=", "lines", "[", "0", "]", ".", "lstrip", "(", ")", "strip_len", "=", "len", "(", "lines", "[", "0", "]", ")", "-", "len", "(", "first_ls...
De-indent based on the first line's indentation.
[ "De", "-", "indent", "based", "on", "the", "first", "line", "s", "indentation", "." ]
train
https://github.com/nicholasbishop/shaderdef/blob/b68a9faf4c7cfa61e32a2e49eb2cae2f2e2b1f78/shaderdef/ast_util.py#L14-L24
ska-sa/kittens
Kittens/pixmaps.py
load_icons
def load_icons(appname, package=""): """ load all icons found in path, subdirs '<package>/icons/<appname>'. Package is optional. """ # loop over system path global __icons_loaded if __icons_loaded: return icon_paths = ['/usr/local/share/meqtrees'] + sys.path for path in icon_...
python
def load_icons(appname, package=""): """ load all icons found in path, subdirs '<package>/icons/<appname>'. Package is optional. """ # loop over system path global __icons_loaded if __icons_loaded: return icon_paths = ['/usr/local/share/meqtrees'] + sys.path for path in icon_...
[ "def", "load_icons", "(", "appname", ",", "package", "=", "\"\"", ")", ":", "# loop over system path", "global", "__icons_loaded", "if", "__icons_loaded", ":", "return", "icon_paths", "=", "[", "'/usr/local/share/meqtrees'", "]", "+", "sys", ".", "path", "for", ...
load all icons found in path, subdirs '<package>/icons/<appname>'. Package is optional.
[ "load", "all", "icons", "found", "in", "path", "subdirs", "<package", ">", "/", "icons", "/", "<appname", ">", ".", "Package", "is", "optional", "." ]
train
https://github.com/ska-sa/kittens/blob/92058e065ddffa5d00a44749145a6f917e0f31dc/Kittens/pixmaps.py#L3009-L3050
ska-sa/kittens
Kittens/pixmaps.py
QPixmapWrapper.assign
def assign(self, pm): """Reassign pixmap or xpm string array to wrapper""" if isinstance(pm, QPixmap): self._pm = pm else: # assume xpm string list to be decoded on-demand self._xpmstr = pm self._pm = None self._icon = None
python
def assign(self, pm): """Reassign pixmap or xpm string array to wrapper""" if isinstance(pm, QPixmap): self._pm = pm else: # assume xpm string list to be decoded on-demand self._xpmstr = pm self._pm = None self._icon = None
[ "def", "assign", "(", "self", ",", "pm", ")", ":", "if", "isinstance", "(", "pm", ",", "QPixmap", ")", ":", "self", ".", "_pm", "=", "pm", "else", ":", "# assume xpm string list to be decoded on-demand", "self", ".", "_xpmstr", "=", "pm", "self", ".", "_...
Reassign pixmap or xpm string array to wrapper
[ "Reassign", "pixmap", "or", "xpm", "string", "array", "to", "wrapper" ]
train
https://github.com/ska-sa/kittens/blob/92058e065ddffa5d00a44749145a6f917e0f31dc/Kittens/pixmaps.py#L85-L92
ska-sa/kittens
Kittens/pixmaps.py
QPixmapWrapper.pm
def pm(self): """Get QPixmap from wrapper""" if self._pm is None: self._pm = QPixmap(self._xpmstr) return self._pm
python
def pm(self): """Get QPixmap from wrapper""" if self._pm is None: self._pm = QPixmap(self._xpmstr) return self._pm
[ "def", "pm", "(", "self", ")", ":", "if", "self", ".", "_pm", "is", "None", ":", "self", ".", "_pm", "=", "QPixmap", "(", "self", ".", "_xpmstr", ")", "return", "self", ".", "_pm" ]
Get QPixmap from wrapper
[ "Get", "QPixmap", "from", "wrapper" ]
train
https://github.com/ska-sa/kittens/blob/92058e065ddffa5d00a44749145a6f917e0f31dc/Kittens/pixmaps.py#L94-L98
ska-sa/kittens
Kittens/pixmaps.py
QPixmapWrapper.icon
def icon(self): """Get QIcon from wrapper""" if self._icon is None: self._icon = QIcon(self.pm()) return self._icon
python
def icon(self): """Get QIcon from wrapper""" if self._icon is None: self._icon = QIcon(self.pm()) return self._icon
[ "def", "icon", "(", "self", ")", ":", "if", "self", ".", "_icon", "is", "None", ":", "self", ".", "_icon", "=", "QIcon", "(", "self", ".", "pm", "(", ")", ")", "return", "self", ".", "_icon" ]
Get QIcon from wrapper
[ "Get", "QIcon", "from", "wrapper" ]
train
https://github.com/ska-sa/kittens/blob/92058e065ddffa5d00a44749145a6f917e0f31dc/Kittens/pixmaps.py#L100-L104
ska-sa/kittens
Kittens/pixmaps.py
PixmapCache._load
def _load(self): """load all icons found in path, subdirs 'icons/appname'""" # loop over system path if self._loaded: return icon_paths = ['/usr/local/share/meqtrees'] + sys.path for path in icon_paths: path = path or '.' # for each entry, try ...
python
def _load(self): """load all icons found in path, subdirs 'icons/appname'""" # loop over system path if self._loaded: return icon_paths = ['/usr/local/share/meqtrees'] + sys.path for path in icon_paths: path = path or '.' # for each entry, try ...
[ "def", "_load", "(", "self", ")", ":", "# loop over system path", "if", "self", ".", "_loaded", ":", "return", "icon_paths", "=", "[", "'/usr/local/share/meqtrees'", "]", "+", "sys", ".", "path", "for", "path", "in", "icon_paths", ":", "path", "=", "path", ...
load all icons found in path, subdirs 'icons/appname
[ "load", "all", "icons", "found", "in", "path", "subdirs", "icons", "/", "appname" ]
train
https://github.com/ska-sa/kittens/blob/92058e065ddffa5d00a44749145a6f917e0f31dc/Kittens/pixmaps.py#L3089-L3124
pyrapt/rapt
rapt/treebrd/treebrd.py
TreeBRD.to_node
def to_node(self, exp, schema): """ Return a Node that is the root of the parse tree for the the specified expression. :param exp: A list that represents a relational algebra expression. Assumes that this list was generated by pyparsing. :param schema: A dictionary of re...
python
def to_node(self, exp, schema): """ Return a Node that is the root of the parse tree for the the specified expression. :param exp: A list that represents a relational algebra expression. Assumes that this list was generated by pyparsing. :param schema: A dictionary of re...
[ "def", "to_node", "(", "self", ",", "exp", ",", "schema", ")", ":", "# A relation node.", "if", "len", "(", "exp", ")", "==", "1", "and", "isinstance", "(", "exp", "[", "0", "]", ",", "str", ")", ":", "node", "=", "RelationNode", "(", "name", "=", ...
Return a Node that is the root of the parse tree for the the specified expression. :param exp: A list that represents a relational algebra expression. Assumes that this list was generated by pyparsing. :param schema: A dictionary of relation names to attribute names used for ver...
[ "Return", "a", "Node", "that", "is", "the", "root", "of", "the", "parse", "tree", "for", "the", "the", "specified", "expression", "." ]
train
https://github.com/pyrapt/rapt/blob/0193a07aafff83a887fdc9e5e0f25eafa5b1b205/rapt/treebrd/treebrd.py#L22-L76
pyrapt/rapt
rapt/treebrd/treebrd.py
TreeBRD.create_unary_node
def create_unary_node(self, operator, child, param=None, schema=None): """ Return a Unary Node whose type depends on the specified operator. :param schema: :param child: :param operator: A relational algebra operator (see constants.py) :param param: A list of parameters ...
python
def create_unary_node(self, operator, child, param=None, schema=None): """ Return a Unary Node whose type depends on the specified operator. :param schema: :param child: :param operator: A relational algebra operator (see constants.py) :param param: A list of parameters ...
[ "def", "create_unary_node", "(", "self", ",", "operator", ",", "child", ",", "param", "=", "None", ",", "schema", "=", "None", ")", ":", "if", "operator", "==", "self", ".", "grammar", ".", "syntax", ".", "select_op", ":", "conditions", "=", "' '", "."...
Return a Unary Node whose type depends on the specified operator. :param schema: :param child: :param operator: A relational algebra operator (see constants.py) :param param: A list of parameters for the operator. :return: A Unary Node.
[ "Return", "a", "Unary", "Node", "whose", "type", "depends", "on", "the", "specified", "operator", "." ]
train
https://github.com/pyrapt/rapt/blob/0193a07aafff83a887fdc9e5e0f25eafa5b1b205/rapt/treebrd/treebrd.py#L78-L113
pyrapt/rapt
rapt/treebrd/treebrd.py
TreeBRD.create_binary_node
def create_binary_node(self, operator, left, right, param=None): """ Return a Node whose type depends on the specified operator. :param operator: A relational algebra operator (see constants.py) :return: A Node. """ # Join operators if operator == self.grammar.s...
python
def create_binary_node(self, operator, left, right, param=None): """ Return a Node whose type depends on the specified operator. :param operator: A relational algebra operator (see constants.py) :return: A Node. """ # Join operators if operator == self.grammar.s...
[ "def", "create_binary_node", "(", "self", ",", "operator", ",", "left", ",", "right", ",", "param", "=", "None", ")", ":", "# Join operators", "if", "operator", "==", "self", ".", "grammar", ".", "syntax", ".", "join_op", ":", "node", "=", "CrossJoinNode",...
Return a Node whose type depends on the specified operator. :param operator: A relational algebra operator (see constants.py) :return: A Node.
[ "Return", "a", "Node", "whose", "type", "depends", "on", "the", "specified", "operator", "." ]
train
https://github.com/pyrapt/rapt/blob/0193a07aafff83a887fdc9e5e0f25eafa5b1b205/rapt/treebrd/treebrd.py#L115-L147
childsish/sofia
templates/genomics/attributes/chromosome_id.py
ChromosomeIdResolver.get_to
def get_to(self, ins): """ Resolve the output attribute value for 'chromosome_id'. Valid values are immutable, ie. the attribute key is not an actual entity. Mutable values will be changed to match the immutable value if unique. Otherwise an error is thrown. :param ins: iterable...
python
def get_to(self, ins): """ Resolve the output attribute value for 'chromosome_id'. Valid values are immutable, ie. the attribute key is not an actual entity. Mutable values will be changed to match the immutable value if unique. Otherwise an error is thrown. :param ins: iterable...
[ "def", "get_to", "(", "self", ",", "ins", ")", ":", "input_entities", "=", "set", "(", ")", "attribute_values", "=", "set", "(", ")", "for", "in_", "in", "ins", ":", "if", "self", ".", "ATTRIBUTE", "not", "in", "self", ".", "entity_graph", ".", "has_...
Resolve the output attribute value for 'chromosome_id'. Valid values are immutable, ie. the attribute key is not an actual entity. Mutable values will be changed to match the immutable value if unique. Otherwise an error is thrown. :param ins: iterable of input workflows :return: output...
[ "Resolve", "the", "output", "attribute", "value", "for", "chromosome_id", ".", "Valid", "values", "are", "immutable", "ie", ".", "the", "attribute", "key", "is", "not", "an", "actual", "entity", ".", "Mutable", "values", "will", "be", "changed", "to", "match...
train
https://github.com/childsish/sofia/blob/39b992f143e2610a62ad751568caa5ca9aaf0224/templates/genomics/attributes/chromosome_id.py#L67-L86
uw-it-aca/uw-restclients
restclients/bridge/__init__.py
patch_resource
def patch_resource(url, body): """ Patch resource with the given json body :returns: http response data """ response = Bridge_DAO().patchURL(url, PHEADER, body) log_data = "PATCH %s %s ==status==> %s" % (url, body, response.status) if response.status != 200: _raise_exception(log_dat...
python
def patch_resource(url, body): """ Patch resource with the given json body :returns: http response data """ response = Bridge_DAO().patchURL(url, PHEADER, body) log_data = "PATCH %s %s ==status==> %s" % (url, body, response.status) if response.status != 200: _raise_exception(log_dat...
[ "def", "patch_resource", "(", "url", ",", "body", ")", ":", "response", "=", "Bridge_DAO", "(", ")", ".", "patchURL", "(", "url", ",", "PHEADER", ",", "body", ")", "log_data", "=", "\"PATCH %s %s ==status==> %s\"", "%", "(", "url", ",", "body", ",", "res...
Patch resource with the given json body :returns: http response data
[ "Patch", "resource", "with", "the", "given", "json", "body", ":", "returns", ":", "http", "response", "data" ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/bridge/__init__.py#L44-L56
uw-it-aca/uw-restclients
restclients/bridge/__init__.py
post_resource
def post_resource(url, body): """ Post resource with the given json body :returns: http response data """ response = Bridge_DAO().postURL(url, PHEADER, body) log_data = "POST %s %s ==status==> %s" % (url, body, response.status) if response.status != 200 and response.status != 201: #...
python
def post_resource(url, body): """ Post resource with the given json body :returns: http response data """ response = Bridge_DAO().postURL(url, PHEADER, body) log_data = "POST %s %s ==status==> %s" % (url, body, response.status) if response.status != 200 and response.status != 201: #...
[ "def", "post_resource", "(", "url", ",", "body", ")", ":", "response", "=", "Bridge_DAO", "(", ")", ".", "postURL", "(", "url", ",", "PHEADER", ",", "body", ")", "log_data", "=", "\"POST %s %s ==status==> %s\"", "%", "(", "url", ",", "body", ",", "respon...
Post resource with the given json body :returns: http response data
[ "Post", "resource", "with", "the", "given", "json", "body", ":", "returns", ":", "http", "response", "data" ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/bridge/__init__.py#L59-L72
uw-it-aca/uw-restclients
restclients/bridge/__init__.py
put_resource
def put_resource(url, body): """ Put request with the given json body :returns: http response data Bridge PUT seems to have the same effect as PATCH currently. """ response = Bridge_DAO().putURL(url, PHEADER, body) log_data = "PUT %s %s ==status==> %s" % (url, body, response.status) if ...
python
def put_resource(url, body): """ Put request with the given json body :returns: http response data Bridge PUT seems to have the same effect as PATCH currently. """ response = Bridge_DAO().putURL(url, PHEADER, body) log_data = "PUT %s %s ==status==> %s" % (url, body, response.status) if ...
[ "def", "put_resource", "(", "url", ",", "body", ")", ":", "response", "=", "Bridge_DAO", "(", ")", ".", "putURL", "(", "url", ",", "PHEADER", ",", "body", ")", "log_data", "=", "\"PUT %s %s ==status==> %s\"", "%", "(", "url", ",", "body", ",", "response"...
Put request with the given json body :returns: http response data Bridge PUT seems to have the same effect as PATCH currently.
[ "Put", "request", "with", "the", "given", "json", "body", ":", "returns", ":", "http", "response", "data", "Bridge", "PUT", "seems", "to", "have", "the", "same", "effect", "as", "PATCH", "currently", "." ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/bridge/__init__.py#L75-L88
9wfox/tornadoweb
tornadoweb/web.py
url
def url(pattern, order = 0): """ Class Decorator: 设置路径匹配模式和排序序号 1. 支持设置多个链接匹配规则。 参数: pattern 链接正则匹配 order 排序序号 示例: @url(r"(?i)/(index.html?)?", 10) @url(r"(?i)/default.html?", 8) class IndexHandler(...
python
def url(pattern, order = 0): """ Class Decorator: 设置路径匹配模式和排序序号 1. 支持设置多个链接匹配规则。 参数: pattern 链接正则匹配 order 排序序号 示例: @url(r"(?i)/(index.html?)?", 10) @url(r"(?i)/default.html?", 8) class IndexHandler(...
[ "def", "url", "(", "pattern", ",", "order", "=", "0", ")", ":", "def", "actual", "(", "handler", ")", ":", "if", "not", "isclass", "(", "handler", ")", "or", "not", "issubclass", "(", "handler", ",", "BaseHandler", ")", ":", "raise", "Exception", "("...
Class Decorator: 设置路径匹配模式和排序序号 1. 支持设置多个链接匹配规则。 参数: pattern 链接正则匹配 order 排序序号 示例: @url(r"(?i)/(index.html?)?", 10) @url(r"(?i)/default.html?", 8) class IndexHandler(BaseHandler): pass
[ "Class", "Decorator", ":", "设置路径匹配模式和排序序号", "1", ".", "支持设置多个链接匹配规则。", "参数", ":", "pattern", "链接正则匹配", "order", "排序序号", "示例", ":" ]
train
https://github.com/9wfox/tornadoweb/blob/2286b66fbe10e4d9f212b979664c15fa17adf378/tornadoweb/web.py#L141-L166
9wfox/tornadoweb
tornadoweb/web.py
BaseHandler.render_string
def render_string(self, template_name, **kwargs): """ 添加注入模板的自定义参数等信息 """ if hasattr(self, "session"): kwargs["session"] = self.session return super(BaseHandler, self).render_string(template_name, **kwargs)
python
def render_string(self, template_name, **kwargs): """ 添加注入模板的自定义参数等信息 """ if hasattr(self, "session"): kwargs["session"] = self.session return super(BaseHandler, self).render_string(template_name, **kwargs)
[ "def", "render_string", "(", "self", ",", "template_name", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "\"session\"", ")", ":", "kwargs", "[", "\"session\"", "]", "=", "self", ".", "session", "return", "super", "(", "BaseHandler...
添加注入模板的自定义参数等信息
[ "添加注入模板的自定义参数等信息" ]
train
https://github.com/9wfox/tornadoweb/blob/2286b66fbe10e4d9f212b979664c15fa17adf378/tornadoweb/web.py#L74-L79
9wfox/tornadoweb
tornadoweb/web.py
BaseHandler._return_url
def _return_url(self): """ 处理登录返回跳转链接 """ if type(self).__name__ == "LoginHandler" and self.request.method == "POST": return_url = self.get_argument("next", None) if return_url: self.set_cookie(self._RETURN_URL, return_url)
python
def _return_url(self): """ 处理登录返回跳转链接 """ if type(self).__name__ == "LoginHandler" and self.request.method == "POST": return_url = self.get_argument("next", None) if return_url: self.set_cookie(self._RETURN_URL, return_url)
[ "def", "_return_url", "(", "self", ")", ":", "if", "type", "(", "self", ")", ".", "__name__", "==", "\"LoginHandler\"", "and", "self", ".", "request", ".", "method", "==", "\"POST\"", ":", "return_url", "=", "self", ".", "get_argument", "(", "\"next\"", ...
处理登录返回跳转链接
[ "处理登录返回跳转链接" ]
train
https://github.com/9wfox/tornadoweb/blob/2286b66fbe10e4d9f212b979664c15fa17adf378/tornadoweb/web.py#L97-L103
9wfox/tornadoweb
tornadoweb/web.py
BaseHandler.signin
def signin(self, loginname, redirect = True, expires_days = None): """ 设置登录状态 参数: loginname 用户名或者编号。 redirect 是否跳转回登录前链接。 expires_days 保存时间,None 表示 Session Cookie,关浏览器就木有了。 """ self.set_secure_cook...
python
def signin(self, loginname, redirect = True, expires_days = None): """ 设置登录状态 参数: loginname 用户名或者编号。 redirect 是否跳转回登录前链接。 expires_days 保存时间,None 表示 Session Cookie,关浏览器就木有了。 """ self.set_secure_cook...
[ "def", "signin", "(", "self", ",", "loginname", ",", "redirect", "=", "True", ",", "expires_days", "=", "None", ")", ":", "self", ".", "set_secure_cookie", "(", "self", ".", "_USER_NAME", ",", "loginname", ",", "expires_days", "=", "expires_days", ")", "re...
设置登录状态 参数: loginname 用户名或者编号。 redirect 是否跳转回登录前链接。 expires_days 保存时间,None 表示 Session Cookie,关浏览器就木有了。
[ "设置登录状态", "参数", ":", "loginname", "用户名或者编号。", "redirect", "是否跳转回登录前链接。", "expires_days", "保存时间,None", "表示", "Session", "Cookie,关浏览器就木有了。" ]
train
https://github.com/9wfox/tornadoweb/blob/2286b66fbe10e4d9f212b979664c15fa17adf378/tornadoweb/web.py#L106-L119
9wfox/tornadoweb
tornadoweb/web.py
BaseHandler.signout
def signout(self, redirect_url = "/"): """ 注销登录状态 参数: redirect_url 跳转链接,为 None 时不跳转 (Ajax 可能用得到)。 """ self.clear_cookie(self._USER_NAME) if redirect_url: self.redirect(redirect_url)
python
def signout(self, redirect_url = "/"): """ 注销登录状态 参数: redirect_url 跳转链接,为 None 时不跳转 (Ajax 可能用得到)。 """ self.clear_cookie(self._USER_NAME) if redirect_url: self.redirect(redirect_url)
[ "def", "signout", "(", "self", ",", "redirect_url", "=", "\"/\"", ")", ":", "self", ".", "clear_cookie", "(", "self", ".", "_USER_NAME", ")", "if", "redirect_url", ":", "self", ".", "redirect", "(", "redirect_url", ")" ]
注销登录状态 参数: redirect_url 跳转链接,为 None 时不跳转 (Ajax 可能用得到)。
[ "注销登录状态", "参数", ":", "redirect_url", "跳转链接,为", "None", "时不跳转", "(", "Ajax", "可能用得到", ")", "。" ]
train
https://github.com/9wfox/tornadoweb/blob/2286b66fbe10e4d9f212b979664c15fa17adf378/tornadoweb/web.py#L122-L130
cmheisel/basecampreporting
src/basecampreporting/project.py
Project.time_entries
def time_entries(self, start_date=None, end_date=None): '''Array of all time entries''' if self.cache['time_entries']: return self.cache['time_entries'] if not start_date: start_date = datetime.date(1900, 1, 1) if not end_date: end_date = datetime.date.today() ...
python
def time_entries(self, start_date=None, end_date=None): '''Array of all time entries''' if self.cache['time_entries']: return self.cache['time_entries'] if not start_date: start_date = datetime.date(1900, 1, 1) if not end_date: end_date = datetime.date.today() ...
[ "def", "time_entries", "(", "self", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ")", ":", "if", "self", ".", "cache", "[", "'time_entries'", "]", ":", "return", "self", ".", "cache", "[", "'time_entries'", "]", "if", "not", "start_date"...
Array of all time entries
[ "Array", "of", "all", "time", "entries" ]
train
https://github.com/cmheisel/basecampreporting/blob/88ecfc6e835608650ff6be23cbf2421d224c122b/src/basecampreporting/project.py#L117-L129
cmheisel/basecampreporting
src/basecampreporting/project.py
Project.people
def people(self): '''Dictionary of people on the project, keyed by id''' if self.cache['people']: return self.cache['people'] people_xml = self.bc.people_within_project(self.id) for person_node in ET.fromstring(people_xml).findall('person'): p = Person(person_node) ...
python
def people(self): '''Dictionary of people on the project, keyed by id''' if self.cache['people']: return self.cache['people'] people_xml = self.bc.people_within_project(self.id) for person_node in ET.fromstring(people_xml).findall('person'): p = Person(person_node) ...
[ "def", "people", "(", "self", ")", ":", "if", "self", ".", "cache", "[", "'people'", "]", ":", "return", "self", ".", "cache", "[", "'people'", "]", "people_xml", "=", "self", ".", "bc", ".", "people_within_project", "(", "self", ".", "id", ")", "for...
Dictionary of people on the project, keyed by id
[ "Dictionary", "of", "people", "on", "the", "project", "keyed", "by", "id" ]
train
https://github.com/cmheisel/basecampreporting/blob/88ecfc6e835608650ff6be23cbf2421d224c122b/src/basecampreporting/project.py#L132-L139
cmheisel/basecampreporting
src/basecampreporting/project.py
Project.person
def person(self, person_id): '''Access a Person object by id''' if not self.cache['persons'].get(person_id, None): try: person_xml = self.bc.person(person_id) p = Person(person_xml) self.cache['persons'][person_id] = p except HTTPEr...
python
def person(self, person_id): '''Access a Person object by id''' if not self.cache['persons'].get(person_id, None): try: person_xml = self.bc.person(person_id) p = Person(person_xml) self.cache['persons'][person_id] = p except HTTPEr...
[ "def", "person", "(", "self", ",", "person_id", ")", ":", "if", "not", "self", ".", "cache", "[", "'persons'", "]", ".", "get", "(", "person_id", ",", "None", ")", ":", "try", ":", "person_xml", "=", "self", ".", "bc", ".", "person", "(", "person_i...
Access a Person object by id
[ "Access", "a", "Person", "object", "by", "id" ]
train
https://github.com/cmheisel/basecampreporting/blob/88ecfc6e835608650ff6be23cbf2421d224c122b/src/basecampreporting/project.py#L141-L150
cmheisel/basecampreporting
src/basecampreporting/project.py
Project.comments
def comments(self): '''Looks through the last 3 messages and returns those comments.''' if self.cache['comments']: return self.cache['comments'] comments = [] for message in self.messages[0:3]: comment_xml = self.bc.comments(message.id) for comment_node in ET.from...
python
def comments(self): '''Looks through the last 3 messages and returns those comments.''' if self.cache['comments']: return self.cache['comments'] comments = [] for message in self.messages[0:3]: comment_xml = self.bc.comments(message.id) for comment_node in ET.from...
[ "def", "comments", "(", "self", ")", ":", "if", "self", ".", "cache", "[", "'comments'", "]", ":", "return", "self", ".", "cache", "[", "'comments'", "]", "comments", "=", "[", "]", "for", "message", "in", "self", ".", "messages", "[", "0", ":", "3...
Looks through the last 3 messages and returns those comments.
[ "Looks", "through", "the", "last", "3", "messages", "and", "returns", "those", "comments", "." ]
train
https://github.com/cmheisel/basecampreporting/blob/88ecfc6e835608650ff6be23cbf2421d224c122b/src/basecampreporting/project.py#L153-L164