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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
250,600
jaraco/jaraco.context
jaraco/context.py
dependency_context
def dependency_context(package_names, aggressively_remove=False): """ Install the supplied packages and yield. Finally, remove all packages that were installed. Currently assumes 'aptitude' is available. """ installed_packages = [] log = logging.getLogger(__name__) try: if not package_names: logging.debug('No packages requested') if package_names: lock = yg.lockfile.FileLock( '/tmp/.pkg-context-lock', timeout=30 * 60) log.info('Acquiring lock to perform install') lock.acquire() log.info('Installing ' + ', '.join(package_names)) output = subprocess.check_output( ['sudo', 'aptitude', 'install', '-y'] + package_names, stderr=subprocess.STDOUT, ) log.debug('Aptitude output:\n%s', output) installed_packages = jaraco.apt.parse_new_packages( output, include_automatic=aggressively_remove) if not installed_packages: lock.release() log.info('Installed ' + ', '.join(installed_packages)) yield installed_packages except subprocess.CalledProcessError: log.error("Error occurred installing packages") raise finally: if installed_packages: log.info('Removing ' + ','.join(installed_packages)) subprocess.check_call( ['sudo', 'aptitude', 'remove', '-y'] + installed_packages, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) lock.release()
python
def dependency_context(package_names, aggressively_remove=False): """ Install the supplied packages and yield. Finally, remove all packages that were installed. Currently assumes 'aptitude' is available. """ installed_packages = [] log = logging.getLogger(__name__) try: if not package_names: logging.debug('No packages requested') if package_names: lock = yg.lockfile.FileLock( '/tmp/.pkg-context-lock', timeout=30 * 60) log.info('Acquiring lock to perform install') lock.acquire() log.info('Installing ' + ', '.join(package_names)) output = subprocess.check_output( ['sudo', 'aptitude', 'install', '-y'] + package_names, stderr=subprocess.STDOUT, ) log.debug('Aptitude output:\n%s', output) installed_packages = jaraco.apt.parse_new_packages( output, include_automatic=aggressively_remove) if not installed_packages: lock.release() log.info('Installed ' + ', '.join(installed_packages)) yield installed_packages except subprocess.CalledProcessError: log.error("Error occurred installing packages") raise finally: if installed_packages: log.info('Removing ' + ','.join(installed_packages)) subprocess.check_call( ['sudo', 'aptitude', 'remove', '-y'] + installed_packages, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) lock.release()
[ "def", "dependency_context", "(", "package_names", ",", "aggressively_remove", "=", "False", ")", ":", "installed_packages", "=", "[", "]", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "try", ":", "if", "not", "package_names", ":", "logging", ".", "debug", "(", "'No packages requested'", ")", "if", "package_names", ":", "lock", "=", "yg", ".", "lockfile", ".", "FileLock", "(", "'/tmp/.pkg-context-lock'", ",", "timeout", "=", "30", "*", "60", ")", "log", ".", "info", "(", "'Acquiring lock to perform install'", ")", "lock", ".", "acquire", "(", ")", "log", ".", "info", "(", "'Installing '", "+", "', '", ".", "join", "(", "package_names", ")", ")", "output", "=", "subprocess", ".", "check_output", "(", "[", "'sudo'", ",", "'aptitude'", ",", "'install'", ",", "'-y'", "]", "+", "package_names", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", ")", "log", ".", "debug", "(", "'Aptitude output:\\n%s'", ",", "output", ")", "installed_packages", "=", "jaraco", ".", "apt", ".", "parse_new_packages", "(", "output", ",", "include_automatic", "=", "aggressively_remove", ")", "if", "not", "installed_packages", ":", "lock", ".", "release", "(", ")", "log", ".", "info", "(", "'Installed '", "+", "', '", ".", "join", "(", "installed_packages", ")", ")", "yield", "installed_packages", "except", "subprocess", ".", "CalledProcessError", ":", "log", ".", "error", "(", "\"Error occurred installing packages\"", ")", "raise", "finally", ":", "if", "installed_packages", ":", "log", ".", "info", "(", "'Removing '", "+", "','", ".", "join", "(", "installed_packages", ")", ")", "subprocess", ".", "check_call", "(", "[", "'sudo'", ",", "'aptitude'", ",", "'remove'", ",", "'-y'", "]", "+", "installed_packages", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", ")", "lock", ".", "release", "(", ")" ]
Install the supplied packages and yield. Finally, remove all packages that were installed. Currently assumes 'aptitude' is available.
[ "Install", "the", "supplied", "packages", "and", "yield", ".", "Finally", "remove", "all", "packages", "that", "were", "installed", ".", "Currently", "assumes", "aptitude", "is", "available", "." ]
105f81a6204d3a9fbb848675d62be4ef185f36f2
https://github.com/jaraco/jaraco.context/blob/105f81a6204d3a9fbb848675d62be4ef185f36f2/jaraco/context.py#L109-L149
250,601
jaraco/jaraco.context
jaraco/context.py
tarball_context
def tarball_context(url, target_dir=None, runner=None, pushd=pushd): """ Get a tarball, extract it, change to that directory, yield, then clean up. `runner` is the function to invoke commands. `pushd` is a context manager for changing the directory. """ if target_dir is None: target_dir = os.path.basename(url).replace('.tar.gz', '').replace( '.tgz', '') if runner is None: runner = functools.partial(subprocess.check_call, shell=True) # In the tar command, use --strip-components=1 to strip the first path and # then # use -C to cause the files to be extracted to {target_dir}. This ensures # that we always know where the files were extracted. runner('mkdir {target_dir}'.format(**vars())) try: getter = 'wget {url} -O -' extract = 'tar x{compression} --strip-components=1 -C {target_dir}' cmd = ' | '.join((getter, extract)) runner(cmd.format(compression=infer_compression(url), **vars())) with pushd(target_dir): yield target_dir finally: runner('rm -Rf {target_dir}'.format(**vars()))
python
def tarball_context(url, target_dir=None, runner=None, pushd=pushd): """ Get a tarball, extract it, change to that directory, yield, then clean up. `runner` is the function to invoke commands. `pushd` is a context manager for changing the directory. """ if target_dir is None: target_dir = os.path.basename(url).replace('.tar.gz', '').replace( '.tgz', '') if runner is None: runner = functools.partial(subprocess.check_call, shell=True) # In the tar command, use --strip-components=1 to strip the first path and # then # use -C to cause the files to be extracted to {target_dir}. This ensures # that we always know where the files were extracted. runner('mkdir {target_dir}'.format(**vars())) try: getter = 'wget {url} -O -' extract = 'tar x{compression} --strip-components=1 -C {target_dir}' cmd = ' | '.join((getter, extract)) runner(cmd.format(compression=infer_compression(url), **vars())) with pushd(target_dir): yield target_dir finally: runner('rm -Rf {target_dir}'.format(**vars()))
[ "def", "tarball_context", "(", "url", ",", "target_dir", "=", "None", ",", "runner", "=", "None", ",", "pushd", "=", "pushd", ")", ":", "if", "target_dir", "is", "None", ":", "target_dir", "=", "os", ".", "path", ".", "basename", "(", "url", ")", ".", "replace", "(", "'.tar.gz'", ",", "''", ")", ".", "replace", "(", "'.tgz'", ",", "''", ")", "if", "runner", "is", "None", ":", "runner", "=", "functools", ".", "partial", "(", "subprocess", ".", "check_call", ",", "shell", "=", "True", ")", "# In the tar command, use --strip-components=1 to strip the first path and", "# then", "# use -C to cause the files to be extracted to {target_dir}. This ensures", "# that we always know where the files were extracted.", "runner", "(", "'mkdir {target_dir}'", ".", "format", "(", "*", "*", "vars", "(", ")", ")", ")", "try", ":", "getter", "=", "'wget {url} -O -'", "extract", "=", "'tar x{compression} --strip-components=1 -C {target_dir}'", "cmd", "=", "' | '", ".", "join", "(", "(", "getter", ",", "extract", ")", ")", "runner", "(", "cmd", ".", "format", "(", "compression", "=", "infer_compression", "(", "url", ")", ",", "*", "*", "vars", "(", ")", ")", ")", "with", "pushd", "(", "target_dir", ")", ":", "yield", "target_dir", "finally", ":", "runner", "(", "'rm -Rf {target_dir}'", ".", "format", "(", "*", "*", "vars", "(", ")", ")", ")" ]
Get a tarball, extract it, change to that directory, yield, then clean up. `runner` is the function to invoke commands. `pushd` is a context manager for changing the directory.
[ "Get", "a", "tarball", "extract", "it", "change", "to", "that", "directory", "yield", "then", "clean", "up", ".", "runner", "is", "the", "function", "to", "invoke", "commands", ".", "pushd", "is", "a", "context", "manager", "for", "changing", "the", "directory", "." ]
105f81a6204d3a9fbb848675d62be4ef185f36f2
https://github.com/jaraco/jaraco.context/blob/105f81a6204d3a9fbb848675d62be4ef185f36f2/jaraco/context.py#L163-L188
250,602
jaraco/jaraco.context
jaraco/context.py
infer_compression
def infer_compression(url): """ Given a URL or filename, infer the compression code for tar. """ # cheat and just assume it's the last two characters compression_indicator = url[-2:] mapping = dict( gz='z', bz='j', xz='J', ) # Assume 'z' (gzip) if no match return mapping.get(compression_indicator, 'z')
python
def infer_compression(url): """ Given a URL or filename, infer the compression code for tar. """ # cheat and just assume it's the last two characters compression_indicator = url[-2:] mapping = dict( gz='z', bz='j', xz='J', ) # Assume 'z' (gzip) if no match return mapping.get(compression_indicator, 'z')
[ "def", "infer_compression", "(", "url", ")", ":", "# cheat and just assume it's the last two characters", "compression_indicator", "=", "url", "[", "-", "2", ":", "]", "mapping", "=", "dict", "(", "gz", "=", "'z'", ",", "bz", "=", "'j'", ",", "xz", "=", "'J'", ",", ")", "# Assume 'z' (gzip) if no match", "return", "mapping", ".", "get", "(", "compression_indicator", ",", "'z'", ")" ]
Given a URL or filename, infer the compression code for tar.
[ "Given", "a", "URL", "or", "filename", "infer", "the", "compression", "code", "for", "tar", "." ]
105f81a6204d3a9fbb848675d62be4ef185f36f2
https://github.com/jaraco/jaraco.context/blob/105f81a6204d3a9fbb848675d62be4ef185f36f2/jaraco/context.py#L191-L203
250,603
jaraco/jaraco.context
jaraco/context.py
temp_dir
def temp_dir(remover=shutil.rmtree): """ Create a temporary directory context. Pass a custom remover to override the removal behavior. """ temp_dir = tempfile.mkdtemp() try: yield temp_dir finally: remover(temp_dir)
python
def temp_dir(remover=shutil.rmtree): """ Create a temporary directory context. Pass a custom remover to override the removal behavior. """ temp_dir = tempfile.mkdtemp() try: yield temp_dir finally: remover(temp_dir)
[ "def", "temp_dir", "(", "remover", "=", "shutil", ".", "rmtree", ")", ":", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "yield", "temp_dir", "finally", ":", "remover", "(", "temp_dir", ")" ]
Create a temporary directory context. Pass a custom remover to override the removal behavior.
[ "Create", "a", "temporary", "directory", "context", ".", "Pass", "a", "custom", "remover", "to", "override", "the", "removal", "behavior", "." ]
105f81a6204d3a9fbb848675d62be4ef185f36f2
https://github.com/jaraco/jaraco.context/blob/105f81a6204d3a9fbb848675d62be4ef185f36f2/jaraco/context.py#L207-L216
250,604
jaraco/jaraco.context
jaraco/context.py
repo_context
def repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir): """ Check out the repo indicated by url. If dest_ctx is supplied, it should be a context manager to yield the target directory for the check out. """ exe = 'git' if 'git' in url else 'hg' with dest_ctx() as repo_dir: cmd = [exe, 'clone', url, repo_dir] if branch: cmd.extend(['--branch', branch]) devnull = open(os.path.devnull, 'w') stdout = devnull if quiet else None subprocess.check_call(cmd, stdout=stdout) yield repo_dir
python
def repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir): """ Check out the repo indicated by url. If dest_ctx is supplied, it should be a context manager to yield the target directory for the check out. """ exe = 'git' if 'git' in url else 'hg' with dest_ctx() as repo_dir: cmd = [exe, 'clone', url, repo_dir] if branch: cmd.extend(['--branch', branch]) devnull = open(os.path.devnull, 'w') stdout = devnull if quiet else None subprocess.check_call(cmd, stdout=stdout) yield repo_dir
[ "def", "repo_context", "(", "url", ",", "branch", "=", "None", ",", "quiet", "=", "True", ",", "dest_ctx", "=", "temp_dir", ")", ":", "exe", "=", "'git'", "if", "'git'", "in", "url", "else", "'hg'", "with", "dest_ctx", "(", ")", "as", "repo_dir", ":", "cmd", "=", "[", "exe", ",", "'clone'", ",", "url", ",", "repo_dir", "]", "if", "branch", ":", "cmd", ".", "extend", "(", "[", "'--branch'", ",", "branch", "]", ")", "devnull", "=", "open", "(", "os", ".", "path", ".", "devnull", ",", "'w'", ")", "stdout", "=", "devnull", "if", "quiet", "else", "None", "subprocess", ".", "check_call", "(", "cmd", ",", "stdout", "=", "stdout", ")", "yield", "repo_dir" ]
Check out the repo indicated by url. If dest_ctx is supplied, it should be a context manager to yield the target directory for the check out.
[ "Check", "out", "the", "repo", "indicated", "by", "url", "." ]
105f81a6204d3a9fbb848675d62be4ef185f36f2
https://github.com/jaraco/jaraco.context/blob/105f81a6204d3a9fbb848675d62be4ef185f36f2/jaraco/context.py#L220-L235
250,605
minhhoit/yacms
yacms/utils/device.py
device_from_request
def device_from_request(request): """ Determine's the device name from the request by first looking for an overridding cookie, and if not found then matching the user agent. Used at both the template level for choosing the template to load and also at the cache level as a cache key prefix. """ from yacms.conf import settings try: # If a device was set via cookie, match available devices. for (device, _) in settings.DEVICE_USER_AGENTS: if device == request.COOKIES["yacms-device"]: return device except KeyError: # If a device wasn't set via cookie, match user agent. try: user_agent = request.META["HTTP_USER_AGENT"].lower() except KeyError: pass else: try: user_agent = user_agent.decode("utf-8") for (device, ua_strings) in settings.DEVICE_USER_AGENTS: for ua_string in ua_strings: if ua_string.lower() in user_agent: return device except (AttributeError, UnicodeDecodeError, UnicodeEncodeError): pass return ""
python
def device_from_request(request): """ Determine's the device name from the request by first looking for an overridding cookie, and if not found then matching the user agent. Used at both the template level for choosing the template to load and also at the cache level as a cache key prefix. """ from yacms.conf import settings try: # If a device was set via cookie, match available devices. for (device, _) in settings.DEVICE_USER_AGENTS: if device == request.COOKIES["yacms-device"]: return device except KeyError: # If a device wasn't set via cookie, match user agent. try: user_agent = request.META["HTTP_USER_AGENT"].lower() except KeyError: pass else: try: user_agent = user_agent.decode("utf-8") for (device, ua_strings) in settings.DEVICE_USER_AGENTS: for ua_string in ua_strings: if ua_string.lower() in user_agent: return device except (AttributeError, UnicodeDecodeError, UnicodeEncodeError): pass return ""
[ "def", "device_from_request", "(", "request", ")", ":", "from", "yacms", ".", "conf", "import", "settings", "try", ":", "# If a device was set via cookie, match available devices.", "for", "(", "device", ",", "_", ")", "in", "settings", ".", "DEVICE_USER_AGENTS", ":", "if", "device", "==", "request", ".", "COOKIES", "[", "\"yacms-device\"", "]", ":", "return", "device", "except", "KeyError", ":", "# If a device wasn't set via cookie, match user agent.", "try", ":", "user_agent", "=", "request", ".", "META", "[", "\"HTTP_USER_AGENT\"", "]", ".", "lower", "(", ")", "except", "KeyError", ":", "pass", "else", ":", "try", ":", "user_agent", "=", "user_agent", ".", "decode", "(", "\"utf-8\"", ")", "for", "(", "device", ",", "ua_strings", ")", "in", "settings", ".", "DEVICE_USER_AGENTS", ":", "for", "ua_string", "in", "ua_strings", ":", "if", "ua_string", ".", "lower", "(", ")", "in", "user_agent", ":", "return", "device", "except", "(", "AttributeError", ",", "UnicodeDecodeError", ",", "UnicodeEncodeError", ")", ":", "pass", "return", "\"\"" ]
Determine's the device name from the request by first looking for an overridding cookie, and if not found then matching the user agent. Used at both the template level for choosing the template to load and also at the cache level as a cache key prefix.
[ "Determine", "s", "the", "device", "name", "from", "the", "request", "by", "first", "looking", "for", "an", "overridding", "cookie", "and", "if", "not", "found", "then", "matching", "the", "user", "agent", ".", "Used", "at", "both", "the", "template", "level", "for", "choosing", "the", "template", "to", "load", "and", "also", "at", "the", "cache", "level", "as", "a", "cache", "key", "prefix", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/device.py#L4-L32
250,606
tomokinakamaru/mapletree
mapletree/defaults/request/request.py
Request.body
def body(self): """ String from `wsgi.input`. """ if self._body is None: if self._fieldstorage is not None: raise ReadBodyTwiceError() clength = int(self.environ('CONTENT_LENGTH') or 0) self._body = self._environ['wsgi.input'].read(clength) if isinstance(self._body, bytes): self._body = self._body.decode('utf8') return self._body
python
def body(self): """ String from `wsgi.input`. """ if self._body is None: if self._fieldstorage is not None: raise ReadBodyTwiceError() clength = int(self.environ('CONTENT_LENGTH') or 0) self._body = self._environ['wsgi.input'].read(clength) if isinstance(self._body, bytes): self._body = self._body.decode('utf8') return self._body
[ "def", "body", "(", "self", ")", ":", "if", "self", ".", "_body", "is", "None", ":", "if", "self", ".", "_fieldstorage", "is", "not", "None", ":", "raise", "ReadBodyTwiceError", "(", ")", "clength", "=", "int", "(", "self", ".", "environ", "(", "'CONTENT_LENGTH'", ")", "or", "0", ")", "self", ".", "_body", "=", "self", ".", "_environ", "[", "'wsgi.input'", "]", ".", "read", "(", "clength", ")", "if", "isinstance", "(", "self", ".", "_body", ",", "bytes", ")", ":", "self", ".", "_body", "=", "self", ".", "_body", ".", "decode", "(", "'utf8'", ")", "return", "self", ".", "_body" ]
String from `wsgi.input`.
[ "String", "from", "wsgi", ".", "input", "." ]
19ec68769ef2c1cd2e4164ed8623e0c4280279bb
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/defaults/request/request.py#L43-L55
250,607
tomokinakamaru/mapletree
mapletree/defaults/request/request.py
Request.fieldstorage
def fieldstorage(self): """ `cgi.FieldStorage` from `wsgi.input`. """ if self._fieldstorage is None: if self._body is not None: raise ReadBodyTwiceError() self._fieldstorage = cgi.FieldStorage( environ=self._environ, fp=self._environ['wsgi.input'] ) return self._fieldstorage
python
def fieldstorage(self): """ `cgi.FieldStorage` from `wsgi.input`. """ if self._fieldstorage is None: if self._body is not None: raise ReadBodyTwiceError() self._fieldstorage = cgi.FieldStorage( environ=self._environ, fp=self._environ['wsgi.input'] ) return self._fieldstorage
[ "def", "fieldstorage", "(", "self", ")", ":", "if", "self", ".", "_fieldstorage", "is", "None", ":", "if", "self", ".", "_body", "is", "not", "None", ":", "raise", "ReadBodyTwiceError", "(", ")", "self", ".", "_fieldstorage", "=", "cgi", ".", "FieldStorage", "(", "environ", "=", "self", ".", "_environ", ",", "fp", "=", "self", ".", "_environ", "[", "'wsgi.input'", "]", ")", "return", "self", ".", "_fieldstorage" ]
`cgi.FieldStorage` from `wsgi.input`.
[ "cgi", ".", "FieldStorage", "from", "wsgi", ".", "input", "." ]
19ec68769ef2c1cd2e4164ed8623e0c4280279bb
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/defaults/request/request.py#L58-L70
250,608
tomokinakamaru/mapletree
mapletree/defaults/request/request.py
Request.params
def params(self): """ Parsed query string. """ if self._params is None: self._params = self.arg_container() data = compat.parse_qs(self.environ('QUERY_STRING') or '') for k, v in data.items(): self._params[k] = v[0] return self._params
python
def params(self): """ Parsed query string. """ if self._params is None: self._params = self.arg_container() data = compat.parse_qs(self.environ('QUERY_STRING') or '') for k, v in data.items(): self._params[k] = v[0] return self._params
[ "def", "params", "(", "self", ")", ":", "if", "self", ".", "_params", "is", "None", ":", "self", ".", "_params", "=", "self", ".", "arg_container", "(", ")", "data", "=", "compat", ".", "parse_qs", "(", "self", ".", "environ", "(", "'QUERY_STRING'", ")", "or", "''", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "self", ".", "_params", "[", "k", "]", "=", "v", "[", "0", "]", "return", "self", ".", "_params" ]
Parsed query string.
[ "Parsed", "query", "string", "." ]
19ec68769ef2c1cd2e4164ed8623e0c4280279bb
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/defaults/request/request.py#L73-L83
250,609
tomokinakamaru/mapletree
mapletree/defaults/request/request.py
Request.cookie
def cookie(self): """ Cookie values. """ if self._cookie is None: self._cookie = self.arg_container() data = compat.parse_qs(self.http_header('cookie') or '') for k, v in data.items(): self._cookie[k.strip()] = v[0] return self._cookie
python
def cookie(self): """ Cookie values. """ if self._cookie is None: self._cookie = self.arg_container() data = compat.parse_qs(self.http_header('cookie') or '') for k, v in data.items(): self._cookie[k.strip()] = v[0] return self._cookie
[ "def", "cookie", "(", "self", ")", ":", "if", "self", ".", "_cookie", "is", "None", ":", "self", ".", "_cookie", "=", "self", ".", "arg_container", "(", ")", "data", "=", "compat", ".", "parse_qs", "(", "self", ".", "http_header", "(", "'cookie'", ")", "or", "''", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "self", ".", "_cookie", "[", "k", ".", "strip", "(", ")", "]", "=", "v", "[", "0", "]", "return", "self", ".", "_cookie" ]
Cookie values.
[ "Cookie", "values", "." ]
19ec68769ef2c1cd2e4164ed8623e0c4280279bb
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/defaults/request/request.py#L92-L102
250,610
tomokinakamaru/mapletree
mapletree/defaults/request/request.py
Request.data
def data(self): """ Values in request body. """ if self._data is None: self._data = self.arg_container() if isinstance(self.fieldstorage.value, list): for k in self.fieldstorage.keys(): fname = self.fieldstorage[k].filename if fname: self._data[k] = (fname, self.fieldstorage[k].file) else: self._data[k] = self.fieldstorage.getfirst(k) return self._data
python
def data(self): """ Values in request body. """ if self._data is None: self._data = self.arg_container() if isinstance(self.fieldstorage.value, list): for k in self.fieldstorage.keys(): fname = self.fieldstorage[k].filename if fname: self._data[k] = (fname, self.fieldstorage[k].file) else: self._data[k] = self.fieldstorage.getfirst(k) return self._data
[ "def", "data", "(", "self", ")", ":", "if", "self", ".", "_data", "is", "None", ":", "self", ".", "_data", "=", "self", ".", "arg_container", "(", ")", "if", "isinstance", "(", "self", ".", "fieldstorage", ".", "value", ",", "list", ")", ":", "for", "k", "in", "self", ".", "fieldstorage", ".", "keys", "(", ")", ":", "fname", "=", "self", ".", "fieldstorage", "[", "k", "]", ".", "filename", "if", "fname", ":", "self", ".", "_data", "[", "k", "]", "=", "(", "fname", ",", "self", ".", "fieldstorage", "[", "k", "]", ".", "file", ")", "else", ":", "self", ".", "_data", "[", "k", "]", "=", "self", ".", "fieldstorage", ".", "getfirst", "(", "k", ")", "return", "self", ".", "_data" ]
Values in request body.
[ "Values", "in", "request", "body", "." ]
19ec68769ef2c1cd2e4164ed8623e0c4280279bb
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/defaults/request/request.py#L105-L120
250,611
smetj/wishbone-input-namedpipe
wishbone_input_namedpipe/namedpipein.py
NamedPipeIn.drain
def drain(self, p): '''Reads the named pipe.''' self.logging.info('Started.') fd = os.open(p, os.O_RDWR | os.O_NONBLOCK) gevent_os.make_nonblocking(fd) while self.loop(): try: lines = gevent_os.nb_read(fd, 4096).splitlines() if len(lines) == 0: sleep(0.5) else: self.consume(lines) except OSError: pass
python
def drain(self, p): '''Reads the named pipe.''' self.logging.info('Started.') fd = os.open(p, os.O_RDWR | os.O_NONBLOCK) gevent_os.make_nonblocking(fd) while self.loop(): try: lines = gevent_os.nb_read(fd, 4096).splitlines() if len(lines) == 0: sleep(0.5) else: self.consume(lines) except OSError: pass
[ "def", "drain", "(", "self", ",", "p", ")", ":", "self", ".", "logging", ".", "info", "(", "'Started.'", ")", "fd", "=", "os", ".", "open", "(", "p", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_NONBLOCK", ")", "gevent_os", ".", "make_nonblocking", "(", "fd", ")", "while", "self", ".", "loop", "(", ")", ":", "try", ":", "lines", "=", "gevent_os", ".", "nb_read", "(", "fd", ",", "4096", ")", ".", "splitlines", "(", ")", "if", "len", "(", "lines", ")", "==", "0", ":", "sleep", "(", "0.5", ")", "else", ":", "self", ".", "consume", "(", "lines", ")", "except", "OSError", ":", "pass" ]
Reads the named pipe.
[ "Reads", "the", "named", "pipe", "." ]
01c3d03aeaa482b4893b38f78a66606e213ef144
https://github.com/smetj/wishbone-input-namedpipe/blob/01c3d03aeaa482b4893b38f78a66606e213ef144/wishbone_input_namedpipe/namedpipein.py#L67-L82
250,612
dhain/potpy
potpy/router.py
Route.add
def add(self, handler, name=None, exception_handlers=()): """Add a handler to the route. :param handler: The "handler" callable to add. :param name: Optional. When specified, the return value of this handler will be added to the context under ``name``. :param exception_handlers: Optional. A list of ``(types, handler)`` tuples, where ``types`` is an exception type (or tuple of types) to handle, and ``handler`` is a callable. See below for example. **Exception Handlers** When an exception occurs in a handler, ``exc_info`` will be temporarily added to the context and the list of exception handlers will be checked for an appropriate handler. If no handler can be found, the exception will be re-raised to the caller of the route. If an appropriate exception handler is found, it will be called (the context will be injected, so handlers may take an ``exc_info`` argument), and its return value will be used in place of the original handler's return value. Examples: >>> from potpy.context import Context >>> route = Route() >>> route.add(lambda: {}['foo'], exception_handlers=[ ... (KeyError, lambda: 'bar') ... ]) >>> route(Context()) 'bar' >>> def read_line_from_file(): ... raise IOError() # simulate a failed read ... >>> def retry_read(): ... return 'success!' # simulate retrying the read ... >>> def process_line(line): ... return line.upper() ... >>> route = Route() >>> route.add(read_line_from_file, 'line', [ ... # return value will be added to context as 'line' ... ((OSError, IOError), retry_read) ... ]) >>> route.add(process_line) >>> route(Context()) 'SUCCESS!' >>> route = Route() >>> route.add(lambda: {}['foo'], exception_handlers=[ ... (IndexError, lambda: 'bar') # does not handle KeyError ... ]) >>> route(Context()) # so exception will be re-raised here Traceback (most recent call last): ... KeyError: 'foo' """ self.route.append((name, handler, exception_handlers))
python
def add(self, handler, name=None, exception_handlers=()): """Add a handler to the route. :param handler: The "handler" callable to add. :param name: Optional. When specified, the return value of this handler will be added to the context under ``name``. :param exception_handlers: Optional. A list of ``(types, handler)`` tuples, where ``types`` is an exception type (or tuple of types) to handle, and ``handler`` is a callable. See below for example. **Exception Handlers** When an exception occurs in a handler, ``exc_info`` will be temporarily added to the context and the list of exception handlers will be checked for an appropriate handler. If no handler can be found, the exception will be re-raised to the caller of the route. If an appropriate exception handler is found, it will be called (the context will be injected, so handlers may take an ``exc_info`` argument), and its return value will be used in place of the original handler's return value. Examples: >>> from potpy.context import Context >>> route = Route() >>> route.add(lambda: {}['foo'], exception_handlers=[ ... (KeyError, lambda: 'bar') ... ]) >>> route(Context()) 'bar' >>> def read_line_from_file(): ... raise IOError() # simulate a failed read ... >>> def retry_read(): ... return 'success!' # simulate retrying the read ... >>> def process_line(line): ... return line.upper() ... >>> route = Route() >>> route.add(read_line_from_file, 'line', [ ... # return value will be added to context as 'line' ... ((OSError, IOError), retry_read) ... ]) >>> route.add(process_line) >>> route(Context()) 'SUCCESS!' >>> route = Route() >>> route.add(lambda: {}['foo'], exception_handlers=[ ... (IndexError, lambda: 'bar') # does not handle KeyError ... ]) >>> route(Context()) # so exception will be re-raised here Traceback (most recent call last): ... KeyError: 'foo' """ self.route.append((name, handler, exception_handlers))
[ "def", "add", "(", "self", ",", "handler", ",", "name", "=", "None", ",", "exception_handlers", "=", "(", ")", ")", ":", "self", ".", "route", ".", "append", "(", "(", "name", ",", "handler", ",", "exception_handlers", ")", ")" ]
Add a handler to the route. :param handler: The "handler" callable to add. :param name: Optional. When specified, the return value of this handler will be added to the context under ``name``. :param exception_handlers: Optional. A list of ``(types, handler)`` tuples, where ``types`` is an exception type (or tuple of types) to handle, and ``handler`` is a callable. See below for example. **Exception Handlers** When an exception occurs in a handler, ``exc_info`` will be temporarily added to the context and the list of exception handlers will be checked for an appropriate handler. If no handler can be found, the exception will be re-raised to the caller of the route. If an appropriate exception handler is found, it will be called (the context will be injected, so handlers may take an ``exc_info`` argument), and its return value will be used in place of the original handler's return value. Examples: >>> from potpy.context import Context >>> route = Route() >>> route.add(lambda: {}['foo'], exception_handlers=[ ... (KeyError, lambda: 'bar') ... ]) >>> route(Context()) 'bar' >>> def read_line_from_file(): ... raise IOError() # simulate a failed read ... >>> def retry_read(): ... return 'success!' # simulate retrying the read ... >>> def process_line(line): ... return line.upper() ... >>> route = Route() >>> route.add(read_line_from_file, 'line', [ ... # return value will be added to context as 'line' ... ((OSError, IOError), retry_read) ... ]) >>> route.add(process_line) >>> route(Context()) 'SUCCESS!' >>> route = Route() >>> route.add(lambda: {}['foo'], exception_handlers=[ ... (IndexError, lambda: 'bar') # does not handle KeyError ... ]) >>> route(Context()) # so exception will be re-raised here Traceback (most recent call last): ... KeyError: 'foo'
[ "Add", "a", "handler", "to", "the", "route", "." ]
e39a5a84f763fbf144b07a620afb02a5ff3741c9
https://github.com/dhain/potpy/blob/e39a5a84f763fbf144b07a620afb02a5ff3741c9/potpy/router.py#L124-L184
250,613
dhain/potpy
potpy/router.py
Router.add
def add(self, match, handler): """Register a handler with the Router. :param match: The first argument passed to the :meth:`match` method when checking against this handler. :param handler: A callable or :class:`Route` instance that will handle matching calls. If not a Route instance, will be wrapped in one. """ self.routes.append((match, ( Route(handler) if not isinstance(handler, Route) else handler )))
python
def add(self, match, handler): """Register a handler with the Router. :param match: The first argument passed to the :meth:`match` method when checking against this handler. :param handler: A callable or :class:`Route` instance that will handle matching calls. If not a Route instance, will be wrapped in one. """ self.routes.append((match, ( Route(handler) if not isinstance(handler, Route) else handler )))
[ "def", "add", "(", "self", ",", "match", ",", "handler", ")", ":", "self", ".", "routes", ".", "append", "(", "(", "match", ",", "(", "Route", "(", "handler", ")", "if", "not", "isinstance", "(", "handler", ",", "Route", ")", "else", "handler", ")", ")", ")" ]
Register a handler with the Router. :param match: The first argument passed to the :meth:`match` method when checking against this handler. :param handler: A callable or :class:`Route` instance that will handle matching calls. If not a Route instance, will be wrapped in one.
[ "Register", "a", "handler", "with", "the", "Router", "." ]
e39a5a84f763fbf144b07a620afb02a5ff3741c9
https://github.com/dhain/potpy/blob/e39a5a84f763fbf144b07a620afb02a5ff3741c9/potpy/router.py#L250-L261
250,614
nicktgr15/sac
sac/util.py
Util.get_annotated_data_x_y
def get_annotated_data_x_y(timestamps, data, lbls): """ DOESN'T work with OVERLAPPING labels :param timestamps: :param data: :param lbls: :return: """ timestamps = np.array(timestamps) timestamp_step = timestamps[3]-timestamps[2] current_new_timestamp = 0.0 new_timestamps = [] X = None Y = [] classes = [] for i in range(0, len(timestamps)): for lbl in lbls: if lbl.start_seconds <= timestamps[i] < lbl.end_seconds: if X is None: X = data[i, :] else: X = np.vstack((X, data[i, :])) Y.append(lbl.label) new_timestamps.append(current_new_timestamp) current_new_timestamp += timestamp_step if lbl.label not in classes: classes.append(lbl.label) return X, Y, classes, new_timestamps
python
def get_annotated_data_x_y(timestamps, data, lbls): """ DOESN'T work with OVERLAPPING labels :param timestamps: :param data: :param lbls: :return: """ timestamps = np.array(timestamps) timestamp_step = timestamps[3]-timestamps[2] current_new_timestamp = 0.0 new_timestamps = [] X = None Y = [] classes = [] for i in range(0, len(timestamps)): for lbl in lbls: if lbl.start_seconds <= timestamps[i] < lbl.end_seconds: if X is None: X = data[i, :] else: X = np.vstack((X, data[i, :])) Y.append(lbl.label) new_timestamps.append(current_new_timestamp) current_new_timestamp += timestamp_step if lbl.label not in classes: classes.append(lbl.label) return X, Y, classes, new_timestamps
[ "def", "get_annotated_data_x_y", "(", "timestamps", ",", "data", ",", "lbls", ")", ":", "timestamps", "=", "np", ".", "array", "(", "timestamps", ")", "timestamp_step", "=", "timestamps", "[", "3", "]", "-", "timestamps", "[", "2", "]", "current_new_timestamp", "=", "0.0", "new_timestamps", "=", "[", "]", "X", "=", "None", "Y", "=", "[", "]", "classes", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "timestamps", ")", ")", ":", "for", "lbl", "in", "lbls", ":", "if", "lbl", ".", "start_seconds", "<=", "timestamps", "[", "i", "]", "<", "lbl", ".", "end_seconds", ":", "if", "X", "is", "None", ":", "X", "=", "data", "[", "i", ",", ":", "]", "else", ":", "X", "=", "np", ".", "vstack", "(", "(", "X", ",", "data", "[", "i", ",", ":", "]", ")", ")", "Y", ".", "append", "(", "lbl", ".", "label", ")", "new_timestamps", ".", "append", "(", "current_new_timestamp", ")", "current_new_timestamp", "+=", "timestamp_step", "if", "lbl", ".", "label", "not", "in", "classes", ":", "classes", ".", "append", "(", "lbl", ".", "label", ")", "return", "X", ",", "Y", ",", "classes", ",", "new_timestamps" ]
DOESN'T work with OVERLAPPING labels :param timestamps: :param data: :param lbls: :return:
[ "DOESN", "T", "work", "with", "OVERLAPPING", "labels" ]
4b1d5d8e6ca2c437972db34ddc72990860865159
https://github.com/nicktgr15/sac/blob/4b1d5d8e6ca2c437972db34ddc72990860865159/sac/util.py#L172-L207
250,615
bluec0re/python-helperlib
helperlib/logging.py
scope_logger
def scope_logger(cls): """ Class decorator for adding a class local logger Example: >>> @scope_logger >>> class Test: >>> def __init__(self): >>> self.log.info("class instantiated") >>> t = Test() """ cls.log = logging.getLogger('{0}.{1}'.format(cls.__module__, cls.__name__)) return cls
python
def scope_logger(cls): """ Class decorator for adding a class local logger Example: >>> @scope_logger >>> class Test: >>> def __init__(self): >>> self.log.info("class instantiated") >>> t = Test() """ cls.log = logging.getLogger('{0}.{1}'.format(cls.__module__, cls.__name__)) return cls
[ "def", "scope_logger", "(", "cls", ")", ":", "cls", ".", "log", "=", "logging", ".", "getLogger", "(", "'{0}.{1}'", ".", "format", "(", "cls", ".", "__module__", ",", "cls", ".", "__name__", ")", ")", "return", "cls" ]
Class decorator for adding a class local logger Example: >>> @scope_logger >>> class Test: >>> def __init__(self): >>> self.log.info("class instantiated") >>> t = Test()
[ "Class", "decorator", "for", "adding", "a", "class", "local", "logger" ]
a2ac429668a6b86d3dc5e686978965c938f07d2c
https://github.com/bluec0re/python-helperlib/blob/a2ac429668a6b86d3dc5e686978965c938f07d2c/helperlib/logging.py#L127-L140
250,616
bluec0re/python-helperlib
helperlib/logging.py
LogPipe.run
def run(self): """Run the thread, logging everything. """ self._finished.clear() for line in iter(self.pipeReader.readline, ''): logging.log(self.level, line.strip('\n')) self.pipeReader.close() self._finished.set()
python
def run(self): """Run the thread, logging everything. """ self._finished.clear() for line in iter(self.pipeReader.readline, ''): logging.log(self.level, line.strip('\n')) self.pipeReader.close() self._finished.set()
[ "def", "run", "(", "self", ")", ":", "self", ".", "_finished", ".", "clear", "(", ")", "for", "line", "in", "iter", "(", "self", ".", "pipeReader", ".", "readline", ",", "''", ")", ":", "logging", ".", "log", "(", "self", ".", "level", ",", "line", ".", "strip", "(", "'\\n'", ")", ")", "self", ".", "pipeReader", ".", "close", "(", ")", "self", ".", "_finished", ".", "set", "(", ")" ]
Run the thread, logging everything.
[ "Run", "the", "thread", "logging", "everything", "." ]
a2ac429668a6b86d3dc5e686978965c938f07d2c
https://github.com/bluec0re/python-helperlib/blob/a2ac429668a6b86d3dc5e686978965c938f07d2c/helperlib/logging.py#L162-L170
250,617
sveetch/py-css-styleguide
py_css_styleguide/model.py
Manifest.load
def load(self, source, filepath=None): """ Load source as manifest attributes Arguments: source (string or file-object): CSS source to parse and serialize to find metas and rules. It can be either a string or a file-like object (aka with a ``read()`` method which return string). Keyword Arguments: filepath (string): Optional filepath to memorize if source comes from a file. Default is ``None`` as if source comes from a string. If ``source`` argument is a file-like object, you should not need to bother of this argument since filepath will be filled from source ``name`` attribute. Returns: dict: Dictionnary of serialized rules. """ # Set _path if source is a file-like object try: self._path = source.name except AttributeError: self._path = filepath # Get source content either it's a string or a file-like object try: source_content = source.read() except AttributeError: source_content = source # Parse and serialize given source parser = TinycssSourceParser() self._datas = parser.parse(source_content) serializer = ManifestSerializer() references = serializer.serialize(self._datas) # Copy serialized metas self.metas = serializer._metas # Set every enabled rule as object attribute for k, v in references.items(): self.set_rule(k, v) return self._datas
python
def load(self, source, filepath=None): """ Load source as manifest attributes Arguments: source (string or file-object): CSS source to parse and serialize to find metas and rules. It can be either a string or a file-like object (aka with a ``read()`` method which return string). Keyword Arguments: filepath (string): Optional filepath to memorize if source comes from a file. Default is ``None`` as if source comes from a string. If ``source`` argument is a file-like object, you should not need to bother of this argument since filepath will be filled from source ``name`` attribute. Returns: dict: Dictionnary of serialized rules. """ # Set _path if source is a file-like object try: self._path = source.name except AttributeError: self._path = filepath # Get source content either it's a string or a file-like object try: source_content = source.read() except AttributeError: source_content = source # Parse and serialize given source parser = TinycssSourceParser() self._datas = parser.parse(source_content) serializer = ManifestSerializer() references = serializer.serialize(self._datas) # Copy serialized metas self.metas = serializer._metas # Set every enabled rule as object attribute for k, v in references.items(): self.set_rule(k, v) return self._datas
[ "def", "load", "(", "self", ",", "source", ",", "filepath", "=", "None", ")", ":", "# Set _path if source is a file-like object", "try", ":", "self", ".", "_path", "=", "source", ".", "name", "except", "AttributeError", ":", "self", ".", "_path", "=", "filepath", "# Get source content either it's a string or a file-like object", "try", ":", "source_content", "=", "source", ".", "read", "(", ")", "except", "AttributeError", ":", "source_content", "=", "source", "# Parse and serialize given source", "parser", "=", "TinycssSourceParser", "(", ")", "self", ".", "_datas", "=", "parser", ".", "parse", "(", "source_content", ")", "serializer", "=", "ManifestSerializer", "(", ")", "references", "=", "serializer", ".", "serialize", "(", "self", ".", "_datas", ")", "# Copy serialized metas", "self", ".", "metas", "=", "serializer", ".", "_metas", "# Set every enabled rule as object attribute", "for", "k", ",", "v", "in", "references", ".", "items", "(", ")", ":", "self", ".", "set_rule", "(", "k", ",", "v", ")", "return", "self", ".", "_datas" ]
Load source as manifest attributes Arguments: source (string or file-object): CSS source to parse and serialize to find metas and rules. It can be either a string or a file-like object (aka with a ``read()`` method which return string). Keyword Arguments: filepath (string): Optional filepath to memorize if source comes from a file. Default is ``None`` as if source comes from a string. If ``source`` argument is a file-like object, you should not need to bother of this argument since filepath will be filled from source ``name`` attribute. Returns: dict: Dictionnary of serialized rules.
[ "Load", "source", "as", "manifest", "attributes" ]
5acc693f71b2fa7d944d7fed561ae0a7699ccd0f
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/model.py#L41-L87
250,618
sveetch/py-css-styleguide
py_css_styleguide/model.py
Manifest.set_rule
def set_rule(self, name, properties): """ Set a rules as object attribute. Arguments: name (string): Rule name to set as attribute name. properties (dict): Dictionnary of properties. """ self._rule_attrs.append(name) setattr(self, name, properties)
python
def set_rule(self, name, properties): """ Set a rules as object attribute. Arguments: name (string): Rule name to set as attribute name. properties (dict): Dictionnary of properties. """ self._rule_attrs.append(name) setattr(self, name, properties)
[ "def", "set_rule", "(", "self", ",", "name", ",", "properties", ")", ":", "self", ".", "_rule_attrs", ".", "append", "(", "name", ")", "setattr", "(", "self", ",", "name", ",", "properties", ")" ]
Set a rules as object attribute. Arguments: name (string): Rule name to set as attribute name. properties (dict): Dictionnary of properties.
[ "Set", "a", "rules", "as", "object", "attribute", "." ]
5acc693f71b2fa7d944d7fed561ae0a7699ccd0f
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/model.py#L89-L98
250,619
sveetch/py-css-styleguide
py_css_styleguide/model.py
Manifest.remove_rule
def remove_rule(self, name): """ Remove a rule from attributes. Arguments: name (string): Rule name to remove. """ self._rule_attrs.remove(name) delattr(self, name)
python
def remove_rule(self, name): """ Remove a rule from attributes. Arguments: name (string): Rule name to remove. """ self._rule_attrs.remove(name) delattr(self, name)
[ "def", "remove_rule", "(", "self", ",", "name", ")", ":", "self", ".", "_rule_attrs", ".", "remove", "(", "name", ")", "delattr", "(", "self", ",", "name", ")" ]
Remove a rule from attributes. Arguments: name (string): Rule name to remove.
[ "Remove", "a", "rule", "from", "attributes", "." ]
5acc693f71b2fa7d944d7fed561ae0a7699ccd0f
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/model.py#L100-L108
250,620
sveetch/py-css-styleguide
py_css_styleguide/model.py
Manifest.to_json
def to_json(self, indent=4): """ Serialize metas and reference attributes to a JSON string. Keyword Arguments: indent (int): Space indentation, default to ``4``. Returns: string: JSON datas. """ agregate = { 'metas': self.metas, } agregate.update({k: getattr(self, k) for k in self._rule_attrs}) return json.dumps(agregate, indent=indent)
python
def to_json(self, indent=4): """ Serialize metas and reference attributes to a JSON string. Keyword Arguments: indent (int): Space indentation, default to ``4``. Returns: string: JSON datas. """ agregate = { 'metas': self.metas, } agregate.update({k: getattr(self, k) for k in self._rule_attrs}) return json.dumps(agregate, indent=indent)
[ "def", "to_json", "(", "self", ",", "indent", "=", "4", ")", ":", "agregate", "=", "{", "'metas'", ":", "self", ".", "metas", ",", "}", "agregate", ".", "update", "(", "{", "k", ":", "getattr", "(", "self", ",", "k", ")", "for", "k", "in", "self", ".", "_rule_attrs", "}", ")", "return", "json", ".", "dumps", "(", "agregate", ",", "indent", "=", "indent", ")" ]
Serialize metas and reference attributes to a JSON string. Keyword Arguments: indent (int): Space indentation, default to ``4``. Returns: string: JSON datas.
[ "Serialize", "metas", "and", "reference", "attributes", "to", "a", "JSON", "string", "." ]
5acc693f71b2fa7d944d7fed561ae0a7699ccd0f
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/model.py#L110-L126
250,621
elkan1788/ppytools
ppytools/emailclient.py
EmailClient.send
def send(self, to, cc, subject, body, atts=None, delete=False): """Send an email action. :param to: receivers list :param cc: copy user list :param subject: email title :param body: email content body :param atts: email attachments :param delete: whether delete att :return: True or False """ email_cnt = MIMEMultipart() email_cnt['From'] = Header(self.smtp_user, CHARSET_ENCODING) email_cnt['To'] = Header(';'.join(to), CHARSET_ENCODING) email_cnt['Cc'] = Header(';'.join(cc), CHARSET_ENCODING) email_cnt['Subject'] = Header(subject, CHARSET_ENCODING) email_cnt['Date'] = formatdate() email_cnt.attach(MIMEText(body, 'html', CHARSET_ENCODING)) self.__add_att__(email_cnt, atts, delete) try: self.__login__() self.smtp_conn.sendmail(self.smtp_user, to+cc, email_cnt.as_string()) with_att_msg = 'Empty' if atts: for i, att in enumerate(atts): atts[i] = att[att.startswith('/')+1:] with_att_msg = ','.join(atts) '''Flush memory ''' atts[:] = [] logger.info('Send email[%s] success.', subject) logger.info('To users: %s.', ','.join(to+cc)) logger.info('With attachments: %s.', with_att_msg) except Exception as e: raise SendEmailException("Send email[%s] failed!!! Case: %s" % (subject, str(e)))
python
def send(self, to, cc, subject, body, atts=None, delete=False): """Send an email action. :param to: receivers list :param cc: copy user list :param subject: email title :param body: email content body :param atts: email attachments :param delete: whether delete att :return: True or False """ email_cnt = MIMEMultipart() email_cnt['From'] = Header(self.smtp_user, CHARSET_ENCODING) email_cnt['To'] = Header(';'.join(to), CHARSET_ENCODING) email_cnt['Cc'] = Header(';'.join(cc), CHARSET_ENCODING) email_cnt['Subject'] = Header(subject, CHARSET_ENCODING) email_cnt['Date'] = formatdate() email_cnt.attach(MIMEText(body, 'html', CHARSET_ENCODING)) self.__add_att__(email_cnt, atts, delete) try: self.__login__() self.smtp_conn.sendmail(self.smtp_user, to+cc, email_cnt.as_string()) with_att_msg = 'Empty' if atts: for i, att in enumerate(atts): atts[i] = att[att.startswith('/')+1:] with_att_msg = ','.join(atts) '''Flush memory ''' atts[:] = [] logger.info('Send email[%s] success.', subject) logger.info('To users: %s.', ','.join(to+cc)) logger.info('With attachments: %s.', with_att_msg) except Exception as e: raise SendEmailException("Send email[%s] failed!!! Case: %s" % (subject, str(e)))
[ "def", "send", "(", "self", ",", "to", ",", "cc", ",", "subject", ",", "body", ",", "atts", "=", "None", ",", "delete", "=", "False", ")", ":", "email_cnt", "=", "MIMEMultipart", "(", ")", "email_cnt", "[", "'From'", "]", "=", "Header", "(", "self", ".", "smtp_user", ",", "CHARSET_ENCODING", ")", "email_cnt", "[", "'To'", "]", "=", "Header", "(", "';'", ".", "join", "(", "to", ")", ",", "CHARSET_ENCODING", ")", "email_cnt", "[", "'Cc'", "]", "=", "Header", "(", "';'", ".", "join", "(", "cc", ")", ",", "CHARSET_ENCODING", ")", "email_cnt", "[", "'Subject'", "]", "=", "Header", "(", "subject", ",", "CHARSET_ENCODING", ")", "email_cnt", "[", "'Date'", "]", "=", "formatdate", "(", ")", "email_cnt", ".", "attach", "(", "MIMEText", "(", "body", ",", "'html'", ",", "CHARSET_ENCODING", ")", ")", "self", ".", "__add_att__", "(", "email_cnt", ",", "atts", ",", "delete", ")", "try", ":", "self", ".", "__login__", "(", ")", "self", ".", "smtp_conn", ".", "sendmail", "(", "self", ".", "smtp_user", ",", "to", "+", "cc", ",", "email_cnt", ".", "as_string", "(", ")", ")", "with_att_msg", "=", "'Empty'", "if", "atts", ":", "for", "i", ",", "att", "in", "enumerate", "(", "atts", ")", ":", "atts", "[", "i", "]", "=", "att", "[", "att", ".", "startswith", "(", "'/'", ")", "+", "1", ":", "]", "with_att_msg", "=", "','", ".", "join", "(", "atts", ")", "'''Flush memory\n '''", "atts", "[", ":", "]", "=", "[", "]", "logger", ".", "info", "(", "'Send email[%s] success.'", ",", "subject", ")", "logger", ".", "info", "(", "'To users: %s.'", ",", "','", ".", "join", "(", "to", "+", "cc", ")", ")", "logger", ".", "info", "(", "'With attachments: %s.'", ",", "with_att_msg", ")", "except", "Exception", "as", "e", ":", "raise", "SendEmailException", "(", "\"Send email[%s] failed!!! Case: %s\"", "%", "(", "subject", ",", "str", "(", "e", ")", ")", ")" ]
Send an email action. :param to: receivers list :param cc: copy user list :param subject: email title :param body: email content body :param atts: email attachments :param delete: whether delete att :return: True or False
[ "Send", "an", "email", "action", "." ]
117aeed9f669ae46e0dd6cb11c5687a5f797816c
https://github.com/elkan1788/ppytools/blob/117aeed9f669ae46e0dd6cb11c5687a5f797816c/ppytools/emailclient.py#L118-L157
250,622
klmitch/bark
bark/proxy.py
Proxy.restrict
def restrict(self, addr): """ Drop an address from the set of addresses this proxy is permitted to introduce. :param addr: The address to remove. """ # Remove the address from the set ip_addr = _parse_ip(addr) if ip_addr is None: LOG.warn("Cannot restrict address %r from proxy %s: " "invalid address" % (addr, self.address)) else: self.excluded.add(addr)
python
def restrict(self, addr): """ Drop an address from the set of addresses this proxy is permitted to introduce. :param addr: The address to remove. """ # Remove the address from the set ip_addr = _parse_ip(addr) if ip_addr is None: LOG.warn("Cannot restrict address %r from proxy %s: " "invalid address" % (addr, self.address)) else: self.excluded.add(addr)
[ "def", "restrict", "(", "self", ",", "addr", ")", ":", "# Remove the address from the set", "ip_addr", "=", "_parse_ip", "(", "addr", ")", "if", "ip_addr", "is", "None", ":", "LOG", ".", "warn", "(", "\"Cannot restrict address %r from proxy %s: \"", "\"invalid address\"", "%", "(", "addr", ",", "self", ".", "address", ")", ")", "else", ":", "self", ".", "excluded", ".", "add", "(", "addr", ")" ]
Drop an address from the set of addresses this proxy is permitted to introduce. :param addr: The address to remove.
[ "Drop", "an", "address", "from", "the", "set", "of", "addresses", "this", "proxy", "is", "permitted", "to", "introduce", "." ]
6e0e002d55f01fee27e3e45bb86e30af1bfeef36
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/proxy.py#L111-L125
250,623
klmitch/bark
bark/proxy.py
Proxy.accept
def accept(self, addr): """ Add an address to the set of addresses this proxy is permitted to introduce. :param addr: The address to add. """ # Add the address to the set ip_addr = _parse_ip(addr) if ip_addr is None: LOG.warn("Cannot add address %r to proxy %s: " "invalid address" % (addr, self.address)) else: self.accepted.add(addr)
python
def accept(self, addr): """ Add an address to the set of addresses this proxy is permitted to introduce. :param addr: The address to add. """ # Add the address to the set ip_addr = _parse_ip(addr) if ip_addr is None: LOG.warn("Cannot add address %r to proxy %s: " "invalid address" % (addr, self.address)) else: self.accepted.add(addr)
[ "def", "accept", "(", "self", ",", "addr", ")", ":", "# Add the address to the set", "ip_addr", "=", "_parse_ip", "(", "addr", ")", "if", "ip_addr", "is", "None", ":", "LOG", ".", "warn", "(", "\"Cannot add address %r to proxy %s: \"", "\"invalid address\"", "%", "(", "addr", ",", "self", ".", "address", ")", ")", "else", ":", "self", ".", "accepted", ".", "add", "(", "addr", ")" ]
Add an address to the set of addresses this proxy is permitted to introduce. :param addr: The address to add.
[ "Add", "an", "address", "to", "the", "set", "of", "addresses", "this", "proxy", "is", "permitted", "to", "introduce", "." ]
6e0e002d55f01fee27e3e45bb86e30af1bfeef36
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/proxy.py#L127-L141
250,624
klmitch/bark
bark/proxy.py
ProxyConfig.validate
def validate(self, proxy_ip, client_ip): """ Looks up the proxy identified by its IP, then verifies that the given client IP may be introduced by that proxy. :param proxy_ip: The IP address of the proxy. :param client_ip: The IP address of the supposed client. :returns: True if the proxy is permitted to introduce the client; False if the proxy doesn't exist or isn't permitted to introduce the client. """ # First, look up the proxy if self.pseudo_proxy: proxy = self.pseudo_proxy elif proxy_ip not in self.proxies: return False else: proxy = self.proxies[proxy_ip] # Now, verify that the client is valid return client_ip in proxy
python
def validate(self, proxy_ip, client_ip): """ Looks up the proxy identified by its IP, then verifies that the given client IP may be introduced by that proxy. :param proxy_ip: The IP address of the proxy. :param client_ip: The IP address of the supposed client. :returns: True if the proxy is permitted to introduce the client; False if the proxy doesn't exist or isn't permitted to introduce the client. """ # First, look up the proxy if self.pseudo_proxy: proxy = self.pseudo_proxy elif proxy_ip not in self.proxies: return False else: proxy = self.proxies[proxy_ip] # Now, verify that the client is valid return client_ip in proxy
[ "def", "validate", "(", "self", ",", "proxy_ip", ",", "client_ip", ")", ":", "# First, look up the proxy", "if", "self", ".", "pseudo_proxy", ":", "proxy", "=", "self", ".", "pseudo_proxy", "elif", "proxy_ip", "not", "in", "self", ".", "proxies", ":", "return", "False", "else", ":", "proxy", "=", "self", ".", "proxies", "[", "proxy_ip", "]", "# Now, verify that the client is valid", "return", "client_ip", "in", "proxy" ]
Looks up the proxy identified by its IP, then verifies that the given client IP may be introduced by that proxy. :param proxy_ip: The IP address of the proxy. :param client_ip: The IP address of the supposed client. :returns: True if the proxy is permitted to introduce the client; False if the proxy doesn't exist or isn't permitted to introduce the client.
[ "Looks", "up", "the", "proxy", "identified", "by", "its", "IP", "then", "verifies", "that", "the", "given", "client", "IP", "may", "be", "introduced", "by", "that", "proxy", "." ]
6e0e002d55f01fee27e3e45bb86e30af1bfeef36
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/proxy.py#L282-L304
250,625
shad7/tvdbapi_client
tvdbapi_client/api.py
requires_auth
def requires_auth(func): """Handle authentication checks. .. py:decorator:: requires_auth Checks if the token has expired and performs authentication if needed. """ @six.wraps(func) def wrapper(self, *args, **kwargs): if self.token_expired: self.authenticate() return func(self, *args, **kwargs) return wrapper
python
def requires_auth(func): """Handle authentication checks. .. py:decorator:: requires_auth Checks if the token has expired and performs authentication if needed. """ @six.wraps(func) def wrapper(self, *args, **kwargs): if self.token_expired: self.authenticate() return func(self, *args, **kwargs) return wrapper
[ "def", "requires_auth", "(", "func", ")", ":", "@", "six", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "token_expired", ":", "self", ".", "authenticate", "(", ")", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Handle authentication checks. .. py:decorator:: requires_auth Checks if the token has expired and performs authentication if needed.
[ "Handle", "authentication", "checks", "." ]
edf1771184122f4db42af7fc087407a3e6a4e377
https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/api.py#L40-L52
250,626
shad7/tvdbapi_client
tvdbapi_client/api.py
TVDBClient.headers
def headers(self): """Provide access to updated headers.""" self._headers.update(**{'Accept-Language': self.language}) if self.__token: self._headers.update( **{'Authorization': 'Bearer %s' % self.__token}) return self._headers
python
def headers(self): """Provide access to updated headers.""" self._headers.update(**{'Accept-Language': self.language}) if self.__token: self._headers.update( **{'Authorization': 'Bearer %s' % self.__token}) return self._headers
[ "def", "headers", "(", "self", ")", ":", "self", ".", "_headers", ".", "update", "(", "*", "*", "{", "'Accept-Language'", ":", "self", ".", "language", "}", ")", "if", "self", ".", "__token", ":", "self", ".", "_headers", ".", "update", "(", "*", "*", "{", "'Authorization'", ":", "'Bearer %s'", "%", "self", ".", "__token", "}", ")", "return", "self", ".", "_headers" ]
Provide access to updated headers.
[ "Provide", "access", "to", "updated", "headers", "." ]
edf1771184122f4db42af7fc087407a3e6a4e377
https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/api.py#L77-L83
250,627
shad7/tvdbapi_client
tvdbapi_client/api.py
TVDBClient.token_expired
def token_expired(self): """Provide access to flag indicating if token has expired.""" if self._token_timer is None: return True return timeutil.is_newer_than(self._token_timer, timeutil.ONE_HOUR)
python
def token_expired(self): """Provide access to flag indicating if token has expired.""" if self._token_timer is None: return True return timeutil.is_newer_than(self._token_timer, timeutil.ONE_HOUR)
[ "def", "token_expired", "(", "self", ")", ":", "if", "self", ".", "_token_timer", "is", "None", ":", "return", "True", "return", "timeutil", ".", "is_newer_than", "(", "self", ".", "_token_timer", ",", "timeutil", ".", "ONE_HOUR", ")" ]
Provide access to flag indicating if token has expired.
[ "Provide", "access", "to", "flag", "indicating", "if", "token", "has", "expired", "." ]
edf1771184122f4db42af7fc087407a3e6a4e377
https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/api.py#L96-L100
250,628
shad7/tvdbapi_client
tvdbapi_client/api.py
TVDBClient.session
def session(self): """Provide access to request session with local cache enabled.""" if self._session is None: self._session = cachecontrol.CacheControl( requests.Session(), cache=caches.FileCache('.tvdb_cache')) return self._session
python
def session(self): """Provide access to request session with local cache enabled.""" if self._session is None: self._session = cachecontrol.CacheControl( requests.Session(), cache=caches.FileCache('.tvdb_cache')) return self._session
[ "def", "session", "(", "self", ")", ":", "if", "self", ".", "_session", "is", "None", ":", "self", ".", "_session", "=", "cachecontrol", ".", "CacheControl", "(", "requests", ".", "Session", "(", ")", ",", "cache", "=", "caches", ".", "FileCache", "(", "'.tvdb_cache'", ")", ")", "return", "self", ".", "_session" ]
Provide access to request session with local cache enabled.
[ "Provide", "access", "to", "request", "session", "with", "local", "cache", "enabled", "." ]
edf1771184122f4db42af7fc087407a3e6a4e377
https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/api.py#L103-L109
250,629
shad7/tvdbapi_client
tvdbapi_client/api.py
TVDBClient._exec_request
def _exec_request(self, service, method=None, path_args=None, data=None, params=None): """Execute request.""" if path_args is None: path_args = [] req = { 'method': method or 'get', 'url': '/'.join(str(a).strip('/') for a in [ cfg.CONF.tvdb.service_url, service] + path_args), 'data': json.dumps(data) if data else None, 'headers': self.headers, 'params': params, 'verify': cfg.CONF.tvdb.verify_ssl_certs, } LOG.debug('executing request (%s %s)', req['method'], req['url']) resp = self.session.request(**req) resp.raise_for_status() return resp.json() if resp.text else resp.text
python
def _exec_request(self, service, method=None, path_args=None, data=None, params=None): """Execute request.""" if path_args is None: path_args = [] req = { 'method': method or 'get', 'url': '/'.join(str(a).strip('/') for a in [ cfg.CONF.tvdb.service_url, service] + path_args), 'data': json.dumps(data) if data else None, 'headers': self.headers, 'params': params, 'verify': cfg.CONF.tvdb.verify_ssl_certs, } LOG.debug('executing request (%s %s)', req['method'], req['url']) resp = self.session.request(**req) resp.raise_for_status() return resp.json() if resp.text else resp.text
[ "def", "_exec_request", "(", "self", ",", "service", ",", "method", "=", "None", ",", "path_args", "=", "None", ",", "data", "=", "None", ",", "params", "=", "None", ")", ":", "if", "path_args", "is", "None", ":", "path_args", "=", "[", "]", "req", "=", "{", "'method'", ":", "method", "or", "'get'", ",", "'url'", ":", "'/'", ".", "join", "(", "str", "(", "a", ")", ".", "strip", "(", "'/'", ")", "for", "a", "in", "[", "cfg", ".", "CONF", ".", "tvdb", ".", "service_url", ",", "service", "]", "+", "path_args", ")", ",", "'data'", ":", "json", ".", "dumps", "(", "data", ")", "if", "data", "else", "None", ",", "'headers'", ":", "self", ".", "headers", ",", "'params'", ":", "params", ",", "'verify'", ":", "cfg", ".", "CONF", ".", "tvdb", ".", "verify_ssl_certs", ",", "}", "LOG", ".", "debug", "(", "'executing request (%s %s)'", ",", "req", "[", "'method'", "]", ",", "req", "[", "'url'", "]", ")", "resp", "=", "self", ".", "session", ".", "request", "(", "*", "*", "req", ")", "resp", ".", "raise_for_status", "(", ")", "return", "resp", ".", "json", "(", ")", "if", "resp", ".", "text", "else", "resp", ".", "text" ]
Execute request.
[ "Execute", "request", "." ]
edf1771184122f4db42af7fc087407a3e6a4e377
https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/api.py#L112-L132
250,630
shad7/tvdbapi_client
tvdbapi_client/api.py
TVDBClient.authenticate
def authenticate(self): """Aquire authorization token for using thetvdb apis.""" if self.__token: try: resp = self._refresh_token() except exceptions.TVDBRequestException as err: # if a 401 is the cause try to login if getattr(err.response, 'status_code', 0) == 401: resp = self._login() else: raise else: resp = self._login() self.__token = resp.get('token') self._token_timer = timeutil.utcnow()
python
def authenticate(self): """Aquire authorization token for using thetvdb apis.""" if self.__token: try: resp = self._refresh_token() except exceptions.TVDBRequestException as err: # if a 401 is the cause try to login if getattr(err.response, 'status_code', 0) == 401: resp = self._login() else: raise else: resp = self._login() self.__token = resp.get('token') self._token_timer = timeutil.utcnow()
[ "def", "authenticate", "(", "self", ")", ":", "if", "self", ".", "__token", ":", "try", ":", "resp", "=", "self", ".", "_refresh_token", "(", ")", "except", "exceptions", ".", "TVDBRequestException", "as", "err", ":", "# if a 401 is the cause try to login", "if", "getattr", "(", "err", ".", "response", ",", "'status_code'", ",", "0", ")", "==", "401", ":", "resp", "=", "self", ".", "_login", "(", ")", "else", ":", "raise", "else", ":", "resp", "=", "self", ".", "_login", "(", ")", "self", ".", "__token", "=", "resp", ".", "get", "(", "'token'", ")", "self", ".", "_token_timer", "=", "timeutil", ".", "utcnow", "(", ")" ]
Aquire authorization token for using thetvdb apis.
[ "Aquire", "authorization", "token", "for", "using", "thetvdb", "apis", "." ]
edf1771184122f4db42af7fc087407a3e6a4e377
https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/api.py#L144-L159
250,631
shad7/tvdbapi_client
tvdbapi_client/api.py
TVDBClient.search_series
def search_series(self, **kwargs): """Provide the ability to search for a series. .. warning:: authorization token required The following search arguments currently supported: * name * imdbId * zap2itId :param kwargs: keyword arguments to search for series :returns: series record or series records :rtype: dict """ params = {} for arg, val in six.iteritems(kwargs): if arg in SERIES_BY: params[arg] = val resp = self._exec_request( 'search', path_args=['series'], params=params) if cfg.CONF.tvdb.select_first: return resp['data'][0] return resp['data']
python
def search_series(self, **kwargs): """Provide the ability to search for a series. .. warning:: authorization token required The following search arguments currently supported: * name * imdbId * zap2itId :param kwargs: keyword arguments to search for series :returns: series record or series records :rtype: dict """ params = {} for arg, val in six.iteritems(kwargs): if arg in SERIES_BY: params[arg] = val resp = self._exec_request( 'search', path_args=['series'], params=params) if cfg.CONF.tvdb.select_first: return resp['data'][0] return resp['data']
[ "def", "search_series", "(", "self", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "}", "for", "arg", ",", "val", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "if", "arg", "in", "SERIES_BY", ":", "params", "[", "arg", "]", "=", "val", "resp", "=", "self", ".", "_exec_request", "(", "'search'", ",", "path_args", "=", "[", "'series'", "]", ",", "params", "=", "params", ")", "if", "cfg", ".", "CONF", ".", "tvdb", ".", "select_first", ":", "return", "resp", "[", "'data'", "]", "[", "0", "]", "return", "resp", "[", "'data'", "]" ]
Provide the ability to search for a series. .. warning:: authorization token required The following search arguments currently supported: * name * imdbId * zap2itId :param kwargs: keyword arguments to search for series :returns: series record or series records :rtype: dict
[ "Provide", "the", "ability", "to", "search", "for", "a", "series", "." ]
edf1771184122f4db42af7fc087407a3e6a4e377
https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/api.py#L162-L187
250,632
shad7/tvdbapi_client
tvdbapi_client/api.py
TVDBClient.get_episodes
def get_episodes(self, series_id, **kwargs): """All episodes for a given series. Paginated with 100 results per page. .. warning:: authorization token required The following search arguments currently supported: * airedSeason * airedEpisode * imdbId * dvdSeason * dvdEpisode * absoluteNumber * page :param str series_id: id of series as found on thetvdb :parm kwargs: keyword args to search/filter episodes by (optional) :returns: series episode records :rtype: list """ params = {'page': 1} for arg, val in six.iteritems(kwargs): if arg in EPISODES_BY: params[arg] = val return self._exec_request( 'series', path_args=[series_id, 'episodes', 'query'], params=params)['data']
python
def get_episodes(self, series_id, **kwargs): """All episodes for a given series. Paginated with 100 results per page. .. warning:: authorization token required The following search arguments currently supported: * airedSeason * airedEpisode * imdbId * dvdSeason * dvdEpisode * absoluteNumber * page :param str series_id: id of series as found on thetvdb :parm kwargs: keyword args to search/filter episodes by (optional) :returns: series episode records :rtype: list """ params = {'page': 1} for arg, val in six.iteritems(kwargs): if arg in EPISODES_BY: params[arg] = val return self._exec_request( 'series', path_args=[series_id, 'episodes', 'query'], params=params)['data']
[ "def", "get_episodes", "(", "self", ",", "series_id", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'page'", ":", "1", "}", "for", "arg", ",", "val", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "if", "arg", "in", "EPISODES_BY", ":", "params", "[", "arg", "]", "=", "val", "return", "self", ".", "_exec_request", "(", "'series'", ",", "path_args", "=", "[", "series_id", ",", "'episodes'", ",", "'query'", "]", ",", "params", "=", "params", ")", "[", "'data'", "]" ]
All episodes for a given series. Paginated with 100 results per page. .. warning:: authorization token required The following search arguments currently supported: * airedSeason * airedEpisode * imdbId * dvdSeason * dvdEpisode * absoluteNumber * page :param str series_id: id of series as found on thetvdb :parm kwargs: keyword args to search/filter episodes by (optional) :returns: series episode records :rtype: list
[ "All", "episodes", "for", "a", "given", "series", "." ]
edf1771184122f4db42af7fc087407a3e6a4e377
https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/api.py#L204-L234
250,633
pjuren/pyokit
src/pyokit/datastruct/intervalTree.py
IntervalTree.intersectingPoint
def intersectingPoint(self, p): """ given a point, get intervals in the tree that are intersected. :param p: intersection point :return: the list of intersected intervals """ # perfect match if p == self.data.mid: return self.data.ends if p > self.data.mid: # we know all intervals in self.data begin before p (if they began after # p, they would have not included mid) we just need to find those that # end after p endAfterP = [r for r in self.data.ends if (r.end >= p and not self.openEnded) or (r.end > p and self.openEnded)] if self.right is not None: endAfterP.extend(self.right.intersectingPoint(p)) return endAfterP if p < self.data.mid: # we know all intervals in self.data end after p (if they ended before p, # they would have not included mid) we just need to find those that start # before p startBeforeP = [r for r in self.data.starts if r.start <= p] if self.left is not None: startBeforeP.extend(self.left.intersectingPoint(p)) return startBeforeP
python
def intersectingPoint(self, p): """ given a point, get intervals in the tree that are intersected. :param p: intersection point :return: the list of intersected intervals """ # perfect match if p == self.data.mid: return self.data.ends if p > self.data.mid: # we know all intervals in self.data begin before p (if they began after # p, they would have not included mid) we just need to find those that # end after p endAfterP = [r for r in self.data.ends if (r.end >= p and not self.openEnded) or (r.end > p and self.openEnded)] if self.right is not None: endAfterP.extend(self.right.intersectingPoint(p)) return endAfterP if p < self.data.mid: # we know all intervals in self.data end after p (if they ended before p, # they would have not included mid) we just need to find those that start # before p startBeforeP = [r for r in self.data.starts if r.start <= p] if self.left is not None: startBeforeP.extend(self.left.intersectingPoint(p)) return startBeforeP
[ "def", "intersectingPoint", "(", "self", ",", "p", ")", ":", "# perfect match", "if", "p", "==", "self", ".", "data", ".", "mid", ":", "return", "self", ".", "data", ".", "ends", "if", "p", ">", "self", ".", "data", ".", "mid", ":", "# we know all intervals in self.data begin before p (if they began after", "# p, they would have not included mid) we just need to find those that", "# end after p", "endAfterP", "=", "[", "r", "for", "r", "in", "self", ".", "data", ".", "ends", "if", "(", "r", ".", "end", ">=", "p", "and", "not", "self", ".", "openEnded", ")", "or", "(", "r", ".", "end", ">", "p", "and", "self", ".", "openEnded", ")", "]", "if", "self", ".", "right", "is", "not", "None", ":", "endAfterP", ".", "extend", "(", "self", ".", "right", ".", "intersectingPoint", "(", "p", ")", ")", "return", "endAfterP", "if", "p", "<", "self", ".", "data", ".", "mid", ":", "# we know all intervals in self.data end after p (if they ended before p,", "# they would have not included mid) we just need to find those that start", "# before p", "startBeforeP", "=", "[", "r", "for", "r", "in", "self", ".", "data", ".", "starts", "if", "r", ".", "start", "<=", "p", "]", "if", "self", ".", "left", "is", "not", "None", ":", "startBeforeP", ".", "extend", "(", "self", ".", "left", ".", "intersectingPoint", "(", "p", ")", ")", "return", "startBeforeP" ]
given a point, get intervals in the tree that are intersected. :param p: intersection point :return: the list of intersected intervals
[ "given", "a", "point", "get", "intervals", "in", "the", "tree", "that", "are", "intersected", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/intervalTree.py#L133-L162
250,634
pjuren/pyokit
src/pyokit/datastruct/intervalTree.py
IntervalTree.intersectingInterval
def intersectingInterval(self, start, end): """ given an interval, get intervals in the tree that are intersected. :param start: start of the intersecting interval :param end: end of the intersecting interval :return: the list of intersected intervals """ # find all intervals in this node that intersect start and end l = [] for x in self.data.starts: xStartsAfterInterval = (x.start > end and not self.openEnded) or \ (x.start >= end and self.openEnded) xEndsBeforeInterval = (x.end < start and not self.openEnded) or \ (x.end <= start and self.openEnded) if ((not xStartsAfterInterval) and (not xEndsBeforeInterval)): l.append(x) # process left subtree (if we have one) if the requested interval begins # before mid if self.left is not None and start <= self.data.mid: l += self.left.intersectingInterval(start, end) # process right subtree (if we have one) if the requested interval ends # after mid if self.right is not None and end >= self.data.mid: l += self.right.intersectingInterval(start, end) return l
python
def intersectingInterval(self, start, end): """ given an interval, get intervals in the tree that are intersected. :param start: start of the intersecting interval :param end: end of the intersecting interval :return: the list of intersected intervals """ # find all intervals in this node that intersect start and end l = [] for x in self.data.starts: xStartsAfterInterval = (x.start > end and not self.openEnded) or \ (x.start >= end and self.openEnded) xEndsBeforeInterval = (x.end < start and not self.openEnded) or \ (x.end <= start and self.openEnded) if ((not xStartsAfterInterval) and (not xEndsBeforeInterval)): l.append(x) # process left subtree (if we have one) if the requested interval begins # before mid if self.left is not None and start <= self.data.mid: l += self.left.intersectingInterval(start, end) # process right subtree (if we have one) if the requested interval ends # after mid if self.right is not None and end >= self.data.mid: l += self.right.intersectingInterval(start, end) return l
[ "def", "intersectingInterval", "(", "self", ",", "start", ",", "end", ")", ":", "# find all intervals in this node that intersect start and end", "l", "=", "[", "]", "for", "x", "in", "self", ".", "data", ".", "starts", ":", "xStartsAfterInterval", "=", "(", "x", ".", "start", ">", "end", "and", "not", "self", ".", "openEnded", ")", "or", "(", "x", ".", "start", ">=", "end", "and", "self", ".", "openEnded", ")", "xEndsBeforeInterval", "=", "(", "x", ".", "end", "<", "start", "and", "not", "self", ".", "openEnded", ")", "or", "(", "x", ".", "end", "<=", "start", "and", "self", ".", "openEnded", ")", "if", "(", "(", "not", "xStartsAfterInterval", ")", "and", "(", "not", "xEndsBeforeInterval", ")", ")", ":", "l", ".", "append", "(", "x", ")", "# process left subtree (if we have one) if the requested interval begins", "# before mid", "if", "self", ".", "left", "is", "not", "None", "and", "start", "<=", "self", ".", "data", ".", "mid", ":", "l", "+=", "self", ".", "left", ".", "intersectingInterval", "(", "start", ",", "end", ")", "# process right subtree (if we have one) if the requested interval ends", "# after mid", "if", "self", ".", "right", "is", "not", "None", "and", "end", ">=", "self", ".", "data", ".", "mid", ":", "l", "+=", "self", ".", "right", ".", "intersectingInterval", "(", "start", ",", "end", ")", "return", "l" ]
given an interval, get intervals in the tree that are intersected. :param start: start of the intersecting interval :param end: end of the intersecting interval :return: the list of intersected intervals
[ "given", "an", "interval", "get", "intervals", "in", "the", "tree", "that", "are", "intersected", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/intervalTree.py#L164-L192
250,635
pjuren/pyokit
src/pyokit/datastruct/intervalTree.py
IntervalTree.intersectingIntervalIterator
def intersectingIntervalIterator(self, start, end): """ Get an iterator which will iterate over those objects in the tree which intersect the given interval - sorted in order of start index :param start: find intervals in the tree that intersect an interval with with this start index (inclusive) :param end: find intervals in the tree that intersect an interval with with this end index (exclusive) :return: an iterator that will yield intersected intervals """ items = self.intersectingInterval(start, end) items.sort(key=lambda x: x.start) for item in items: yield item
python
def intersectingIntervalIterator(self, start, end): """ Get an iterator which will iterate over those objects in the tree which intersect the given interval - sorted in order of start index :param start: find intervals in the tree that intersect an interval with with this start index (inclusive) :param end: find intervals in the tree that intersect an interval with with this end index (exclusive) :return: an iterator that will yield intersected intervals """ items = self.intersectingInterval(start, end) items.sort(key=lambda x: x.start) for item in items: yield item
[ "def", "intersectingIntervalIterator", "(", "self", ",", "start", ",", "end", ")", ":", "items", "=", "self", ".", "intersectingInterval", "(", "start", ",", "end", ")", "items", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "start", ")", "for", "item", "in", "items", ":", "yield", "item" ]
Get an iterator which will iterate over those objects in the tree which intersect the given interval - sorted in order of start index :param start: find intervals in the tree that intersect an interval with with this start index (inclusive) :param end: find intervals in the tree that intersect an interval with with this end index (exclusive) :return: an iterator that will yield intersected intervals
[ "Get", "an", "iterator", "which", "will", "iterate", "over", "those", "objects", "in", "the", "tree", "which", "intersect", "the", "given", "interval", "-", "sorted", "in", "order", "of", "start", "index" ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/intervalTree.py#L194-L208
250,636
aganezov/gos
gos/manager.py
Manager.initiate_tasks
def initiate_tasks(self): """ Loads all tasks using `TaskLoader` from respective configuration option """ self.tasks_classes = TaskLoader().load_tasks( paths=self.configuration[Configuration.ALGORITHM][Configuration.TASKS][Configuration.PATHS])
python
def initiate_tasks(self): """ Loads all tasks using `TaskLoader` from respective configuration option """ self.tasks_classes = TaskLoader().load_tasks( paths=self.configuration[Configuration.ALGORITHM][Configuration.TASKS][Configuration.PATHS])
[ "def", "initiate_tasks", "(", "self", ")", ":", "self", ".", "tasks_classes", "=", "TaskLoader", "(", ")", ".", "load_tasks", "(", "paths", "=", "self", ".", "configuration", "[", "Configuration", ".", "ALGORITHM", "]", "[", "Configuration", ".", "TASKS", "]", "[", "Configuration", ".", "PATHS", "]", ")" ]
Loads all tasks using `TaskLoader` from respective configuration option
[ "Loads", "all", "tasks", "using", "TaskLoader", "from", "respective", "configuration", "option" ]
fb4d210284f3037c5321250cb95f3901754feb6b
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/manager.py#L16-L19
250,637
aganezov/gos
gos/manager.py
Manager.instantiate_tasks
def instantiate_tasks(self): """ All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent """ self.tasks_instances = {} for task_name, task_class in self.tasks_classes.items(): try: self.tasks_instances[task_name] = task_class() except Exception as ex: if not self.configuration[Configuration.ALGORITHM][Configuration.IOSF]: raise GOSTaskException("An exception happened during the task instantiation." "{exception}".format(exception=ex))
python
def instantiate_tasks(self): """ All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent """ self.tasks_instances = {} for task_name, task_class in self.tasks_classes.items(): try: self.tasks_instances[task_name] = task_class() except Exception as ex: if not self.configuration[Configuration.ALGORITHM][Configuration.IOSF]: raise GOSTaskException("An exception happened during the task instantiation." "{exception}".format(exception=ex))
[ "def", "instantiate_tasks", "(", "self", ")", ":", "self", ".", "tasks_instances", "=", "{", "}", "for", "task_name", ",", "task_class", "in", "self", ".", "tasks_classes", ".", "items", "(", ")", ":", "try", ":", "self", ".", "tasks_instances", "[", "task_name", "]", "=", "task_class", "(", ")", "except", "Exception", "as", "ex", ":", "if", "not", "self", ".", "configuration", "[", "Configuration", ".", "ALGORITHM", "]", "[", "Configuration", ".", "IOSF", "]", ":", "raise", "GOSTaskException", "(", "\"An exception happened during the task instantiation.\"", "\"{exception}\"", ".", "format", "(", "exception", "=", "ex", ")", ")" ]
All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent
[ "All", "loaded", "tasks", "are", "initialized", ".", "Depending", "on", "configuration", "fails", "in", "such", "instantiations", "may", "be", "silent" ]
fb4d210284f3037c5321250cb95f3901754feb6b
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/manager.py#L21-L30
250,638
tehmaze-labs/wright
wright/stage/env.py
Generate._have
def _have(self, name=None): """Check if a configure flag is set. If called without argument, it returns all HAVE_* items. Example: {% if have('netinet/ip.h') %}...{% endif %} """ if name is None: return ( (k, v) for k, v in self.env.items() if k.startswith('HAVE_') ) return self.env.get('HAVE_' + self.env_key(name)) == True
python
def _have(self, name=None): """Check if a configure flag is set. If called without argument, it returns all HAVE_* items. Example: {% if have('netinet/ip.h') %}...{% endif %} """ if name is None: return ( (k, v) for k, v in self.env.items() if k.startswith('HAVE_') ) return self.env.get('HAVE_' + self.env_key(name)) == True
[ "def", "_have", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "return", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "env", ".", "items", "(", ")", "if", "k", ".", "startswith", "(", "'HAVE_'", ")", ")", "return", "self", ".", "env", ".", "get", "(", "'HAVE_'", "+", "self", ".", "env_key", "(", "name", ")", ")", "==", "True" ]
Check if a configure flag is set. If called without argument, it returns all HAVE_* items. Example: {% if have('netinet/ip.h') %}...{% endif %}
[ "Check", "if", "a", "configure", "flag", "is", "set", "." ]
79b2d816f541e69d5fb7f36a3c39fa0d432157a6
https://github.com/tehmaze-labs/wright/blob/79b2d816f541e69d5fb7f36a3c39fa0d432157a6/wright/stage/env.py#L32-L46
250,639
tehmaze-labs/wright
wright/stage/env.py
Generate._lib
def _lib(self, name, only_if_have=False): """Specify a linker library. Example: LDFLAGS={{ lib("rt") }} {{ lib("pthread", True) }} Will unconditionally add `-lrt` and check the environment if the key `HAVE_LIBPTHREAD` is set to be true, then add `-lpthread`. """ emit = True if only_if_have: emit = self.env.get('HAVE_LIB' + self.env_key(name)) if emit: return '-l' + name return ''
python
def _lib(self, name, only_if_have=False): """Specify a linker library. Example: LDFLAGS={{ lib("rt") }} {{ lib("pthread", True) }} Will unconditionally add `-lrt` and check the environment if the key `HAVE_LIBPTHREAD` is set to be true, then add `-lpthread`. """ emit = True if only_if_have: emit = self.env.get('HAVE_LIB' + self.env_key(name)) if emit: return '-l' + name return ''
[ "def", "_lib", "(", "self", ",", "name", ",", "only_if_have", "=", "False", ")", ":", "emit", "=", "True", "if", "only_if_have", ":", "emit", "=", "self", ".", "env", ".", "get", "(", "'HAVE_LIB'", "+", "self", ".", "env_key", "(", "name", ")", ")", "if", "emit", ":", "return", "'-l'", "+", "name", "return", "''" ]
Specify a linker library. Example: LDFLAGS={{ lib("rt") }} {{ lib("pthread", True) }} Will unconditionally add `-lrt` and check the environment if the key `HAVE_LIBPTHREAD` is set to be true, then add `-lpthread`.
[ "Specify", "a", "linker", "library", "." ]
79b2d816f541e69d5fb7f36a3c39fa0d432157a6
https://github.com/tehmaze-labs/wright/blob/79b2d816f541e69d5fb7f36a3c39fa0d432157a6/wright/stage/env.py#L48-L63
250,640
tehmaze-labs/wright
wright/stage/env.py
Generate._with
def _with(self, option=None): """Check if a build option is enabled. If called without argument, it returns all WITH_* items. Example: {% if with('foo') %}...{% endif %} """ if option is None: return ( (k, v) for k, v in self.env.items() if k.startswith('WITH_') ) return self.env.get('WITH_' + option.upper()) == True
python
def _with(self, option=None): """Check if a build option is enabled. If called without argument, it returns all WITH_* items. Example: {% if with('foo') %}...{% endif %} """ if option is None: return ( (k, v) for k, v in self.env.items() if k.startswith('WITH_') ) return self.env.get('WITH_' + option.upper()) == True
[ "def", "_with", "(", "self", ",", "option", "=", "None", ")", ":", "if", "option", "is", "None", ":", "return", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "env", ".", "items", "(", ")", "if", "k", ".", "startswith", "(", "'WITH_'", ")", ")", "return", "self", ".", "env", ".", "get", "(", "'WITH_'", "+", "option", ".", "upper", "(", ")", ")", "==", "True" ]
Check if a build option is enabled. If called without argument, it returns all WITH_* items. Example: {% if with('foo') %}...{% endif %}
[ "Check", "if", "a", "build", "option", "is", "enabled", "." ]
79b2d816f541e69d5fb7f36a3c39fa0d432157a6
https://github.com/tehmaze-labs/wright/blob/79b2d816f541e69d5fb7f36a3c39fa0d432157a6/wright/stage/env.py#L65-L79
250,641
klmitch/bark
bark/conversions.py
Modifier.set_codes
def set_codes(self, codes, reject=False): """ Set the accepted or rejected codes codes list. :param codes: A list of the response codes. :param reject: If True, the listed codes will be rejected, and the conversion will format as "-"; if False, only the listed codes will be accepted, and the conversion will format as "-" for all the others. """ self.codes = set(codes) self.reject = reject
python
def set_codes(self, codes, reject=False): """ Set the accepted or rejected codes codes list. :param codes: A list of the response codes. :param reject: If True, the listed codes will be rejected, and the conversion will format as "-"; if False, only the listed codes will be accepted, and the conversion will format as "-" for all the others. """ self.codes = set(codes) self.reject = reject
[ "def", "set_codes", "(", "self", ",", "codes", ",", "reject", "=", "False", ")", ":", "self", ".", "codes", "=", "set", "(", "codes", ")", "self", ".", "reject", "=", "reject" ]
Set the accepted or rejected codes codes list. :param codes: A list of the response codes. :param reject: If True, the listed codes will be rejected, and the conversion will format as "-"; if False, only the listed codes will be accepted, and the conversion will format as "-" for all the others.
[ "Set", "the", "accepted", "or", "rejected", "codes", "codes", "list", "." ]
6e0e002d55f01fee27e3e45bb86e30af1bfeef36
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L60-L73
250,642
klmitch/bark
bark/conversions.py
Modifier.accept
def accept(self, code): """ Determine whether to accept the given code. :param code: The response code. :returns: True if the code should be accepted, False otherwise. """ if code in self.codes: return not self.reject return self.reject
python
def accept(self, code): """ Determine whether to accept the given code. :param code: The response code. :returns: True if the code should be accepted, False otherwise. """ if code in self.codes: return not self.reject return self.reject
[ "def", "accept", "(", "self", ",", "code", ")", ":", "if", "code", "in", "self", ".", "codes", ":", "return", "not", "self", ".", "reject", "return", "self", ".", "reject" ]
Determine whether to accept the given code. :param code: The response code. :returns: True if the code should be accepted, False otherwise.
[ "Determine", "whether", "to", "accept", "the", "given", "code", "." ]
6e0e002d55f01fee27e3e45bb86e30af1bfeef36
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L84-L96
250,643
klmitch/bark
bark/conversions.py
Conversion._needescape
def _needescape(c): """ Return True if character needs escaping, else False. """ return not ascii.isprint(c) or c == '"' or c == '\\' or ascii.isctrl(c)
python
def _needescape(c): """ Return True if character needs escaping, else False. """ return not ascii.isprint(c) or c == '"' or c == '\\' or ascii.isctrl(c)
[ "def", "_needescape", "(", "c", ")", ":", "return", "not", "ascii", ".", "isprint", "(", "c", ")", "or", "c", "==", "'\"'", "or", "c", "==", "'\\\\'", "or", "ascii", ".", "isctrl", "(", "c", ")" ]
Return True if character needs escaping, else False.
[ "Return", "True", "if", "character", "needs", "escaping", "else", "False", "." ]
6e0e002d55f01fee27e3e45bb86e30af1bfeef36
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L118-L123
250,644
klmitch/bark
bark/conversions.py
Conversion.escape
def escape(cls, string): """ Utility method to produce an escaped version of a given string. :param string: The string to escape. :returns: The escaped version of the string. """ return ''.join([cls._escapes[c] if cls._needescape(c) else c for c in string.encode('utf8')])
python
def escape(cls, string): """ Utility method to produce an escaped version of a given string. :param string: The string to escape. :returns: The escaped version of the string. """ return ''.join([cls._escapes[c] if cls._needescape(c) else c for c in string.encode('utf8')])
[ "def", "escape", "(", "cls", ",", "string", ")", ":", "return", "''", ".", "join", "(", "[", "cls", ".", "_escapes", "[", "c", "]", "if", "cls", ".", "_needescape", "(", "c", ")", "else", "c", "for", "c", "in", "string", ".", "encode", "(", "'utf8'", ")", "]", ")" ]
Utility method to produce an escaped version of a given string. :param string: The string to escape. :returns: The escaped version of the string.
[ "Utility", "method", "to", "produce", "an", "escaped", "version", "of", "a", "given", "string", "." ]
6e0e002d55f01fee27e3e45bb86e30af1bfeef36
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L126-L137
250,645
jmgilman/Neolib
neolib/http/HTTPForm.py
HTTPForm.submit
def submit(self): """ Posts the form's data and returns the resulting Page Returns Page - The resulting page """ u = urlparse(self.url) if not self.action: self.action = self.url elif self.action == u.path: self.action = self.url else: if not u.netloc in self.action: path = "/".join(u.path.split("/")[1:-1]) if self.action.startswith("/"): path = path + self.action else: path = path + "/" + self.action self.action = "http://" + u.netloc + "/" + path return self.usr.getPage(self.action, self.items, {'Referer': self.url}, self.usePin)
python
def submit(self): """ Posts the form's data and returns the resulting Page Returns Page - The resulting page """ u = urlparse(self.url) if not self.action: self.action = self.url elif self.action == u.path: self.action = self.url else: if not u.netloc in self.action: path = "/".join(u.path.split("/")[1:-1]) if self.action.startswith("/"): path = path + self.action else: path = path + "/" + self.action self.action = "http://" + u.netloc + "/" + path return self.usr.getPage(self.action, self.items, {'Referer': self.url}, self.usePin)
[ "def", "submit", "(", "self", ")", ":", "u", "=", "urlparse", "(", "self", ".", "url", ")", "if", "not", "self", ".", "action", ":", "self", ".", "action", "=", "self", ".", "url", "elif", "self", ".", "action", "==", "u", ".", "path", ":", "self", ".", "action", "=", "self", ".", "url", "else", ":", "if", "not", "u", ".", "netloc", "in", "self", ".", "action", ":", "path", "=", "\"/\"", ".", "join", "(", "u", ".", "path", ".", "split", "(", "\"/\"", ")", "[", "1", ":", "-", "1", "]", ")", "if", "self", ".", "action", ".", "startswith", "(", "\"/\"", ")", ":", "path", "=", "path", "+", "self", ".", "action", "else", ":", "path", "=", "path", "+", "\"/\"", "+", "self", ".", "action", "self", ".", "action", "=", "\"http://\"", "+", "u", ".", "netloc", "+", "\"/\"", "+", "path", "return", "self", ".", "usr", ".", "getPage", "(", "self", ".", "action", ",", "self", ".", "items", ",", "{", "'Referer'", ":", "self", ".", "url", "}", ",", "self", ".", "usePin", ")" ]
Posts the form's data and returns the resulting Page Returns Page - The resulting page
[ "Posts", "the", "form", "s", "data", "and", "returns", "the", "resulting", "Page", "Returns", "Page", "-", "The", "resulting", "page" ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/http/HTTPForm.py#L73-L94
250,646
amaas-fintech/amaas-utils-python
amaasutils/hash.py
compute_hash
def compute_hash(attributes, ignored_attributes=None): """ Computes a hash code for the given dictionary that is safe for persistence round trips """ ignored_attributes = list(ignored_attributes) if ignored_attributes else [] tuple_attributes = _convert(attributes.copy(), ignored_attributes) hasher = hashlib.sha256(str(tuple_attributes).encode('utf-8', errors='ignore')) return hasher.hexdigest()
python
def compute_hash(attributes, ignored_attributes=None): """ Computes a hash code for the given dictionary that is safe for persistence round trips """ ignored_attributes = list(ignored_attributes) if ignored_attributes else [] tuple_attributes = _convert(attributes.copy(), ignored_attributes) hasher = hashlib.sha256(str(tuple_attributes).encode('utf-8', errors='ignore')) return hasher.hexdigest()
[ "def", "compute_hash", "(", "attributes", ",", "ignored_attributes", "=", "None", ")", ":", "ignored_attributes", "=", "list", "(", "ignored_attributes", ")", "if", "ignored_attributes", "else", "[", "]", "tuple_attributes", "=", "_convert", "(", "attributes", ".", "copy", "(", ")", ",", "ignored_attributes", ")", "hasher", "=", "hashlib", ".", "sha256", "(", "str", "(", "tuple_attributes", ")", ".", "encode", "(", "'utf-8'", ",", "errors", "=", "'ignore'", ")", ")", "return", "hasher", ".", "hexdigest", "(", ")" ]
Computes a hash code for the given dictionary that is safe for persistence round trips
[ "Computes", "a", "hash", "code", "for", "the", "given", "dictionary", "that", "is", "safe", "for", "persistence", "round", "trips" ]
5aa64ca65ce0c77b513482d943345d94c9ae58e8
https://github.com/amaas-fintech/amaas-utils-python/blob/5aa64ca65ce0c77b513482d943345d94c9ae58e8/amaasutils/hash.py#L3-L10
250,647
emencia/emencia_paste_djangocms_3
emencia_paste_djangocms_3/django_buildout/project/contact_form/forms.py
SimpleRowColumn
def SimpleRowColumn(field, *args, **kwargs): """ Shortcut for simple row with only a full column """ if isinstance(field, basestring): field = Field(field, *args, **kwargs) return Row( Column(field), )
python
def SimpleRowColumn(field, *args, **kwargs): """ Shortcut for simple row with only a full column """ if isinstance(field, basestring): field = Field(field, *args, **kwargs) return Row( Column(field), )
[ "def", "SimpleRowColumn", "(", "field", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "field", ",", "basestring", ")", ":", "field", "=", "Field", "(", "field", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "Row", "(", "Column", "(", "field", ")", ",", ")" ]
Shortcut for simple row with only a full column
[ "Shortcut", "for", "simple", "row", "with", "only", "a", "full", "column" ]
29eabbcb17e21996a6e1d99592fc719dc8833b59
https://github.com/emencia/emencia_paste_djangocms_3/blob/29eabbcb17e21996a6e1d99592fc719dc8833b59/emencia_paste_djangocms_3/django_buildout/project/contact_form/forms.py#L21-L29
250,648
emencia/emencia_paste_djangocms_3
emencia_paste_djangocms_3/django_buildout/project/contact_form/forms.py
ContactFormBase.save
def save(self, commit=True): """Save and send""" contact = super(ContactFormBase, self).save() context = {'contact': contact} context.update(get_site_metas()) subject = ''.join(render_to_string(self.mail_subject_template, context).splitlines()) content = render_to_string(self.mail_content_template, context) send_mail(subject, content, settings.DEFAULT_FROM_EMAIL, settings.CONTACT_FORM_TO, fail_silently=not settings.DEBUG) return contact
python
def save(self, commit=True): """Save and send""" contact = super(ContactFormBase, self).save() context = {'contact': contact} context.update(get_site_metas()) subject = ''.join(render_to_string(self.mail_subject_template, context).splitlines()) content = render_to_string(self.mail_content_template, context) send_mail(subject, content, settings.DEFAULT_FROM_EMAIL, settings.CONTACT_FORM_TO, fail_silently=not settings.DEBUG) return contact
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "contact", "=", "super", "(", "ContactFormBase", ",", "self", ")", ".", "save", "(", ")", "context", "=", "{", "'contact'", ":", "contact", "}", "context", ".", "update", "(", "get_site_metas", "(", ")", ")", "subject", "=", "''", ".", "join", "(", "render_to_string", "(", "self", ".", "mail_subject_template", ",", "context", ")", ".", "splitlines", "(", ")", ")", "content", "=", "render_to_string", "(", "self", ".", "mail_content_template", ",", "context", ")", "send_mail", "(", "subject", ",", "content", ",", "settings", ".", "DEFAULT_FROM_EMAIL", ",", "settings", ".", "CONTACT_FORM_TO", ",", "fail_silently", "=", "not", "settings", ".", "DEBUG", ")", "return", "contact" ]
Save and send
[ "Save", "and", "send" ]
29eabbcb17e21996a6e1d99592fc719dc8833b59
https://github.com/emencia/emencia_paste_djangocms_3/blob/29eabbcb17e21996a6e1d99592fc719dc8833b59/emencia_paste_djangocms_3/django_buildout/project/contact_form/forms.py#L47-L61
250,649
klmitch/bark
bark/middleware.py
bark_filter
def bark_filter(global_conf, **local_conf): """ Factory function for Bark. Returns a function which, when passed the application, returns an instance of BarkMiddleware. :param global_conf: The global configuration, from the [DEFAULT] section of the PasteDeploy configuration file. :param local_conf: The local configuration, from the filter section of the PasteDeploy configuration file. """ # First, parse the configuration conf_file = None sections = {} for key, value in local_conf.items(): # 'config' key causes a load of a configuration file; settings # in the local_conf will override settings in the # configuration file, however if key == 'config': conf_file = value elif '.' in key: sect, _sep, opt = key.partition('.') sect_dict = sections.setdefault(sect, {}) sect_dict[opt] = value # note: a string # Now that we've loaded local_conf, process conf_file (if any) if conf_file: cp = ConfigParser.SafeConfigParser() cp.read([conf_file]) for sect in cp.sections(): for opt, value in cp.options(sect): sect_dict = sections.setdefault(sect, {}) # By using setdefault(), we allow local_conf to # override the configuration file sect_dict.setdefault(opt, value) # OK, the configuration is all read; next step is to turn the # configuration into logging handlers handlers = {} proxies = None for sect, sect_dict in sections.items(): if sect == 'proxies': # Reserved for proxy configuration try: proxies = bark.proxy.ProxyConfig(sect_dict) except KeyError as exc: LOG.warn("Cannot configure proxy handling: option %s is " "missing from the proxy configuration" % exc) continue # Pragma: nocover # First, determine the logging format try: format = bark.format.Format.parse(sect_dict.pop('format')) except KeyError: LOG.warn("No format specified for log %r; skipping." % sect) continue # Next, determine the handler type handle_type = sect_dict.pop('type', 'file') # Now, let's construct a handler; this will be a callable # taking the formatted message to log try: handler = bark.handlers.get_handler(handle_type, sect, sect_dict) except Exception as exc: LOG.warn("Cannot load handler of type %r for log %r: %s" % (handle_type, sect, exc)) continue # We now have a handler and a format; bundle them up handlers[sect] = (format, handler) # Construct the wrapper which is going to instantiate the # middleware def wrapper(app): return BarkMiddleware(app, handlers, proxies) return wrapper
python
def bark_filter(global_conf, **local_conf): """ Factory function for Bark. Returns a function which, when passed the application, returns an instance of BarkMiddleware. :param global_conf: The global configuration, from the [DEFAULT] section of the PasteDeploy configuration file. :param local_conf: The local configuration, from the filter section of the PasteDeploy configuration file. """ # First, parse the configuration conf_file = None sections = {} for key, value in local_conf.items(): # 'config' key causes a load of a configuration file; settings # in the local_conf will override settings in the # configuration file, however if key == 'config': conf_file = value elif '.' in key: sect, _sep, opt = key.partition('.') sect_dict = sections.setdefault(sect, {}) sect_dict[opt] = value # note: a string # Now that we've loaded local_conf, process conf_file (if any) if conf_file: cp = ConfigParser.SafeConfigParser() cp.read([conf_file]) for sect in cp.sections(): for opt, value in cp.options(sect): sect_dict = sections.setdefault(sect, {}) # By using setdefault(), we allow local_conf to # override the configuration file sect_dict.setdefault(opt, value) # OK, the configuration is all read; next step is to turn the # configuration into logging handlers handlers = {} proxies = None for sect, sect_dict in sections.items(): if sect == 'proxies': # Reserved for proxy configuration try: proxies = bark.proxy.ProxyConfig(sect_dict) except KeyError as exc: LOG.warn("Cannot configure proxy handling: option %s is " "missing from the proxy configuration" % exc) continue # Pragma: nocover # First, determine the logging format try: format = bark.format.Format.parse(sect_dict.pop('format')) except KeyError: LOG.warn("No format specified for log %r; skipping." % sect) continue # Next, determine the handler type handle_type = sect_dict.pop('type', 'file') # Now, let's construct a handler; this will be a callable # taking the formatted message to log try: handler = bark.handlers.get_handler(handle_type, sect, sect_dict) except Exception as exc: LOG.warn("Cannot load handler of type %r for log %r: %s" % (handle_type, sect, exc)) continue # We now have a handler and a format; bundle them up handlers[sect] = (format, handler) # Construct the wrapper which is going to instantiate the # middleware def wrapper(app): return BarkMiddleware(app, handlers, proxies) return wrapper
[ "def", "bark_filter", "(", "global_conf", ",", "*", "*", "local_conf", ")", ":", "# First, parse the configuration", "conf_file", "=", "None", "sections", "=", "{", "}", "for", "key", ",", "value", "in", "local_conf", ".", "items", "(", ")", ":", "# 'config' key causes a load of a configuration file; settings", "# in the local_conf will override settings in the", "# configuration file, however", "if", "key", "==", "'config'", ":", "conf_file", "=", "value", "elif", "'.'", "in", "key", ":", "sect", ",", "_sep", ",", "opt", "=", "key", ".", "partition", "(", "'.'", ")", "sect_dict", "=", "sections", ".", "setdefault", "(", "sect", ",", "{", "}", ")", "sect_dict", "[", "opt", "]", "=", "value", "# note: a string", "# Now that we've loaded local_conf, process conf_file (if any)", "if", "conf_file", ":", "cp", "=", "ConfigParser", ".", "SafeConfigParser", "(", ")", "cp", ".", "read", "(", "[", "conf_file", "]", ")", "for", "sect", "in", "cp", ".", "sections", "(", ")", ":", "for", "opt", ",", "value", "in", "cp", ".", "options", "(", "sect", ")", ":", "sect_dict", "=", "sections", ".", "setdefault", "(", "sect", ",", "{", "}", ")", "# By using setdefault(), we allow local_conf to", "# override the configuration file", "sect_dict", ".", "setdefault", "(", "opt", ",", "value", ")", "# OK, the configuration is all read; next step is to turn the", "# configuration into logging handlers", "handlers", "=", "{", "}", "proxies", "=", "None", "for", "sect", ",", "sect_dict", "in", "sections", ".", "items", "(", ")", ":", "if", "sect", "==", "'proxies'", ":", "# Reserved for proxy configuration", "try", ":", "proxies", "=", "bark", ".", "proxy", ".", "ProxyConfig", "(", "sect_dict", ")", "except", "KeyError", "as", "exc", ":", "LOG", ".", "warn", "(", "\"Cannot configure proxy handling: option %s is \"", "\"missing from the proxy configuration\"", "%", "exc", ")", "continue", "# Pragma: nocover", "# First, determine the logging format", "try", ":", "format", "=", "bark", ".", "format", ".", "Format", ".", "parse", "(", "sect_dict", ".", "pop", "(", "'format'", ")", ")", "except", "KeyError", ":", "LOG", ".", "warn", "(", "\"No format specified for log %r; skipping.\"", "%", "sect", ")", "continue", "# Next, determine the handler type", "handle_type", "=", "sect_dict", ".", "pop", "(", "'type'", ",", "'file'", ")", "# Now, let's construct a handler; this will be a callable", "# taking the formatted message to log", "try", ":", "handler", "=", "bark", ".", "handlers", ".", "get_handler", "(", "handle_type", ",", "sect", ",", "sect_dict", ")", "except", "Exception", "as", "exc", ":", "LOG", ".", "warn", "(", "\"Cannot load handler of type %r for log %r: %s\"", "%", "(", "handle_type", ",", "sect", ",", "exc", ")", ")", "continue", "# We now have a handler and a format; bundle them up", "handlers", "[", "sect", "]", "=", "(", "format", ",", "handler", ")", "# Construct the wrapper which is going to instantiate the", "# middleware", "def", "wrapper", "(", "app", ")", ":", "return", "BarkMiddleware", "(", "app", ",", "handlers", ",", "proxies", ")", "return", "wrapper" ]
Factory function for Bark. Returns a function which, when passed the application, returns an instance of BarkMiddleware. :param global_conf: The global configuration, from the [DEFAULT] section of the PasteDeploy configuration file. :param local_conf: The local configuration, from the filter section of the PasteDeploy configuration file.
[ "Factory", "function", "for", "Bark", ".", "Returns", "a", "function", "which", "when", "passed", "the", "application", "returns", "an", "instance", "of", "BarkMiddleware", "." ]
6e0e002d55f01fee27e3e45bb86e30af1bfeef36
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/middleware.py#L29-L106
250,650
minhhoit/yacms
yacms/blog/views.py
blog_post_feed
def blog_post_feed(request, format, **kwargs): """ Blog posts feeds - maps format to the correct feed view. """ try: return {"rss": PostsRSS, "atom": PostsAtom}[format](**kwargs)(request) except KeyError: raise Http404()
python
def blog_post_feed(request, format, **kwargs): """ Blog posts feeds - maps format to the correct feed view. """ try: return {"rss": PostsRSS, "atom": PostsAtom}[format](**kwargs)(request) except KeyError: raise Http404()
[ "def", "blog_post_feed", "(", "request", ",", "format", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "{", "\"rss\"", ":", "PostsRSS", ",", "\"atom\"", ":", "PostsAtom", "}", "[", "format", "]", "(", "*", "*", "kwargs", ")", "(", "request", ")", "except", "KeyError", ":", "raise", "Http404", "(", ")" ]
Blog posts feeds - maps format to the correct feed view.
[ "Blog", "posts", "feeds", "-", "maps", "format", "to", "the", "correct", "feed", "view", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/views.py#L84-L91
250,651
florianpaquet/mease
mease/backends/rabbitmq.py
RabbitMQBackendMixin.connect
def connect(self): """ Connects to RabbitMQ """ self.connection = Connection(self.broker_url) e = Exchange('mease', type='fanout', durable=False, delivery_mode=1) self.exchange = e(self.connection.default_channel) self.exchange.declare()
python
def connect(self): """ Connects to RabbitMQ """ self.connection = Connection(self.broker_url) e = Exchange('mease', type='fanout', durable=False, delivery_mode=1) self.exchange = e(self.connection.default_channel) self.exchange.declare()
[ "def", "connect", "(", "self", ")", ":", "self", ".", "connection", "=", "Connection", "(", "self", ".", "broker_url", ")", "e", "=", "Exchange", "(", "'mease'", ",", "type", "=", "'fanout'", ",", "durable", "=", "False", ",", "delivery_mode", "=", "1", ")", "self", ".", "exchange", "=", "e", "(", "self", ".", "connection", ".", "default_channel", ")", "self", ".", "exchange", ".", "declare", "(", ")" ]
Connects to RabbitMQ
[ "Connects", "to", "RabbitMQ" ]
b9fbd08bbe162c8890c2a2124674371170c319ef
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/rabbitmq.py#L32-L40
250,652
florianpaquet/mease
mease/backends/rabbitmq.py
RabbitMQPublisher.publish
def publish(self, message_type, client_id, client_storage, *args, **kwargs): """ Publishes a message Uses `self.pack` instead of 'msgpack' serializer on kombu for backend consistency """ if self.connection.connected: message = self.exchange.Message( self.pack(message_type, client_id, client_storage, args, kwargs)) self.exchange.publish(message, routing_key='')
python
def publish(self, message_type, client_id, client_storage, *args, **kwargs): """ Publishes a message Uses `self.pack` instead of 'msgpack' serializer on kombu for backend consistency """ if self.connection.connected: message = self.exchange.Message( self.pack(message_type, client_id, client_storage, args, kwargs)) self.exchange.publish(message, routing_key='')
[ "def", "publish", "(", "self", ",", "message_type", ",", "client_id", ",", "client_storage", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "connection", ".", "connected", ":", "message", "=", "self", ".", "exchange", ".", "Message", "(", "self", ".", "pack", "(", "message_type", ",", "client_id", ",", "client_storage", ",", "args", ",", "kwargs", ")", ")", "self", ".", "exchange", ".", "publish", "(", "message", ",", "routing_key", "=", "''", ")" ]
Publishes a message Uses `self.pack` instead of 'msgpack' serializer on kombu for backend consistency
[ "Publishes", "a", "message", "Uses", "self", ".", "pack", "instead", "of", "msgpack", "serializer", "on", "kombu", "for", "backend", "consistency" ]
b9fbd08bbe162c8890c2a2124674371170c319ef
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/rabbitmq.py#L53-L61
250,653
florianpaquet/mease
mease/backends/rabbitmq.py
RabbitMQSubscriber.connect
def connect(self): """ Connects to RabbitMQ and starts listening """ logger.info("Connecting to RabbitMQ on {broker_url}...".format( broker_url=self.broker_url)) super(RabbitMQSubscriber, self).connect() q = Queue(exchange=self.exchange, exclusive=True, durable=False) self.queue = q(self.connection.default_channel) self.queue.declare() self.thread = Thread(target=self.listen) self.thread.setDaemon(True) self.thread.start()
python
def connect(self): """ Connects to RabbitMQ and starts listening """ logger.info("Connecting to RabbitMQ on {broker_url}...".format( broker_url=self.broker_url)) super(RabbitMQSubscriber, self).connect() q = Queue(exchange=self.exchange, exclusive=True, durable=False) self.queue = q(self.connection.default_channel) self.queue.declare() self.thread = Thread(target=self.listen) self.thread.setDaemon(True) self.thread.start()
[ "def", "connect", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Connecting to RabbitMQ on {broker_url}...\"", ".", "format", "(", "broker_url", "=", "self", ".", "broker_url", ")", ")", "super", "(", "RabbitMQSubscriber", ",", "self", ")", ".", "connect", "(", ")", "q", "=", "Queue", "(", "exchange", "=", "self", ".", "exchange", ",", "exclusive", "=", "True", ",", "durable", "=", "False", ")", "self", ".", "queue", "=", "q", "(", "self", ".", "connection", ".", "default_channel", ")", "self", ".", "queue", ".", "declare", "(", ")", "self", ".", "thread", "=", "Thread", "(", "target", "=", "self", ".", "listen", ")", "self", ".", "thread", ".", "setDaemon", "(", "True", ")", "self", ".", "thread", ".", "start", "(", ")" ]
Connects to RabbitMQ and starts listening
[ "Connects", "to", "RabbitMQ", "and", "starts", "listening" ]
b9fbd08bbe162c8890c2a2124674371170c319ef
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/rabbitmq.py#L68-L84
250,654
florianpaquet/mease
mease/backends/rabbitmq.py
RabbitMQSubscriber.listen
def listen(self): """ Listens to messages """ with Consumer(self.connection, queues=self.queue, on_message=self.on_message, auto_declare=False): for _ in eventloop(self.connection, timeout=1, ignore_timeouts=True): pass
python
def listen(self): """ Listens to messages """ with Consumer(self.connection, queues=self.queue, on_message=self.on_message, auto_declare=False): for _ in eventloop(self.connection, timeout=1, ignore_timeouts=True): pass
[ "def", "listen", "(", "self", ")", ":", "with", "Consumer", "(", "self", ".", "connection", ",", "queues", "=", "self", ".", "queue", ",", "on_message", "=", "self", ".", "on_message", ",", "auto_declare", "=", "False", ")", ":", "for", "_", "in", "eventloop", "(", "self", ".", "connection", ",", "timeout", "=", "1", ",", "ignore_timeouts", "=", "True", ")", ":", "pass" ]
Listens to messages
[ "Listens", "to", "messages" ]
b9fbd08bbe162c8890c2a2124674371170c319ef
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/rabbitmq.py#L86-L93
250,655
tbreitenfeldt/invisible_ui
invisible_ui/session.py
Session.main_loop
def main_loop(self): """Runs the main game loop.""" while True: for e in pygame.event.get(): self.handle_event(e) self.step() pygame.time.wait(5)
python
def main_loop(self): """Runs the main game loop.""" while True: for e in pygame.event.get(): self.handle_event(e) self.step() pygame.time.wait(5)
[ "def", "main_loop", "(", "self", ")", ":", "while", "True", ":", "for", "e", "in", "pygame", ".", "event", ".", "get", "(", ")", ":", "self", ".", "handle_event", "(", "e", ")", "self", ".", "step", "(", ")", "pygame", ".", "time", ".", "wait", "(", "5", ")" ]
Runs the main game loop.
[ "Runs", "the", "main", "game", "loop", "." ]
1a6907bfa61bded13fa9fb83ec7778c0df84487f
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/session.py#L48-L55
250,656
tbreitenfeldt/invisible_ui
invisible_ui/session.py
Session.quit
def quit(self, event): """Quit the game.""" self.logger.info("Quitting.") self.on_exit() sys.exit()
python
def quit(self, event): """Quit the game.""" self.logger.info("Quitting.") self.on_exit() sys.exit()
[ "def", "quit", "(", "self", ",", "event", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Quitting.\"", ")", "self", ".", "on_exit", "(", ")", "sys", ".", "exit", "(", ")" ]
Quit the game.
[ "Quit", "the", "game", "." ]
1a6907bfa61bded13fa9fb83ec7778c0df84487f
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/session.py#L84-L88
250,657
mqopen/mqreceive
mqreceive/broker.py
Broker.setCredentials
def setCredentials(self, user, password): """! Set authentication credentials. @param user Username. @param password Password. """ self._checkUserAndPass(user, password) self.user = user self.password = password
python
def setCredentials(self, user, password): """! Set authentication credentials. @param user Username. @param password Password. """ self._checkUserAndPass(user, password) self.user = user self.password = password
[ "def", "setCredentials", "(", "self", ",", "user", ",", "password", ")", ":", "self", ".", "_checkUserAndPass", "(", "user", ",", "password", ")", "self", ".", "user", "=", "user", "self", ".", "password", "=", "password" ]
! Set authentication credentials. @param user Username. @param password Password.
[ "!", "Set", "authentication", "credentials", "." ]
cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf
https://github.com/mqopen/mqreceive/blob/cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf/mqreceive/broker.py#L48-L57
250,658
espenak/django_seleniumhelpers
seleniumhelpers/seleniumhelpers.py
get_setting_with_envfallback
def get_setting_with_envfallback(setting, default=None, typecast=None): """ Get the given setting and fall back to the default of not found in ``django.conf.settings`` or ``os.environ``. :param settings: The setting as a string. :param default: The fallback if ``setting`` is not found. :param typecast: A function that converts the given value from string to another type. E.g.: Use ``typecast=int`` to convert the value to int before returning. """ try: from django.conf import settings except ImportError: return default else: fallback = getattr(settings, setting, default) value = os.environ.get(setting, fallback) if typecast: value = typecast(value) return value
python
def get_setting_with_envfallback(setting, default=None, typecast=None): """ Get the given setting and fall back to the default of not found in ``django.conf.settings`` or ``os.environ``. :param settings: The setting as a string. :param default: The fallback if ``setting`` is not found. :param typecast: A function that converts the given value from string to another type. E.g.: Use ``typecast=int`` to convert the value to int before returning. """ try: from django.conf import settings except ImportError: return default else: fallback = getattr(settings, setting, default) value = os.environ.get(setting, fallback) if typecast: value = typecast(value) return value
[ "def", "get_setting_with_envfallback", "(", "setting", ",", "default", "=", "None", ",", "typecast", "=", "None", ")", ":", "try", ":", "from", "django", ".", "conf", "import", "settings", "except", "ImportError", ":", "return", "default", "else", ":", "fallback", "=", "getattr", "(", "settings", ",", "setting", ",", "default", ")", "value", "=", "os", ".", "environ", ".", "get", "(", "setting", ",", "fallback", ")", "if", "typecast", ":", "value", "=", "typecast", "(", "value", ")", "return", "value" ]
Get the given setting and fall back to the default of not found in ``django.conf.settings`` or ``os.environ``. :param settings: The setting as a string. :param default: The fallback if ``setting`` is not found. :param typecast: A function that converts the given value from string to another type. E.g.: Use ``typecast=int`` to convert the value to int before returning.
[ "Get", "the", "given", "setting", "and", "fall", "back", "to", "the", "default", "of", "not", "found", "in", "django", ".", "conf", ".", "settings", "or", "os", ".", "environ", "." ]
c86781f2c89b850780945621c78fb6776da64f28
https://github.com/espenak/django_seleniumhelpers/blob/c86781f2c89b850780945621c78fb6776da64f28/seleniumhelpers/seleniumhelpers.py#L11-L31
250,659
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.add_file_locations
def add_file_locations(self, file_locations=[]): """ Adds a list of file locations to the current list Args: file_locations: list of file location tuples """ if not hasattr(self, '__file_locations__'): self.__file_locations__ = copy.copy(file_locations) else: self.__file_locations__ += copy.copy(file_locations)
python
def add_file_locations(self, file_locations=[]): """ Adds a list of file locations to the current list Args: file_locations: list of file location tuples """ if not hasattr(self, '__file_locations__'): self.__file_locations__ = copy.copy(file_locations) else: self.__file_locations__ += copy.copy(file_locations)
[ "def", "add_file_locations", "(", "self", ",", "file_locations", "=", "[", "]", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'__file_locations__'", ")", ":", "self", ".", "__file_locations__", "=", "copy", ".", "copy", "(", "file_locations", ")", "else", ":", "self", ".", "__file_locations__", "+=", "copy", ".", "copy", "(", "file_locations", ")" ]
Adds a list of file locations to the current list Args: file_locations: list of file location tuples
[ "Adds", "a", "list", "of", "file", "locations", "to", "the", "current", "list" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L50-L60
250,660
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.reset
def reset(self, **kwargs): """ Reset the triplestore with all of the data """ self.drop_all(**kwargs) file_locations = self.__file_locations__ self.__file_locations__ = [] self.load(file_locations, **kwargs)
python
def reset(self, **kwargs): """ Reset the triplestore with all of the data """ self.drop_all(**kwargs) file_locations = self.__file_locations__ self.__file_locations__ = [] self.load(file_locations, **kwargs)
[ "def", "reset", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "drop_all", "(", "*", "*", "kwargs", ")", "file_locations", "=", "self", ".", "__file_locations__", "self", ".", "__file_locations__", "=", "[", "]", "self", ".", "load", "(", "file_locations", ",", "*", "*", "kwargs", ")" ]
Reset the triplestore with all of the data
[ "Reset", "the", "triplestore", "with", "all", "of", "the", "data" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L63-L69
250,661
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.drop_all
def drop_all(self, **kwargs): """ Drops all definitions""" conn = self.__get_conn__(**kwargs) conn.update_query("DROP ALL") self.loaded = [] self.loaded_times = {}
python
def drop_all(self, **kwargs): """ Drops all definitions""" conn = self.__get_conn__(**kwargs) conn.update_query("DROP ALL") self.loaded = [] self.loaded_times = {}
[ "def", "drop_all", "(", "self", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "self", ".", "__get_conn__", "(", "*", "*", "kwargs", ")", "conn", ".", "update_query", "(", "\"DROP ALL\"", ")", "self", ".", "loaded", "=", "[", "]", "self", ".", "loaded_times", "=", "{", "}" ]
Drops all definitions
[ "Drops", "all", "definitions" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L76-L81
250,662
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.load_file
def load_file(self, filepath, **kwargs): """ loads a file into the defintion triplestore args: filepath: the path to the file """ log.setLevel(kwargs.get("log_level", self.log_level)) filename = os.path.split(filepath)[-1] if filename in self.loaded: if self.loaded_times.get(filename, datetime.datetime(2001,1,1)).timestamp() \ < os.path.getmtime(filepath): self.drop_file(filename, **kwargs) else: return conn = self.__get_conn__(**kwargs) conn.load_data(graph=getattr(__NSM__.kdr, filename).clean_uri, data=filepath, # log_level=logging.DEBUG, is_file=True) self.__update_time__(filename, **kwargs) log.warning("\n\tfile: '%s' loaded\n\tconn: '%s'\n\tpath: %s", filename, conn, filepath) self.loaded.append(filename)
python
def load_file(self, filepath, **kwargs): """ loads a file into the defintion triplestore args: filepath: the path to the file """ log.setLevel(kwargs.get("log_level", self.log_level)) filename = os.path.split(filepath)[-1] if filename in self.loaded: if self.loaded_times.get(filename, datetime.datetime(2001,1,1)).timestamp() \ < os.path.getmtime(filepath): self.drop_file(filename, **kwargs) else: return conn = self.__get_conn__(**kwargs) conn.load_data(graph=getattr(__NSM__.kdr, filename).clean_uri, data=filepath, # log_level=logging.DEBUG, is_file=True) self.__update_time__(filename, **kwargs) log.warning("\n\tfile: '%s' loaded\n\tconn: '%s'\n\tpath: %s", filename, conn, filepath) self.loaded.append(filename)
[ "def", "load_file", "(", "self", ",", "filepath", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "\"log_level\"", ",", "self", ".", "log_level", ")", ")", "filename", "=", "os", ".", "path", ".", "split", "(", "filepath", ")", "[", "-", "1", "]", "if", "filename", "in", "self", ".", "loaded", ":", "if", "self", ".", "loaded_times", ".", "get", "(", "filename", ",", "datetime", ".", "datetime", "(", "2001", ",", "1", ",", "1", ")", ")", ".", "timestamp", "(", ")", "<", "os", ".", "path", ".", "getmtime", "(", "filepath", ")", ":", "self", ".", "drop_file", "(", "filename", ",", "*", "*", "kwargs", ")", "else", ":", "return", "conn", "=", "self", ".", "__get_conn__", "(", "*", "*", "kwargs", ")", "conn", ".", "load_data", "(", "graph", "=", "getattr", "(", "__NSM__", ".", "kdr", ",", "filename", ")", ".", "clean_uri", ",", "data", "=", "filepath", ",", "# log_level=logging.DEBUG,", "is_file", "=", "True", ")", "self", ".", "__update_time__", "(", "filename", ",", "*", "*", "kwargs", ")", "log", ".", "warning", "(", "\"\\n\\tfile: '%s' loaded\\n\\tconn: '%s'\\n\\tpath: %s\"", ",", "filename", ",", "conn", ",", "filepath", ")", "self", ".", "loaded", ".", "append", "(", "filename", ")" ]
loads a file into the defintion triplestore args: filepath: the path to the file
[ "loads", "a", "file", "into", "the", "defintion", "triplestore" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L165-L190
250,663
KnowledgeLinks/rdfframework
rdfframework/datamanager/datamanager.py
DataFileManager.load_directory
def load_directory(self, directory, **kwargs): """ loads all rdf files in a directory args: directory: full path to the directory """ log.setLevel(kwargs.get("log_level", self.log_level)) conn = self.__get_conn__(**kwargs) file_extensions = kwargs.get('file_extensions', conn.rdf_formats) file_list = list_files(directory, file_extensions, kwargs.get('include_subfolders', False), include_root=True) for file in file_list: self.load_file(file[1], **kwargs) log.setLevel(self.log_level)
python
def load_directory(self, directory, **kwargs): """ loads all rdf files in a directory args: directory: full path to the directory """ log.setLevel(kwargs.get("log_level", self.log_level)) conn = self.__get_conn__(**kwargs) file_extensions = kwargs.get('file_extensions', conn.rdf_formats) file_list = list_files(directory, file_extensions, kwargs.get('include_subfolders', False), include_root=True) for file in file_list: self.load_file(file[1], **kwargs) log.setLevel(self.log_level)
[ "def", "load_directory", "(", "self", ",", "directory", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "\"log_level\"", ",", "self", ".", "log_level", ")", ")", "conn", "=", "self", ".", "__get_conn__", "(", "*", "*", "kwargs", ")", "file_extensions", "=", "kwargs", ".", "get", "(", "'file_extensions'", ",", "conn", ".", "rdf_formats", ")", "file_list", "=", "list_files", "(", "directory", ",", "file_extensions", ",", "kwargs", ".", "get", "(", "'include_subfolders'", ",", "False", ")", ",", "include_root", "=", "True", ")", "for", "file", "in", "file_list", ":", "self", ".", "load_file", "(", "file", "[", "1", "]", ",", "*", "*", "kwargs", ")", "log", ".", "setLevel", "(", "self", ".", "log_level", ")" ]
loads all rdf files in a directory args: directory: full path to the directory
[ "loads", "all", "rdf", "files", "in", "a", "directory" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamanager/datamanager.py#L279-L294
250,664
abalkin/tz
tz/tzfile.py
read
def read(fileobj, version=None): """Read tz data from a binary file. @param fileobj: @param version: @return: TZFileData """ magic = fileobj.read(5) if magic[:4] != b"TZif": raise ValueError("not a zoneinfo file") if version is None: version = int(magic[4:]) if magic[4] else 0 fileobj.seek(20) # Read the counts: # [0] - The number of UT/local indicators stored in the file. # [1] - The number of standard/wall indicators stored in the file. # [2] - The number of leap seconds for which data entries are stored # in the file. # [3] - The number of transition times for which data entries are # stored in the file. # [4] - The number of local time types for which data entries are # stored in the file (must not be zero). # [5] - The number of characters of time zone abbreviation strings # stored in the file. (ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt) = _read_counts(fileobj) if version >= 2: # Skip to the counts in the second header. data_size = (5 * timecnt + 6 * typecnt + charcnt + 8 * leapcnt + ttisstdcnt + ttisgmtcnt) fileobj.seek(data_size + 20, os.SEEK_CUR) # Re-read the counts. (ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt) = _read_counts(fileobj) ttfmt = 'q' else: ttfmt = 'i' times = array(ttfmt) times.fromfile(fileobj, timecnt) if sys.byteorder != 'big': times.byteswap() type_indices = array('B') type_indices.fromfile(fileobj, timecnt) # Read local time types. type_infos = [] for i in range(typecnt): type_infos.append(struct.unpack(">iBB", fileobj.read(6))) abbrs = fileobj.read(charcnt) if version > 0: # Skip to POSIX TZ string fileobj.seek(12 * leapcnt + ttisstdcnt + ttisgmtcnt, os.SEEK_CUR) posix_string = fileobj.read().strip().decode('ascii') else: posix_string = None # Convert type_infos for i, (gmtoff, isdst, abbrind) in enumerate(type_infos): abbr = abbrs[abbrind:abbrs.find(0, abbrind)].decode() type_infos[i] = (gmtoff, isdst, abbr) return TZFileData(version, type_infos, times, type_indices, posix_string)
python
def read(fileobj, version=None): """Read tz data from a binary file. @param fileobj: @param version: @return: TZFileData """ magic = fileobj.read(5) if magic[:4] != b"TZif": raise ValueError("not a zoneinfo file") if version is None: version = int(magic[4:]) if magic[4] else 0 fileobj.seek(20) # Read the counts: # [0] - The number of UT/local indicators stored in the file. # [1] - The number of standard/wall indicators stored in the file. # [2] - The number of leap seconds for which data entries are stored # in the file. # [3] - The number of transition times for which data entries are # stored in the file. # [4] - The number of local time types for which data entries are # stored in the file (must not be zero). # [5] - The number of characters of time zone abbreviation strings # stored in the file. (ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt) = _read_counts(fileobj) if version >= 2: # Skip to the counts in the second header. data_size = (5 * timecnt + 6 * typecnt + charcnt + 8 * leapcnt + ttisstdcnt + ttisgmtcnt) fileobj.seek(data_size + 20, os.SEEK_CUR) # Re-read the counts. (ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt) = _read_counts(fileobj) ttfmt = 'q' else: ttfmt = 'i' times = array(ttfmt) times.fromfile(fileobj, timecnt) if sys.byteorder != 'big': times.byteswap() type_indices = array('B') type_indices.fromfile(fileobj, timecnt) # Read local time types. type_infos = [] for i in range(typecnt): type_infos.append(struct.unpack(">iBB", fileobj.read(6))) abbrs = fileobj.read(charcnt) if version > 0: # Skip to POSIX TZ string fileobj.seek(12 * leapcnt + ttisstdcnt + ttisgmtcnt, os.SEEK_CUR) posix_string = fileobj.read().strip().decode('ascii') else: posix_string = None # Convert type_infos for i, (gmtoff, isdst, abbrind) in enumerate(type_infos): abbr = abbrs[abbrind:abbrs.find(0, abbrind)].decode() type_infos[i] = (gmtoff, isdst, abbr) return TZFileData(version, type_infos, times, type_indices, posix_string)
[ "def", "read", "(", "fileobj", ",", "version", "=", "None", ")", ":", "magic", "=", "fileobj", ".", "read", "(", "5", ")", "if", "magic", "[", ":", "4", "]", "!=", "b\"TZif\"", ":", "raise", "ValueError", "(", "\"not a zoneinfo file\"", ")", "if", "version", "is", "None", ":", "version", "=", "int", "(", "magic", "[", "4", ":", "]", ")", "if", "magic", "[", "4", "]", "else", "0", "fileobj", ".", "seek", "(", "20", ")", "# Read the counts:", "# [0] - The number of UT/local indicators stored in the file.", "# [1] - The number of standard/wall indicators stored in the file.", "# [2] - The number of leap seconds for which data entries are stored", "# in the file.", "# [3] - The number of transition times for which data entries are", "# stored in the file.", "# [4] - The number of local time types for which data entries are", "# stored in the file (must not be zero).", "# [5] - The number of characters of time zone abbreviation strings", "# stored in the file.", "(", "ttisgmtcnt", ",", "ttisstdcnt", ",", "leapcnt", ",", "timecnt", ",", "typecnt", ",", "charcnt", ")", "=", "_read_counts", "(", "fileobj", ")", "if", "version", ">=", "2", ":", "# Skip to the counts in the second header.", "data_size", "=", "(", "5", "*", "timecnt", "+", "6", "*", "typecnt", "+", "charcnt", "+", "8", "*", "leapcnt", "+", "ttisstdcnt", "+", "ttisgmtcnt", ")", "fileobj", ".", "seek", "(", "data_size", "+", "20", ",", "os", ".", "SEEK_CUR", ")", "# Re-read the counts.", "(", "ttisgmtcnt", ",", "ttisstdcnt", ",", "leapcnt", ",", "timecnt", ",", "typecnt", ",", "charcnt", ")", "=", "_read_counts", "(", "fileobj", ")", "ttfmt", "=", "'q'", "else", ":", "ttfmt", "=", "'i'", "times", "=", "array", "(", "ttfmt", ")", "times", ".", "fromfile", "(", "fileobj", ",", "timecnt", ")", "if", "sys", ".", "byteorder", "!=", "'big'", ":", "times", ".", "byteswap", "(", ")", "type_indices", "=", "array", "(", "'B'", ")", "type_indices", ".", "fromfile", "(", "fileobj", ",", "timecnt", ")", "# Read local time types.", "type_infos", "=", "[", "]", "for", "i", "in", "range", "(", "typecnt", ")", ":", "type_infos", ".", "append", "(", "struct", ".", "unpack", "(", "\">iBB\"", ",", "fileobj", ".", "read", "(", "6", ")", ")", ")", "abbrs", "=", "fileobj", ".", "read", "(", "charcnt", ")", "if", "version", ">", "0", ":", "# Skip to POSIX TZ string", "fileobj", ".", "seek", "(", "12", "*", "leapcnt", "+", "ttisstdcnt", "+", "ttisgmtcnt", ",", "os", ".", "SEEK_CUR", ")", "posix_string", "=", "fileobj", ".", "read", "(", ")", ".", "strip", "(", ")", ".", "decode", "(", "'ascii'", ")", "else", ":", "posix_string", "=", "None", "# Convert type_infos", "for", "i", ",", "(", "gmtoff", ",", "isdst", ",", "abbrind", ")", "in", "enumerate", "(", "type_infos", ")", ":", "abbr", "=", "abbrs", "[", "abbrind", ":", "abbrs", ".", "find", "(", "0", ",", "abbrind", ")", "]", ".", "decode", "(", ")", "type_infos", "[", "i", "]", "=", "(", "gmtoff", ",", "isdst", ",", "abbr", ")", "return", "TZFileData", "(", "version", ",", "type_infos", ",", "times", ",", "type_indices", ",", "posix_string", ")" ]
Read tz data from a binary file. @param fileobj: @param version: @return: TZFileData
[ "Read", "tz", "data", "from", "a", "binary", "file", "." ]
f25fca6afbf1abd46fd7aeb978282823c7dab5ab
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/tz/tzfile.py#L31-L101
250,665
openpermissions/chub
chub/handlers.py
convert
def convert(data): """ convert a standalone unicode string or unicode strings in a mapping or iterable into byte strings. """ if isinstance(data, unicode): return data.encode('utf-8') elif isinstance(data, str): return data elif isinstance(data, collections.Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, collections.Iterable): return type(data)(map(convert, data)) else: return data
python
def convert(data): """ convert a standalone unicode string or unicode strings in a mapping or iterable into byte strings. """ if isinstance(data, unicode): return data.encode('utf-8') elif isinstance(data, str): return data elif isinstance(data, collections.Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, collections.Iterable): return type(data)(map(convert, data)) else: return data
[ "def", "convert", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "unicode", ")", ":", "return", "data", ".", "encode", "(", "'utf-8'", ")", "elif", "isinstance", "(", "data", ",", "str", ")", ":", "return", "data", "elif", "isinstance", "(", "data", ",", "collections", ".", "Mapping", ")", ":", "return", "dict", "(", "map", "(", "convert", ",", "data", ".", "iteritems", "(", ")", ")", ")", "elif", "isinstance", "(", "data", ",", "collections", ".", "Iterable", ")", ":", "return", "type", "(", "data", ")", "(", "map", "(", "convert", ",", "data", ")", ")", "else", ":", "return", "data" ]
convert a standalone unicode string or unicode strings in a mapping or iterable into byte strings.
[ "convert", "a", "standalone", "unicode", "string", "or", "unicode", "strings", "in", "a", "mapping", "or", "iterable", "into", "byte", "strings", "." ]
00762aa17015f4b3010673d1570c708eab3c34ed
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/handlers.py#L26-L40
250,666
openpermissions/chub
chub/handlers.py
make_fetch_func
def make_fetch_func(base_url, async, **kwargs): """ make a fetch function based on conditions of 1) async 2) ssl """ if async: client = AsyncHTTPClient(force_instance=True, defaults=kwargs) return partial(async_fetch, httpclient=client) else: client = HTTPClient(force_instance=True, defaults=kwargs) return partial(sync_fetch, httpclient=client)
python
def make_fetch_func(base_url, async, **kwargs): """ make a fetch function based on conditions of 1) async 2) ssl """ if async: client = AsyncHTTPClient(force_instance=True, defaults=kwargs) return partial(async_fetch, httpclient=client) else: client = HTTPClient(force_instance=True, defaults=kwargs) return partial(sync_fetch, httpclient=client)
[ "def", "make_fetch_func", "(", "base_url", ",", "async", ",", "*", "*", "kwargs", ")", ":", "if", "async", ":", "client", "=", "AsyncHTTPClient", "(", "force_instance", "=", "True", ",", "defaults", "=", "kwargs", ")", "return", "partial", "(", "async_fetch", ",", "httpclient", "=", "client", ")", "else", ":", "client", "=", "HTTPClient", "(", "force_instance", "=", "True", ",", "defaults", "=", "kwargs", ")", "return", "partial", "(", "sync_fetch", ",", "httpclient", "=", "client", ")" ]
make a fetch function based on conditions of 1) async 2) ssl
[ "make", "a", "fetch", "function", "based", "on", "conditions", "of", "1", ")", "async", "2", ")", "ssl" ]
00762aa17015f4b3010673d1570c708eab3c34ed
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/handlers.py#L137-L148
250,667
racker/python-twisted-keystone-agent
txKeystone/keystone.py
KeystoneAgent._getAuthHeaders
def _getAuthHeaders(self): """ Get authentication headers. If we have valid header data already, they immediately return it. If not, then get new authentication data. If we are currently in the process of getting the header data, put this request into a queue to be handled when the data are received. @returns: A deferred that will eventually be called back with the header data """ def _handleAuthBody(body): self.msg("_handleAuthBody: %(body)s", body=body) try: body_parsed = json.loads(body) access_token = body_parsed['access']['token'] tenant_id = access_token['tenant']['id'].encode('ascii') auth_token = access_token['id'].encode('ascii') self.auth_headers["X-Tenant-Id"] = tenant_id self.auth_headers["X-Auth-Token"] = auth_token self._state = self.AUTHENTICATED self.msg("_handleAuthHeaders: found token %(token)s" " tenant id %(tenant_id)s", token=self.auth_headers["X-Auth-Token"], tenant_id=self.auth_headers["X-Tenant-Id"]) # Callback all queued auth headers requests while not self._headers_requests.empty(): self._headers_requests.get().callback(self.auth_headers) except ValueError: # We received a bad response return fail(MalformedJSONError("Malformed keystone" " response received.")) def _handleAuthResponse(response): if response.code == httplib.OK: self.msg("_handleAuthResponse: %(response)s accepted", response=response) body = Deferred() response.deliverBody(StringIOReceiver(body)) body.addCallback(_handleAuthBody) return body else: self.msg("_handleAuthResponse: %(response)s rejected", response=response) return fail( KeystoneAuthenticationError("Keystone" " authentication credentials" " rejected")) self.msg("_getAuthHeaders: state is %(state)s", state=self._state) if self._state == self.AUTHENTICATED: # We are authenticated, immediately succeed with the current # auth headers self.msg("_getAuthHeaders: succeed with %(headers)s", headers=self.auth_headers) return succeed(self.auth_headers) elif (self._state == self.NOT_AUTHENTICATED or self._state == self.AUTHENTICATING): # We cannot satisfy the auth header request immediately, # put it in a queue self.msg("_getAuthHeaders: defer, place in queue") auth_headers_deferred = Deferred() self._headers_requests.put(auth_headers_deferred) if self._state == self.NOT_AUTHENTICATED: self.msg("_getAuthHeaders: not authenticated, start" " authentication process") # We are not authenticated, and not in the process of # authenticating. # Set our state to AUTHENTICATING and begin the # authentication process self._state = self.AUTHENTICATING d = self.agent.request('POST', self.auth_url, Headers({ "Content-type": ["application/json"] }), self._getAuthRequestBodyProducer()) d.addCallback(_handleAuthResponse) d.addErrback(auth_headers_deferred.errback) return auth_headers_deferred else: # Bad state, fail return fail(RuntimeError("Invalid state encountered."))
python
def _getAuthHeaders(self): """ Get authentication headers. If we have valid header data already, they immediately return it. If not, then get new authentication data. If we are currently in the process of getting the header data, put this request into a queue to be handled when the data are received. @returns: A deferred that will eventually be called back with the header data """ def _handleAuthBody(body): self.msg("_handleAuthBody: %(body)s", body=body) try: body_parsed = json.loads(body) access_token = body_parsed['access']['token'] tenant_id = access_token['tenant']['id'].encode('ascii') auth_token = access_token['id'].encode('ascii') self.auth_headers["X-Tenant-Id"] = tenant_id self.auth_headers["X-Auth-Token"] = auth_token self._state = self.AUTHENTICATED self.msg("_handleAuthHeaders: found token %(token)s" " tenant id %(tenant_id)s", token=self.auth_headers["X-Auth-Token"], tenant_id=self.auth_headers["X-Tenant-Id"]) # Callback all queued auth headers requests while not self._headers_requests.empty(): self._headers_requests.get().callback(self.auth_headers) except ValueError: # We received a bad response return fail(MalformedJSONError("Malformed keystone" " response received.")) def _handleAuthResponse(response): if response.code == httplib.OK: self.msg("_handleAuthResponse: %(response)s accepted", response=response) body = Deferred() response.deliverBody(StringIOReceiver(body)) body.addCallback(_handleAuthBody) return body else: self.msg("_handleAuthResponse: %(response)s rejected", response=response) return fail( KeystoneAuthenticationError("Keystone" " authentication credentials" " rejected")) self.msg("_getAuthHeaders: state is %(state)s", state=self._state) if self._state == self.AUTHENTICATED: # We are authenticated, immediately succeed with the current # auth headers self.msg("_getAuthHeaders: succeed with %(headers)s", headers=self.auth_headers) return succeed(self.auth_headers) elif (self._state == self.NOT_AUTHENTICATED or self._state == self.AUTHENTICATING): # We cannot satisfy the auth header request immediately, # put it in a queue self.msg("_getAuthHeaders: defer, place in queue") auth_headers_deferred = Deferred() self._headers_requests.put(auth_headers_deferred) if self._state == self.NOT_AUTHENTICATED: self.msg("_getAuthHeaders: not authenticated, start" " authentication process") # We are not authenticated, and not in the process of # authenticating. # Set our state to AUTHENTICATING and begin the # authentication process self._state = self.AUTHENTICATING d = self.agent.request('POST', self.auth_url, Headers({ "Content-type": ["application/json"] }), self._getAuthRequestBodyProducer()) d.addCallback(_handleAuthResponse) d.addErrback(auth_headers_deferred.errback) return auth_headers_deferred else: # Bad state, fail return fail(RuntimeError("Invalid state encountered."))
[ "def", "_getAuthHeaders", "(", "self", ")", ":", "def", "_handleAuthBody", "(", "body", ")", ":", "self", ".", "msg", "(", "\"_handleAuthBody: %(body)s\"", ",", "body", "=", "body", ")", "try", ":", "body_parsed", "=", "json", ".", "loads", "(", "body", ")", "access_token", "=", "body_parsed", "[", "'access'", "]", "[", "'token'", "]", "tenant_id", "=", "access_token", "[", "'tenant'", "]", "[", "'id'", "]", ".", "encode", "(", "'ascii'", ")", "auth_token", "=", "access_token", "[", "'id'", "]", ".", "encode", "(", "'ascii'", ")", "self", ".", "auth_headers", "[", "\"X-Tenant-Id\"", "]", "=", "tenant_id", "self", ".", "auth_headers", "[", "\"X-Auth-Token\"", "]", "=", "auth_token", "self", ".", "_state", "=", "self", ".", "AUTHENTICATED", "self", ".", "msg", "(", "\"_handleAuthHeaders: found token %(token)s\"", "\" tenant id %(tenant_id)s\"", ",", "token", "=", "self", ".", "auth_headers", "[", "\"X-Auth-Token\"", "]", ",", "tenant_id", "=", "self", ".", "auth_headers", "[", "\"X-Tenant-Id\"", "]", ")", "# Callback all queued auth headers requests", "while", "not", "self", ".", "_headers_requests", ".", "empty", "(", ")", ":", "self", ".", "_headers_requests", ".", "get", "(", ")", ".", "callback", "(", "self", ".", "auth_headers", ")", "except", "ValueError", ":", "# We received a bad response", "return", "fail", "(", "MalformedJSONError", "(", "\"Malformed keystone\"", "\" response received.\"", ")", ")", "def", "_handleAuthResponse", "(", "response", ")", ":", "if", "response", ".", "code", "==", "httplib", ".", "OK", ":", "self", ".", "msg", "(", "\"_handleAuthResponse: %(response)s accepted\"", ",", "response", "=", "response", ")", "body", "=", "Deferred", "(", ")", "response", ".", "deliverBody", "(", "StringIOReceiver", "(", "body", ")", ")", "body", ".", "addCallback", "(", "_handleAuthBody", ")", "return", "body", "else", ":", "self", ".", "msg", "(", "\"_handleAuthResponse: %(response)s rejected\"", ",", "response", "=", "response", ")", "return", "fail", "(", "KeystoneAuthenticationError", "(", "\"Keystone\"", "\" authentication credentials\"", "\" rejected\"", ")", ")", "self", ".", "msg", "(", "\"_getAuthHeaders: state is %(state)s\"", ",", "state", "=", "self", ".", "_state", ")", "if", "self", ".", "_state", "==", "self", ".", "AUTHENTICATED", ":", "# We are authenticated, immediately succeed with the current", "# auth headers", "self", ".", "msg", "(", "\"_getAuthHeaders: succeed with %(headers)s\"", ",", "headers", "=", "self", ".", "auth_headers", ")", "return", "succeed", "(", "self", ".", "auth_headers", ")", "elif", "(", "self", ".", "_state", "==", "self", ".", "NOT_AUTHENTICATED", "or", "self", ".", "_state", "==", "self", ".", "AUTHENTICATING", ")", ":", "# We cannot satisfy the auth header request immediately,", "# put it in a queue", "self", ".", "msg", "(", "\"_getAuthHeaders: defer, place in queue\"", ")", "auth_headers_deferred", "=", "Deferred", "(", ")", "self", ".", "_headers_requests", ".", "put", "(", "auth_headers_deferred", ")", "if", "self", ".", "_state", "==", "self", ".", "NOT_AUTHENTICATED", ":", "self", ".", "msg", "(", "\"_getAuthHeaders: not authenticated, start\"", "\" authentication process\"", ")", "# We are not authenticated, and not in the process of", "# authenticating.", "# Set our state to AUTHENTICATING and begin the", "# authentication process", "self", ".", "_state", "=", "self", ".", "AUTHENTICATING", "d", "=", "self", ".", "agent", ".", "request", "(", "'POST'", ",", "self", ".", "auth_url", ",", "Headers", "(", "{", "\"Content-type\"", ":", "[", "\"application/json\"", "]", "}", ")", ",", "self", ".", "_getAuthRequestBodyProducer", "(", ")", ")", "d", ".", "addCallback", "(", "_handleAuthResponse", ")", "d", ".", "addErrback", "(", "auth_headers_deferred", ".", "errback", ")", "return", "auth_headers_deferred", "else", ":", "# Bad state, fail", "return", "fail", "(", "RuntimeError", "(", "\"Invalid state encountered.\"", ")", ")" ]
Get authentication headers. If we have valid header data already, they immediately return it. If not, then get new authentication data. If we are currently in the process of getting the header data, put this request into a queue to be handled when the data are received. @returns: A deferred that will eventually be called back with the header data
[ "Get", "authentication", "headers", ".", "If", "we", "have", "valid", "header", "data", "already", "they", "immediately", "return", "it", ".", "If", "not", "then", "get", "new", "authentication", "data", ".", "If", "we", "are", "currently", "in", "the", "process", "of", "getting", "the", "header", "data", "put", "this", "request", "into", "a", "queue", "to", "be", "handled", "when", "the", "data", "are", "received", "." ]
8b245bc51cc4a4512550cd64e6f1007379ca1466
https://github.com/racker/python-twisted-keystone-agent/blob/8b245bc51cc4a4512550cd64e6f1007379ca1466/txKeystone/keystone.py#L166-L261
250,668
tagcubeio/tagcube-cli
tagcube_cli/main.py
main
def main(): """ Project's main method which will parse the command line arguments, run a scan using the TagCubeClient and exit. """ cmd_args = TagCubeCLI.parse_args() try: tagcube_cli = TagCubeCLI.from_cmd_args(cmd_args) except ValueError, ve: # We get here when there are no credentials configured print '%s' % ve sys.exit(1) try: sys.exit(tagcube_cli.run()) except ValueError, ve: # We get here when the configured credentials had some issue (invalid) # or there was some error (such as invalid profile name) with the params print '%s' % ve sys.exit(2)
python
def main(): """ Project's main method which will parse the command line arguments, run a scan using the TagCubeClient and exit. """ cmd_args = TagCubeCLI.parse_args() try: tagcube_cli = TagCubeCLI.from_cmd_args(cmd_args) except ValueError, ve: # We get here when there are no credentials configured print '%s' % ve sys.exit(1) try: sys.exit(tagcube_cli.run()) except ValueError, ve: # We get here when the configured credentials had some issue (invalid) # or there was some error (such as invalid profile name) with the params print '%s' % ve sys.exit(2)
[ "def", "main", "(", ")", ":", "cmd_args", "=", "TagCubeCLI", ".", "parse_args", "(", ")", "try", ":", "tagcube_cli", "=", "TagCubeCLI", ".", "from_cmd_args", "(", "cmd_args", ")", "except", "ValueError", ",", "ve", ":", "# We get here when there are no credentials configured", "print", "'%s'", "%", "ve", "sys", ".", "exit", "(", "1", ")", "try", ":", "sys", ".", "exit", "(", "tagcube_cli", ".", "run", "(", ")", ")", "except", "ValueError", ",", "ve", ":", "# We get here when the configured credentials had some issue (invalid)", "# or there was some error (such as invalid profile name) with the params", "print", "'%s'", "%", "ve", "sys", ".", "exit", "(", "2", ")" ]
Project's main method which will parse the command line arguments, run a scan using the TagCubeClient and exit.
[ "Project", "s", "main", "method", "which", "will", "parse", "the", "command", "line", "arguments", "run", "a", "scan", "using", "the", "TagCubeClient", "and", "exit", "." ]
709e4b0b11331a4d2791dc79107e5081518d75bf
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/main.py#L6-L26
250,669
jenanwise/codequality
codequality/checkers.py
register
def register(filetypes): """ Decorator to register a class as a checker for extensions. """ def decorator(clazz): for ext in filetypes: checkers.setdefault(ext, []).append(clazz) return clazz return decorator
python
def register(filetypes): """ Decorator to register a class as a checker for extensions. """ def decorator(clazz): for ext in filetypes: checkers.setdefault(ext, []).append(clazz) return clazz return decorator
[ "def", "register", "(", "filetypes", ")", ":", "def", "decorator", "(", "clazz", ")", ":", "for", "ext", "in", "filetypes", ":", "checkers", ".", "setdefault", "(", "ext", ",", "[", "]", ")", ".", "append", "(", "clazz", ")", "return", "clazz", "return", "decorator" ]
Decorator to register a class as a checker for extensions.
[ "Decorator", "to", "register", "a", "class", "as", "a", "checker", "for", "extensions", "." ]
8a2bd767fd73091c49a5318fdbfb2b4fff77533d
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/checkers.py#L11-L19
250,670
jenanwise/codequality
codequality/checkers.py
Checker.check
def check(self, paths): """ Return list of error dicts for all found errors in paths. The default implementation expects `tool`, and `tool_err_re` to be defined. tool: external binary to use for checking. tool_err_re: regexp that can match output of `tool` -- must provide a groupdict with at least "filename", "lineno", "colno", and "msg" keys. See example checkers. """ if not paths: return () cmd_pieces = [self.tool] cmd_pieces.extend(self.tool_args) return self._check_std(paths, cmd_pieces)
python
def check(self, paths): """ Return list of error dicts for all found errors in paths. The default implementation expects `tool`, and `tool_err_re` to be defined. tool: external binary to use for checking. tool_err_re: regexp that can match output of `tool` -- must provide a groupdict with at least "filename", "lineno", "colno", and "msg" keys. See example checkers. """ if not paths: return () cmd_pieces = [self.tool] cmd_pieces.extend(self.tool_args) return self._check_std(paths, cmd_pieces)
[ "def", "check", "(", "self", ",", "paths", ")", ":", "if", "not", "paths", ":", "return", "(", ")", "cmd_pieces", "=", "[", "self", ".", "tool", "]", "cmd_pieces", ".", "extend", "(", "self", ".", "tool_args", ")", "return", "self", ".", "_check_std", "(", "paths", ",", "cmd_pieces", ")" ]
Return list of error dicts for all found errors in paths. The default implementation expects `tool`, and `tool_err_re` to be defined. tool: external binary to use for checking. tool_err_re: regexp that can match output of `tool` -- must provide a groupdict with at least "filename", "lineno", "colno", and "msg" keys. See example checkers.
[ "Return", "list", "of", "error", "dicts", "for", "all", "found", "errors", "in", "paths", "." ]
8a2bd767fd73091c49a5318fdbfb2b4fff77533d
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/checkers.py#L40-L57
250,671
jenanwise/codequality
codequality/checkers.py
Checker.get_version
def get_version(cls): """ Return the version number of the tool. """ cmd_pieces = [cls.tool, '--version'] process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() if err: return '' else: return out.splitlines()[0].strip()
python
def get_version(cls): """ Return the version number of the tool. """ cmd_pieces = [cls.tool, '--version'] process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() if err: return '' else: return out.splitlines()[0].strip()
[ "def", "get_version", "(", "cls", ")", ":", "cmd_pieces", "=", "[", "cls", ".", "tool", ",", "'--version'", "]", "process", "=", "Popen", "(", "cmd_pieces", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "out", ",", "err", "=", "process", ".", "communicate", "(", ")", "if", "err", ":", "return", "''", "else", ":", "return", "out", ".", "splitlines", "(", ")", "[", "0", "]", ".", "strip", "(", ")" ]
Return the version number of the tool.
[ "Return", "the", "version", "number", "of", "the", "tool", "." ]
8a2bd767fd73091c49a5318fdbfb2b4fff77533d
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/checkers.py#L60-L70
250,672
jenanwise/codequality
codequality/checkers.py
Checker._check_std
def _check_std(self, paths, cmd_pieces): """ Run `cmd` as a check on `paths`. """ cmd_pieces.extend(paths) process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() lines = out.strip().splitlines() + err.strip().splitlines() result = [] for line in lines: match = self.tool_err_re.match(line) if not match: if self.break_on_tool_re_mismatch: raise ValueError( 'Unexpected `%s` output: %r' % ( ' '.join(cmd_pieces), paths, line)) continue vals = match.groupdict() # All tools should at least give us line numbers, but only # some give column numbers. vals['lineno'] = int(vals['lineno']) vals['colno'] = \ int(vals['colno']) if vals['colno'] is not None else '' result.append(vals) return result
python
def _check_std(self, paths, cmd_pieces): """ Run `cmd` as a check on `paths`. """ cmd_pieces.extend(paths) process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() lines = out.strip().splitlines() + err.strip().splitlines() result = [] for line in lines: match = self.tool_err_re.match(line) if not match: if self.break_on_tool_re_mismatch: raise ValueError( 'Unexpected `%s` output: %r' % ( ' '.join(cmd_pieces), paths, line)) continue vals = match.groupdict() # All tools should at least give us line numbers, but only # some give column numbers. vals['lineno'] = int(vals['lineno']) vals['colno'] = \ int(vals['colno']) if vals['colno'] is not None else '' result.append(vals) return result
[ "def", "_check_std", "(", "self", ",", "paths", ",", "cmd_pieces", ")", ":", "cmd_pieces", ".", "extend", "(", "paths", ")", "process", "=", "Popen", "(", "cmd_pieces", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "out", ",", "err", "=", "process", ".", "communicate", "(", ")", "lines", "=", "out", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "+", "err", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "result", "=", "[", "]", "for", "line", "in", "lines", ":", "match", "=", "self", ".", "tool_err_re", ".", "match", "(", "line", ")", "if", "not", "match", ":", "if", "self", ".", "break_on_tool_re_mismatch", ":", "raise", "ValueError", "(", "'Unexpected `%s` output: %r'", "%", "(", "' '", ".", "join", "(", "cmd_pieces", ")", ",", "paths", ",", "line", ")", ")", "continue", "vals", "=", "match", ".", "groupdict", "(", ")", "# All tools should at least give us line numbers, but only", "# some give column numbers.", "vals", "[", "'lineno'", "]", "=", "int", "(", "vals", "[", "'lineno'", "]", ")", "vals", "[", "'colno'", "]", "=", "int", "(", "vals", "[", "'colno'", "]", ")", "if", "vals", "[", "'colno'", "]", "is", "not", "None", "else", "''", "result", ".", "append", "(", "vals", ")", "return", "result" ]
Run `cmd` as a check on `paths`.
[ "Run", "cmd", "as", "a", "check", "on", "paths", "." ]
8a2bd767fd73091c49a5318fdbfb2b4fff77533d
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/checkers.py#L74-L102
250,673
AguaClara/aide_document-DEPRECATED
aide_document/translate.py
replace
def replace(dict,line): """ Find and replace the special words according to the dictionary. Parameters ========== dict : Dictionary A dictionary derived from a yaml file. Source language as keys and the target language as values. line : String A string need to be processed. """ words = line.split() new_line = "" for word in words: fst = word[0] last = word[-1] # Check if the word ends with a punctuation if last == "," or last == ";" or last == ".": clean_word = word[0:-1] last = last + " " elif last == "]": clean_word = word[0:-1] else: clean_word = word last = " " # Check if the word starts with "[" if fst == "[": clean_word = clean_word[1:] else: clean_word = clean_word fst = "" find = dict.get(clean_word) if find == None: new_line = new_line + fst + str(clean_word) + last else: new_line = new_line + fst + str(find) + last return new_line
python
def replace(dict,line): """ Find and replace the special words according to the dictionary. Parameters ========== dict : Dictionary A dictionary derived from a yaml file. Source language as keys and the target language as values. line : String A string need to be processed. """ words = line.split() new_line = "" for word in words: fst = word[0] last = word[-1] # Check if the word ends with a punctuation if last == "," or last == ";" or last == ".": clean_word = word[0:-1] last = last + " " elif last == "]": clean_word = word[0:-1] else: clean_word = word last = " " # Check if the word starts with "[" if fst == "[": clean_word = clean_word[1:] else: clean_word = clean_word fst = "" find = dict.get(clean_word) if find == None: new_line = new_line + fst + str(clean_word) + last else: new_line = new_line + fst + str(find) + last return new_line
[ "def", "replace", "(", "dict", ",", "line", ")", ":", "words", "=", "line", ".", "split", "(", ")", "new_line", "=", "\"\"", "for", "word", "in", "words", ":", "fst", "=", "word", "[", "0", "]", "last", "=", "word", "[", "-", "1", "]", "# Check if the word ends with a punctuation", "if", "last", "==", "\",\"", "or", "last", "==", "\";\"", "or", "last", "==", "\".\"", ":", "clean_word", "=", "word", "[", "0", ":", "-", "1", "]", "last", "=", "last", "+", "\" \"", "elif", "last", "==", "\"]\"", ":", "clean_word", "=", "word", "[", "0", ":", "-", "1", "]", "else", ":", "clean_word", "=", "word", "last", "=", "\" \"", "# Check if the word starts with \"[\"", "if", "fst", "==", "\"[\"", ":", "clean_word", "=", "clean_word", "[", "1", ":", "]", "else", ":", "clean_word", "=", "clean_word", "fst", "=", "\"\"", "find", "=", "dict", ".", "get", "(", "clean_word", ")", "if", "find", "==", "None", ":", "new_line", "=", "new_line", "+", "fst", "+", "str", "(", "clean_word", ")", "+", "last", "else", ":", "new_line", "=", "new_line", "+", "fst", "+", "str", "(", "find", ")", "+", "last", "return", "new_line" ]
Find and replace the special words according to the dictionary. Parameters ========== dict : Dictionary A dictionary derived from a yaml file. Source language as keys and the target language as values. line : String A string need to be processed.
[ "Find", "and", "replace", "the", "special", "words", "according", "to", "the", "dictionary", "." ]
3f3b5c9f321264e0e4d8ed68dfbc080762579815
https://github.com/AguaClara/aide_document-DEPRECATED/blob/3f3b5c9f321264e0e4d8ed68dfbc080762579815/aide_document/translate.py#L6-L47
250,674
AguaClara/aide_document-DEPRECATED
aide_document/translate.py
translate
def translate(src_filename, dest_filename, dest_lang, src_lang='auto', specialwords_filename=''): """ Converts a source file to a destination file in the selected language. Parameters ========== src_filename : String Relative file path to the original MarkDown source file. dest_filename : String Relative file path to where the translated MarkDown file should go. dest_lang : String The language of the destination file. Must be the correct 2-letter ISO-639-1 abbreviation from https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes src_lang : String (OPTIONAL) The language of the source file. Only needed if the source file contains multiple languages. Like dest_lang, must be the correct ISO-639-1 abbreviation from https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes specialwords_filename : String (OPTIONAL) YAML file containing special translations of words. Must map a string of the translation direction (e.g. 'en_es') to a sequence of specially translated words. Examples ======== Suppose you have the following directory in English: data/ doc_en.md special.yaml special.yaml is organized as follows: en_es: - tank : bote #TODO: add more/better translation examples To translate it to Spanish: >>> from aide_document import translate >>> translate.translate('data/doc_en.md', 'data/doc_es.md', 'es', 'en', 'data/special.yaml') The 4th parameter can be omitted if the source file has only one language, and the 5th can be omitted if there are no special translations. """ translator = Translator() # Initialize translator object with open(src_filename) as srcfile, open(dest_filename, 'w') as destfile: lines = srcfile.readlines() specialwords_dict = {} # If special words file exists, place special word mappings into specialwords_dict if specialwords_filename != '': with yaml.load(open(specialwords_filename)) as specialwords_fulllist: # Gets source language if not passed through if src_lang == 'auto': src_lang == str(translator.detect(lines[0]))[14:16] # Attempts to add the correct dictionary of special words try: specialwords_dict = specialwords_dict_full[src_lang + '_' + dest_lang] except KeyError: print('Special words file doesn\'t contain required language translation!') # Parses each line for special cases and ignores them when translating for line in lines: line = line.strip() # Parses for code blocks and ignores them entirely if line.startswith("```"): line = line else: # Parses for URL's and file links and ignores them if line.find("[") != -1 and line.find("]") != -1 and line.find("(") != -1 and line.find(")") != -1: ignore_start = line.find("(") ignore_end = line.find(")") head = replace(specialwords_dict,line[0:ignore_start]) tail = replace(specialwords_dict,line[ignore_end+1:]) head = translator.translate(head, dest_lang, src_lang).text tail = translator.translate(tail, dest_lang, src_lang).text line = head + line[ignore_start:ignore_end+1] + tail # Translates normally if there are no special cases else: line = translator.translate(line, dest_lang, src_lang).text # Write to destination file destfile.write(line + '\n')
python
def translate(src_filename, dest_filename, dest_lang, src_lang='auto', specialwords_filename=''): """ Converts a source file to a destination file in the selected language. Parameters ========== src_filename : String Relative file path to the original MarkDown source file. dest_filename : String Relative file path to where the translated MarkDown file should go. dest_lang : String The language of the destination file. Must be the correct 2-letter ISO-639-1 abbreviation from https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes src_lang : String (OPTIONAL) The language of the source file. Only needed if the source file contains multiple languages. Like dest_lang, must be the correct ISO-639-1 abbreviation from https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes specialwords_filename : String (OPTIONAL) YAML file containing special translations of words. Must map a string of the translation direction (e.g. 'en_es') to a sequence of specially translated words. Examples ======== Suppose you have the following directory in English: data/ doc_en.md special.yaml special.yaml is organized as follows: en_es: - tank : bote #TODO: add more/better translation examples To translate it to Spanish: >>> from aide_document import translate >>> translate.translate('data/doc_en.md', 'data/doc_es.md', 'es', 'en', 'data/special.yaml') The 4th parameter can be omitted if the source file has only one language, and the 5th can be omitted if there are no special translations. """ translator = Translator() # Initialize translator object with open(src_filename) as srcfile, open(dest_filename, 'w') as destfile: lines = srcfile.readlines() specialwords_dict = {} # If special words file exists, place special word mappings into specialwords_dict if specialwords_filename != '': with yaml.load(open(specialwords_filename)) as specialwords_fulllist: # Gets source language if not passed through if src_lang == 'auto': src_lang == str(translator.detect(lines[0]))[14:16] # Attempts to add the correct dictionary of special words try: specialwords_dict = specialwords_dict_full[src_lang + '_' + dest_lang] except KeyError: print('Special words file doesn\'t contain required language translation!') # Parses each line for special cases and ignores them when translating for line in lines: line = line.strip() # Parses for code blocks and ignores them entirely if line.startswith("```"): line = line else: # Parses for URL's and file links and ignores them if line.find("[") != -1 and line.find("]") != -1 and line.find("(") != -1 and line.find(")") != -1: ignore_start = line.find("(") ignore_end = line.find(")") head = replace(specialwords_dict,line[0:ignore_start]) tail = replace(specialwords_dict,line[ignore_end+1:]) head = translator.translate(head, dest_lang, src_lang).text tail = translator.translate(tail, dest_lang, src_lang).text line = head + line[ignore_start:ignore_end+1] + tail # Translates normally if there are no special cases else: line = translator.translate(line, dest_lang, src_lang).text # Write to destination file destfile.write(line + '\n')
[ "def", "translate", "(", "src_filename", ",", "dest_filename", ",", "dest_lang", ",", "src_lang", "=", "'auto'", ",", "specialwords_filename", "=", "''", ")", ":", "translator", "=", "Translator", "(", ")", "# Initialize translator object", "with", "open", "(", "src_filename", ")", "as", "srcfile", ",", "open", "(", "dest_filename", ",", "'w'", ")", "as", "destfile", ":", "lines", "=", "srcfile", ".", "readlines", "(", ")", "specialwords_dict", "=", "{", "}", "# If special words file exists, place special word mappings into specialwords_dict", "if", "specialwords_filename", "!=", "''", ":", "with", "yaml", ".", "load", "(", "open", "(", "specialwords_filename", ")", ")", "as", "specialwords_fulllist", ":", "# Gets source language if not passed through", "if", "src_lang", "==", "'auto'", ":", "src_lang", "==", "str", "(", "translator", ".", "detect", "(", "lines", "[", "0", "]", ")", ")", "[", "14", ":", "16", "]", "# Attempts to add the correct dictionary of special words", "try", ":", "specialwords_dict", "=", "specialwords_dict_full", "[", "src_lang", "+", "'_'", "+", "dest_lang", "]", "except", "KeyError", ":", "print", "(", "'Special words file doesn\\'t contain required language translation!'", ")", "# Parses each line for special cases and ignores them when translating", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "strip", "(", ")", "# Parses for code blocks and ignores them entirely", "if", "line", ".", "startswith", "(", "\"```\"", ")", ":", "line", "=", "line", "else", ":", "# Parses for URL's and file links and ignores them", "if", "line", ".", "find", "(", "\"[\"", ")", "!=", "-", "1", "and", "line", ".", "find", "(", "\"]\"", ")", "!=", "-", "1", "and", "line", ".", "find", "(", "\"(\"", ")", "!=", "-", "1", "and", "line", ".", "find", "(", "\")\"", ")", "!=", "-", "1", ":", "ignore_start", "=", "line", ".", "find", "(", "\"(\"", ")", "ignore_end", "=", "line", ".", "find", "(", "\")\"", ")", "head", "=", "replace", "(", "specialwords_dict", ",", "line", "[", "0", ":", "ignore_start", "]", ")", "tail", "=", "replace", "(", "specialwords_dict", ",", "line", "[", "ignore_end", "+", "1", ":", "]", ")", "head", "=", "translator", ".", "translate", "(", "head", ",", "dest_lang", ",", "src_lang", ")", ".", "text", "tail", "=", "translator", ".", "translate", "(", "tail", ",", "dest_lang", ",", "src_lang", ")", ".", "text", "line", "=", "head", "+", "line", "[", "ignore_start", ":", "ignore_end", "+", "1", "]", "+", "tail", "# Translates normally if there are no special cases", "else", ":", "line", "=", "translator", ".", "translate", "(", "line", ",", "dest_lang", ",", "src_lang", ")", ".", "text", "# Write to destination file", "destfile", ".", "write", "(", "line", "+", "'\\n'", ")" ]
Converts a source file to a destination file in the selected language. Parameters ========== src_filename : String Relative file path to the original MarkDown source file. dest_filename : String Relative file path to where the translated MarkDown file should go. dest_lang : String The language of the destination file. Must be the correct 2-letter ISO-639-1 abbreviation from https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes src_lang : String (OPTIONAL) The language of the source file. Only needed if the source file contains multiple languages. Like dest_lang, must be the correct ISO-639-1 abbreviation from https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes specialwords_filename : String (OPTIONAL) YAML file containing special translations of words. Must map a string of the translation direction (e.g. 'en_es') to a sequence of specially translated words. Examples ======== Suppose you have the following directory in English: data/ doc_en.md special.yaml special.yaml is organized as follows: en_es: - tank : bote #TODO: add more/better translation examples To translate it to Spanish: >>> from aide_document import translate >>> translate.translate('data/doc_en.md', 'data/doc_es.md', 'es', 'en', 'data/special.yaml') The 4th parameter can be omitted if the source file has only one language, and the 5th can be omitted if there are no special translations.
[ "Converts", "a", "source", "file", "to", "a", "destination", "file", "in", "the", "selected", "language", "." ]
3f3b5c9f321264e0e4d8ed68dfbc080762579815
https://github.com/AguaClara/aide_document-DEPRECATED/blob/3f3b5c9f321264e0e4d8ed68dfbc080762579815/aide_document/translate.py#L49-L128
250,675
qzmfranklin/easyshell
easyshell/base.py
deprecated
def deprecated(f): """Decorate a function object as deprecated. Work nicely with the @command and @subshell decorators. Add a __deprecated__ field to the input object and set it to True. """ def inner_func(*args, **kwargs): print(textwrap.dedent("""\ This command is deprecated and is subject to complete removal at any later version without notice. """)) f(*args, **kwargs) inner_func.__deprecated__ = True inner_func.__doc__ = f.__doc__ inner_func.__name__ = f.__name__ if iscommand(f): inner_func.__command__ = f.__command__ return inner_func
python
def deprecated(f): """Decorate a function object as deprecated. Work nicely with the @command and @subshell decorators. Add a __deprecated__ field to the input object and set it to True. """ def inner_func(*args, **kwargs): print(textwrap.dedent("""\ This command is deprecated and is subject to complete removal at any later version without notice. """)) f(*args, **kwargs) inner_func.__deprecated__ = True inner_func.__doc__ = f.__doc__ inner_func.__name__ = f.__name__ if iscommand(f): inner_func.__command__ = f.__command__ return inner_func
[ "def", "deprecated", "(", "f", ")", ":", "def", "inner_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", "(", "textwrap", ".", "dedent", "(", "\"\"\"\\\n This command is deprecated and is subject to complete\n removal at any later version without notice.\n \"\"\"", ")", ")", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "inner_func", ".", "__deprecated__", "=", "True", "inner_func", ".", "__doc__", "=", "f", ".", "__doc__", "inner_func", ".", "__name__", "=", "f", ".", "__name__", "if", "iscommand", "(", "f", ")", ":", "inner_func", ".", "__command__", "=", "f", ".", "__command__", "return", "inner_func" ]
Decorate a function object as deprecated. Work nicely with the @command and @subshell decorators. Add a __deprecated__ field to the input object and set it to True.
[ "Decorate", "a", "function", "object", "as", "deprecated", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L40-L58
250,676
qzmfranklin/easyshell
easyshell/base.py
helper
def helper(*commands): """Decorate a function to be the helper function of commands. Arguments: commands: Names of command that should trigger this function object. --------------------------- Interface of helper methods: @helper('some-command') def help_foo(self, args): ''' Arguments: args: A list of arguments. Returns: A string that is the help message. ''' pass """ def decorated_func(f): f.__help_targets__ = list(commands) return f return decorated_func
python
def helper(*commands): """Decorate a function to be the helper function of commands. Arguments: commands: Names of command that should trigger this function object. --------------------------- Interface of helper methods: @helper('some-command') def help_foo(self, args): ''' Arguments: args: A list of arguments. Returns: A string that is the help message. ''' pass """ def decorated_func(f): f.__help_targets__ = list(commands) return f return decorated_func
[ "def", "helper", "(", "*", "commands", ")", ":", "def", "decorated_func", "(", "f", ")", ":", "f", ".", "__help_targets__", "=", "list", "(", "commands", ")", "return", "f", "return", "decorated_func" ]
Decorate a function to be the helper function of commands. Arguments: commands: Names of command that should trigger this function object. --------------------------- Interface of helper methods: @helper('some-command') def help_foo(self, args): ''' Arguments: args: A list of arguments. Returns: A string that is the help message. ''' pass
[ "Decorate", "a", "function", "to", "be", "the", "helper", "function", "of", "commands", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L181-L204
250,677
qzmfranklin/easyshell
easyshell/base.py
completer
def completer(*commands): """Decorate a function to be the completer function of commands. Arguments: commands: Names of command that should trigger this function object. ------------------------------ Interface of completer methods: @completer('some-other_command') def complete_foo(self, args, text): ''' Arguments: args: A list of arguments. The first token, i.e, the command itself, is not included. text: The scope of text being replaced. A few examples, with '$' representing the shell prompt and '|' represents the cursor position: $ | $ history| handled by the __driver_completer() method $ history | args = [] text = '' $ history cle| args = [] text = 'cle' $ history clear | args = ['clear'] text = '' Returns: A list of candidates. If no candidate was found, return either [] or None. ''' pass """ def decorated_func(f): f.__complete_targets__ = list(commands) return f return decorated_func
python
def completer(*commands): """Decorate a function to be the completer function of commands. Arguments: commands: Names of command that should trigger this function object. ------------------------------ Interface of completer methods: @completer('some-other_command') def complete_foo(self, args, text): ''' Arguments: args: A list of arguments. The first token, i.e, the command itself, is not included. text: The scope of text being replaced. A few examples, with '$' representing the shell prompt and '|' represents the cursor position: $ | $ history| handled by the __driver_completer() method $ history | args = [] text = '' $ history cle| args = [] text = 'cle' $ history clear | args = ['clear'] text = '' Returns: A list of candidates. If no candidate was found, return either [] or None. ''' pass """ def decorated_func(f): f.__complete_targets__ = list(commands) return f return decorated_func
[ "def", "completer", "(", "*", "commands", ")", ":", "def", "decorated_func", "(", "f", ")", ":", "f", ".", "__complete_targets__", "=", "list", "(", "commands", ")", "return", "f", "return", "decorated_func" ]
Decorate a function to be the completer function of commands. Arguments: commands: Names of command that should trigger this function object. ------------------------------ Interface of completer methods: @completer('some-other_command') def complete_foo(self, args, text): ''' Arguments: args: A list of arguments. The first token, i.e, the command itself, is not included. text: The scope of text being replaced. A few examples, with '$' representing the shell prompt and '|' represents the cursor position: $ | $ history| handled by the __driver_completer() method $ history | args = [] text = '' $ history cle| args = [] text = 'cle' $ history clear | args = ['clear'] text = '' Returns: A list of candidates. If no candidate was found, return either [] or None. ''' pass
[ "Decorate", "a", "function", "to", "be", "the", "completer", "function", "of", "commands", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L212-L253
250,678
qzmfranklin/easyshell
easyshell/base.py
subshell
def subshell(shell_cls, *commands, **kwargs): """Decorate a function to conditionally launch a _ShellBase subshell. Arguments: shell_cls: A subclass of _ShellBase to be launched. commands: Names of command that should trigger this function object. kwargs: The keyword arguments for the command decorator method. ----------------------------- Interface of methods decorated by this decorator method: @command(SomeShellClass, 'foo', 'bar') def bar(self, cmd, args): '''The command 'foo' invokes this method then launches the subshell. Arguments: cmd: A string, the name of the command that triggered this function. This is useful for knowing which command, in this case, 'foo' or 'bar', triggered this method. args: The list of arguments passed along with the command. Returns: There are three categories of valid return values. None, False, or anything that evaluates to False: The subshell is not invoked. This is useful for making a command conditionally launch a subshell. String: A string will appended to the prompt string to uniquely identify the subshell. A 2-tuple of type (string, dict): The string will be appended to the prompt string. The dictionary stores the data passed to the subshell. These data are the context of the subshell. The parent shell must conform to the subhshell class in terms of which key-value pairs to pass to the subshell. ''' pass """ def decorated_func(f): def inner_func(self, cmd, args): retval = f(self, cmd, args) # Do not launch the subshell if the return value is None. if not retval: return # Pass the context (see the doc string) to the subshell if the # return value is a 2-tuple. Otherwise, the context is just an empty # dictionary. if isinstance(retval, tuple): prompt, context = retval else: prompt = retval context = {} return self.launch_subshell(shell_cls, cmd, args, prompt = prompt, context = context) inner_func.__name__ = f.__name__ inner_func.__doc__ = f.__doc__ obj = command(*commands, **kwargs)(inner_func) if commands else inner_func obj.__launch_subshell__ = shell_cls return obj return decorated_func
python
def subshell(shell_cls, *commands, **kwargs): """Decorate a function to conditionally launch a _ShellBase subshell. Arguments: shell_cls: A subclass of _ShellBase to be launched. commands: Names of command that should trigger this function object. kwargs: The keyword arguments for the command decorator method. ----------------------------- Interface of methods decorated by this decorator method: @command(SomeShellClass, 'foo', 'bar') def bar(self, cmd, args): '''The command 'foo' invokes this method then launches the subshell. Arguments: cmd: A string, the name of the command that triggered this function. This is useful for knowing which command, in this case, 'foo' or 'bar', triggered this method. args: The list of arguments passed along with the command. Returns: There are three categories of valid return values. None, False, or anything that evaluates to False: The subshell is not invoked. This is useful for making a command conditionally launch a subshell. String: A string will appended to the prompt string to uniquely identify the subshell. A 2-tuple of type (string, dict): The string will be appended to the prompt string. The dictionary stores the data passed to the subshell. These data are the context of the subshell. The parent shell must conform to the subhshell class in terms of which key-value pairs to pass to the subshell. ''' pass """ def decorated_func(f): def inner_func(self, cmd, args): retval = f(self, cmd, args) # Do not launch the subshell if the return value is None. if not retval: return # Pass the context (see the doc string) to the subshell if the # return value is a 2-tuple. Otherwise, the context is just an empty # dictionary. if isinstance(retval, tuple): prompt, context = retval else: prompt = retval context = {} return self.launch_subshell(shell_cls, cmd, args, prompt = prompt, context = context) inner_func.__name__ = f.__name__ inner_func.__doc__ = f.__doc__ obj = command(*commands, **kwargs)(inner_func) if commands else inner_func obj.__launch_subshell__ = shell_cls return obj return decorated_func
[ "def", "subshell", "(", "shell_cls", ",", "*", "commands", ",", "*", "*", "kwargs", ")", ":", "def", "decorated_func", "(", "f", ")", ":", "def", "inner_func", "(", "self", ",", "cmd", ",", "args", ")", ":", "retval", "=", "f", "(", "self", ",", "cmd", ",", "args", ")", "# Do not launch the subshell if the return value is None.", "if", "not", "retval", ":", "return", "# Pass the context (see the doc string) to the subshell if the", "# return value is a 2-tuple. Otherwise, the context is just an empty", "# dictionary.", "if", "isinstance", "(", "retval", ",", "tuple", ")", ":", "prompt", ",", "context", "=", "retval", "else", ":", "prompt", "=", "retval", "context", "=", "{", "}", "return", "self", ".", "launch_subshell", "(", "shell_cls", ",", "cmd", ",", "args", ",", "prompt", "=", "prompt", ",", "context", "=", "context", ")", "inner_func", ".", "__name__", "=", "f", ".", "__name__", "inner_func", ".", "__doc__", "=", "f", ".", "__doc__", "obj", "=", "command", "(", "*", "commands", ",", "*", "*", "kwargs", ")", "(", "inner_func", ")", "if", "commands", "else", "inner_func", "obj", ".", "__launch_subshell__", "=", "shell_cls", "return", "obj", "return", "decorated_func" ]
Decorate a function to conditionally launch a _ShellBase subshell. Arguments: shell_cls: A subclass of _ShellBase to be launched. commands: Names of command that should trigger this function object. kwargs: The keyword arguments for the command decorator method. ----------------------------- Interface of methods decorated by this decorator method: @command(SomeShellClass, 'foo', 'bar') def bar(self, cmd, args): '''The command 'foo' invokes this method then launches the subshell. Arguments: cmd: A string, the name of the command that triggered this function. This is useful for knowing which command, in this case, 'foo' or 'bar', triggered this method. args: The list of arguments passed along with the command. Returns: There are three categories of valid return values. None, False, or anything that evaluates to False: The subshell is not invoked. This is useful for making a command conditionally launch a subshell. String: A string will appended to the prompt string to uniquely identify the subshell. A 2-tuple of type (string, dict): The string will be appended to the prompt string. The dictionary stores the data passed to the subshell. These data are the context of the subshell. The parent shell must conform to the subhshell class in terms of which key-value pairs to pass to the subshell. ''' pass
[ "Decorate", "a", "function", "to", "conditionally", "launch", "a", "_ShellBase", "subshell", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L267-L325
250,679
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.doc_string
def doc_string(cls): """Get the doc string of this class. If this class does not have a doc string or the doc string is empty, try its base classes until the root base class, _ShellBase, is reached. CAVEAT: This method assumes that this class and all its super classes are derived from _ShellBase or object. """ clz = cls while not clz.__doc__: clz = clz.__bases__[0] return clz.__doc__
python
def doc_string(cls): """Get the doc string of this class. If this class does not have a doc string or the doc string is empty, try its base classes until the root base class, _ShellBase, is reached. CAVEAT: This method assumes that this class and all its super classes are derived from _ShellBase or object. """ clz = cls while not clz.__doc__: clz = clz.__bases__[0] return clz.__doc__
[ "def", "doc_string", "(", "cls", ")", ":", "clz", "=", "cls", "while", "not", "clz", ".", "__doc__", ":", "clz", "=", "clz", ".", "__bases__", "[", "0", "]", "return", "clz", ".", "__doc__" ]
Get the doc string of this class. If this class does not have a doc string or the doc string is empty, try its base classes until the root base class, _ShellBase, is reached. CAVEAT: This method assumes that this class and all its super classes are derived from _ShellBase or object.
[ "Get", "the", "doc", "string", "of", "this", "class", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L437-L450
250,680
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.launch_subshell
def launch_subshell(self, shell_cls, cmd, args, *, prompt = None, context = {}): """Launch a subshell. The doc string of the cmdloop() method explains how shell histories and history files are saved and restored. The design of the _ShellBase class encourage launching of subshells through the subshell() decorator function. Nonetheless, the user has the option of directly launching subshells via this method. Arguments: shell_cls: The _ShellBase class object to instantiate and launch. args: Arguments used to launch this subshell. prompt: The name of the subshell. The default, None, means to use the shell_cls.__name__. context: A dictionary to pass to the subshell as its context. Returns: 'root': Inform the parent shell to keep exiting until the root shell is reached. 'all': Exit the the command line. False, None, or anything that are evaluated as False: Inform the parent shell to stay in that parent shell. An integer indicating the depth of shell to exit to. 0 = root shell. """ # Save history of the current shell. readline.write_history_file(self.history_fname) prompt = prompt if prompt else shell_cls.__name__ mode = _ShellBase._Mode( shell = self, cmd = cmd, args = args, prompt = prompt, context = context, ) shell = shell_cls( batch_mode = self.batch_mode, debug = self.debug, mode_stack = self._mode_stack + [ mode ], pipe_end = self._pipe_end, root_prompt = self.root_prompt, stdout = self.stdout, stderr = self.stderr, temp_dir = self._temp_dir, ) # The subshell creates its own history context. self.print_debug("Leave parent shell '{}'".format(self.prompt)) exit_directive = shell.cmdloop() self.print_debug("Enter parent shell '{}': {}".format(self.prompt, exit_directive)) # Restore history. The subshell could have deleted the history file of # this shell via 'history clearall'. readline.clear_history() if os.path.isfile(self.history_fname): readline.read_history_file(self.history_fname) if not exit_directive is True: return exit_directive
python
def launch_subshell(self, shell_cls, cmd, args, *, prompt = None, context = {}): """Launch a subshell. The doc string of the cmdloop() method explains how shell histories and history files are saved and restored. The design of the _ShellBase class encourage launching of subshells through the subshell() decorator function. Nonetheless, the user has the option of directly launching subshells via this method. Arguments: shell_cls: The _ShellBase class object to instantiate and launch. args: Arguments used to launch this subshell. prompt: The name of the subshell. The default, None, means to use the shell_cls.__name__. context: A dictionary to pass to the subshell as its context. Returns: 'root': Inform the parent shell to keep exiting until the root shell is reached. 'all': Exit the the command line. False, None, or anything that are evaluated as False: Inform the parent shell to stay in that parent shell. An integer indicating the depth of shell to exit to. 0 = root shell. """ # Save history of the current shell. readline.write_history_file(self.history_fname) prompt = prompt if prompt else shell_cls.__name__ mode = _ShellBase._Mode( shell = self, cmd = cmd, args = args, prompt = prompt, context = context, ) shell = shell_cls( batch_mode = self.batch_mode, debug = self.debug, mode_stack = self._mode_stack + [ mode ], pipe_end = self._pipe_end, root_prompt = self.root_prompt, stdout = self.stdout, stderr = self.stderr, temp_dir = self._temp_dir, ) # The subshell creates its own history context. self.print_debug("Leave parent shell '{}'".format(self.prompt)) exit_directive = shell.cmdloop() self.print_debug("Enter parent shell '{}': {}".format(self.prompt, exit_directive)) # Restore history. The subshell could have deleted the history file of # this shell via 'history clearall'. readline.clear_history() if os.path.isfile(self.history_fname): readline.read_history_file(self.history_fname) if not exit_directive is True: return exit_directive
[ "def", "launch_subshell", "(", "self", ",", "shell_cls", ",", "cmd", ",", "args", ",", "*", ",", "prompt", "=", "None", ",", "context", "=", "{", "}", ")", ":", "# Save history of the current shell.", "readline", ".", "write_history_file", "(", "self", ".", "history_fname", ")", "prompt", "=", "prompt", "if", "prompt", "else", "shell_cls", ".", "__name__", "mode", "=", "_ShellBase", ".", "_Mode", "(", "shell", "=", "self", ",", "cmd", "=", "cmd", ",", "args", "=", "args", ",", "prompt", "=", "prompt", ",", "context", "=", "context", ",", ")", "shell", "=", "shell_cls", "(", "batch_mode", "=", "self", ".", "batch_mode", ",", "debug", "=", "self", ".", "debug", ",", "mode_stack", "=", "self", ".", "_mode_stack", "+", "[", "mode", "]", ",", "pipe_end", "=", "self", ".", "_pipe_end", ",", "root_prompt", "=", "self", ".", "root_prompt", ",", "stdout", "=", "self", ".", "stdout", ",", "stderr", "=", "self", ".", "stderr", ",", "temp_dir", "=", "self", ".", "_temp_dir", ",", ")", "# The subshell creates its own history context.", "self", ".", "print_debug", "(", "\"Leave parent shell '{}'\"", ".", "format", "(", "self", ".", "prompt", ")", ")", "exit_directive", "=", "shell", ".", "cmdloop", "(", ")", "self", ".", "print_debug", "(", "\"Enter parent shell '{}': {}\"", ".", "format", "(", "self", ".", "prompt", ",", "exit_directive", ")", ")", "# Restore history. The subshell could have deleted the history file of", "# this shell via 'history clearall'.", "readline", ".", "clear_history", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "history_fname", ")", ":", "readline", ".", "read_history_file", "(", "self", ".", "history_fname", ")", "if", "not", "exit_directive", "is", "True", ":", "return", "exit_directive" ]
Launch a subshell. The doc string of the cmdloop() method explains how shell histories and history files are saved and restored. The design of the _ShellBase class encourage launching of subshells through the subshell() decorator function. Nonetheless, the user has the option of directly launching subshells via this method. Arguments: shell_cls: The _ShellBase class object to instantiate and launch. args: Arguments used to launch this subshell. prompt: The name of the subshell. The default, None, means to use the shell_cls.__name__. context: A dictionary to pass to the subshell as its context. Returns: 'root': Inform the parent shell to keep exiting until the root shell is reached. 'all': Exit the the command line. False, None, or anything that are evaluated as False: Inform the parent shell to stay in that parent shell. An integer indicating the depth of shell to exit to. 0 = root shell.
[ "Launch", "a", "subshell", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L480-L539
250,681
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.batch_string
def batch_string(self, content): """Process a string in batch mode. Arguments: content: A unicode string representing the content to be processed. """ pipe_send, pipe_recv = multiprocessing.Pipe() self._pipe_end = pipe_recv proc = multiprocessing.Process(target = self.cmdloop) for line in content.split('\n'): pipe_send.send(line) pipe_send.close() proc.start() proc.join()
python
def batch_string(self, content): """Process a string in batch mode. Arguments: content: A unicode string representing the content to be processed. """ pipe_send, pipe_recv = multiprocessing.Pipe() self._pipe_end = pipe_recv proc = multiprocessing.Process(target = self.cmdloop) for line in content.split('\n'): pipe_send.send(line) pipe_send.close() proc.start() proc.join()
[ "def", "batch_string", "(", "self", ",", "content", ")", ":", "pipe_send", ",", "pipe_recv", "=", "multiprocessing", ".", "Pipe", "(", ")", "self", ".", "_pipe_end", "=", "pipe_recv", "proc", "=", "multiprocessing", ".", "Process", "(", "target", "=", "self", ".", "cmdloop", ")", "for", "line", "in", "content", ".", "split", "(", "'\\n'", ")", ":", "pipe_send", ".", "send", "(", "line", ")", "pipe_send", ".", "close", "(", ")", "proc", ".", "start", "(", ")", "proc", ".", "join", "(", ")" ]
Process a string in batch mode. Arguments: content: A unicode string representing the content to be processed.
[ "Process", "a", "string", "in", "batch", "mode", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L541-L554
250,682
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.cmdloop
def cmdloop(self): """Start the main loop of the interactive shell. The preloop() and postloop() methods are always run before and after the main loop, respectively. Returns: 'root': Inform the parent shell to to keep exiting until the root shell is reached. 'all': Exit all the way back the the command line shell. False, None, or anything that are evaluated as False: Exit this shell, enter the parent shell. An integer: The depth of the shell to exit to. 0 = root shell. History: _ShellBase histories are persistently saved to files, whose name matches the prompt string. For example, if the prompt of a subshell is '(Foo-Bar-Kar)$ ', the name of its history file is s-Foo-Bar-Kar. The history_fname property encodes this algorithm. All history files are saved to the the directory whose path is self._temp_dir. Subshells use the same temp_dir as their parent shells, thus their root shell. The history of the parent shell is saved and restored by the parent shell, as in launch_subshell(). The history of the subshell is saved and restored by the subshell, as in cmdloop(). When a subshell is started, i.e., when the cmdloop() method of the subshell is called, the subshell will try to load its own history file, whose file name is determined by the naming convention introduced earlier. Completer Delimiters: Certain characters such as '-' could be part of a command. But by default they are considered the delimiters by the readline library, which causes completion candidates with those characters to malfunction. The old completer delimiters are saved before the loop and restored after the loop ends. This is to keep the environment clean. """ self.print_debug("Enter subshell '{}'".format(self.prompt)) # Save the completer function, the history buffer, and the # completer_delims. old_completer = readline.get_completer() old_delims = readline.get_completer_delims() new_delims = ''.join(list(set(old_delims) - set(_ShellBase._non_delims))) readline.set_completer_delims(new_delims) # Load the new completer function and start a new history buffer. readline.set_completer(self.__driver_stub) readline.clear_history() if os.path.isfile(self.history_fname): readline.read_history_file(self.history_fname) # main loop try: # The exit_directive: # True Leave this shell, enter the parent shell. # False Continue with the loop. # 'root' Exit to the root shell. # 'all' Exit to the command line. # an integer The depth of the shell to exit to. 0 = root # shell. Negative number is taken as error. self.preloop() while True: exit_directive = False try: if self.batch_mode: line = self._pipe_end.recv() else: line = input(self.prompt).strip() except EOFError: line = _ShellBase.EOF try: exit_directive = self.__exec_line__(line) except: self.stderr.write(traceback.format_exc()) if type(exit_directive) is int: if len(self._mode_stack) > exit_directive: break if len(self._mode_stack) == exit_directive: continue if self._mode_stack and exit_directive == 'root': break if exit_directive in { 'all', True, }: break finally: self.postloop() # Restore the completer function, save the history, and restore old # delims. readline.set_completer(old_completer) readline.write_history_file(self.history_fname) readline.set_completer_delims(old_delims) self.print_debug("Leave subshell '{}': {}".format(self.prompt, exit_directive)) return exit_directive
python
def cmdloop(self): """Start the main loop of the interactive shell. The preloop() and postloop() methods are always run before and after the main loop, respectively. Returns: 'root': Inform the parent shell to to keep exiting until the root shell is reached. 'all': Exit all the way back the the command line shell. False, None, or anything that are evaluated as False: Exit this shell, enter the parent shell. An integer: The depth of the shell to exit to. 0 = root shell. History: _ShellBase histories are persistently saved to files, whose name matches the prompt string. For example, if the prompt of a subshell is '(Foo-Bar-Kar)$ ', the name of its history file is s-Foo-Bar-Kar. The history_fname property encodes this algorithm. All history files are saved to the the directory whose path is self._temp_dir. Subshells use the same temp_dir as their parent shells, thus their root shell. The history of the parent shell is saved and restored by the parent shell, as in launch_subshell(). The history of the subshell is saved and restored by the subshell, as in cmdloop(). When a subshell is started, i.e., when the cmdloop() method of the subshell is called, the subshell will try to load its own history file, whose file name is determined by the naming convention introduced earlier. Completer Delimiters: Certain characters such as '-' could be part of a command. But by default they are considered the delimiters by the readline library, which causes completion candidates with those characters to malfunction. The old completer delimiters are saved before the loop and restored after the loop ends. This is to keep the environment clean. """ self.print_debug("Enter subshell '{}'".format(self.prompt)) # Save the completer function, the history buffer, and the # completer_delims. old_completer = readline.get_completer() old_delims = readline.get_completer_delims() new_delims = ''.join(list(set(old_delims) - set(_ShellBase._non_delims))) readline.set_completer_delims(new_delims) # Load the new completer function and start a new history buffer. readline.set_completer(self.__driver_stub) readline.clear_history() if os.path.isfile(self.history_fname): readline.read_history_file(self.history_fname) # main loop try: # The exit_directive: # True Leave this shell, enter the parent shell. # False Continue with the loop. # 'root' Exit to the root shell. # 'all' Exit to the command line. # an integer The depth of the shell to exit to. 0 = root # shell. Negative number is taken as error. self.preloop() while True: exit_directive = False try: if self.batch_mode: line = self._pipe_end.recv() else: line = input(self.prompt).strip() except EOFError: line = _ShellBase.EOF try: exit_directive = self.__exec_line__(line) except: self.stderr.write(traceback.format_exc()) if type(exit_directive) is int: if len(self._mode_stack) > exit_directive: break if len(self._mode_stack) == exit_directive: continue if self._mode_stack and exit_directive == 'root': break if exit_directive in { 'all', True, }: break finally: self.postloop() # Restore the completer function, save the history, and restore old # delims. readline.set_completer(old_completer) readline.write_history_file(self.history_fname) readline.set_completer_delims(old_delims) self.print_debug("Leave subshell '{}': {}".format(self.prompt, exit_directive)) return exit_directive
[ "def", "cmdloop", "(", "self", ")", ":", "self", ".", "print_debug", "(", "\"Enter subshell '{}'\"", ".", "format", "(", "self", ".", "prompt", ")", ")", "# Save the completer function, the history buffer, and the", "# completer_delims.", "old_completer", "=", "readline", ".", "get_completer", "(", ")", "old_delims", "=", "readline", ".", "get_completer_delims", "(", ")", "new_delims", "=", "''", ".", "join", "(", "list", "(", "set", "(", "old_delims", ")", "-", "set", "(", "_ShellBase", ".", "_non_delims", ")", ")", ")", "readline", ".", "set_completer_delims", "(", "new_delims", ")", "# Load the new completer function and start a new history buffer.", "readline", ".", "set_completer", "(", "self", ".", "__driver_stub", ")", "readline", ".", "clear_history", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "history_fname", ")", ":", "readline", ".", "read_history_file", "(", "self", ".", "history_fname", ")", "# main loop", "try", ":", "# The exit_directive:", "# True Leave this shell, enter the parent shell.", "# False Continue with the loop.", "# 'root' Exit to the root shell.", "# 'all' Exit to the command line.", "# an integer The depth of the shell to exit to. 0 = root", "# shell. Negative number is taken as error.", "self", ".", "preloop", "(", ")", "while", "True", ":", "exit_directive", "=", "False", "try", ":", "if", "self", ".", "batch_mode", ":", "line", "=", "self", ".", "_pipe_end", ".", "recv", "(", ")", "else", ":", "line", "=", "input", "(", "self", ".", "prompt", ")", ".", "strip", "(", ")", "except", "EOFError", ":", "line", "=", "_ShellBase", ".", "EOF", "try", ":", "exit_directive", "=", "self", ".", "__exec_line__", "(", "line", ")", "except", ":", "self", ".", "stderr", ".", "write", "(", "traceback", ".", "format_exc", "(", ")", ")", "if", "type", "(", "exit_directive", ")", "is", "int", ":", "if", "len", "(", "self", ".", "_mode_stack", ")", ">", "exit_directive", ":", "break", "if", "len", "(", "self", ".", "_mode_stack", ")", "==", "exit_directive", ":", "continue", "if", "self", ".", "_mode_stack", "and", "exit_directive", "==", "'root'", ":", "break", "if", "exit_directive", "in", "{", "'all'", ",", "True", ",", "}", ":", "break", "finally", ":", "self", ".", "postloop", "(", ")", "# Restore the completer function, save the history, and restore old", "# delims.", "readline", ".", "set_completer", "(", "old_completer", ")", "readline", ".", "write_history_file", "(", "self", ".", "history_fname", ")", "readline", ".", "set_completer_delims", "(", "old_delims", ")", "self", ".", "print_debug", "(", "\"Leave subshell '{}': {}\"", ".", "format", "(", "self", ".", "prompt", ",", "exit_directive", ")", ")", "return", "exit_directive" ]
Start the main loop of the interactive shell. The preloop() and postloop() methods are always run before and after the main loop, respectively. Returns: 'root': Inform the parent shell to to keep exiting until the root shell is reached. 'all': Exit all the way back the the command line shell. False, None, or anything that are evaluated as False: Exit this shell, enter the parent shell. An integer: The depth of the shell to exit to. 0 = root shell. History: _ShellBase histories are persistently saved to files, whose name matches the prompt string. For example, if the prompt of a subshell is '(Foo-Bar-Kar)$ ', the name of its history file is s-Foo-Bar-Kar. The history_fname property encodes this algorithm. All history files are saved to the the directory whose path is self._temp_dir. Subshells use the same temp_dir as their parent shells, thus their root shell. The history of the parent shell is saved and restored by the parent shell, as in launch_subshell(). The history of the subshell is saved and restored by the subshell, as in cmdloop(). When a subshell is started, i.e., when the cmdloop() method of the subshell is called, the subshell will try to load its own history file, whose file name is determined by the naming convention introduced earlier. Completer Delimiters: Certain characters such as '-' could be part of a command. But by default they are considered the delimiters by the readline library, which causes completion candidates with those characters to malfunction. The old completer delimiters are saved before the loop and restored after the loop ends. This is to keep the environment clean.
[ "Start", "the", "main", "loop", "of", "the", "interactive", "shell", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L562-L665
250,683
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.parse_line
def parse_line(self, line): """Parse a line of input. The input line is tokenized using the same rules as the way bash shell tokenizes inputs. All quoting and escaping rules from the bash shell apply here too. The following cases are handled by __exec_line__(): 1. Empty line. 2. The input line is completely made of whitespace characters. 3. The input line is the EOF character. 4. The first token, as tokenized by shlex.split(), is '!'. 5. Internal commands, i.e., commands registered with internal = True Arguments: The line to parse. Returns: A tuple (cmd, args). The first element cmd must be a python3 string. The second element is, by default, a list of strings representing the arguments, as tokenized by shlex.split(). How to overload parse_line(): 1. The signature of the method must be the same. 2. The return value must be a tuple (cmd, args), where the cmd is a string representing the first token, and args is a list of strings. """ toks = shlex.split(line) # Safe to index the 0-th element because this line would have been # parsed by __exec_line__ if toks is an empty list. return ( toks[0], [] if len(toks) == 1 else toks[1:] )
python
def parse_line(self, line): """Parse a line of input. The input line is tokenized using the same rules as the way bash shell tokenizes inputs. All quoting and escaping rules from the bash shell apply here too. The following cases are handled by __exec_line__(): 1. Empty line. 2. The input line is completely made of whitespace characters. 3. The input line is the EOF character. 4. The first token, as tokenized by shlex.split(), is '!'. 5. Internal commands, i.e., commands registered with internal = True Arguments: The line to parse. Returns: A tuple (cmd, args). The first element cmd must be a python3 string. The second element is, by default, a list of strings representing the arguments, as tokenized by shlex.split(). How to overload parse_line(): 1. The signature of the method must be the same. 2. The return value must be a tuple (cmd, args), where the cmd is a string representing the first token, and args is a list of strings. """ toks = shlex.split(line) # Safe to index the 0-th element because this line would have been # parsed by __exec_line__ if toks is an empty list. return ( toks[0], [] if len(toks) == 1 else toks[1:] )
[ "def", "parse_line", "(", "self", ",", "line", ")", ":", "toks", "=", "shlex", ".", "split", "(", "line", ")", "# Safe to index the 0-th element because this line would have been", "# parsed by __exec_line__ if toks is an empty list.", "return", "(", "toks", "[", "0", "]", ",", "[", "]", "if", "len", "(", "toks", ")", "==", "1", "else", "toks", "[", "1", ":", "]", ")" ]
Parse a line of input. The input line is tokenized using the same rules as the way bash shell tokenizes inputs. All quoting and escaping rules from the bash shell apply here too. The following cases are handled by __exec_line__(): 1. Empty line. 2. The input line is completely made of whitespace characters. 3. The input line is the EOF character. 4. The first token, as tokenized by shlex.split(), is '!'. 5. Internal commands, i.e., commands registered with internal = True Arguments: The line to parse. Returns: A tuple (cmd, args). The first element cmd must be a python3 string. The second element is, by default, a list of strings representing the arguments, as tokenized by shlex.split(). How to overload parse_line(): 1. The signature of the method must be the same. 2. The return value must be a tuple (cmd, args), where the cmd is a string representing the first token, and args is a list of strings.
[ "Parse", "a", "line", "of", "input", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L714-L746
250,684
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__driver_stub
def __driver_stub(self, text, state): """Display help messages or invoke the proper completer. The interface of helper methods and completer methods are documented in the helper() decorator method and the completer() decorator method, respectively. Arguments: text: A string, that is the current completion scope. state: An integer. Returns: A string used to replace the given text, if any. None if no completion candidates are found. Raises: This method is called via the readline callback. If this method raises an error, it is silently ignored by the readline library. This behavior makes debugging very difficult. For this reason, non-driver methods are run within try-except blocks. When an error occurs, the stack trace is printed to self.stderr. """ origline = readline.get_line_buffer() line = origline.lstrip() if line and line[-1] == '?': self.__driver_helper(line) else: toks = shlex.split(line) return self.__driver_completer(toks, text, state)
python
def __driver_stub(self, text, state): """Display help messages or invoke the proper completer. The interface of helper methods and completer methods are documented in the helper() decorator method and the completer() decorator method, respectively. Arguments: text: A string, that is the current completion scope. state: An integer. Returns: A string used to replace the given text, if any. None if no completion candidates are found. Raises: This method is called via the readline callback. If this method raises an error, it is silently ignored by the readline library. This behavior makes debugging very difficult. For this reason, non-driver methods are run within try-except blocks. When an error occurs, the stack trace is printed to self.stderr. """ origline = readline.get_line_buffer() line = origline.lstrip() if line and line[-1] == '?': self.__driver_helper(line) else: toks = shlex.split(line) return self.__driver_completer(toks, text, state)
[ "def", "__driver_stub", "(", "self", ",", "text", ",", "state", ")", ":", "origline", "=", "readline", ".", "get_line_buffer", "(", ")", "line", "=", "origline", ".", "lstrip", "(", ")", "if", "line", "and", "line", "[", "-", "1", "]", "==", "'?'", ":", "self", ".", "__driver_helper", "(", "line", ")", "else", ":", "toks", "=", "shlex", ".", "split", "(", "line", ")", "return", "self", ".", "__driver_completer", "(", "toks", ",", "text", ",", "state", ")" ]
Display help messages or invoke the proper completer. The interface of helper methods and completer methods are documented in the helper() decorator method and the completer() decorator method, respectively. Arguments: text: A string, that is the current completion scope. state: An integer. Returns: A string used to replace the given text, if any. None if no completion candidates are found. Raises: This method is called via the readline callback. If this method raises an error, it is silently ignored by the readline library. This behavior makes debugging very difficult. For this reason, non-driver methods are run within try-except blocks. When an error occurs, the stack trace is printed to self.stderr.
[ "Display", "help", "messages", "or", "invoke", "the", "proper", "completer", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L748-L776
250,685
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__driver_completer
def __driver_completer(self, toks, text, state): """Driver level completer. Arguments: toks: A list of tokens, tokenized from the original input line. text: A string, the text to be replaced if a completion candidate is chosen. state: An integer, the index of the candidate out of the list of candidates. Returns: A string, the candidate. """ if state != 0: return self.__completion_candidates[state] # Update the cache when this method is first called, i.e., state == 0. # If the line is empty or the user is still inputing the first token, # complete with available commands. if not toks or (len(toks) == 1 and text == toks[0]): try: self.__completion_candidates = self.__complete_cmds(text) except: self.stderr.write('\n') self.stderr.write(traceback.format_exc()) self.__completion_candidates = [] return self.__completion_candidates[state] # Otherwise, try to complete with the registered completer method. cmd = toks[0] args = toks[1:] if len(toks) > 1 else None if text and args: del args[-1] if cmd in self._completer_map.keys(): completer_name = self._completer_map[cmd] completer_method = getattr(self, completer_name) try: self.__completion_candidates = completer_method(cmd, args, text) except: self.stderr.write('\n') self.stderr.write(traceback.format_exc()) self.__completion_candidates = [] else: self.__completion_candidates = [] return self.__completion_candidates[state]
python
def __driver_completer(self, toks, text, state): """Driver level completer. Arguments: toks: A list of tokens, tokenized from the original input line. text: A string, the text to be replaced if a completion candidate is chosen. state: An integer, the index of the candidate out of the list of candidates. Returns: A string, the candidate. """ if state != 0: return self.__completion_candidates[state] # Update the cache when this method is first called, i.e., state == 0. # If the line is empty or the user is still inputing the first token, # complete with available commands. if not toks or (len(toks) == 1 and text == toks[0]): try: self.__completion_candidates = self.__complete_cmds(text) except: self.stderr.write('\n') self.stderr.write(traceback.format_exc()) self.__completion_candidates = [] return self.__completion_candidates[state] # Otherwise, try to complete with the registered completer method. cmd = toks[0] args = toks[1:] if len(toks) > 1 else None if text and args: del args[-1] if cmd in self._completer_map.keys(): completer_name = self._completer_map[cmd] completer_method = getattr(self, completer_name) try: self.__completion_candidates = completer_method(cmd, args, text) except: self.stderr.write('\n') self.stderr.write(traceback.format_exc()) self.__completion_candidates = [] else: self.__completion_candidates = [] return self.__completion_candidates[state]
[ "def", "__driver_completer", "(", "self", ",", "toks", ",", "text", ",", "state", ")", ":", "if", "state", "!=", "0", ":", "return", "self", ".", "__completion_candidates", "[", "state", "]", "# Update the cache when this method is first called, i.e., state == 0.", "# If the line is empty or the user is still inputing the first token,", "# complete with available commands.", "if", "not", "toks", "or", "(", "len", "(", "toks", ")", "==", "1", "and", "text", "==", "toks", "[", "0", "]", ")", ":", "try", ":", "self", ".", "__completion_candidates", "=", "self", ".", "__complete_cmds", "(", "text", ")", "except", ":", "self", ".", "stderr", ".", "write", "(", "'\\n'", ")", "self", ".", "stderr", ".", "write", "(", "traceback", ".", "format_exc", "(", ")", ")", "self", ".", "__completion_candidates", "=", "[", "]", "return", "self", ".", "__completion_candidates", "[", "state", "]", "# Otherwise, try to complete with the registered completer method.", "cmd", "=", "toks", "[", "0", "]", "args", "=", "toks", "[", "1", ":", "]", "if", "len", "(", "toks", ")", ">", "1", "else", "None", "if", "text", "and", "args", ":", "del", "args", "[", "-", "1", "]", "if", "cmd", "in", "self", ".", "_completer_map", ".", "keys", "(", ")", ":", "completer_name", "=", "self", ".", "_completer_map", "[", "cmd", "]", "completer_method", "=", "getattr", "(", "self", ",", "completer_name", ")", "try", ":", "self", ".", "__completion_candidates", "=", "completer_method", "(", "cmd", ",", "args", ",", "text", ")", "except", ":", "self", ".", "stderr", ".", "write", "(", "'\\n'", ")", "self", ".", "stderr", ".", "write", "(", "traceback", ".", "format_exc", "(", ")", ")", "self", ".", "__completion_candidates", "=", "[", "]", "else", ":", "self", ".", "__completion_candidates", "=", "[", "]", "return", "self", ".", "__completion_candidates", "[", "state", "]" ]
Driver level completer. Arguments: toks: A list of tokens, tokenized from the original input line. text: A string, the text to be replaced if a completion candidate is chosen. state: An integer, the index of the candidate out of the list of candidates. Returns: A string, the candidate.
[ "Driver", "level", "completer", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L778-L825
250,686
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__complete_cmds
def __complete_cmds(self, text): """Get the list of commands whose names start with a given text.""" return [ name for name in self._cmd_map_visible.keys() if name.startswith(text) ]
python
def __complete_cmds(self, text): """Get the list of commands whose names start with a given text.""" return [ name for name in self._cmd_map_visible.keys() if name.startswith(text) ]
[ "def", "__complete_cmds", "(", "self", ",", "text", ")", ":", "return", "[", "name", "for", "name", "in", "self", ".", "_cmd_map_visible", ".", "keys", "(", ")", "if", "name", ".", "startswith", "(", "text", ")", "]" ]
Get the list of commands whose names start with a given text.
[ "Get", "the", "list", "of", "commands", "whose", "names", "start", "with", "a", "given", "text", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L827-L829
250,687
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__driver_helper
def __driver_helper(self, line): """Driver level helper method. 1. Display help message for the given input. Internally calls self.__get_help_message() to obtain the help message. 2. Re-display the prompt and the input line. Arguments: line: The input line. Raises: Errors from helper methods print stack trace without terminating this shell. Other exceptions will terminate this shell. """ if line.strip() == '?': self.stdout.write('\n') self.stdout.write(self.doc_string()) else: toks = shlex.split(line[:-1]) try: msg = self.__get_help_message(toks) except Exception as e: self.stderr.write('\n') self.stderr.write(traceback.format_exc()) self.stderr.flush() self.stdout.write('\n') self.stdout.write(msg) # Restore the prompt and the original input. self.stdout.write('\n') self.stdout.write(self.prompt) self.stdout.write(line) self.stdout.flush()
python
def __driver_helper(self, line): """Driver level helper method. 1. Display help message for the given input. Internally calls self.__get_help_message() to obtain the help message. 2. Re-display the prompt and the input line. Arguments: line: The input line. Raises: Errors from helper methods print stack trace without terminating this shell. Other exceptions will terminate this shell. """ if line.strip() == '?': self.stdout.write('\n') self.stdout.write(self.doc_string()) else: toks = shlex.split(line[:-1]) try: msg = self.__get_help_message(toks) except Exception as e: self.stderr.write('\n') self.stderr.write(traceback.format_exc()) self.stderr.flush() self.stdout.write('\n') self.stdout.write(msg) # Restore the prompt and the original input. self.stdout.write('\n') self.stdout.write(self.prompt) self.stdout.write(line) self.stdout.flush()
[ "def", "__driver_helper", "(", "self", ",", "line", ")", ":", "if", "line", ".", "strip", "(", ")", "==", "'?'", ":", "self", ".", "stdout", ".", "write", "(", "'\\n'", ")", "self", ".", "stdout", ".", "write", "(", "self", ".", "doc_string", "(", ")", ")", "else", ":", "toks", "=", "shlex", ".", "split", "(", "line", "[", ":", "-", "1", "]", ")", "try", ":", "msg", "=", "self", ".", "__get_help_message", "(", "toks", ")", "except", "Exception", "as", "e", ":", "self", ".", "stderr", ".", "write", "(", "'\\n'", ")", "self", ".", "stderr", ".", "write", "(", "traceback", ".", "format_exc", "(", ")", ")", "self", ".", "stderr", ".", "flush", "(", ")", "self", ".", "stdout", ".", "write", "(", "'\\n'", ")", "self", ".", "stdout", ".", "write", "(", "msg", ")", "# Restore the prompt and the original input.", "self", ".", "stdout", ".", "write", "(", "'\\n'", ")", "self", ".", "stdout", ".", "write", "(", "self", ".", "prompt", ")", "self", ".", "stdout", ".", "write", "(", "line", ")", "self", ".", "stdout", ".", "flush", "(", ")" ]
Driver level helper method. 1. Display help message for the given input. Internally calls self.__get_help_message() to obtain the help message. 2. Re-display the prompt and the input line. Arguments: line: The input line. Raises: Errors from helper methods print stack trace without terminating this shell. Other exceptions will terminate this shell.
[ "Driver", "level", "helper", "method", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L831-L862
250,688
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__build_cmd_maps
def __build_cmd_maps(cls): """Build the mapping from command names to method names. One command name maps to at most one method. Multiple command names can map to the same method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Returns: A tuple (cmd_map, hidden_cmd_map, internal_cmd_map). """ cmd_map_all = {} cmd_map_visible = {} cmd_map_internal = {} for name in dir(cls): obj = getattr(cls, name) if iscommand(obj): for cmd in getcommands(obj): if cmd in cmd_map_all.keys(): raise PyShellError("The command '{}' already has cmd" " method '{}', cannot register a" " second method '{}'.".format( \ cmd, cmd_map_all[cmd], obj.__name__)) cmd_map_all[cmd] = obj.__name__ if isvisiblecommand(obj): cmd_map_visible[cmd] = obj.__name__ if isinternalcommand(obj): cmd_map_internal[cmd] = obj.__name__ return cmd_map_all, cmd_map_visible, cmd_map_internal
python
def __build_cmd_maps(cls): """Build the mapping from command names to method names. One command name maps to at most one method. Multiple command names can map to the same method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Returns: A tuple (cmd_map, hidden_cmd_map, internal_cmd_map). """ cmd_map_all = {} cmd_map_visible = {} cmd_map_internal = {} for name in dir(cls): obj = getattr(cls, name) if iscommand(obj): for cmd in getcommands(obj): if cmd in cmd_map_all.keys(): raise PyShellError("The command '{}' already has cmd" " method '{}', cannot register a" " second method '{}'.".format( \ cmd, cmd_map_all[cmd], obj.__name__)) cmd_map_all[cmd] = obj.__name__ if isvisiblecommand(obj): cmd_map_visible[cmd] = obj.__name__ if isinternalcommand(obj): cmd_map_internal[cmd] = obj.__name__ return cmd_map_all, cmd_map_visible, cmd_map_internal
[ "def", "__build_cmd_maps", "(", "cls", ")", ":", "cmd_map_all", "=", "{", "}", "cmd_map_visible", "=", "{", "}", "cmd_map_internal", "=", "{", "}", "for", "name", "in", "dir", "(", "cls", ")", ":", "obj", "=", "getattr", "(", "cls", ",", "name", ")", "if", "iscommand", "(", "obj", ")", ":", "for", "cmd", "in", "getcommands", "(", "obj", ")", ":", "if", "cmd", "in", "cmd_map_all", ".", "keys", "(", ")", ":", "raise", "PyShellError", "(", "\"The command '{}' already has cmd\"", "\" method '{}', cannot register a\"", "\" second method '{}'.\"", ".", "format", "(", "cmd", ",", "cmd_map_all", "[", "cmd", "]", ",", "obj", ".", "__name__", ")", ")", "cmd_map_all", "[", "cmd", "]", "=", "obj", ".", "__name__", "if", "isvisiblecommand", "(", "obj", ")", ":", "cmd_map_visible", "[", "cmd", "]", "=", "obj", ".", "__name__", "if", "isinternalcommand", "(", "obj", ")", ":", "cmd_map_internal", "[", "cmd", "]", "=", "obj", ".", "__name__", "return", "cmd_map_all", ",", "cmd_map_visible", ",", "cmd_map_internal" ]
Build the mapping from command names to method names. One command name maps to at most one method. Multiple command names can map to the same method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Returns: A tuple (cmd_map, hidden_cmd_map, internal_cmd_map).
[ "Build", "the", "mapping", "from", "command", "names", "to", "method", "names", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L913-L942
250,689
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__build_helper_map
def __build_helper_map(cls): """Build a mapping from command names to helper names. One command name maps to at most one helper method. Multiple command names can map to the same helper method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Raises: PyShellError: A command maps to multiple helper methods. """ ret = {} for name in dir(cls): obj = getattr(cls, name) if ishelper(obj): for cmd in obj.__help_targets__: if cmd in ret.keys(): raise PyShellError("The command '{}' already has helper" " method '{}', cannot register a" " second method '{}'.".format( \ cmd, ret[cmd], obj.__name__)) ret[cmd] = obj.__name__ return ret
python
def __build_helper_map(cls): """Build a mapping from command names to helper names. One command name maps to at most one helper method. Multiple command names can map to the same helper method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Raises: PyShellError: A command maps to multiple helper methods. """ ret = {} for name in dir(cls): obj = getattr(cls, name) if ishelper(obj): for cmd in obj.__help_targets__: if cmd in ret.keys(): raise PyShellError("The command '{}' already has helper" " method '{}', cannot register a" " second method '{}'.".format( \ cmd, ret[cmd], obj.__name__)) ret[cmd] = obj.__name__ return ret
[ "def", "__build_helper_map", "(", "cls", ")", ":", "ret", "=", "{", "}", "for", "name", "in", "dir", "(", "cls", ")", ":", "obj", "=", "getattr", "(", "cls", ",", "name", ")", "if", "ishelper", "(", "obj", ")", ":", "for", "cmd", "in", "obj", ".", "__help_targets__", ":", "if", "cmd", "in", "ret", ".", "keys", "(", ")", ":", "raise", "PyShellError", "(", "\"The command '{}' already has helper\"", "\" method '{}', cannot register a\"", "\" second method '{}'.\"", ".", "format", "(", "cmd", ",", "ret", "[", "cmd", "]", ",", "obj", ".", "__name__", ")", ")", "ret", "[", "cmd", "]", "=", "obj", ".", "__name__", "return", "ret" ]
Build a mapping from command names to helper names. One command name maps to at most one helper method. Multiple command names can map to the same helper method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Raises: PyShellError: A command maps to multiple helper methods.
[ "Build", "a", "mapping", "from", "command", "names", "to", "helper", "names", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L945-L968
250,690
qzmfranklin/easyshell
easyshell/base.py
_ShellBase.__build_completer_map
def __build_completer_map(cls): """Build a mapping from command names to completer names. One command name maps to at most one completer method. Multiple command names can map to the same completer method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Raises: PyShellError: A command maps to multiple helper methods. """ ret = {} for name in dir(cls): obj = getattr(cls, name) if iscompleter(obj): for cmd in obj.__complete_targets__: if cmd in ret.keys(): raise PyShellError("The command '{}' already has" " complter" " method '{}', cannot register a" " second method '{}'.".format( \ cmd, ret[cmd], obj.__name__)) ret[cmd] = obj.__name__ return ret
python
def __build_completer_map(cls): """Build a mapping from command names to completer names. One command name maps to at most one completer method. Multiple command names can map to the same completer method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Raises: PyShellError: A command maps to multiple helper methods. """ ret = {} for name in dir(cls): obj = getattr(cls, name) if iscompleter(obj): for cmd in obj.__complete_targets__: if cmd in ret.keys(): raise PyShellError("The command '{}' already has" " complter" " method '{}', cannot register a" " second method '{}'.".format( \ cmd, ret[cmd], obj.__name__)) ret[cmd] = obj.__name__ return ret
[ "def", "__build_completer_map", "(", "cls", ")", ":", "ret", "=", "{", "}", "for", "name", "in", "dir", "(", "cls", ")", ":", "obj", "=", "getattr", "(", "cls", ",", "name", ")", "if", "iscompleter", "(", "obj", ")", ":", "for", "cmd", "in", "obj", ".", "__complete_targets__", ":", "if", "cmd", "in", "ret", ".", "keys", "(", ")", ":", "raise", "PyShellError", "(", "\"The command '{}' already has\"", "\" complter\"", "\" method '{}', cannot register a\"", "\" second method '{}'.\"", ".", "format", "(", "cmd", ",", "ret", "[", "cmd", "]", ",", "obj", ".", "__name__", ")", ")", "ret", "[", "cmd", "]", "=", "obj", ".", "__name__", "return", "ret" ]
Build a mapping from command names to completer names. One command name maps to at most one completer method. Multiple command names can map to the same completer method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Raises: PyShellError: A command maps to multiple helper methods.
[ "Build", "a", "mapping", "from", "command", "names", "to", "completer", "names", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/base.py#L971-L995
250,691
rgmining/ria
ria/credibility.py
GraphBasedCredibility.review_score
def review_score(self, reviewer, product): """Find a review score from a given reviewer to a product. Args: reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`. product: Product i.e. an instance of :class:`ria.bipartite.Product`. Returns: A review object representing the review from the reviewer to the product. """ return self._g.retrieve_review(reviewer, product).score
python
def review_score(self, reviewer, product): """Find a review score from a given reviewer to a product. Args: reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`. product: Product i.e. an instance of :class:`ria.bipartite.Product`. Returns: A review object representing the review from the reviewer to the product. """ return self._g.retrieve_review(reviewer, product).score
[ "def", "review_score", "(", "self", ",", "reviewer", ",", "product", ")", ":", "return", "self", ".", "_g", ".", "retrieve_review", "(", "reviewer", ",", "product", ")", ".", "score" ]
Find a review score from a given reviewer to a product. Args: reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`. product: Product i.e. an instance of :class:`ria.bipartite.Product`. Returns: A review object representing the review from the reviewer to the product.
[ "Find", "a", "review", "score", "from", "a", "given", "reviewer", "to", "a", "product", "." ]
39223c67b7e59e10bd8e3a9062fb13f8bf893a5d
https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/credibility.py#L109-L119
250,692
tducret/precisionmapper-python
python-flask/swagger_server/models/base_model_.py
Model.from_dict
def from_dict(cls: typing.Type[T], dikt) -> T: """Returns the dict as a model""" return util.deserialize_model(dikt, cls)
python
def from_dict(cls: typing.Type[T], dikt) -> T: """Returns the dict as a model""" return util.deserialize_model(dikt, cls)
[ "def", "from_dict", "(", "cls", ":", "typing", ".", "Type", "[", "T", "]", ",", "dikt", ")", "->", "T", ":", "return", "util", ".", "deserialize_model", "(", "dikt", ",", "cls", ")" ]
Returns the dict as a model
[ "Returns", "the", "dict", "as", "a", "model" ]
462dcc5bccf6edec780b8b7bc42e8c1d717db942
https://github.com/tducret/precisionmapper-python/blob/462dcc5bccf6edec780b8b7bc42e8c1d717db942/python-flask/swagger_server/models/base_model_.py#L21-L23
250,693
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
RdfBaseFactory.get_defs
def get_defs(self, cache=True): """ Gets the defitions args: cache: True will read from the file cache, False queries the triplestore """ log.debug(" *** Started") cache = self.__use_cache__(cache) if cache: log.info(" loading json cache") try: with open(self.cache_filepath) as file_obj: self.results = json.loads(file_obj.read()) except FileNotFoundError: self.results = [] if not cache or len(self.results) == 0: log.info(" NO CACHE, querying the triplestore") sparql = render_without_request(self.def_sparql, graph=self.conn.graph, prefix=self.nsm.prefix()) start = datetime.datetime.now() log.info(" Starting query") self.results = self.conn.query(sparql) log.info("query complete in: %s | %s triples retrieved.", (datetime.datetime.now() - start), len(self.results)) with open(self.cache_filepath, "w") as file_obj: file_obj.write(json.dumps(self.results, indent=4)) with open(self.loaded_filepath, "w") as file_obj: file_obj.write((json.dumps(self.conn.mgr.loaded)))
python
def get_defs(self, cache=True): """ Gets the defitions args: cache: True will read from the file cache, False queries the triplestore """ log.debug(" *** Started") cache = self.__use_cache__(cache) if cache: log.info(" loading json cache") try: with open(self.cache_filepath) as file_obj: self.results = json.loads(file_obj.read()) except FileNotFoundError: self.results = [] if not cache or len(self.results) == 0: log.info(" NO CACHE, querying the triplestore") sparql = render_without_request(self.def_sparql, graph=self.conn.graph, prefix=self.nsm.prefix()) start = datetime.datetime.now() log.info(" Starting query") self.results = self.conn.query(sparql) log.info("query complete in: %s | %s triples retrieved.", (datetime.datetime.now() - start), len(self.results)) with open(self.cache_filepath, "w") as file_obj: file_obj.write(json.dumps(self.results, indent=4)) with open(self.loaded_filepath, "w") as file_obj: file_obj.write((json.dumps(self.conn.mgr.loaded)))
[ "def", "get_defs", "(", "self", ",", "cache", "=", "True", ")", ":", "log", ".", "debug", "(", "\" *** Started\"", ")", "cache", "=", "self", ".", "__use_cache__", "(", "cache", ")", "if", "cache", ":", "log", ".", "info", "(", "\" loading json cache\"", ")", "try", ":", "with", "open", "(", "self", ".", "cache_filepath", ")", "as", "file_obj", ":", "self", ".", "results", "=", "json", ".", "loads", "(", "file_obj", ".", "read", "(", ")", ")", "except", "FileNotFoundError", ":", "self", ".", "results", "=", "[", "]", "if", "not", "cache", "or", "len", "(", "self", ".", "results", ")", "==", "0", ":", "log", ".", "info", "(", "\" NO CACHE, querying the triplestore\"", ")", "sparql", "=", "render_without_request", "(", "self", ".", "def_sparql", ",", "graph", "=", "self", ".", "conn", ".", "graph", ",", "prefix", "=", "self", ".", "nsm", ".", "prefix", "(", ")", ")", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "log", ".", "info", "(", "\" Starting query\"", ")", "self", ".", "results", "=", "self", ".", "conn", ".", "query", "(", "sparql", ")", "log", ".", "info", "(", "\"query complete in: %s | %s triples retrieved.\"", ",", "(", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "start", ")", ",", "len", "(", "self", ".", "results", ")", ")", "with", "open", "(", "self", ".", "cache_filepath", ",", "\"w\"", ")", "as", "file_obj", ":", "file_obj", ".", "write", "(", "json", ".", "dumps", "(", "self", ".", "results", ",", "indent", "=", "4", ")", ")", "with", "open", "(", "self", ".", "loaded_filepath", ",", "\"w\"", ")", "as", "file_obj", ":", "file_obj", ".", "write", "(", "(", "json", ".", "dumps", "(", "self", ".", "conn", ".", "mgr", ".", "loaded", ")", ")", ")" ]
Gets the defitions args: cache: True will read from the file cache, False queries the triplestore
[ "Gets", "the", "defitions" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L96-L127
250,694
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
RdfBaseFactory.conv_defs
def conv_defs(self): """ Reads through the JSON object and converts them to Dataset """ log.setLevel(self.log_level) start = datetime.datetime.now() log.debug(" Converting to a Dataset: %s Triples", len(self.results)) self.defs = RdfDataset(self.results, def_load=True, bnode_only=True) # self.cfg.__setattr__('rdf_prop_defs', self.defs, True) log.debug(" conv complete in: %s" % (datetime.datetime.now() - start))
python
def conv_defs(self): """ Reads through the JSON object and converts them to Dataset """ log.setLevel(self.log_level) start = datetime.datetime.now() log.debug(" Converting to a Dataset: %s Triples", len(self.results)) self.defs = RdfDataset(self.results, def_load=True, bnode_only=True) # self.cfg.__setattr__('rdf_prop_defs', self.defs, True) log.debug(" conv complete in: %s" % (datetime.datetime.now() - start))
[ "def", "conv_defs", "(", "self", ")", ":", "log", ".", "setLevel", "(", "self", ".", "log_level", ")", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "log", ".", "debug", "(", "\" Converting to a Dataset: %s Triples\"", ",", "len", "(", "self", ".", "results", ")", ")", "self", ".", "defs", "=", "RdfDataset", "(", "self", ".", "results", ",", "def_load", "=", "True", ",", "bnode_only", "=", "True", ")", "# self.cfg.__setattr__('rdf_prop_defs', self.defs, True)", "log", ".", "debug", "(", "\" conv complete in: %s\"", "%", "(", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "start", ")", ")" ]
Reads through the JSON object and converts them to Dataset
[ "Reads", "through", "the", "JSON", "object", "and", "converts", "them", "to", "Dataset" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L129-L140
250,695
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
RdfClassFactory.set_class_dict
def set_class_dict(self): """ Reads through the dataset and assigns self.class_dict the key value pairs for the classes in the dataset """ self.class_dict = {} for name, cls_defs in self.defs.items(): def_type = set(cls_defs.get(self.rdf_type, [])) if name.type == 'bnode': continue # a class can be determined by checking to see if it is of an # rdf_type listed in the classes_key or has a property that is # listed in the inferred_key if def_type.intersection(self.classes_key) or \ list([cls_defs.get(item) for item in self.inferred_key]): self.class_dict[name] = cls_defs
python
def set_class_dict(self): """ Reads through the dataset and assigns self.class_dict the key value pairs for the classes in the dataset """ self.class_dict = {} for name, cls_defs in self.defs.items(): def_type = set(cls_defs.get(self.rdf_type, [])) if name.type == 'bnode': continue # a class can be determined by checking to see if it is of an # rdf_type listed in the classes_key or has a property that is # listed in the inferred_key if def_type.intersection(self.classes_key) or \ list([cls_defs.get(item) for item in self.inferred_key]): self.class_dict[name] = cls_defs
[ "def", "set_class_dict", "(", "self", ")", ":", "self", ".", "class_dict", "=", "{", "}", "for", "name", ",", "cls_defs", "in", "self", ".", "defs", ".", "items", "(", ")", ":", "def_type", "=", "set", "(", "cls_defs", ".", "get", "(", "self", ".", "rdf_type", ",", "[", "]", ")", ")", "if", "name", ".", "type", "==", "'bnode'", ":", "continue", "# a class can be determined by checking to see if it is of an", "# rdf_type listed in the classes_key or has a property that is", "# listed in the inferred_key", "if", "def_type", ".", "intersection", "(", "self", ".", "classes_key", ")", "or", "list", "(", "[", "cls_defs", ".", "get", "(", "item", ")", "for", "item", "in", "self", ".", "inferred_key", "]", ")", ":", "self", ".", "class_dict", "[", "name", "]", "=", "cls_defs" ]
Reads through the dataset and assigns self.class_dict the key value pairs for the classes in the dataset
[ "Reads", "through", "the", "dataset", "and", "assigns", "self", ".", "class_dict", "the", "key", "value", "pairs", "for", "the", "classes", "in", "the", "dataset" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L266-L281
250,696
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdffactories.py
RdfClassFactory.tie_properties
def tie_properties(self, class_list): """ Runs through the classess and ties the properties to the class args: class_list: a list of class names to run """ log.setLevel(self.log_level) start = datetime.datetime.now() log.info(" Tieing properties to the class") for cls_name in class_list: cls_obj = getattr(MODULE.rdfclass, cls_name) prop_dict = dict(cls_obj.properties) for prop_name, prop_obj in cls_obj.properties.items(): setattr(cls_obj, prop_name, link_property(prop_obj, cls_obj)) log.info(" Finished tieing properties in: %s", (datetime.datetime.now() - start))
python
def tie_properties(self, class_list): """ Runs through the classess and ties the properties to the class args: class_list: a list of class names to run """ log.setLevel(self.log_level) start = datetime.datetime.now() log.info(" Tieing properties to the class") for cls_name in class_list: cls_obj = getattr(MODULE.rdfclass, cls_name) prop_dict = dict(cls_obj.properties) for prop_name, prop_obj in cls_obj.properties.items(): setattr(cls_obj, prop_name, link_property(prop_obj, cls_obj)) log.info(" Finished tieing properties in: %s", (datetime.datetime.now() - start))
[ "def", "tie_properties", "(", "self", ",", "class_list", ")", ":", "log", ".", "setLevel", "(", "self", ".", "log_level", ")", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "log", ".", "info", "(", "\" Tieing properties to the class\"", ")", "for", "cls_name", "in", "class_list", ":", "cls_obj", "=", "getattr", "(", "MODULE", ".", "rdfclass", ",", "cls_name", ")", "prop_dict", "=", "dict", "(", "cls_obj", ".", "properties", ")", "for", "prop_name", ",", "prop_obj", "in", "cls_obj", ".", "properties", ".", "items", "(", ")", ":", "setattr", "(", "cls_obj", ",", "prop_name", ",", "link_property", "(", "prop_obj", ",", "cls_obj", ")", ")", "log", ".", "info", "(", "\" Finished tieing properties in: %s\"", ",", "(", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "start", ")", ")" ]
Runs through the classess and ties the properties to the class args: class_list: a list of class names to run
[ "Runs", "through", "the", "classess", "and", "ties", "the", "properties", "to", "the", "class" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdffactories.py#L283-L298
250,697
ariebovenberg/valuable
valuable/xml.py
elemgetter
def elemgetter(path: str) -> t.Callable[[Element], Element]: """shortcut making an XML element getter""" return compose( partial(_raise_if_none, exc=LookupError(path)), methodcaller('find', path) )
python
def elemgetter(path: str) -> t.Callable[[Element], Element]: """shortcut making an XML element getter""" return compose( partial(_raise_if_none, exc=LookupError(path)), methodcaller('find', path) )
[ "def", "elemgetter", "(", "path", ":", "str", ")", "->", "t", ".", "Callable", "[", "[", "Element", "]", ",", "Element", "]", ":", "return", "compose", "(", "partial", "(", "_raise_if_none", ",", "exc", "=", "LookupError", "(", "path", ")", ")", ",", "methodcaller", "(", "'find'", ",", "path", ")", ")" ]
shortcut making an XML element getter
[ "shortcut", "making", "an", "XML", "element", "getter" ]
72ac98b5a044233f13d14a9b9f273ce3a237d9ae
https://github.com/ariebovenberg/valuable/blob/72ac98b5a044233f13d14a9b9f273ce3a237d9ae/valuable/xml.py#L15-L20
250,698
ariebovenberg/valuable
valuable/xml.py
textgetter
def textgetter(path: str, *, default: T=NO_DEFAULT, strip: bool=False) -> t.Callable[[Element], t.Union[str, T]]: """shortcut for making an XML element text getter""" find = compose( str.strip if strip else identity, partial(_raise_if_none, exc=LookupError(path)), methodcaller('findtext', path) ) return (find if default is NO_DEFAULT else lookup_defaults(find, default))
python
def textgetter(path: str, *, default: T=NO_DEFAULT, strip: bool=False) -> t.Callable[[Element], t.Union[str, T]]: """shortcut for making an XML element text getter""" find = compose( str.strip if strip else identity, partial(_raise_if_none, exc=LookupError(path)), methodcaller('findtext', path) ) return (find if default is NO_DEFAULT else lookup_defaults(find, default))
[ "def", "textgetter", "(", "path", ":", "str", ",", "*", ",", "default", ":", "T", "=", "NO_DEFAULT", ",", "strip", ":", "bool", "=", "False", ")", "->", "t", ".", "Callable", "[", "[", "Element", "]", ",", "t", ".", "Union", "[", "str", ",", "T", "]", "]", ":", "find", "=", "compose", "(", "str", ".", "strip", "if", "strip", "else", "identity", ",", "partial", "(", "_raise_if_none", ",", "exc", "=", "LookupError", "(", "path", ")", ")", ",", "methodcaller", "(", "'findtext'", ",", "path", ")", ")", "return", "(", "find", "if", "default", "is", "NO_DEFAULT", "else", "lookup_defaults", "(", "find", ",", "default", ")", ")" ]
shortcut for making an XML element text getter
[ "shortcut", "for", "making", "an", "XML", "element", "text", "getter" ]
72ac98b5a044233f13d14a9b9f273ce3a237d9ae
https://github.com/ariebovenberg/valuable/blob/72ac98b5a044233f13d14a9b9f273ce3a237d9ae/valuable/xml.py#L35-L44
250,699
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/cpress_cz.py
_parse_alt_url
def _parse_alt_url(html_chunk): """ Parse URL from alternative location if not found where it should be. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: str: Book's URL. """ url_list = html_chunk.find("a", fn=has_param("href")) url_list = map(lambda x: x.params["href"], url_list) url_list = filter(lambda x: not x.startswith("autori/"), url_list) if not url_list: return None return normalize_url(BASE_URL, url_list[0])
python
def _parse_alt_url(html_chunk): """ Parse URL from alternative location if not found where it should be. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: str: Book's URL. """ url_list = html_chunk.find("a", fn=has_param("href")) url_list = map(lambda x: x.params["href"], url_list) url_list = filter(lambda x: not x.startswith("autori/"), url_list) if not url_list: return None return normalize_url(BASE_URL, url_list[0])
[ "def", "_parse_alt_url", "(", "html_chunk", ")", ":", "url_list", "=", "html_chunk", ".", "find", "(", "\"a\"", ",", "fn", "=", "has_param", "(", "\"href\"", ")", ")", "url_list", "=", "map", "(", "lambda", "x", ":", "x", ".", "params", "[", "\"href\"", "]", ",", "url_list", ")", "url_list", "=", "filter", "(", "lambda", "x", ":", "not", "x", ".", "startswith", "(", "\"autori/\"", ")", ",", "url_list", ")", "if", "not", "url_list", ":", "return", "None", "return", "normalize_url", "(", "BASE_URL", ",", "url_list", "[", "0", "]", ")" ]
Parse URL from alternative location if not found where it should be. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: str: Book's URL.
[ "Parse", "URL", "from", "alternative", "location", "if", "not", "found", "where", "it", "should", "be", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/cpress_cz.py#L45-L62