id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
241,800
hactar-is/frink
frink/orm.py
ORMLayer.filter
def filter(self, order_by=None, limit=0, **kwargs): """ Fetch a list of instances. :param order_by: column on which to order the results. \ To change the sort, prepend with < or >. :param limit: How many rows to fetch. :param kwargs: keyword args on which to filter, column=value """ with rconnect() as conn: if len(kwargs) == 0: raise ValueError try: query = self._base() query = query.filter(kwargs) if order_by is not None: query = self._order_by(query, order_by) if limit > 0: query = self._limit(query, limit) log.debug(query) rv = query.run(conn) except ReqlOpFailedError as e: log.warn(e) raise except Exception as e: log.warn(e) raise else: data = [self._model(_) for _ in rv] return data
python
def filter(self, order_by=None, limit=0, **kwargs): """ Fetch a list of instances. :param order_by: column on which to order the results. \ To change the sort, prepend with < or >. :param limit: How many rows to fetch. :param kwargs: keyword args on which to filter, column=value """ with rconnect() as conn: if len(kwargs) == 0: raise ValueError try: query = self._base() query = query.filter(kwargs) if order_by is not None: query = self._order_by(query, order_by) if limit > 0: query = self._limit(query, limit) log.debug(query) rv = query.run(conn) except ReqlOpFailedError as e: log.warn(e) raise except Exception as e: log.warn(e) raise else: data = [self._model(_) for _ in rv] return data
[ "def", "filter", "(", "self", ",", "order_by", "=", "None", ",", "limit", "=", "0", ",", "*", "*", "kwargs", ")", ":", "with", "rconnect", "(", ")", "as", "conn", ":", "if", "len", "(", "kwargs", ")", "==", "0", ":", "raise", "ValueError", "try", ":", "query", "=", "self", ".", "_base", "(", ")", "query", "=", "query", ".", "filter", "(", "kwargs", ")", "if", "order_by", "is", "not", "None", ":", "query", "=", "self", ".", "_order_by", "(", "query", ",", "order_by", ")", "if", "limit", ">", "0", ":", "query", "=", "self", ".", "_limit", "(", "query", ",", "limit", ")", "log", ".", "debug", "(", "query", ")", "rv", "=", "query", ".", "run", "(", "conn", ")", "except", "ReqlOpFailedError", "as", "e", ":", "log", ".", "warn", "(", "e", ")", "raise", "except", "Exception", "as", "e", ":", "log", ".", "warn", "(", "e", ")", "raise", "else", ":", "data", "=", "[", "self", ".", "_model", "(", "_", ")", "for", "_", "in", "rv", "]", "return", "data" ]
Fetch a list of instances. :param order_by: column on which to order the results. \ To change the sort, prepend with < or >. :param limit: How many rows to fetch. :param kwargs: keyword args on which to filter, column=value
[ "Fetch", "a", "list", "of", "instances", "." ]
0d2c11daca8ef6d4365e98914bdc0bc65478ae72
https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L180-L215
241,801
hactar-is/frink
frink/orm.py
ORMLayer.all
def all(self, order_by=None, limit=0): """ Fetch all items. :param limit: How many rows to fetch. :param order_by: column on which to order the results. \ To change the sort, prepend with < or >. """ with rconnect() as conn: try: query = self._base() if order_by is not None: query = self._order_by(query, order_by) if limit > 0: query = self._limit(query, limit) log.debug(query) rv = query.run(conn) except Exception as e: log.warn(e) raise else: data = [self._model(_) for _ in rv] return data
python
def all(self, order_by=None, limit=0): """ Fetch all items. :param limit: How many rows to fetch. :param order_by: column on which to order the results. \ To change the sort, prepend with < or >. """ with rconnect() as conn: try: query = self._base() if order_by is not None: query = self._order_by(query, order_by) if limit > 0: query = self._limit(query, limit) log.debug(query) rv = query.run(conn) except Exception as e: log.warn(e) raise else: data = [self._model(_) for _ in rv] return data
[ "def", "all", "(", "self", ",", "order_by", "=", "None", ",", "limit", "=", "0", ")", ":", "with", "rconnect", "(", ")", "as", "conn", ":", "try", ":", "query", "=", "self", ".", "_base", "(", ")", "if", "order_by", "is", "not", "None", ":", "query", "=", "self", ".", "_order_by", "(", "query", ",", "order_by", ")", "if", "limit", ">", "0", ":", "query", "=", "self", ".", "_limit", "(", "query", ",", "limit", ")", "log", ".", "debug", "(", "query", ")", "rv", "=", "query", ".", "run", "(", "conn", ")", "except", "Exception", "as", "e", ":", "log", ".", "warn", "(", "e", ")", "raise", "else", ":", "data", "=", "[", "self", ".", "_model", "(", "_", ")", "for", "_", "in", "rv", "]", "return", "data" ]
Fetch all items. :param limit: How many rows to fetch. :param order_by: column on which to order the results. \ To change the sort, prepend with < or >.
[ "Fetch", "all", "items", "." ]
0d2c11daca8ef6d4365e98914bdc0bc65478ae72
https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L320-L344
241,802
dusty-phillips/opterator
opterator.py
opterate
def opterate(func): '''A decorator for a main function entry point to a script. It automatically generates the options for the main entry point based on the arguments, keyword arguments, and docstring. All keyword arguments in the function definition are options. Positional arguments are mandatory arguments that store a string value. Varargs become a variable length (zero allowed) list of positional arguments. Varkwargs are currently ignored. The default value assigned to a keyword argument helps determine the type of option and action. The defalut value is assigned directly to the parser's default for that option. In addition, it determines the ArgumentParser action -- a default value of False implies store_true, while True implies store_false. If the default value is a list, the action is append (multiple instances of that option are permitted). Strings or None imply a store action. Options are further defined in the docstring. The top part of the docstring becomes the usage message for the app. Below that, ReST-style :param: lines in the following format describe the option: :param variable_name: -v --verbose the help_text for the variable :param variable_name: -v the help_text no long option :param variable_name: --verbose the help_text no short option the format is: :param name: [short option and/or long option] help text Variable_name is the name of the variable in the function specification and must refer to a keyword argument. All options must have a :param: line like this. If you can have an arbitrary length of positional arguments, add a *arglist variable; It can be named with any valid python identifier. See opterator_test.py and examples/ for some examples.''' ( positional_params, kw_params, varargs, defaults, annotations ) = portable_argspec(func) description = '' param_docs = {} if func.__doc__: param_doc = func.__doc__.split(':param') description = param_doc.pop(0).strip() for param in param_doc: param_args = param.split() variable_name = param_args.pop(0)[:-1] param_docs[variable_name] = param_args parser = ArgumentParser(description=description) option_generator = generate_options() next(option_generator) for param in positional_params: parser.add_argument(param, help=" ".join(param_docs.get(param, []))) for param in kw_params: default = defaults[kw_params.index(param)] names = [] param_doc = [] if param in annotations: names = annotations[param] if param in param_docs: param_doc = param_docs.get(param, []) while param_doc and param_doc[0].startswith('-'): names.append(param_doc.pop(0)) names = names if names else option_generator.send(param) option_kwargs = { 'action': 'store', 'help': ' '.join(param_doc), 'dest': param, 'default': default } if default is False: option_kwargs['action'] = 'store_true' elif default is True: option_kwargs['action'] = 'store_false' elif type(default) in (list, tuple): if default: option_kwargs['choices'] = default else: option_kwargs['action'] = 'append' parser.add_argument(*names, **option_kwargs) if varargs: parser.add_argument(varargs, nargs='*') def wrapper(argv=None): args = vars(parser.parse_args(argv)) processed_args = [args[p] for p in positional_params + kw_params] if varargs: processed_args.extend(args[varargs]) func(*processed_args) return wrapper
python
def opterate(func): '''A decorator for a main function entry point to a script. It automatically generates the options for the main entry point based on the arguments, keyword arguments, and docstring. All keyword arguments in the function definition are options. Positional arguments are mandatory arguments that store a string value. Varargs become a variable length (zero allowed) list of positional arguments. Varkwargs are currently ignored. The default value assigned to a keyword argument helps determine the type of option and action. The defalut value is assigned directly to the parser's default for that option. In addition, it determines the ArgumentParser action -- a default value of False implies store_true, while True implies store_false. If the default value is a list, the action is append (multiple instances of that option are permitted). Strings or None imply a store action. Options are further defined in the docstring. The top part of the docstring becomes the usage message for the app. Below that, ReST-style :param: lines in the following format describe the option: :param variable_name: -v --verbose the help_text for the variable :param variable_name: -v the help_text no long option :param variable_name: --verbose the help_text no short option the format is: :param name: [short option and/or long option] help text Variable_name is the name of the variable in the function specification and must refer to a keyword argument. All options must have a :param: line like this. If you can have an arbitrary length of positional arguments, add a *arglist variable; It can be named with any valid python identifier. See opterator_test.py and examples/ for some examples.''' ( positional_params, kw_params, varargs, defaults, annotations ) = portable_argspec(func) description = '' param_docs = {} if func.__doc__: param_doc = func.__doc__.split(':param') description = param_doc.pop(0).strip() for param in param_doc: param_args = param.split() variable_name = param_args.pop(0)[:-1] param_docs[variable_name] = param_args parser = ArgumentParser(description=description) option_generator = generate_options() next(option_generator) for param in positional_params: parser.add_argument(param, help=" ".join(param_docs.get(param, []))) for param in kw_params: default = defaults[kw_params.index(param)] names = [] param_doc = [] if param in annotations: names = annotations[param] if param in param_docs: param_doc = param_docs.get(param, []) while param_doc and param_doc[0].startswith('-'): names.append(param_doc.pop(0)) names = names if names else option_generator.send(param) option_kwargs = { 'action': 'store', 'help': ' '.join(param_doc), 'dest': param, 'default': default } if default is False: option_kwargs['action'] = 'store_true' elif default is True: option_kwargs['action'] = 'store_false' elif type(default) in (list, tuple): if default: option_kwargs['choices'] = default else: option_kwargs['action'] = 'append' parser.add_argument(*names, **option_kwargs) if varargs: parser.add_argument(varargs, nargs='*') def wrapper(argv=None): args = vars(parser.parse_args(argv)) processed_args = [args[p] for p in positional_params + kw_params] if varargs: processed_args.extend(args[varargs]) func(*processed_args) return wrapper
[ "def", "opterate", "(", "func", ")", ":", "(", "positional_params", ",", "kw_params", ",", "varargs", ",", "defaults", ",", "annotations", ")", "=", "portable_argspec", "(", "func", ")", "description", "=", "''", "param_docs", "=", "{", "}", "if", "func", ".", "__doc__", ":", "param_doc", "=", "func", ".", "__doc__", ".", "split", "(", "':param'", ")", "description", "=", "param_doc", ".", "pop", "(", "0", ")", ".", "strip", "(", ")", "for", "param", "in", "param_doc", ":", "param_args", "=", "param", ".", "split", "(", ")", "variable_name", "=", "param_args", ".", "pop", "(", "0", ")", "[", ":", "-", "1", "]", "param_docs", "[", "variable_name", "]", "=", "param_args", "parser", "=", "ArgumentParser", "(", "description", "=", "description", ")", "option_generator", "=", "generate_options", "(", ")", "next", "(", "option_generator", ")", "for", "param", "in", "positional_params", ":", "parser", ".", "add_argument", "(", "param", ",", "help", "=", "\" \"", ".", "join", "(", "param_docs", ".", "get", "(", "param", ",", "[", "]", ")", ")", ")", "for", "param", "in", "kw_params", ":", "default", "=", "defaults", "[", "kw_params", ".", "index", "(", "param", ")", "]", "names", "=", "[", "]", "param_doc", "=", "[", "]", "if", "param", "in", "annotations", ":", "names", "=", "annotations", "[", "param", "]", "if", "param", "in", "param_docs", ":", "param_doc", "=", "param_docs", ".", "get", "(", "param", ",", "[", "]", ")", "while", "param_doc", "and", "param_doc", "[", "0", "]", ".", "startswith", "(", "'-'", ")", ":", "names", ".", "append", "(", "param_doc", ".", "pop", "(", "0", ")", ")", "names", "=", "names", "if", "names", "else", "option_generator", ".", "send", "(", "param", ")", "option_kwargs", "=", "{", "'action'", ":", "'store'", ",", "'help'", ":", "' '", ".", "join", "(", "param_doc", ")", ",", "'dest'", ":", "param", ",", "'default'", ":", "default", "}", "if", "default", "is", "False", ":", "option_kwargs", "[", "'action'", "]", "=", "'store_true'", "elif", "default", "is", "True", ":", "option_kwargs", "[", "'action'", "]", "=", "'store_false'", "elif", "type", "(", "default", ")", "in", "(", "list", ",", "tuple", ")", ":", "if", "default", ":", "option_kwargs", "[", "'choices'", "]", "=", "default", "else", ":", "option_kwargs", "[", "'action'", "]", "=", "'append'", "parser", ".", "add_argument", "(", "*", "names", ",", "*", "*", "option_kwargs", ")", "if", "varargs", ":", "parser", ".", "add_argument", "(", "varargs", ",", "nargs", "=", "'*'", ")", "def", "wrapper", "(", "argv", "=", "None", ")", ":", "args", "=", "vars", "(", "parser", ".", "parse_args", "(", "argv", ")", ")", "processed_args", "=", "[", "args", "[", "p", "]", "for", "p", "in", "positional_params", "+", "kw_params", "]", "if", "varargs", ":", "processed_args", ".", "extend", "(", "args", "[", "varargs", "]", ")", "func", "(", "*", "processed_args", ")", "return", "wrapper" ]
A decorator for a main function entry point to a script. It automatically generates the options for the main entry point based on the arguments, keyword arguments, and docstring. All keyword arguments in the function definition are options. Positional arguments are mandatory arguments that store a string value. Varargs become a variable length (zero allowed) list of positional arguments. Varkwargs are currently ignored. The default value assigned to a keyword argument helps determine the type of option and action. The defalut value is assigned directly to the parser's default for that option. In addition, it determines the ArgumentParser action -- a default value of False implies store_true, while True implies store_false. If the default value is a list, the action is append (multiple instances of that option are permitted). Strings or None imply a store action. Options are further defined in the docstring. The top part of the docstring becomes the usage message for the app. Below that, ReST-style :param: lines in the following format describe the option: :param variable_name: -v --verbose the help_text for the variable :param variable_name: -v the help_text no long option :param variable_name: --verbose the help_text no short option the format is: :param name: [short option and/or long option] help text Variable_name is the name of the variable in the function specification and must refer to a keyword argument. All options must have a :param: line like this. If you can have an arbitrary length of positional arguments, add a *arglist variable; It can be named with any valid python identifier. See opterator_test.py and examples/ for some examples.
[ "A", "decorator", "for", "a", "main", "function", "entry", "point", "to", "a", "script", ".", "It", "automatically", "generates", "the", "options", "for", "the", "main", "entry", "point", "based", "on", "the", "arguments", "keyword", "arguments", "and", "docstring", "." ]
84fe31f22c73dc0a3666ed82c179461b1799c257
https://github.com/dusty-phillips/opterator/blob/84fe31f22c73dc0a3666ed82c179461b1799c257/opterator.py#L81-L175
241,803
mayfield/shellish
shellish/command/contrib/syscomplete.py
SystemCompletion.show_setup
def show_setup(self): """ Provide a helper script for the user to setup completion. """ shell = os.getenv('SHELL') if not shell: raise SystemError("No $SHELL env var found") shell = os.path.basename(shell) if shell not in self.script_body: raise SystemError("Unsupported shell: %s" % shell) tplvars = { "prog": '-'.join(self.prog.split()[:-1]), "shell": shell, "name": self.name } print(self.trim(self.script_header % tplvars)) print(self.trim(self.script_body[shell] % tplvars)) print(self.trim(self.script_footer % tplvars))
python
def show_setup(self): """ Provide a helper script for the user to setup completion. """ shell = os.getenv('SHELL') if not shell: raise SystemError("No $SHELL env var found") shell = os.path.basename(shell) if shell not in self.script_body: raise SystemError("Unsupported shell: %s" % shell) tplvars = { "prog": '-'.join(self.prog.split()[:-1]), "shell": shell, "name": self.name } print(self.trim(self.script_header % tplvars)) print(self.trim(self.script_body[shell] % tplvars)) print(self.trim(self.script_footer % tplvars))
[ "def", "show_setup", "(", "self", ")", ":", "shell", "=", "os", ".", "getenv", "(", "'SHELL'", ")", "if", "not", "shell", ":", "raise", "SystemError", "(", "\"No $SHELL env var found\"", ")", "shell", "=", "os", ".", "path", ".", "basename", "(", "shell", ")", "if", "shell", "not", "in", "self", ".", "script_body", ":", "raise", "SystemError", "(", "\"Unsupported shell: %s\"", "%", "shell", ")", "tplvars", "=", "{", "\"prog\"", ":", "'-'", ".", "join", "(", "self", ".", "prog", ".", "split", "(", ")", "[", ":", "-", "1", "]", ")", ",", "\"shell\"", ":", "shell", ",", "\"name\"", ":", "self", ".", "name", "}", "print", "(", "self", ".", "trim", "(", "self", ".", "script_header", "%", "tplvars", ")", ")", "print", "(", "self", ".", "trim", "(", "self", ".", "script_body", "[", "shell", "]", "%", "tplvars", ")", ")", "print", "(", "self", ".", "trim", "(", "self", ".", "script_footer", "%", "tplvars", ")", ")" ]
Provide a helper script for the user to setup completion.
[ "Provide", "a", "helper", "script", "for", "the", "user", "to", "setup", "completion", "." ]
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/contrib/syscomplete.py#L84-L99
241,804
mayfield/shellish
shellish/command/contrib/syscomplete.py
SystemCompletion.trim
def trim(self, text): """ Trim whitespace indentation from text. """ lines = text.splitlines() firstline = lines[0] or lines[1] indent = len(firstline) - len(firstline.lstrip()) return '\n'.join(x[indent:] for x in lines if x.strip())
python
def trim(self, text): """ Trim whitespace indentation from text. """ lines = text.splitlines() firstline = lines[0] or lines[1] indent = len(firstline) - len(firstline.lstrip()) return '\n'.join(x[indent:] for x in lines if x.strip())
[ "def", "trim", "(", "self", ",", "text", ")", ":", "lines", "=", "text", ".", "splitlines", "(", ")", "firstline", "=", "lines", "[", "0", "]", "or", "lines", "[", "1", "]", "indent", "=", "len", "(", "firstline", ")", "-", "len", "(", "firstline", ".", "lstrip", "(", ")", ")", "return", "'\\n'", ".", "join", "(", "x", "[", "indent", ":", "]", "for", "x", "in", "lines", "if", "x", ".", "strip", "(", ")", ")" ]
Trim whitespace indentation from text.
[ "Trim", "whitespace", "indentation", "from", "text", "." ]
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/contrib/syscomplete.py#L101-L106
241,805
holmes-app/holmes-alf
holmesalf/wrapper.py
AlfAuthNZWrapper.sync_client
def sync_client(self): """Synchronous OAuth 2.0 Bearer client""" if not self._sync_client: self._sync_client = AlfSyncClient( token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'), client_id=self.config.get('OAUTH_CLIENT_ID'), client_secret=self.config.get('OAUTH_CLIENT_SECRET') ) return self._sync_client
python
def sync_client(self): """Synchronous OAuth 2.0 Bearer client""" if not self._sync_client: self._sync_client = AlfSyncClient( token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'), client_id=self.config.get('OAUTH_CLIENT_ID'), client_secret=self.config.get('OAUTH_CLIENT_SECRET') ) return self._sync_client
[ "def", "sync_client", "(", "self", ")", ":", "if", "not", "self", ".", "_sync_client", ":", "self", ".", "_sync_client", "=", "AlfSyncClient", "(", "token_endpoint", "=", "self", ".", "config", ".", "get", "(", "'OAUTH_TOKEN_ENDPOINT'", ")", ",", "client_id", "=", "self", ".", "config", ".", "get", "(", "'OAUTH_CLIENT_ID'", ")", ",", "client_secret", "=", "self", ".", "config", ".", "get", "(", "'OAUTH_CLIENT_SECRET'", ")", ")", "return", "self", ".", "_sync_client" ]
Synchronous OAuth 2.0 Bearer client
[ "Synchronous", "OAuth", "2", ".", "0", "Bearer", "client" ]
4bf891831390ecfae818cf37d8ffc3a76fe9f1ec
https://github.com/holmes-app/holmes-alf/blob/4bf891831390ecfae818cf37d8ffc3a76fe9f1ec/holmesalf/wrapper.py#L26-L34
241,806
holmes-app/holmes-alf
holmesalf/wrapper.py
AlfAuthNZWrapper.async_client
def async_client(self): """Asynchronous OAuth 2.0 Bearer client""" if not self._async_client: self._async_client = AlfAsyncClient( token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'), client_id=self.config.get('OAUTH_CLIENT_ID'), client_secret=self.config.get('OAUTH_CLIENT_SECRET') ) return self._async_client
python
def async_client(self): """Asynchronous OAuth 2.0 Bearer client""" if not self._async_client: self._async_client = AlfAsyncClient( token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'), client_id=self.config.get('OAUTH_CLIENT_ID'), client_secret=self.config.get('OAUTH_CLIENT_SECRET') ) return self._async_client
[ "def", "async_client", "(", "self", ")", ":", "if", "not", "self", ".", "_async_client", ":", "self", ".", "_async_client", "=", "AlfAsyncClient", "(", "token_endpoint", "=", "self", ".", "config", ".", "get", "(", "'OAUTH_TOKEN_ENDPOINT'", ")", ",", "client_id", "=", "self", ".", "config", ".", "get", "(", "'OAUTH_CLIENT_ID'", ")", ",", "client_secret", "=", "self", ".", "config", ".", "get", "(", "'OAUTH_CLIENT_SECRET'", ")", ")", "return", "self", ".", "_async_client" ]
Asynchronous OAuth 2.0 Bearer client
[ "Asynchronous", "OAuth", "2", ".", "0", "Bearer", "client" ]
4bf891831390ecfae818cf37d8ffc3a76fe9f1ec
https://github.com/holmes-app/holmes-alf/blob/4bf891831390ecfae818cf37d8ffc3a76fe9f1ec/holmesalf/wrapper.py#L37-L45
241,807
thwehner/python-firepit
setup.py
get_package_version
def get_package_version(): """returns package version without importing it""" base = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(base, "firepit/__init__.py")) as pkg: for line in pkg: m = version.match(line.strip()) if not m: continue return ".".join(m.groups()[0].split(", "))
python
def get_package_version(): """returns package version without importing it""" base = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(base, "firepit/__init__.py")) as pkg: for line in pkg: m = version.match(line.strip()) if not m: continue return ".".join(m.groups()[0].split(", "))
[ "def", "get_package_version", "(", ")", ":", "base", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "base", ",", "\"firepit/__init__.py\"", ")", ")", "as", "pkg", ":", "for", "line", "in", "pkg", ":", "m", "=", "version", ".", "match", "(", "line", ".", "strip", "(", ")", ")", "if", "not", "m", ":", "continue", "return", "\".\"", ".", "join", "(", "m", ".", "groups", "(", ")", "[", "0", "]", ".", "split", "(", "\", \"", ")", ")" ]
returns package version without importing it
[ "returns", "package", "version", "without", "importing", "it" ]
68aa3b9c9e034e6a9a3498d997ac8d9a03f8c0f9
https://github.com/thwehner/python-firepit/blob/68aa3b9c9e034e6a9a3498d997ac8d9a03f8c0f9/setup.py#L12-L20
241,808
pavelsof/ipalint
ipalint/ipa.py
Recogniser.recognise
def recognise(self, string, line_num): """ Splits the string into chars and distributes these into the buckets of IPA and non-IPA symbols. Expects that there are no precomposed chars in the string. """ symbols = [] unknown = [] for char in string: if char == SPACE: continue try: name = unicodedata.name(char) except ValueError: name = 'UNNAMED CHARACTER {}'.format(ord(char)) if char in self.ipa: symbol = Symbol(char, name, self.ipa[char]) symbols.append(symbol) self.ipa_symbols[symbol].append(line_num) else: symbol = UnknownSymbol(char, name) unknown.append(symbol) self.unk_symbols[symbol].append(line_num) return tuple(symbols), tuple(unknown)
python
def recognise(self, string, line_num): """ Splits the string into chars and distributes these into the buckets of IPA and non-IPA symbols. Expects that there are no precomposed chars in the string. """ symbols = [] unknown = [] for char in string: if char == SPACE: continue try: name = unicodedata.name(char) except ValueError: name = 'UNNAMED CHARACTER {}'.format(ord(char)) if char in self.ipa: symbol = Symbol(char, name, self.ipa[char]) symbols.append(symbol) self.ipa_symbols[symbol].append(line_num) else: symbol = UnknownSymbol(char, name) unknown.append(symbol) self.unk_symbols[symbol].append(line_num) return tuple(symbols), tuple(unknown)
[ "def", "recognise", "(", "self", ",", "string", ",", "line_num", ")", ":", "symbols", "=", "[", "]", "unknown", "=", "[", "]", "for", "char", "in", "string", ":", "if", "char", "==", "SPACE", ":", "continue", "try", ":", "name", "=", "unicodedata", ".", "name", "(", "char", ")", "except", "ValueError", ":", "name", "=", "'UNNAMED CHARACTER {}'", ".", "format", "(", "ord", "(", "char", ")", ")", "if", "char", "in", "self", ".", "ipa", ":", "symbol", "=", "Symbol", "(", "char", ",", "name", ",", "self", ".", "ipa", "[", "char", "]", ")", "symbols", ".", "append", "(", "symbol", ")", "self", ".", "ipa_symbols", "[", "symbol", "]", ".", "append", "(", "line_num", ")", "else", ":", "symbol", "=", "UnknownSymbol", "(", "char", ",", "name", ")", "unknown", ".", "append", "(", "symbol", ")", "self", ".", "unk_symbols", "[", "symbol", "]", ".", "append", "(", "line_num", ")", "return", "tuple", "(", "symbols", ")", ",", "tuple", "(", "unknown", ")" ]
Splits the string into chars and distributes these into the buckets of IPA and non-IPA symbols. Expects that there are no precomposed chars in the string.
[ "Splits", "the", "string", "into", "chars", "and", "distributes", "these", "into", "the", "buckets", "of", "IPA", "and", "non", "-", "IPA", "symbols", ".", "Expects", "that", "there", "are", "no", "precomposed", "chars", "in", "the", "string", "." ]
763e5979ede6980cbfc746b06fd007b379762eeb
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/ipa.py#L158-L185
241,809
pavelsof/ipalint
ipalint/ipa.py
Recogniser.report
def report(self, reporter): """ Adds the problems that have been found so far to the given Reporter instance. """ for symbol in sorted(self.unk_symbols.keys()): err = '{} ({}) is not part of IPA'.format(symbol.char, symbol.name) if symbol.char in self.common_err: repl = self.common_err[symbol.char] err += ', suggested replacement is {}'.format(repl) if len(repl) == 1: err += ' ({})'.format(unicodedata.name(repl)) reporter.add(self.unk_symbols[symbol], err)
python
def report(self, reporter): """ Adds the problems that have been found so far to the given Reporter instance. """ for symbol in sorted(self.unk_symbols.keys()): err = '{} ({}) is not part of IPA'.format(symbol.char, symbol.name) if symbol.char in self.common_err: repl = self.common_err[symbol.char] err += ', suggested replacement is {}'.format(repl) if len(repl) == 1: err += ' ({})'.format(unicodedata.name(repl)) reporter.add(self.unk_symbols[symbol], err)
[ "def", "report", "(", "self", ",", "reporter", ")", ":", "for", "symbol", "in", "sorted", "(", "self", ".", "unk_symbols", ".", "keys", "(", ")", ")", ":", "err", "=", "'{} ({}) is not part of IPA'", ".", "format", "(", "symbol", ".", "char", ",", "symbol", ".", "name", ")", "if", "symbol", ".", "char", "in", "self", ".", "common_err", ":", "repl", "=", "self", ".", "common_err", "[", "symbol", ".", "char", "]", "err", "+=", "', suggested replacement is {}'", ".", "format", "(", "repl", ")", "if", "len", "(", "repl", ")", "==", "1", ":", "err", "+=", "' ({})'", ".", "format", "(", "unicodedata", ".", "name", "(", "repl", ")", ")", "reporter", ".", "add", "(", "self", ".", "unk_symbols", "[", "symbol", "]", ",", "err", ")" ]
Adds the problems that have been found so far to the given Reporter instance.
[ "Adds", "the", "problems", "that", "have", "been", "found", "so", "far", "to", "the", "given", "Reporter", "instance", "." ]
763e5979ede6980cbfc746b06fd007b379762eeb
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/ipa.py#L188-L202
241,810
mrstephenneal/dirutility
dirutility/gui.py
WalkGUI.parsing
def parsing(self): """Parameters for parsing directory trees""" with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form: layout = [ [gui.Text('Directory Paths utility', size=(30, 1), font=("Helvetica", 25), text_color='blue')], # Source [gui.Text('Source Folder', size=(15, 1), auto_size_text=False), gui.InputText('Source'), gui.FolderBrowse()], # Parallel / Sequential [gui.Text('Parallel or Sequential Processing. Larger directory trees are typically parsed faster ' 'using parallel processing.')], [gui.Radio('Parallel Processing', "RADIO1"), gui.Radio('Sequential Processing', "RADIO1", default=True)], [_line()], # Files and non-empty-folders [gui.Text('Return files or folders, returning folders is useful for creating inventories.')], [gui.Radio('Return Files', "RADIO2", default=True), gui.Radio('Return Non-Empty Directories', "RADIO2")], [_line()], # max_level [gui.Text('Max Depth.... Max number of sub directory depths to traverse (starting directory is 0)')], [gui.InputCombo(list(reversed(range(0, 13))), size=(20, 3))], [_line()], # Relative and absolute [gui.Text('Relative or Absolute Paths. Relative paths are saved relative to the starting directory. ' 'Absolute paths are saved as full paths.')], [gui.Radio('Relative Paths', "RADIO3", default=True), gui.Radio('Absolute Paths', "RADIO3")], [_line()], # Topdown and output [gui.Checkbox('Topdown Parse', default=True), gui.Checkbox('Live output results')], [_line()], # Save results to file [gui.Checkbox('Save Results to File', default=False)], [gui.Submit(), gui.Cancel()]] (button, (values)) = form.LayoutAndShow(layout) # gui.MsgBox(self.title, 'Parameters set', 'The results of the form are... ', # 'The button clicked was "{}"'.format(button), 'The values are', values, auto_close=True) self.params['parse'] = { 'directory': values[0], 'parallelize': values[1], 'sequential': values[2], 'yield_files': values[3], 'non_empty_folders': values[4], 'max_level': int(values[5]), '_relative': values[6], 'full_paths': values[7], 'topdown': values[8], 'console_stream': values[9], 'save_file': values[10], } if self.params['parse']['save_file']: self._saving() return self.params
python
def parsing(self): """Parameters for parsing directory trees""" with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form: layout = [ [gui.Text('Directory Paths utility', size=(30, 1), font=("Helvetica", 25), text_color='blue')], # Source [gui.Text('Source Folder', size=(15, 1), auto_size_text=False), gui.InputText('Source'), gui.FolderBrowse()], # Parallel / Sequential [gui.Text('Parallel or Sequential Processing. Larger directory trees are typically parsed faster ' 'using parallel processing.')], [gui.Radio('Parallel Processing', "RADIO1"), gui.Radio('Sequential Processing', "RADIO1", default=True)], [_line()], # Files and non-empty-folders [gui.Text('Return files or folders, returning folders is useful for creating inventories.')], [gui.Radio('Return Files', "RADIO2", default=True), gui.Radio('Return Non-Empty Directories', "RADIO2")], [_line()], # max_level [gui.Text('Max Depth.... Max number of sub directory depths to traverse (starting directory is 0)')], [gui.InputCombo(list(reversed(range(0, 13))), size=(20, 3))], [_line()], # Relative and absolute [gui.Text('Relative or Absolute Paths. Relative paths are saved relative to the starting directory. ' 'Absolute paths are saved as full paths.')], [gui.Radio('Relative Paths', "RADIO3", default=True), gui.Radio('Absolute Paths', "RADIO3")], [_line()], # Topdown and output [gui.Checkbox('Topdown Parse', default=True), gui.Checkbox('Live output results')], [_line()], # Save results to file [gui.Checkbox('Save Results to File', default=False)], [gui.Submit(), gui.Cancel()]] (button, (values)) = form.LayoutAndShow(layout) # gui.MsgBox(self.title, 'Parameters set', 'The results of the form are... ', # 'The button clicked was "{}"'.format(button), 'The values are', values, auto_close=True) self.params['parse'] = { 'directory': values[0], 'parallelize': values[1], 'sequential': values[2], 'yield_files': values[3], 'non_empty_folders': values[4], 'max_level': int(values[5]), '_relative': values[6], 'full_paths': values[7], 'topdown': values[8], 'console_stream': values[9], 'save_file': values[10], } if self.params['parse']['save_file']: self._saving() return self.params
[ "def", "parsing", "(", "self", ")", ":", "with", "gui", ".", "FlexForm", "(", "self", ".", "title", ",", "auto_size_text", "=", "True", ",", "default_element_size", "=", "(", "40", ",", "1", ")", ")", "as", "form", ":", "layout", "=", "[", "[", "gui", ".", "Text", "(", "'Directory Paths utility'", ",", "size", "=", "(", "30", ",", "1", ")", ",", "font", "=", "(", "\"Helvetica\"", ",", "25", ")", ",", "text_color", "=", "'blue'", ")", "]", ",", "# Source", "[", "gui", ".", "Text", "(", "'Source Folder'", ",", "size", "=", "(", "15", ",", "1", ")", ",", "auto_size_text", "=", "False", ")", ",", "gui", ".", "InputText", "(", "'Source'", ")", ",", "gui", ".", "FolderBrowse", "(", ")", "]", ",", "# Parallel / Sequential", "[", "gui", ".", "Text", "(", "'Parallel or Sequential Processing. Larger directory trees are typically parsed faster '", "'using parallel processing.'", ")", "]", ",", "[", "gui", ".", "Radio", "(", "'Parallel Processing'", ",", "\"RADIO1\"", ")", ",", "gui", ".", "Radio", "(", "'Sequential Processing'", ",", "\"RADIO1\"", ",", "default", "=", "True", ")", "]", ",", "[", "_line", "(", ")", "]", ",", "# Files and non-empty-folders", "[", "gui", ".", "Text", "(", "'Return files or folders, returning folders is useful for creating inventories.'", ")", "]", ",", "[", "gui", ".", "Radio", "(", "'Return Files'", ",", "\"RADIO2\"", ",", "default", "=", "True", ")", ",", "gui", ".", "Radio", "(", "'Return Non-Empty Directories'", ",", "\"RADIO2\"", ")", "]", ",", "[", "_line", "(", ")", "]", ",", "# max_level", "[", "gui", ".", "Text", "(", "'Max Depth.... Max number of sub directory depths to traverse (starting directory is 0)'", ")", "]", ",", "[", "gui", ".", "InputCombo", "(", "list", "(", "reversed", "(", "range", "(", "0", ",", "13", ")", ")", ")", ",", "size", "=", "(", "20", ",", "3", ")", ")", "]", ",", "[", "_line", "(", ")", "]", ",", "# Relative and absolute", "[", "gui", ".", "Text", "(", "'Relative or Absolute Paths. Relative paths are saved relative to the starting directory. '", "'Absolute paths are saved as full paths.'", ")", "]", ",", "[", "gui", ".", "Radio", "(", "'Relative Paths'", ",", "\"RADIO3\"", ",", "default", "=", "True", ")", ",", "gui", ".", "Radio", "(", "'Absolute Paths'", ",", "\"RADIO3\"", ")", "]", ",", "[", "_line", "(", ")", "]", ",", "# Topdown and output", "[", "gui", ".", "Checkbox", "(", "'Topdown Parse'", ",", "default", "=", "True", ")", ",", "gui", ".", "Checkbox", "(", "'Live output results'", ")", "]", ",", "[", "_line", "(", ")", "]", ",", "# Save results to file", "[", "gui", ".", "Checkbox", "(", "'Save Results to File'", ",", "default", "=", "False", ")", "]", ",", "[", "gui", ".", "Submit", "(", ")", ",", "gui", ".", "Cancel", "(", ")", "]", "]", "(", "button", ",", "(", "values", ")", ")", "=", "form", ".", "LayoutAndShow", "(", "layout", ")", "# gui.MsgBox(self.title, 'Parameters set', 'The results of the form are... ',", "# 'The button clicked was \"{}\"'.format(button), 'The values are', values, auto_close=True)", "self", ".", "params", "[", "'parse'", "]", "=", "{", "'directory'", ":", "values", "[", "0", "]", ",", "'parallelize'", ":", "values", "[", "1", "]", ",", "'sequential'", ":", "values", "[", "2", "]", ",", "'yield_files'", ":", "values", "[", "3", "]", ",", "'non_empty_folders'", ":", "values", "[", "4", "]", ",", "'max_level'", ":", "int", "(", "values", "[", "5", "]", ")", ",", "'_relative'", ":", "values", "[", "6", "]", ",", "'full_paths'", ":", "values", "[", "7", "]", ",", "'topdown'", ":", "values", "[", "8", "]", ",", "'console_stream'", ":", "values", "[", "9", "]", ",", "'save_file'", ":", "values", "[", "10", "]", ",", "}", "if", "self", ".", "params", "[", "'parse'", "]", "[", "'save_file'", "]", ":", "self", ".", "_saving", "(", ")", "return", "self", ".", "params" ]
Parameters for parsing directory trees
[ "Parameters", "for", "parsing", "directory", "trees" ]
339378659e2d7e09c53acfc51c5df745bb0cd517
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/gui.py#L51-L114
241,811
mrstephenneal/dirutility
dirutility/gui.py
BackupZipGUI.source
def source(self): """Parameters for saving zip backups""" with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form: layout = [ [gui.Text('Zip Backup utility', size=(30, 1), font=("Helvetica", 30), text_color='blue')], [gui.Text('Create a zip backup of a file or directory.', size=(50, 1), font=("Helvetica", 18), text_color='black')], [gui.Text('-' * 200)], # Source [gui.Text('Select source folder', size=(20, 1), font=("Helvetica", 25), auto_size_text=False), gui.InputText('', key='source', font=("Helvetica", 20)), gui.FolderBrowse()], [gui.Submit(), gui.Cancel()]] button, values = form.LayoutAndRead(layout) if button == 'Submit': return values['source'] else: exit()
python
def source(self): """Parameters for saving zip backups""" with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form: layout = [ [gui.Text('Zip Backup utility', size=(30, 1), font=("Helvetica", 30), text_color='blue')], [gui.Text('Create a zip backup of a file or directory.', size=(50, 1), font=("Helvetica", 18), text_color='black')], [gui.Text('-' * 200)], # Source [gui.Text('Select source folder', size=(20, 1), font=("Helvetica", 25), auto_size_text=False), gui.InputText('', key='source', font=("Helvetica", 20)), gui.FolderBrowse()], [gui.Submit(), gui.Cancel()]] button, values = form.LayoutAndRead(layout) if button == 'Submit': return values['source'] else: exit()
[ "def", "source", "(", "self", ")", ":", "with", "gui", ".", "FlexForm", "(", "self", ".", "title", ",", "auto_size_text", "=", "True", ",", "default_element_size", "=", "(", "40", ",", "1", ")", ")", "as", "form", ":", "layout", "=", "[", "[", "gui", ".", "Text", "(", "'Zip Backup utility'", ",", "size", "=", "(", "30", ",", "1", ")", ",", "font", "=", "(", "\"Helvetica\"", ",", "30", ")", ",", "text_color", "=", "'blue'", ")", "]", ",", "[", "gui", ".", "Text", "(", "'Create a zip backup of a file or directory.'", ",", "size", "=", "(", "50", ",", "1", ")", ",", "font", "=", "(", "\"Helvetica\"", ",", "18", ")", ",", "text_color", "=", "'black'", ")", "]", ",", "[", "gui", ".", "Text", "(", "'-'", "*", "200", ")", "]", ",", "# Source", "[", "gui", ".", "Text", "(", "'Select source folder'", ",", "size", "=", "(", "20", ",", "1", ")", ",", "font", "=", "(", "\"Helvetica\"", ",", "25", ")", ",", "auto_size_text", "=", "False", ")", ",", "gui", ".", "InputText", "(", "''", ",", "key", "=", "'source'", ",", "font", "=", "(", "\"Helvetica\"", ",", "20", ")", ")", ",", "gui", ".", "FolderBrowse", "(", ")", "]", ",", "[", "gui", ".", "Submit", "(", ")", ",", "gui", ".", "Cancel", "(", ")", "]", "]", "button", ",", "values", "=", "form", ".", "LayoutAndRead", "(", "layout", ")", "if", "button", "==", "'Submit'", ":", "return", "values", "[", "'source'", "]", "else", ":", "exit", "(", ")" ]
Parameters for saving zip backups
[ "Parameters", "for", "saving", "zip", "backups" ]
339378659e2d7e09c53acfc51c5df745bb0cd517
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/gui.py#L123-L143
241,812
Pertino/pertino-sdk-python
pertinosdk/__init__.py
QueryBuilder.contains
def contains(self, desired): '''Return the filter closure fully constructed.''' field = self.__field def aFilter(testDictionary): return (desired in testDictionary[field]) return aFilter
python
def contains(self, desired): '''Return the filter closure fully constructed.''' field = self.__field def aFilter(testDictionary): return (desired in testDictionary[field]) return aFilter
[ "def", "contains", "(", "self", ",", "desired", ")", ":", "field", "=", "self", ".", "__field", "def", "aFilter", "(", "testDictionary", ")", ":", "return", "(", "desired", "in", "testDictionary", "[", "field", "]", ")", "return", "aFilter" ]
Return the filter closure fully constructed.
[ "Return", "the", "filter", "closure", "fully", "constructed", "." ]
d7d75bd374b7f44967ae6f1626a6520507be3a54
https://github.com/Pertino/pertino-sdk-python/blob/d7d75bd374b7f44967ae6f1626a6520507be3a54/pertinosdk/__init__.py#L20-L25
241,813
marccarre/py_sak
py_sak/validation.py
is_valid_file
def is_valid_file(path): ''' Returns True if provided file exists and is a file, or False otherwise. ''' return os.path.exists(path) and os.path.isfile(path)
python
def is_valid_file(path): ''' Returns True if provided file exists and is a file, or False otherwise. ''' return os.path.exists(path) and os.path.isfile(path)
[ "def", "is_valid_file", "(", "path", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "os", ".", "path", ".", "isfile", "(", "path", ")" ]
Returns True if provided file exists and is a file, or False otherwise.
[ "Returns", "True", "if", "provided", "file", "exists", "and", "is", "a", "file", "or", "False", "otherwise", "." ]
8ad4cafbd725d2700a31b50526804c0330d828dd
https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/validation.py#L42-L44
241,814
marccarre/py_sak
py_sak/validation.py
is_valid_dir
def is_valid_dir(path): ''' Returns True if provided directory exists and is a directory, or False otherwise. ''' return os.path.exists(path) and os.path.isdir(path)
python
def is_valid_dir(path): ''' Returns True if provided directory exists and is a directory, or False otherwise. ''' return os.path.exists(path) and os.path.isdir(path)
[ "def", "is_valid_dir", "(", "path", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "os", ".", "path", ".", "isdir", "(", "path", ")" ]
Returns True if provided directory exists and is a directory, or False otherwise.
[ "Returns", "True", "if", "provided", "directory", "exists", "and", "is", "a", "directory", "or", "False", "otherwise", "." ]
8ad4cafbd725d2700a31b50526804c0330d828dd
https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/validation.py#L47-L49
241,815
marccarre/py_sak
py_sak/validation.py
is_readable
def is_readable(path): ''' Returns True if provided file or directory exists and can be read with the current user. Returns False otherwise. ''' return os.access(os.path.abspath(path), os.R_OK)
python
def is_readable(path): ''' Returns True if provided file or directory exists and can be read with the current user. Returns False otherwise. ''' return os.access(os.path.abspath(path), os.R_OK)
[ "def", "is_readable", "(", "path", ")", ":", "return", "os", ".", "access", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ",", "os", ".", "R_OK", ")" ]
Returns True if provided file or directory exists and can be read with the current user. Returns False otherwise.
[ "Returns", "True", "if", "provided", "file", "or", "directory", "exists", "and", "can", "be", "read", "with", "the", "current", "user", ".", "Returns", "False", "otherwise", "." ]
8ad4cafbd725d2700a31b50526804c0330d828dd
https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/validation.py#L52-L57
241,816
jlesquembre/doc2git
doc2git/cmdline.py
run
def run(command, get_output=False, cwd=None): """By default, run all commands at GITPATH directory. If command fails, stop program execution. """ if cwd is None: cwd = GITPATH cprint('===') cprint('=== Command: ', command) cprint('=== CWD: ', cwd) cprint('===') if get_output: proc = capture_stdout(command, cwd=cwd) out = proc.stdout.read().decode() print(out, end='') check_exit_code(proc.returncode) return out else: proc = sarge_run(command, cwd=cwd) check_exit_code(proc.returncode)
python
def run(command, get_output=False, cwd=None): """By default, run all commands at GITPATH directory. If command fails, stop program execution. """ if cwd is None: cwd = GITPATH cprint('===') cprint('=== Command: ', command) cprint('=== CWD: ', cwd) cprint('===') if get_output: proc = capture_stdout(command, cwd=cwd) out = proc.stdout.read().decode() print(out, end='') check_exit_code(proc.returncode) return out else: proc = sarge_run(command, cwd=cwd) check_exit_code(proc.returncode)
[ "def", "run", "(", "command", ",", "get_output", "=", "False", ",", "cwd", "=", "None", ")", ":", "if", "cwd", "is", "None", ":", "cwd", "=", "GITPATH", "cprint", "(", "'==='", ")", "cprint", "(", "'=== Command: '", ",", "command", ")", "cprint", "(", "'=== CWD: '", ",", "cwd", ")", "cprint", "(", "'==='", ")", "if", "get_output", ":", "proc", "=", "capture_stdout", "(", "command", ",", "cwd", "=", "cwd", ")", "out", "=", "proc", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", ")", "print", "(", "out", ",", "end", "=", "''", ")", "check_exit_code", "(", "proc", ".", "returncode", ")", "return", "out", "else", ":", "proc", "=", "sarge_run", "(", "command", ",", "cwd", "=", "cwd", ")", "check_exit_code", "(", "proc", ".", "returncode", ")" ]
By default, run all commands at GITPATH directory. If command fails, stop program execution.
[ "By", "default", "run", "all", "commands", "at", "GITPATH", "directory", ".", "If", "command", "fails", "stop", "program", "execution", "." ]
9aa5b0d220ae018573375f50bb035e700e2ca56e
https://github.com/jlesquembre/doc2git/blob/9aa5b0d220ae018573375f50bb035e700e2ca56e/doc2git/cmdline.py#L85-L105
241,817
CognitionGuidedSurgery/pyclictk
clictk/argparseutil.py
build_argument_parser
def build_argument_parser(executable): """creates an argument parser from the given `executable` model. An argument '__xml__' for "--xml" is added independently. :param executable: CLI Model :type executable: clictk.model.Executable :return: """ a = ArgumentParser() a.add_argument("--xml", action="store_true", dest="__xml__", help="show cli xml") for p in executable: o = [] if p.flag: o.append("-%s" % p.flag) if p.longflag: o.append("--%s" % p.longflag) a.add_argument( *o, metavar=p.type.upper(), dest=p.name, action="store", help=(p.description.strip() or "parameter %s" % p.name) ) return a
python
def build_argument_parser(executable): """creates an argument parser from the given `executable` model. An argument '__xml__' for "--xml" is added independently. :param executable: CLI Model :type executable: clictk.model.Executable :return: """ a = ArgumentParser() a.add_argument("--xml", action="store_true", dest="__xml__", help="show cli xml") for p in executable: o = [] if p.flag: o.append("-%s" % p.flag) if p.longflag: o.append("--%s" % p.longflag) a.add_argument( *o, metavar=p.type.upper(), dest=p.name, action="store", help=(p.description.strip() or "parameter %s" % p.name) ) return a
[ "def", "build_argument_parser", "(", "executable", ")", ":", "a", "=", "ArgumentParser", "(", ")", "a", ".", "add_argument", "(", "\"--xml\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"__xml__\"", ",", "help", "=", "\"show cli xml\"", ")", "for", "p", "in", "executable", ":", "o", "=", "[", "]", "if", "p", ".", "flag", ":", "o", ".", "append", "(", "\"-%s\"", "%", "p", ".", "flag", ")", "if", "p", ".", "longflag", ":", "o", ".", "append", "(", "\"--%s\"", "%", "p", ".", "longflag", ")", "a", ".", "add_argument", "(", "*", "o", ",", "metavar", "=", "p", ".", "type", ".", "upper", "(", ")", ",", "dest", "=", "p", ".", "name", ",", "action", "=", "\"store\"", ",", "help", "=", "(", "p", ".", "description", ".", "strip", "(", ")", "or", "\"parameter %s\"", "%", "p", ".", "name", ")", ")", "return", "a" ]
creates an argument parser from the given `executable` model. An argument '__xml__' for "--xml" is added independently. :param executable: CLI Model :type executable: clictk.model.Executable :return:
[ "creates", "an", "argument", "parser", "from", "the", "given", "executable", "model", "." ]
74915098a24a33adb46d8738f9c4746d91ecc1dc
https://github.com/CognitionGuidedSurgery/pyclictk/blob/74915098a24a33adb46d8738f9c4746d91ecc1dc/clictk/argparseutil.py#L13-L38
241,818
the01/python-paps
paps/person.py
Person.from_dict
def from_dict(self, d): """ Set this person from dict :param d: Dictionary representing a person ('sitting'[, 'id']) :type d: dict :rtype: Person :raises KeyError: 'sitting' not set """ self.sitting = d['sitting'] self.id = d.get('id', None) return self
python
def from_dict(self, d): """ Set this person from dict :param d: Dictionary representing a person ('sitting'[, 'id']) :type d: dict :rtype: Person :raises KeyError: 'sitting' not set """ self.sitting = d['sitting'] self.id = d.get('id', None) return self
[ "def", "from_dict", "(", "self", ",", "d", ")", ":", "self", ".", "sitting", "=", "d", "[", "'sitting'", "]", "self", ".", "id", "=", "d", ".", "get", "(", "'id'", ",", "None", ")", "return", "self" ]
Set this person from dict :param d: Dictionary representing a person ('sitting'[, 'id']) :type d: dict :rtype: Person :raises KeyError: 'sitting' not set
[ "Set", "this", "person", "from", "dict" ]
2dde5a71913e4c7b22901cf05c6ecedd890919c4
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/person.py#L53-L64
241,819
the01/python-paps
paps/person.py
Person.from_tuple
def from_tuple(self, t): """ Set this person from tuple :param t: Tuple representing a person (sitting[, id]) :type t: (bool) | (bool, None | str | unicode | int) :rtype: Person """ if len(t) > 1: self.id = t[0] self.sitting = t[1] else: self.sitting = t[0] self.id = None return self
python
def from_tuple(self, t): """ Set this person from tuple :param t: Tuple representing a person (sitting[, id]) :type t: (bool) | (bool, None | str | unicode | int) :rtype: Person """ if len(t) > 1: self.id = t[0] self.sitting = t[1] else: self.sitting = t[0] self.id = None return self
[ "def", "from_tuple", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", ">", "1", ":", "self", ".", "id", "=", "t", "[", "0", "]", "self", ".", "sitting", "=", "t", "[", "1", "]", "else", ":", "self", ".", "sitting", "=", "t", "[", "0", "]", "self", ".", "id", "=", "None", "return", "self" ]
Set this person from tuple :param t: Tuple representing a person (sitting[, id]) :type t: (bool) | (bool, None | str | unicode | int) :rtype: Person
[ "Set", "this", "person", "from", "tuple" ]
2dde5a71913e4c7b22901cf05c6ecedd890919c4
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/person.py#L75-L89
241,820
hobson/pug-dj
pug/dj/explore.py
meta_bar_chart
def meta_bar_chart(series=None, N=20): "Each column in the series is a dict of dicts" if not series or isinstance(series, basestring): series = json.load(load_app_meta) if isinstance(series, Mapping) and isinstance(series.values()[0], Mapping): rows_received = series['# Received'].items() elif isinstance(series, Mapping): rows_received = series.items() else: rows_received = list(series) #rows = sorted(rows, key=operator.itemgetter(1), reverse=True) rows = sorted(rows_received, key=lambda x: x[1], reverse=True) received_names, received_qty = zip(*rows) ra_qty = [(series['Qty in RA'].get(name, 0.) or 0.) for name in received_names] # percent = [100. - 100. * (num or 0.) / (den or 1.) for num, den in zip(received_qty, ra_qty)] # only care about the top 30 model numbers in terms of quantity #ind = range(N) figs = [] figs += [plt.figure()] ax = figs[-1].add_subplot(111) ax.set_ylabel('# Units Returned') ax.set_title('Most-Returned LCDTV Models 2013-present') x = np.arange(N) bars1 = ax.bar(x, received_qty[:N], color='b', width=.4, log=1) bars2 = ax.bar(x+.4, ra_qty[:N], color='g', width=.4, log=1) ax.set_xticks(range(N)) ax.set_xticklabels(received_names[:N], rotation=35) ax.grid(True) ax.legend((bars1[0], bars2[0]), ('# in RA', '# Received'), 'center right') figs[-1].show()
python
def meta_bar_chart(series=None, N=20): "Each column in the series is a dict of dicts" if not series or isinstance(series, basestring): series = json.load(load_app_meta) if isinstance(series, Mapping) and isinstance(series.values()[0], Mapping): rows_received = series['# Received'].items() elif isinstance(series, Mapping): rows_received = series.items() else: rows_received = list(series) #rows = sorted(rows, key=operator.itemgetter(1), reverse=True) rows = sorted(rows_received, key=lambda x: x[1], reverse=True) received_names, received_qty = zip(*rows) ra_qty = [(series['Qty in RA'].get(name, 0.) or 0.) for name in received_names] # percent = [100. - 100. * (num or 0.) / (den or 1.) for num, den in zip(received_qty, ra_qty)] # only care about the top 30 model numbers in terms of quantity #ind = range(N) figs = [] figs += [plt.figure()] ax = figs[-1].add_subplot(111) ax.set_ylabel('# Units Returned') ax.set_title('Most-Returned LCDTV Models 2013-present') x = np.arange(N) bars1 = ax.bar(x, received_qty[:N], color='b', width=.4, log=1) bars2 = ax.bar(x+.4, ra_qty[:N], color='g', width=.4, log=1) ax.set_xticks(range(N)) ax.set_xticklabels(received_names[:N], rotation=35) ax.grid(True) ax.legend((bars1[0], bars2[0]), ('# in RA', '# Received'), 'center right') figs[-1].show()
[ "def", "meta_bar_chart", "(", "series", "=", "None", ",", "N", "=", "20", ")", ":", "if", "not", "series", "or", "isinstance", "(", "series", ",", "basestring", ")", ":", "series", "=", "json", ".", "load", "(", "load_app_meta", ")", "if", "isinstance", "(", "series", ",", "Mapping", ")", "and", "isinstance", "(", "series", ".", "values", "(", ")", "[", "0", "]", ",", "Mapping", ")", ":", "rows_received", "=", "series", "[", "'# Received'", "]", ".", "items", "(", ")", "elif", "isinstance", "(", "series", ",", "Mapping", ")", ":", "rows_received", "=", "series", ".", "items", "(", ")", "else", ":", "rows_received", "=", "list", "(", "series", ")", "#rows = sorted(rows, key=operator.itemgetter(1), reverse=True)", "rows", "=", "sorted", "(", "rows_received", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ")", "received_names", ",", "received_qty", "=", "zip", "(", "*", "rows", ")", "ra_qty", "=", "[", "(", "series", "[", "'Qty in RA'", "]", ".", "get", "(", "name", ",", "0.", ")", "or", "0.", ")", "for", "name", "in", "received_names", "]", "# percent = [100. - 100. * (num or 0.) / (den or 1.) for num, den in zip(received_qty, ra_qty)]", "# only care about the top 30 model numbers in terms of quantity", "#ind = range(N)", "figs", "=", "[", "]", "figs", "+=", "[", "plt", ".", "figure", "(", ")", "]", "ax", "=", "figs", "[", "-", "1", "]", ".", "add_subplot", "(", "111", ")", "ax", ".", "set_ylabel", "(", "'# Units Returned'", ")", "ax", ".", "set_title", "(", "'Most-Returned LCDTV Models 2013-present'", ")", "x", "=", "np", ".", "arange", "(", "N", ")", "bars1", "=", "ax", ".", "bar", "(", "x", ",", "received_qty", "[", ":", "N", "]", ",", "color", "=", "'b'", ",", "width", "=", ".4", ",", "log", "=", "1", ")", "bars2", "=", "ax", ".", "bar", "(", "x", "+", ".4", ",", "ra_qty", "[", ":", "N", "]", ",", "color", "=", "'g'", ",", "width", "=", ".4", ",", "log", "=", "1", ")", "ax", ".", "set_xticks", "(", "range", "(", "N", ")", ")", "ax", ".", "set_xticklabels", "(", "received_names", "[", ":", "N", "]", ",", "rotation", "=", "35", ")", "ax", ".", "grid", "(", "True", ")", "ax", ".", "legend", "(", "(", "bars1", "[", "0", "]", ",", "bars2", "[", "0", "]", ")", ",", "(", "'# in RA'", ",", "'# Received'", ")", ",", "'center right'", ")", "figs", "[", "-", "1", "]", ".", "show", "(", ")" ]
Each column in the series is a dict of dicts
[ "Each", "column", "in", "the", "series", "is", "a", "dict", "of", "dicts" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L105-L138
241,821
hobson/pug-dj
pug/dj/explore.py
index_with_dupes
def index_with_dupes(values_list, unique_together=2, model_number_i=0, serial_number_i=1, verbosity=1): '''Create dict from values_list with first N values as a compound key. Default N (number of columns assumbed to be "unique_together") is 2. >>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == ({(1, 2): (1, 2, 3), (2, 1): (2, 1, 3), (5, 6): (5, 6, 7)}, {(5, 6): [(5, 6, 7), (5, 6, 8)]}) True ''' try: N = values_list.count() except: N = len(values_list) if verbosity > 0: print 'Indexing %d values_lists in a queryset or a sequence of Django model instances (database table rows).' % N index, dupes = {}, {} pbar = None if verbosity and N > min(1000000, max(0, 100000**(1./verbosity))): widgets = [pb.Counter(), '%d rows: ' % N, pb.Percentage(), ' ', pb.RotatingMarker(), ' ', pb.Bar(),' ', pb.ETA()] pbar = pb.ProgressBar(widgets=widgets, maxval=N).start() rownum = 0 for row in values_list: normalized_key = [str(row[model_number_i]).strip(), str(row[serial_number_i]).strip()] normalized_key += [i for i in range(unique_together) if i not in (serial_number_i, model_number_i)] normalized_key = tuple(normalized_key) if normalized_key in index: # need to add the first nondupe before we add the dupes to the list if normalized_key not in dupes: dupes[normalized_key] = [index[normalized_key]] dupes[normalized_key] = dupes[normalized_key] + [row] if verbosity > 2: print 'Duplicate "unique_together" tuple found. Here are all the rows that match this key:' print dupes[normalized_key] else: index[normalized_key] = row if pbar: pbar.update(rownum) rownum += 1 if pbar: pbar.finish() if verbosity > 0: print 'Found %d duplicate model-serial pairs in the %d records or %g%%' % (len(dupes), len(index), len(dupes)*100./(len(index) or 1.)) return index, dupes
python
def index_with_dupes(values_list, unique_together=2, model_number_i=0, serial_number_i=1, verbosity=1): '''Create dict from values_list with first N values as a compound key. Default N (number of columns assumbed to be "unique_together") is 2. >>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == ({(1, 2): (1, 2, 3), (2, 1): (2, 1, 3), (5, 6): (5, 6, 7)}, {(5, 6): [(5, 6, 7), (5, 6, 8)]}) True ''' try: N = values_list.count() except: N = len(values_list) if verbosity > 0: print 'Indexing %d values_lists in a queryset or a sequence of Django model instances (database table rows).' % N index, dupes = {}, {} pbar = None if verbosity and N > min(1000000, max(0, 100000**(1./verbosity))): widgets = [pb.Counter(), '%d rows: ' % N, pb.Percentage(), ' ', pb.RotatingMarker(), ' ', pb.Bar(),' ', pb.ETA()] pbar = pb.ProgressBar(widgets=widgets, maxval=N).start() rownum = 0 for row in values_list: normalized_key = [str(row[model_number_i]).strip(), str(row[serial_number_i]).strip()] normalized_key += [i for i in range(unique_together) if i not in (serial_number_i, model_number_i)] normalized_key = tuple(normalized_key) if normalized_key in index: # need to add the first nondupe before we add the dupes to the list if normalized_key not in dupes: dupes[normalized_key] = [index[normalized_key]] dupes[normalized_key] = dupes[normalized_key] + [row] if verbosity > 2: print 'Duplicate "unique_together" tuple found. Here are all the rows that match this key:' print dupes[normalized_key] else: index[normalized_key] = row if pbar: pbar.update(rownum) rownum += 1 if pbar: pbar.finish() if verbosity > 0: print 'Found %d duplicate model-serial pairs in the %d records or %g%%' % (len(dupes), len(index), len(dupes)*100./(len(index) or 1.)) return index, dupes
[ "def", "index_with_dupes", "(", "values_list", ",", "unique_together", "=", "2", ",", "model_number_i", "=", "0", ",", "serial_number_i", "=", "1", ",", "verbosity", "=", "1", ")", ":", "try", ":", "N", "=", "values_list", ".", "count", "(", ")", "except", ":", "N", "=", "len", "(", "values_list", ")", "if", "verbosity", ">", "0", ":", "print", "'Indexing %d values_lists in a queryset or a sequence of Django model instances (database table rows).'", "%", "N", "index", ",", "dupes", "=", "{", "}", ",", "{", "}", "pbar", "=", "None", "if", "verbosity", "and", "N", ">", "min", "(", "1000000", ",", "max", "(", "0", ",", "100000", "**", "(", "1.", "/", "verbosity", ")", ")", ")", ":", "widgets", "=", "[", "pb", ".", "Counter", "(", ")", ",", "'%d rows: '", "%", "N", ",", "pb", ".", "Percentage", "(", ")", ",", "' '", ",", "pb", ".", "RotatingMarker", "(", ")", ",", "' '", ",", "pb", ".", "Bar", "(", ")", ",", "' '", ",", "pb", ".", "ETA", "(", ")", "]", "pbar", "=", "pb", ".", "ProgressBar", "(", "widgets", "=", "widgets", ",", "maxval", "=", "N", ")", ".", "start", "(", ")", "rownum", "=", "0", "for", "row", "in", "values_list", ":", "normalized_key", "=", "[", "str", "(", "row", "[", "model_number_i", "]", ")", ".", "strip", "(", ")", ",", "str", "(", "row", "[", "serial_number_i", "]", ")", ".", "strip", "(", ")", "]", "normalized_key", "+=", "[", "i", "for", "i", "in", "range", "(", "unique_together", ")", "if", "i", "not", "in", "(", "serial_number_i", ",", "model_number_i", ")", "]", "normalized_key", "=", "tuple", "(", "normalized_key", ")", "if", "normalized_key", "in", "index", ":", "# need to add the first nondupe before we add the dupes to the list", "if", "normalized_key", "not", "in", "dupes", ":", "dupes", "[", "normalized_key", "]", "=", "[", "index", "[", "normalized_key", "]", "]", "dupes", "[", "normalized_key", "]", "=", "dupes", "[", "normalized_key", "]", "+", "[", "row", "]", "if", "verbosity", ">", "2", ":", "print", "'Duplicate \"unique_together\" tuple found. Here are all the rows that match this key:'", "print", "dupes", "[", "normalized_key", "]", "else", ":", "index", "[", "normalized_key", "]", "=", "row", "if", "pbar", ":", "pbar", ".", "update", "(", "rownum", ")", "rownum", "+=", "1", "if", "pbar", ":", "pbar", ".", "finish", "(", ")", "if", "verbosity", ">", "0", ":", "print", "'Found %d duplicate model-serial pairs in the %d records or %g%%'", "%", "(", "len", "(", "dupes", ")", ",", "len", "(", "index", ")", ",", "len", "(", "dupes", ")", "*", "100.", "/", "(", "len", "(", "index", ")", "or", "1.", ")", ")", "return", "index", ",", "dupes" ]
Create dict from values_list with first N values as a compound key. Default N (number of columns assumbed to be "unique_together") is 2. >>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == ({(1, 2): (1, 2, 3), (2, 1): (2, 1, 3), (5, 6): (5, 6, 7)}, {(5, 6): [(5, 6, 7), (5, 6, 8)]}) True
[ "Create", "dict", "from", "values_list", "with", "first", "N", "values", "as", "a", "compound", "key", "." ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L421-L461
241,822
hobson/pug-dj
pug/dj/explore.py
index_model_field_batches
def index_model_field_batches(model_or_queryset, key_fields=['model_number', 'serial_number'], value_fields=['pk'], key_formatter=lambda x: str.lstrip(str.strip(str(x or '')), '0'), value_formatter=lambda x: str.strip(str(x)), batch_len=10000, limit=100000000, verbosity=1): '''Like index_model_field except uses 50x less memory and 10x more processing cycles Returns 2 dicts where both the keys and values are tuples: target_index = {(<key_fields[0]>, <key_fields[1]>, ...): (<value_fields[0]>,)} for all distinct model-serial pairs in the Sales queryset target_dupes = {(<key_fields[0]>, <key_fields[1]>, ...): [(<value_fields[1]>,), (<value_fields[2]>,), ...]} with all the duplicates except the first pk already listed above ''' qs = djdb.get_queryset(model_or_queryset) N = qs.count() if verbosity > 0: print 'Indexing %d rows (database records) to aid in finding record %r values using the field %r.' % (N, value_fields, key_fields) index, dupes, rownum = {}, {}, 0 pbar, rownum = None, 0 if verbosity and N > min(1000000, max(0, 100000**(1./verbosity))): widgets = [pb.Counter(), '/%d rows: ' % N, pb.Percentage(), ' ', pb.RotatingMarker(), ' ', pb.Bar(),' ', pb.ETA()] pbar = pb.ProgressBar(widgets=widgets, maxval=N).start() # to determine the type of the field value and decide whether to strip() or normalize in any way #obj0 = qs.filter(**{field + '__isnull': False}).all()[0] value_fields = util.listify(value_fields) key_fields = util.listify(key_fields) for batch in djdb.generate_queryset_batches(qs, batch_len=batch_len, verbosity=verbosity): for obj in batch: # print obj # normalize the key keys = [] for kf in key_fields: k = getattr(obj, kf) keys += [key_formatter(k or '')] values = [] keys = tuple(keys) for vf in value_fields: v = getattr(obj, vf) values += [value_formatter(v or '')] values = tuple(values) if keys in index: dupes[keys] = dupes.get(keys, []) + [values] else: index[keys] = values # print rownum / float(N) if pbar: pbar.update(rownum) rownum += 1 if rownum >= limit: break if pbar: pbar.finish() if verbosity > 0: print 'Found %d duplicate %s values among the %d records or %g%%' % (len(dupes), key_fields, len(index), len(dupes)*100./(len(index) or 1.)) return index, dupes
python
def index_model_field_batches(model_or_queryset, key_fields=['model_number', 'serial_number'], value_fields=['pk'], key_formatter=lambda x: str.lstrip(str.strip(str(x or '')), '0'), value_formatter=lambda x: str.strip(str(x)), batch_len=10000, limit=100000000, verbosity=1): '''Like index_model_field except uses 50x less memory and 10x more processing cycles Returns 2 dicts where both the keys and values are tuples: target_index = {(<key_fields[0]>, <key_fields[1]>, ...): (<value_fields[0]>,)} for all distinct model-serial pairs in the Sales queryset target_dupes = {(<key_fields[0]>, <key_fields[1]>, ...): [(<value_fields[1]>,), (<value_fields[2]>,), ...]} with all the duplicates except the first pk already listed above ''' qs = djdb.get_queryset(model_or_queryset) N = qs.count() if verbosity > 0: print 'Indexing %d rows (database records) to aid in finding record %r values using the field %r.' % (N, value_fields, key_fields) index, dupes, rownum = {}, {}, 0 pbar, rownum = None, 0 if verbosity and N > min(1000000, max(0, 100000**(1./verbosity))): widgets = [pb.Counter(), '/%d rows: ' % N, pb.Percentage(), ' ', pb.RotatingMarker(), ' ', pb.Bar(),' ', pb.ETA()] pbar = pb.ProgressBar(widgets=widgets, maxval=N).start() # to determine the type of the field value and decide whether to strip() or normalize in any way #obj0 = qs.filter(**{field + '__isnull': False}).all()[0] value_fields = util.listify(value_fields) key_fields = util.listify(key_fields) for batch in djdb.generate_queryset_batches(qs, batch_len=batch_len, verbosity=verbosity): for obj in batch: # print obj # normalize the key keys = [] for kf in key_fields: k = getattr(obj, kf) keys += [key_formatter(k or '')] values = [] keys = tuple(keys) for vf in value_fields: v = getattr(obj, vf) values += [value_formatter(v or '')] values = tuple(values) if keys in index: dupes[keys] = dupes.get(keys, []) + [values] else: index[keys] = values # print rownum / float(N) if pbar: pbar.update(rownum) rownum += 1 if rownum >= limit: break if pbar: pbar.finish() if verbosity > 0: print 'Found %d duplicate %s values among the %d records or %g%%' % (len(dupes), key_fields, len(index), len(dupes)*100./(len(index) or 1.)) return index, dupes
[ "def", "index_model_field_batches", "(", "model_or_queryset", ",", "key_fields", "=", "[", "'model_number'", ",", "'serial_number'", "]", ",", "value_fields", "=", "[", "'pk'", "]", ",", "key_formatter", "=", "lambda", "x", ":", "str", ".", "lstrip", "(", "str", ".", "strip", "(", "str", "(", "x", "or", "''", ")", ")", ",", "'0'", ")", ",", "value_formatter", "=", "lambda", "x", ":", "str", ".", "strip", "(", "str", "(", "x", ")", ")", ",", "batch_len", "=", "10000", ",", "limit", "=", "100000000", ",", "verbosity", "=", "1", ")", ":", "qs", "=", "djdb", ".", "get_queryset", "(", "model_or_queryset", ")", "N", "=", "qs", ".", "count", "(", ")", "if", "verbosity", ">", "0", ":", "print", "'Indexing %d rows (database records) to aid in finding record %r values using the field %r.'", "%", "(", "N", ",", "value_fields", ",", "key_fields", ")", "index", ",", "dupes", ",", "rownum", "=", "{", "}", ",", "{", "}", ",", "0", "pbar", ",", "rownum", "=", "None", ",", "0", "if", "verbosity", "and", "N", ">", "min", "(", "1000000", ",", "max", "(", "0", ",", "100000", "**", "(", "1.", "/", "verbosity", ")", ")", ")", ":", "widgets", "=", "[", "pb", ".", "Counter", "(", ")", ",", "'/%d rows: '", "%", "N", ",", "pb", ".", "Percentage", "(", ")", ",", "' '", ",", "pb", ".", "RotatingMarker", "(", ")", ",", "' '", ",", "pb", ".", "Bar", "(", ")", ",", "' '", ",", "pb", ".", "ETA", "(", ")", "]", "pbar", "=", "pb", ".", "ProgressBar", "(", "widgets", "=", "widgets", ",", "maxval", "=", "N", ")", ".", "start", "(", ")", "# to determine the type of the field value and decide whether to strip() or normalize in any way", "#obj0 = qs.filter(**{field + '__isnull': False}).all()[0]", "value_fields", "=", "util", ".", "listify", "(", "value_fields", ")", "key_fields", "=", "util", ".", "listify", "(", "key_fields", ")", "for", "batch", "in", "djdb", ".", "generate_queryset_batches", "(", "qs", ",", "batch_len", "=", "batch_len", ",", "verbosity", "=", "verbosity", ")", ":", "for", "obj", "in", "batch", ":", "# print obj", "# normalize the key", "keys", "=", "[", "]", "for", "kf", "in", "key_fields", ":", "k", "=", "getattr", "(", "obj", ",", "kf", ")", "keys", "+=", "[", "key_formatter", "(", "k", "or", "''", ")", "]", "values", "=", "[", "]", "keys", "=", "tuple", "(", "keys", ")", "for", "vf", "in", "value_fields", ":", "v", "=", "getattr", "(", "obj", ",", "vf", ")", "values", "+=", "[", "value_formatter", "(", "v", "or", "''", ")", "]", "values", "=", "tuple", "(", "values", ")", "if", "keys", "in", "index", ":", "dupes", "[", "keys", "]", "=", "dupes", ".", "get", "(", "keys", ",", "[", "]", ")", "+", "[", "values", "]", "else", ":", "index", "[", "keys", "]", "=", "values", "# print rownum / float(N)", "if", "pbar", ":", "pbar", ".", "update", "(", "rownum", ")", "rownum", "+=", "1", "if", "rownum", ">=", "limit", ":", "break", "if", "pbar", ":", "pbar", ".", "finish", "(", ")", "if", "verbosity", ">", "0", ":", "print", "'Found %d duplicate %s values among the %d records or %g%%'", "%", "(", "len", "(", "dupes", ")", ",", "key_fields", ",", "len", "(", "index", ")", ",", "len", "(", "dupes", ")", "*", "100.", "/", "(", "len", "(", "index", ")", "or", "1.", ")", ")", "return", "index", ",", "dupes" ]
Like index_model_field except uses 50x less memory and 10x more processing cycles Returns 2 dicts where both the keys and values are tuples: target_index = {(<key_fields[0]>, <key_fields[1]>, ...): (<value_fields[0]>,)} for all distinct model-serial pairs in the Sales queryset target_dupes = {(<key_fields[0]>, <key_fields[1]>, ...): [(<value_fields[1]>,), (<value_fields[2]>,), ...]} with all the duplicates except the first pk already listed above
[ "Like", "index_model_field", "except", "uses", "50x", "less", "memory", "and", "10x", "more", "processing", "cycles" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L516-L577
241,823
hobson/pug-dj
pug/dj/explore.py
find_index
def find_index(model_meta, weights=None, verbosity=0): """Return a tuple of index metadata for the model metadata dict provided return value format is: ( field_name, { 'primary_key': boolean representing whether it's the primary key, 'unique': boolean representing whether it's a unique index }, score, ) """ weights = weights or find_index.default_weights N = model_meta['Meta'].get('count', 0) for field_name, field_meta in model_meta.iteritems(): if field_name == 'Meta': continue pkfield = field_meta.get('primary_key') if pkfield: if verbosity > 1: print pkfield # TODO: Allow more than one index per model/table return { field_name: { 'primary_key': True, 'unique': field_meta.get('unique') or ( N >= 3 and field_meta.get('num_null') <= 1 and field_meta.get('num_distinct') == N), }} score_names = [] for field_name, field_meta in model_meta.iteritems(): score = 0 for feature, weight in weights: # for categorical features (strings), need to look for a particular value value = field_meta.get(feature) if isinstance(weight, tuple): if value is not None and value in (float, int): score += weight * value if callable(weight[1]): score += weight[0] * weight[1](field_meta.get(feature)) else: score += weight[0] * (field_meta.get(feature) == weight[1]) else: feature_value = field_meta.get(feature) if feature_value is not None: score += weight * field_meta.get(feature) score_names += [(score, field_name)] max_name = max(score_names) field_meta = model_meta[max_name[1]] return ( max_name[1], { 'primary_key': True, 'unique': field_meta.get('unique') or ( N >= 3 and field_meta.get('num_null') <= 1 and field_meta.get('num_distinct') == N), }, max_name[0], )
python
def find_index(model_meta, weights=None, verbosity=0): """Return a tuple of index metadata for the model metadata dict provided return value format is: ( field_name, { 'primary_key': boolean representing whether it's the primary key, 'unique': boolean representing whether it's a unique index }, score, ) """ weights = weights or find_index.default_weights N = model_meta['Meta'].get('count', 0) for field_name, field_meta in model_meta.iteritems(): if field_name == 'Meta': continue pkfield = field_meta.get('primary_key') if pkfield: if verbosity > 1: print pkfield # TODO: Allow more than one index per model/table return { field_name: { 'primary_key': True, 'unique': field_meta.get('unique') or ( N >= 3 and field_meta.get('num_null') <= 1 and field_meta.get('num_distinct') == N), }} score_names = [] for field_name, field_meta in model_meta.iteritems(): score = 0 for feature, weight in weights: # for categorical features (strings), need to look for a particular value value = field_meta.get(feature) if isinstance(weight, tuple): if value is not None and value in (float, int): score += weight * value if callable(weight[1]): score += weight[0] * weight[1](field_meta.get(feature)) else: score += weight[0] * (field_meta.get(feature) == weight[1]) else: feature_value = field_meta.get(feature) if feature_value is not None: score += weight * field_meta.get(feature) score_names += [(score, field_name)] max_name = max(score_names) field_meta = model_meta[max_name[1]] return ( max_name[1], { 'primary_key': True, 'unique': field_meta.get('unique') or ( N >= 3 and field_meta.get('num_null') <= 1 and field_meta.get('num_distinct') == N), }, max_name[0], )
[ "def", "find_index", "(", "model_meta", ",", "weights", "=", "None", ",", "verbosity", "=", "0", ")", ":", "weights", "=", "weights", "or", "find_index", ".", "default_weights", "N", "=", "model_meta", "[", "'Meta'", "]", ".", "get", "(", "'count'", ",", "0", ")", "for", "field_name", ",", "field_meta", "in", "model_meta", ".", "iteritems", "(", ")", ":", "if", "field_name", "==", "'Meta'", ":", "continue", "pkfield", "=", "field_meta", ".", "get", "(", "'primary_key'", ")", "if", "pkfield", ":", "if", "verbosity", ">", "1", ":", "print", "pkfield", "# TODO: Allow more than one index per model/table", "return", "{", "field_name", ":", "{", "'primary_key'", ":", "True", ",", "'unique'", ":", "field_meta", ".", "get", "(", "'unique'", ")", "or", "(", "N", ">=", "3", "and", "field_meta", ".", "get", "(", "'num_null'", ")", "<=", "1", "and", "field_meta", ".", "get", "(", "'num_distinct'", ")", "==", "N", ")", ",", "}", "}", "score_names", "=", "[", "]", "for", "field_name", ",", "field_meta", "in", "model_meta", ".", "iteritems", "(", ")", ":", "score", "=", "0", "for", "feature", ",", "weight", "in", "weights", ":", "# for categorical features (strings), need to look for a particular value", "value", "=", "field_meta", ".", "get", "(", "feature", ")", "if", "isinstance", "(", "weight", ",", "tuple", ")", ":", "if", "value", "is", "not", "None", "and", "value", "in", "(", "float", ",", "int", ")", ":", "score", "+=", "weight", "*", "value", "if", "callable", "(", "weight", "[", "1", "]", ")", ":", "score", "+=", "weight", "[", "0", "]", "*", "weight", "[", "1", "]", "(", "field_meta", ".", "get", "(", "feature", ")", ")", "else", ":", "score", "+=", "weight", "[", "0", "]", "*", "(", "field_meta", ".", "get", "(", "feature", ")", "==", "weight", "[", "1", "]", ")", "else", ":", "feature_value", "=", "field_meta", ".", "get", "(", "feature", ")", "if", "feature_value", "is", "not", "None", ":", "score", "+=", "weight", "*", "field_meta", ".", "get", "(", "feature", ")", "score_names", "+=", "[", "(", "score", ",", "field_name", ")", "]", "max_name", "=", "max", "(", "score_names", ")", "field_meta", "=", "model_meta", "[", "max_name", "[", "1", "]", "]", "return", "(", "max_name", "[", "1", "]", ",", "{", "'primary_key'", ":", "True", ",", "'unique'", ":", "field_meta", ".", "get", "(", "'unique'", ")", "or", "(", "N", ">=", "3", "and", "field_meta", ".", "get", "(", "'num_null'", ")", "<=", "1", "and", "field_meta", ".", "get", "(", "'num_distinct'", ")", "==", "N", ")", ",", "}", ",", "max_name", "[", "0", "]", ",", ")" ]
Return a tuple of index metadata for the model metadata dict provided return value format is: ( field_name, { 'primary_key': boolean representing whether it's the primary key, 'unique': boolean representing whether it's a unique index }, score, )
[ "Return", "a", "tuple", "of", "index", "metadata", "for", "the", "model", "metadata", "dict", "provided" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L580-L641
241,824
hobson/pug-dj
pug/dj/explore.py
count_unique
def count_unique(table, field=-1): """Use the Django ORM or collections.Counter to count unique values of a field in a table `table` is one of: 1. An iterable of Django model instances for a database table (e.g. a Django queryset) 2. An iterable of dicts or lists with elements accessed by row[field] where field can be an integer or string 3. An iterable of objects or namedtuples with elements accessed by `row.field` `field` can be any immutable object (the key or index in a row of the table that access the value to be counted) """ from collections import Counter # try/except only happens once, and fastest route (straight to db) tried first try: ans = {} for row in table.distinct().values(field).annotate(field_value_count=models.Count(field)): ans[row[field]] = row['field_value_count'] return ans except: try: return Counter(row[field] for row in table) except: try: return Counter(row.get(field, None) for row in table) except: try: return Counter(row.getattr(field, None) for row in table) except: pass
python
def count_unique(table, field=-1): """Use the Django ORM or collections.Counter to count unique values of a field in a table `table` is one of: 1. An iterable of Django model instances for a database table (e.g. a Django queryset) 2. An iterable of dicts or lists with elements accessed by row[field] where field can be an integer or string 3. An iterable of objects or namedtuples with elements accessed by `row.field` `field` can be any immutable object (the key or index in a row of the table that access the value to be counted) """ from collections import Counter # try/except only happens once, and fastest route (straight to db) tried first try: ans = {} for row in table.distinct().values(field).annotate(field_value_count=models.Count(field)): ans[row[field]] = row['field_value_count'] return ans except: try: return Counter(row[field] for row in table) except: try: return Counter(row.get(field, None) for row in table) except: try: return Counter(row.getattr(field, None) for row in table) except: pass
[ "def", "count_unique", "(", "table", ",", "field", "=", "-", "1", ")", ":", "from", "collections", "import", "Counter", "# try/except only happens once, and fastest route (straight to db) tried first", "try", ":", "ans", "=", "{", "}", "for", "row", "in", "table", ".", "distinct", "(", ")", ".", "values", "(", "field", ")", ".", "annotate", "(", "field_value_count", "=", "models", ".", "Count", "(", "field", ")", ")", ":", "ans", "[", "row", "[", "field", "]", "]", "=", "row", "[", "'field_value_count'", "]", "return", "ans", "except", ":", "try", ":", "return", "Counter", "(", "row", "[", "field", "]", "for", "row", "in", "table", ")", "except", ":", "try", ":", "return", "Counter", "(", "row", ".", "get", "(", "field", ",", "None", ")", "for", "row", "in", "table", ")", "except", ":", "try", ":", "return", "Counter", "(", "row", ".", "getattr", "(", "field", ",", "None", ")", "for", "row", "in", "table", ")", "except", ":", "pass" ]
Use the Django ORM or collections.Counter to count unique values of a field in a table `table` is one of: 1. An iterable of Django model instances for a database table (e.g. a Django queryset) 2. An iterable of dicts or lists with elements accessed by row[field] where field can be an integer or string 3. An iterable of objects or namedtuples with elements accessed by `row.field` `field` can be any immutable object (the key or index in a row of the table that access the value to be counted)
[ "Use", "the", "Django", "ORM", "or", "collections", ".", "Counter", "to", "count", "unique", "values", "of", "a", "field", "in", "a", "table" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L913-L941
241,825
ttm/participationLegacy
participation/triplification/participaTriplification.py
ParticipaTriplification.startGraph
def startGraph(self): """Starts RDF graph and bing namespaces""" g = r.Graph() g.namespace_manager.bind("rdf", r.namespace.RDF) g.namespace_manager.bind("foaf", r.namespace.FOAF) g.namespace_manager.bind("xsd", r.namespace.XSD) g.namespace_manager.bind("opa", "http://purl.org/socialparticipation/opa/") g.namespace_manager.bind("ops", "http://purl.org/socialparticipation/ops/") g.namespace_manager.bind("wsg", "http://www.w3.org/2003/01/geo/wgs84_pos#") g.namespace_manager.bind("dc2", "http://purl.org/dc/elements/1.1/") g.namespace_manager.bind("dc", "http://purl.org/dc/terms/") g.namespace_manager.bind("sioc", "http://rdfs.org/sioc/ns#") g.namespace_manager.bind("tsioc", "http://rdfs.org/sioc/types#") g.namespace_manager.bind("schema", "http://schema.org/") g.namespace_manager.bind("part", "http://participa.br/") self.g=g
python
def startGraph(self): """Starts RDF graph and bing namespaces""" g = r.Graph() g.namespace_manager.bind("rdf", r.namespace.RDF) g.namespace_manager.bind("foaf", r.namespace.FOAF) g.namespace_manager.bind("xsd", r.namespace.XSD) g.namespace_manager.bind("opa", "http://purl.org/socialparticipation/opa/") g.namespace_manager.bind("ops", "http://purl.org/socialparticipation/ops/") g.namespace_manager.bind("wsg", "http://www.w3.org/2003/01/geo/wgs84_pos#") g.namespace_manager.bind("dc2", "http://purl.org/dc/elements/1.1/") g.namespace_manager.bind("dc", "http://purl.org/dc/terms/") g.namespace_manager.bind("sioc", "http://rdfs.org/sioc/ns#") g.namespace_manager.bind("tsioc", "http://rdfs.org/sioc/types#") g.namespace_manager.bind("schema", "http://schema.org/") g.namespace_manager.bind("part", "http://participa.br/") self.g=g
[ "def", "startGraph", "(", "self", ")", ":", "g", "=", "r", ".", "Graph", "(", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"rdf\"", ",", "r", ".", "namespace", ".", "RDF", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"foaf\"", ",", "r", ".", "namespace", ".", "FOAF", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"xsd\"", ",", "r", ".", "namespace", ".", "XSD", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"opa\"", ",", "\"http://purl.org/socialparticipation/opa/\"", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"ops\"", ",", "\"http://purl.org/socialparticipation/ops/\"", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"wsg\"", ",", "\"http://www.w3.org/2003/01/geo/wgs84_pos#\"", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"dc2\"", ",", "\"http://purl.org/dc/elements/1.1/\"", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"dc\"", ",", "\"http://purl.org/dc/terms/\"", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"sioc\"", ",", "\"http://rdfs.org/sioc/ns#\"", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"tsioc\"", ",", "\"http://rdfs.org/sioc/types#\"", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"schema\"", ",", "\"http://schema.org/\"", ")", "g", ".", "namespace_manager", ".", "bind", "(", "\"part\"", ",", "\"http://participa.br/\"", ")", "self", ".", "g", "=", "g" ]
Starts RDF graph and bing namespaces
[ "Starts", "RDF", "graph", "and", "bing", "namespaces" ]
d78975038a64ea018120889d019a559409dae631
https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L102-L117
241,826
ttm/participationLegacy
participation/triplification/participaTriplification.py
ParticipaTriplification.triplifyPortalInfo
def triplifyPortalInfo(self): """Make triples with information about the portal. """ uri=self.P.opa.ParticipationPortal+self.separator+"participabr" self.X.G(uri,self.P.rdf.type,self.P.opa.ParticipationPortal) self.X.G(uri,self.P.opa.description,self.X.L(DATA.portal_description,self.P.xsd.string)) self.X.G(uri,self.P.opa.url,self.X.L("http://participa.br/",self.P.xsd.string))
python
def triplifyPortalInfo(self): """Make triples with information about the portal. """ uri=self.P.opa.ParticipationPortal+self.separator+"participabr" self.X.G(uri,self.P.rdf.type,self.P.opa.ParticipationPortal) self.X.G(uri,self.P.opa.description,self.X.L(DATA.portal_description,self.P.xsd.string)) self.X.G(uri,self.P.opa.url,self.X.L("http://participa.br/",self.P.xsd.string))
[ "def", "triplifyPortalInfo", "(", "self", ")", ":", "uri", "=", "self", ".", "P", ".", "opa", ".", "ParticipationPortal", "+", "self", ".", "separator", "+", "\"participabr\"", "self", ".", "X", ".", "G", "(", "uri", ",", "self", ".", "P", ".", "rdf", ".", "type", ",", "self", ".", "P", ".", "opa", ".", "ParticipationPortal", ")", "self", ".", "X", ".", "G", "(", "uri", ",", "self", ".", "P", ".", "opa", ".", "description", ",", "self", ".", "X", ".", "L", "(", "DATA", ".", "portal_description", ",", "self", ".", "P", ".", "xsd", ".", "string", ")", ")", "self", ".", "X", ".", "G", "(", "uri", ",", "self", ".", "P", ".", "opa", ".", "url", ",", "self", ".", "X", ".", "L", "(", "\"http://participa.br/\"", ",", "self", ".", "P", ".", "xsd", ".", "string", ")", ")" ]
Make triples with information about the portal.
[ "Make", "triples", "with", "information", "about", "the", "portal", "." ]
d78975038a64ea018120889d019a559409dae631
https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L150-L156
241,827
ttm/participationLegacy
participation/triplification/participaTriplification.py
ParticipaTriplification.triplifyOverallStructures
def triplifyOverallStructures(self): """Insert into RDF graph the textual and network structures. Ideally, one should be able to make bag of words related to each item (communities, users, posts, comments, tags, etc). Interaction and friendship networks should be made. Human networks mediated by co-ocurrance (time os posts, geographical locations, vocabulary, etc) should be addressed as well. """ if self.compute_networks: self.computeNetworks() if self.compute_bows: self.computeBows()
python
def triplifyOverallStructures(self): """Insert into RDF graph the textual and network structures. Ideally, one should be able to make bag of words related to each item (communities, users, posts, comments, tags, etc). Interaction and friendship networks should be made. Human networks mediated by co-ocurrance (time os posts, geographical locations, vocabulary, etc) should be addressed as well. """ if self.compute_networks: self.computeNetworks() if self.compute_bows: self.computeBows()
[ "def", "triplifyOverallStructures", "(", "self", ")", ":", "if", "self", ".", "compute_networks", ":", "self", ".", "computeNetworks", "(", ")", "if", "self", ".", "compute_bows", ":", "self", ".", "computeBows", "(", ")" ]
Insert into RDF graph the textual and network structures. Ideally, one should be able to make bag of words related to each item (communities, users, posts, comments, tags, etc). Interaction and friendship networks should be made. Human networks mediated by co-ocurrance (time os posts, geographical locations, vocabulary, etc) should be addressed as well.
[ "Insert", "into", "RDF", "graph", "the", "textual", "and", "network", "structures", "." ]
d78975038a64ea018120889d019a559409dae631
https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L157-L170
241,828
rehandalal/buchner
buchner/project-template/manage.py
db_create
def db_create(): """Create the database""" try: migrate_api.version_control(url=db_url, repository=db_repo) db_upgrade() except DatabaseAlreadyControlledError: print 'ERROR: Database is already version controlled.'
python
def db_create(): """Create the database""" try: migrate_api.version_control(url=db_url, repository=db_repo) db_upgrade() except DatabaseAlreadyControlledError: print 'ERROR: Database is already version controlled.'
[ "def", "db_create", "(", ")", ":", "try", ":", "migrate_api", ".", "version_control", "(", "url", "=", "db_url", ",", "repository", "=", "db_repo", ")", "db_upgrade", "(", ")", "except", "DatabaseAlreadyControlledError", ":", "print", "'ERROR: Database is already version controlled.'" ]
Create the database
[ "Create", "the", "database" ]
dc22a61c493b9d4a74d76e8b42a319aa13e385f3
https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L30-L36
241,829
rehandalal/buchner
buchner/project-template/manage.py
db_downgrade
def db_downgrade(version): """Downgrade the database""" v1 = get_db_version() migrate_api.downgrade(url=db_url, repository=db_repo, version=version) v2 = get_db_version() if v1 == v2: print 'No changes made.' else: print 'Downgraded: %s ... %s' % (v1, v2)
python
def db_downgrade(version): """Downgrade the database""" v1 = get_db_version() migrate_api.downgrade(url=db_url, repository=db_repo, version=version) v2 = get_db_version() if v1 == v2: print 'No changes made.' else: print 'Downgraded: %s ... %s' % (v1, v2)
[ "def", "db_downgrade", "(", "version", ")", ":", "v1", "=", "get_db_version", "(", ")", "migrate_api", ".", "downgrade", "(", "url", "=", "db_url", ",", "repository", "=", "db_repo", ",", "version", "=", "version", ")", "v2", "=", "get_db_version", "(", ")", "if", "v1", "==", "v2", ":", "print", "'No changes made.'", "else", ":", "print", "'Downgraded: %s ... %s'", "%", "(", "v1", ",", "v2", ")" ]
Downgrade the database
[ "Downgrade", "the", "database" ]
dc22a61c493b9d4a74d76e8b42a319aa13e385f3
https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L40-L49
241,830
rehandalal/buchner
buchner/project-template/manage.py
db_upgrade
def db_upgrade(version=None): """Upgrade the database""" v1 = get_db_version() migrate_api.upgrade(url=db_url, repository=db_repo, version=version) v2 = get_db_version() if v1 == v2: print 'Database already up-to-date.' else: print 'Upgraded: %s ... %s' % (v1, v2)
python
def db_upgrade(version=None): """Upgrade the database""" v1 = get_db_version() migrate_api.upgrade(url=db_url, repository=db_repo, version=version) v2 = get_db_version() if v1 == v2: print 'Database already up-to-date.' else: print 'Upgraded: %s ... %s' % (v1, v2)
[ "def", "db_upgrade", "(", "version", "=", "None", ")", ":", "v1", "=", "get_db_version", "(", ")", "migrate_api", ".", "upgrade", "(", "url", "=", "db_url", ",", "repository", "=", "db_repo", ",", "version", "=", "version", ")", "v2", "=", "get_db_version", "(", ")", "if", "v1", "==", "v2", ":", "print", "'Database already up-to-date.'", "else", ":", "print", "'Upgraded: %s ... %s'", "%", "(", "v1", ",", "v2", ")" ]
Upgrade the database
[ "Upgrade", "the", "database" ]
dc22a61c493b9d4a74d76e8b42a319aa13e385f3
https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L53-L62
241,831
rehandalal/buchner
buchner/project-template/manage.py
install_npm_modules
def install_npm_modules(): """Uses npm to dependencies in node.json""" # This is a little weird, but we do it this way because if you # have package.json, then heroku thinks this might be a node.js # app. call_command('cp node.json package.json', verbose=True) call_command('npm install', verbose=True) call_command('rm package.json', verbose=True)
python
def install_npm_modules(): """Uses npm to dependencies in node.json""" # This is a little weird, but we do it this way because if you # have package.json, then heroku thinks this might be a node.js # app. call_command('cp node.json package.json', verbose=True) call_command('npm install', verbose=True) call_command('rm package.json', verbose=True)
[ "def", "install_npm_modules", "(", ")", ":", "# This is a little weird, but we do it this way because if you", "# have package.json, then heroku thinks this might be a node.js", "# app.", "call_command", "(", "'cp node.json package.json'", ",", "verbose", "=", "True", ")", "call_command", "(", "'npm install'", ",", "verbose", "=", "True", ")", "call_command", "(", "'rm package.json'", ",", "verbose", "=", "True", ")" ]
Uses npm to dependencies in node.json
[ "Uses", "npm", "to", "dependencies", "in", "node", ".", "json" ]
dc22a61c493b9d4a74d76e8b42a319aa13e385f3
https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L79-L86
241,832
asyncdef/interfaces
asyncdef/interfaces/engine/itime.py
ITime.defer
def defer( self, func: typing.Callable[[], typing.Any], until: typing.Union[int, float]=-1, ) -> typing.Any: """Defer the execution of a function until some clock value. Args: func (typing.Callable[[], typing.Any]): A callable that accepts no arguments. All return values are ignored. until (typing.Union[int, float]): A numeric value that represents the clock time when the callback becomes available for execution. Values that are less than the current time result in the function being called at the next opportunity. Returns: typing.Any: An opaque identifier that represents the callback uniquely within the processor. This identifier is used to modify the callback scheduling. Note: The time given should not be considered absolute. It represents the time when the callback becomes available to execute. It may be much later than the given time value when the function actually executes depending on the implementation. """ raise NotImplementedError()
python
def defer( self, func: typing.Callable[[], typing.Any], until: typing.Union[int, float]=-1, ) -> typing.Any: """Defer the execution of a function until some clock value. Args: func (typing.Callable[[], typing.Any]): A callable that accepts no arguments. All return values are ignored. until (typing.Union[int, float]): A numeric value that represents the clock time when the callback becomes available for execution. Values that are less than the current time result in the function being called at the next opportunity. Returns: typing.Any: An opaque identifier that represents the callback uniquely within the processor. This identifier is used to modify the callback scheduling. Note: The time given should not be considered absolute. It represents the time when the callback becomes available to execute. It may be much later than the given time value when the function actually executes depending on the implementation. """ raise NotImplementedError()
[ "def", "defer", "(", "self", ",", "func", ":", "typing", ".", "Callable", "[", "[", "]", ",", "typing", ".", "Any", "]", ",", "until", ":", "typing", ".", "Union", "[", "int", ",", "float", "]", "=", "-", "1", ",", ")", "->", "typing", ".", "Any", ":", "raise", "NotImplementedError", "(", ")" ]
Defer the execution of a function until some clock value. Args: func (typing.Callable[[], typing.Any]): A callable that accepts no arguments. All return values are ignored. until (typing.Union[int, float]): A numeric value that represents the clock time when the callback becomes available for execution. Values that are less than the current time result in the function being called at the next opportunity. Returns: typing.Any: An opaque identifier that represents the callback uniquely within the processor. This identifier is used to modify the callback scheduling. Note: The time given should not be considered absolute. It represents the time when the callback becomes available to execute. It may be much later than the given time value when the function actually executes depending on the implementation.
[ "Defer", "the", "execution", "of", "a", "function", "until", "some", "clock", "value", "." ]
17c589c6ab158e3d9977a6d9da6d5ecd44844285
https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/itime.py#L24-L50
241,833
asyncdef/interfaces
asyncdef/interfaces/engine/itime.py
ITime.delay
def delay( self, identifier: typing.Any, until: typing.Union[int, float]=-1, ) -> bool: """Delay a deferred function until the given time. Args: identifier (typing.Any): The identifier returned from a call to defer or defer_for. until (typing.Union[int, float]): A numeric value that represents the clock time when the callback becomes available for execution. Values that are less than the current time result in the function being called at the next opportunity. Returns: bool: True if the call is delayed. False if the identifier is invalid or if the deferred call is already executed. """ raise NotImplementedError()
python
def delay( self, identifier: typing.Any, until: typing.Union[int, float]=-1, ) -> bool: """Delay a deferred function until the given time. Args: identifier (typing.Any): The identifier returned from a call to defer or defer_for. until (typing.Union[int, float]): A numeric value that represents the clock time when the callback becomes available for execution. Values that are less than the current time result in the function being called at the next opportunity. Returns: bool: True if the call is delayed. False if the identifier is invalid or if the deferred call is already executed. """ raise NotImplementedError()
[ "def", "delay", "(", "self", ",", "identifier", ":", "typing", ".", "Any", ",", "until", ":", "typing", ".", "Union", "[", "int", ",", "float", "]", "=", "-", "1", ",", ")", "->", "bool", ":", "raise", "NotImplementedError", "(", ")" ]
Delay a deferred function until the given time. Args: identifier (typing.Any): The identifier returned from a call to defer or defer_for. until (typing.Union[int, float]): A numeric value that represents the clock time when the callback becomes available for execution. Values that are less than the current time result in the function being called at the next opportunity. Returns: bool: True if the call is delayed. False if the identifier is invalid or if the deferred call is already executed.
[ "Delay", "a", "deferred", "function", "until", "the", "given", "time", "." ]
17c589c6ab158e3d9977a6d9da6d5ecd44844285
https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/itime.py#L76-L95
241,834
davidmiller/letter
letter/contrib/contact.py
EmailForm.send_email
def send_email(self, to): """ Do work. """ body = self.body() subject = self.subject() import letter class Message(letter.Letter): Postie = letter.DjangoPostman() From = getattr(settings, 'DEFAULT_FROM_EMAIL', 'contact@example.com') To = to Subject = subject Body = body if hasattr(self, 'reply_to'): Message.ReplyTo = self.reply_to() Message.send() return
python
def send_email(self, to): """ Do work. """ body = self.body() subject = self.subject() import letter class Message(letter.Letter): Postie = letter.DjangoPostman() From = getattr(settings, 'DEFAULT_FROM_EMAIL', 'contact@example.com') To = to Subject = subject Body = body if hasattr(self, 'reply_to'): Message.ReplyTo = self.reply_to() Message.send() return
[ "def", "send_email", "(", "self", ",", "to", ")", ":", "body", "=", "self", ".", "body", "(", ")", "subject", "=", "self", ".", "subject", "(", ")", "import", "letter", "class", "Message", "(", "letter", ".", "Letter", ")", ":", "Postie", "=", "letter", ".", "DjangoPostman", "(", ")", "From", "=", "getattr", "(", "settings", ",", "'DEFAULT_FROM_EMAIL'", ",", "'contact@example.com'", ")", "To", "=", "to", "Subject", "=", "subject", "Body", "=", "body", "if", "hasattr", "(", "self", ",", "'reply_to'", ")", ":", "Message", ".", "ReplyTo", "=", "self", ".", "reply_to", "(", ")", "Message", ".", "send", "(", ")", "return" ]
Do work.
[ "Do", "work", "." ]
c0c66ae2c6a792106e9a8374a01421817c8a8ae0
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/contrib/contact.py#L24-L45
241,835
davidmiller/letter
letter/contrib/contact.py
EmailView.form_valid
def form_valid(self, form): """ Praise be, someone has spammed us. """ form.send_email(to=self.to_addr) return super(EmailView, self).form_valid(form)
python
def form_valid(self, form): """ Praise be, someone has spammed us. """ form.send_email(to=self.to_addr) return super(EmailView, self).form_valid(form)
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "form", ".", "send_email", "(", "to", "=", "self", ".", "to_addr", ")", "return", "super", "(", "EmailView", ",", "self", ")", ".", "form_valid", "(", "form", ")" ]
Praise be, someone has spammed us.
[ "Praise", "be", "someone", "has", "spammed", "us", "." ]
c0c66ae2c6a792106e9a8374a01421817c8a8ae0
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/contrib/contact.py#L87-L92
241,836
tevino/mongu
mongu.py
Client.register_model
def register_model(self, model_cls): """Decorator for registering model.""" if not getattr(model_cls, '_database_'): raise ModelAttributeError('_database_ missing ' 'on %s!' % model_cls.__name__) if not getattr(model_cls, '_collection_'): raise ModelAttributeError('_collection_ missing ' 'on %s!' % model_cls.__name__) model_cls._mongo_client_ = self.client logging.info('Registering Model ' + model_cls.__name__) return model_cls
python
def register_model(self, model_cls): """Decorator for registering model.""" if not getattr(model_cls, '_database_'): raise ModelAttributeError('_database_ missing ' 'on %s!' % model_cls.__name__) if not getattr(model_cls, '_collection_'): raise ModelAttributeError('_collection_ missing ' 'on %s!' % model_cls.__name__) model_cls._mongo_client_ = self.client logging.info('Registering Model ' + model_cls.__name__) return model_cls
[ "def", "register_model", "(", "self", ",", "model_cls", ")", ":", "if", "not", "getattr", "(", "model_cls", ",", "'_database_'", ")", ":", "raise", "ModelAttributeError", "(", "'_database_ missing '", "'on %s!'", "%", "model_cls", ".", "__name__", ")", "if", "not", "getattr", "(", "model_cls", ",", "'_collection_'", ")", ":", "raise", "ModelAttributeError", "(", "'_collection_ missing '", "'on %s!'", "%", "model_cls", ".", "__name__", ")", "model_cls", ".", "_mongo_client_", "=", "self", ".", "client", "logging", ".", "info", "(", "'Registering Model '", "+", "model_cls", ".", "__name__", ")", "return", "model_cls" ]
Decorator for registering model.
[ "Decorator", "for", "registering", "model", "." ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L34-L46
241,837
tevino/mongu
mongu.py
Client.enable_counter
def enable_counter(self, base=None, database='counter', collection='counters'): """Register the builtin counter model, return the registered Counter class and the corresponding ``CounterMixin`` class. The ``CounterMixin`` automatically increases and decreases the counter after model creation(save without ``_id``) and deletion. It contains a classmethod ``count()`` which returns the current count of the model collection.""" Counter._database_ = database Counter._collection_ = collection bases = (base, Counter) if base else (Counter,) counter = self.register_model(type('Counter', bases, {})) class CounterMixin(object): """Mixin class for model""" @classmethod def inc_counter(cls): """Wrapper for ``Counter.increase()``.""" return counter.increase(cls._collection_) @classmethod def dec_counter(cls): """Wrapper for ``Counter.decrease()``.""" return counter.decrease(cls._collection_) @classmethod def chg_counter(cls, *args, **kwargs): """Wrapper for ``Counter.change_by()``.""" return counter.change_by(cls._collection_, *args, **kwargs) @classmethod def set_counter(cls, *args, **kwargs): """Wrapper for ``Counter.set_to()``.""" return counter.set_to(cls._collection_, *args, **kwargs) def on_save(self, old_dict): super(CounterMixin, self).on_save(old_dict) if not old_dict.get('_id'): counter.increase(self._collection_) def on_delete(self, *args, **kwargs): super(CounterMixin, self).on_delete(*args, **kwargs) counter.decrease(self._collection_) @classmethod def count(cls): """Return the current count of this collection.""" return counter.count(cls._collection_) logging.info('Counter enabled on: %s' % counter.collection) return counter, CounterMixin
python
def enable_counter(self, base=None, database='counter', collection='counters'): """Register the builtin counter model, return the registered Counter class and the corresponding ``CounterMixin`` class. The ``CounterMixin`` automatically increases and decreases the counter after model creation(save without ``_id``) and deletion. It contains a classmethod ``count()`` which returns the current count of the model collection.""" Counter._database_ = database Counter._collection_ = collection bases = (base, Counter) if base else (Counter,) counter = self.register_model(type('Counter', bases, {})) class CounterMixin(object): """Mixin class for model""" @classmethod def inc_counter(cls): """Wrapper for ``Counter.increase()``.""" return counter.increase(cls._collection_) @classmethod def dec_counter(cls): """Wrapper for ``Counter.decrease()``.""" return counter.decrease(cls._collection_) @classmethod def chg_counter(cls, *args, **kwargs): """Wrapper for ``Counter.change_by()``.""" return counter.change_by(cls._collection_, *args, **kwargs) @classmethod def set_counter(cls, *args, **kwargs): """Wrapper for ``Counter.set_to()``.""" return counter.set_to(cls._collection_, *args, **kwargs) def on_save(self, old_dict): super(CounterMixin, self).on_save(old_dict) if not old_dict.get('_id'): counter.increase(self._collection_) def on_delete(self, *args, **kwargs): super(CounterMixin, self).on_delete(*args, **kwargs) counter.decrease(self._collection_) @classmethod def count(cls): """Return the current count of this collection.""" return counter.count(cls._collection_) logging.info('Counter enabled on: %s' % counter.collection) return counter, CounterMixin
[ "def", "enable_counter", "(", "self", ",", "base", "=", "None", ",", "database", "=", "'counter'", ",", "collection", "=", "'counters'", ")", ":", "Counter", ".", "_database_", "=", "database", "Counter", ".", "_collection_", "=", "collection", "bases", "=", "(", "base", ",", "Counter", ")", "if", "base", "else", "(", "Counter", ",", ")", "counter", "=", "self", ".", "register_model", "(", "type", "(", "'Counter'", ",", "bases", ",", "{", "}", ")", ")", "class", "CounterMixin", "(", "object", ")", ":", "\"\"\"Mixin class for model\"\"\"", "@", "classmethod", "def", "inc_counter", "(", "cls", ")", ":", "\"\"\"Wrapper for ``Counter.increase()``.\"\"\"", "return", "counter", ".", "increase", "(", "cls", ".", "_collection_", ")", "@", "classmethod", "def", "dec_counter", "(", "cls", ")", ":", "\"\"\"Wrapper for ``Counter.decrease()``.\"\"\"", "return", "counter", ".", "decrease", "(", "cls", ".", "_collection_", ")", "@", "classmethod", "def", "chg_counter", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper for ``Counter.change_by()``.\"\"\"", "return", "counter", ".", "change_by", "(", "cls", ".", "_collection_", ",", "*", "args", ",", "*", "*", "kwargs", ")", "@", "classmethod", "def", "set_counter", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper for ``Counter.set_to()``.\"\"\"", "return", "counter", ".", "set_to", "(", "cls", ".", "_collection_", ",", "*", "args", ",", "*", "*", "kwargs", ")", "def", "on_save", "(", "self", ",", "old_dict", ")", ":", "super", "(", "CounterMixin", ",", "self", ")", ".", "on_save", "(", "old_dict", ")", "if", "not", "old_dict", ".", "get", "(", "'_id'", ")", ":", "counter", ".", "increase", "(", "self", ".", "_collection_", ")", "def", "on_delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "CounterMixin", ",", "self", ")", ".", "on_delete", "(", "*", "args", ",", "*", "*", "kwargs", ")", "counter", ".", "decrease", "(", "self", ".", "_collection_", ")", "@", "classmethod", "def", "count", "(", "cls", ")", ":", "\"\"\"Return the current count of this collection.\"\"\"", "return", "counter", ".", "count", "(", "cls", ".", "_collection_", ")", "logging", ".", "info", "(", "'Counter enabled on: %s'", "%", "counter", ".", "collection", ")", "return", "counter", ",", "CounterMixin" ]
Register the builtin counter model, return the registered Counter class and the corresponding ``CounterMixin`` class. The ``CounterMixin`` automatically increases and decreases the counter after model creation(save without ``_id``) and deletion. It contains a classmethod ``count()`` which returns the current count of the model collection.
[ "Register", "the", "builtin", "counter", "model", "return", "the", "registered", "Counter", "class", "and", "the", "corresponding", "CounterMixin", "class", "." ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L48-L100
241,838
tevino/mongu
mongu.py
Model.by_id
def by_id(cls, oid): """Find a model object by its ``ObjectId``, ``oid`` can be string or ObjectId""" if oid: d = cls.collection.find_one(ObjectId(oid)) if d: return cls(**d)
python
def by_id(cls, oid): """Find a model object by its ``ObjectId``, ``oid`` can be string or ObjectId""" if oid: d = cls.collection.find_one(ObjectId(oid)) if d: return cls(**d)
[ "def", "by_id", "(", "cls", ",", "oid", ")", ":", "if", "oid", ":", "d", "=", "cls", ".", "collection", ".", "find_one", "(", "ObjectId", "(", "oid", ")", ")", "if", "d", ":", "return", "cls", "(", "*", "*", "d", ")" ]
Find a model object by its ``ObjectId``, ``oid`` can be string or ObjectId
[ "Find", "a", "model", "object", "by", "its", "ObjectId", "oid", "can", "be", "string", "or", "ObjectId" ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L164-L170
241,839
tevino/mongu
mongu.py
Model.from_dict
def from_dict(cls, d): """Build model object from a dict. Will be removed in v1.0""" warnings.warn( 'from_dict is deprecated and will be removed in v1.0!', stacklevel=2) d = d or {} return cls(**d)
python
def from_dict(cls, d): """Build model object from a dict. Will be removed in v1.0""" warnings.warn( 'from_dict is deprecated and will be removed in v1.0!', stacklevel=2) d = d or {} return cls(**d)
[ "def", "from_dict", "(", "cls", ",", "d", ")", ":", "warnings", ".", "warn", "(", "'from_dict is deprecated and will be removed in v1.0!'", ",", "stacklevel", "=", "2", ")", "d", "=", "d", "or", "{", "}", "return", "cls", "(", "*", "*", "d", ")" ]
Build model object from a dict. Will be removed in v1.0
[ "Build", "model", "object", "from", "a", "dict", ".", "Will", "be", "removed", "in", "v1", ".", "0" ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L180-L186
241,840
tevino/mongu
mongu.py
Model.find
def find(cls, *args, **kwargs): """Same as ``collection.find``, returns model object instead of dict.""" return cls.from_cursor(cls.collection.find(*args, **kwargs))
python
def find(cls, *args, **kwargs): """Same as ``collection.find``, returns model object instead of dict.""" return cls.from_cursor(cls.collection.find(*args, **kwargs))
[ "def", "find", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "cls", ".", "from_cursor", "(", "cls", ".", "collection", ".", "find", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
Same as ``collection.find``, returns model object instead of dict.
[ "Same", "as", "collection", ".", "find", "returns", "model", "object", "instead", "of", "dict", "." ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L195-L197
241,841
tevino/mongu
mongu.py
Model.find_one
def find_one(cls, *args, **kwargs): """Same as ``collection.find_one``, returns model object instead of dict.""" d = cls.collection.find_one(*args, **kwargs) if d: return cls(**d)
python
def find_one(cls, *args, **kwargs): """Same as ``collection.find_one``, returns model object instead of dict.""" d = cls.collection.find_one(*args, **kwargs) if d: return cls(**d)
[ "def", "find_one", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "d", "=", "cls", ".", "collection", ".", "find_one", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "d", ":", "return", "cls", "(", "*", "*", "d", ")" ]
Same as ``collection.find_one``, returns model object instead of dict.
[ "Same", "as", "collection", ".", "find_one", "returns", "model", "object", "instead", "of", "dict", "." ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L200-L205
241,842
tevino/mongu
mongu.py
Model.reload
def reload(self, d=None): """Reload model from given dict or database.""" if d: self.clear() self.update(d) elif self.id: new_dict = self.by_id(self._id) self.clear() self.update(new_dict) else: # should I raise an exception here? # Like "Model must be saved first." pass
python
def reload(self, d=None): """Reload model from given dict or database.""" if d: self.clear() self.update(d) elif self.id: new_dict = self.by_id(self._id) self.clear() self.update(new_dict) else: # should I raise an exception here? # Like "Model must be saved first." pass
[ "def", "reload", "(", "self", ",", "d", "=", "None", ")", ":", "if", "d", ":", "self", ".", "clear", "(", ")", "self", ".", "update", "(", "d", ")", "elif", "self", ".", "id", ":", "new_dict", "=", "self", ".", "by_id", "(", "self", ".", "_id", ")", "self", ".", "clear", "(", ")", "self", ".", "update", "(", "new_dict", ")", "else", ":", "# should I raise an exception here?", "# Like \"Model must be saved first.\"", "pass" ]
Reload model from given dict or database.
[ "Reload", "model", "from", "given", "dict", "or", "database", "." ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L213-L225
241,843
tevino/mongu
mongu.py
Model.save
def save(self): """Save model object to database.""" d = dict(self) old_dict = d.copy() _id = self.collection.save(d) self._id = _id self.on_save(old_dict) return self._id
python
def save(self): """Save model object to database.""" d = dict(self) old_dict = d.copy() _id = self.collection.save(d) self._id = _id self.on_save(old_dict) return self._id
[ "def", "save", "(", "self", ")", ":", "d", "=", "dict", "(", "self", ")", "old_dict", "=", "d", ".", "copy", "(", ")", "_id", "=", "self", ".", "collection", ".", "save", "(", "d", ")", "self", ".", "_id", "=", "_id", "self", ".", "on_save", "(", "old_dict", ")", "return", "self", ".", "_id" ]
Save model object to database.
[ "Save", "model", "object", "to", "database", "." ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L231-L238
241,844
tevino/mongu
mongu.py
Model.delete
def delete(self): """Remove from database.""" if not self.id: return self.collection.remove({'_id': self._id}) self.on_delete(self)
python
def delete(self): """Remove from database.""" if not self.id: return self.collection.remove({'_id': self._id}) self.on_delete(self)
[ "def", "delete", "(", "self", ")", ":", "if", "not", "self", ".", "id", ":", "return", "self", ".", "collection", ".", "remove", "(", "{", "'_id'", ":", "self", ".", "_id", "}", ")", "self", ".", "on_delete", "(", "self", ")" ]
Remove from database.
[ "Remove", "from", "database", "." ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L244-L249
241,845
tevino/mongu
mongu.py
Counter.set_to
def set_to(cls, name, num): """Set counter of ``name`` to ``num``.""" if num < 0: raise CounterValueError('Counter[%s] can not be set to %s' % ( name, num)) else: counter = cls.collection.find_and_modify( {'name': name}, {'$set': {'seq': num}}, new=True, upsert=True ) return counter['seq']
python
def set_to(cls, name, num): """Set counter of ``name`` to ``num``.""" if num < 0: raise CounterValueError('Counter[%s] can not be set to %s' % ( name, num)) else: counter = cls.collection.find_and_modify( {'name': name}, {'$set': {'seq': num}}, new=True, upsert=True ) return counter['seq']
[ "def", "set_to", "(", "cls", ",", "name", ",", "num", ")", ":", "if", "num", "<", "0", ":", "raise", "CounterValueError", "(", "'Counter[%s] can not be set to %s'", "%", "(", "name", ",", "num", ")", ")", "else", ":", "counter", "=", "cls", ".", "collection", ".", "find_and_modify", "(", "{", "'name'", ":", "name", "}", ",", "{", "'$set'", ":", "{", "'seq'", ":", "num", "}", "}", ",", "new", "=", "True", ",", "upsert", "=", "True", ")", "return", "counter", "[", "'seq'", "]" ]
Set counter of ``name`` to ``num``.
[ "Set", "counter", "of", "name", "to", "num", "." ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L255-L267
241,846
tevino/mongu
mongu.py
Counter.count
def count(cls, name): """Return the count of ``name``""" counter = cls.collection.find_one({'name': name}) or {} return counter.get('seq', 0)
python
def count(cls, name): """Return the count of ``name``""" counter = cls.collection.find_one({'name': name}) or {} return counter.get('seq', 0)
[ "def", "count", "(", "cls", ",", "name", ")", ":", "counter", "=", "cls", ".", "collection", ".", "find_one", "(", "{", "'name'", ":", "name", "}", ")", "or", "{", "}", "return", "counter", ".", "get", "(", "'seq'", ",", "0", ")" ]
Return the count of ``name``
[ "Return", "the", "count", "of", "name" ]
98f15cdb9e5906062f2d5088c7bf774ab007c6e5
https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L296-L299
241,847
gear11/pypelogs
pypein/wikip.py
geo_filter
def geo_filter(d): """Inspects the given Wikipedia article dict for geo-coordinates. If no coordinates are found, returns None. Otherwise, returns a new dict with the title and URL of the original article, along with coordinates.""" page = d["page"] if not "revision" in page: return None title = page["title"] if skip_article(title): LOG.info("Skipping low-value article %s", title) return None text = page["revision"]["text"] if not utils.is_str_type(text): if "#text" in text: text = text["#text"] else: return None LOG.debug("--------------------------------------------------------------") LOG.debug(title) LOG.debug("--------------------------------------------------------------") LOG.debug(text) c = find_geo_coords(text) u = wikip_url(title) """ m = hashlib.md5() m.update(u.encode("UTF-8") if hasattr(u, 'encode') else u) i = base64.urlsafe_b64encode(m.digest()).replace('=', '') """ return { #"id": i, "title": title, "url": u, "coords": c, "updated": page["revision"].get("timestamp") } if c else None
python
def geo_filter(d): """Inspects the given Wikipedia article dict for geo-coordinates. If no coordinates are found, returns None. Otherwise, returns a new dict with the title and URL of the original article, along with coordinates.""" page = d["page"] if not "revision" in page: return None title = page["title"] if skip_article(title): LOG.info("Skipping low-value article %s", title) return None text = page["revision"]["text"] if not utils.is_str_type(text): if "#text" in text: text = text["#text"] else: return None LOG.debug("--------------------------------------------------------------") LOG.debug(title) LOG.debug("--------------------------------------------------------------") LOG.debug(text) c = find_geo_coords(text) u = wikip_url(title) """ m = hashlib.md5() m.update(u.encode("UTF-8") if hasattr(u, 'encode') else u) i = base64.urlsafe_b64encode(m.digest()).replace('=', '') """ return { #"id": i, "title": title, "url": u, "coords": c, "updated": page["revision"].get("timestamp") } if c else None
[ "def", "geo_filter", "(", "d", ")", ":", "page", "=", "d", "[", "\"page\"", "]", "if", "not", "\"revision\"", "in", "page", ":", "return", "None", "title", "=", "page", "[", "\"title\"", "]", "if", "skip_article", "(", "title", ")", ":", "LOG", ".", "info", "(", "\"Skipping low-value article %s\"", ",", "title", ")", "return", "None", "text", "=", "page", "[", "\"revision\"", "]", "[", "\"text\"", "]", "if", "not", "utils", ".", "is_str_type", "(", "text", ")", ":", "if", "\"#text\"", "in", "text", ":", "text", "=", "text", "[", "\"#text\"", "]", "else", ":", "return", "None", "LOG", ".", "debug", "(", "\"--------------------------------------------------------------\"", ")", "LOG", ".", "debug", "(", "title", ")", "LOG", ".", "debug", "(", "\"--------------------------------------------------------------\"", ")", "LOG", ".", "debug", "(", "text", ")", "c", "=", "find_geo_coords", "(", "text", ")", "u", "=", "wikip_url", "(", "title", ")", "\"\"\"\n m = hashlib.md5()\n m.update(u.encode(\"UTF-8\") if hasattr(u, 'encode') else u)\n i = base64.urlsafe_b64encode(m.digest()).replace('=', '')\n \"\"\"", "return", "{", "#\"id\": i,", "\"title\"", ":", "title", ",", "\"url\"", ":", "u", ",", "\"coords\"", ":", "c", ",", "\"updated\"", ":", "page", "[", "\"revision\"", "]", ".", "get", "(", "\"timestamp\"", ")", "}", "if", "c", "else", "None" ]
Inspects the given Wikipedia article dict for geo-coordinates. If no coordinates are found, returns None. Otherwise, returns a new dict with the title and URL of the original article, along with coordinates.
[ "Inspects", "the", "given", "Wikipedia", "article", "dict", "for", "geo", "-", "coordinates", "." ]
da5dc0fee5373a4be294798b5e32cd0a803d8bbe
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L76-L111
241,848
gear11/pypelogs
pypein/wikip.py
depipe
def depipe(s): """Convert a string of the form DD or DD|MM or DD|MM|SS to decimal degrees""" n = 0 for i in reversed(s.split('|')): n = n / 60.0 + float(i) return n
python
def depipe(s): """Convert a string of the form DD or DD|MM or DD|MM|SS to decimal degrees""" n = 0 for i in reversed(s.split('|')): n = n / 60.0 + float(i) return n
[ "def", "depipe", "(", "s", ")", ":", "n", "=", "0", "for", "i", "in", "reversed", "(", "s", ".", "split", "(", "'|'", ")", ")", ":", "n", "=", "n", "/", "60.0", "+", "float", "(", "i", ")", "return", "n" ]
Convert a string of the form DD or DD|MM or DD|MM|SS to decimal degrees
[ "Convert", "a", "string", "of", "the", "form", "DD", "or", "DD|MM", "or", "DD|MM|SS", "to", "decimal", "degrees" ]
da5dc0fee5373a4be294798b5e32cd0a803d8bbe
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L179-L184
241,849
gear11/pypelogs
pypein/wikip.py
skip_coords
def skip_coords(c): """Skip coordinate strings that are not valid""" if c == "{{coord|LAT|LONG|display=inline,title}}": # Unpopulated coord template return True if c.find("globe:") >= 0 and c.find("globe:earth") == -1: # Moon, venus, etc. return True return False
python
def skip_coords(c): """Skip coordinate strings that are not valid""" if c == "{{coord|LAT|LONG|display=inline,title}}": # Unpopulated coord template return True if c.find("globe:") >= 0 and c.find("globe:earth") == -1: # Moon, venus, etc. return True return False
[ "def", "skip_coords", "(", "c", ")", ":", "if", "c", "==", "\"{{coord|LAT|LONG|display=inline,title}}\"", ":", "# Unpopulated coord template", "return", "True", "if", "c", ".", "find", "(", "\"globe:\"", ")", ">=", "0", "and", "c", ".", "find", "(", "\"globe:earth\"", ")", "==", "-", "1", ":", "# Moon, venus, etc.", "return", "True", "return", "False" ]
Skip coordinate strings that are not valid
[ "Skip", "coordinate", "strings", "that", "are", "not", "valid" ]
da5dc0fee5373a4be294798b5e32cd0a803d8bbe
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L186-L192
241,850
lukaszb/porunga
porunga/procme.py
Command.iter_output
def iter_output(self, pause=0.05): """ Returns iterator of chunked output. :param cmd: command that would be passed to ``subprocess.Popen`` :param shell: Tells if process should be run within a shell. Default: False :param timeout: If command exceeds given ``timeout`` in seconds, ``TimeoutExceeded`` exception would be raised. Default: None :param pause: How long (in seconds) we should wait for the output. Default: 0.05 Example:: >>> command = Command('ls -l', shell=True) >>> for chunk in command.iter_output(): ... print(chunk, end='') """ with self.stream as temp: for chunk in self.iter_output_for_stream(temp, pause=pause): yield chunk
python
def iter_output(self, pause=0.05): """ Returns iterator of chunked output. :param cmd: command that would be passed to ``subprocess.Popen`` :param shell: Tells if process should be run within a shell. Default: False :param timeout: If command exceeds given ``timeout`` in seconds, ``TimeoutExceeded`` exception would be raised. Default: None :param pause: How long (in seconds) we should wait for the output. Default: 0.05 Example:: >>> command = Command('ls -l', shell=True) >>> for chunk in command.iter_output(): ... print(chunk, end='') """ with self.stream as temp: for chunk in self.iter_output_for_stream(temp, pause=pause): yield chunk
[ "def", "iter_output", "(", "self", ",", "pause", "=", "0.05", ")", ":", "with", "self", ".", "stream", "as", "temp", ":", "for", "chunk", "in", "self", ".", "iter_output_for_stream", "(", "temp", ",", "pause", "=", "pause", ")", ":", "yield", "chunk" ]
Returns iterator of chunked output. :param cmd: command that would be passed to ``subprocess.Popen`` :param shell: Tells if process should be run within a shell. Default: False :param timeout: If command exceeds given ``timeout`` in seconds, ``TimeoutExceeded`` exception would be raised. Default: None :param pause: How long (in seconds) we should wait for the output. Default: 0.05 Example:: >>> command = Command('ls -l', shell=True) >>> for chunk in command.iter_output(): ... print(chunk, end='')
[ "Returns", "iterator", "of", "chunked", "output", "." ]
13177ff9bc654ac25cf09def6b526eb38e40e483
https://github.com/lukaszb/porunga/blob/13177ff9bc654ac25cf09def6b526eb38e40e483/porunga/procme.py#L74-L93
241,851
peepall/FancyLogger
FancyLogger/__init__.py
FancyLogger.terminate
def terminate(self): """ Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some messages of progresses that have not been displayed yet. This method blocks until logger process has stopped. """ self.queue.put(dill.dumps(ExitCommand())) if self.process: self.process.join()
python
def terminate(self): """ Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some messages of progresses that have not been displayed yet. This method blocks until logger process has stopped. """ self.queue.put(dill.dumps(ExitCommand())) if self.process: self.process.join()
[ "def", "terminate", "(", "self", ")", ":", "self", ".", "queue", ".", "put", "(", "dill", ".", "dumps", "(", "ExitCommand", "(", ")", ")", ")", "if", "self", ".", "process", ":", "self", ".", "process", ".", "join", "(", ")" ]
Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some messages of progresses that have not been displayed yet. This method blocks until logger process has stopped.
[ "Tells", "the", "logger", "process", "to", "exit", "immediately", ".", "If", "you", "do", "not", "call", "flush", "method", "before", "you", "may", "lose", "some", "messages", "of", "progresses", "that", "have", "not", "been", "displayed", "yet", ".", "This", "method", "blocks", "until", "logger", "process", "has", "stopped", "." ]
7f13f1397e76ed768fb6b6358194118831fafc6d
https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/__init__.py#L217-L225
241,852
alkivi-sas/python-alkivi-logger
alkivi/logger/handlers.py
AlkiviEmailHandler.generate_mail
def generate_mail(self): """Generate the email as MIMEText """ # Script info msg = "Script info : \r\n" msg = msg + "%-9s: %s" % ('Script', SOURCEDIR) + "\r\n" msg = msg + "%-9s: %s" % ('User', USER) + "\r\n" msg = msg + "%-9s: %s" % ('Host', HOST) + "\r\n" msg = msg + "%-9s: %s" % ('PID', PID) + "\r\n" # Current trace msg = msg + "\r\nCurrent trace : \r\n" for record in self.current_buffer: msg = msg + record + "\r\n" # Now add stack trace msg = msg + "\r\nFull trace : \r\n" for record in self.complete_buffer: msg = msg + record + "\r\n" # Dump ENV msg = msg + "\r\nEnvironment:" + "\r\n" environ = OrderedDict(sorted(os.environ.items())) for name, value in environ.items(): msg = msg + "%-10s = %s\r\n" % (name, value) if USE_MIME: real_msg = MIMEText(msg, _charset='utf-8') real_msg['Subject'] = self.get_subject() real_msg['To'] = ','.join(self.toaddrs) real_msg['From'] = self.fromaddr else: real_msg = EmailMessage() real_msg['Subject'] = self.get_subject() real_msg['To'] = ','.join(self.toaddrs) real_msg['From'] = self.fromaddr real_msg.set_content(msg) return real_msg
python
def generate_mail(self): """Generate the email as MIMEText """ # Script info msg = "Script info : \r\n" msg = msg + "%-9s: %s" % ('Script', SOURCEDIR) + "\r\n" msg = msg + "%-9s: %s" % ('User', USER) + "\r\n" msg = msg + "%-9s: %s" % ('Host', HOST) + "\r\n" msg = msg + "%-9s: %s" % ('PID', PID) + "\r\n" # Current trace msg = msg + "\r\nCurrent trace : \r\n" for record in self.current_buffer: msg = msg + record + "\r\n" # Now add stack trace msg = msg + "\r\nFull trace : \r\n" for record in self.complete_buffer: msg = msg + record + "\r\n" # Dump ENV msg = msg + "\r\nEnvironment:" + "\r\n" environ = OrderedDict(sorted(os.environ.items())) for name, value in environ.items(): msg = msg + "%-10s = %s\r\n" % (name, value) if USE_MIME: real_msg = MIMEText(msg, _charset='utf-8') real_msg['Subject'] = self.get_subject() real_msg['To'] = ','.join(self.toaddrs) real_msg['From'] = self.fromaddr else: real_msg = EmailMessage() real_msg['Subject'] = self.get_subject() real_msg['To'] = ','.join(self.toaddrs) real_msg['From'] = self.fromaddr real_msg.set_content(msg) return real_msg
[ "def", "generate_mail", "(", "self", ")", ":", "# Script info", "msg", "=", "\"Script info : \\r\\n\"", "msg", "=", "msg", "+", "\"%-9s: %s\"", "%", "(", "'Script'", ",", "SOURCEDIR", ")", "+", "\"\\r\\n\"", "msg", "=", "msg", "+", "\"%-9s: %s\"", "%", "(", "'User'", ",", "USER", ")", "+", "\"\\r\\n\"", "msg", "=", "msg", "+", "\"%-9s: %s\"", "%", "(", "'Host'", ",", "HOST", ")", "+", "\"\\r\\n\"", "msg", "=", "msg", "+", "\"%-9s: %s\"", "%", "(", "'PID'", ",", "PID", ")", "+", "\"\\r\\n\"", "# Current trace", "msg", "=", "msg", "+", "\"\\r\\nCurrent trace : \\r\\n\"", "for", "record", "in", "self", ".", "current_buffer", ":", "msg", "=", "msg", "+", "record", "+", "\"\\r\\n\"", "# Now add stack trace", "msg", "=", "msg", "+", "\"\\r\\nFull trace : \\r\\n\"", "for", "record", "in", "self", ".", "complete_buffer", ":", "msg", "=", "msg", "+", "record", "+", "\"\\r\\n\"", "# Dump ENV", "msg", "=", "msg", "+", "\"\\r\\nEnvironment:\"", "+", "\"\\r\\n\"", "environ", "=", "OrderedDict", "(", "sorted", "(", "os", ".", "environ", ".", "items", "(", ")", ")", ")", "for", "name", ",", "value", "in", "environ", ".", "items", "(", ")", ":", "msg", "=", "msg", "+", "\"%-10s = %s\\r\\n\"", "%", "(", "name", ",", "value", ")", "if", "USE_MIME", ":", "real_msg", "=", "MIMEText", "(", "msg", ",", "_charset", "=", "'utf-8'", ")", "real_msg", "[", "'Subject'", "]", "=", "self", ".", "get_subject", "(", ")", "real_msg", "[", "'To'", "]", "=", "','", ".", "join", "(", "self", ".", "toaddrs", ")", "real_msg", "[", "'From'", "]", "=", "self", ".", "fromaddr", "else", ":", "real_msg", "=", "EmailMessage", "(", ")", "real_msg", "[", "'Subject'", "]", "=", "self", ".", "get_subject", "(", ")", "real_msg", "[", "'To'", "]", "=", "','", ".", "join", "(", "self", ".", "toaddrs", ")", "real_msg", "[", "'From'", "]", "=", "self", ".", "fromaddr", "real_msg", ".", "set_content", "(", "msg", ")", "return", "real_msg" ]
Generate the email as MIMEText
[ "Generate", "the", "email", "as", "MIMEText" ]
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/handlers.py#L57-L100
241,853
alkivi-sas/python-alkivi-logger
alkivi/logger/handlers.py
AlkiviEmailHandler.get_subject
def get_subject(self): """Generate the subject.""" level = logging.getLevelName(self.flush_level) message = self.current_buffer[0].split("\n")[0] message = message.split(']')[-1] return '{0} : {1}{2}'.format(level, SOURCE, message)
python
def get_subject(self): """Generate the subject.""" level = logging.getLevelName(self.flush_level) message = self.current_buffer[0].split("\n")[0] message = message.split(']')[-1] return '{0} : {1}{2}'.format(level, SOURCE, message)
[ "def", "get_subject", "(", "self", ")", ":", "level", "=", "logging", ".", "getLevelName", "(", "self", ".", "flush_level", ")", "message", "=", "self", ".", "current_buffer", "[", "0", "]", ".", "split", "(", "\"\\n\"", ")", "[", "0", "]", "message", "=", "message", ".", "split", "(", "']'", ")", "[", "-", "1", "]", "return", "'{0} : {1}{2}'", ".", "format", "(", "level", ",", "SOURCE", ",", "message", ")" ]
Generate the subject.
[ "Generate", "the", "subject", "." ]
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/handlers.py#L102-L107
241,854
AndresMWeber/Nomenclate
nomenclate/core/configurator.py
ConfigEntryFormatter.format_query_result
def format_query_result(self, query_result, query_path, return_type=list, preceding_depth=None): """ Formats the query result based on the return type requested. :param query_result: (dict or str or list), yaml query result :param query_path: (str, list(str)), representing query path :param return_type: type, return type of object user desires :param preceding_depth: int, the depth to which we want to encapsulate back up config tree -1 : defaults to entire tree :return: (dict, OrderedDict, str, list), specified return type """ if type(query_result) != return_type: converted_result = self.format_with_handler(query_result, return_type) else: converted_result = query_result converted_result = self.add_preceding_dict(converted_result, query_path, preceding_depth) return converted_result
python
def format_query_result(self, query_result, query_path, return_type=list, preceding_depth=None): """ Formats the query result based on the return type requested. :param query_result: (dict or str or list), yaml query result :param query_path: (str, list(str)), representing query path :param return_type: type, return type of object user desires :param preceding_depth: int, the depth to which we want to encapsulate back up config tree -1 : defaults to entire tree :return: (dict, OrderedDict, str, list), specified return type """ if type(query_result) != return_type: converted_result = self.format_with_handler(query_result, return_type) else: converted_result = query_result converted_result = self.add_preceding_dict(converted_result, query_path, preceding_depth) return converted_result
[ "def", "format_query_result", "(", "self", ",", "query_result", ",", "query_path", ",", "return_type", "=", "list", ",", "preceding_depth", "=", "None", ")", ":", "if", "type", "(", "query_result", ")", "!=", "return_type", ":", "converted_result", "=", "self", ".", "format_with_handler", "(", "query_result", ",", "return_type", ")", "else", ":", "converted_result", "=", "query_result", "converted_result", "=", "self", ".", "add_preceding_dict", "(", "converted_result", ",", "query_path", ",", "preceding_depth", ")", "return", "converted_result" ]
Formats the query result based on the return type requested. :param query_result: (dict or str or list), yaml query result :param query_path: (str, list(str)), representing query path :param return_type: type, return type of object user desires :param preceding_depth: int, the depth to which we want to encapsulate back up config tree -1 : defaults to entire tree :return: (dict, OrderedDict, str, list), specified return type
[ "Formats", "the", "query", "result", "based", "on", "the", "return", "type", "requested", "." ]
e6d6fc28beac042bad588e56fbe77531d2de6b6f
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L13-L29
241,855
AndresMWeber/Nomenclate
nomenclate/core/configurator.py
ConfigEntryFormatter.format_with_handler
def format_with_handler(self, query_result, return_type): """ Uses the callable handler to format the query result to the desired return type :param query_result: the result value of our query :param return_type: desired return type :return: type, the query value as the return type requested """ handler = self.get_handler(type(query_result), return_type) return handler.format_result(query_result)
python
def format_with_handler(self, query_result, return_type): """ Uses the callable handler to format the query result to the desired return type :param query_result: the result value of our query :param return_type: desired return type :return: type, the query value as the return type requested """ handler = self.get_handler(type(query_result), return_type) return handler.format_result(query_result)
[ "def", "format_with_handler", "(", "self", ",", "query_result", ",", "return_type", ")", ":", "handler", "=", "self", ".", "get_handler", "(", "type", "(", "query_result", ")", ",", "return_type", ")", "return", "handler", ".", "format_result", "(", "query_result", ")" ]
Uses the callable handler to format the query result to the desired return type :param query_result: the result value of our query :param return_type: desired return type :return: type, the query value as the return type requested
[ "Uses", "the", "callable", "handler", "to", "format", "the", "query", "result", "to", "the", "desired", "return", "type" ]
e6d6fc28beac042bad588e56fbe77531d2de6b6f
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L31-L39
241,856
AndresMWeber/Nomenclate
nomenclate/core/configurator.py
ConfigEntryFormatter.get_handler
def get_handler(query_result_type, return_type): """ Find the appropriate return type handler to convert the query result to the desired return type :param query_result_type: type, desired return type :param return_type: type, actual return type :return: callable, function that will handle the conversion """ try: return FormatterRegistry.get_by_take_and_return_type(query_result_type, return_type) except (IndexError, AttributeError, KeyError): raise IndexError( 'Could not find function in conversion list for input type %s and return type %s' % ( query_result_type, return_type))
python
def get_handler(query_result_type, return_type): """ Find the appropriate return type handler to convert the query result to the desired return type :param query_result_type: type, desired return type :param return_type: type, actual return type :return: callable, function that will handle the conversion """ try: return FormatterRegistry.get_by_take_and_return_type(query_result_type, return_type) except (IndexError, AttributeError, KeyError): raise IndexError( 'Could not find function in conversion list for input type %s and return type %s' % ( query_result_type, return_type))
[ "def", "get_handler", "(", "query_result_type", ",", "return_type", ")", ":", "try", ":", "return", "FormatterRegistry", ".", "get_by_take_and_return_type", "(", "query_result_type", ",", "return_type", ")", "except", "(", "IndexError", ",", "AttributeError", ",", "KeyError", ")", ":", "raise", "IndexError", "(", "'Could not find function in conversion list for input type %s and return type %s'", "%", "(", "query_result_type", ",", "return_type", ")", ")" ]
Find the appropriate return type handler to convert the query result to the desired return type :param query_result_type: type, desired return type :param return_type: type, actual return type :return: callable, function that will handle the conversion
[ "Find", "the", "appropriate", "return", "type", "handler", "to", "convert", "the", "query", "result", "to", "the", "desired", "return", "type" ]
e6d6fc28beac042bad588e56fbe77531d2de6b6f
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L42-L54
241,857
AndresMWeber/Nomenclate
nomenclate/core/configurator.py
ConfigEntryFormatter.add_preceding_dict
def add_preceding_dict(config_entry, query_path, preceding_depth): """ Adds the preceeding config keys to the config_entry to simulate the original full path to the config entry :param config_entry: object, the entry that was requested and returned from the config :param query_path: (str, list(str)), the original path to the config_entry :param preceding_depth: int, the depth to which we are recreating the preceding config keys :return: dict, simulated config to n * preceding_depth """ if preceding_depth is None: return config_entry preceding_dict = {query_path[-1]: config_entry} path_length_minus_query_pos = len(query_path) - 1 preceding_depth = path_length_minus_query_pos - preceding_depth if preceding_depth != -1 else 0 for index in reversed(range(preceding_depth, path_length_minus_query_pos)): preceding_dict = {query_path[index]: preceding_dict} return preceding_dict
python
def add_preceding_dict(config_entry, query_path, preceding_depth): """ Adds the preceeding config keys to the config_entry to simulate the original full path to the config entry :param config_entry: object, the entry that was requested and returned from the config :param query_path: (str, list(str)), the original path to the config_entry :param preceding_depth: int, the depth to which we are recreating the preceding config keys :return: dict, simulated config to n * preceding_depth """ if preceding_depth is None: return config_entry preceding_dict = {query_path[-1]: config_entry} path_length_minus_query_pos = len(query_path) - 1 preceding_depth = path_length_minus_query_pos - preceding_depth if preceding_depth != -1 else 0 for index in reversed(range(preceding_depth, path_length_minus_query_pos)): preceding_dict = {query_path[index]: preceding_dict} return preceding_dict
[ "def", "add_preceding_dict", "(", "config_entry", ",", "query_path", ",", "preceding_depth", ")", ":", "if", "preceding_depth", "is", "None", ":", "return", "config_entry", "preceding_dict", "=", "{", "query_path", "[", "-", "1", "]", ":", "config_entry", "}", "path_length_minus_query_pos", "=", "len", "(", "query_path", ")", "-", "1", "preceding_depth", "=", "path_length_minus_query_pos", "-", "preceding_depth", "if", "preceding_depth", "!=", "-", "1", "else", "0", "for", "index", "in", "reversed", "(", "range", "(", "preceding_depth", ",", "path_length_minus_query_pos", ")", ")", ":", "preceding_dict", "=", "{", "query_path", "[", "index", "]", ":", "preceding_dict", "}", "return", "preceding_dict" ]
Adds the preceeding config keys to the config_entry to simulate the original full path to the config entry :param config_entry: object, the entry that was requested and returned from the config :param query_path: (str, list(str)), the original path to the config_entry :param preceding_depth: int, the depth to which we are recreating the preceding config keys :return: dict, simulated config to n * preceding_depth
[ "Adds", "the", "preceeding", "config", "keys", "to", "the", "config_entry", "to", "simulate", "the", "original", "full", "path", "to", "the", "config", "entry" ]
e6d6fc28beac042bad588e56fbe77531d2de6b6f
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L57-L75
241,858
AndresMWeber/Nomenclate
nomenclate/core/configurator.py
ConfigParse.rebuild_config_cache
def rebuild_config_cache(self, config_filepath): """ Loads from file and caches all data from the config file in the form of an OrderedDict to self.data :param config_filepath: str, the full filepath to the config file :return: bool, success status """ self.validate_config_file(config_filepath) config_data = None try: with open(config_filepath, 'r') as f: config_data = yaml.load(f) items = list(iteritems(config_data)) except AttributeError: items = list(config_data) self.config_file_contents = OrderedDict(sorted(items, key=lambda x: x[0], reverse=True)) self.config_filepath = config_filepath
python
def rebuild_config_cache(self, config_filepath): """ Loads from file and caches all data from the config file in the form of an OrderedDict to self.data :param config_filepath: str, the full filepath to the config file :return: bool, success status """ self.validate_config_file(config_filepath) config_data = None try: with open(config_filepath, 'r') as f: config_data = yaml.load(f) items = list(iteritems(config_data)) except AttributeError: items = list(config_data) self.config_file_contents = OrderedDict(sorted(items, key=lambda x: x[0], reverse=True)) self.config_filepath = config_filepath
[ "def", "rebuild_config_cache", "(", "self", ",", "config_filepath", ")", ":", "self", ".", "validate_config_file", "(", "config_filepath", ")", "config_data", "=", "None", "try", ":", "with", "open", "(", "config_filepath", ",", "'r'", ")", "as", "f", ":", "config_data", "=", "yaml", ".", "load", "(", "f", ")", "items", "=", "list", "(", "iteritems", "(", "config_data", ")", ")", "except", "AttributeError", ":", "items", "=", "list", "(", "config_data", ")", "self", ".", "config_file_contents", "=", "OrderedDict", "(", "sorted", "(", "items", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ",", "reverse", "=", "True", ")", ")", "self", ".", "config_filepath", "=", "config_filepath" ]
Loads from file and caches all data from the config file in the form of an OrderedDict to self.data :param config_filepath: str, the full filepath to the config file :return: bool, success status
[ "Loads", "from", "file", "and", "caches", "all", "data", "from", "the", "config", "file", "in", "the", "form", "of", "an", "OrderedDict", "to", "self", ".", "data" ]
e6d6fc28beac042bad588e56fbe77531d2de6b6f
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L111-L128
241,859
AndresMWeber/Nomenclate
nomenclate/core/configurator.py
ConfigParse.get
def get(self, query_path=None, return_type=list, preceding_depth=None, throw_null_return_error=False): """ Traverses the list of query paths to find the data requested :param query_path: (list(str), str), list of query path branches or query string Default behavior: returns list(str) of possible config headers :param return_type: (list, str, dict, OrderedDict), desired return type for the data :param preceding_depth: int, returns a dictionary containing the data that traces back up the path for x depth -1: for the full traversal back up the path None: is default for no traversal :param throw_null_return_error: bool, whether or not to throw an error if we get an empty result but no error :return: (list, str, dict, OrderedDict), the type specified from return_type :raises: exceptions.ResourceNotFoundError: if the query path is invalid """ function_type_lookup = {str: self._get_path_entry_from_string, list: self._get_path_entry_from_list} if query_path is None: return self._default_config(return_type) try: config_entry = function_type_lookup.get(type(query_path), str)(query_path) query_result = self.config_entry_handler.format_query_result(config_entry, query_path, return_type=return_type, preceding_depth=preceding_depth) return query_result except IndexError: return return_type()
python
def get(self, query_path=None, return_type=list, preceding_depth=None, throw_null_return_error=False): """ Traverses the list of query paths to find the data requested :param query_path: (list(str), str), list of query path branches or query string Default behavior: returns list(str) of possible config headers :param return_type: (list, str, dict, OrderedDict), desired return type for the data :param preceding_depth: int, returns a dictionary containing the data that traces back up the path for x depth -1: for the full traversal back up the path None: is default for no traversal :param throw_null_return_error: bool, whether or not to throw an error if we get an empty result but no error :return: (list, str, dict, OrderedDict), the type specified from return_type :raises: exceptions.ResourceNotFoundError: if the query path is invalid """ function_type_lookup = {str: self._get_path_entry_from_string, list: self._get_path_entry_from_list} if query_path is None: return self._default_config(return_type) try: config_entry = function_type_lookup.get(type(query_path), str)(query_path) query_result = self.config_entry_handler.format_query_result(config_entry, query_path, return_type=return_type, preceding_depth=preceding_depth) return query_result except IndexError: return return_type()
[ "def", "get", "(", "self", ",", "query_path", "=", "None", ",", "return_type", "=", "list", ",", "preceding_depth", "=", "None", ",", "throw_null_return_error", "=", "False", ")", ":", "function_type_lookup", "=", "{", "str", ":", "self", ".", "_get_path_entry_from_string", ",", "list", ":", "self", ".", "_get_path_entry_from_list", "}", "if", "query_path", "is", "None", ":", "return", "self", ".", "_default_config", "(", "return_type", ")", "try", ":", "config_entry", "=", "function_type_lookup", ".", "get", "(", "type", "(", "query_path", ")", ",", "str", ")", "(", "query_path", ")", "query_result", "=", "self", ".", "config_entry_handler", ".", "format_query_result", "(", "config_entry", ",", "query_path", ",", "return_type", "=", "return_type", ",", "preceding_depth", "=", "preceding_depth", ")", "return", "query_result", "except", "IndexError", ":", "return", "return_type", "(", ")" ]
Traverses the list of query paths to find the data requested :param query_path: (list(str), str), list of query path branches or query string Default behavior: returns list(str) of possible config headers :param return_type: (list, str, dict, OrderedDict), desired return type for the data :param preceding_depth: int, returns a dictionary containing the data that traces back up the path for x depth -1: for the full traversal back up the path None: is default for no traversal :param throw_null_return_error: bool, whether or not to throw an error if we get an empty result but no error :return: (list, str, dict, OrderedDict), the type specified from return_type :raises: exceptions.ResourceNotFoundError: if the query path is invalid
[ "Traverses", "the", "list", "of", "query", "paths", "to", "find", "the", "data", "requested" ]
e6d6fc28beac042bad588e56fbe77531d2de6b6f
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L130-L158
241,860
AndresMWeber/Nomenclate
nomenclate/core/configurator.py
ConfigParse._get_path_entry_from_string
def _get_path_entry_from_string(self, query_string, first_found=True, full_path=False): """ Parses a string to form a list of strings that represents a possible config entry header :param query_string: str, query string we are looking for :param first_found: bool, return first found entry or entire list :param full_path: bool, whether to return each entry with their corresponding config entry path :return: (Generator((list, str, dict, OrderedDict)), config entries that match the query string :raises: exceptions.ResourceNotFoundError """ iter_matches = gen_dict_key_matches(query_string, self.config_file_contents, full_path=full_path) try: return next(iter_matches) if first_found else iter_matches except (StopIteration, TypeError): raise errors.ResourceNotFoundError('Could not find search string %s in the config file contents %s' % (query_string, self.config_file_contents))
python
def _get_path_entry_from_string(self, query_string, first_found=True, full_path=False): """ Parses a string to form a list of strings that represents a possible config entry header :param query_string: str, query string we are looking for :param first_found: bool, return first found entry or entire list :param full_path: bool, whether to return each entry with their corresponding config entry path :return: (Generator((list, str, dict, OrderedDict)), config entries that match the query string :raises: exceptions.ResourceNotFoundError """ iter_matches = gen_dict_key_matches(query_string, self.config_file_contents, full_path=full_path) try: return next(iter_matches) if first_found else iter_matches except (StopIteration, TypeError): raise errors.ResourceNotFoundError('Could not find search string %s in the config file contents %s' % (query_string, self.config_file_contents))
[ "def", "_get_path_entry_from_string", "(", "self", ",", "query_string", ",", "first_found", "=", "True", ",", "full_path", "=", "False", ")", ":", "iter_matches", "=", "gen_dict_key_matches", "(", "query_string", ",", "self", ".", "config_file_contents", ",", "full_path", "=", "full_path", ")", "try", ":", "return", "next", "(", "iter_matches", ")", "if", "first_found", "else", "iter_matches", "except", "(", "StopIteration", ",", "TypeError", ")", ":", "raise", "errors", ".", "ResourceNotFoundError", "(", "'Could not find search string %s in the config file contents %s'", "%", "(", "query_string", ",", "self", ".", "config_file_contents", ")", ")" ]
Parses a string to form a list of strings that represents a possible config entry header :param query_string: str, query string we are looking for :param first_found: bool, return first found entry or entire list :param full_path: bool, whether to return each entry with their corresponding config entry path :return: (Generator((list, str, dict, OrderedDict)), config entries that match the query string :raises: exceptions.ResourceNotFoundError
[ "Parses", "a", "string", "to", "form", "a", "list", "of", "strings", "that", "represents", "a", "possible", "config", "entry", "header" ]
e6d6fc28beac042bad588e56fbe77531d2de6b6f
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L160-L174
241,861
AndresMWeber/Nomenclate
nomenclate/core/configurator.py
ConfigParse._get_path_entry_from_list
def _get_path_entry_from_list(self, query_path): """ Returns the config entry at query path :param query_path: list(str), config header path to follow for entry :return: (list, str, dict, OrderedDict), config entry requested :raises: exceptions.ResourceNotFoundError """ cur_data = self.config_file_contents try: for child in query_path: cur_data = cur_data[child] return cur_data except (AttributeError, KeyError): raise errors.ResourceNotFoundError('Could not find query path %s in the config file contents' % query_path)
python
def _get_path_entry_from_list(self, query_path): """ Returns the config entry at query path :param query_path: list(str), config header path to follow for entry :return: (list, str, dict, OrderedDict), config entry requested :raises: exceptions.ResourceNotFoundError """ cur_data = self.config_file_contents try: for child in query_path: cur_data = cur_data[child] return cur_data except (AttributeError, KeyError): raise errors.ResourceNotFoundError('Could not find query path %s in the config file contents' % query_path)
[ "def", "_get_path_entry_from_list", "(", "self", ",", "query_path", ")", ":", "cur_data", "=", "self", ".", "config_file_contents", "try", ":", "for", "child", "in", "query_path", ":", "cur_data", "=", "cur_data", "[", "child", "]", "return", "cur_data", "except", "(", "AttributeError", ",", "KeyError", ")", ":", "raise", "errors", ".", "ResourceNotFoundError", "(", "'Could not find query path %s in the config file contents'", "%", "query_path", ")" ]
Returns the config entry at query path :param query_path: list(str), config header path to follow for entry :return: (list, str, dict, OrderedDict), config entry requested :raises: exceptions.ResourceNotFoundError
[ "Returns", "the", "config", "entry", "at", "query", "path" ]
e6d6fc28beac042bad588e56fbe77531d2de6b6f
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L176-L190
241,862
AndresMWeber/Nomenclate
nomenclate/core/configurator.py
ConfigParse.validate_config_file
def validate_config_file(cls, config_filepath): """ Validates the filepath to the config. Detects whether it is a true YAML file + existance :param config_filepath: str, file path to the config file to query :return: None :raises: IOError """ is_file = os.path.isfile(config_filepath) if not is_file and os.path.isabs(config_filepath): raise IOError('File path %s is not a valid yml, ini or cfg file or does not exist' % config_filepath) elif is_file: if os.path.getsize(config_filepath) == 0: raise IOError('File %s is empty' % config_filepath) with open(config_filepath, 'r') as f: if yaml.load(f) is None: raise IOError('No YAML config was found in file %s' % config_filepath)
python
def validate_config_file(cls, config_filepath): """ Validates the filepath to the config. Detects whether it is a true YAML file + existance :param config_filepath: str, file path to the config file to query :return: None :raises: IOError """ is_file = os.path.isfile(config_filepath) if not is_file and os.path.isabs(config_filepath): raise IOError('File path %s is not a valid yml, ini or cfg file or does not exist' % config_filepath) elif is_file: if os.path.getsize(config_filepath) == 0: raise IOError('File %s is empty' % config_filepath) with open(config_filepath, 'r') as f: if yaml.load(f) is None: raise IOError('No YAML config was found in file %s' % config_filepath)
[ "def", "validate_config_file", "(", "cls", ",", "config_filepath", ")", ":", "is_file", "=", "os", ".", "path", ".", "isfile", "(", "config_filepath", ")", "if", "not", "is_file", "and", "os", ".", "path", ".", "isabs", "(", "config_filepath", ")", ":", "raise", "IOError", "(", "'File path %s is not a valid yml, ini or cfg file or does not exist'", "%", "config_filepath", ")", "elif", "is_file", ":", "if", "os", ".", "path", ".", "getsize", "(", "config_filepath", ")", "==", "0", ":", "raise", "IOError", "(", "'File %s is empty'", "%", "config_filepath", ")", "with", "open", "(", "config_filepath", ",", "'r'", ")", "as", "f", ":", "if", "yaml", ".", "load", "(", "f", ")", "is", "None", ":", "raise", "IOError", "(", "'No YAML config was found in file %s'", "%", "config_filepath", ")" ]
Validates the filepath to the config. Detects whether it is a true YAML file + existance :param config_filepath: str, file path to the config file to query :return: None :raises: IOError
[ "Validates", "the", "filepath", "to", "the", "config", ".", "Detects", "whether", "it", "is", "a", "true", "YAML", "file", "+", "existance" ]
e6d6fc28beac042bad588e56fbe77531d2de6b6f
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L203-L220
241,863
luismasuelli/python-cantrips
cantrips/features.py
Feature.import_it
def import_it(cls): """ Performs the import only once. """ if not cls in cls._FEATURES: try: cls._FEATURES[cls] = cls._import_it() except ImportError: raise cls.Error(cls._import_error_message(), cls.Error.UNSATISFIED_IMPORT_REQ) return cls._FEATURES[cls]
python
def import_it(cls): """ Performs the import only once. """ if not cls in cls._FEATURES: try: cls._FEATURES[cls] = cls._import_it() except ImportError: raise cls.Error(cls._import_error_message(), cls.Error.UNSATISFIED_IMPORT_REQ) return cls._FEATURES[cls]
[ "def", "import_it", "(", "cls", ")", ":", "if", "not", "cls", "in", "cls", ".", "_FEATURES", ":", "try", ":", "cls", ".", "_FEATURES", "[", "cls", "]", "=", "cls", ".", "_import_it", "(", ")", "except", "ImportError", ":", "raise", "cls", ".", "Error", "(", "cls", ".", "_import_error_message", "(", ")", ",", "cls", ".", "Error", ".", "UNSATISFIED_IMPORT_REQ", ")", "return", "cls", ".", "_FEATURES", "[", "cls", "]" ]
Performs the import only once.
[ "Performs", "the", "import", "only", "once", "." ]
dba2742c1d1a60863bb65f4a291464f6e68eb2ee
https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/features.py#L12-L21
241,864
goldsborough/li
li/cache.py
read
def read(author, kind): """ Attempts to read the cache to fetch missing arguments. This method will attempt to find a '.license' file in the 'CACHE_DIRECTORY', to read any arguments that were not passed to the license utility. Arguments: author (str): The author passed, if any. kind (str): The kind of license passed, if any. Throws: LicenseError, if there was a cache miss or I/O error. """ if not os.path.exists(CACHE_PATH): raise LicenseError('No cache found. You must ' 'supply at least -a and -k.') cache = read_cache() if author is None: author = read_author(cache) if kind is None: kind = read_kind(cache) return author, kind
python
def read(author, kind): """ Attempts to read the cache to fetch missing arguments. This method will attempt to find a '.license' file in the 'CACHE_DIRECTORY', to read any arguments that were not passed to the license utility. Arguments: author (str): The author passed, if any. kind (str): The kind of license passed, if any. Throws: LicenseError, if there was a cache miss or I/O error. """ if not os.path.exists(CACHE_PATH): raise LicenseError('No cache found. You must ' 'supply at least -a and -k.') cache = read_cache() if author is None: author = read_author(cache) if kind is None: kind = read_kind(cache) return author, kind
[ "def", "read", "(", "author", ",", "kind", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "CACHE_PATH", ")", ":", "raise", "LicenseError", "(", "'No cache found. You must '", "'supply at least -a and -k.'", ")", "cache", "=", "read_cache", "(", ")", "if", "author", "is", "None", ":", "author", "=", "read_author", "(", "cache", ")", "if", "kind", "is", "None", ":", "kind", "=", "read_kind", "(", "cache", ")", "return", "author", ",", "kind" ]
Attempts to read the cache to fetch missing arguments. This method will attempt to find a '.license' file in the 'CACHE_DIRECTORY', to read any arguments that were not passed to the license utility. Arguments: author (str): The author passed, if any. kind (str): The kind of license passed, if any. Throws: LicenseError, if there was a cache miss or I/O error.
[ "Attempts", "to", "read", "the", "cache", "to", "fetch", "missing", "arguments", "." ]
8ea4f8b55183aadaa96bc70cfcfcb7b198874319
https://github.com/goldsborough/li/blob/8ea4f8b55183aadaa96bc70cfcfcb7b198874319/li/cache.py#L26-L53
241,865
Baguage/django-auth-pubtkt
django_auth_pubtkt/auth_pubtkt.py
Authpubtkt.verify_ticket_signature
def verify_ticket_signature(self, data, sig): """Verify ticket signature. """ try: signature = base64.b64decode(sig) except TypeError as e: if hasattr(self, "debug"): print("Exception in function base64.b64decode. File %s" % (__file__)) print("%s" % e) return False if six.PY3: # To avoid "TypeError: Unicode-objects must be encoded before hashing' data = data.encode('utf-8') digest = hashlib.sha1(data).digest() if isinstance(self.pub_key, RSA.RSA_pub): try: self.pub_key.verify(digest, signature, 'sha1') except RSA.RSAError: return False return True if isinstance(self.pub_key, DSA.DSA_pub): try: return self.pub_key.verify_asn1(digest, signature) except DSA.DSAError as e: if hasattr(self, "debug"): print("Exception in function self.pub_key.verify_asn1(digest, signature). File %s" % (__file__)) print("%s" % e) return False # Unknown key type return False
python
def verify_ticket_signature(self, data, sig): """Verify ticket signature. """ try: signature = base64.b64decode(sig) except TypeError as e: if hasattr(self, "debug"): print("Exception in function base64.b64decode. File %s" % (__file__)) print("%s" % e) return False if six.PY3: # To avoid "TypeError: Unicode-objects must be encoded before hashing' data = data.encode('utf-8') digest = hashlib.sha1(data).digest() if isinstance(self.pub_key, RSA.RSA_pub): try: self.pub_key.verify(digest, signature, 'sha1') except RSA.RSAError: return False return True if isinstance(self.pub_key, DSA.DSA_pub): try: return self.pub_key.verify_asn1(digest, signature) except DSA.DSAError as e: if hasattr(self, "debug"): print("Exception in function self.pub_key.verify_asn1(digest, signature). File %s" % (__file__)) print("%s" % e) return False # Unknown key type return False
[ "def", "verify_ticket_signature", "(", "self", ",", "data", ",", "sig", ")", ":", "try", ":", "signature", "=", "base64", ".", "b64decode", "(", "sig", ")", "except", "TypeError", "as", "e", ":", "if", "hasattr", "(", "self", ",", "\"debug\"", ")", ":", "print", "(", "\"Exception in function base64.b64decode. File %s\"", "%", "(", "__file__", ")", ")", "print", "(", "\"%s\"", "%", "e", ")", "return", "False", "if", "six", ".", "PY3", ":", "# To avoid \"TypeError: Unicode-objects must be encoded before hashing'", "data", "=", "data", ".", "encode", "(", "'utf-8'", ")", "digest", "=", "hashlib", ".", "sha1", "(", "data", ")", ".", "digest", "(", ")", "if", "isinstance", "(", "self", ".", "pub_key", ",", "RSA", ".", "RSA_pub", ")", ":", "try", ":", "self", ".", "pub_key", ".", "verify", "(", "digest", ",", "signature", ",", "'sha1'", ")", "except", "RSA", ".", "RSAError", ":", "return", "False", "return", "True", "if", "isinstance", "(", "self", ".", "pub_key", ",", "DSA", ".", "DSA_pub", ")", ":", "try", ":", "return", "self", ".", "pub_key", ".", "verify_asn1", "(", "digest", ",", "signature", ")", "except", "DSA", ".", "DSAError", "as", "e", ":", "if", "hasattr", "(", "self", ",", "\"debug\"", ")", ":", "print", "(", "\"Exception in function self.pub_key.verify_asn1(digest, signature). File %s\"", "%", "(", "__file__", ")", ")", "print", "(", "\"%s\"", "%", "e", ")", "return", "False", "# Unknown key type", "return", "False" ]
Verify ticket signature.
[ "Verify", "ticket", "signature", "." ]
d3f4284212ffbfdc3588929a31e36a4cc7f39786
https://github.com/Baguage/django-auth-pubtkt/blob/d3f4284212ffbfdc3588929a31e36a4cc7f39786/django_auth_pubtkt/auth_pubtkt.py#L45-L73
241,866
krukas/Trionyx
trionyx/trionyx/apps.py
Config.ready
def ready(self): """Auto load Trionyx""" models_config.auto_load_configs() self.auto_load_app_modules(['layouts', 'signals']) app_menu.auto_load_model_menu() auto_register_search_models() tabs.auto_generate_missing_tabs()
python
def ready(self): """Auto load Trionyx""" models_config.auto_load_configs() self.auto_load_app_modules(['layouts', 'signals']) app_menu.auto_load_model_menu() auto_register_search_models() tabs.auto_generate_missing_tabs()
[ "def", "ready", "(", "self", ")", ":", "models_config", ".", "auto_load_configs", "(", ")", "self", ".", "auto_load_app_modules", "(", "[", "'layouts'", ",", "'signals'", "]", ")", "app_menu", ".", "auto_load_model_menu", "(", ")", "auto_register_search_models", "(", ")", "tabs", ".", "auto_generate_missing_tabs", "(", ")" ]
Auto load Trionyx
[ "Auto", "load", "Trionyx" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/apps.py#L36-L45
241,867
krukas/Trionyx
trionyx/trionyx/apps.py
Config.auto_load_app_modules
def auto_load_app_modules(self, modules): """Auto load app modules""" for app in apps.get_app_configs(): for module in modules: try: import_module('{}.{}'.format(app.module.__package__, module)) except ImportError: pass
python
def auto_load_app_modules(self, modules): """Auto load app modules""" for app in apps.get_app_configs(): for module in modules: try: import_module('{}.{}'.format(app.module.__package__, module)) except ImportError: pass
[ "def", "auto_load_app_modules", "(", "self", ",", "modules", ")", ":", "for", "app", "in", "apps", ".", "get_app_configs", "(", ")", ":", "for", "module", "in", "modules", ":", "try", ":", "import_module", "(", "'{}.{}'", ".", "format", "(", "app", ".", "module", ".", "__package__", ",", "module", ")", ")", "except", "ImportError", ":", "pass" ]
Auto load app modules
[ "Auto", "load", "app", "modules" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/apps.py#L47-L54
241,868
goldsborough/li
scripts/bump.py
bump
def bump(match): """Bumps the version""" before, old_version, after = match.groups() major, minor, patch = map(int, old_version.split('.')) patch += 1 if patch == 10: patch = 0 minor += 1 if minor == 10: minor = 0 major += 1 new_version = '{0}.{1}.{2}'.format(major, minor, patch) print('{0} => {1}'.format(old_version, new_version)) return before + new_version + after
python
def bump(match): """Bumps the version""" before, old_version, after = match.groups() major, minor, patch = map(int, old_version.split('.')) patch += 1 if patch == 10: patch = 0 minor += 1 if minor == 10: minor = 0 major += 1 new_version = '{0}.{1}.{2}'.format(major, minor, patch) print('{0} => {1}'.format(old_version, new_version)) return before + new_version + after
[ "def", "bump", "(", "match", ")", ":", "before", ",", "old_version", ",", "after", "=", "match", ".", "groups", "(", ")", "major", ",", "minor", ",", "patch", "=", "map", "(", "int", ",", "old_version", ".", "split", "(", "'.'", ")", ")", "patch", "+=", "1", "if", "patch", "==", "10", ":", "patch", "=", "0", "minor", "+=", "1", "if", "minor", "==", "10", ":", "minor", "=", "0", "major", "+=", "1", "new_version", "=", "'{0}.{1}.{2}'", ".", "format", "(", "major", ",", "minor", ",", "patch", ")", "print", "(", "'{0} => {1}'", ".", "format", "(", "old_version", ",", "new_version", ")", ")", "return", "before", "+", "new_version", "+", "after" ]
Bumps the version
[ "Bumps", "the", "version" ]
8ea4f8b55183aadaa96bc70cfcfcb7b198874319
https://github.com/goldsborough/li/blob/8ea4f8b55183aadaa96bc70cfcfcb7b198874319/scripts/bump.py#L11-L26
241,869
wadoon/ansitagcolor
ansitagcolor.py
term._write_raw
def _write_raw(self, suffix): """ writes a the suffix prefixed by the CSI to the handle """ if not self.enabled: return self.buffer.write(CSI) self.buffer.write(suffix)
python
def _write_raw(self, suffix): """ writes a the suffix prefixed by the CSI to the handle """ if not self.enabled: return self.buffer.write(CSI) self.buffer.write(suffix)
[ "def", "_write_raw", "(", "self", ",", "suffix", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "self", ".", "buffer", ".", "write", "(", "CSI", ")", "self", ".", "buffer", ".", "write", "(", "suffix", ")" ]
writes a the suffix prefixed by the CSI to the handle
[ "writes", "a", "the", "suffix", "prefixed", "by", "the", "CSI", "to", "the", "handle" ]
7247ee8ec3b91590a07c68a7889ec87c5137b82d
https://github.com/wadoon/ansitagcolor/blob/7247ee8ec3b91590a07c68a7889ec87c5137b82d/ansitagcolor.py#L191-L198
241,870
Kopachris/seshet
seshet/config.py
build_db_tables
def build_db_tables(db): """Build Seshet's basic database schema. Requires one parameter, `db` as `pydal.DAL` instance. """ if not isinstance(db, DAL) or not db._uri: raise Exception("Need valid DAL object to define tables") # event log - self-explanatory, logs all events db.define_table('event_log', Field('event_type'), Field('event_time', 'datetime'), Field('source'), Field('target'), Field('message', 'text'), Field('host'), Field('params', 'list:string'), ) db.define_table('modules', Field('name', notnull=True, unique=True, length=256), Field('enabled', 'boolean'), Field('event_types', 'list:string'), Field('description', 'text'), Field('echannels', 'list:string'), Field('dchannels', 'list:string'), Field('enicks', 'list:string'), Field('dnicks', 'list:string'), Field('whitelist', 'list:string'), Field('blacklist', 'list:string'), Field('cmd_prefix', length=1, default='!', notnull=True), Field('acl', 'json'), Field('rate_limit', 'json'), )
python
def build_db_tables(db): """Build Seshet's basic database schema. Requires one parameter, `db` as `pydal.DAL` instance. """ if not isinstance(db, DAL) or not db._uri: raise Exception("Need valid DAL object to define tables") # event log - self-explanatory, logs all events db.define_table('event_log', Field('event_type'), Field('event_time', 'datetime'), Field('source'), Field('target'), Field('message', 'text'), Field('host'), Field('params', 'list:string'), ) db.define_table('modules', Field('name', notnull=True, unique=True, length=256), Field('enabled', 'boolean'), Field('event_types', 'list:string'), Field('description', 'text'), Field('echannels', 'list:string'), Field('dchannels', 'list:string'), Field('enicks', 'list:string'), Field('dnicks', 'list:string'), Field('whitelist', 'list:string'), Field('blacklist', 'list:string'), Field('cmd_prefix', length=1, default='!', notnull=True), Field('acl', 'json'), Field('rate_limit', 'json'), )
[ "def", "build_db_tables", "(", "db", ")", ":", "if", "not", "isinstance", "(", "db", ",", "DAL", ")", "or", "not", "db", ".", "_uri", ":", "raise", "Exception", "(", "\"Need valid DAL object to define tables\"", ")", "# event log - self-explanatory, logs all events", "db", ".", "define_table", "(", "'event_log'", ",", "Field", "(", "'event_type'", ")", ",", "Field", "(", "'event_time'", ",", "'datetime'", ")", ",", "Field", "(", "'source'", ")", ",", "Field", "(", "'target'", ")", ",", "Field", "(", "'message'", ",", "'text'", ")", ",", "Field", "(", "'host'", ")", ",", "Field", "(", "'params'", ",", "'list:string'", ")", ",", ")", "db", ".", "define_table", "(", "'modules'", ",", "Field", "(", "'name'", ",", "notnull", "=", "True", ",", "unique", "=", "True", ",", "length", "=", "256", ")", ",", "Field", "(", "'enabled'", ",", "'boolean'", ")", ",", "Field", "(", "'event_types'", ",", "'list:string'", ")", ",", "Field", "(", "'description'", ",", "'text'", ")", ",", "Field", "(", "'echannels'", ",", "'list:string'", ")", ",", "Field", "(", "'dchannels'", ",", "'list:string'", ")", ",", "Field", "(", "'enicks'", ",", "'list:string'", ")", ",", "Field", "(", "'dnicks'", ",", "'list:string'", ")", ",", "Field", "(", "'whitelist'", ",", "'list:string'", ")", ",", "Field", "(", "'blacklist'", ",", "'list:string'", ")", ",", "Field", "(", "'cmd_prefix'", ",", "length", "=", "1", ",", "default", "=", "'!'", ",", "notnull", "=", "True", ")", ",", "Field", "(", "'acl'", ",", "'json'", ")", ",", "Field", "(", "'rate_limit'", ",", "'json'", ")", ",", ")" ]
Build Seshet's basic database schema. Requires one parameter, `db` as `pydal.DAL` instance.
[ "Build", "Seshet", "s", "basic", "database", "schema", ".", "Requires", "one", "parameter", "db", "as", "pydal", ".", "DAL", "instance", "." ]
d55bae01cff56762c5467138474145a2c17d1932
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/config.py#L121-L153
241,871
dschien/PyExcelModelingHelper
excel_helper/__init__.py
DistributionFunctionGenerator.generate_values
def generate_values(self, *args, **kwargs): """ Generate a sample of values by sampling from a distribution. The size of the sample can be overriden with the 'size' kwarg. If `self.sample_mean_value == True` the sample will contain "size" times the mean value. :param args: :param kwargs: :return: sample as vector of given size """ sample_size = kwargs.get('size', self.size) f = self.instantiate_distribution_function(self.module_name, self.distribution_name) distribution_function = partial(f, *self.random_function_params, size=sample_size) if self.sample_mean_value: sample = np.full(sample_size, self.get_mean(distribution_function)) else: sample = distribution_function() return sample
python
def generate_values(self, *args, **kwargs): """ Generate a sample of values by sampling from a distribution. The size of the sample can be overriden with the 'size' kwarg. If `self.sample_mean_value == True` the sample will contain "size" times the mean value. :param args: :param kwargs: :return: sample as vector of given size """ sample_size = kwargs.get('size', self.size) f = self.instantiate_distribution_function(self.module_name, self.distribution_name) distribution_function = partial(f, *self.random_function_params, size=sample_size) if self.sample_mean_value: sample = np.full(sample_size, self.get_mean(distribution_function)) else: sample = distribution_function() return sample
[ "def", "generate_values", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "sample_size", "=", "kwargs", ".", "get", "(", "'size'", ",", "self", ".", "size", ")", "f", "=", "self", ".", "instantiate_distribution_function", "(", "self", ".", "module_name", ",", "self", ".", "distribution_name", ")", "distribution_function", "=", "partial", "(", "f", ",", "*", "self", ".", "random_function_params", ",", "size", "=", "sample_size", ")", "if", "self", ".", "sample_mean_value", ":", "sample", "=", "np", ".", "full", "(", "sample_size", ",", "self", ".", "get_mean", "(", "distribution_function", ")", ")", "else", ":", "sample", "=", "distribution_function", "(", ")", "return", "sample" ]
Generate a sample of values by sampling from a distribution. The size of the sample can be overriden with the 'size' kwarg. If `self.sample_mean_value == True` the sample will contain "size" times the mean value. :param args: :param kwargs: :return: sample as vector of given size
[ "Generate", "a", "sample", "of", "values", "by", "sampling", "from", "a", "distribution", ".", "The", "size", "of", "the", "sample", "can", "be", "overriden", "with", "the", "size", "kwarg", "." ]
d00d98ae2f28ad71cfcd2a365c3045e439517df2
https://github.com/dschien/PyExcelModelingHelper/blob/d00d98ae2f28ad71cfcd2a365c3045e439517df2/excel_helper/__init__.py#L112-L132
241,872
dschien/PyExcelModelingHelper
excel_helper/__init__.py
ParameterScenarioSet.add_scenario
def add_scenario(self, parameter: 'Parameter', scenario_name: str = default_scenario): """ Add a scenario for this parameter. :param scenario_name: :param parameter: :return: """ self.scenarios[scenario_name] = parameter
python
def add_scenario(self, parameter: 'Parameter', scenario_name: str = default_scenario): """ Add a scenario for this parameter. :param scenario_name: :param parameter: :return: """ self.scenarios[scenario_name] = parameter
[ "def", "add_scenario", "(", "self", ",", "parameter", ":", "'Parameter'", ",", "scenario_name", ":", "str", "=", "default_scenario", ")", ":", "self", ".", "scenarios", "[", "scenario_name", "]", "=", "parameter" ]
Add a scenario for this parameter. :param scenario_name: :param parameter: :return:
[ "Add", "a", "scenario", "for", "this", "parameter", "." ]
d00d98ae2f28ad71cfcd2a365c3045e439517df2
https://github.com/dschien/PyExcelModelingHelper/blob/d00d98ae2f28ad71cfcd2a365c3045e439517df2/excel_helper/__init__.py#L438-L446
241,873
dschien/PyExcelModelingHelper
excel_helper/__init__.py
ParameterRepository.fill_missing_attributes_from_default_parameter
def fill_missing_attributes_from_default_parameter(self, param): """ Empty fields in Parameter definitions in scenarios are populated with default values. E.g. in the example below, the source for the Power_TV variable in the 8K scenario would also be EnergyStar. | name | scenario | val | tags | source | |----------|----------|-----|--------|------------| | Power_TV | | 60 | UD, TV | EnergyStar | | Power_TV | 8K | 85 | new_tag| | **Note** tags must not differ. In the example above, the 8K scenario variable the tags value would be overwritten with the default value. :param param: :return: """ if not self.exists(param.name) or not ParameterScenarioSet.default_scenario in self.parameter_sets[ param.name].scenarios.keys(): logger.warning( f'No default value for param {param.name} found.') return default = self.parameter_sets[param.name][ParameterScenarioSet.default_scenario] for att_name, att_value in default.__dict__.items(): if att_name in ['unit', 'label', 'comment', 'source', 'tags']: if att_name == 'tags' and default.tags != param.tags: logger.warning( f'For param {param.name} for scenarios {param.source_scenarios_string}, tags is different from default parameter tags. Overwriting with default values.') setattr(param, att_name, att_value) if not getattr(param, att_name): logger.debug( f'For param {param.name} for scenarios {param.source_scenarios_string}, populating attribute {att_name} with value {att_value} from default parameter.') setattr(param, att_name, att_value)
python
def fill_missing_attributes_from_default_parameter(self, param): """ Empty fields in Parameter definitions in scenarios are populated with default values. E.g. in the example below, the source for the Power_TV variable in the 8K scenario would also be EnergyStar. | name | scenario | val | tags | source | |----------|----------|-----|--------|------------| | Power_TV | | 60 | UD, TV | EnergyStar | | Power_TV | 8K | 85 | new_tag| | **Note** tags must not differ. In the example above, the 8K scenario variable the tags value would be overwritten with the default value. :param param: :return: """ if not self.exists(param.name) or not ParameterScenarioSet.default_scenario in self.parameter_sets[ param.name].scenarios.keys(): logger.warning( f'No default value for param {param.name} found.') return default = self.parameter_sets[param.name][ParameterScenarioSet.default_scenario] for att_name, att_value in default.__dict__.items(): if att_name in ['unit', 'label', 'comment', 'source', 'tags']: if att_name == 'tags' and default.tags != param.tags: logger.warning( f'For param {param.name} for scenarios {param.source_scenarios_string}, tags is different from default parameter tags. Overwriting with default values.') setattr(param, att_name, att_value) if not getattr(param, att_name): logger.debug( f'For param {param.name} for scenarios {param.source_scenarios_string}, populating attribute {att_name} with value {att_value} from default parameter.') setattr(param, att_name, att_value)
[ "def", "fill_missing_attributes_from_default_parameter", "(", "self", ",", "param", ")", ":", "if", "not", "self", ".", "exists", "(", "param", ".", "name", ")", "or", "not", "ParameterScenarioSet", ".", "default_scenario", "in", "self", ".", "parameter_sets", "[", "param", ".", "name", "]", ".", "scenarios", ".", "keys", "(", ")", ":", "logger", ".", "warning", "(", "f'No default value for param {param.name} found.'", ")", "return", "default", "=", "self", ".", "parameter_sets", "[", "param", ".", "name", "]", "[", "ParameterScenarioSet", ".", "default_scenario", "]", "for", "att_name", ",", "att_value", "in", "default", ".", "__dict__", ".", "items", "(", ")", ":", "if", "att_name", "in", "[", "'unit'", ",", "'label'", ",", "'comment'", ",", "'source'", ",", "'tags'", "]", ":", "if", "att_name", "==", "'tags'", "and", "default", ".", "tags", "!=", "param", ".", "tags", ":", "logger", ".", "warning", "(", "f'For param {param.name} for scenarios {param.source_scenarios_string}, tags is different from default parameter tags. Overwriting with default values.'", ")", "setattr", "(", "param", ",", "att_name", ",", "att_value", ")", "if", "not", "getattr", "(", "param", ",", "att_name", ")", ":", "logger", ".", "debug", "(", "f'For param {param.name} for scenarios {param.source_scenarios_string}, populating attribute {att_name} with value {att_value} from default parameter.'", ")", "setattr", "(", "param", ",", "att_name", ",", "att_value", ")" ]
Empty fields in Parameter definitions in scenarios are populated with default values. E.g. in the example below, the source for the Power_TV variable in the 8K scenario would also be EnergyStar. | name | scenario | val | tags | source | |----------|----------|-----|--------|------------| | Power_TV | | 60 | UD, TV | EnergyStar | | Power_TV | 8K | 85 | new_tag| | **Note** tags must not differ. In the example above, the 8K scenario variable the tags value would be overwritten with the default value. :param param: :return:
[ "Empty", "fields", "in", "Parameter", "definitions", "in", "scenarios", "are", "populated", "with", "default", "values", "." ]
d00d98ae2f28ad71cfcd2a365c3045e439517df2
https://github.com/dschien/PyExcelModelingHelper/blob/d00d98ae2f28ad71cfcd2a365c3045e439517df2/excel_helper/__init__.py#L506-L541
241,874
dschien/PyExcelModelingHelper
excel_helper/__init__.py
ParameterRepository.find_by_tag
def find_by_tag(self, tag) -> Dict[str, Set[Parameter]]: """ Get all registered dicts that are registered for a tag :param tag: str - single tag :return: a dict of {param name: set[Parameter]} that contains all ParameterScenarioSets for all parameter names with a given tag """ return self.tags[tag]
python
def find_by_tag(self, tag) -> Dict[str, Set[Parameter]]: """ Get all registered dicts that are registered for a tag :param tag: str - single tag :return: a dict of {param name: set[Parameter]} that contains all ParameterScenarioSets for all parameter names with a given tag """ return self.tags[tag]
[ "def", "find_by_tag", "(", "self", ",", "tag", ")", "->", "Dict", "[", "str", ",", "Set", "[", "Parameter", "]", "]", ":", "return", "self", ".", "tags", "[", "tag", "]" ]
Get all registered dicts that are registered for a tag :param tag: str - single tag :return: a dict of {param name: set[Parameter]} that contains all ParameterScenarioSets for all parameter names with a given tag
[ "Get", "all", "registered", "dicts", "that", "are", "registered", "for", "a", "tag" ]
d00d98ae2f28ad71cfcd2a365c3045e439517df2
https://github.com/dschien/PyExcelModelingHelper/blob/d00d98ae2f28ad71cfcd2a365c3045e439517df2/excel_helper/__init__.py#L560-L568
241,875
dschien/PyExcelModelingHelper
excel_helper/__init__.py
ExcelParameterLoader.load_parameter_definitions
def load_parameter_definitions(self, sheet_name: str = None): """ Load variable text from rows in excel file. If no spreadsheet arg is given, all spreadsheets are loaded. The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored. Any cells used as titles (with no associated value) are also added to the returned dictionary. However, the values associated with each header will be None. For example, given the speadsheet: | variable | A | B | |----------|---|---| | Title | | | | Entry | 1 | 2 | The following list of definitions would be returned: [ { variable: 'Title', A: None, B: None } , { variable: 'Entry', A: 1 , B: 2 } ] :param sheet_name: :return: list of dicts with {header col name : cell value} pairs """ definitions = self.excel_handler.load_definitions(sheet_name, filename=self.filename) self.definition_version = self.excel_handler.version return definitions
python
def load_parameter_definitions(self, sheet_name: str = None): """ Load variable text from rows in excel file. If no spreadsheet arg is given, all spreadsheets are loaded. The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored. Any cells used as titles (with no associated value) are also added to the returned dictionary. However, the values associated with each header will be None. For example, given the speadsheet: | variable | A | B | |----------|---|---| | Title | | | | Entry | 1 | 2 | The following list of definitions would be returned: [ { variable: 'Title', A: None, B: None } , { variable: 'Entry', A: 1 , B: 2 } ] :param sheet_name: :return: list of dicts with {header col name : cell value} pairs """ definitions = self.excel_handler.load_definitions(sheet_name, filename=self.filename) self.definition_version = self.excel_handler.version return definitions
[ "def", "load_parameter_definitions", "(", "self", ",", "sheet_name", ":", "str", "=", "None", ")", ":", "definitions", "=", "self", ".", "excel_handler", ".", "load_definitions", "(", "sheet_name", ",", "filename", "=", "self", ".", "filename", ")", "self", ".", "definition_version", "=", "self", ".", "excel_handler", ".", "version", "return", "definitions" ]
Load variable text from rows in excel file. If no spreadsheet arg is given, all spreadsheets are loaded. The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored. Any cells used as titles (with no associated value) are also added to the returned dictionary. However, the values associated with each header will be None. For example, given the speadsheet: | variable | A | B | |----------|---|---| | Title | | | | Entry | 1 | 2 | The following list of definitions would be returned: [ { variable: 'Title', A: None, B: None } , { variable: 'Entry', A: 1 , B: 2 } ] :param sheet_name: :return: list of dicts with {header col name : cell value} pairs
[ "Load", "variable", "text", "from", "rows", "in", "excel", "file", ".", "If", "no", "spreadsheet", "arg", "is", "given", "all", "spreadsheets", "are", "loaded", ".", "The", "first", "cell", "in", "the", "first", "row", "in", "a", "spreadsheet", "must", "contain", "the", "keyword", "variable", "or", "the", "sheet", "is", "ignored", "." ]
d00d98ae2f28ad71cfcd2a365c3045e439517df2
https://github.com/dschien/PyExcelModelingHelper/blob/d00d98ae2f28ad71cfcd2a365c3045e439517df2/excel_helper/__init__.py#L787-L812
241,876
Naught0/lolrune
lolrune/runeclient.py
RuneClient._get
def _get(self, url: str) -> str: """A small wrapper method which makes a quick GET request. Parameters ---------- url : str The URL to get. Returns ------- str The raw html of the requested page. Raises ------ RuneConnectionError If the GET response status is not 200. """ resp = self.session.get(url, headers=self.HEADERS) if resp.status_code is 200: return resp.text else: raise RuneConnectionError(resp.status_code)
python
def _get(self, url: str) -> str: """A small wrapper method which makes a quick GET request. Parameters ---------- url : str The URL to get. Returns ------- str The raw html of the requested page. Raises ------ RuneConnectionError If the GET response status is not 200. """ resp = self.session.get(url, headers=self.HEADERS) if resp.status_code is 200: return resp.text else: raise RuneConnectionError(resp.status_code)
[ "def", "_get", "(", "self", ",", "url", ":", "str", ")", "->", "str", ":", "resp", "=", "self", ".", "session", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "HEADERS", ")", "if", "resp", ".", "status_code", "is", "200", ":", "return", "resp", ".", "text", "else", ":", "raise", "RuneConnectionError", "(", "resp", ".", "status_code", ")" ]
A small wrapper method which makes a quick GET request. Parameters ---------- url : str The URL to get. Returns ------- str The raw html of the requested page. Raises ------ RuneConnectionError If the GET response status is not 200.
[ "A", "small", "wrapper", "method", "which", "makes", "a", "quick", "GET", "request", "." ]
99f67b9137e42a78198ba369ceb371e473759f11
https://github.com/Naught0/lolrune/blob/99f67b9137e42a78198ba369ceb371e473759f11/lolrune/runeclient.py#L52-L74
241,877
edwards-lab/libGWAS
libgwas/__init__.py
sys_call
def sys_call(cmd): """Execute cmd and capture stdout and stderr :param cmd: command to be executed :return: (stdout, stderr) """ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) return p.stdout.readlines(), p.stderr.readlines()
python
def sys_call(cmd): """Execute cmd and capture stdout and stderr :param cmd: command to be executed :return: (stdout, stderr) """ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) return p.stdout.readlines(), p.stderr.readlines()
[ "def", "sys_call", "(", "cmd", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "close_fds", "=", "True", ")", "return", "p", ".", "stdout", ".", "readlines", "(", ")", ",", "p", ".", "stderr", ".", "readlines", "(", ")" ]
Execute cmd and capture stdout and stderr :param cmd: command to be executed :return: (stdout, stderr)
[ "Execute", "cmd", "and", "capture", "stdout", "and", "stderr" ]
d68c9a083d443dfa5d7c5112de29010909cfe23f
https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/__init__.py#L51-L58
241,878
AndresMWeber/Nomenclate
nomenclate/core/rendering.py
InputRenderer._get_alphanumeric_index
def _get_alphanumeric_index(query_string): """ Given an input string of either int or char, returns what index in the alphabet and case it is :param query_string: str, query string :return: (int, str), list of the index and type """ # TODO: could probably rework this. it works, but it's ugly as hell. try: return [int(query_string), 'int'] except ValueError: if len(query_string) == 1: if query_string.isupper(): return [string.ascii_uppercase.index(query_string), 'char_hi'] elif query_string.islower(): return [string.ascii_lowercase.index(query_string), 'char_lo'] else: raise IOError('The input is a string longer than one character')
python
def _get_alphanumeric_index(query_string): """ Given an input string of either int or char, returns what index in the alphabet and case it is :param query_string: str, query string :return: (int, str), list of the index and type """ # TODO: could probably rework this. it works, but it's ugly as hell. try: return [int(query_string), 'int'] except ValueError: if len(query_string) == 1: if query_string.isupper(): return [string.ascii_uppercase.index(query_string), 'char_hi'] elif query_string.islower(): return [string.ascii_lowercase.index(query_string), 'char_lo'] else: raise IOError('The input is a string longer than one character')
[ "def", "_get_alphanumeric_index", "(", "query_string", ")", ":", "# TODO: could probably rework this. it works, but it's ugly as hell.", "try", ":", "return", "[", "int", "(", "query_string", ")", ",", "'int'", "]", "except", "ValueError", ":", "if", "len", "(", "query_string", ")", "==", "1", ":", "if", "query_string", ".", "isupper", "(", ")", ":", "return", "[", "string", ".", "ascii_uppercase", ".", "index", "(", "query_string", ")", ",", "'char_hi'", "]", "elif", "query_string", ".", "islower", "(", ")", ":", "return", "[", "string", ".", "ascii_lowercase", ".", "index", "(", "query_string", ")", ",", "'char_lo'", "]", "else", ":", "raise", "IOError", "(", "'The input is a string longer than one character'", ")" ]
Given an input string of either int or char, returns what index in the alphabet and case it is :param query_string: str, query string :return: (int, str), list of the index and type
[ "Given", "an", "input", "string", "of", "either", "int", "or", "char", "returns", "what", "index", "in", "the", "alphabet", "and", "case", "it", "is" ]
e6d6fc28beac042bad588e56fbe77531d2de6b6f
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/rendering.py#L105-L121
241,879
honzamach/pynspect
pynspect/traversers.py
_to_numeric
def _to_numeric(val): """ Helper function for conversion of various data types into numeric representation. """ if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)): return val return float(val)
python
def _to_numeric(val): """ Helper function for conversion of various data types into numeric representation. """ if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)): return val return float(val)
[ "def", "_to_numeric", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "(", "int", ",", "float", ",", "datetime", ".", "datetime", ",", "datetime", ".", "timedelta", ")", ")", ":", "return", "val", "return", "float", "(", "val", ")" ]
Helper function for conversion of various data types into numeric representation.
[ "Helper", "function", "for", "conversion", "of", "various", "data", "types", "into", "numeric", "representation", "." ]
0582dcc1f7aafe50e25a21c792ea1b3367ea5881
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L517-L523
241,880
honzamach/pynspect
pynspect/traversers.py
BaseFilteringTreeTraverser.evaluate_binop_logical
def evaluate_binop_logical(self, operation, left, right, **kwargs): """ Evaluate given logical binary operation with given operands. """ if not operation in self.binops_logical: raise ValueError("Invalid logical binary operation '{}'".format(operation)) result = self.binops_logical[operation](left, right) return bool(result)
python
def evaluate_binop_logical(self, operation, left, right, **kwargs): """ Evaluate given logical binary operation with given operands. """ if not operation in self.binops_logical: raise ValueError("Invalid logical binary operation '{}'".format(operation)) result = self.binops_logical[operation](left, right) return bool(result)
[ "def", "evaluate_binop_logical", "(", "self", ",", "operation", ",", "left", ",", "right", ",", "*", "*", "kwargs", ")", ":", "if", "not", "operation", "in", "self", ".", "binops_logical", ":", "raise", "ValueError", "(", "\"Invalid logical binary operation '{}'\"", ".", "format", "(", "operation", ")", ")", "result", "=", "self", ".", "binops_logical", "[", "operation", "]", "(", "left", ",", "right", ")", "return", "bool", "(", "result", ")" ]
Evaluate given logical binary operation with given operands.
[ "Evaluate", "given", "logical", "binary", "operation", "with", "given", "operands", "." ]
0582dcc1f7aafe50e25a21c792ea1b3367ea5881
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L642-L649
241,881
honzamach/pynspect
pynspect/traversers.py
BaseFilteringTreeTraverser.evaluate_binop_comparison
def evaluate_binop_comparison(self, operation, left, right, **kwargs): """ Evaluate given comparison binary operation with given operands. """ if not operation in self.binops_comparison: raise ValueError("Invalid comparison binary operation '{}'".format(operation)) if left is None or right is None: return None if not isinstance(left, (list, ListIP)): left = [left] if not isinstance(right, (list, ListIP)): right = [right] if not left or not right: return None if operation in ['OP_IS']: res = self.binops_comparison[operation](left, right) if res: return True elif operation in ['OP_IN']: for iteml in left: res = self.binops_comparison[operation](iteml, right) if res: return True else: for iteml in left: if iteml is None: continue for itemr in right: if itemr is None: continue res = self.binops_comparison[operation](iteml, itemr) if res: return True return False
python
def evaluate_binop_comparison(self, operation, left, right, **kwargs): """ Evaluate given comparison binary operation with given operands. """ if not operation in self.binops_comparison: raise ValueError("Invalid comparison binary operation '{}'".format(operation)) if left is None or right is None: return None if not isinstance(left, (list, ListIP)): left = [left] if not isinstance(right, (list, ListIP)): right = [right] if not left or not right: return None if operation in ['OP_IS']: res = self.binops_comparison[operation](left, right) if res: return True elif operation in ['OP_IN']: for iteml in left: res = self.binops_comparison[operation](iteml, right) if res: return True else: for iteml in left: if iteml is None: continue for itemr in right: if itemr is None: continue res = self.binops_comparison[operation](iteml, itemr) if res: return True return False
[ "def", "evaluate_binop_comparison", "(", "self", ",", "operation", ",", "left", ",", "right", ",", "*", "*", "kwargs", ")", ":", "if", "not", "operation", "in", "self", ".", "binops_comparison", ":", "raise", "ValueError", "(", "\"Invalid comparison binary operation '{}'\"", ".", "format", "(", "operation", ")", ")", "if", "left", "is", "None", "or", "right", "is", "None", ":", "return", "None", "if", "not", "isinstance", "(", "left", ",", "(", "list", ",", "ListIP", ")", ")", ":", "left", "=", "[", "left", "]", "if", "not", "isinstance", "(", "right", ",", "(", "list", ",", "ListIP", ")", ")", ":", "right", "=", "[", "right", "]", "if", "not", "left", "or", "not", "right", ":", "return", "None", "if", "operation", "in", "[", "'OP_IS'", "]", ":", "res", "=", "self", ".", "binops_comparison", "[", "operation", "]", "(", "left", ",", "right", ")", "if", "res", ":", "return", "True", "elif", "operation", "in", "[", "'OP_IN'", "]", ":", "for", "iteml", "in", "left", ":", "res", "=", "self", ".", "binops_comparison", "[", "operation", "]", "(", "iteml", ",", "right", ")", "if", "res", ":", "return", "True", "else", ":", "for", "iteml", "in", "left", ":", "if", "iteml", "is", "None", ":", "continue", "for", "itemr", "in", "right", ":", "if", "itemr", "is", "None", ":", "continue", "res", "=", "self", ".", "binops_comparison", "[", "operation", "]", "(", "iteml", ",", "itemr", ")", "if", "res", ":", "return", "True", "return", "False" ]
Evaluate given comparison binary operation with given operands.
[ "Evaluate", "given", "comparison", "binary", "operation", "with", "given", "operands", "." ]
0582dcc1f7aafe50e25a21c792ea1b3367ea5881
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L651-L684
241,882
honzamach/pynspect
pynspect/traversers.py
BaseFilteringTreeTraverser._calculate_vector
def _calculate_vector(self, operation, left, right): """ Calculate vector result from two list operands with given mathematical operation. """ result = [] if len(right) == 1: right = _to_numeric(right[0]) for iteml in left: iteml = _to_numeric(iteml) result.append(self.binops_math[operation](iteml, right)) elif len(left) == 1: left = _to_numeric(left[0]) for itemr in right: itemr = _to_numeric(itemr) result.append(self.binops_math[operation](left, itemr)) elif len(left) == len(right): for iteml, itemr in zip(left, right): iteml = _to_numeric(iteml) itemr = _to_numeric(itemr) result.append(self.binops_math[operation](iteml, itemr)) else: raise FilteringRuleException("Uneven length of math operation '{}' operands".format(operation)) return result
python
def _calculate_vector(self, operation, left, right): """ Calculate vector result from two list operands with given mathematical operation. """ result = [] if len(right) == 1: right = _to_numeric(right[0]) for iteml in left: iteml = _to_numeric(iteml) result.append(self.binops_math[operation](iteml, right)) elif len(left) == 1: left = _to_numeric(left[0]) for itemr in right: itemr = _to_numeric(itemr) result.append(self.binops_math[operation](left, itemr)) elif len(left) == len(right): for iteml, itemr in zip(left, right): iteml = _to_numeric(iteml) itemr = _to_numeric(itemr) result.append(self.binops_math[operation](iteml, itemr)) else: raise FilteringRuleException("Uneven length of math operation '{}' operands".format(operation)) return result
[ "def", "_calculate_vector", "(", "self", ",", "operation", ",", "left", ",", "right", ")", ":", "result", "=", "[", "]", "if", "len", "(", "right", ")", "==", "1", ":", "right", "=", "_to_numeric", "(", "right", "[", "0", "]", ")", "for", "iteml", "in", "left", ":", "iteml", "=", "_to_numeric", "(", "iteml", ")", "result", ".", "append", "(", "self", ".", "binops_math", "[", "operation", "]", "(", "iteml", ",", "right", ")", ")", "elif", "len", "(", "left", ")", "==", "1", ":", "left", "=", "_to_numeric", "(", "left", "[", "0", "]", ")", "for", "itemr", "in", "right", ":", "itemr", "=", "_to_numeric", "(", "itemr", ")", "result", ".", "append", "(", "self", ".", "binops_math", "[", "operation", "]", "(", "left", ",", "itemr", ")", ")", "elif", "len", "(", "left", ")", "==", "len", "(", "right", ")", ":", "for", "iteml", ",", "itemr", "in", "zip", "(", "left", ",", "right", ")", ":", "iteml", "=", "_to_numeric", "(", "iteml", ")", "itemr", "=", "_to_numeric", "(", "itemr", ")", "result", ".", "append", "(", "self", ".", "binops_math", "[", "operation", "]", "(", "iteml", ",", "itemr", ")", ")", "else", ":", "raise", "FilteringRuleException", "(", "\"Uneven length of math operation '{}' operands\"", ".", "format", "(", "operation", ")", ")", "return", "result" ]
Calculate vector result from two list operands with given mathematical operation.
[ "Calculate", "vector", "result", "from", "two", "list", "operands", "with", "given", "mathematical", "operation", "." ]
0582dcc1f7aafe50e25a21c792ea1b3367ea5881
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L686-L708
241,883
honzamach/pynspect
pynspect/traversers.py
BaseFilteringTreeTraverser.evaluate_binop_math
def evaluate_binop_math(self, operation, left, right, **kwargs): """ Evaluate given mathematical binary operation with given operands. """ if not operation in self.binops_math: raise ValueError("Invalid math binary operation '{}'".format(operation)) if left is None or right is None: return None if not isinstance(left, (list, ListIP)): left = [left] if not isinstance(right, (list, ListIP)): right = [right] if not left or not right: return None try: vect = self._calculate_vector(operation, left, right) if len(vect) > 1: return vect return vect[0] except: return None
python
def evaluate_binop_math(self, operation, left, right, **kwargs): """ Evaluate given mathematical binary operation with given operands. """ if not operation in self.binops_math: raise ValueError("Invalid math binary operation '{}'".format(operation)) if left is None or right is None: return None if not isinstance(left, (list, ListIP)): left = [left] if not isinstance(right, (list, ListIP)): right = [right] if not left or not right: return None try: vect = self._calculate_vector(operation, left, right) if len(vect) > 1: return vect return vect[0] except: return None
[ "def", "evaluate_binop_math", "(", "self", ",", "operation", ",", "left", ",", "right", ",", "*", "*", "kwargs", ")", ":", "if", "not", "operation", "in", "self", ".", "binops_math", ":", "raise", "ValueError", "(", "\"Invalid math binary operation '{}'\"", ".", "format", "(", "operation", ")", ")", "if", "left", "is", "None", "or", "right", "is", "None", ":", "return", "None", "if", "not", "isinstance", "(", "left", ",", "(", "list", ",", "ListIP", ")", ")", ":", "left", "=", "[", "left", "]", "if", "not", "isinstance", "(", "right", ",", "(", "list", ",", "ListIP", ")", ")", ":", "right", "=", "[", "right", "]", "if", "not", "left", "or", "not", "right", ":", "return", "None", "try", ":", "vect", "=", "self", ".", "_calculate_vector", "(", "operation", ",", "left", ",", "right", ")", "if", "len", "(", "vect", ")", ">", "1", ":", "return", "vect", "return", "vect", "[", "0", "]", "except", ":", "return", "None" ]
Evaluate given mathematical binary operation with given operands.
[ "Evaluate", "given", "mathematical", "binary", "operation", "with", "given", "operands", "." ]
0582dcc1f7aafe50e25a21c792ea1b3367ea5881
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L710-L730
241,884
honzamach/pynspect
pynspect/traversers.py
BaseFilteringTreeTraverser.evaluate_unop
def evaluate_unop(self, operation, right, **kwargs): """ Evaluate given unary operation with given operand. """ if not operation in self.unops: raise ValueError("Invalid unary operation '{}'".format(operation)) if right is None: return None return self.unops[operation](right)
python
def evaluate_unop(self, operation, right, **kwargs): """ Evaluate given unary operation with given operand. """ if not operation in self.unops: raise ValueError("Invalid unary operation '{}'".format(operation)) if right is None: return None return self.unops[operation](right)
[ "def", "evaluate_unop", "(", "self", ",", "operation", ",", "right", ",", "*", "*", "kwargs", ")", ":", "if", "not", "operation", "in", "self", ".", "unops", ":", "raise", "ValueError", "(", "\"Invalid unary operation '{}'\"", ".", "format", "(", "operation", ")", ")", "if", "right", "is", "None", ":", "return", "None", "return", "self", ".", "unops", "[", "operation", "]", "(", "right", ")" ]
Evaluate given unary operation with given operand.
[ "Evaluate", "given", "unary", "operation", "with", "given", "operand", "." ]
0582dcc1f7aafe50e25a21c792ea1b3367ea5881
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L732-L740
241,885
honzamach/pynspect
pynspect/traversers.py
BaseFilteringTreeTraverser.decorate_function
def decorate_function(self, name, decorator): """ Decorate function with given name with given decorator. :param str name: Name of the function. :param callable decorator: Decorator callback. """ self.functions[name] = decorator(self.functions[name])
python
def decorate_function(self, name, decorator): """ Decorate function with given name with given decorator. :param str name: Name of the function. :param callable decorator: Decorator callback. """ self.functions[name] = decorator(self.functions[name])
[ "def", "decorate_function", "(", "self", ",", "name", ",", "decorator", ")", ":", "self", ".", "functions", "[", "name", "]", "=", "decorator", "(", "self", ".", "functions", "[", "name", "]", ")" ]
Decorate function with given name with given decorator. :param str name: Name of the function. :param callable decorator: Decorator callback.
[ "Decorate", "function", "with", "given", "name", "with", "given", "decorator", "." ]
0582dcc1f7aafe50e25a21c792ea1b3367ea5881
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L753-L760
241,886
a1fred/django-model-render
model_render/__init__.py
ModelRenderMixin.render
def render(self, template=None, additional=None): """ Render single model to its html representation. You may set template path in render function argument, or model's variable named 'template_path', or get default name: $app_label$/models/$model_name$.html Settings: * MODEL_RENDER_DEFAULT_EXTENSION set default template extension. Usable if you use jinja or others. :param template: custom template_path :return: rendered model html string """ template_path = template or self.get_template_path() template_vars = {'model': self} if additional: template_vars.update(additional) rendered = render_to_string(template_path, template_vars) return mark_safe(rendered)
python
def render(self, template=None, additional=None): """ Render single model to its html representation. You may set template path in render function argument, or model's variable named 'template_path', or get default name: $app_label$/models/$model_name$.html Settings: * MODEL_RENDER_DEFAULT_EXTENSION set default template extension. Usable if you use jinja or others. :param template: custom template_path :return: rendered model html string """ template_path = template or self.get_template_path() template_vars = {'model': self} if additional: template_vars.update(additional) rendered = render_to_string(template_path, template_vars) return mark_safe(rendered)
[ "def", "render", "(", "self", ",", "template", "=", "None", ",", "additional", "=", "None", ")", ":", "template_path", "=", "template", "or", "self", ".", "get_template_path", "(", ")", "template_vars", "=", "{", "'model'", ":", "self", "}", "if", "additional", ":", "template_vars", ".", "update", "(", "additional", ")", "rendered", "=", "render_to_string", "(", "template_path", ",", "template_vars", ")", "return", "mark_safe", "(", "rendered", ")" ]
Render single model to its html representation. You may set template path in render function argument, or model's variable named 'template_path', or get default name: $app_label$/models/$model_name$.html Settings: * MODEL_RENDER_DEFAULT_EXTENSION set default template extension. Usable if you use jinja or others. :param template: custom template_path :return: rendered model html string
[ "Render", "single", "model", "to", "its", "html", "representation", "." ]
0912b2ec9d33bada8875a57f7af9eb18d24e1e84
https://github.com/a1fred/django-model-render/blob/0912b2ec9d33bada8875a57f7af9eb18d24e1e84/model_render/__init__.py#L18-L40
241,887
mrstephenneal/dirutility
dirutility/system.py
SystemCommand.execute
def execute(self): """Execute a system command.""" if self._decode_output: # Capture and decode system output with Popen(self.command, shell=True, stdout=PIPE) as process: self._output = [i.decode("utf-8").strip() for i in process.stdout] self._success = True else: # Execute without capturing output os.system(self.command) self._success = True return self
python
def execute(self): """Execute a system command.""" if self._decode_output: # Capture and decode system output with Popen(self.command, shell=True, stdout=PIPE) as process: self._output = [i.decode("utf-8").strip() for i in process.stdout] self._success = True else: # Execute without capturing output os.system(self.command) self._success = True return self
[ "def", "execute", "(", "self", ")", ":", "if", "self", ".", "_decode_output", ":", "# Capture and decode system output", "with", "Popen", "(", "self", ".", "command", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ")", "as", "process", ":", "self", ".", "_output", "=", "[", "i", ".", "decode", "(", "\"utf-8\"", ")", ".", "strip", "(", ")", "for", "i", "in", "process", ".", "stdout", "]", "self", ".", "_success", "=", "True", "else", ":", "# Execute without capturing output", "os", ".", "system", "(", "self", ".", "command", ")", "self", ".", "_success", "=", "True", "return", "self" ]
Execute a system command.
[ "Execute", "a", "system", "command", "." ]
339378659e2d7e09c53acfc51c5df745bb0cd517
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/system.py#L51-L62
241,888
Vito2015/pyextend
pyextend/core/wrappers/accepts.py
accepts
def accepts(exception=TypeError, **types): """ A wrapper of function for checking function parameters type Example 1: @accepts(a=int, b='__iter__', c=str) def test(a, b=None, c=None): print('accepts OK') test(13, b=[], c='abc') -- OK test('aaa', b=(), c='abc') --Failed Example 2: @accepts(a=int, b=('__iter__', None), c=str) def test(a, b=None, c=None): print('accepts OK') test(13, b=[], c='abc') -- OK test(13, b=None, c='abc') -- OK """ def check_param(v, type_or_funcname): if isinstance(type_or_funcname, tuple): results1 = [check_param(v, t) for t in type_or_funcname if t is not None] results2 = [v == t for t in type_or_funcname if t is None] return any(results1) or any(results2) is_type_instance, is_func_like = False, False try: is_type_instance = isinstance(v, type_or_funcname) except TypeError: pass if isinstance(type_or_funcname, str): if type_or_funcname == '__iter__' and isinstance(v, str) and version_info < (3,): # at py 2.x, str object has non `__iter__` attribute, # str object can use like `for c in s`, bcz `iter(s)` returns an iterable object. is_func_like = True else: is_func_like = hasattr(v, type_or_funcname) return is_type_instance or is_func_like def check_accepts(f): assert len(types) <= f.__code__.co_argcount,\ 'accept number of arguments not equal with function number of arguments in "{}"'.format(f.__name__) @functools.wraps(f) def new_f(*args, **kwargs): for i, v in enumerate(args): if f.__code__.co_varnames[i] in types and \ not check_param(v, types[f.__code__.co_varnames[i]]): raise exception("function '%s' arg '%s'=%r does not match %s" % (f.__name__, f.__code__.co_varnames[i], v, types[f.__code__.co_varnames[i]])) del types[f.__code__.co_varnames[i]] for k, v in kwargs.items(): if k in types and \ not check_param(v, types[k]): raise exception("function '%s' arg '%s'=%r does not match %s" % (f.__name__, k, v, types[k])) return f(*args, **kwargs) return new_f return check_accepts
python
def accepts(exception=TypeError, **types): """ A wrapper of function for checking function parameters type Example 1: @accepts(a=int, b='__iter__', c=str) def test(a, b=None, c=None): print('accepts OK') test(13, b=[], c='abc') -- OK test('aaa', b=(), c='abc') --Failed Example 2: @accepts(a=int, b=('__iter__', None), c=str) def test(a, b=None, c=None): print('accepts OK') test(13, b=[], c='abc') -- OK test(13, b=None, c='abc') -- OK """ def check_param(v, type_or_funcname): if isinstance(type_or_funcname, tuple): results1 = [check_param(v, t) for t in type_or_funcname if t is not None] results2 = [v == t for t in type_or_funcname if t is None] return any(results1) or any(results2) is_type_instance, is_func_like = False, False try: is_type_instance = isinstance(v, type_or_funcname) except TypeError: pass if isinstance(type_or_funcname, str): if type_or_funcname == '__iter__' and isinstance(v, str) and version_info < (3,): # at py 2.x, str object has non `__iter__` attribute, # str object can use like `for c in s`, bcz `iter(s)` returns an iterable object. is_func_like = True else: is_func_like = hasattr(v, type_or_funcname) return is_type_instance or is_func_like def check_accepts(f): assert len(types) <= f.__code__.co_argcount,\ 'accept number of arguments not equal with function number of arguments in "{}"'.format(f.__name__) @functools.wraps(f) def new_f(*args, **kwargs): for i, v in enumerate(args): if f.__code__.co_varnames[i] in types and \ not check_param(v, types[f.__code__.co_varnames[i]]): raise exception("function '%s' arg '%s'=%r does not match %s" % (f.__name__, f.__code__.co_varnames[i], v, types[f.__code__.co_varnames[i]])) del types[f.__code__.co_varnames[i]] for k, v in kwargs.items(): if k in types and \ not check_param(v, types[k]): raise exception("function '%s' arg '%s'=%r does not match %s" % (f.__name__, k, v, types[k])) return f(*args, **kwargs) return new_f return check_accepts
[ "def", "accepts", "(", "exception", "=", "TypeError", ",", "*", "*", "types", ")", ":", "def", "check_param", "(", "v", ",", "type_or_funcname", ")", ":", "if", "isinstance", "(", "type_or_funcname", ",", "tuple", ")", ":", "results1", "=", "[", "check_param", "(", "v", ",", "t", ")", "for", "t", "in", "type_or_funcname", "if", "t", "is", "not", "None", "]", "results2", "=", "[", "v", "==", "t", "for", "t", "in", "type_or_funcname", "if", "t", "is", "None", "]", "return", "any", "(", "results1", ")", "or", "any", "(", "results2", ")", "is_type_instance", ",", "is_func_like", "=", "False", ",", "False", "try", ":", "is_type_instance", "=", "isinstance", "(", "v", ",", "type_or_funcname", ")", "except", "TypeError", ":", "pass", "if", "isinstance", "(", "type_or_funcname", ",", "str", ")", ":", "if", "type_or_funcname", "==", "'__iter__'", "and", "isinstance", "(", "v", ",", "str", ")", "and", "version_info", "<", "(", "3", ",", ")", ":", "# at py 2.x, str object has non `__iter__` attribute,", "# str object can use like `for c in s`, bcz `iter(s)` returns an iterable object.", "is_func_like", "=", "True", "else", ":", "is_func_like", "=", "hasattr", "(", "v", ",", "type_or_funcname", ")", "return", "is_type_instance", "or", "is_func_like", "def", "check_accepts", "(", "f", ")", ":", "assert", "len", "(", "types", ")", "<=", "f", ".", "__code__", ".", "co_argcount", ",", "'accept number of arguments not equal with function number of arguments in \"{}\"'", ".", "format", "(", "f", ".", "__name__", ")", "@", "functools", ".", "wraps", "(", "f", ")", "def", "new_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "i", ",", "v", "in", "enumerate", "(", "args", ")", ":", "if", "f", ".", "__code__", ".", "co_varnames", "[", "i", "]", "in", "types", "and", "not", "check_param", "(", "v", ",", "types", "[", "f", ".", "__code__", ".", "co_varnames", "[", "i", "]", "]", ")", ":", "raise", "exception", "(", "\"function '%s' arg '%s'=%r does not match %s\"", "%", "(", "f", ".", "__name__", ",", "f", ".", "__code__", ".", "co_varnames", "[", "i", "]", ",", "v", ",", "types", "[", "f", ".", "__code__", ".", "co_varnames", "[", "i", "]", "]", ")", ")", "del", "types", "[", "f", ".", "__code__", ".", "co_varnames", "[", "i", "]", "]", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "in", "types", "and", "not", "check_param", "(", "v", ",", "types", "[", "k", "]", ")", ":", "raise", "exception", "(", "\"function '%s' arg '%s'=%r does not match %s\"", "%", "(", "f", ".", "__name__", ",", "k", ",", "v", ",", "types", "[", "k", "]", ")", ")", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_f", "return", "check_accepts" ]
A wrapper of function for checking function parameters type Example 1: @accepts(a=int, b='__iter__', c=str) def test(a, b=None, c=None): print('accepts OK') test(13, b=[], c='abc') -- OK test('aaa', b=(), c='abc') --Failed Example 2: @accepts(a=int, b=('__iter__', None), c=str) def test(a, b=None, c=None): print('accepts OK') test(13, b=[], c='abc') -- OK test(13, b=None, c='abc') -- OK
[ "A", "wrapper", "of", "function", "for", "checking", "function", "parameters", "type" ]
36861dfe1087e437ffe9b5a1da9345c85b4fa4a1
https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/wrappers/accepts.py#L15-L77
241,889
radhermit/vimball
vimball/base.py
is_vimball
def is_vimball(fd): """Test for vimball archive format compliance. Simple check to see if the first line of the file starts with standard vimball archive header. """ fd.seek(0) try: header = fd.readline() except UnicodeDecodeError: # binary files will raise exceptions when trying to decode raw bytes to # str objects in our readline() wrapper return False if re.match('^" Vimball Archiver', header) is not None: return True return False
python
def is_vimball(fd): """Test for vimball archive format compliance. Simple check to see if the first line of the file starts with standard vimball archive header. """ fd.seek(0) try: header = fd.readline() except UnicodeDecodeError: # binary files will raise exceptions when trying to decode raw bytes to # str objects in our readline() wrapper return False if re.match('^" Vimball Archiver', header) is not None: return True return False
[ "def", "is_vimball", "(", "fd", ")", ":", "fd", ".", "seek", "(", "0", ")", "try", ":", "header", "=", "fd", ".", "readline", "(", ")", "except", "UnicodeDecodeError", ":", "# binary files will raise exceptions when trying to decode raw bytes to", "# str objects in our readline() wrapper", "return", "False", "if", "re", ".", "match", "(", "'^\" Vimball Archiver'", ",", "header", ")", "is", "not", "None", ":", "return", "True", "return", "False" ]
Test for vimball archive format compliance. Simple check to see if the first line of the file starts with standard vimball archive header.
[ "Test", "for", "vimball", "archive", "format", "compliance", "." ]
3998bdb8d8c4852a388a259778f971f562f9ef37
https://github.com/radhermit/vimball/blob/3998bdb8d8c4852a388a259778f971f562f9ef37/vimball/base.py#L24-L39
241,890
radhermit/vimball
vimball/base.py
Vimball.files
def files(self): """Yields archive file information.""" # try new file header format first, then fallback on old for header in (r"(.*)\t\[\[\[1\n", r"^(\d+)\n$"): header = re.compile(header) filename = None self.fd.seek(0) line = self.readline() while line: m = header.match(line) if m is not None: filename = m.group(1) try: filelines = int(self.readline().rstrip()) except ValueError: raise ArchiveError('invalid archive format') filestart = self.fd.tell() yield (filename, filelines, filestart) line = self.readline() if filename is not None: break
python
def files(self): """Yields archive file information.""" # try new file header format first, then fallback on old for header in (r"(.*)\t\[\[\[1\n", r"^(\d+)\n$"): header = re.compile(header) filename = None self.fd.seek(0) line = self.readline() while line: m = header.match(line) if m is not None: filename = m.group(1) try: filelines = int(self.readline().rstrip()) except ValueError: raise ArchiveError('invalid archive format') filestart = self.fd.tell() yield (filename, filelines, filestart) line = self.readline() if filename is not None: break
[ "def", "files", "(", "self", ")", ":", "# try new file header format first, then fallback on old", "for", "header", "in", "(", "r\"(.*)\\t\\[\\[\\[1\\n\"", ",", "r\"^(\\d+)\\n$\"", ")", ":", "header", "=", "re", ".", "compile", "(", "header", ")", "filename", "=", "None", "self", ".", "fd", ".", "seek", "(", "0", ")", "line", "=", "self", ".", "readline", "(", ")", "while", "line", ":", "m", "=", "header", ".", "match", "(", "line", ")", "if", "m", "is", "not", "None", ":", "filename", "=", "m", ".", "group", "(", "1", ")", "try", ":", "filelines", "=", "int", "(", "self", ".", "readline", "(", ")", ".", "rstrip", "(", ")", ")", "except", "ValueError", ":", "raise", "ArchiveError", "(", "'invalid archive format'", ")", "filestart", "=", "self", ".", "fd", ".", "tell", "(", ")", "yield", "(", "filename", ",", "filelines", ",", "filestart", ")", "line", "=", "self", ".", "readline", "(", ")", "if", "filename", "is", "not", "None", ":", "break" ]
Yields archive file information.
[ "Yields", "archive", "file", "information", "." ]
3998bdb8d8c4852a388a259778f971f562f9ef37
https://github.com/radhermit/vimball/blob/3998bdb8d8c4852a388a259778f971f562f9ef37/vimball/base.py#L82-L102
241,891
radhermit/vimball
vimball/base.py
Vimball.extract
def extract(self, extractdir=None, verbose=False): """Extract archive files to a directory.""" if extractdir is None: filebase, ext = os.path.splitext(self.path) if ext in ('.gz', '.bz2', '.xz'): filebase, _ext = os.path.splitext(filebase) extractdir = os.path.basename(filebase) if os.path.exists(extractdir): tempdir = tempfile.mkdtemp(prefix='vimball-', dir=os.getcwd()) extractdir = os.path.join(tempdir.split('/')[-1], extractdir) self.fd.seek(0) for filename, lines, offset in self.files: filepath = os.path.join(extractdir, filename) try: directory = os.path.dirname(filepath) mkdir_p(directory) except OSError as e: raise ArchiveError(f"failed creating directory {directory!r}: {e.strerror}") with open(filepath, 'w') as f: if verbose: print(filepath) self.fd.seek(offset) for i in range(lines): f.write(self.readline())
python
def extract(self, extractdir=None, verbose=False): """Extract archive files to a directory.""" if extractdir is None: filebase, ext = os.path.splitext(self.path) if ext in ('.gz', '.bz2', '.xz'): filebase, _ext = os.path.splitext(filebase) extractdir = os.path.basename(filebase) if os.path.exists(extractdir): tempdir = tempfile.mkdtemp(prefix='vimball-', dir=os.getcwd()) extractdir = os.path.join(tempdir.split('/')[-1], extractdir) self.fd.seek(0) for filename, lines, offset in self.files: filepath = os.path.join(extractdir, filename) try: directory = os.path.dirname(filepath) mkdir_p(directory) except OSError as e: raise ArchiveError(f"failed creating directory {directory!r}: {e.strerror}") with open(filepath, 'w') as f: if verbose: print(filepath) self.fd.seek(offset) for i in range(lines): f.write(self.readline())
[ "def", "extract", "(", "self", ",", "extractdir", "=", "None", ",", "verbose", "=", "False", ")", ":", "if", "extractdir", "is", "None", ":", "filebase", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "path", ")", "if", "ext", "in", "(", "'.gz'", ",", "'.bz2'", ",", "'.xz'", ")", ":", "filebase", ",", "_ext", "=", "os", ".", "path", ".", "splitext", "(", "filebase", ")", "extractdir", "=", "os", ".", "path", ".", "basename", "(", "filebase", ")", "if", "os", ".", "path", ".", "exists", "(", "extractdir", ")", ":", "tempdir", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "'vimball-'", ",", "dir", "=", "os", ".", "getcwd", "(", ")", ")", "extractdir", "=", "os", ".", "path", ".", "join", "(", "tempdir", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ",", "extractdir", ")", "self", ".", "fd", ".", "seek", "(", "0", ")", "for", "filename", ",", "lines", ",", "offset", "in", "self", ".", "files", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "extractdir", ",", "filename", ")", "try", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "filepath", ")", "mkdir_p", "(", "directory", ")", "except", "OSError", "as", "e", ":", "raise", "ArchiveError", "(", "f\"failed creating directory {directory!r}: {e.strerror}\"", ")", "with", "open", "(", "filepath", ",", "'w'", ")", "as", "f", ":", "if", "verbose", ":", "print", "(", "filepath", ")", "self", ".", "fd", ".", "seek", "(", "offset", ")", "for", "i", "in", "range", "(", "lines", ")", ":", "f", ".", "write", "(", "self", ".", "readline", "(", ")", ")" ]
Extract archive files to a directory.
[ "Extract", "archive", "files", "to", "a", "directory", "." ]
3998bdb8d8c4852a388a259778f971f562f9ef37
https://github.com/radhermit/vimball/blob/3998bdb8d8c4852a388a259778f971f562f9ef37/vimball/base.py#L104-L128
241,892
Fuyukai/ConfigMaster
configmaster/INIConfigFile.py
ini_dump_hook
def ini_dump_hook(cfg, text: bool=False): """ Dumps all the data into a INI file. This will automatically kill anything with a '_' in the keyname, replacing it with a dot. You have been warned. """ data = cfg.config.dump() # Load data back into the goddamned ini file. ndict = {} for key, item in data.items(): key = key.replace('_', '.') ndict[key] = item cfg.tmpini = configparser.ConfigParser() cfg.tmpini.read_dict(data) if not text: cfg.tmpini.write(cfg.fd) else: return cfg.reload()
python
def ini_dump_hook(cfg, text: bool=False): """ Dumps all the data into a INI file. This will automatically kill anything with a '_' in the keyname, replacing it with a dot. You have been warned. """ data = cfg.config.dump() # Load data back into the goddamned ini file. ndict = {} for key, item in data.items(): key = key.replace('_', '.') ndict[key] = item cfg.tmpini = configparser.ConfigParser() cfg.tmpini.read_dict(data) if not text: cfg.tmpini.write(cfg.fd) else: return cfg.reload()
[ "def", "ini_dump_hook", "(", "cfg", ",", "text", ":", "bool", "=", "False", ")", ":", "data", "=", "cfg", ".", "config", ".", "dump", "(", ")", "# Load data back into the goddamned ini file.", "ndict", "=", "{", "}", "for", "key", ",", "item", "in", "data", ".", "items", "(", ")", ":", "key", "=", "key", ".", "replace", "(", "'_'", ",", "'.'", ")", "ndict", "[", "key", "]", "=", "item", "cfg", ".", "tmpini", "=", "configparser", ".", "ConfigParser", "(", ")", "cfg", ".", "tmpini", ".", "read_dict", "(", "data", ")", "if", "not", "text", ":", "cfg", ".", "tmpini", ".", "write", "(", "cfg", ".", "fd", ")", "else", ":", "return", "cfg", ".", "reload", "(", ")" ]
Dumps all the data into a INI file. This will automatically kill anything with a '_' in the keyname, replacing it with a dot. You have been warned.
[ "Dumps", "all", "the", "data", "into", "a", "INI", "file", "." ]
8018aa415da55c84edaa8a49664f674758a14edd
https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/INIConfigFile.py#L40-L60
241,893
waltermoreira/tartpy
tartpy/runtime.py
exception_message
def exception_message(): """Create a message with details on the exception.""" exc_type, exc_value, exc_tb = exc_info = sys.exc_info() return {'exception': {'type': exc_type, 'value': exc_value, 'traceback': exc_tb}, 'traceback': traceback.format_exception(*exc_info)}
python
def exception_message(): """Create a message with details on the exception.""" exc_type, exc_value, exc_tb = exc_info = sys.exc_info() return {'exception': {'type': exc_type, 'value': exc_value, 'traceback': exc_tb}, 'traceback': traceback.format_exception(*exc_info)}
[ "def", "exception_message", "(", ")", ":", "exc_type", ",", "exc_value", ",", "exc_tb", "=", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "return", "{", "'exception'", ":", "{", "'type'", ":", "exc_type", ",", "'value'", ":", "exc_value", ",", "'traceback'", ":", "exc_tb", "}", ",", "'traceback'", ":", "traceback", ".", "format_exception", "(", "*", "exc_info", ")", "}" ]
Create a message with details on the exception.
[ "Create", "a", "message", "with", "details", "on", "the", "exception", "." ]
d9f66c8b373bd55a7b055c0fd39b516490bb0235
https://github.com/waltermoreira/tartpy/blob/d9f66c8b373bd55a7b055c0fd39b516490bb0235/tartpy/runtime.py#L97-L103
241,894
waltermoreira/tartpy
tartpy/runtime.py
behavior
def behavior(f): """Decorator for declaring a function as behavior. Use as:: @behavior def fun(x, y, self, msg): ... And create or become this behavior by passing the two arguments `x` and `y`. """ @wraps(f) def wrapper(*args): message = args[-1] if isinstance(message, MutableMapping): message = Message(message) f(*(args[:-1] + (message,))) return wrapper
python
def behavior(f): """Decorator for declaring a function as behavior. Use as:: @behavior def fun(x, y, self, msg): ... And create or become this behavior by passing the two arguments `x` and `y`. """ @wraps(f) def wrapper(*args): message = args[-1] if isinstance(message, MutableMapping): message = Message(message) f(*(args[:-1] + (message,))) return wrapper
[ "def", "behavior", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ")", ":", "message", "=", "args", "[", "-", "1", "]", "if", "isinstance", "(", "message", ",", "MutableMapping", ")", ":", "message", "=", "Message", "(", "message", ")", "f", "(", "*", "(", "args", "[", ":", "-", "1", "]", "+", "(", "message", ",", ")", ")", ")", "return", "wrapper" ]
Decorator for declaring a function as behavior. Use as:: @behavior def fun(x, y, self, msg): ... And create or become this behavior by passing the two arguments `x` and `y`.
[ "Decorator", "for", "declaring", "a", "function", "as", "behavior", "." ]
d9f66c8b373bd55a7b055c0fd39b516490bb0235
https://github.com/waltermoreira/tartpy/blob/d9f66c8b373bd55a7b055c0fd39b516490bb0235/tartpy/runtime.py#L148-L167
241,895
MacHu-GWU/angora-project
angora/math/interp.py
fromtimestamp
def fromtimestamp(timestamp): """Because python doesn't support negative timestamp to datetime so we have to implement my own method """ if timestamp >= 0: return datetime.fromtimestamp(timestamp) else: return datetime(1969, 12, 31, 20, 0) + timedelta(seconds=timestamp)
python
def fromtimestamp(timestamp): """Because python doesn't support negative timestamp to datetime so we have to implement my own method """ if timestamp >= 0: return datetime.fromtimestamp(timestamp) else: return datetime(1969, 12, 31, 20, 0) + timedelta(seconds=timestamp)
[ "def", "fromtimestamp", "(", "timestamp", ")", ":", "if", "timestamp", ">=", "0", ":", "return", "datetime", ".", "fromtimestamp", "(", "timestamp", ")", "else", ":", "return", "datetime", "(", "1969", ",", "12", ",", "31", ",", "20", ",", "0", ")", "+", "timedelta", "(", "seconds", "=", "timestamp", ")" ]
Because python doesn't support negative timestamp to datetime so we have to implement my own method
[ "Because", "python", "doesn", "t", "support", "negative", "timestamp", "to", "datetime", "so", "we", "have", "to", "implement", "my", "own", "method" ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/interp.py#L111-L118
241,896
MacHu-GWU/angora-project
angora/math/interp.py
rigid_linear_interpolate_by_datetime
def rigid_linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis): """A datetime-version that takes datetime object list as x_axis. """ numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp(a_datetime) for a_datetime in datetime_new_axis ] return rigid_linear_interpolate( numeric_datetime_axis, y_axis, numeric_datetime_new_axis)
python
def rigid_linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis): """A datetime-version that takes datetime object list as x_axis. """ numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp(a_datetime) for a_datetime in datetime_new_axis ] return rigid_linear_interpolate( numeric_datetime_axis, y_axis, numeric_datetime_new_axis)
[ "def", "rigid_linear_interpolate_by_datetime", "(", "datetime_axis", ",", "y_axis", ",", "datetime_new_axis", ")", ":", "numeric_datetime_axis", "=", "[", "totimestamp", "(", "a_datetime", ")", "for", "a_datetime", "in", "datetime_axis", "]", "numeric_datetime_new_axis", "=", "[", "totimestamp", "(", "a_datetime", ")", "for", "a_datetime", "in", "datetime_new_axis", "]", "return", "rigid_linear_interpolate", "(", "numeric_datetime_axis", ",", "y_axis", ",", "numeric_datetime_new_axis", ")" ]
A datetime-version that takes datetime object list as x_axis.
[ "A", "datetime", "-", "version", "that", "takes", "datetime", "object", "list", "as", "x_axis", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/interp.py#L146-L158
241,897
MacHu-GWU/angora-project
angora/math/interp.py
exam_reliability_by_datetime
def exam_reliability_by_datetime( datetime_axis, datetime_new_axis, reliable_distance): """A datetime-version that takes datetime object list as x_axis reliable_distance equals to the time difference in seconds. """ numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp(a_datetime) for a_datetime in datetime_new_axis ] return exam_reliability(numeric_datetime_axis, numeric_datetime_new_axis, reliable_distance, precision=0)
python
def exam_reliability_by_datetime( datetime_axis, datetime_new_axis, reliable_distance): """A datetime-version that takes datetime object list as x_axis reliable_distance equals to the time difference in seconds. """ numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp(a_datetime) for a_datetime in datetime_new_axis ] return exam_reliability(numeric_datetime_axis, numeric_datetime_new_axis, reliable_distance, precision=0)
[ "def", "exam_reliability_by_datetime", "(", "datetime_axis", ",", "datetime_new_axis", ",", "reliable_distance", ")", ":", "numeric_datetime_axis", "=", "[", "totimestamp", "(", "a_datetime", ")", "for", "a_datetime", "in", "datetime_axis", "]", "numeric_datetime_new_axis", "=", "[", "totimestamp", "(", "a_datetime", ")", "for", "a_datetime", "in", "datetime_new_axis", "]", "return", "exam_reliability", "(", "numeric_datetime_axis", ",", "numeric_datetime_new_axis", ",", "reliable_distance", ",", "precision", "=", "0", ")" ]
A datetime-version that takes datetime object list as x_axis reliable_distance equals to the time difference in seconds.
[ "A", "datetime", "-", "version", "that", "takes", "datetime", "object", "list", "as", "x_axis", "reliable_distance", "equals", "to", "the", "time", "difference", "in", "seconds", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/interp.py#L265-L279
241,898
krukas/Trionyx
trionyx/utils.py
import_object_by_string
def import_object_by_string(namespace): """Import object by complete namespace""" segments = namespace.split('.') module = importlib.import_module('.'.join(segments[:-1])) return getattr(module, segments[-1])
python
def import_object_by_string(namespace): """Import object by complete namespace""" segments = namespace.split('.') module = importlib.import_module('.'.join(segments[:-1])) return getattr(module, segments[-1])
[ "def", "import_object_by_string", "(", "namespace", ")", ":", "segments", "=", "namespace", ".", "split", "(", "'.'", ")", "module", "=", "importlib", ".", "import_module", "(", "'.'", ".", "join", "(", "segments", "[", ":", "-", "1", "]", ")", ")", "return", "getattr", "(", "module", ",", "segments", "[", "-", "1", "]", ")" ]
Import object by complete namespace
[ "Import", "object", "by", "complete", "namespace" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/utils.py#L24-L28
241,899
krukas/Trionyx
trionyx/utils.py
create_celerybeat_schedule
def create_celerybeat_schedule(apps): """Create Celery beat schedule by get schedule from every installed app""" beat_schedule = {} for app in apps: try: config = import_object_by_string(app) module = importlib.import_module('{}.cron'.format(config.name)) except Exception: try: module = importlib.import_module('{}.cron'.format(app)) except Exception: continue if not (hasattr(module, 'schedule') and isinstance(module.schedule, dict)): logger.warning('{} has no schedule or schedule is not a dict'.format(module.__name__)) continue # Add cron queue option for name, schedule in module.schedule.items(): options = schedule.get('options', {}) if 'queue' not in options: options['queue'] = 'cron' schedule['options'] = options beat_schedule[name] = schedule return beat_schedule
python
def create_celerybeat_schedule(apps): """Create Celery beat schedule by get schedule from every installed app""" beat_schedule = {} for app in apps: try: config = import_object_by_string(app) module = importlib.import_module('{}.cron'.format(config.name)) except Exception: try: module = importlib.import_module('{}.cron'.format(app)) except Exception: continue if not (hasattr(module, 'schedule') and isinstance(module.schedule, dict)): logger.warning('{} has no schedule or schedule is not a dict'.format(module.__name__)) continue # Add cron queue option for name, schedule in module.schedule.items(): options = schedule.get('options', {}) if 'queue' not in options: options['queue'] = 'cron' schedule['options'] = options beat_schedule[name] = schedule return beat_schedule
[ "def", "create_celerybeat_schedule", "(", "apps", ")", ":", "beat_schedule", "=", "{", "}", "for", "app", "in", "apps", ":", "try", ":", "config", "=", "import_object_by_string", "(", "app", ")", "module", "=", "importlib", ".", "import_module", "(", "'{}.cron'", ".", "format", "(", "config", ".", "name", ")", ")", "except", "Exception", ":", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "'{}.cron'", ".", "format", "(", "app", ")", ")", "except", "Exception", ":", "continue", "if", "not", "(", "hasattr", "(", "module", ",", "'schedule'", ")", "and", "isinstance", "(", "module", ".", "schedule", ",", "dict", ")", ")", ":", "logger", ".", "warning", "(", "'{} has no schedule or schedule is not a dict'", ".", "format", "(", "module", ".", "__name__", ")", ")", "continue", "# Add cron queue option", "for", "name", ",", "schedule", "in", "module", ".", "schedule", ".", "items", "(", ")", ":", "options", "=", "schedule", ".", "get", "(", "'options'", ",", "{", "}", ")", "if", "'queue'", "not", "in", "options", ":", "options", "[", "'queue'", "]", "=", "'cron'", "schedule", "[", "'options'", "]", "=", "options", "beat_schedule", "[", "name", "]", "=", "schedule", "return", "beat_schedule" ]
Create Celery beat schedule by get schedule from every installed app
[ "Create", "Celery", "beat", "schedule", "by", "get", "schedule", "from", "every", "installed", "app" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/utils.py#L31-L57