repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
armstrong/armstrong.apps.images
fabfile.py
update_colorbox
def update_colorbox(): """Update Colorbox code from vendor tree""" base_name = os.path.dirname(__file__) destination = os.path.join(base_name, "armstrong", "apps", "images", "static", "colorbox") colorbox_source = os.path.join(base_name, "vendor", "colorbox") colorbox_files = [ os.path.join(...
python
def update_colorbox(): """Update Colorbox code from vendor tree""" base_name = os.path.dirname(__file__) destination = os.path.join(base_name, "armstrong", "apps", "images", "static", "colorbox") colorbox_source = os.path.join(base_name, "vendor", "colorbox") colorbox_files = [ os.path.join(...
[ "def", "update_colorbox", "(", ")", ":", "base_name", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "destination", "=", "os", ".", "path", ".", "join", "(", "base_name", ",", "\"armstrong\"", ",", "\"apps\"", ",", "\"images\"", ",", "\"st...
Update Colorbox code from vendor tree
[ "Update", "Colorbox", "code", "from", "vendor", "tree" ]
train
https://github.com/armstrong/armstrong.apps.images/blob/f334697ee6e2273deac12092069d02119d913e67/fabfile.py#L40-L53
frigg/frigg-worker
frigg_worker/environment_variables.py
environment_variables_for_task
def environment_variables_for_task(task): """ This will build a dict with all the environment variables that should be present when running a build or deployment. :param task: A dict of the json payload with information about the build task. :return: A dict of environment variables...
python
def environment_variables_for_task(task): """ This will build a dict with all the environment variables that should be present when running a build or deployment. :param task: A dict of the json payload with information about the build task. :return: A dict of environment variables...
[ "def", "environment_variables_for_task", "(", "task", ")", ":", "env", "=", "{", "'CI'", ":", "'frigg'", ",", "'FRIGG'", ":", "'true'", ",", "'FRIGG_CI'", ":", "'true'", ",", "'GH_TOKEN'", ":", "task", "[", "'gh_token'", "]", ",", "'FRIGG_BUILD_BRANCH'", ":"...
This will build a dict with all the environment variables that should be present when running a build or deployment. :param task: A dict of the json payload with information about the build task. :return: A dict of environment variables.
[ "This", "will", "build", "a", "dict", "with", "all", "the", "environment", "variables", "that", "should", "be", "present", "when", "running", "a", "build", "or", "deployment", "." ]
train
https://github.com/frigg/frigg-worker/blob/8c215cd8f5a27ff9f5a4fedafe93d2ef0fbca86c/frigg_worker/environment_variables.py#L4-L38
political-memory/django-representatives-votes
representatives_votes/contrib/parltrack/import_dossiers.py
parse_dossier_data
def parse_dossier_data(data, ep): """Parse data from parltarck dossier export (1 dossier) Update dossier if it existed before, this function goal is to import and update a dossier, not to import all parltrack data """ changed = False doc_changed = False ref = data['procedure']['reference'] ...
python
def parse_dossier_data(data, ep): """Parse data from parltarck dossier export (1 dossier) Update dossier if it existed before, this function goal is to import and update a dossier, not to import all parltrack data """ changed = False doc_changed = False ref = data['procedure']['reference'] ...
[ "def", "parse_dossier_data", "(", "data", ",", "ep", ")", ":", "changed", "=", "False", "doc_changed", "=", "False", "ref", "=", "data", "[", "'procedure'", "]", "[", "'reference'", "]", "logger", ".", "debug", "(", "'Processing dossier %s'", ",", "ref", "...
Parse data from parltarck dossier export (1 dossier) Update dossier if it existed before, this function goal is to import and update a dossier, not to import all parltrack data
[ "Parse", "data", "from", "parltarck", "dossier", "export", "(", "1", "dossier", ")", "Update", "dossier", "if", "it", "existed", "before", "this", "function", "goal", "is", "to", "import", "and", "update", "a", "dossier", "not", "to", "import", "all", "par...
train
https://github.com/political-memory/django-representatives-votes/blob/97f9f29deefec05f18e51f6c38270b791b921bac/representatives_votes/contrib/parltrack/import_dossiers.py#L22-L71
WTRMQDev/lnoise
lnoise/noisetypes.py
Hash.hkdf
def hkdf(self, chaining_key, input_key_material, dhlen=64): """Hash-based key derivation function Takes a ``chaining_key'' byte sequence of len HASHLEN, and an ``input_key_material'' byte sequence with length either zero bytes, 32 bytes or dhlen bytes. Returns two byte sequence...
python
def hkdf(self, chaining_key, input_key_material, dhlen=64): """Hash-based key derivation function Takes a ``chaining_key'' byte sequence of len HASHLEN, and an ``input_key_material'' byte sequence with length either zero bytes, 32 bytes or dhlen bytes. Returns two byte sequence...
[ "def", "hkdf", "(", "self", ",", "chaining_key", ",", "input_key_material", ",", "dhlen", "=", "64", ")", ":", "if", "len", "(", "chaining_key", ")", "!=", "self", ".", "HASHLEN", ":", "raise", "HashError", "(", "\"Incorrect chaining key length\"", ")", "if"...
Hash-based key derivation function Takes a ``chaining_key'' byte sequence of len HASHLEN, and an ``input_key_material'' byte sequence with length either zero bytes, 32 bytes or dhlen bytes. Returns two byte sequences of length HASHLEN
[ "Hash", "-", "based", "key", "derivation", "function" ]
train
https://github.com/WTRMQDev/lnoise/blob/7f8d9faf135025a6aac50131d14a34d1009e8cdd/lnoise/noisetypes.py#L69-L85
WTRMQDev/lnoise
lnoise/noisetypes.py
NoiseBuffer.append
def append(self, val): """Append byte string val to buffer If the result exceeds the length of the buffer, behavior depends on whether instance was initialized as strict. In strict mode, a ValueError is raised. In non-strict mode, the buffer is extended as necessary. """ ...
python
def append(self, val): """Append byte string val to buffer If the result exceeds the length of the buffer, behavior depends on whether instance was initialized as strict. In strict mode, a ValueError is raised. In non-strict mode, the buffer is extended as necessary. """ ...
[ "def", "append", "(", "self", ",", "val", ")", ":", "new_len", "=", "self", ".", "length", "+", "len", "(", "val", ")", "to_add", "=", "new_len", "-", "len", "(", "self", ".", "bfr", ")", "if", "self", ".", "strict", "and", "to_add", ">", "0", ...
Append byte string val to buffer If the result exceeds the length of the buffer, behavior depends on whether instance was initialized as strict. In strict mode, a ValueError is raised. In non-strict mode, the buffer is extended as necessary.
[ "Append", "byte", "string", "val", "to", "buffer", "If", "the", "result", "exceeds", "the", "length", "of", "the", "buffer", "behavior", "depends", "on", "whether", "instance", "was", "initialized", "as", "strict", ".", "In", "strict", "mode", "a", "ValueErr...
train
https://github.com/WTRMQDev/lnoise/blob/7f8d9faf135025a6aac50131d14a34d1009e8cdd/lnoise/noisetypes.py#L113-L125
CitrineInformatics/dftparse
dftparse/wien2k/eloss_parser.py
_parse_eloss
def _parse_eloss(line, lines): """Parse Energy [eV] eloss_xx eloss_zz""" split_line = line.split() energy = float(split_line[0]) eloss_xx = float(split_line[1]) eloss_zz = float(split_line[2]) return {"energy": energy, "eloss_xx": eloss_xx, "eloss_zz": eloss_zz}
python
def _parse_eloss(line, lines): """Parse Energy [eV] eloss_xx eloss_zz""" split_line = line.split() energy = float(split_line[0]) eloss_xx = float(split_line[1]) eloss_zz = float(split_line[2]) return {"energy": energy, "eloss_xx": eloss_xx, "eloss_zz": eloss_zz}
[ "def", "_parse_eloss", "(", "line", ",", "lines", ")", ":", "split_line", "=", "line", ".", "split", "(", ")", "energy", "=", "float", "(", "split_line", "[", "0", "]", ")", "eloss_xx", "=", "float", "(", "split_line", "[", "1", "]", ")", "eloss_zz",...
Parse Energy [eV] eloss_xx eloss_zz
[ "Parse", "Energy", "[", "eV", "]", "eloss_xx", "eloss_zz" ]
train
https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/wien2k/eloss_parser.py#L4-L13
briancappello/flask-sqlalchemy-bundle
flask_sqlalchemy_bundle/services/model_manager.py
ModelManager.get_or_create
def get_or_create(self, commit=False, **kwargs) -> Tuple[model, bool]: """ :return: returns a tuple of the instance and a boolean flag specifying whether or not the instance was created """ instance = self.get_by(**kwargs) if not instance: return self.create(c...
python
def get_or_create(self, commit=False, **kwargs) -> Tuple[model, bool]: """ :return: returns a tuple of the instance and a boolean flag specifying whether or not the instance was created """ instance = self.get_by(**kwargs) if not instance: return self.create(c...
[ "def", "get_or_create", "(", "self", ",", "commit", "=", "False", ",", "*", "*", "kwargs", ")", "->", "Tuple", "[", "model", ",", "bool", "]", ":", "instance", "=", "self", ".", "get_by", "(", "*", "*", "kwargs", ")", "if", "not", "instance", ":", ...
:return: returns a tuple of the instance and a boolean flag specifying whether or not the instance was created
[ ":", "return", ":", "returns", "a", "tuple", "of", "the", "instance", "and", "a", "boolean", "flag", "specifying", "whether", "or", "not", "the", "instance", "was", "created" ]
train
https://github.com/briancappello/flask-sqlalchemy-bundle/blob/8150896787907ef0001839b5a6ef303edccb9b6c/flask_sqlalchemy_bundle/services/model_manager.py#L43-L51
shi-cong/PYSTUDY
PYSTUDY/randomlib.py
random_str
def random_str(n=20): """ 随机生成一串密码 :param n: 密码的长度,默认为20 :return: 长度为n的随机字符串 """ return ''.join(random.sample(string.ascii_letters + string.digits, n))
python
def random_str(n=20): """ 随机生成一串密码 :param n: 密码的长度,默认为20 :return: 长度为n的随机字符串 """ return ''.join(random.sample(string.ascii_letters + string.digits, n))
[ "def", "random_str", "(", "n", "=", "20", ")", ":", "return", "''", ".", "join", "(", "random", ".", "sample", "(", "string", ".", "ascii_letters", "+", "string", ".", "digits", ",", "n", ")", ")" ]
随机生成一串密码 :param n: 密码的长度,默认为20 :return: 长度为n的随机字符串
[ "随机生成一串密码", ":", "param", "n", ":", "密码的长度,默认为20", ":", "return", ":", "长度为n的随机字符串" ]
train
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/randomlib.py#L9-L15
klmitch/tendril
tendril/utils.py
addr_info
def addr_info(addr): """ Interprets an address in standard tuple format to determine if it is valid, and, if so, which socket family it is. Returns the socket family. """ # If it's a string, it's in the UNIX family if isinstance(addr, basestring): return socket.AF_UNIX # Verif...
python
def addr_info(addr): """ Interprets an address in standard tuple format to determine if it is valid, and, if so, which socket family it is. Returns the socket family. """ # If it's a string, it's in the UNIX family if isinstance(addr, basestring): return socket.AF_UNIX # Verif...
[ "def", "addr_info", "(", "addr", ")", ":", "# If it's a string, it's in the UNIX family", "if", "isinstance", "(", "addr", ",", "basestring", ")", ":", "return", "socket", ".", "AF_UNIX", "# Verify that addr is a tuple", "if", "not", "isinstance", "(", "addr", ",", ...
Interprets an address in standard tuple format to determine if it is valid, and, if so, which socket family it is. Returns the socket family.
[ "Interprets", "an", "address", "in", "standard", "tuple", "format", "to", "determine", "if", "it", "is", "valid", "and", "if", "so", "which", "socket", "family", "it", "is", ".", "Returns", "the", "socket", "family", "." ]
train
https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/utils.py#L113-L158
klmitch/tendril
tendril/utils.py
WrapperChain.chain
def chain(self, wrapper, *args, **kwargs): """ Add a wrapper to the chain. Any extra positional or keyword arguments will be passed to that wrapper through construction of a ``TendrilPartial``. For convenience, returns the WrapperChain object, allowing ``chain()`` to be called ...
python
def chain(self, wrapper, *args, **kwargs): """ Add a wrapper to the chain. Any extra positional or keyword arguments will be passed to that wrapper through construction of a ``TendrilPartial``. For convenience, returns the WrapperChain object, allowing ``chain()`` to be called ...
[ "def", "chain", "(", "self", ",", "wrapper", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "or", "kwargs", ":", "wrapper", "=", "TendrilPartial", "(", "wrapper", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_...
Add a wrapper to the chain. Any extra positional or keyword arguments will be passed to that wrapper through construction of a ``TendrilPartial``. For convenience, returns the WrapperChain object, allowing ``chain()`` to be called on the return result to register multiple wrappers.
[ "Add", "a", "wrapper", "to", "the", "chain", ".", "Any", "extra", "positional", "or", "keyword", "arguments", "will", "be", "passed", "to", "that", "wrapper", "through", "construction", "of", "a", "TendrilPartial", ".", "For", "convenience", "returns", "the", ...
train
https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/utils.py#L95-L110
anjos/rrbob
rr/algorithm.py
make_labels
def make_labels(X): """Helper function that generates a single 1D numpy.ndarray with labels which are good targets for stock logistic regression. Parameters: X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2 ...
python
def make_labels(X): """Helper function that generates a single 1D numpy.ndarray with labels which are good targets for stock logistic regression. Parameters: X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2 ...
[ "def", "make_labels", "(", "X", ")", ":", "return", "numpy", ".", "hstack", "(", "[", "k", "*", "numpy", ".", "ones", "(", "len", "(", "X", "[", "k", "]", ")", ",", "dtype", "=", "int", ")", "for", "k", "in", "range", "(", "len", "(", "X", ...
Helper function that generates a single 1D numpy.ndarray with labels which are good targets for stock logistic regression. Parameters: X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2 dimensions each. Each c...
[ "Helper", "function", "that", "generates", "a", "single", "1D", "numpy", ".", "ndarray", "with", "labels", "which", "are", "good", "targets", "for", "stock", "logistic", "regression", "." ]
train
https://github.com/anjos/rrbob/blob/d32d35bab2aa2698d3caa923fd02afb6d67f3235/rr/algorithm.py#L13-L34
anjos/rrbob
rr/algorithm.py
add_bias
def add_bias(X): """Helper function to add a bias column to the input array X Parameters: X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 2 dimension wheres every row corresponds to one example of the data set, every column, one different feature. Returns: num...
python
def add_bias(X): """Helper function to add a bias column to the input array X Parameters: X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 2 dimension wheres every row corresponds to one example of the data set, every column, one different feature. Returns: num...
[ "def", "add_bias", "(", "X", ")", ":", "return", "numpy", ".", "hstack", "(", "(", "numpy", ".", "ones", "(", "(", "len", "(", "X", ")", ",", "1", ")", ",", "dtype", "=", "X", ".", "dtype", ")", ",", "X", ")", ")" ]
Helper function to add a bias column to the input array X Parameters: X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 2 dimension wheres every row corresponds to one example of the data set, every column, one different feature. Returns: numpy.ndarray: The same i...
[ "Helper", "function", "to", "add", "a", "bias", "column", "to", "the", "input", "array", "X" ]
train
https://github.com/anjos/rrbob/blob/d32d35bab2aa2698d3caa923fd02afb6d67f3235/rr/algorithm.py#L37-L55
anjos/rrbob
rr/algorithm.py
MultiClassTrainer.train
def train(self, X): """ Trains multiple logistic regression classifiers to handle the multiclass problem posed by ``X`` X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2 dimensions each. Each corr...
python
def train(self, X): """ Trains multiple logistic regression classifiers to handle the multiclass problem posed by ``X`` X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2 dimensions each. Each corr...
[ "def", "train", "(", "self", ",", "X", ")", ":", "_trainer", "=", "bob", ".", "learn", ".", "linear", ".", "CGLogRegTrainer", "(", "*", "*", "{", "'lambda'", ":", "self", ".", "regularizer", "}", ")", "if", "len", "(", "X", ")", "==", "2", ":", ...
Trains multiple logistic regression classifiers to handle the multiclass problem posed by ``X`` X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2 dimensions each. Each correspond to the data for one of th...
[ "Trains", "multiple", "logistic", "regression", "classifiers", "to", "handle", "the", "multiclass", "problem", "posed", "by", "X" ]
train
https://github.com/anjos/rrbob/blob/d32d35bab2aa2698d3caa923fd02afb6d67f3235/rr/algorithm.py#L136-L169
robertchase/ergaleia
ergaleia/nested_get.py
nested_get
def nested_get(d, keys, default=None, required=False, as_list=False): """ Multi-level dict get helper Parameters: d - dict instance keys - iterable of keys or dot-delimited str of keys (see Note 1) default - value if index fails ...
python
def nested_get(d, keys, default=None, required=False, as_list=False): """ Multi-level dict get helper Parameters: d - dict instance keys - iterable of keys or dot-delimited str of keys (see Note 1) default - value if index fails ...
[ "def", "nested_get", "(", "d", ",", "keys", ",", "default", "=", "None", ",", "required", "=", "False", ",", "as_list", "=", "False", ")", ":", "if", "isinstance", "(", "keys", ",", "str", ")", ":", "keys", "=", "keys", ".", "split", "(", "'.'", ...
Multi-level dict get helper Parameters: d - dict instance keys - iterable of keys or dot-delimited str of keys (see Note 1) default - value if index fails required - require every index to work (see Note 2) as_list ...
[ "Multi", "-", "level", "dict", "get", "helper" ]
train
https://github.com/robertchase/ergaleia/blob/df8e9a4b18c563022a503faa27e822c9a5755490/ergaleia/nested_get.py#L8-L51
zagfai/webtul
webtul/utils.py
recur
def recur(obj, type_func_tuple_list=()): '''recuring dealing an object''' for obj_type, func in type_func_tuple_list: if type(obj) == type(obj_type): return func(obj) # by default, we wolud recurring list, tuple and dict if isinstance(obj, list) or isinstance(obj, tuple): n_o...
python
def recur(obj, type_func_tuple_list=()): '''recuring dealing an object''' for obj_type, func in type_func_tuple_list: if type(obj) == type(obj_type): return func(obj) # by default, we wolud recurring list, tuple and dict if isinstance(obj, list) or isinstance(obj, tuple): n_o...
[ "def", "recur", "(", "obj", ",", "type_func_tuple_list", "=", "(", ")", ")", ":", "for", "obj_type", ",", "func", "in", "type_func_tuple_list", ":", "if", "type", "(", "obj", ")", "==", "type", "(", "obj_type", ")", ":", "return", "func", "(", "obj", ...
recuring dealing an object
[ "recuring", "dealing", "an", "object" ]
train
https://github.com/zagfai/webtul/blob/58c49928070b56ef54a45b4af20d800b269ad8ce/webtul/utils.py#L32-L48
zagfai/webtul
webtul/utils.py
browser_cache
def browser_cache(seconds): """Decorator for browser cache. Only for webpy @browser_cache( seconds ) before GET/POST function. """ import web def wrap(f): def wrapped_f(*args): last_time_str = web.ctx.env.get('HTTP_IF_MODIFIED_SINCE', '') last_time = web.net.parsehttp...
python
def browser_cache(seconds): """Decorator for browser cache. Only for webpy @browser_cache( seconds ) before GET/POST function. """ import web def wrap(f): def wrapped_f(*args): last_time_str = web.ctx.env.get('HTTP_IF_MODIFIED_SINCE', '') last_time = web.net.parsehttp...
[ "def", "browser_cache", "(", "seconds", ")", ":", "import", "web", "def", "wrap", "(", "f", ")", ":", "def", "wrapped_f", "(", "*", "args", ")", ":", "last_time_str", "=", "web", ".", "ctx", ".", "env", ".", "get", "(", "'HTTP_IF_MODIFIED_SINCE'", ",",...
Decorator for browser cache. Only for webpy @browser_cache( seconds ) before GET/POST function.
[ "Decorator", "for", "browser", "cache", ".", "Only", "for", "webpy" ]
train
https://github.com/zagfai/webtul/blob/58c49928070b56ef54a45b4af20d800b269ad8ce/webtul/utils.py#L50-L68
jalanb/pysyte
pysyte/splits.py
join
def join(items, separator=None): """Join the items into a string using the separator Converts items to strings if needed >>> join([1, 2, 3]) '1,2,3' """ if not items: return '' if separator is None: separator = _default_separator() return separator.join([str(item) for i...
python
def join(items, separator=None): """Join the items into a string using the separator Converts items to strings if needed >>> join([1, 2, 3]) '1,2,3' """ if not items: return '' if separator is None: separator = _default_separator() return separator.join([str(item) for i...
[ "def", "join", "(", "items", ",", "separator", "=", "None", ")", ":", "if", "not", "items", ":", "return", "''", "if", "separator", "is", "None", ":", "separator", "=", "_default_separator", "(", ")", "return", "separator", ".", "join", "(", "[", "str"...
Join the items into a string using the separator Converts items to strings if needed >>> join([1, 2, 3]) '1,2,3'
[ "Join", "the", "items", "into", "a", "string", "using", "the", "separator" ]
train
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/splits.py#L17-L29
jalanb/pysyte
pysyte/splits.py
split
def split(string, separator_regexp=None, maxsplit=0): """Split a string to a list >>> split('fred, was, here') ['fred', ' was', ' here'] """ if not string: return [] if separator_regexp is None: separator_regexp = _default_separator() if not separator_regexp: return ...
python
def split(string, separator_regexp=None, maxsplit=0): """Split a string to a list >>> split('fred, was, here') ['fred', ' was', ' here'] """ if not string: return [] if separator_regexp is None: separator_regexp = _default_separator() if not separator_regexp: return ...
[ "def", "split", "(", "string", ",", "separator_regexp", "=", "None", ",", "maxsplit", "=", "0", ")", ":", "if", "not", "string", ":", "return", "[", "]", "if", "separator_regexp", "is", "None", ":", "separator_regexp", "=", "_default_separator", "(", ")", ...
Split a string to a list >>> split('fred, was, here') ['fred', ' was', ' here']
[ "Split", "a", "string", "to", "a", "list" ]
train
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/splits.py#L41-L53
jalanb/pysyte
pysyte/splits.py
split_and_strip
def split_and_strip(string, separator_regexp=None, maxsplit=0): """Split a string into items and trim any excess spaces from the items >>> split_and_strip('fred, was, here ') ['fred', 'was', 'here'] """ if not string: return [''] if separator_regexp is None: separator_regexp = ...
python
def split_and_strip(string, separator_regexp=None, maxsplit=0): """Split a string into items and trim any excess spaces from the items >>> split_and_strip('fred, was, here ') ['fred', 'was', 'here'] """ if not string: return [''] if separator_regexp is None: separator_regexp = ...
[ "def", "split_and_strip", "(", "string", ",", "separator_regexp", "=", "None", ",", "maxsplit", "=", "0", ")", ":", "if", "not", "string", ":", "return", "[", "''", "]", "if", "separator_regexp", "is", "None", ":", "separator_regexp", "=", "_default_separato...
Split a string into items and trim any excess spaces from the items >>> split_and_strip('fred, was, here ') ['fred', 'was', 'here']
[ "Split", "a", "string", "into", "items", "and", "trim", "any", "excess", "spaces", "from", "the", "items" ]
train
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/splits.py#L56-L69
jalanb/pysyte
pysyte/splits.py
split_and_strip_without
def split_and_strip_without(string, exclude, separator_regexp=None): """Split a string into items, and trim any excess spaces Any items in exclude are not in the returned list >>> split_and_strip_without('fred, was, here ', ['was']) ['fred', 'here'] """ result = split_and_strip(string, separa...
python
def split_and_strip_without(string, exclude, separator_regexp=None): """Split a string into items, and trim any excess spaces Any items in exclude are not in the returned list >>> split_and_strip_without('fred, was, here ', ['was']) ['fred', 'here'] """ result = split_and_strip(string, separa...
[ "def", "split_and_strip_without", "(", "string", ",", "exclude", ",", "separator_regexp", "=", "None", ")", ":", "result", "=", "split_and_strip", "(", "string", ",", "separator_regexp", ")", "if", "not", "exclude", ":", "return", "result", "return", "[", "x",...
Split a string into items, and trim any excess spaces Any items in exclude are not in the returned list >>> split_and_strip_without('fred, was, here ', ['was']) ['fred', 'here']
[ "Split", "a", "string", "into", "items", "and", "trim", "any", "excess", "spaces" ]
train
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/splits.py#L72-L83
jalanb/pysyte
pysyte/splits.py
split_by_count
def split_by_count(items, count, filler=None): """Split the items into tuples of count items each >>> split_by_count([0,1,2,3], 2) [(0, 1), (2, 3)] If there are a mutiple of count items then filler makes no difference >>> split_by_count([0,1,2,7,8,9], 3, 0) == split_by_count([0,1,2,7,8,9], 3) ...
python
def split_by_count(items, count, filler=None): """Split the items into tuples of count items each >>> split_by_count([0,1,2,3], 2) [(0, 1), (2, 3)] If there are a mutiple of count items then filler makes no difference >>> split_by_count([0,1,2,7,8,9], 3, 0) == split_by_count([0,1,2,7,8,9], 3) ...
[ "def", "split_by_count", "(", "items", ",", "count", ",", "filler", "=", "None", ")", ":", "if", "filler", "is", "not", "None", ":", "items", "=", "items", "[", ":", "]", "while", "len", "(", "items", ")", "%", "count", ":", "items", ".", "append",...
Split the items into tuples of count items each >>> split_by_count([0,1,2,3], 2) [(0, 1), (2, 3)] If there are a mutiple of count items then filler makes no difference >>> split_by_count([0,1,2,7,8,9], 3, 0) == split_by_count([0,1,2,7,8,9], 3) True If there are not a multiple of count items, ...
[ "Split", "the", "items", "into", "tuples", "of", "count", "items", "each" ]
train
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/splits.py#L97-L121
jalanb/pysyte
pysyte/splits.py
rejoin
def rejoin(string, separator_regexp=None, spaced=False): """Split a string and then rejoin it Spaces are interspersed between items only if spaced is True >>> rejoin('fred, was, here ') 'fred,was,here' """ strings = split_and_strip(string) if separator_regexp is None: separator_re...
python
def rejoin(string, separator_regexp=None, spaced=False): """Split a string and then rejoin it Spaces are interspersed between items only if spaced is True >>> rejoin('fred, was, here ') 'fred,was,here' """ strings = split_and_strip(string) if separator_regexp is None: separator_re...
[ "def", "rejoin", "(", "string", ",", "separator_regexp", "=", "None", ",", "spaced", "=", "False", ")", ":", "strings", "=", "split_and_strip", "(", "string", ")", "if", "separator_regexp", "is", "None", ":", "separator_regexp", "=", "_default_separator", "(",...
Split a string and then rejoin it Spaces are interspersed between items only if spaced is True >>> rejoin('fred, was, here ') 'fred,was,here'
[ "Split", "a", "string", "and", "then", "rejoin", "it" ]
train
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/splits.py#L172-L184
Bystroushaak/BalancedDiscStorage
src/BalancedDiscStorage/balanced_disc_storage_z.py
BalancedDiscStorageZ._unpack_zip
def _unpack_zip(self, file_obj, path): """ Unpack .zip archive in `file_obj` to given `path`. Make sure, that it fits into limits (see :attr:`._max_zipfiles` for details). Args: file_obj (file): Opened file-like object. path (str): Path into which the .zip will b...
python
def _unpack_zip(self, file_obj, path): """ Unpack .zip archive in `file_obj` to given `path`. Make sure, that it fits into limits (see :attr:`._max_zipfiles` for details). Args: file_obj (file): Opened file-like object. path (str): Path into which the .zip will b...
[ "def", "_unpack_zip", "(", "self", ",", "file_obj", ",", "path", ")", ":", "old_cwd", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "path", ")", "zip_obj", "=", "zipfile", ".", "ZipFile", "(", "file_obj", ")", "for", "cnt", ",", "zip...
Unpack .zip archive in `file_obj` to given `path`. Make sure, that it fits into limits (see :attr:`._max_zipfiles` for details). Args: file_obj (file): Opened file-like object. path (str): Path into which the .zip will be unpacked. Raises: ValueError: If the...
[ "Unpack", ".", "zip", "archive", "in", "file_obj", "to", "given", "path", ".", "Make", "sure", "that", "it", "fits", "into", "limits", "(", "see", ":", "attr", ":", ".", "_max_zipfiles", "for", "details", ")", "." ]
train
https://github.com/Bystroushaak/BalancedDiscStorage/blob/d96854e2afdd70c814b16d177ff6308841b34b24/src/BalancedDiscStorage/balanced_disc_storage_z.py#L26-L55
Bystroushaak/BalancedDiscStorage
src/BalancedDiscStorage/balanced_disc_storage_z.py
BalancedDiscStorageZ.add_archive_as_dir
def add_archive_as_dir(self, zip_file_obj): """ Add archive to the storage and unpack it. Args: zip_file_obj (file): Opened file-like object. Returns: obj: Path where the `zip_file_obj` was unpacked wrapped in \ :class:`.PathAndHash` structure. ...
python
def add_archive_as_dir(self, zip_file_obj): """ Add archive to the storage and unpack it. Args: zip_file_obj (file): Opened file-like object. Returns: obj: Path where the `zip_file_obj` was unpacked wrapped in \ :class:`.PathAndHash` structure. ...
[ "def", "add_archive_as_dir", "(", "self", ",", "zip_file_obj", ")", ":", "BalancedDiscStorage", ".", "_check_interface", "(", "zip_file_obj", ")", "file_hash", "=", "self", ".", "_get_hash", "(", "zip_file_obj", ")", "dir_path", "=", "self", ".", "_create_dir_path...
Add archive to the storage and unpack it. Args: zip_file_obj (file): Opened file-like object. Returns: obj: Path where the `zip_file_obj` was unpacked wrapped in \ :class:`.PathAndHash` structure. Raises: ValueError: If there is too many fi...
[ "Add", "archive", "to", "the", "storage", "and", "unpack", "it", "." ]
train
https://github.com/Bystroushaak/BalancedDiscStorage/blob/d96854e2afdd70c814b16d177ff6308841b34b24/src/BalancedDiscStorage/balanced_disc_storage_z.py#L57-L90
aquatix/python-utilkit
utilkit/printutil.py
to_even_columns
def to_even_columns(data, headers=None): """ Nicely format the 2-dimensional list into evenly spaced columns """ result = '' col_width = max(len(word) for row in data for word in row) + 2 # padding if headers: header_width = max(len(word) for row in headers for word in row) + 2 ...
python
def to_even_columns(data, headers=None): """ Nicely format the 2-dimensional list into evenly spaced columns """ result = '' col_width = max(len(word) for row in data for word in row) + 2 # padding if headers: header_width = max(len(word) for row in headers for word in row) + 2 ...
[ "def", "to_even_columns", "(", "data", ",", "headers", "=", "None", ")", ":", "result", "=", "''", "col_width", "=", "max", "(", "len", "(", "word", ")", "for", "row", "in", "data", "for", "word", "in", "row", ")", "+", "2", "# padding", "if", "hea...
Nicely format the 2-dimensional list into evenly spaced columns
[ "Nicely", "format", "the", "2", "-", "dimensional", "list", "into", "evenly", "spaced", "columns" ]
train
https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/printutil.py#L6-L22
aquatix/python-utilkit
utilkit/printutil.py
to_smart_columns
def to_smart_columns(data, headers=None, padding=2): """ Nicely format the 2-dimensional list into columns """ result = '' col_widths = [] for row in data: col_counter = 0 for word in row: try: col_widths[col_counter] = max(len(word), col_widths[col_co...
python
def to_smart_columns(data, headers=None, padding=2): """ Nicely format the 2-dimensional list into columns """ result = '' col_widths = [] for row in data: col_counter = 0 for word in row: try: col_widths[col_counter] = max(len(word), col_widths[col_co...
[ "def", "to_smart_columns", "(", "data", ",", "headers", "=", "None", ",", "padding", "=", "2", ")", ":", "result", "=", "''", "col_widths", "=", "[", "]", "for", "row", "in", "data", ":", "col_counter", "=", "0", "for", "word", "in", "row", ":", "t...
Nicely format the 2-dimensional list into columns
[ "Nicely", "format", "the", "2", "-", "dimensional", "list", "into", "columns" ]
train
https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/printutil.py#L25-L67
aquatix/python-utilkit
utilkit/printutil.py
progress_bar
def progress_bar(items_total, items_progress, columns=40, base_char='.', progress_char='#', percentage=False, prefix='', postfix=''): """ Print a progress bar of width `columns` """ bins_total = int(float(items_total) / columns) + 1 bins_progress = int((float(items_progress) / float(items_total)) * ...
python
def progress_bar(items_total, items_progress, columns=40, base_char='.', progress_char='#', percentage=False, prefix='', postfix=''): """ Print a progress bar of width `columns` """ bins_total = int(float(items_total) / columns) + 1 bins_progress = int((float(items_progress) / float(items_total)) * ...
[ "def", "progress_bar", "(", "items_total", ",", "items_progress", ",", "columns", "=", "40", ",", "base_char", "=", "'.'", ",", "progress_char", "=", "'#'", ",", "percentage", "=", "False", ",", "prefix", "=", "''", ",", "postfix", "=", "''", ")", ":", ...
Print a progress bar of width `columns`
[ "Print", "a", "progress", "bar", "of", "width", "columns" ]
train
https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/printutil.py#L70-L84
aquatix/python-utilkit
utilkit/printutil.py
merge_x_y
def merge_x_y(collection_x, collection_y, filter_none=False): """ Merge two lists, creating a dictionary with key `label` and a set x and y """ data = {} for item in collection_x: #print item[0:-1] #print item[-1] label = datetimeutil.tuple_to_string(item[0:-1]) if fi...
python
def merge_x_y(collection_x, collection_y, filter_none=False): """ Merge two lists, creating a dictionary with key `label` and a set x and y """ data = {} for item in collection_x: #print item[0:-1] #print item[-1] label = datetimeutil.tuple_to_string(item[0:-1]) if fi...
[ "def", "merge_x_y", "(", "collection_x", ",", "collection_y", ",", "filter_none", "=", "False", ")", ":", "data", "=", "{", "}", "for", "item", "in", "collection_x", ":", "#print item[0:-1]", "#print item[-1]", "label", "=", "datetimeutil", ".", "tuple_to_string...
Merge two lists, creating a dictionary with key `label` and a set x and y
[ "Merge", "two", "lists", "creating", "a", "dictionary", "with", "key", "label", "and", "a", "set", "x", "and", "y" ]
train
https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/printutil.py#L87-L110
aquatix/python-utilkit
utilkit/printutil.py
x_vs_y
def x_vs_y(collection_x, collection_y, title_x=None, title_y=None, width=43, filter_none=False): """ Print a histogram with bins for x to the left and bins of y to the right """ data = merge_x_y(collection_x, collection_y, filter_none) max_value = get_max_x_y(data) bins_total = int(float(max_va...
python
def x_vs_y(collection_x, collection_y, title_x=None, title_y=None, width=43, filter_none=False): """ Print a histogram with bins for x to the left and bins of y to the right """ data = merge_x_y(collection_x, collection_y, filter_none) max_value = get_max_x_y(data) bins_total = int(float(max_va...
[ "def", "x_vs_y", "(", "collection_x", ",", "collection_y", ",", "title_x", "=", "None", ",", "title_y", "=", "None", ",", "width", "=", "43", ",", "filter_none", "=", "False", ")", ":", "data", "=", "merge_x_y", "(", "collection_x", ",", "collection_y", ...
Print a histogram with bins for x to the left and bins of y to the right
[ "Print", "a", "histogram", "with", "bins", "for", "x", "to", "the", "left", "and", "bins", "of", "y", "to", "the", "right" ]
train
https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/printutil.py#L123-L147
Amsterdam/authorization_django
authorization_django/config.py
_rectify
def _rectify(settings): """ Rectify (and validate) the given settings using the functions in :data:`_settings_rectifiers`. """ for key, rectifier in _settings_rectifiers.items(): try: new_value = rectifier['func'](settings[key]) if new_value is False: rais...
python
def _rectify(settings): """ Rectify (and validate) the given settings using the functions in :data:`_settings_rectifiers`. """ for key, rectifier in _settings_rectifiers.items(): try: new_value = rectifier['func'](settings[key]) if new_value is False: rais...
[ "def", "_rectify", "(", "settings", ")", ":", "for", "key", ",", "rectifier", "in", "_settings_rectifiers", ".", "items", "(", ")", ":", "try", ":", "new_value", "=", "rectifier", "[", "'func'", "]", "(", "settings", "[", "key", "]", ")", "if", "new_va...
Rectify (and validate) the given settings using the functions in :data:`_settings_rectifiers`.
[ "Rectify", "(", "and", "validate", ")", "the", "given", "settings", "using", "the", "functions", "in", ":", "data", ":", "_settings_rectifiers", "." ]
train
https://github.com/Amsterdam/authorization_django/blob/71da52b38a7f5a16a2bde8f8ea97b3c11ccb1be1/authorization_django/config.py#L60-L75
Amsterdam/authorization_django
authorization_django/config.py
settings
def settings(): """ Fetch the middleware settings. :return dict: settings """ # Get the user-provided settings user_settings = dict(getattr(django_settings, _settings_key, {})) user_settings_keys = set(user_settings.keys()) # Check for required but missing settings missing = _required_s...
python
def settings(): """ Fetch the middleware settings. :return dict: settings """ # Get the user-provided settings user_settings = dict(getattr(django_settings, _settings_key, {})) user_settings_keys = set(user_settings.keys()) # Check for required but missing settings missing = _required_s...
[ "def", "settings", "(", ")", ":", "# Get the user-provided settings", "user_settings", "=", "dict", "(", "getattr", "(", "django_settings", ",", "_settings_key", ",", "{", "}", ")", ")", "user_settings_keys", "=", "set", "(", "user_settings", ".", "keys", "(", ...
Fetch the middleware settings. :return dict: settings
[ "Fetch", "the", "middleware", "settings", "." ]
train
https://github.com/Amsterdam/authorization_django/blob/71da52b38a7f5a16a2bde8f8ea97b3c11ccb1be1/authorization_django/config.py#L79-L102
selenol/selenol-python
selenol_python/services.py
SelenolClient.run
def run(self): """Run the service in infinitive loop processing requests.""" try: while True: message = self.connection.recv() result = self.on_message(message) if result: self.connection.send(result) except SelenolW...
python
def run(self): """Run the service in infinitive loop processing requests.""" try: while True: message = self.connection.recv() result = self.on_message(message) if result: self.connection.send(result) except SelenolW...
[ "def", "run", "(", "self", ")", ":", "try", ":", "while", "True", ":", "message", "=", "self", ".", "connection", ".", "recv", "(", ")", "result", "=", "self", ".", "on_message", "(", "message", ")", "if", "result", ":", "self", ".", "connection", ...
Run the service in infinitive loop processing requests.
[ "Run", "the", "service", "in", "infinitive", "loop", "processing", "requests", "." ]
train
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/services.py#L39-L49
selenol/selenol-python
selenol_python/services.py
SelenolService.on_message
def on_message(self, message): """Message from the backend has been received. :param message: Message string received. """ work_unit = SelenolMessage(message) request_id = work_unit.request_id if message['reason'] == ['selenol', 'request']: try: ...
python
def on_message(self, message): """Message from the backend has been received. :param message: Message string received. """ work_unit = SelenolMessage(message) request_id = work_unit.request_id if message['reason'] == ['selenol', 'request']: try: ...
[ "def", "on_message", "(", "self", ",", "message", ")", ":", "work_unit", "=", "SelenolMessage", "(", "message", ")", "request_id", "=", "work_unit", ".", "request_id", "if", "message", "[", "'reason'", "]", "==", "[", "'selenol'", ",", "'request'", "]", ":...
Message from the backend has been received. :param message: Message string received.
[ "Message", "from", "the", "backend", "has", "been", "received", "." ]
train
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/services.py#L115-L151
selenol/selenol-python
selenol_python/services.py
SelenolService.event
def event(self, request_id, trigger, event, message): """Create an event in the backend to be triggered given a circumstance. :param request_id: Request ID of a involved session. :param trigger: Circumstance that will trigger the event. :param event: Reason of the message that will be c...
python
def event(self, request_id, trigger, event, message): """Create an event in the backend to be triggered given a circumstance. :param request_id: Request ID of a involved session. :param trigger: Circumstance that will trigger the event. :param event: Reason of the message that will be c...
[ "def", "event", "(", "self", ",", "request_id", ",", "trigger", ",", "event", ",", "message", ")", ":", "self", ".", "connection", ".", "send", "(", "{", "'reason'", ":", "[", "'request'", ",", "'event'", "]", ",", "'request_id'", ":", "request_id", ",...
Create an event in the backend to be triggered given a circumstance. :param request_id: Request ID of a involved session. :param trigger: Circumstance that will trigger the event. :param event: Reason of the message that will be created. :param message: Content of the message that will ...
[ "Create", "an", "event", "in", "the", "backend", "to", "be", "triggered", "given", "a", "circumstance", "." ]
train
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/services.py#L172-L190
selenol/selenol-python
selenol_python/services.py
SelenolService.send
def send(self, event, message): """Send a message to the backend. :param reason: Reason of the message. :param message: Message content. """ self.connection.send({ 'reason': ['request', 'send'], 'content': { 'reason': event, ...
python
def send(self, event, message): """Send a message to the backend. :param reason: Reason of the message. :param message: Message content. """ self.connection.send({ 'reason': ['request', 'send'], 'content': { 'reason': event, ...
[ "def", "send", "(", "self", ",", "event", ",", "message", ")", ":", "self", ".", "connection", ".", "send", "(", "{", "'reason'", ":", "[", "'request'", ",", "'send'", "]", ",", "'content'", ":", "{", "'reason'", ":", "event", ",", "'request_id'", ":...
Send a message to the backend. :param reason: Reason of the message. :param message: Message content.
[ "Send", "a", "message", "to", "the", "backend", "." ]
train
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/services.py#L192-L206
Infinidat/infi.recipe.console_scripts
src/infi/recipe/console_scripts/__init__.py
_get_matching_dist_in_location
def _get_matching_dist_in_location(dist, location): """ Check if `locations` contain only the one intended dist. Return the dist with metadata in the new location. """ # Getting the dist from the environment causes the # distribution meta data to be read. Cloning isn't # good enough. im...
python
def _get_matching_dist_in_location(dist, location): """ Check if `locations` contain only the one intended dist. Return the dist with metadata in the new location. """ # Getting the dist from the environment causes the # distribution meta data to be read. Cloning isn't # good enough. im...
[ "def", "_get_matching_dist_in_location", "(", "dist", ",", "location", ")", ":", "# Getting the dist from the environment causes the", "# distribution meta data to be read. Cloning isn't", "# good enough.", "import", "pkg_resources", "env", "=", "pkg_resources", ".", "Environment"...
Check if `locations` contain only the one intended dist. Return the dist with metadata in the new location.
[ "Check", "if", "locations", "contain", "only", "the", "one", "intended", "dist", ".", "Return", "the", "dist", "with", "metadata", "in", "the", "new", "location", "." ]
train
https://github.com/Infinidat/infi.recipe.console_scripts/blob/7beab59537654ee475527dbbd59b0aa49348ebd3/src/infi/recipe/console_scripts/__init__.py#L98-L113
krukas/Trionyx
trionyx/trionyx/views/core.py
media_nginx_accel
def media_nginx_accel(request, path): """ location /protected/ { internal; root <complete path to project root dir>; } """ response = HttpResponse(status=200) response['Content-Type'] = '' response['X-Accel-Redirect'] = '/protected' + request.path return response
python
def media_nginx_accel(request, path): """ location /protected/ { internal; root <complete path to project root dir>; } """ response = HttpResponse(status=200) response['Content-Type'] = '' response['X-Accel-Redirect'] = '/protected' + request.path return response
[ "def", "media_nginx_accel", "(", "request", ",", "path", ")", ":", "response", "=", "HttpResponse", "(", "status", "=", "200", ")", "response", "[", "'Content-Type'", "]", "=", "''", "response", "[", "'X-Accel-Redirect'", "]", "=", "'/protected'", "+", "requ...
location /protected/ { internal; root <complete path to project root dir>; }
[ "location", "/", "protected", "/", "{", "internal", ";", "root", "<complete", "path", "to", "project", "root", "dir", ">", ";", "}" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L38-L49
krukas/Trionyx
trionyx/trionyx/views/core.py
ModelClassMixin.get_model_class
def get_model_class(self): """Get model class""" if getattr(self, 'model', None): return self.model elif getattr(self, 'object', None): return self.object.__class__ elif 'app' in self.kwargs and 'model' in self.kwargs: return apps.get_model(self.kwargs...
python
def get_model_class(self): """Get model class""" if getattr(self, 'model', None): return self.model elif getattr(self, 'object', None): return self.object.__class__ elif 'app' in self.kwargs and 'model' in self.kwargs: return apps.get_model(self.kwargs...
[ "def", "get_model_class", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'model'", ",", "None", ")", ":", "return", "self", ".", "model", "elif", "getattr", "(", "self", ",", "'object'", ",", "None", ")", ":", "return", "self", ".", "obje...
Get model class
[ "Get", "model", "class" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L55-L66
krukas/Trionyx
trionyx/trionyx/views/core.py
ModelClassMixin.get_model_config
def get_model_config(self): """Get Trionyx model config""" if not hasattr(self, '__config'): setattr(self, '__config', models_config.get_config(self.get_model_class())) return getattr(self, '__config', None)
python
def get_model_config(self): """Get Trionyx model config""" if not hasattr(self, '__config'): setattr(self, '__config', models_config.get_config(self.get_model_class())) return getattr(self, '__config', None)
[ "def", "get_model_config", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'__config'", ")", ":", "setattr", "(", "self", ",", "'__config'", ",", "models_config", ".", "get_config", "(", "self", ".", "get_model_class", "(", ")", ")", ")...
Get Trionyx model config
[ "Get", "Trionyx", "model", "config" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L68-L72
krukas/Trionyx
trionyx/trionyx/views/core.py
ModelPermission.dispatch
def dispatch(self, request, *args, **kwargs): """Validate if user can use view""" if False: # TODO do permission check based on Model raise PermissionDenied return super().dispatch(request, *args, **kwargs)
python
def dispatch(self, request, *args, **kwargs): """Validate if user can use view""" if False: # TODO do permission check based on Model raise PermissionDenied return super().dispatch(request, *args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "False", ":", "# TODO do permission check based on Model", "raise", "PermissionDenied", "return", "super", "(", ")", ".", "dispatch", "(", "request", "...
Validate if user can use view
[ "Validate", "if", "user", "can", "use", "view" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L78-L82
krukas/Trionyx
trionyx/trionyx/views/core.py
SessionValueMixin.get_and_save_value
def get_and_save_value(self, name, default=None): """Get value from request/session and save value to session""" if getattr(self, name, None): return getattr(self, name) value = self.get_session_value(name, default) value = self.request.POST.get(name, value) self.sav...
python
def get_and_save_value(self, name, default=None): """Get value from request/session and save value to session""" if getattr(self, name, None): return getattr(self, name) value = self.get_session_value(name, default) value = self.request.POST.get(name, value) self.sav...
[ "def", "get_and_save_value", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "if", "getattr", "(", "self", ",", "name", ",", "None", ")", ":", "return", "getattr", "(", "self", ",", "name", ")", "value", "=", "self", ".", "get_sessio...
Get value from request/session and save value to session
[ "Get", "value", "from", "request", "/", "session", "and", "save", "value", "to", "session" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L88-L96
krukas/Trionyx
trionyx/trionyx/views/core.py
SessionValueMixin.get_session_value
def get_session_value(self, name, default=None): """Get value from session""" session_name = 'list_{}_{}_{}'.format(self.kwargs.get('app'), self.kwargs.get('model'), name) return self.request.session.get(session_name, default)
python
def get_session_value(self, name, default=None): """Get value from session""" session_name = 'list_{}_{}_{}'.format(self.kwargs.get('app'), self.kwargs.get('model'), name) return self.request.session.get(session_name, default)
[ "def", "get_session_value", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "session_name", "=", "'list_{}_{}_{}'", ".", "format", "(", "self", ".", "kwargs", ".", "get", "(", "'app'", ")", ",", "self", ".", "kwargs", ".", "get", "(", ...
Get value from session
[ "Get", "value", "from", "session" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L98-L101
krukas/Trionyx
trionyx/trionyx/views/core.py
SessionValueMixin.save_value
def save_value(self, name, value): """Save value to session""" session_name = 'list_{}_{}_{}'.format(self.kwargs.get('app'), self.kwargs.get('model'), name) self.request.session[session_name] = value setattr(self, name, value) return value
python
def save_value(self, name, value): """Save value to session""" session_name = 'list_{}_{}_{}'.format(self.kwargs.get('app'), self.kwargs.get('model'), name) self.request.session[session_name] = value setattr(self, name, value) return value
[ "def", "save_value", "(", "self", ",", "name", ",", "value", ")", ":", "session_name", "=", "'list_{}_{}_{}'", ".", "format", "(", "self", ".", "kwargs", ".", "get", "(", "'app'", ")", ",", "self", ".", "kwargs", ".", "get", "(", "'model'", ")", ",",...
Save value to session
[ "Save", "value", "to", "session" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L103-L108
krukas/Trionyx
trionyx/trionyx/views/core.py
ListView.get_title
def get_title(self): """Get page title""" if self.title: return self.title return self.get_model_class()._meta.verbose_name_plural
python
def get_title(self): """Get page title""" if self.title: return self.title return self.get_model_class()._meta.verbose_name_plural
[ "def", "get_title", "(", "self", ")", ":", "if", "self", ".", "title", ":", "return", "self", ".", "title", "return", "self", ".", "get_model_class", "(", ")", ".", "_meta", ".", "verbose_name_plural" ]
Get page title
[ "Get", "page", "title" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L131-L135
krukas/Trionyx
trionyx/trionyx/views/core.py
ListView.get_ajax_url
def get_ajax_url(self): """Get ajax url""" if self.ajax_url: return self.ajax_url return reverse('trionyx:model-list-ajax', kwargs=self.kwargs)
python
def get_ajax_url(self): """Get ajax url""" if self.ajax_url: return self.ajax_url return reverse('trionyx:model-list-ajax', kwargs=self.kwargs)
[ "def", "get_ajax_url", "(", "self", ")", ":", "if", "self", ".", "ajax_url", ":", "return", "self", ".", "ajax_url", "return", "reverse", "(", "'trionyx:model-list-ajax'", ",", "kwargs", "=", "self", ".", "kwargs", ")" ]
Get ajax url
[ "Get", "ajax", "url" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L137-L141
krukas/Trionyx
trionyx/trionyx/views/core.py
ListView.get_download_url
def get_download_url(self): """Get ajax url""" if self.download_url: return self.download_url return reverse('trionyx:model-list-download', kwargs=self.kwargs)
python
def get_download_url(self): """Get ajax url""" if self.download_url: return self.download_url return reverse('trionyx:model-list-download', kwargs=self.kwargs)
[ "def", "get_download_url", "(", "self", ")", ":", "if", "self", ".", "download_url", ":", "return", "self", ".", "download_url", "return", "reverse", "(", "'trionyx:model-list-download'", ",", "kwargs", "=", "self", ".", "kwargs", ")" ]
Get ajax url
[ "Get", "ajax", "url" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L143-L147
krukas/Trionyx
trionyx/trionyx/views/core.py
ListView.get_context_data
def get_context_data(self, **kwargs): """Add context data to view""" context = super().get_context_data(**kwargs) context.update({ 'title': self.get_title(), 'ajax_url': self.get_ajax_url(), 'download_url': self.get_download_url(), 'create_url': se...
python
def get_context_data(self, **kwargs): """Add context data to view""" context = super().get_context_data(**kwargs) context.update({ 'title': self.get_title(), 'ajax_url': self.get_ajax_url(), 'download_url': self.get_download_url(), 'create_url': se...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'title'", ":", "self", ".", "get_title", "(", ")...
Add context data to view
[ "Add", "context", "data", "to", "view" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L153-L162
krukas/Trionyx
trionyx/trionyx/views/core.py
ModelListMixin.get_page
def get_page(self, paginator): """Get current page or page in session""" page = int(self.get_and_save_value('page', 1)) if page < 1: return self.save_value('page', 1) if page > paginator.num_pages: return self.save_value('page', paginator.num_pages) retur...
python
def get_page(self, paginator): """Get current page or page in session""" page = int(self.get_and_save_value('page', 1)) if page < 1: return self.save_value('page', 1) if page > paginator.num_pages: return self.save_value('page', paginator.num_pages) retur...
[ "def", "get_page", "(", "self", ",", "paginator", ")", ":", "page", "=", "int", "(", "self", ".", "get_and_save_value", "(", "'page'", ",", "1", ")", ")", "if", "page", "<", "1", ":", "return", "self", ".", "save_value", "(", "'page'", ",", "1", ")...
Get current page or page in session
[ "Get", "current", "page", "or", "page", "in", "session" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L168-L176
krukas/Trionyx
trionyx/trionyx/views/core.py
ModelListMixin.get_search
def get_search(self): """Get current search or search from session, reset page if search is changed""" old_search = self.get_session_value('search', '') search = self.get_and_save_value('search', '') if old_search != search: self.page = 1 self.get_session_value('p...
python
def get_search(self): """Get current search or search from session, reset page if search is changed""" old_search = self.get_session_value('search', '') search = self.get_and_save_value('search', '') if old_search != search: self.page = 1 self.get_session_value('p...
[ "def", "get_search", "(", "self", ")", ":", "old_search", "=", "self", ".", "get_session_value", "(", "'search'", ",", "''", ")", "search", "=", "self", ".", "get_and_save_value", "(", "'search'", ",", "''", ")", "if", "old_search", "!=", "search", ":", ...
Get current search or search from session, reset page if search is changed
[ "Get", "current", "search", "or", "search", "from", "session", "reset", "page", "if", "search", "is", "changed" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L186-L193
krukas/Trionyx
trionyx/trionyx/views/core.py
ModelListMixin.get_all_fields
def get_all_fields(self): """Get all aviable fields""" return { name: { 'name': name, 'label': field['label'], } for name, field in self.get_model_config().get_list_fields().items() }
python
def get_all_fields(self): """Get all aviable fields""" return { name: { 'name': name, 'label': field['label'], } for name, field in self.get_model_config().get_list_fields().items() }
[ "def", "get_all_fields", "(", "self", ")", ":", "return", "{", "name", ":", "{", "'name'", ":", "name", ",", "'label'", ":", "field", "[", "'label'", "]", ",", "}", "for", "name", ",", "field", "in", "self", ".", "get_model_config", "(", ")", ".", ...
Get all aviable fields
[ "Get", "all", "aviable", "fields" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L195-L203
krukas/Trionyx
trionyx/trionyx/views/core.py
ModelListMixin.get_current_fields
def get_current_fields(self): """Get current list to be used""" if hasattr(self, 'current_fields') and self.current_fields: return self.current_fields field_attribute = 'list_{}_{}_fields'.format(self.kwargs.get('app'), self.kwargs.get('model')) current_fields = self.request...
python
def get_current_fields(self): """Get current list to be used""" if hasattr(self, 'current_fields') and self.current_fields: return self.current_fields field_attribute = 'list_{}_{}_fields'.format(self.kwargs.get('app'), self.kwargs.get('model')) current_fields = self.request...
[ "def", "get_current_fields", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'current_fields'", ")", "and", "self", ".", "current_fields", ":", "return", "self", ".", "current_fields", "field_attribute", "=", "'list_{}_{}_fields'", ".", "format", "(",...
Get current list to be used
[ "Get", "current", "list", "to", "be", "used" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L205-L226
krukas/Trionyx
trionyx/trionyx/views/core.py
ModelListMixin.search_queryset
def search_queryset(self): """Get search query set""" queryset = self.get_model_class().objects.get_queryset() if self.get_model_config().list_select_related: queryset = queryset.select_related(*self.get_model_config().list_select_related) return watson.filter(queryset, sel...
python
def search_queryset(self): """Get search query set""" queryset = self.get_model_class().objects.get_queryset() if self.get_model_config().list_select_related: queryset = queryset.select_related(*self.get_model_config().list_select_related) return watson.filter(queryset, sel...
[ "def", "search_queryset", "(", "self", ")", ":", "queryset", "=", "self", ".", "get_model_class", "(", ")", ".", "objects", ".", "get_queryset", "(", ")", "if", "self", ".", "get_model_config", "(", ")", ".", "list_select_related", ":", "queryset", "=", "q...
Get search query set
[ "Get", "search", "query", "set" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L238-L245
krukas/Trionyx
trionyx/trionyx/views/core.py
ListJsendView.handle_request
def handle_request(self, request, *args, **kwargs): """Give back list items + config""" paginator = self.get_paginator() # Call search first, it will reset page if search is changed search = self.get_search() page = self.get_page(paginator) items = self.get_items(paginato...
python
def handle_request(self, request, *args, **kwargs): """Give back list items + config""" paginator = self.get_paginator() # Call search first, it will reset page if search is changed search = self.get_search() page = self.get_page(paginator) items = self.get_items(paginato...
[ "def", "handle_request", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "paginator", "=", "self", ".", "get_paginator", "(", ")", "# Call search first, it will reset page if search is changed", "search", "=", "self", ".", "get_...
Give back list items + config
[ "Give", "back", "list", "items", "+", "config" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L259-L276
krukas/Trionyx
trionyx/trionyx/views/core.py
ListJsendView.get_items
def get_items(self, paginator, current_page): """Get list items for current page""" fields = self.get_model_config().get_list_fields() page = paginator.page(current_page) items = [] for item in page: items.append({ 'id': item.id, 'url...
python
def get_items(self, paginator, current_page): """Get list items for current page""" fields = self.get_model_config().get_list_fields() page = paginator.page(current_page) items = [] for item in page: items.append({ 'id': item.id, 'url...
[ "def", "get_items", "(", "self", ",", "paginator", ",", "current_page", ")", ":", "fields", "=", "self", ".", "get_model_config", "(", ")", ".", "get_list_fields", "(", ")", "page", "=", "paginator", ".", "page", "(", "current_page", ")", "items", "=", "...
Get list items for current page
[ "Get", "list", "items", "for", "current", "page" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L278-L294
krukas/Trionyx
trionyx/trionyx/views/core.py
ListExportView.items
def items(self): """Get all list items""" query = self.get_queryset() fields = self.get_model_config().get_list_fields() for item in query.iterator(): row = OrderedDict() for field_name in self.get_current_fields(): field = fields.get(field_name) ...
python
def items(self): """Get all list items""" query = self.get_queryset() fields = self.get_model_config().get_list_fields() for item in query.iterator(): row = OrderedDict() for field_name in self.get_current_fields(): field = fields.get(field_name) ...
[ "def", "items", "(", "self", ")", ":", "query", "=", "self", ".", "get_queryset", "(", ")", "fields", "=", "self", ".", "get_model_config", "(", ")", ".", "get_list_fields", "(", ")", "for", "item", "in", "query", ".", "iterator", "(", ")", ":", "row...
Get all list items
[ "Get", "all", "list", "items" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L304-L320
krukas/Trionyx
trionyx/trionyx/views/core.py
ListExportView.csv_response
def csv_response(self): """Get csv response""" def stream(): """Create data stream generator""" stream_file = io.StringIO() csvwriter = csv.writer(stream_file, delimiter=',', quotechar='"') csvwriter.writerow(self.get_current_fields()) for in...
python
def csv_response(self): """Get csv response""" def stream(): """Create data stream generator""" stream_file = io.StringIO() csvwriter = csv.writer(stream_file, delimiter=',', quotechar='"') csvwriter.writerow(self.get_current_fields()) for in...
[ "def", "csv_response", "(", "self", ")", ":", "def", "stream", "(", ")", ":", "\"\"\"Create data stream generator\"\"\"", "stream_file", "=", "io", ".", "StringIO", "(", ")", "csvwriter", "=", "csv", ".", "writer", "(", "stream_file", ",", "delimiter", "=", ...
Get csv response
[ "Get", "csv", "response" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L322-L341
krukas/Trionyx
trionyx/trionyx/views/core.py
DetailTabView.get_queryset
def get_queryset(self): """Get queryset based on url params(<app>, <mode>) if model is not set on class""" if self.queryset is None and not self.model: try: ModelClass = apps.get_model(self.kwargs.get('app'), self.kwargs.get('model')) return ModelClass._defaul...
python
def get_queryset(self): """Get queryset based on url params(<app>, <mode>) if model is not set on class""" if self.queryset is None and not self.model: try: ModelClass = apps.get_model(self.kwargs.get('app'), self.kwargs.get('model')) return ModelClass._defaul...
[ "def", "get_queryset", "(", "self", ")", ":", "if", "self", ".", "queryset", "is", "None", "and", "not", "self", ".", "model", ":", "try", ":", "ModelClass", "=", "apps", ".", "get_model", "(", "self", ".", "kwargs", ".", "get", "(", "'app'", ")", ...
Get queryset based on url params(<app>, <mode>) if model is not set on class
[ "Get", "queryset", "based", "on", "url", "params", "(", "<app", ">", "<mode", ">", ")", "if", "model", "is", "not", "set", "on", "class" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L363-L371
krukas/Trionyx
trionyx/trionyx/views/core.py
DetailTabView.get_context_data
def get_context_data(self, **kwargs): """Add context data to view""" context = super().get_context_data(**kwargs) tabs = self.get_active_tabs() context.update({ 'page_detail_tabs': tabs, 'active_tab': tabs[0].code if tabs else '', 'app_label': self.get...
python
def get_context_data(self, **kwargs): """Add context data to view""" context = super().get_context_data(**kwargs) tabs = self.get_active_tabs() context.update({ 'page_detail_tabs': tabs, 'active_tab': tabs[0].code if tabs else '', 'app_label': self.get...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "tabs", "=", "self", ".", "get_active_tabs", "(", ")", "context", ".", "update", "(", ...
Add context data to view
[ "Add", "context", "data", "to", "view" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L373-L389
krukas/Trionyx
trionyx/trionyx/views/core.py
DetailTabView.get_delete_url
def get_delete_url(self): """Get model object delete url""" return reverse('trionyx:model-delete', kwargs={ 'app': self.get_app_label(), 'model': self.get_model_name(), 'pk': self.object.id })
python
def get_delete_url(self): """Get model object delete url""" return reverse('trionyx:model-delete', kwargs={ 'app': self.get_app_label(), 'model': self.get_model_name(), 'pk': self.object.id })
[ "def", "get_delete_url", "(", "self", ")", ":", "return", "reverse", "(", "'trionyx:model-delete'", ",", "kwargs", "=", "{", "'app'", ":", "self", ".", "get_app_label", "(", ")", ",", "'model'", ":", "self", ".", "get_model_name", "(", ")", ",", "'pk'", ...
Get model object delete url
[ "Get", "model", "object", "delete", "url" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L398-L404
krukas/Trionyx
trionyx/trionyx/views/core.py
DetailTabView.get_edit_url
def get_edit_url(self): """Get model object edit url""" return reverse('trionyx:model-edit', kwargs={ 'app': self.get_app_label(), 'model': self.get_model_name(), 'pk': self.object.id })
python
def get_edit_url(self): """Get model object edit url""" return reverse('trionyx:model-edit', kwargs={ 'app': self.get_app_label(), 'model': self.get_model_name(), 'pk': self.object.id })
[ "def", "get_edit_url", "(", "self", ")", ":", "return", "reverse", "(", "'trionyx:model-edit'", ",", "kwargs", "=", "{", "'app'", ":", "self", ".", "get_app_label", "(", ")", ",", "'model'", ":", "self", ".", "get_model_name", "(", ")", ",", "'pk'", ":",...
Get model object edit url
[ "Get", "model", "object", "edit", "url" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L406-L412
krukas/Trionyx
trionyx/trionyx/views/core.py
DetailTabView.get_model_alias
def get_model_alias(self): """Get model alias""" if self.model_alias: return self.model_alias return '{}.{}'.format(self.get_app_label(), self.get_model_name())
python
def get_model_alias(self): """Get model alias""" if self.model_alias: return self.model_alias return '{}.{}'.format(self.get_app_label(), self.get_model_name())
[ "def", "get_model_alias", "(", "self", ")", ":", "if", "self", ".", "model_alias", ":", "return", "self", ".", "model_alias", "return", "'{}.{}'", ".", "format", "(", "self", ".", "get_app_label", "(", ")", ",", "self", ".", "get_model_name", "(", ")", "...
Get model alias
[ "Get", "model", "alias" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L414-L418
krukas/Trionyx
trionyx/trionyx/views/core.py
DetailTabJsendView.handle_request
def handle_request(self, request, app, model, pk): """Render and return tab""" ModelClass = self.get_model_class() object = ModelClass.objects.get(id=pk) tab_code = request.GET.get('tab') model_alias = request.GET.get('model_alias') model_alias = model_alias if model_ali...
python
def handle_request(self, request, app, model, pk): """Render and return tab""" ModelClass = self.get_model_class() object = ModelClass.objects.get(id=pk) tab_code = request.GET.get('tab') model_alias = request.GET.get('model_alias') model_alias = model_alias if model_ali...
[ "def", "handle_request", "(", "self", ",", "request", ",", "app", ",", "model", ",", "pk", ")", ":", "ModelClass", "=", "self", ".", "get_model_class", "(", ")", "object", "=", "ModelClass", ".", "objects", ".", "get", "(", "id", "=", "pk", ")", "tab...
Render and return tab
[ "Render", "and", "return", "tab" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L442-L455
krukas/Trionyx
trionyx/trionyx/views/core.py
UpdateView.get_queryset
def get_queryset(self): """Get queryset based on url params(<app>, <mode>) if model is not set on class""" if self.queryset is None and not self.model: try: return self.get_model_class()._default_manager.all() except LookupError: raise Http404() ...
python
def get_queryset(self): """Get queryset based on url params(<app>, <mode>) if model is not set on class""" if self.queryset is None and not self.model: try: return self.get_model_class()._default_manager.all() except LookupError: raise Http404() ...
[ "def", "get_queryset", "(", "self", ")", ":", "if", "self", ".", "queryset", "is", "None", "and", "not", "self", ".", "model", ":", "try", ":", "return", "self", ".", "get_model_class", "(", ")", ".", "_default_manager", ".", "all", "(", ")", "except",...
Get queryset based on url params(<app>, <mode>) if model is not set on class
[ "Get", "queryset", "based", "on", "url", "params", "(", "<app", ">", "<mode", ">", ")", "if", "model", "is", "not", "set", "on", "class" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L475-L482
krukas/Trionyx
trionyx/trionyx/views/core.py
UpdateView.get_form
def get_form(self, form_class=None): """Get form for model""" form = super().get_form(form_class) if not getattr(form, 'helper', None): form.helper = FormHelper() form.helper.form_tag = False else: form.helper.form_tag = False return form
python
def get_form(self, form_class=None): """Get form for model""" form = super().get_form(form_class) if not getattr(form, 'helper', None): form.helper = FormHelper() form.helper.form_tag = False else: form.helper.form_tag = False return form
[ "def", "get_form", "(", "self", ",", "form_class", "=", "None", ")", ":", "form", "=", "super", "(", ")", ".", "get_form", "(", "form_class", ")", "if", "not", "getattr", "(", "form", ",", "'helper'", ",", "None", ")", ":", "form", ".", "helper", "...
Get form for model
[ "Get", "form", "for", "model" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L490-L499
krukas/Trionyx
trionyx/trionyx/views/core.py
CreateView.get_cancel_url
def get_cancel_url(self): """Get cancel url""" if self.cancel_url: return self.cancel_url ModelClass = self.get_model_class() return reverse('trionyx:model-list', kwargs={ 'app': ModelClass._meta.app_label, 'model': ModelClass._meta.model_name, ...
python
def get_cancel_url(self): """Get cancel url""" if self.cancel_url: return self.cancel_url ModelClass = self.get_model_class() return reverse('trionyx:model-list', kwargs={ 'app': ModelClass._meta.app_label, 'model': ModelClass._meta.model_name, ...
[ "def", "get_cancel_url", "(", "self", ")", ":", "if", "self", ".", "cancel_url", ":", "return", "self", ".", "cancel_url", "ModelClass", "=", "self", ".", "get_model_class", "(", ")", "return", "reverse", "(", "'trionyx:model-list'", ",", "kwargs", "=", "{",...
Get cancel url
[ "Get", "cancel", "url" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L559-L568
krukas/Trionyx
trionyx/trionyx/views/core.py
CreateView.get_context_data
def get_context_data(self, **kwargs): """Add context data to view""" context = super().get_context_data(**kwargs) context.update({ 'title': self.title, 'submit_value': self.submit_value, 'cancel_url': self.get_cancel_url(), 'model_verbose_name': se...
python
def get_context_data(self, **kwargs): """Add context data to view""" context = super().get_context_data(**kwargs) context.update({ 'title': self.title, 'submit_value': self.submit_value, 'cancel_url': self.get_cancel_url(), 'model_verbose_name': se...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'title'", ":", "self", ".", "title", ",", "'subm...
Add context data to view
[ "Add", "context", "data", "to", "view" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L570-L580
krukas/Trionyx
trionyx/trionyx/views/core.py
CreateView.form_valid
def form_valid(self, form): """Add success message""" response = super().form_valid(form) messages.success(self.request, "Successfully created ({})".format(self.object)) return response
python
def form_valid(self, form): """Add success message""" response = super().form_valid(form) messages.success(self.request, "Successfully created ({})".format(self.object)) return response
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "response", "=", "super", "(", ")", ".", "form_valid", "(", "form", ")", "messages", ".", "success", "(", "self", ".", "request", ",", "\"Successfully created ({})\"", ".", "format", "(", "self", "...
Add success message
[ "Add", "success", "message" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L582-L586
krukas/Trionyx
trionyx/trionyx/views/core.py
DeleteView.get_context_data
def get_context_data(self, **kwargs): """Add context data to view""" context = super().get_context_data(**kwargs) context.update({ 'title': self.title, 'submit_value': self.submit_value, 'cancel_url': self.cancel_url }) return context
python
def get_context_data(self, **kwargs): """Add context data to view""" context = super().get_context_data(**kwargs) context.update({ 'title': self.title, 'submit_value': self.submit_value, 'cancel_url': self.cancel_url }) return context
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'title'", ":", "self", ".", "title", ",", "'subm...
Add context data to view
[ "Add", "context", "data", "to", "view" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L612-L620
krukas/Trionyx
trionyx/trionyx/views/core.py
DeleteView.get_success_url
def get_success_url(self): """Get success url""" messages.success(self.request, "Successfully deleted ({})".format(self.object)) if self.success_url: return reverse(self.success_url) if 'app' in self.kwargs and 'model' in self.kwargs: return reverse('trionyx:mode...
python
def get_success_url(self): """Get success url""" messages.success(self.request, "Successfully deleted ({})".format(self.object)) if self.success_url: return reverse(self.success_url) if 'app' in self.kwargs and 'model' in self.kwargs: return reverse('trionyx:mode...
[ "def", "get_success_url", "(", "self", ")", ":", "messages", ".", "success", "(", "self", ".", "request", ",", "\"Successfully deleted ({})\"", ".", "format", "(", "self", ".", "object", ")", ")", "if", "self", ".", "success_url", ":", "return", "reverse", ...
Get success url
[ "Get", "success", "url" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L622-L634
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.get
def get(self, request, *args, **kwargs): """Handle get request""" try: kwargs = self.load_object(kwargs) except Exception as e: return self.render_te_response({ 'title': str(e), }) if not self.has_permission(request): retur...
python
def get(self, request, *args, **kwargs): """Handle get request""" try: kwargs = self.load_object(kwargs) except Exception as e: return self.render_te_response({ 'title': str(e), }) if not self.has_permission(request): retur...
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "kwargs", "=", "self", ".", "load_object", "(", "kwargs", ")", "except", "Exception", "as", "e", ":", "return", "self", ".", "render_te_respon...
Handle get request
[ "Handle", "get", "request" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L682-L695
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.post
def post(self, request, *args, **kwargs): """Handle post request""" try: kwargs = self.load_object(kwargs) except Exception as e: return self.render_te_response({ 'title': str(e), }) if not self.has_permission(request): ret...
python
def post(self, request, *args, **kwargs): """Handle post request""" try: kwargs = self.load_object(kwargs) except Exception as e: return self.render_te_response({ 'title': str(e), }) if not self.has_permission(request): ret...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "kwargs", "=", "self", ".", "load_object", "(", "kwargs", ")", "except", "Exception", "as", "e", ":", "return", "self", ".", "render_te_respo...
Handle post request
[ "Handle", "post", "request" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L697-L710
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.load_object
def load_object(self, kwargs): """Load object and model config and remove pk from kwargs""" self.object = None self.config = None self.model = self.get_model_class() kwargs.pop('app', None) kwargs.pop('model', None) if self.model and kwargs.get('pk', False): ...
python
def load_object(self, kwargs): """Load object and model config and remove pk from kwargs""" self.object = None self.config = None self.model = self.get_model_class() kwargs.pop('app', None) kwargs.pop('model', None) if self.model and kwargs.get('pk', False): ...
[ "def", "load_object", "(", "self", ",", "kwargs", ")", ":", "self", ".", "object", "=", "None", "self", ".", "config", "=", "None", "self", ".", "model", "=", "self", ".", "get_model_class", "(", ")", "kwargs", ".", "pop", "(", "'app'", ",", "None", ...
Load object and model config and remove pk from kwargs
[ "Load", "object", "and", "model", "config", "and", "remove", "pk", "from", "kwargs" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L712-L727
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.has_permission
def has_permission(self, request): """Check if user has permission""" if not self.object and not self.permission: return True if not self.permission: return request.user.has_perm('{}_{}'.format( self.model_permission, self.object.__class__...
python
def has_permission(self, request): """Check if user has permission""" if not self.object and not self.permission: return True if not self.permission: return request.user.has_perm('{}_{}'.format( self.model_permission, self.object.__class__...
[ "def", "has_permission", "(", "self", ",", "request", ")", ":", "if", "not", "self", ".", "object", "and", "not", "self", ".", "permission", ":", "return", "True", "if", "not", "self", ".", "permission", ":", "return", "request", ".", "user", ".", "has...
Check if user has permission
[ "Check", "if", "user", "has", "permission" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L729-L740
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.render_to_string
def render_to_string(self, template_file, context): """Render given template to string and add object to context""" context = context if context else {} if self.object: context['object'] = self.object context[self.object.__class__.__name__.lower()] = self.object r...
python
def render_to_string(self, template_file, context): """Render given template to string and add object to context""" context = context if context else {} if self.object: context['object'] = self.object context[self.object.__class__.__name__.lower()] = self.object r...
[ "def", "render_to_string", "(", "self", ",", "template_file", ",", "context", ")", ":", "context", "=", "context", "if", "context", "else", "{", "}", "if", "self", ".", "object", ":", "context", "[", "'object'", "]", "=", "self", ".", "object", "context"...
Render given template to string and add object to context
[ "Render", "given", "template", "to", "string", "and", "add", "object", "to", "context" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L742-L748
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.render_te_response
def render_te_response(self, data): """Render data to JsonResponse""" if 'submit_label' in data and 'url' not in data: data['url'] = self.request.get_full_path() return JsonResponse(data)
python
def render_te_response(self, data): """Render data to JsonResponse""" if 'submit_label' in data and 'url' not in data: data['url'] = self.request.get_full_path() return JsonResponse(data)
[ "def", "render_te_response", "(", "self", ",", "data", ")", ":", "if", "'submit_label'", "in", "data", "and", "'url'", "not", "in", "data", ":", "data", "[", "'url'", "]", "=", "self", ".", "request", ".", "get_full_path", "(", ")", "return", "JsonRespon...
Render data to JsonResponse
[ "Render", "data", "to", "JsonResponse" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L774-L779
krukas/Trionyx
trionyx/trionyx/views/core.py
UpdateDialog.display_dialog
def display_dialog(self, *args, **kwargs): """Display form and success message when set""" form = kwargs.pop('form_instance', None) success_message = kwargs.pop('success_message', None) if not form: form = self.get_form_class()(initial=kwargs, instance=self.object) ...
python
def display_dialog(self, *args, **kwargs): """Display form and success message when set""" form = kwargs.pop('form_instance', None) success_message = kwargs.pop('success_message', None) if not form: form = self.get_form_class()(initial=kwargs, instance=self.object) ...
[ "def", "display_dialog", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "form", "=", "kwargs", ".", "pop", "(", "'form_instance'", ",", "None", ")", "success_message", "=", "kwargs", ".", "pop", "(", "'success_message'", ",", "None", ...
Display form and success message when set
[ "Display", "form", "and", "success", "message", "when", "set" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L802-L825
krukas/Trionyx
trionyx/trionyx/views/core.py
UpdateDialog.handle_dialog
def handle_dialog(self, *args, **kwargs): """Handle form and save and set success message on valid form""" form = self.get_form_class()(self.request.POST, initial=kwargs, instance=self.object) success_message = None if form.is_valid(): obj = form.save() success_m...
python
def handle_dialog(self, *args, **kwargs): """Handle form and save and set success message on valid form""" form = self.get_form_class()(self.request.POST, initial=kwargs, instance=self.object) success_message = None if form.is_valid(): obj = form.save() success_m...
[ "def", "handle_dialog", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "form", "=", "self", ".", "get_form_class", "(", ")", "(", "self", ".", "request", ".", "POST", ",", "initial", "=", "kwargs", ",", "instance", "=", "self", "...
Handle form and save and set success message on valid form
[ "Handle", "form", "and", "save", "and", "set", "success", "message", "on", "valid", "form" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L827-L838
briancappello/flask-sqlalchemy-bundle
flask_sqlalchemy_bundle/sqla/relationships.py
foreign_key
def foreign_key(model_or_table_name_or_column_name: Union[str, Type[Model]], model_or_table_name: Optional[Union[str, Type[Model]]] = None, *, fk_col: str = 'id', primary_key: bool = False, **kwargs, ) -> Column: """Help...
python
def foreign_key(model_or_table_name_or_column_name: Union[str, Type[Model]], model_or_table_name: Optional[Union[str, Type[Model]]] = None, *, fk_col: str = 'id', primary_key: bool = False, **kwargs, ) -> Column: """Help...
[ "def", "foreign_key", "(", "model_or_table_name_or_column_name", ":", "Union", "[", "str", ",", "Type", "[", "Model", "]", "]", ",", "model_or_table_name", ":", "Optional", "[", "Union", "[", "str", ",", "Type", "[", "Model", "]", "]", "]", "=", "None", ...
Helper method to add a foreign key column to a model. For example:: class Post(Model): category_id = foreign_key('Category') category = relationship('Category', back_populates='posts') Is equivalent to:: class Post(Model): category_id = Column(BigInteger, ...
[ "Helper", "method", "to", "add", "a", "foreign", "key", "column", "to", "a", "model", "." ]
train
https://github.com/briancappello/flask-sqlalchemy-bundle/blob/8150896787907ef0001839b5a6ef303edccb9b6c/flask_sqlalchemy_bundle/sqla/relationships.py#L19-L73
neshkatrapati/pypresenter
pypresenter/pypresenter.py
SlideDeck.get_term_size
def get_term_size(): '''Gets the size of your terminal. May not work everywhere. YMMV.''' rows, columns = os.popen('stty size', 'r').read().split() return int(rows), int(columns)
python
def get_term_size(): '''Gets the size of your terminal. May not work everywhere. YMMV.''' rows, columns = os.popen('stty size', 'r').read().split() return int(rows), int(columns)
[ "def", "get_term_size", "(", ")", ":", "rows", ",", "columns", "=", "os", ".", "popen", "(", "'stty size'", ",", "'r'", ")", ".", "read", "(", ")", ".", "split", "(", ")", "return", "int", "(", "rows", ")", ",", "int", "(", "columns", ")" ]
Gets the size of your terminal. May not work everywhere. YMMV.
[ "Gets", "the", "size", "of", "your", "terminal", ".", "May", "not", "work", "everywhere", ".", "YMMV", "." ]
train
https://github.com/neshkatrapati/pypresenter/blob/bc4cccb17523972dd60de49a34e0ed050b788ad4/pypresenter/pypresenter.py#L280-L283
hobson/pug-dj
pug/dj/crawlnmine/management/__init__.py
find_commands
def find_commands(management_dir): """ Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined. """ command_dir = os.path.join(management_dir, 'commands') try: return [f[:-3] for f in os.lis...
python
def find_commands(management_dir): """ Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined. """ command_dir = os.path.join(management_dir, 'commands') try: return [f[:-3] for f in os.lis...
[ "def", "find_commands", "(", "management_dir", ")", ":", "command_dir", "=", "os", ".", "path", ".", "join", "(", "management_dir", ",", "'commands'", ")", "try", ":", "return", "[", "f", "[", ":", "-", "3", "]", "for", "f", "in", "os", ".", "listdir...
Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined.
[ "Given", "a", "path", "to", "a", "management", "directory", "returns", "a", "list", "of", "all", "the", "command", "names", "that", "are", "available", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/management/__init__.py#L23-L35
hobson/pug-dj
pug/dj/crawlnmine/management/__init__.py
get_commands
def get_commands(): """ Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core comman...
python
def get_commands(): """ Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core comman...
[ "def", "get_commands", "(", ")", ":", "commands", "=", "dict", "(", "(", "name", ",", "'pug.crawlnmine'", ")", "for", "name", "in", "find_commands", "(", "__path__", "[", "0", "]", ")", ")", "if", "not", "settings", ".", "configured", ":", "return", "c...
Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core commands are always included. If a set...
[ "Returns", "a", "dictionary", "mapping", "command", "names", "to", "their", "callback", "applications", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/management/__init__.py#L49-L80
hobson/pug-dj
pug/dj/crawlnmine/management/__init__.py
call_command
def call_command(name, *args, **options): """ Calls the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. Some examples: call_command('syncdb') call_command('shell', plain=True) call_command('sqlall', 'm...
python
def call_command(name, *args, **options): """ Calls the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. Some examples: call_command('syncdb') call_command('shell', plain=True) call_command('sqlall', 'm...
[ "def", "call_command", "(", "name", ",", "*", "args", ",", "*", "*", "options", ")", ":", "# Load the command object.", "try", ":", "app_name", "=", "get_commands", "(", ")", "[", "name", "]", "except", "KeyError", ":", "raise", "CommandError", "(", "\"Unk...
Calls the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. Some examples: call_command('syncdb') call_command('shell', plain=True) call_command('sqlall', 'myapp')
[ "Calls", "the", "given", "command", "with", "the", "given", "options", "and", "args", "/", "kwargs", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/management/__init__.py#L83-L116
hobson/pug-dj
pug/dj/crawlnmine/management/__init__.py
ManagementUtility.main_help_text
def main_help_text(self, commands_only=False): """ Returns the script's main help text, as a string. """ if commands_only: usage = sorted(get_commands().keys()) else: usage = [ "", "Type '%s help <subcommand>' for help on a ...
python
def main_help_text(self, commands_only=False): """ Returns the script's main help text, as a string. """ if commands_only: usage = sorted(get_commands().keys()) else: usage = [ "", "Type '%s help <subcommand>' for help on a ...
[ "def", "main_help_text", "(", "self", ",", "commands_only", "=", "False", ")", ":", "if", "commands_only", ":", "usage", "=", "sorted", "(", "get_commands", "(", ")", ".", "keys", "(", ")", ")", "else", ":", "usage", "=", "[", "\"\"", ",", "\"Type '%s ...
Returns the script's main help text, as a string.
[ "Returns", "the", "script", "s", "main", "help", "text", "as", "a", "string", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/management/__init__.py#L131-L164
hobson/pug-dj
pug/dj/crawlnmine/management/__init__.py
ManagementUtility.fetch_command
def fetch_command(self, subcommand): """ Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "jira.py") if it can't be found. """ # Get commands outside of try block to prevent swallowing exceptions ...
python
def fetch_command(self, subcommand): """ Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "jira.py") if it can't be found. """ # Get commands outside of try block to prevent swallowing exceptions ...
[ "def", "fetch_command", "(", "self", ",", "subcommand", ")", ":", "# Get commands outside of try block to prevent swallowing exceptions", "commands", "=", "get_commands", "(", ")", "try", ":", "app_name", "=", "commands", "[", "subcommand", "]", "except", "KeyError", ...
Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "jira.py") if it can't be found.
[ "Tries", "to", "fetch", "the", "given", "subcommand", "printing", "a", "message", "with", "the", "appropriate", "command", "called", "from", "the", "command", "line", "(", "usually", "jira", ".", "py", ")", "if", "it", "can", "t", "be", "found", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/management/__init__.py#L166-L187
hobson/pug-dj
pug/dj/crawlnmine/management/__init__.py
ManagementUtility.autocomplete
def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BA...
python
def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BA...
[ "def", "autocomplete", "(", "self", ")", ":", "# Don't complete if user hasn't sourced bash_completion file.", "if", "'DJANGO_AUTO_COMPLETE'", "not", "in", "os", ".", "environ", ":", "return", "cwords", "=", "os", ".", "environ", "[", "'COMP_WORDS'", "]", ".", "spli...
Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used to...
[ "Output", "completion", "suggestions", "for", "BASH", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/management/__init__.py#L189-L267
hobson/pug-dj
pug/dj/crawlnmine/management/__init__.py
ManagementUtility.execute
def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display...
python
def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display...
[ "def", "execute", "(", "self", ")", ":", "try", ":", "subcommand", "=", "self", ".", "argv", "[", "1", "]", "except", "IndexError", ":", "subcommand", "=", "'help'", "# Display help if no arguments were given.", "# Preprocess options to extract --settings and --pythonpa...
Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it.
[ "Given", "the", "command", "-", "line", "arguments", "this", "figures", "out", "which", "subcommand", "is", "being", "run", "creates", "a", "parser", "appropriate", "to", "that", "command", "and", "runs", "it", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/management/__init__.py#L269-L325
csaez/wishlib
wishlib/ma/qt.py
show_qt
def show_qt(qt_class, modal=False, onshow_event=None, force_style=False): """ Shows and raise a pyqt window ensuring it's not duplicated (if it's duplicated then raise the old one). qt_class argument should be a class/subclass of QMainWindow, QDialog or any top-level widget. onshow_event provide...
python
def show_qt(qt_class, modal=False, onshow_event=None, force_style=False): """ Shows and raise a pyqt window ensuring it's not duplicated (if it's duplicated then raise the old one). qt_class argument should be a class/subclass of QMainWindow, QDialog or any top-level widget. onshow_event provide...
[ "def", "show_qt", "(", "qt_class", ",", "modal", "=", "False", ",", "onshow_event", "=", "None", ",", "force_style", "=", "False", ")", ":", "dialog", "=", "None", "window", "=", "anchor", "(", ")", "# look for a previous instance", "for", "d", "in", "wind...
Shows and raise a pyqt window ensuring it's not duplicated (if it's duplicated then raise the old one). qt_class argument should be a class/subclass of QMainWindow, QDialog or any top-level widget. onshow_event provides a way to pass a function to execute before the window is showed on screen, it sh...
[ "Shows", "and", "raise", "a", "pyqt", "window", "ensuring", "it", "s", "not", "duplicated", "(", "if", "it", "s", "duplicated", "then", "raise", "the", "old", "one", ")", ".", "qt_class", "argument", "should", "be", "a", "class", "/", "subclass", "of", ...
train
https://github.com/csaez/wishlib/blob/c212fa7875006a332a4cefbf69885ced9647bc2f/wishlib/ma/qt.py#L36-L71
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscbitcoinfuncs.py
genkeyhex
def genkeyhex(): ''' Generate new random Bitcoin private key, using os.urandom and double-sha256. Hex format. ''' while True: key = hash256( hexlify(os.urandom(40) + str(datetime.datetime.now()) .encode("utf-8"))) # 40 byt...
python
def genkeyhex(): ''' Generate new random Bitcoin private key, using os.urandom and double-sha256. Hex format. ''' while True: key = hash256( hexlify(os.urandom(40) + str(datetime.datetime.now()) .encode("utf-8"))) # 40 byt...
[ "def", "genkeyhex", "(", ")", ":", "while", "True", ":", "key", "=", "hash256", "(", "hexlify", "(", "os", ".", "urandom", "(", "40", ")", "+", "str", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ")", ".", "encode", "(", "\"utf-8\"", "...
Generate new random Bitcoin private key, using os.urandom and double-sha256. Hex format.
[ "Generate", "new", "random", "Bitcoin", "private", "key", "using", "os", ".", "urandom", "and", "double", "-", "sha256", ".", "Hex", "format", "." ]
train
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscbitcoinfuncs.py#L38-L56
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscbitcoinfuncs.py
genkey
def genkey(outcompressed=True,prefix='80'): ''' Generate new random Bitcoin private key, using os.urandom and double-sha256. ''' key = prefix + genkeyhex() if outcompressed: key = key + '01' return b58e(key)
python
def genkey(outcompressed=True,prefix='80'): ''' Generate new random Bitcoin private key, using os.urandom and double-sha256. ''' key = prefix + genkeyhex() if outcompressed: key = key + '01' return b58e(key)
[ "def", "genkey", "(", "outcompressed", "=", "True", ",", "prefix", "=", "'80'", ")", ":", "key", "=", "prefix", "+", "genkeyhex", "(", ")", "if", "outcompressed", ":", "key", "=", "key", "+", "'01'", "return", "b58e", "(", "key", ")" ]
Generate new random Bitcoin private key, using os.urandom and double-sha256.
[ "Generate", "new", "random", "Bitcoin", "private", "key", "using", "os", ".", "urandom", "and", "double", "-", "sha256", "." ]
train
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscbitcoinfuncs.py#L59-L68
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscbitcoinfuncs.py
getandstrip_varintdata
def getandstrip_varintdata(data): ''' Takes a hex string that begins with varint data, and has extra at the end, and gets the varint integer, strips the varint bytes, and returns the integer and the remaining data. So rather than having to manually read the varint prefix, count, and strip, you can ...
python
def getandstrip_varintdata(data): ''' Takes a hex string that begins with varint data, and has extra at the end, and gets the varint integer, strips the varint bytes, and returns the integer and the remaining data. So rather than having to manually read the varint prefix, count, and strip, you can ...
[ "def", "getandstrip_varintdata", "(", "data", ")", ":", "data", "=", "strlify", "(", "data", ")", "numbytes", "=", "numvarintbytes", "(", "data", "[", ":", "2", "]", ")", "varint", "=", "data", "[", ":", "2", "*", "numbytes", "]", "data", "=", "data"...
Takes a hex string that begins with varint data, and has extra at the end, and gets the varint integer, strips the varint bytes, and returns the integer and the remaining data. So rather than having to manually read the varint prefix, count, and strip, you can do it in one function. This function will...
[ "Takes", "a", "hex", "string", "that", "begins", "with", "varint", "data", "and", "has", "extra", "at", "the", "end", "and", "gets", "the", "varint", "integer", "strips", "the", "varint", "bytes", "and", "returns", "the", "integer", "and", "the", "remainin...
train
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscbitcoinfuncs.py#L147-L187
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscbitcoinfuncs.py
inttoDER
def inttoDER(a): ''' Format an int/long to DER hex format ''' o = dechex(a,1) if int(o[:2],16) > 127: o = '00' + o olen = dechex(len(o)//2,1) return '02' + olen + o
python
def inttoDER(a): ''' Format an int/long to DER hex format ''' o = dechex(a,1) if int(o[:2],16) > 127: o = '00' + o olen = dechex(len(o)//2,1) return '02' + olen + o
[ "def", "inttoDER", "(", "a", ")", ":", "o", "=", "dechex", "(", "a", ",", "1", ")", "if", "int", "(", "o", "[", ":", "2", "]", ",", "16", ")", ">", "127", ":", "o", "=", "'00'", "+", "o", "olen", "=", "dechex", "(", "len", "(", "o", ")"...
Format an int/long to DER hex format
[ "Format", "an", "int", "/", "long", "to", "DER", "hex", "format" ]
train
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscbitcoinfuncs.py#L190-L199
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscbitcoinfuncs.py
inttoLEB128
def inttoLEB128(intinput): ''' Convert int/long to unsigned LEB128 format hex ''' binstr = str(bin(intinput)) \ .lstrip("0b").replace("b","").replace("L","") \ .replace("'","").replace('"',"") if len(binstr) % 7: binstr = binstr.zfill(len(binstr) + 7 - (len(binstr)...
python
def inttoLEB128(intinput): ''' Convert int/long to unsigned LEB128 format hex ''' binstr = str(bin(intinput)) \ .lstrip("0b").replace("b","").replace("L","") \ .replace("'","").replace('"',"") if len(binstr) % 7: binstr = binstr.zfill(len(binstr) + 7 - (len(binstr)...
[ "def", "inttoLEB128", "(", "intinput", ")", ":", "binstr", "=", "str", "(", "bin", "(", "intinput", ")", ")", ".", "lstrip", "(", "\"0b\"", ")", ".", "replace", "(", "\"b\"", ",", "\"\"", ")", ".", "replace", "(", "\"L\"", ",", "\"\"", ")", ".", ...
Convert int/long to unsigned LEB128 format hex
[ "Convert", "int", "/", "long", "to", "unsigned", "LEB128", "format", "hex" ]
train
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscbitcoinfuncs.py#L202-L223
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscbitcoinfuncs.py
LEB128toint
def LEB128toint(LEBinput): ''' Convert unsigned LEB128 hex to integer ''' reversedbytes = hexreverse(LEBinput) binstr = "" for i in range(len(LEBinput) // 2): if i == 0: assert int(reversedbytes[2*i:(2*i + 2)],16) < 128 else: assert int(reversedbytes[2*i:...
python
def LEB128toint(LEBinput): ''' Convert unsigned LEB128 hex to integer ''' reversedbytes = hexreverse(LEBinput) binstr = "" for i in range(len(LEBinput) // 2): if i == 0: assert int(reversedbytes[2*i:(2*i + 2)],16) < 128 else: assert int(reversedbytes[2*i:...
[ "def", "LEB128toint", "(", "LEBinput", ")", ":", "reversedbytes", "=", "hexreverse", "(", "LEBinput", ")", "binstr", "=", "\"\"", "for", "i", "in", "range", "(", "len", "(", "LEBinput", ")", "//", "2", ")", ":", "if", "i", "==", "0", ":", "assert", ...
Convert unsigned LEB128 hex to integer
[ "Convert", "unsigned", "LEB128", "hex", "to", "integer" ]
train
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscbitcoinfuncs.py#L226-L243
AoiKuiyuyou/AoikSixyIO
src/aoiksixyio/aoiksixyio_.py
SixyIO.get_traceback_stxt
def get_traceback_stxt(): """ Result is (bytes) str type on Python 2 and (unicode) str type on Python 3. """ #/ exc_cls, exc_obj, tb_obj = sys.exc_info() #/ txt_s = traceback.format_exception(exc_cls, exc_obj, tb_obj) #/ res = ''.join...
python
def get_traceback_stxt(): """ Result is (bytes) str type on Python 2 and (unicode) str type on Python 3. """ #/ exc_cls, exc_obj, tb_obj = sys.exc_info() #/ txt_s = traceback.format_exception(exc_cls, exc_obj, tb_obj) #/ res = ''.join...
[ "def", "get_traceback_stxt", "(", ")", ":", "#/", "exc_cls", ",", "exc_obj", ",", "tb_obj", "=", "sys", ".", "exc_info", "(", ")", "#/", "txt_s", "=", "traceback", ".", "format_exception", "(", "exc_cls", ",", "exc_obj", ",", "tb_obj", ")", "#/", "res", ...
Result is (bytes) str type on Python 2 and (unicode) str type on Python 3.
[ "Result", "is", "(", "bytes", ")", "str", "type", "on", "Python", "2", "and", "(", "unicode", ")", "str", "type", "on", "Python", "3", "." ]
train
https://github.com/AoiKuiyuyou/AoikSixyIO/blob/d8f05360201b5d14178ecb24ff6ca71f305797cd/src/aoiksixyio/aoiksixyio_.py#L160-L173
Nekroze/librarian
librarian/card.py
Card.add_attribute
def add_attribute(self, attribute): """ Add the given attribute to this Card. Returns the length of attributes after addition. """ self.attributes.append(attribute) return len(self.attributes)
python
def add_attribute(self, attribute): """ Add the given attribute to this Card. Returns the length of attributes after addition. """ self.attributes.append(attribute) return len(self.attributes)
[ "def", "add_attribute", "(", "self", ",", "attribute", ")", ":", "self", ".", "attributes", ".", "append", "(", "attribute", ")", "return", "len", "(", "self", ".", "attributes", ")" ]
Add the given attribute to this Card. Returns the length of attributes after addition.
[ "Add", "the", "given", "attribute", "to", "this", "Card", ".", "Returns", "the", "length", "of", "attributes", "after", "addition", "." ]
train
https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/card.py#L42-L48
Nekroze/librarian
librarian/card.py
Card.add_ability
def add_ability(self, phase, ability): """Add the given ability to this Card under the given phase. Returns the length of the abilities for the given phase after the addition. """ if phase not in self.abilities: self.abilities[phase] = [] self.abilities[phase].append(...
python
def add_ability(self, phase, ability): """Add the given ability to this Card under the given phase. Returns the length of the abilities for the given phase after the addition. """ if phase not in self.abilities: self.abilities[phase] = [] self.abilities[phase].append(...
[ "def", "add_ability", "(", "self", ",", "phase", ",", "ability", ")", ":", "if", "phase", "not", "in", "self", ".", "abilities", ":", "self", ".", "abilities", "[", "phase", "]", "=", "[", "]", "self", ".", "abilities", "[", "phase", "]", ".", "app...
Add the given ability to this Card under the given phase. Returns the length of the abilities for the given phase after the addition.
[ "Add", "the", "given", "ability", "to", "this", "Card", "under", "the", "given", "phase", ".", "Returns", "the", "length", "of", "the", "abilities", "for", "the", "given", "phase", "after", "the", "addition", "." ]
train
https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/card.py#L54-L61
Nekroze/librarian
librarian/card.py
Card.set_info
def set_info(self, key, value, append=True): """ Set any special info you wish to the given key. Each info is stored in a list and will be appended to rather then overriden unless append is False. """ if append: if key not in self.info: self.in...
python
def set_info(self, key, value, append=True): """ Set any special info you wish to the given key. Each info is stored in a list and will be appended to rather then overriden unless append is False. """ if append: if key not in self.info: self.in...
[ "def", "set_info", "(", "self", ",", "key", ",", "value", ",", "append", "=", "True", ")", ":", "if", "append", ":", "if", "key", "not", "in", "self", ".", "info", ":", "self", ".", "info", "[", "key", "]", "=", "[", "]", "self", ".", "info", ...
Set any special info you wish to the given key. Each info is stored in a list and will be appended to rather then overriden unless append is False.
[ "Set", "any", "special", "info", "you", "wish", "to", "the", "given", "key", ".", "Each", "info", "is", "stored", "in", "a", "list", "and", "will", "be", "appended", "to", "rather", "then", "overriden", "unless", "append", "is", "False", "." ]
train
https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/card.py#L67-L78
Nekroze/librarian
librarian/card.py
Card.save
def save(self): """ Converts the Card as is into a dictionary capable of reconstructing the card with ``Card.load`` or serialized to a string for storage. """ return dict(code=self.code, name=self.name, abilities=self.abilities, attributes=self.attributes, inf...
python
def save(self): """ Converts the Card as is into a dictionary capable of reconstructing the card with ``Card.load`` or serialized to a string for storage. """ return dict(code=self.code, name=self.name, abilities=self.abilities, attributes=self.attributes, inf...
[ "def", "save", "(", "self", ")", ":", "return", "dict", "(", "code", "=", "self", ".", "code", ",", "name", "=", "self", ".", "name", ",", "abilities", "=", "self", ".", "abilities", ",", "attributes", "=", "self", ".", "attributes", ",", "info", "...
Converts the Card as is into a dictionary capable of reconstructing the card with ``Card.load`` or serialized to a string for storage.
[ "Converts", "the", "Card", "as", "is", "into", "a", "dictionary", "capable", "of", "reconstructing", "the", "card", "with", "Card", ".", "load", "or", "serialized", "to", "a", "string", "for", "storage", "." ]
train
https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/card.py#L80-L86
Nekroze/librarian
librarian/card.py
Card.load
def load(self, carddict): """ Takes a carddict as produced by ``Card.save`` and sets this card instances information to the previously saved cards information. """ self.code = carddict["code"] if isinstance(self.code, text_type): self.code = eval(self.code) ...
python
def load(self, carddict): """ Takes a carddict as produced by ``Card.save`` and sets this card instances information to the previously saved cards information. """ self.code = carddict["code"] if isinstance(self.code, text_type): self.code = eval(self.code) ...
[ "def", "load", "(", "self", ",", "carddict", ")", ":", "self", ".", "code", "=", "carddict", "[", "\"code\"", "]", "if", "isinstance", "(", "self", ".", "code", ",", "text_type", ")", ":", "self", ".", "code", "=", "eval", "(", "self", ".", "code",...
Takes a carddict as produced by ``Card.save`` and sets this card instances information to the previously saved cards information.
[ "Takes", "a", "carddict", "as", "produced", "by", "Card", ".", "save", "and", "sets", "this", "card", "instances", "information", "to", "the", "previously", "saved", "cards", "information", "." ]
train
https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/card.py#L88-L106
SmartDeveloperHub/sdh-metrics
sdh/metrics/jobs/calculus.py
chunks
def chunks(l, n): """Yield successive n-sized chunks from l.""" if n: for i in xrange(0, len(l), n): yield l[i:i + n]
python
def chunks(l, n): """Yield successive n-sized chunks from l.""" if n: for i in xrange(0, len(l), n): yield l[i:i + n]
[ "def", "chunks", "(", "l", ",", "n", ")", ":", "if", "n", ":", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "l", ")", ",", "n", ")", ":", "yield", "l", "[", "i", ":", "i", "+", "n", "]" ]
Yield successive n-sized chunks from l.
[ "Yield", "successive", "n", "-", "sized", "chunks", "from", "l", "." ]
train
https://github.com/SmartDeveloperHub/sdh-metrics/blob/a418619e85e38b90a71cf8eca0bd3f852d42423b/sdh/metrics/jobs/calculus.py#L45-L49