id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
244,600
tlatsas/wigiki
wigiki/config.py
ConfigManager.cli
def cli(self): """Read program parameters from command line and configuration files We support both command line arguments and configuration files. The command line arguments have always precedence over any configuration file parameters. This allows us to have most of our options in files but override them individually from the command line. """ # first we parse only for a configuration file with an initial parser init_parser = argparse.ArgumentParser( description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter, add_help = False) # we don't use a file metavar because we need to support both json/yml init_parser.add_argument("-c", "--config", action="store", help = "read from target configuration file") args, remaining_args = init_parser.parse_known_args() # read from supplied configuration file or try to find one in the # current working directory reader = None config_file = args.config or self.detect_config() if config_file: with open(config_file, 'r') as f: reader = ConfigReader(f.read()) # implement the rest cli options parser = argparse.ArgumentParser( parents = [init_parser], add_help = True, description = "Static wiki generator using Github's gists as pages") application_opts = reader.application if reader else {} default_options = self.merge_with_default_options(application_opts) parser.set_defaults(**default_options) parser.add_argument("-v", "--version", action="version", version="%(prog)s {0}".format(__version__)) parser.add_argument("-t", "--templates", action="store", help="read templates from specified folder") parser.add_argument("-o", "--output", action="store", help="generate static files in target folder") parser.add_argument("-u", "--baseurl", action="store", help="use a specific base URL instead of /") if reader: self.config = reader.config self.config['app'] = vars(parser.parse_args(remaining_args)) # parsing of command line argumenents is done check if we have gists if 'gists' not in self.config: raise WigikiConfigError("Cannot read gists. " "Check your configuration file.")
python
def cli(self): """Read program parameters from command line and configuration files We support both command line arguments and configuration files. The command line arguments have always precedence over any configuration file parameters. This allows us to have most of our options in files but override them individually from the command line. """ # first we parse only for a configuration file with an initial parser init_parser = argparse.ArgumentParser( description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter, add_help = False) # we don't use a file metavar because we need to support both json/yml init_parser.add_argument("-c", "--config", action="store", help = "read from target configuration file") args, remaining_args = init_parser.parse_known_args() # read from supplied configuration file or try to find one in the # current working directory reader = None config_file = args.config or self.detect_config() if config_file: with open(config_file, 'r') as f: reader = ConfigReader(f.read()) # implement the rest cli options parser = argparse.ArgumentParser( parents = [init_parser], add_help = True, description = "Static wiki generator using Github's gists as pages") application_opts = reader.application if reader else {} default_options = self.merge_with_default_options(application_opts) parser.set_defaults(**default_options) parser.add_argument("-v", "--version", action="version", version="%(prog)s {0}".format(__version__)) parser.add_argument("-t", "--templates", action="store", help="read templates from specified folder") parser.add_argument("-o", "--output", action="store", help="generate static files in target folder") parser.add_argument("-u", "--baseurl", action="store", help="use a specific base URL instead of /") if reader: self.config = reader.config self.config['app'] = vars(parser.parse_args(remaining_args)) # parsing of command line argumenents is done check if we have gists if 'gists' not in self.config: raise WigikiConfigError("Cannot read gists. " "Check your configuration file.")
[ "def", "cli", "(", "self", ")", ":", "# first we parse only for a configuration file with an initial parser", "init_parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "__doc__", ",", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ",", "add_help", "=", "False", ")", "# we don't use a file metavar because we need to support both json/yml", "init_parser", ".", "add_argument", "(", "\"-c\"", ",", "\"--config\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"read from target configuration file\"", ")", "args", ",", "remaining_args", "=", "init_parser", ".", "parse_known_args", "(", ")", "# read from supplied configuration file or try to find one in the", "# current working directory", "reader", "=", "None", "config_file", "=", "args", ".", "config", "or", "self", ".", "detect_config", "(", ")", "if", "config_file", ":", "with", "open", "(", "config_file", ",", "'r'", ")", "as", "f", ":", "reader", "=", "ConfigReader", "(", "f", ".", "read", "(", ")", ")", "# implement the rest cli options", "parser", "=", "argparse", ".", "ArgumentParser", "(", "parents", "=", "[", "init_parser", "]", ",", "add_help", "=", "True", ",", "description", "=", "\"Static wiki generator using Github's gists as pages\"", ")", "application_opts", "=", "reader", ".", "application", "if", "reader", "else", "{", "}", "default_options", "=", "self", ".", "merge_with_default_options", "(", "application_opts", ")", "parser", ".", "set_defaults", "(", "*", "*", "default_options", ")", "parser", ".", "add_argument", "(", "\"-v\"", ",", "\"--version\"", ",", "action", "=", "\"version\"", ",", "version", "=", "\"%(prog)s {0}\"", ".", "format", "(", "__version__", ")", ")", "parser", ".", "add_argument", "(", "\"-t\"", ",", "\"--templates\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"read templates from specified folder\"", ")", "parser", ".", "add_argument", "(", "\"-o\"", ",", "\"--output\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"generate static files in target folder\"", ")", "parser", ".", "add_argument", "(", "\"-u\"", ",", "\"--baseurl\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"use a specific base URL instead of /\"", ")", "if", "reader", ":", "self", ".", "config", "=", "reader", ".", "config", "self", ".", "config", "[", "'app'", "]", "=", "vars", "(", "parser", ".", "parse_args", "(", "remaining_args", ")", ")", "# parsing of command line argumenents is done check if we have gists", "if", "'gists'", "not", "in", "self", ".", "config", ":", "raise", "WigikiConfigError", "(", "\"Cannot read gists. \"", "\"Check your configuration file.\"", ")" ]
Read program parameters from command line and configuration files We support both command line arguments and configuration files. The command line arguments have always precedence over any configuration file parameters. This allows us to have most of our options in files but override them individually from the command line.
[ "Read", "program", "parameters", "from", "command", "line", "and", "configuration", "files" ]
baf9c5a6523a9b90db7572330d04e3e199391273
https://github.com/tlatsas/wigiki/blob/baf9c5a6523a9b90db7572330d04e3e199391273/wigiki/config.py#L46-L104
244,601
tlatsas/wigiki
wigiki/config.py
ConfigManager.detect_config
def detect_config(self): """check in the current working directory for configuration files""" default_files = ("config.json", "config.yml") for file_ in default_files: if os.path.exists(file_): return file_
python
def detect_config(self): """check in the current working directory for configuration files""" default_files = ("config.json", "config.yml") for file_ in default_files: if os.path.exists(file_): return file_
[ "def", "detect_config", "(", "self", ")", ":", "default_files", "=", "(", "\"config.json\"", ",", "\"config.yml\"", ")", "for", "file_", "in", "default_files", ":", "if", "os", ".", "path", ".", "exists", "(", "file_", ")", ":", "return", "file_" ]
check in the current working directory for configuration files
[ "check", "in", "the", "current", "working", "directory", "for", "configuration", "files" ]
baf9c5a6523a9b90db7572330d04e3e199391273
https://github.com/tlatsas/wigiki/blob/baf9c5a6523a9b90db7572330d04e3e199391273/wigiki/config.py#L106-L111
244,602
tlatsas/wigiki
wigiki/config.py
ConfigManager.merge_with_default_options
def merge_with_default_options(self, config_opts): """merge options from configuration file with the default options""" return dict(list(self.defaults.items()) + list(config_opts.items()))
python
def merge_with_default_options(self, config_opts): """merge options from configuration file with the default options""" return dict(list(self.defaults.items()) + list(config_opts.items()))
[ "def", "merge_with_default_options", "(", "self", ",", "config_opts", ")", ":", "return", "dict", "(", "list", "(", "self", ".", "defaults", ".", "items", "(", ")", ")", "+", "list", "(", "config_opts", ".", "items", "(", ")", ")", ")" ]
merge options from configuration file with the default options
[ "merge", "options", "from", "configuration", "file", "with", "the", "default", "options" ]
baf9c5a6523a9b90db7572330d04e3e199391273
https://github.com/tlatsas/wigiki/blob/baf9c5a6523a9b90db7572330d04e3e199391273/wigiki/config.py#L113-L115
244,603
Kjwon15/autotweet
autotweet/twitter.py
authorize
def authorize(): """Authorize to twitter. Use PIN authentification. :returns: Token for authentificate with Twitter. :rtype: :class:`autotweet.twitter.OAuthToken` """ auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) url = auth.get_authorization_url() print('Open this url on your webbrowser: {0}'.format(url)) webbrowser.open(url) pin = input('Input verification number here: ').strip() token_key, token_secret = auth.get_access_token(verifier=pin) return OAuthToken(token_key, token_secret)
python
def authorize(): """Authorize to twitter. Use PIN authentification. :returns: Token for authentificate with Twitter. :rtype: :class:`autotweet.twitter.OAuthToken` """ auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) url = auth.get_authorization_url() print('Open this url on your webbrowser: {0}'.format(url)) webbrowser.open(url) pin = input('Input verification number here: ').strip() token_key, token_secret = auth.get_access_token(verifier=pin) return OAuthToken(token_key, token_secret)
[ "def", "authorize", "(", ")", ":", "auth", "=", "tweepy", ".", "OAuthHandler", "(", "CONSUMER_KEY", ",", "CONSUMER_SECRET", ")", "url", "=", "auth", ".", "get_authorization_url", "(", ")", "print", "(", "'Open this url on your webbrowser: {0}'", ".", "format", "(", "url", ")", ")", "webbrowser", ".", "open", "(", "url", ")", "pin", "=", "input", "(", "'Input verification number here: '", ")", ".", "strip", "(", ")", "token_key", ",", "token_secret", "=", "auth", ".", "get_access_token", "(", "verifier", "=", "pin", ")", "return", "OAuthToken", "(", "token_key", ",", "token_secret", ")" ]
Authorize to twitter. Use PIN authentification. :returns: Token for authentificate with Twitter. :rtype: :class:`autotweet.twitter.OAuthToken`
[ "Authorize", "to", "twitter", "." ]
c35b68ee1814916fbe9e5a5bd6ea6e75b3cc596e
https://github.com/Kjwon15/autotweet/blob/c35b68ee1814916fbe9e5a5bd6ea6e75b3cc596e/autotweet/twitter.py#L61-L78
244,604
Kjwon15/autotweet
autotweet/twitter.py
expand_url
def expand_url(status): """Expand url on statuses. :param status: A tweepy status to expand urls. :type status: :class:`tweepy.models.Status` :returns: A string with expanded urls. :rtype: :class:`str` """ try: txt = get_full_text(status) for url in status.entities['urls']: txt = txt.replace(url['url'], url['expanded_url']) except: # Manually replace txt = status tco_pattern = re.compile(r'https://t.co/\S+') urls = tco_pattern.findall(txt) for url in urls: with urlopen(url) as resp: expanded_url = resp.url txt = txt.replace(url, expanded_url) return txt
python
def expand_url(status): """Expand url on statuses. :param status: A tweepy status to expand urls. :type status: :class:`tweepy.models.Status` :returns: A string with expanded urls. :rtype: :class:`str` """ try: txt = get_full_text(status) for url in status.entities['urls']: txt = txt.replace(url['url'], url['expanded_url']) except: # Manually replace txt = status tco_pattern = re.compile(r'https://t.co/\S+') urls = tco_pattern.findall(txt) for url in urls: with urlopen(url) as resp: expanded_url = resp.url txt = txt.replace(url, expanded_url) return txt
[ "def", "expand_url", "(", "status", ")", ":", "try", ":", "txt", "=", "get_full_text", "(", "status", ")", "for", "url", "in", "status", ".", "entities", "[", "'urls'", "]", ":", "txt", "=", "txt", ".", "replace", "(", "url", "[", "'url'", "]", ",", "url", "[", "'expanded_url'", "]", ")", "except", ":", "# Manually replace", "txt", "=", "status", "tco_pattern", "=", "re", ".", "compile", "(", "r'https://t.co/\\S+'", ")", "urls", "=", "tco_pattern", ".", "findall", "(", "txt", ")", "for", "url", "in", "urls", ":", "with", "urlopen", "(", "url", ")", "as", "resp", ":", "expanded_url", "=", "resp", ".", "url", "txt", "=", "txt", ".", "replace", "(", "url", ",", "expanded_url", ")", "return", "txt" ]
Expand url on statuses. :param status: A tweepy status to expand urls. :type status: :class:`tweepy.models.Status` :returns: A string with expanded urls. :rtype: :class:`str`
[ "Expand", "url", "on", "statuses", "." ]
c35b68ee1814916fbe9e5a5bd6ea6e75b3cc596e
https://github.com/Kjwon15/autotweet/blob/c35b68ee1814916fbe9e5a5bd6ea6e75b3cc596e/autotweet/twitter.py#L92-L115
244,605
Kjwon15/autotweet
autotweet/twitter.py
strip_tweet
def strip_tweet(text, remove_url=True): """Strip tweet message. This method removes mentions strings and urls(optional). :param text: tweet message :type text: :class:`str` :param remove_url: Remove urls. default :const:`True`. :type remove_url: :class:`boolean` :returns: Striped tweet message :rtype: :class:`str` """ if remove_url: text = url_pattern.sub('', text) else: text = expand_url(text) text = mention_pattern.sub('', text) text = html_parser.unescape(text) text = text.strip() return text
python
def strip_tweet(text, remove_url=True): """Strip tweet message. This method removes mentions strings and urls(optional). :param text: tweet message :type text: :class:`str` :param remove_url: Remove urls. default :const:`True`. :type remove_url: :class:`boolean` :returns: Striped tweet message :rtype: :class:`str` """ if remove_url: text = url_pattern.sub('', text) else: text = expand_url(text) text = mention_pattern.sub('', text) text = html_parser.unescape(text) text = text.strip() return text
[ "def", "strip_tweet", "(", "text", ",", "remove_url", "=", "True", ")", ":", "if", "remove_url", ":", "text", "=", "url_pattern", ".", "sub", "(", "''", ",", "text", ")", "else", ":", "text", "=", "expand_url", "(", "text", ")", "text", "=", "mention_pattern", ".", "sub", "(", "''", ",", "text", ")", "text", "=", "html_parser", ".", "unescape", "(", "text", ")", "text", "=", "text", ".", "strip", "(", ")", "return", "text" ]
Strip tweet message. This method removes mentions strings and urls(optional). :param text: tweet message :type text: :class:`str` :param remove_url: Remove urls. default :const:`True`. :type remove_url: :class:`boolean` :returns: Striped tweet message :rtype: :class:`str`
[ "Strip", "tweet", "message", "." ]
c35b68ee1814916fbe9e5a5bd6ea6e75b3cc596e
https://github.com/Kjwon15/autotweet/blob/c35b68ee1814916fbe9e5a5bd6ea6e75b3cc596e/autotweet/twitter.py#L127-L149
244,606
fizyk/pyramid_yml
setup.py
read
def read(fname): """Quick way to read a file content.""" content = None with open(os.path.join(here, fname)) as f: content = f.read() return content
python
def read(fname): """Quick way to read a file content.""" content = None with open(os.path.join(here, fname)) as f: content = f.read() return content
[ "def", "read", "(", "fname", ")", ":", "content", "=", "None", "with", "open", "(", "os", ".", "path", ".", "join", "(", "here", ",", "fname", ")", ")", "as", "f", ":", "content", "=", "f", ".", "read", "(", ")", "return", "content" ]
Quick way to read a file content.
[ "Quick", "way", "to", "read", "a", "file", "content", "." ]
1b36c4e74194c04d7d69b4d7f86801757e78f0a6
https://github.com/fizyk/pyramid_yml/blob/1b36c4e74194c04d7d69b4d7f86801757e78f0a6/setup.py#L8-L13
244,607
sahilchinoy/django-irs-filings
irs/management/commands/downloadIRS.py
Command.download
def download(self): """ Download the archive from the IRS website. """ url = 'http://forms.irs.gov/app/pod/dataDownload/fullData' r = requests.get(url, stream=True) with open(self.zip_path, 'wb') as f: # This is a big file, so we download in chunks for chunk in r.iter_content(chunk_size=30720): logger.debug('Downloading...') f.write(chunk) f.flush()
python
def download(self): """ Download the archive from the IRS website. """ url = 'http://forms.irs.gov/app/pod/dataDownload/fullData' r = requests.get(url, stream=True) with open(self.zip_path, 'wb') as f: # This is a big file, so we download in chunks for chunk in r.iter_content(chunk_size=30720): logger.debug('Downloading...') f.write(chunk) f.flush()
[ "def", "download", "(", "self", ")", ":", "url", "=", "'http://forms.irs.gov/app/pod/dataDownload/fullData'", "r", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "with", "open", "(", "self", ".", "zip_path", ",", "'wb'", ")", "as", "f", ":", "# This is a big file, so we download in chunks", "for", "chunk", "in", "r", ".", "iter_content", "(", "chunk_size", "=", "30720", ")", ":", "logger", ".", "debug", "(", "'Downloading...'", ")", "f", ".", "write", "(", "chunk", ")", "f", ".", "flush", "(", ")" ]
Download the archive from the IRS website.
[ "Download", "the", "archive", "from", "the", "IRS", "website", "." ]
efe80cc57ce1d9d8488f4e9496cf2347e29b6d8b
https://github.com/sahilchinoy/django-irs-filings/blob/efe80cc57ce1d9d8488f4e9496cf2347e29b6d8b/irs/management/commands/downloadIRS.py#L63-L74
244,608
sahilchinoy/django-irs-filings
irs/management/commands/downloadIRS.py
Command.unzip
def unzip(self): """ Unzip the archive. """ logger.info('Unzipping archive') with zipfile.ZipFile(self.zip_path, 'r') as zipped_archive: data_file = zipped_archive.namelist()[0] zipped_archive.extract(data_file, self.extract_path)
python
def unzip(self): """ Unzip the archive. """ logger.info('Unzipping archive') with zipfile.ZipFile(self.zip_path, 'r') as zipped_archive: data_file = zipped_archive.namelist()[0] zipped_archive.extract(data_file, self.extract_path)
[ "def", "unzip", "(", "self", ")", ":", "logger", ".", "info", "(", "'Unzipping archive'", ")", "with", "zipfile", ".", "ZipFile", "(", "self", ".", "zip_path", ",", "'r'", ")", "as", "zipped_archive", ":", "data_file", "=", "zipped_archive", ".", "namelist", "(", ")", "[", "0", "]", "zipped_archive", ".", "extract", "(", "data_file", ",", "self", ".", "extract_path", ")" ]
Unzip the archive.
[ "Unzip", "the", "archive", "." ]
efe80cc57ce1d9d8488f4e9496cf2347e29b6d8b
https://github.com/sahilchinoy/django-irs-filings/blob/efe80cc57ce1d9d8488f4e9496cf2347e29b6d8b/irs/management/commands/downloadIRS.py#L76-L83
244,609
sahilchinoy/django-irs-filings
irs/management/commands/downloadIRS.py
Command.clean
def clean(self): """ Get the .txt file from within the many-layered directory structure, then delete the directories. """ logger.info('Cleaning up archive') shutil.move( os.path.join( self.data_dir, 'var/IRS/data/scripts/pofd/download/FullDataFile.txt' ), self.final_path ) shutil.rmtree(os.path.join(self.data_dir, 'var')) os.remove(self.zip_path)
python
def clean(self): """ Get the .txt file from within the many-layered directory structure, then delete the directories. """ logger.info('Cleaning up archive') shutil.move( os.path.join( self.data_dir, 'var/IRS/data/scripts/pofd/download/FullDataFile.txt' ), self.final_path ) shutil.rmtree(os.path.join(self.data_dir, 'var')) os.remove(self.zip_path)
[ "def", "clean", "(", "self", ")", ":", "logger", ".", "info", "(", "'Cleaning up archive'", ")", "shutil", ".", "move", "(", "os", ".", "path", ".", "join", "(", "self", ".", "data_dir", ",", "'var/IRS/data/scripts/pofd/download/FullDataFile.txt'", ")", ",", "self", ".", "final_path", ")", "shutil", ".", "rmtree", "(", "os", ".", "path", ".", "join", "(", "self", ".", "data_dir", ",", "'var'", ")", ")", "os", ".", "remove", "(", "self", ".", "zip_path", ")" ]
Get the .txt file from within the many-layered directory structure, then delete the directories.
[ "Get", "the", ".", "txt", "file", "from", "within", "the", "many", "-", "layered", "directory", "structure", "then", "delete", "the", "directories", "." ]
efe80cc57ce1d9d8488f4e9496cf2347e29b6d8b
https://github.com/sahilchinoy/django-irs-filings/blob/efe80cc57ce1d9d8488f4e9496cf2347e29b6d8b/irs/management/commands/downloadIRS.py#L85-L100
244,610
rameshg87/pyremotevbox
pyremotevbox/ZSI/TC.py
TypeCode.get_parse_and_errorlist
def get_parse_and_errorlist(self): """Get the parselist and human-readable version, errorlist is returned, because it is used in error messages. """ d = self.__class__.__dict__ parselist = d.get('parselist') errorlist = d.get('errorlist') if parselist and not errorlist: errorlist = [] for t in parselist: if t[1] not in errorlist: errorlist.append(t[1]) errorlist = ' or '.join(errorlist) d['errorlist'] = errorlist return (parselist, errorlist)
python
def get_parse_and_errorlist(self): """Get the parselist and human-readable version, errorlist is returned, because it is used in error messages. """ d = self.__class__.__dict__ parselist = d.get('parselist') errorlist = d.get('errorlist') if parselist and not errorlist: errorlist = [] for t in parselist: if t[1] not in errorlist: errorlist.append(t[1]) errorlist = ' or '.join(errorlist) d['errorlist'] = errorlist return (parselist, errorlist)
[ "def", "get_parse_and_errorlist", "(", "self", ")", ":", "d", "=", "self", ".", "__class__", ".", "__dict__", "parselist", "=", "d", ".", "get", "(", "'parselist'", ")", "errorlist", "=", "d", ".", "get", "(", "'errorlist'", ")", "if", "parselist", "and", "not", "errorlist", ":", "errorlist", "=", "[", "]", "for", "t", "in", "parselist", ":", "if", "t", "[", "1", "]", "not", "in", "errorlist", ":", "errorlist", ".", "append", "(", "t", "[", "1", "]", ")", "errorlist", "=", "' or '", ".", "join", "(", "errorlist", ")", "d", "[", "'errorlist'", "]", "=", "errorlist", "return", "(", "parselist", ",", "errorlist", ")" ]
Get the parselist and human-readable version, errorlist is returned, because it is used in error messages.
[ "Get", "the", "parselist", "and", "human", "-", "readable", "version", "errorlist", "is", "returned", "because", "it", "is", "used", "in", "error", "messages", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/TC.py#L159-L172
244,611
rameshg87/pyremotevbox
pyremotevbox/ZSI/TC.py
String.text_to_data
def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. Encode all strings as UTF-8, which will be type 'str' not 'unicode' ''' if self.strip: text = text.strip() if self.pyclass is not None: return self.pyclass(text.encode(UNICODE_ENCODING)) return text.encode(UNICODE_ENCODING)
python
def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. Encode all strings as UTF-8, which will be type 'str' not 'unicode' ''' if self.strip: text = text.strip() if self.pyclass is not None: return self.pyclass(text.encode(UNICODE_ENCODING)) return text.encode(UNICODE_ENCODING)
[ "def", "text_to_data", "(", "self", ",", "text", ",", "elt", ",", "ps", ")", ":", "if", "self", ".", "strip", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "self", ".", "pyclass", "is", "not", "None", ":", "return", "self", ".", "pyclass", "(", "text", ".", "encode", "(", "UNICODE_ENCODING", ")", ")", "return", "text", ".", "encode", "(", "UNICODE_ENCODING", ")" ]
convert text into typecode specific data. Encode all strings as UTF-8, which will be type 'str' not 'unicode'
[ "convert", "text", "into", "typecode", "specific", "data", ".", "Encode", "all", "strings", "as", "UTF", "-", "8", "which", "will", "be", "type", "str", "not", "unicode" ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/TC.py#L709-L717
244,612
rameshg87/pyremotevbox
pyremotevbox/ZSI/TC.py
QName.set_prefix
def set_prefix(self, elt, pyobj): '''use this method to set the prefix of the QName, method looks in DOM to find prefix or set new prefix. This method must be called before get_formatted_content. ''' if isinstance(pyobj, tuple): namespaceURI,localName = pyobj self.prefix = elt.getPrefix(namespaceURI)
python
def set_prefix(self, elt, pyobj): '''use this method to set the prefix of the QName, method looks in DOM to find prefix or set new prefix. This method must be called before get_formatted_content. ''' if isinstance(pyobj, tuple): namespaceURI,localName = pyobj self.prefix = elt.getPrefix(namespaceURI)
[ "def", "set_prefix", "(", "self", ",", "elt", ",", "pyobj", ")", ":", "if", "isinstance", "(", "pyobj", ",", "tuple", ")", ":", "namespaceURI", ",", "localName", "=", "pyobj", "self", ".", "prefix", "=", "elt", ".", "getPrefix", "(", "namespaceURI", ")" ]
use this method to set the prefix of the QName, method looks in DOM to find prefix or set new prefix. This method must be called before get_formatted_content.
[ "use", "this", "method", "to", "set", "the", "prefix", "of", "the", "QName", "method", "looks", "in", "DOM", "to", "find", "prefix", "or", "set", "new", "prefix", ".", "This", "method", "must", "be", "called", "before", "get_formatted_content", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/TC.py#L771-L778
244,613
rameshg87/pyremotevbox
pyremotevbox/ZSI/TC.py
Union.parse
def parse(self, elt, ps, **kw): '''attempt to parse sequentially. No way to know ahead of time what this instance represents. Must be simple type so it can not have attributes nor children, so this isn't too bad. ''' self.setMemberTypeCodes() (nsuri,typeName) = self.checkname(elt, ps) #if (nsuri,typeName) not in self.memberTypes: # raise EvaluateException( # 'Union Type mismatch got (%s,%s) not in %s' % \ # (nsuri, typeName, self.memberTypes), ps.Backtrace(elt)) for indx in range(len(self.memberTypeCodes)): typecode = self.memberTypeCodes[indx] try: pyobj = typecode.parse(elt, ps) except ParseException, ex: continue except Exception, ex: continue if indx > 0: self.memberTypeCodes.remove(typecode) self.memberTypeCodes.insert(0, typecode) break else: raise return pyobj
python
def parse(self, elt, ps, **kw): '''attempt to parse sequentially. No way to know ahead of time what this instance represents. Must be simple type so it can not have attributes nor children, so this isn't too bad. ''' self.setMemberTypeCodes() (nsuri,typeName) = self.checkname(elt, ps) #if (nsuri,typeName) not in self.memberTypes: # raise EvaluateException( # 'Union Type mismatch got (%s,%s) not in %s' % \ # (nsuri, typeName, self.memberTypes), ps.Backtrace(elt)) for indx in range(len(self.memberTypeCodes)): typecode = self.memberTypeCodes[indx] try: pyobj = typecode.parse(elt, ps) except ParseException, ex: continue except Exception, ex: continue if indx > 0: self.memberTypeCodes.remove(typecode) self.memberTypeCodes.insert(0, typecode) break else: raise return pyobj
[ "def", "parse", "(", "self", ",", "elt", ",", "ps", ",", "*", "*", "kw", ")", ":", "self", ".", "setMemberTypeCodes", "(", ")", "(", "nsuri", ",", "typeName", ")", "=", "self", ".", "checkname", "(", "elt", ",", "ps", ")", "#if (nsuri,typeName) not in self.memberTypes:", "# raise EvaluateException(", "# 'Union Type mismatch got (%s,%s) not in %s' % \\", "# (nsuri, typeName, self.memberTypes), ps.Backtrace(elt))", "for", "indx", "in", "range", "(", "len", "(", "self", ".", "memberTypeCodes", ")", ")", ":", "typecode", "=", "self", ".", "memberTypeCodes", "[", "indx", "]", "try", ":", "pyobj", "=", "typecode", ".", "parse", "(", "elt", ",", "ps", ")", "except", "ParseException", ",", "ex", ":", "continue", "except", "Exception", ",", "ex", ":", "continue", "if", "indx", ">", "0", ":", "self", ".", "memberTypeCodes", ".", "remove", "(", "typecode", ")", "self", ".", "memberTypeCodes", ".", "insert", "(", "0", ",", "typecode", ")", "break", "else", ":", "raise", "return", "pyobj" ]
attempt to parse sequentially. No way to know ahead of time what this instance represents. Must be simple type so it can not have attributes nor children, so this isn't too bad.
[ "attempt", "to", "parse", "sequentially", ".", "No", "way", "to", "know", "ahead", "of", "time", "what", "this", "instance", "represents", ".", "Must", "be", "simple", "type", "so", "it", "can", "not", "have", "attributes", "nor", "children", "so", "this", "isn", "t", "too", "bad", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/TC.py#L1540-L1570
244,614
rameshg87/pyremotevbox
pyremotevbox/ZSI/TC.py
List.text_to_data
def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. items in list are space separated. ''' v = [] items = text.split() for item in items: v.append(self.itemTypeCode.text_to_data(item, elt, ps)) if self.pyclass is not None: return self.pyclass(v) return v
python
def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. items in list are space separated. ''' v = [] items = text.split() for item in items: v.append(self.itemTypeCode.text_to_data(item, elt, ps)) if self.pyclass is not None: return self.pyclass(v) return v
[ "def", "text_to_data", "(", "self", ",", "text", ",", "elt", ",", "ps", ")", ":", "v", "=", "[", "]", "items", "=", "text", ".", "split", "(", ")", "for", "item", "in", "items", ":", "v", ".", "append", "(", "self", ".", "itemTypeCode", ".", "text_to_data", "(", "item", ",", "elt", ",", "ps", ")", ")", "if", "self", ".", "pyclass", "is", "not", "None", ":", "return", "self", ".", "pyclass", "(", "v", ")", "return", "v" ]
convert text into typecode specific data. items in list are space separated.
[ "convert", "text", "into", "typecode", "specific", "data", ".", "items", "in", "list", "are", "space", "separated", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/TC.py#L1636-L1647
244,615
nefarioustim/parker
parker/workers.py
consumer
def consumer(site, uri): """Consume URI using site config.""" config = load_site_config(site) model = _get_model('consume', config, uri) consumestore = get_consumestore( model=model, method=_config.get('storage', 'file'), bucket=_config.get('s3_data_bucket', None) ) consumestore.save_media() consumestore.save_data()
python
def consumer(site, uri): """Consume URI using site config.""" config = load_site_config(site) model = _get_model('consume', config, uri) consumestore = get_consumestore( model=model, method=_config.get('storage', 'file'), bucket=_config.get('s3_data_bucket', None) ) consumestore.save_media() consumestore.save_data()
[ "def", "consumer", "(", "site", ",", "uri", ")", ":", "config", "=", "load_site_config", "(", "site", ")", "model", "=", "_get_model", "(", "'consume'", ",", "config", ",", "uri", ")", "consumestore", "=", "get_consumestore", "(", "model", "=", "model", ",", "method", "=", "_config", ".", "get", "(", "'storage'", ",", "'file'", ")", ",", "bucket", "=", "_config", ".", "get", "(", "'s3_data_bucket'", ",", "None", ")", ")", "consumestore", ".", "save_media", "(", ")", "consumestore", ".", "save_data", "(", ")" ]
Consume URI using site config.
[ "Consume", "URI", "using", "site", "config", "." ]
ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6
https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/workers.py#L21-L31
244,616
nefarioustim/parker
parker/workers.py
crawler
def crawler(site, uri=None): """Crawl URI using site config.""" config = load_site_config(site) model = _get_model('crawl', config, uri) visited_set, visited_uri_set, consume_set, crawl_set = get_site_sets( site, config ) if not visited_set.has(model.hash): visited_set.add(model.hash) visited_uri_set.add(model.uri) if ( model.is_consume_page and not consume_set.has(model.hash) ): consume_set.add(model.hash) consume_q.enqueue( consumer, site, model.uri ) else: for crawl_uri in model.uris_to_crawl: if ( not visited_uri_set.has(crawl_uri) and not crawl_set.has(crawl_uri) ): crawl_set.add(crawl_uri) crawl_q.enqueue( crawler, site, crawl_uri )
python
def crawler(site, uri=None): """Crawl URI using site config.""" config = load_site_config(site) model = _get_model('crawl', config, uri) visited_set, visited_uri_set, consume_set, crawl_set = get_site_sets( site, config ) if not visited_set.has(model.hash): visited_set.add(model.hash) visited_uri_set.add(model.uri) if ( model.is_consume_page and not consume_set.has(model.hash) ): consume_set.add(model.hash) consume_q.enqueue( consumer, site, model.uri ) else: for crawl_uri in model.uris_to_crawl: if ( not visited_uri_set.has(crawl_uri) and not crawl_set.has(crawl_uri) ): crawl_set.add(crawl_uri) crawl_q.enqueue( crawler, site, crawl_uri )
[ "def", "crawler", "(", "site", ",", "uri", "=", "None", ")", ":", "config", "=", "load_site_config", "(", "site", ")", "model", "=", "_get_model", "(", "'crawl'", ",", "config", ",", "uri", ")", "visited_set", ",", "visited_uri_set", ",", "consume_set", ",", "crawl_set", "=", "get_site_sets", "(", "site", ",", "config", ")", "if", "not", "visited_set", ".", "has", "(", "model", ".", "hash", ")", ":", "visited_set", ".", "add", "(", "model", ".", "hash", ")", "visited_uri_set", ".", "add", "(", "model", ".", "uri", ")", "if", "(", "model", ".", "is_consume_page", "and", "not", "consume_set", ".", "has", "(", "model", ".", "hash", ")", ")", ":", "consume_set", ".", "add", "(", "model", ".", "hash", ")", "consume_q", ".", "enqueue", "(", "consumer", ",", "site", ",", "model", ".", "uri", ")", "else", ":", "for", "crawl_uri", "in", "model", ".", "uris_to_crawl", ":", "if", "(", "not", "visited_uri_set", ".", "has", "(", "crawl_uri", ")", "and", "not", "crawl_set", ".", "has", "(", "crawl_uri", ")", ")", ":", "crawl_set", ".", "add", "(", "crawl_uri", ")", "crawl_q", ".", "enqueue", "(", "crawler", ",", "site", ",", "crawl_uri", ")" ]
Crawl URI using site config.
[ "Crawl", "URI", "using", "site", "config", "." ]
ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6
https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/workers.py#L34-L67
244,617
nefarioustim/parker
parker/workers.py
killer
def killer(site): """Kill queues and Redis sets.""" config = load_site_config(site) crawl_q.empty() consume_q.empty() for site_set in get_site_sets(site, config): site_set.destroy()
python
def killer(site): """Kill queues and Redis sets.""" config = load_site_config(site) crawl_q.empty() consume_q.empty() for site_set in get_site_sets(site, config): site_set.destroy()
[ "def", "killer", "(", "site", ")", ":", "config", "=", "load_site_config", "(", "site", ")", "crawl_q", ".", "empty", "(", ")", "consume_q", ".", "empty", "(", ")", "for", "site_set", "in", "get_site_sets", "(", "site", ",", "config", ")", ":", "site_set", ".", "destroy", "(", ")" ]
Kill queues and Redis sets.
[ "Kill", "queues", "and", "Redis", "sets", "." ]
ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6
https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/workers.py#L70-L77
244,618
rameshg87/pyremotevbox
pyremotevbox/ZSI/auth.py
ClientBinding.GetAuth
def GetAuth(self): '''Return a tuple containing client authentication data. ''' if self.auth: return self.auth for elt in self.ps.GetMyHeaderElements(): if elt.localName == 'BasicAuth' \ and elt.namespaceURI == ZSI_SCHEMA_URI: d = _auth_tc.parse(elt, self.ps) self.auth = (AUTH.zsibasic, d['Name'], d['Password']) return self.auth ba = self.environ.get('HTTP_AUTHENTICATION') if ba: ba = ba.split(' ') if len(ba) == 2 and ba[0].lower() == 'basic': ba = _b64_decode(ba[1]) self.auth = (AUTH.httpbasic,) + tuple(ba.split(':')) return self.auth self.auth = (AUTH.none,) return self.auth
python
def GetAuth(self): '''Return a tuple containing client authentication data. ''' if self.auth: return self.auth for elt in self.ps.GetMyHeaderElements(): if elt.localName == 'BasicAuth' \ and elt.namespaceURI == ZSI_SCHEMA_URI: d = _auth_tc.parse(elt, self.ps) self.auth = (AUTH.zsibasic, d['Name'], d['Password']) return self.auth ba = self.environ.get('HTTP_AUTHENTICATION') if ba: ba = ba.split(' ') if len(ba) == 2 and ba[0].lower() == 'basic': ba = _b64_decode(ba[1]) self.auth = (AUTH.httpbasic,) + tuple(ba.split(':')) return self.auth self.auth = (AUTH.none,) return self.auth
[ "def", "GetAuth", "(", "self", ")", ":", "if", "self", ".", "auth", ":", "return", "self", ".", "auth", "for", "elt", "in", "self", ".", "ps", ".", "GetMyHeaderElements", "(", ")", ":", "if", "elt", ".", "localName", "==", "'BasicAuth'", "and", "elt", ".", "namespaceURI", "==", "ZSI_SCHEMA_URI", ":", "d", "=", "_auth_tc", ".", "parse", "(", "elt", ",", "self", ".", "ps", ")", "self", ".", "auth", "=", "(", "AUTH", ".", "zsibasic", ",", "d", "[", "'Name'", "]", ",", "d", "[", "'Password'", "]", ")", "return", "self", ".", "auth", "ba", "=", "self", ".", "environ", ".", "get", "(", "'HTTP_AUTHENTICATION'", ")", "if", "ba", ":", "ba", "=", "ba", ".", "split", "(", "' '", ")", "if", "len", "(", "ba", ")", "==", "2", "and", "ba", "[", "0", "]", ".", "lower", "(", ")", "==", "'basic'", ":", "ba", "=", "_b64_decode", "(", "ba", "[", "1", "]", ")", "self", ".", "auth", "=", "(", "AUTH", ".", "httpbasic", ",", ")", "+", "tuple", "(", "ba", ".", "split", "(", "':'", ")", ")", "return", "self", ".", "auth", "self", ".", "auth", "=", "(", "AUTH", ".", "none", ",", ")", "return", "self", ".", "auth" ]
Return a tuple containing client authentication data.
[ "Return", "a", "tuple", "containing", "client", "authentication", "data", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/auth.py#L35-L53
244,619
emory-libraries/eulcommon
eulcommon/djangoextras/auth/decorators.py
permission_required_with_403
def permission_required_with_403(perm, login_url=None): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the login page or rendering a 403 as necessary. See :meth:`django.contrib.auth.decorators.permission_required`. """ return user_passes_test_with_403(lambda u: u.has_perm(perm), login_url=login_url)
python
def permission_required_with_403(perm, login_url=None): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the login page or rendering a 403 as necessary. See :meth:`django.contrib.auth.decorators.permission_required`. """ return user_passes_test_with_403(lambda u: u.has_perm(perm), login_url=login_url)
[ "def", "permission_required_with_403", "(", "perm", ",", "login_url", "=", "None", ")", ":", "return", "user_passes_test_with_403", "(", "lambda", "u", ":", "u", ".", "has_perm", "(", "perm", ")", ",", "login_url", "=", "login_url", ")" ]
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the login page or rendering a 403 as necessary. See :meth:`django.contrib.auth.decorators.permission_required`.
[ "Decorator", "for", "views", "that", "checks", "whether", "a", "user", "has", "a", "particular", "permission", "enabled", "redirecting", "to", "the", "login", "page", "or", "rendering", "a", "403", "as", "necessary", "." ]
dc63a9b3b5e38205178235e0d716d1b28158d3a9
https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/djangoextras/auth/decorators.py#L52-L59
244,620
callowayproject/Transmogrify
transmogrify/optimize.py
convert_to_rgb
def convert_to_rgb(img): """ Convert an image to RGB if it isn't already RGB or grayscale """ if img.mode == 'CMYK' and HAS_PROFILE_TO_PROFILE: profile_dir = os.path.join(os.path.dirname(__file__), 'profiles') input_profile = os.path.join(profile_dir, "USWebUncoated.icc") output_profile = os.path.join(profile_dir, "sRGB_v4_ICC_preference.icc") return profileToProfile(img, input_profile, output_profile, outputMode='RGB') return img
python
def convert_to_rgb(img): """ Convert an image to RGB if it isn't already RGB or grayscale """ if img.mode == 'CMYK' and HAS_PROFILE_TO_PROFILE: profile_dir = os.path.join(os.path.dirname(__file__), 'profiles') input_profile = os.path.join(profile_dir, "USWebUncoated.icc") output_profile = os.path.join(profile_dir, "sRGB_v4_ICC_preference.icc") return profileToProfile(img, input_profile, output_profile, outputMode='RGB') return img
[ "def", "convert_to_rgb", "(", "img", ")", ":", "if", "img", ".", "mode", "==", "'CMYK'", "and", "HAS_PROFILE_TO_PROFILE", ":", "profile_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'profiles'", ")", "input_profile", "=", "os", ".", "path", ".", "join", "(", "profile_dir", ",", "\"USWebUncoated.icc\"", ")", "output_profile", "=", "os", ".", "path", ".", "join", "(", "profile_dir", ",", "\"sRGB_v4_ICC_preference.icc\"", ")", "return", "profileToProfile", "(", "img", ",", "input_profile", ",", "output_profile", ",", "outputMode", "=", "'RGB'", ")", "return", "img" ]
Convert an image to RGB if it isn't already RGB or grayscale
[ "Convert", "an", "image", "to", "RGB", "if", "it", "isn", "t", "already", "RGB", "or", "grayscale" ]
f1f891b8b923b3a1ede5eac7f60531c1c472379e
https://github.com/callowayproject/Transmogrify/blob/f1f891b8b923b3a1ede5eac7f60531c1c472379e/transmogrify/optimize.py#L20-L29
244,621
callowayproject/Transmogrify
transmogrify/optimize.py
optimize
def optimize(image, fmt='jpeg', quality=80): """ Optimize the image if the IMAGE_OPTIMIZATION_CMD is set. IMAGE_OPTIMIZATION_CMD must accept piped input """ from io import BytesIO if IMAGE_OPTIMIZATION_CMD and is_tool(IMAGE_OPTIMIZATION_CMD): image_buffer = BytesIO() image.save(image_buffer, format=fmt, quality=quality) image_buffer.seek(0) # If you don't reset the file pointer, the read command returns an empty string p1 = subprocess.Popen(IMAGE_OPTIMIZATION_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE) output_optim, output_err = p1.communicate(image_buffer.read()) if not output_optim: logger.debug("No image buffer received from IMAGE_OPTIMIZATION_CMD") logger.debug("output_err: {0}".format(output_err)) return image im = Image.open(BytesIO(output_optim)) return im else: return image
python
def optimize(image, fmt='jpeg', quality=80): """ Optimize the image if the IMAGE_OPTIMIZATION_CMD is set. IMAGE_OPTIMIZATION_CMD must accept piped input """ from io import BytesIO if IMAGE_OPTIMIZATION_CMD and is_tool(IMAGE_OPTIMIZATION_CMD): image_buffer = BytesIO() image.save(image_buffer, format=fmt, quality=quality) image_buffer.seek(0) # If you don't reset the file pointer, the read command returns an empty string p1 = subprocess.Popen(IMAGE_OPTIMIZATION_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE) output_optim, output_err = p1.communicate(image_buffer.read()) if not output_optim: logger.debug("No image buffer received from IMAGE_OPTIMIZATION_CMD") logger.debug("output_err: {0}".format(output_err)) return image im = Image.open(BytesIO(output_optim)) return im else: return image
[ "def", "optimize", "(", "image", ",", "fmt", "=", "'jpeg'", ",", "quality", "=", "80", ")", ":", "from", "io", "import", "BytesIO", "if", "IMAGE_OPTIMIZATION_CMD", "and", "is_tool", "(", "IMAGE_OPTIMIZATION_CMD", ")", ":", "image_buffer", "=", "BytesIO", "(", ")", "image", ".", "save", "(", "image_buffer", ",", "format", "=", "fmt", ",", "quality", "=", "quality", ")", "image_buffer", ".", "seek", "(", "0", ")", "# If you don't reset the file pointer, the read command returns an empty string", "p1", "=", "subprocess", ".", "Popen", "(", "IMAGE_OPTIMIZATION_CMD", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "output_optim", ",", "output_err", "=", "p1", ".", "communicate", "(", "image_buffer", ".", "read", "(", ")", ")", "if", "not", "output_optim", ":", "logger", ".", "debug", "(", "\"No image buffer received from IMAGE_OPTIMIZATION_CMD\"", ")", "logger", ".", "debug", "(", "\"output_err: {0}\"", ".", "format", "(", "output_err", ")", ")", "return", "image", "im", "=", "Image", ".", "open", "(", "BytesIO", "(", "output_optim", ")", ")", "return", "im", "else", ":", "return", "image" ]
Optimize the image if the IMAGE_OPTIMIZATION_CMD is set. IMAGE_OPTIMIZATION_CMD must accept piped input
[ "Optimize", "the", "image", "if", "the", "IMAGE_OPTIMIZATION_CMD", "is", "set", "." ]
f1f891b8b923b3a1ede5eac7f60531c1c472379e
https://github.com/callowayproject/Transmogrify/blob/f1f891b8b923b3a1ede5eac7f60531c1c472379e/transmogrify/optimize.py#L32-L53
244,622
pydsigner/pygu
pygu/pyslim.py
load
def load(filename, default=None): ''' Try to load @filename. If there is no loader for @filename's filetype, return @default. ''' ext = get_ext(filename) if ext in ldict: return ldict[ext](filename) else: return default
python
def load(filename, default=None): ''' Try to load @filename. If there is no loader for @filename's filetype, return @default. ''' ext = get_ext(filename) if ext in ldict: return ldict[ext](filename) else: return default
[ "def", "load", "(", "filename", ",", "default", "=", "None", ")", ":", "ext", "=", "get_ext", "(", "filename", ")", "if", "ext", "in", "ldict", ":", "return", "ldict", "[", "ext", "]", "(", "filename", ")", "else", ":", "return", "default" ]
Try to load @filename. If there is no loader for @filename's filetype, return @default.
[ "Try", "to", "load" ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pyslim.py#L33-L42
244,623
edwards-lab/MVtest
meanvar/simple_timer.py
SimpleTimer.report
def report(self, msg, do_reset=False, file=sys.stdout): """Print to stdout msg followed by the runtime. When true, do_reset will result in a reset of start time. """ print >> file, "%s (%s s)" % (msg, time.time() - self.start) if do_reset: self.start = time.time()
python
def report(self, msg, do_reset=False, file=sys.stdout): """Print to stdout msg followed by the runtime. When true, do_reset will result in a reset of start time. """ print >> file, "%s (%s s)" % (msg, time.time() - self.start) if do_reset: self.start = time.time()
[ "def", "report", "(", "self", ",", "msg", ",", "do_reset", "=", "False", ",", "file", "=", "sys", ".", "stdout", ")", ":", "print", ">>", "file", ",", "\"%s (%s s)\"", "%", "(", "msg", ",", "time", ".", "time", "(", ")", "-", "self", ".", "start", ")", "if", "do_reset", ":", "self", ".", "start", "=", "time", ".", "time", "(", ")" ]
Print to stdout msg followed by the runtime. When true, do_reset will result in a reset of start time.
[ "Print", "to", "stdout", "msg", "followed", "by", "the", "runtime", "." ]
fe8cf627464ef59d68b7eda628a19840d033882f
https://github.com/edwards-lab/MVtest/blob/fe8cf627464ef59d68b7eda628a19840d033882f/meanvar/simple_timer.py#L28-L36
244,624
edwards-lab/MVtest
meanvar/simple_timer.py
SimpleTimer.result
def result(self, msg, do_reset=False): """Return log message containing ellapsed time as a string. When true, do_reset will result in a reset of start time. """ result = "%s (%s s)" % (msg, time.time() - self.start) if do_reset: self.start = time.time() return result
python
def result(self, msg, do_reset=False): """Return log message containing ellapsed time as a string. When true, do_reset will result in a reset of start time. """ result = "%s (%s s)" % (msg, time.time() - self.start) if do_reset: self.start = time.time() return result
[ "def", "result", "(", "self", ",", "msg", ",", "do_reset", "=", "False", ")", ":", "result", "=", "\"%s (%s s)\"", "%", "(", "msg", ",", "time", ".", "time", "(", ")", "-", "self", ".", "start", ")", "if", "do_reset", ":", "self", ".", "start", "=", "time", ".", "time", "(", ")", "return", "result" ]
Return log message containing ellapsed time as a string. When true, do_reset will result in a reset of start time.
[ "Return", "log", "message", "containing", "ellapsed", "time", "as", "a", "string", "." ]
fe8cf627464ef59d68b7eda628a19840d033882f
https://github.com/edwards-lab/MVtest/blob/fe8cf627464ef59d68b7eda628a19840d033882f/meanvar/simple_timer.py#L38-L47
244,625
edwards-lab/MVtest
meanvar/simple_timer.py
SimpleTimer.runtime
def runtime(self): """Return ellapsed time and reset start. """ t = time.time() - self.start self.start = time.time() return t
python
def runtime(self): """Return ellapsed time and reset start. """ t = time.time() - self.start self.start = time.time() return t
[ "def", "runtime", "(", "self", ")", ":", "t", "=", "time", ".", "time", "(", ")", "-", "self", ".", "start", "self", ".", "start", "=", "time", ".", "time", "(", ")", "return", "t" ]
Return ellapsed time and reset start.
[ "Return", "ellapsed", "time", "and", "reset", "start", "." ]
fe8cf627464ef59d68b7eda628a19840d033882f
https://github.com/edwards-lab/MVtest/blob/fe8cf627464ef59d68b7eda628a19840d033882f/meanvar/simple_timer.py#L54-L58
244,626
delfick/aws_syncr
aws_syncr/option_spec/apigateway.py
Gateways.sync_one
def sync_one(self, aws_syncr, amazon, gateway): """Make sure this gateway exists and has only attributes we want it to have""" gateway_info = amazon.apigateway.gateway_info(gateway.name, gateway.location) if not gateway_info: amazon.apigateway.create_gateway(gateway.name, gateway.location, gateway.stages, gateway.resources, gateway.api_keys, gateway.domain_names) else: amazon.apigateway.modify_gateway(gateway_info, gateway.name, gateway.location, gateway.stages, gateway.resources, gateway.api_keys, gateway.domain_names)
python
def sync_one(self, aws_syncr, amazon, gateway): """Make sure this gateway exists and has only attributes we want it to have""" gateway_info = amazon.apigateway.gateway_info(gateway.name, gateway.location) if not gateway_info: amazon.apigateway.create_gateway(gateway.name, gateway.location, gateway.stages, gateway.resources, gateway.api_keys, gateway.domain_names) else: amazon.apigateway.modify_gateway(gateway_info, gateway.name, gateway.location, gateway.stages, gateway.resources, gateway.api_keys, gateway.domain_names)
[ "def", "sync_one", "(", "self", ",", "aws_syncr", ",", "amazon", ",", "gateway", ")", ":", "gateway_info", "=", "amazon", ".", "apigateway", ".", "gateway_info", "(", "gateway", ".", "name", ",", "gateway", ".", "location", ")", "if", "not", "gateway_info", ":", "amazon", ".", "apigateway", ".", "create_gateway", "(", "gateway", ".", "name", ",", "gateway", ".", "location", ",", "gateway", ".", "stages", ",", "gateway", ".", "resources", ",", "gateway", ".", "api_keys", ",", "gateway", ".", "domain_names", ")", "else", ":", "amazon", ".", "apigateway", ".", "modify_gateway", "(", "gateway_info", ",", "gateway", ".", "name", ",", "gateway", ".", "location", ",", "gateway", ".", "stages", ",", "gateway", ".", "resources", ",", "gateway", ".", "api_keys", ",", "gateway", ".", "domain_names", ")" ]
Make sure this gateway exists and has only attributes we want it to have
[ "Make", "sure", "this", "gateway", "exists", "and", "has", "only", "attributes", "we", "want", "it", "to", "have" ]
8cd214b27c1eee98dfba4632cbb8bc0ae36356bd
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/option_spec/apigateway.py#L362-L368
244,627
fizyk/pyramid_yml
tzf/pyramid_yml/__init__.py
includeme
def includeme(configurator): """ Add yaml configuration utilities. :param pyramid.config.Configurator configurator: pyramid's app configurator """ settings = configurator.registry.settings # lets default it to running path yaml_locations = settings.get('yaml.location', settings.get('yml.location', os.getcwd())) configurator.add_directive('config_defaults', config_defaults) configurator.config_defaults(yaml_locations) # reading yml configuration if configurator.registry['config']: config = configurator.registry['config'] log.debug('Yaml config created') # extend settings object if 'configurator' in config and config.configurator: _extend_settings(settings, config.configurator) # run include's if 'include' in config: _run_includemes(configurator, config.include) # let's calla a convenience request method configurator.add_request_method( lambda request: request.registry['config'], name='config', property=True )
python
def includeme(configurator): """ Add yaml configuration utilities. :param pyramid.config.Configurator configurator: pyramid's app configurator """ settings = configurator.registry.settings # lets default it to running path yaml_locations = settings.get('yaml.location', settings.get('yml.location', os.getcwd())) configurator.add_directive('config_defaults', config_defaults) configurator.config_defaults(yaml_locations) # reading yml configuration if configurator.registry['config']: config = configurator.registry['config'] log.debug('Yaml config created') # extend settings object if 'configurator' in config and config.configurator: _extend_settings(settings, config.configurator) # run include's if 'include' in config: _run_includemes(configurator, config.include) # let's calla a convenience request method configurator.add_request_method( lambda request: request.registry['config'], name='config', property=True )
[ "def", "includeme", "(", "configurator", ")", ":", "settings", "=", "configurator", ".", "registry", ".", "settings", "# lets default it to running path", "yaml_locations", "=", "settings", ".", "get", "(", "'yaml.location'", ",", "settings", ".", "get", "(", "'yml.location'", ",", "os", ".", "getcwd", "(", ")", ")", ")", "configurator", ".", "add_directive", "(", "'config_defaults'", ",", "config_defaults", ")", "configurator", ".", "config_defaults", "(", "yaml_locations", ")", "# reading yml configuration", "if", "configurator", ".", "registry", "[", "'config'", "]", ":", "config", "=", "configurator", ".", "registry", "[", "'config'", "]", "log", ".", "debug", "(", "'Yaml config created'", ")", "# extend settings object", "if", "'configurator'", "in", "config", "and", "config", ".", "configurator", ":", "_extend_settings", "(", "settings", ",", "config", ".", "configurator", ")", "# run include's", "if", "'include'", "in", "config", ":", "_run_includemes", "(", "configurator", ",", "config", ".", "include", ")", "# let's calla a convenience request method", "configurator", ".", "add_request_method", "(", "lambda", "request", ":", "request", ".", "registry", "[", "'config'", "]", ",", "name", "=", "'config'", ",", "property", "=", "True", ")" ]
Add yaml configuration utilities. :param pyramid.config.Configurator configurator: pyramid's app configurator
[ "Add", "yaml", "configuration", "utilities", "." ]
1b36c4e74194c04d7d69b4d7f86801757e78f0a6
https://github.com/fizyk/pyramid_yml/blob/1b36c4e74194c04d7d69b4d7f86801757e78f0a6/tzf/pyramid_yml/__init__.py#L21-L55
244,628
fizyk/pyramid_yml
tzf/pyramid_yml/__init__.py
_translate_config_path
def _translate_config_path(location): """ Translate location into fullpath according asset specification. Might be package:path for package related paths, or simply path :param str location: resource location :returns: fullpath :rtype: str """ # getting spec path package_name, filename = resolve_asset_spec(location.strip()) if not package_name: path = filename else: package = __import__(package_name) path = os.path.join(package_path(package), filename) return path
python
def _translate_config_path(location): """ Translate location into fullpath according asset specification. Might be package:path for package related paths, or simply path :param str location: resource location :returns: fullpath :rtype: str """ # getting spec path package_name, filename = resolve_asset_spec(location.strip()) if not package_name: path = filename else: package = __import__(package_name) path = os.path.join(package_path(package), filename) return path
[ "def", "_translate_config_path", "(", "location", ")", ":", "# getting spec path", "package_name", ",", "filename", "=", "resolve_asset_spec", "(", "location", ".", "strip", "(", ")", ")", "if", "not", "package_name", ":", "path", "=", "filename", "else", ":", "package", "=", "__import__", "(", "package_name", ")", "path", "=", "os", ".", "path", ".", "join", "(", "package_path", "(", "package", ")", ",", "filename", ")", "return", "path" ]
Translate location into fullpath according asset specification. Might be package:path for package related paths, or simply path :param str location: resource location :returns: fullpath :rtype: str
[ "Translate", "location", "into", "fullpath", "according", "asset", "specification", "." ]
1b36c4e74194c04d7d69b4d7f86801757e78f0a6
https://github.com/fizyk/pyramid_yml/blob/1b36c4e74194c04d7d69b4d7f86801757e78f0a6/tzf/pyramid_yml/__init__.py#L105-L124
244,629
fizyk/pyramid_yml
tzf/pyramid_yml/__init__.py
_env_filenames
def _env_filenames(filenames, env): """ Extend filenames with ennv indication of environments. :param list filenames: list of strings indicating filenames :param str env: environment indicator :returns: list of filenames extended with environment version :rtype: list """ env_filenames = [] for filename in filenames: filename_parts = filename.split('.') filename_parts.insert(1, env) env_filenames.extend([filename, '.'.join(filename_parts)]) return env_filenames
python
def _env_filenames(filenames, env): """ Extend filenames with ennv indication of environments. :param list filenames: list of strings indicating filenames :param str env: environment indicator :returns: list of filenames extended with environment version :rtype: list """ env_filenames = [] for filename in filenames: filename_parts = filename.split('.') filename_parts.insert(1, env) env_filenames.extend([filename, '.'.join(filename_parts)]) return env_filenames
[ "def", "_env_filenames", "(", "filenames", ",", "env", ")", ":", "env_filenames", "=", "[", "]", "for", "filename", "in", "filenames", ":", "filename_parts", "=", "filename", ".", "split", "(", "'.'", ")", "filename_parts", ".", "insert", "(", "1", ",", "env", ")", "env_filenames", ".", "extend", "(", "[", "filename", ",", "'.'", ".", "join", "(", "filename_parts", ")", "]", ")", "return", "env_filenames" ]
Extend filenames with ennv indication of environments. :param list filenames: list of strings indicating filenames :param str env: environment indicator :returns: list of filenames extended with environment version :rtype: list
[ "Extend", "filenames", "with", "ennv", "indication", "of", "environments", "." ]
1b36c4e74194c04d7d69b4d7f86801757e78f0a6
https://github.com/fizyk/pyramid_yml/blob/1b36c4e74194c04d7d69b4d7f86801757e78f0a6/tzf/pyramid_yml/__init__.py#L127-L143
244,630
fizyk/pyramid_yml
tzf/pyramid_yml/__init__.py
_extend_settings
def _extend_settings(settings, configurator_config, prefix=None): """ Extend settings dictionary with content of yaml's configurator key. .. note:: This methods changes multilayered subkeys defined within **configurator** into dotted keys in settings dictionary: .. code-block:: yaml configurator: sqlalchemy: url: mysql://user:password@host/dbname will result in **sqlalchemy.url**: mysql://user:password@host/dbname key value in settings dictionary. :param dict settings: settings dictionary :param dict configurator_config: yml defined settings :param str prefix: prefix for settings dict key """ for key in configurator_config: settings_key = '.'.join([prefix, key]) if prefix else key if hasattr(configurator_config[key], 'keys') and\ hasattr(configurator_config[key], '__getitem__'): _extend_settings( settings, configurator_config[key], prefix=settings_key ) else: settings[settings_key] = configurator_config[key]
python
def _extend_settings(settings, configurator_config, prefix=None): """ Extend settings dictionary with content of yaml's configurator key. .. note:: This methods changes multilayered subkeys defined within **configurator** into dotted keys in settings dictionary: .. code-block:: yaml configurator: sqlalchemy: url: mysql://user:password@host/dbname will result in **sqlalchemy.url**: mysql://user:password@host/dbname key value in settings dictionary. :param dict settings: settings dictionary :param dict configurator_config: yml defined settings :param str prefix: prefix for settings dict key """ for key in configurator_config: settings_key = '.'.join([prefix, key]) if prefix else key if hasattr(configurator_config[key], 'keys') and\ hasattr(configurator_config[key], '__getitem__'): _extend_settings( settings, configurator_config[key], prefix=settings_key ) else: settings[settings_key] = configurator_config[key]
[ "def", "_extend_settings", "(", "settings", ",", "configurator_config", ",", "prefix", "=", "None", ")", ":", "for", "key", "in", "configurator_config", ":", "settings_key", "=", "'.'", ".", "join", "(", "[", "prefix", ",", "key", "]", ")", "if", "prefix", "else", "key", "if", "hasattr", "(", "configurator_config", "[", "key", "]", ",", "'keys'", ")", "and", "hasattr", "(", "configurator_config", "[", "key", "]", ",", "'__getitem__'", ")", ":", "_extend_settings", "(", "settings", ",", "configurator_config", "[", "key", "]", ",", "prefix", "=", "settings_key", ")", "else", ":", "settings", "[", "settings_key", "]", "=", "configurator_config", "[", "key", "]" ]
Extend settings dictionary with content of yaml's configurator key. .. note:: This methods changes multilayered subkeys defined within **configurator** into dotted keys in settings dictionary: .. code-block:: yaml configurator: sqlalchemy: url: mysql://user:password@host/dbname will result in **sqlalchemy.url**: mysql://user:password@host/dbname key value in settings dictionary. :param dict settings: settings dictionary :param dict configurator_config: yml defined settings :param str prefix: prefix for settings dict key
[ "Extend", "settings", "dictionary", "with", "content", "of", "yaml", "s", "configurator", "key", "." ]
1b36c4e74194c04d7d69b4d7f86801757e78f0a6
https://github.com/fizyk/pyramid_yml/blob/1b36c4e74194c04d7d69b4d7f86801757e78f0a6/tzf/pyramid_yml/__init__.py#L146-L177
244,631
nefarioustim/parker
parker/page.py
get_instance
def get_instance(uri): """Return an instance of Page.""" global _instances try: instance = _instances[uri] except KeyError: instance = Page( uri, client.get_instance() ) _instances[uri] = instance return instance
python
def get_instance(uri): """Return an instance of Page.""" global _instances try: instance = _instances[uri] except KeyError: instance = Page( uri, client.get_instance() ) _instances[uri] = instance return instance
[ "def", "get_instance", "(", "uri", ")", ":", "global", "_instances", "try", ":", "instance", "=", "_instances", "[", "uri", "]", "except", "KeyError", ":", "instance", "=", "Page", "(", "uri", ",", "client", ".", "get_instance", "(", ")", ")", "_instances", "[", "uri", "]", "=", "instance", "return", "instance" ]
Return an instance of Page.
[ "Return", "an", "instance", "of", "Page", "." ]
ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6
https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/page.py#L10-L22
244,632
nefarioustim/parker
parker/page.py
Page.fetch
def fetch(self): """Fetch Page.content from client.""" self.content = self.client.get_content( uri=self.uri ) self.hash = hashlib.sha256( self.content ).hexdigest()
python
def fetch(self): """Fetch Page.content from client.""" self.content = self.client.get_content( uri=self.uri ) self.hash = hashlib.sha256( self.content ).hexdigest()
[ "def", "fetch", "(", "self", ")", ":", "self", ".", "content", "=", "self", ".", "client", ".", "get_content", "(", "uri", "=", "self", ".", "uri", ")", "self", ".", "hash", "=", "hashlib", ".", "sha256", "(", "self", ".", "content", ")", ".", "hexdigest", "(", ")" ]
Fetch Page.content from client.
[ "Fetch", "Page", ".", "content", "from", "client", "." ]
ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6
https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/page.py#L39-L46
244,633
pydsigner/pygu
pygu/pyramid.py
Resources.load_objects
def load_objects(self, dirs=[], callwith={}): ''' Call this to load resources from each dir in @dirs. Code resources will receive @callwith as an argument. ''' for d in dirs: contents = ls(d) for t in contents: first = join(d, t) if t.startswith('.') or os.path.isfile(first): continue t_l = t.lower() for fl in ls(first): full = join(first, fl) if fl.startswith('.') or os.path.isdir(full): continue fl_n = fl.lower().rsplit('.', 1)[0] ty = guess_type(full) if ty == T_IMAGE: self.load_image(full, fl_n, t) elif ty == T_SOUND: self.load_sound(full, fl_n, t) elif ty == T_MUSIC: self.load_music(full, fl_n, t) elif ty == T_CODE and fl_n == '__init__': self.load_code(d, t, callwith) elif ty == T_PLAYLIST: self.load_playlist(full, fl_n)
python
def load_objects(self, dirs=[], callwith={}): ''' Call this to load resources from each dir in @dirs. Code resources will receive @callwith as an argument. ''' for d in dirs: contents = ls(d) for t in contents: first = join(d, t) if t.startswith('.') or os.path.isfile(first): continue t_l = t.lower() for fl in ls(first): full = join(first, fl) if fl.startswith('.') or os.path.isdir(full): continue fl_n = fl.lower().rsplit('.', 1)[0] ty = guess_type(full) if ty == T_IMAGE: self.load_image(full, fl_n, t) elif ty == T_SOUND: self.load_sound(full, fl_n, t) elif ty == T_MUSIC: self.load_music(full, fl_n, t) elif ty == T_CODE and fl_n == '__init__': self.load_code(d, t, callwith) elif ty == T_PLAYLIST: self.load_playlist(full, fl_n)
[ "def", "load_objects", "(", "self", ",", "dirs", "=", "[", "]", ",", "callwith", "=", "{", "}", ")", ":", "for", "d", "in", "dirs", ":", "contents", "=", "ls", "(", "d", ")", "for", "t", "in", "contents", ":", "first", "=", "join", "(", "d", ",", "t", ")", "if", "t", ".", "startswith", "(", "'.'", ")", "or", "os", ".", "path", ".", "isfile", "(", "first", ")", ":", "continue", "t_l", "=", "t", ".", "lower", "(", ")", "for", "fl", "in", "ls", "(", "first", ")", ":", "full", "=", "join", "(", "first", ",", "fl", ")", "if", "fl", ".", "startswith", "(", "'.'", ")", "or", "os", ".", "path", ".", "isdir", "(", "full", ")", ":", "continue", "fl_n", "=", "fl", ".", "lower", "(", ")", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "ty", "=", "guess_type", "(", "full", ")", "if", "ty", "==", "T_IMAGE", ":", "self", ".", "load_image", "(", "full", ",", "fl_n", ",", "t", ")", "elif", "ty", "==", "T_SOUND", ":", "self", ".", "load_sound", "(", "full", ",", "fl_n", ",", "t", ")", "elif", "ty", "==", "T_MUSIC", ":", "self", ".", "load_music", "(", "full", ",", "fl_n", ",", "t", ")", "elif", "ty", "==", "T_CODE", "and", "fl_n", "==", "'__init__'", ":", "self", ".", "load_code", "(", "d", ",", "t", ",", "callwith", ")", "elif", "ty", "==", "T_PLAYLIST", ":", "self", ".", "load_playlist", "(", "full", ",", "fl_n", ")" ]
Call this to load resources from each dir in @dirs. Code resources will receive @callwith as an argument.
[ "Call", "this", "to", "load", "resources", "from", "each", "dir", "in" ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pyramid.py#L215-L242
244,634
pydsigner/pygu
pygu/pyramid.py
Resources.set_music
def set_music(self, plylst, force=False): ''' Use to set the playlist to @plylst. If @force is False, the playlist will not be set if it is @plylst already. ''' plylst = plylst.lower() if plylst != self.cur_playlist or force: self.cur_playlist = plylst self.play_song(self.get_playlist().begin())
python
def set_music(self, plylst, force=False): ''' Use to set the playlist to @plylst. If @force is False, the playlist will not be set if it is @plylst already. ''' plylst = plylst.lower() if plylst != self.cur_playlist or force: self.cur_playlist = plylst self.play_song(self.get_playlist().begin())
[ "def", "set_music", "(", "self", ",", "plylst", ",", "force", "=", "False", ")", ":", "plylst", "=", "plylst", ".", "lower", "(", ")", "if", "plylst", "!=", "self", ".", "cur_playlist", "or", "force", ":", "self", ".", "cur_playlist", "=", "plylst", "self", ".", "play_song", "(", "self", ".", "get_playlist", "(", ")", ".", "begin", "(", ")", ")" ]
Use to set the playlist to @plylst. If @force is False, the playlist will not be set if it is @plylst already.
[ "Use", "to", "set", "the", "playlist", "to" ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pyramid.py#L248-L256
244,635
pydsigner/pygu
pygu/pyramid.py
Resources.set_m_vol
def set_m_vol(self, vol=None, relative=False): ''' Set the music volume. If @vol != None, It will be changed to it (or by it, if @relative is True.) ''' if vol != None: if relative: vol += self.m_vol self.m_vol = min(max(vol, 0), 1) pygame.mixer.music.set_volume(self.m_vol)
python
def set_m_vol(self, vol=None, relative=False): ''' Set the music volume. If @vol != None, It will be changed to it (or by it, if @relative is True.) ''' if vol != None: if relative: vol += self.m_vol self.m_vol = min(max(vol, 0), 1) pygame.mixer.music.set_volume(self.m_vol)
[ "def", "set_m_vol", "(", "self", ",", "vol", "=", "None", ",", "relative", "=", "False", ")", ":", "if", "vol", "!=", "None", ":", "if", "relative", ":", "vol", "+=", "self", ".", "m_vol", "self", ".", "m_vol", "=", "min", "(", "max", "(", "vol", ",", "0", ")", ",", "1", ")", "pygame", ".", "mixer", ".", "music", ".", "set_volume", "(", "self", ".", "m_vol", ")" ]
Set the music volume. If @vol != None, It will be changed to it (or by it, if @relative is True.)
[ "Set", "the", "music", "volume", ".", "If" ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pyramid.py#L274-L283
244,636
pydsigner/pygu
pygu/pyramid.py
Resources.set_s_vol
def set_s_vol(self, vol=None, relative=False): ''' Set the volume of all sounds. If @vol != None, It will be changed to it (or by it, if @relative is True.) ''' if vol != None: if relative: vol += self.s_vol self.s_vol = min(max(vol, 0), 1) for sgroup in self.sounds.values(): for snd in sgroup.values(): snd.set_volume()
python
def set_s_vol(self, vol=None, relative=False): ''' Set the volume of all sounds. If @vol != None, It will be changed to it (or by it, if @relative is True.) ''' if vol != None: if relative: vol += self.s_vol self.s_vol = min(max(vol, 0), 1) for sgroup in self.sounds.values(): for snd in sgroup.values(): snd.set_volume()
[ "def", "set_s_vol", "(", "self", ",", "vol", "=", "None", ",", "relative", "=", "False", ")", ":", "if", "vol", "!=", "None", ":", "if", "relative", ":", "vol", "+=", "self", ".", "s_vol", "self", ".", "s_vol", "=", "min", "(", "max", "(", "vol", ",", "0", ")", ",", "1", ")", "for", "sgroup", "in", "self", ".", "sounds", ".", "values", "(", ")", ":", "for", "snd", "in", "sgroup", ".", "values", "(", ")", ":", "snd", ".", "set_volume", "(", ")" ]
Set the volume of all sounds. If @vol != None, It will be changed to it (or by it, if @relative is True.)
[ "Set", "the", "volume", "of", "all", "sounds", ".", "If" ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pyramid.py#L285-L296
244,637
pydsigner/pygu
pygu/pyramid.py
Resources.get_channel
def get_channel(self): ''' Used internally when playing sounds. ''' c = pygame.mixer.find_channel(not self.dynamic) while c is None: self.channels += 1 pygame.mixer.set_num_channels(self.channels) c = pygame.mixer.find_channel() return c
python
def get_channel(self): ''' Used internally when playing sounds. ''' c = pygame.mixer.find_channel(not self.dynamic) while c is None: self.channels += 1 pygame.mixer.set_num_channels(self.channels) c = pygame.mixer.find_channel() return c
[ "def", "get_channel", "(", "self", ")", ":", "c", "=", "pygame", ".", "mixer", ".", "find_channel", "(", "not", "self", ".", "dynamic", ")", "while", "c", "is", "None", ":", "self", ".", "channels", "+=", "1", "pygame", ".", "mixer", ".", "set_num_channels", "(", "self", ".", "channels", ")", "c", "=", "pygame", ".", "mixer", ".", "find_channel", "(", ")", "return", "c" ]
Used internally when playing sounds.
[ "Used", "internally", "when", "playing", "sounds", "." ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pyramid.py#L316-L325
244,638
pydsigner/pygu
pygu/pyramid.py
EventManager.event
def event(self, utype, **kw): ''' Make a meta-event with a utype of @type. **@kw works the same as for pygame.event.Event(). ''' d = {'utype': utype} d.update(kw) pygame.event.post(pygame.event.Event(METAEVENT, d))
python
def event(self, utype, **kw): ''' Make a meta-event with a utype of @type. **@kw works the same as for pygame.event.Event(). ''' d = {'utype': utype} d.update(kw) pygame.event.post(pygame.event.Event(METAEVENT, d))
[ "def", "event", "(", "self", ",", "utype", ",", "*", "*", "kw", ")", ":", "d", "=", "{", "'utype'", ":", "utype", "}", "d", ".", "update", "(", "kw", ")", "pygame", ".", "event", ".", "post", "(", "pygame", ".", "event", ".", "Event", "(", "METAEVENT", ",", "d", ")", ")" ]
Make a meta-event with a utype of @type. **@kw works the same as for pygame.event.Event().
[ "Make", "a", "meta", "-", "event", "with", "a", "utype", "of" ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pyramid.py#L431-L438
244,639
pydsigner/pygu
pygu/pyramid.py
EventManager.loop
def loop(self, events=[]): ''' Run the loop. ''' try: for e in events: if e.type == METAEVENT: e = self.MetaEvent(e) for func in self.event_funcs.get(e.type, []): func(self, self.gstate, e) except self.Message as e: return e.message
python
def loop(self, events=[]): ''' Run the loop. ''' try: for e in events: if e.type == METAEVENT: e = self.MetaEvent(e) for func in self.event_funcs.get(e.type, []): func(self, self.gstate, e) except self.Message as e: return e.message
[ "def", "loop", "(", "self", ",", "events", "=", "[", "]", ")", ":", "try", ":", "for", "e", "in", "events", ":", "if", "e", ".", "type", "==", "METAEVENT", ":", "e", "=", "self", ".", "MetaEvent", "(", "e", ")", "for", "func", "in", "self", ".", "event_funcs", ".", "get", "(", "e", ".", "type", ",", "[", "]", ")", ":", "func", "(", "self", ",", "self", ".", "gstate", ",", "e", ")", "except", "self", ".", "Message", "as", "e", ":", "return", "e", ".", "message" ]
Run the loop.
[ "Run", "the", "loop", "." ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pyramid.py#L442-L453
244,640
johnwlockwood/cooperative
cooperative/__init__.py
accumulate
def accumulate(a_generator, cooperator=None): """ Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator. :param a_generator: An iterator which yields some not None values. :return: A Deferred to which the next callback will be called with the yielded contents of the generator function. """ if cooperator: own_cooperate = cooperator.cooperate else: own_cooperate = cooperate spigot = ValueBucket() items = stream_tap((spigot,), a_generator) d = own_cooperate(items).whenDone() d.addCallback(accumulation_handler, spigot) return d
python
def accumulate(a_generator, cooperator=None): """ Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator. :param a_generator: An iterator which yields some not None values. :return: A Deferred to which the next callback will be called with the yielded contents of the generator function. """ if cooperator: own_cooperate = cooperator.cooperate else: own_cooperate = cooperate spigot = ValueBucket() items = stream_tap((spigot,), a_generator) d = own_cooperate(items).whenDone() d.addCallback(accumulation_handler, spigot) return d
[ "def", "accumulate", "(", "a_generator", ",", "cooperator", "=", "None", ")", ":", "if", "cooperator", ":", "own_cooperate", "=", "cooperator", ".", "cooperate", "else", ":", "own_cooperate", "=", "cooperate", "spigot", "=", "ValueBucket", "(", ")", "items", "=", "stream_tap", "(", "(", "spigot", ",", ")", ",", "a_generator", ")", "d", "=", "own_cooperate", "(", "items", ")", ".", "whenDone", "(", ")", "d", ".", "addCallback", "(", "accumulation_handler", ",", "spigot", ")", "return", "d" ]
Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator. :param a_generator: An iterator which yields some not None values. :return: A Deferred to which the next callback will be called with the yielded contents of the generator function.
[ "Start", "a", "Deferred", "whose", "callBack", "arg", "is", "a", "deque", "of", "the", "accumulation", "of", "the", "values", "yielded", "from", "a_generator", "." ]
bec25451a6d2b06260be809b72cfd6287c75da39
https://github.com/johnwlockwood/cooperative/blob/bec25451a6d2b06260be809b72cfd6287c75da39/cooperative/__init__.py#L59-L77
244,641
johnwlockwood/cooperative
cooperative/__init__.py
batch_accumulate
def batch_accumulate(max_batch_size, a_generator, cooperator=None): """ Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator which is iterated over in batches the size of max_batch_size. It should be more efficient to iterate over the generator in batches and still provide enough speed for non-blocking execution. :param max_batch_size: The number of iterations of the generator to consume at a time. :param a_generator: An iterator which yields some not None values. :return: A Deferred to which the next callback will be called with the yielded contents of the generator function. """ if cooperator: own_cooperate = cooperator.cooperate else: own_cooperate = cooperate spigot = ValueBucket() items = stream_tap((spigot,), a_generator) d = own_cooperate(i_batch(max_batch_size, items)).whenDone() d.addCallback(accumulation_handler, spigot) return d
python
def batch_accumulate(max_batch_size, a_generator, cooperator=None): """ Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator which is iterated over in batches the size of max_batch_size. It should be more efficient to iterate over the generator in batches and still provide enough speed for non-blocking execution. :param max_batch_size: The number of iterations of the generator to consume at a time. :param a_generator: An iterator which yields some not None values. :return: A Deferred to which the next callback will be called with the yielded contents of the generator function. """ if cooperator: own_cooperate = cooperator.cooperate else: own_cooperate = cooperate spigot = ValueBucket() items = stream_tap((spigot,), a_generator) d = own_cooperate(i_batch(max_batch_size, items)).whenDone() d.addCallback(accumulation_handler, spigot) return d
[ "def", "batch_accumulate", "(", "max_batch_size", ",", "a_generator", ",", "cooperator", "=", "None", ")", ":", "if", "cooperator", ":", "own_cooperate", "=", "cooperator", ".", "cooperate", "else", ":", "own_cooperate", "=", "cooperate", "spigot", "=", "ValueBucket", "(", ")", "items", "=", "stream_tap", "(", "(", "spigot", ",", ")", ",", "a_generator", ")", "d", "=", "own_cooperate", "(", "i_batch", "(", "max_batch_size", ",", "items", ")", ")", ".", "whenDone", "(", ")", "d", ".", "addCallback", "(", "accumulation_handler", ",", "spigot", ")", "return", "d" ]
Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator which is iterated over in batches the size of max_batch_size. It should be more efficient to iterate over the generator in batches and still provide enough speed for non-blocking execution. :param max_batch_size: The number of iterations of the generator to consume at a time. :param a_generator: An iterator which yields some not None values. :return: A Deferred to which the next callback will be called with the yielded contents of the generator function.
[ "Start", "a", "Deferred", "whose", "callBack", "arg", "is", "a", "deque", "of", "the", "accumulation", "of", "the", "values", "yielded", "from", "a_generator", "which", "is", "iterated", "over", "in", "batches", "the", "size", "of", "max_batch_size", "." ]
bec25451a6d2b06260be809b72cfd6287c75da39
https://github.com/johnwlockwood/cooperative/blob/bec25451a6d2b06260be809b72cfd6287c75da39/cooperative/__init__.py#L80-L105
244,642
alexpearce/jobmonitor
jobmonitor/start_worker.py
create_connection
def create_connection(): """Return a redis.Redis instance connected to REDIS_URL.""" # REDIS_URL is defined in .env and loaded into the environment by Honcho redis_url = os.getenv('REDIS_URL') # If it's not defined, use the Redis default if not redis_url: redis_url = 'redis://localhost:6379' urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) return redis.StrictRedis( host=url.hostname, port=url.port, db=0, password=url.password )
python
def create_connection(): """Return a redis.Redis instance connected to REDIS_URL.""" # REDIS_URL is defined in .env and loaded into the environment by Honcho redis_url = os.getenv('REDIS_URL') # If it's not defined, use the Redis default if not redis_url: redis_url = 'redis://localhost:6379' urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) return redis.StrictRedis( host=url.hostname, port=url.port, db=0, password=url.password )
[ "def", "create_connection", "(", ")", ":", "# REDIS_URL is defined in .env and loaded into the environment by Honcho", "redis_url", "=", "os", ".", "getenv", "(", "'REDIS_URL'", ")", "# If it's not defined, use the Redis default", "if", "not", "redis_url", ":", "redis_url", "=", "'redis://localhost:6379'", "urlparse", ".", "uses_netloc", ".", "append", "(", "'redis'", ")", "url", "=", "urlparse", ".", "urlparse", "(", "redis_url", ")", "return", "redis", ".", "StrictRedis", "(", "host", "=", "url", ".", "hostname", ",", "port", "=", "url", ".", "port", ",", "db", "=", "0", ",", "password", "=", "url", ".", "password", ")" ]
Return a redis.Redis instance connected to REDIS_URL.
[ "Return", "a", "redis", ".", "Redis", "instance", "connected", "to", "REDIS_URL", "." ]
c08955ed3c357b2b3518aa0853b43bc237bc0814
https://github.com/alexpearce/jobmonitor/blob/c08955ed3c357b2b3518aa0853b43bc237bc0814/jobmonitor/start_worker.py#L16-L30
244,643
alexpearce/jobmonitor
jobmonitor/start_worker.py
work
def work(): """Start an rq worker on the connection provided by create_connection.""" with rq.Connection(create_connection()): worker = rq.Worker(list(map(rq.Queue, listen))) worker.work()
python
def work(): """Start an rq worker on the connection provided by create_connection.""" with rq.Connection(create_connection()): worker = rq.Worker(list(map(rq.Queue, listen))) worker.work()
[ "def", "work", "(", ")", ":", "with", "rq", ".", "Connection", "(", "create_connection", "(", ")", ")", ":", "worker", "=", "rq", ".", "Worker", "(", "list", "(", "map", "(", "rq", ".", "Queue", ",", "listen", ")", ")", ")", "worker", ".", "work", "(", ")" ]
Start an rq worker on the connection provided by create_connection.
[ "Start", "an", "rq", "worker", "on", "the", "connection", "provided", "by", "create_connection", "." ]
c08955ed3c357b2b3518aa0853b43bc237bc0814
https://github.com/alexpearce/jobmonitor/blob/c08955ed3c357b2b3518aa0853b43bc237bc0814/jobmonitor/start_worker.py#L33-L37
244,644
pydsigner/pygu
pygu/pms.py
Playlist._gen_shuffles
def _gen_shuffles(self): ''' Used internally to build a list for mapping between a random number and a song index. ''' # The current metasong index si = 0 # The shuffle mapper list self.shuffles = [] # Go through all our songs... for song in self.loop: # And add them to the list as many times as they say to. for i in range(song[1]): self.shuffles.append(si) si += 1
python
def _gen_shuffles(self): ''' Used internally to build a list for mapping between a random number and a song index. ''' # The current metasong index si = 0 # The shuffle mapper list self.shuffles = [] # Go through all our songs... for song in self.loop: # And add them to the list as many times as they say to. for i in range(song[1]): self.shuffles.append(si) si += 1
[ "def", "_gen_shuffles", "(", "self", ")", ":", "# The current metasong index ", "si", "=", "0", "# The shuffle mapper list", "self", ".", "shuffles", "=", "[", "]", "# Go through all our songs...", "for", "song", "in", "self", ".", "loop", ":", "# And add them to the list as many times as they say to.", "for", "i", "in", "range", "(", "song", "[", "1", "]", ")", ":", "self", ".", "shuffles", ".", "append", "(", "si", ")", "si", "+=", "1" ]
Used internally to build a list for mapping between a random number and a song index.
[ "Used", "internally", "to", "build", "a", "list", "for", "mapping", "between", "a", "random", "number", "and", "a", "song", "index", "." ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pms.py#L109-L123
244,645
pydsigner/pygu
pygu/pms.py
Playlist._new_song
def _new_song(self): ''' Used internally to get a metasong index. ''' # We'll need this later s = self.song if self.shuffle: # If shuffle is on, we need to (1) get a random song that # (2) accounts for weighting. This line does both. self.song = self.shuffles[random.randrange(len(self.shuffles))] else: # Nice and easy, just get the next song... self.song += 1 # But wait! need to make sure it exists! if self.song >= len(self.loop): # It doesn't, so start over at the beginning. self.song = 0 # Set flag if we have the same song as we had before. self.dif_song = s != self.song # Reset the position within the metasong self.pos = 0
python
def _new_song(self): ''' Used internally to get a metasong index. ''' # We'll need this later s = self.song if self.shuffle: # If shuffle is on, we need to (1) get a random song that # (2) accounts for weighting. This line does both. self.song = self.shuffles[random.randrange(len(self.shuffles))] else: # Nice and easy, just get the next song... self.song += 1 # But wait! need to make sure it exists! if self.song >= len(self.loop): # It doesn't, so start over at the beginning. self.song = 0 # Set flag if we have the same song as we had before. self.dif_song = s != self.song # Reset the position within the metasong self.pos = 0
[ "def", "_new_song", "(", "self", ")", ":", "# We'll need this later", "s", "=", "self", ".", "song", "if", "self", ".", "shuffle", ":", "# If shuffle is on, we need to (1) get a random song that ", "# (2) accounts for weighting. This line does both.", "self", ".", "song", "=", "self", ".", "shuffles", "[", "random", ".", "randrange", "(", "len", "(", "self", ".", "shuffles", ")", ")", "]", "else", ":", "# Nice and easy, just get the next song...", "self", ".", "song", "+=", "1", "# But wait! need to make sure it exists!", "if", "self", ".", "song", ">=", "len", "(", "self", ".", "loop", ")", ":", "# It doesn't, so start over at the beginning.", "self", ".", "song", "=", "0", "# Set flag if we have the same song as we had before.", "self", ".", "dif_song", "=", "s", "!=", "self", ".", "song", "# Reset the position within the metasong", "self", ".", "pos", "=", "0" ]
Used internally to get a metasong index.
[ "Used", "internally", "to", "get", "a", "metasong", "index", "." ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pms.py#L125-L146
244,646
pydsigner/pygu
pygu/pms.py
Playlist._get_selectable
def _get_selectable(self): ''' Used internally to get a group of choosable tracks. ''' # Save some typing cursong = self.loop[self.song][0] if self.dif_song and len(cursong) > 1: # Position is relative to the intro of the track, # so we we will get the both the intro and body. s = cursong[0] + cursong[1] else: # Position is relative to the body of the track, so just get that. s = cursong[-1] # Return what we found return s
python
def _get_selectable(self): ''' Used internally to get a group of choosable tracks. ''' # Save some typing cursong = self.loop[self.song][0] if self.dif_song and len(cursong) > 1: # Position is relative to the intro of the track, # so we we will get the both the intro and body. s = cursong[0] + cursong[1] else: # Position is relative to the body of the track, so just get that. s = cursong[-1] # Return what we found return s
[ "def", "_get_selectable", "(", "self", ")", ":", "# Save some typing", "cursong", "=", "self", ".", "loop", "[", "self", ".", "song", "]", "[", "0", "]", "if", "self", ".", "dif_song", "and", "len", "(", "cursong", ")", ">", "1", ":", "# Position is relative to the intro of the track,", "# so we we will get the both the intro and body.", "s", "=", "cursong", "[", "0", "]", "+", "cursong", "[", "1", "]", "else", ":", "# Position is relative to the body of the track, so just get that.", "s", "=", "cursong", "[", "-", "1", "]", "# Return what we found", "return", "s" ]
Used internally to get a group of choosable tracks.
[ "Used", "internally", "to", "get", "a", "group", "of", "choosable", "tracks", "." ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pms.py#L148-L163
244,647
pydsigner/pygu
pygu/pms.py
Playlist._get_song
def _get_song(self): ''' Used internally to get the current track and make sure it exists. ''' # Try to get the current track from the start metasong if self.at_beginning: # Make sure it exists. if self.pos < len(self.start): # It exists, so return it. return self.start[self.pos] # It doesn't exist, so let's move on! self.at_beginning = False # Generate a new track selection self._new_track() # A bit more difficult than using the start metasong, # because we could have a beginning part. Call a function that gets all # applicable tracks from the metasong. s = self._get_selectable() # Make sure it is long enough while self.pos >= len(s): # Or pick a new metasong. self._new_song() # And repeat. s = self._get_selectable() # Found a track, return it. return s[self.pos]
python
def _get_song(self): ''' Used internally to get the current track and make sure it exists. ''' # Try to get the current track from the start metasong if self.at_beginning: # Make sure it exists. if self.pos < len(self.start): # It exists, so return it. return self.start[self.pos] # It doesn't exist, so let's move on! self.at_beginning = False # Generate a new track selection self._new_track() # A bit more difficult than using the start metasong, # because we could have a beginning part. Call a function that gets all # applicable tracks from the metasong. s = self._get_selectable() # Make sure it is long enough while self.pos >= len(s): # Or pick a new metasong. self._new_song() # And repeat. s = self._get_selectable() # Found a track, return it. return s[self.pos]
[ "def", "_get_song", "(", "self", ")", ":", "# Try to get the current track from the start metasong", "if", "self", ".", "at_beginning", ":", "# Make sure it exists.", "if", "self", ".", "pos", "<", "len", "(", "self", ".", "start", ")", ":", "# It exists, so return it.", "return", "self", ".", "start", "[", "self", ".", "pos", "]", "# It doesn't exist, so let's move on!", "self", ".", "at_beginning", "=", "False", "# Generate a new track selection", "self", ".", "_new_track", "(", ")", "# A bit more difficult than using the start metasong, ", "# because we could have a beginning part. Call a function that gets all ", "# applicable tracks from the metasong.", "s", "=", "self", ".", "_get_selectable", "(", ")", "# Make sure it is long enough", "while", "self", ".", "pos", ">=", "len", "(", "s", ")", ":", "# Or pick a new metasong.", "self", ".", "_new_song", "(", ")", "# And repeat.", "s", "=", "self", ".", "_get_selectable", "(", ")", "# Found a track, return it.", "return", "s", "[", "self", ".", "pos", "]" ]
Used internally to get the current track and make sure it exists.
[ "Used", "internally", "to", "get", "the", "current", "track", "and", "make", "sure", "it", "exists", "." ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pms.py#L165-L190
244,648
pydsigner/pygu
pygu/pms.py
Playlist.begin
def begin(self): ''' Start over and get a track. ''' # Check for a start metasong if self.start: # We are in the beginning song self.at_beginning = True # And on the first track. self.pos = 0 else: # We aren't in the beginning song self.at_beginning = False # So we need to get new one. self._new_song() return self._get_song()
python
def begin(self): ''' Start over and get a track. ''' # Check for a start metasong if self.start: # We are in the beginning song self.at_beginning = True # And on the first track. self.pos = 0 else: # We aren't in the beginning song self.at_beginning = False # So we need to get new one. self._new_song() return self._get_song()
[ "def", "begin", "(", "self", ")", ":", "# Check for a start metasong", "if", "self", ".", "start", ":", "# We are in the beginning song", "self", ".", "at_beginning", "=", "True", "# And on the first track.", "self", ".", "pos", "=", "0", "else", ":", "# We aren't in the beginning song", "self", ".", "at_beginning", "=", "False", "# So we need to get new one.", "self", ".", "_new_song", "(", ")", "return", "self", ".", "_get_song", "(", ")" ]
Start over and get a track.
[ "Start", "over", "and", "get", "a", "track", "." ]
09fe71534900933908ab83db12f5659b7827e31c
https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pms.py#L192-L207
244,649
Nixiware/viper
nx/viper/service/mysql.py
Service._applicationStart
def _applicationStart(self, data): """ Initializes the database connection pool. :param data: <object> event data object :return: <void> """ checkup = False if "viper.mysql" in self.application.config \ and isinstance(self.application.config["viper.mysql"], dict): if "host" in self.application.config["viper.mysql"] and \ "port" in self.application.config["viper.mysql"] and \ "name" in self.application.config["viper.mysql"]: if len(self.application.config["viper.mysql"]["host"]) > 0 and \ self.application.config["viper.mysql"]["port"] > 0 and \ len(self.application.config["viper.mysql"]["name"]) > 0: checkup = True if checkup is not True: return try: self._connectionPool = adbapi.ConnectionPool( "MySQLdb", host=self.application.config["viper.mysql"]["host"], port=int(self.application.config["viper.mysql"]["port"]), user=self.application.config["viper.mysql"]["username"], passwd=self.application.config["viper.mysql"]["password"], db=self.application.config["viper.mysql"]["name"], charset=self.application.config["viper.mysql"]["charset"], cp_min=int( self.application.config["viper.mysql"]["connectionsMinimum"] ), cp_max=int( self.application.config["viper.mysql"]["connectionsMaximum"] ), cp_reconnect=True ) except Exception as e: self.log.error( "[Viper.MySQL] Cannot connect to server. Error: {error}", error=str(e) ) if "init" in self.application.config["viper.mysql"] \ and self.application.config["viper.mysql"]["init"]["runIfEmpty"]: self._checkIfDatabaseIsEmpty( lambda isEmpty: self._scheduleDatabaseInit(isEmpty) , lambda error: self.log.error("[Viper.MySQL] Cannot check if database is empty. Error {error}", error=error) )
python
def _applicationStart(self, data): """ Initializes the database connection pool. :param data: <object> event data object :return: <void> """ checkup = False if "viper.mysql" in self.application.config \ and isinstance(self.application.config["viper.mysql"], dict): if "host" in self.application.config["viper.mysql"] and \ "port" in self.application.config["viper.mysql"] and \ "name" in self.application.config["viper.mysql"]: if len(self.application.config["viper.mysql"]["host"]) > 0 and \ self.application.config["viper.mysql"]["port"] > 0 and \ len(self.application.config["viper.mysql"]["name"]) > 0: checkup = True if checkup is not True: return try: self._connectionPool = adbapi.ConnectionPool( "MySQLdb", host=self.application.config["viper.mysql"]["host"], port=int(self.application.config["viper.mysql"]["port"]), user=self.application.config["viper.mysql"]["username"], passwd=self.application.config["viper.mysql"]["password"], db=self.application.config["viper.mysql"]["name"], charset=self.application.config["viper.mysql"]["charset"], cp_min=int( self.application.config["viper.mysql"]["connectionsMinimum"] ), cp_max=int( self.application.config["viper.mysql"]["connectionsMaximum"] ), cp_reconnect=True ) except Exception as e: self.log.error( "[Viper.MySQL] Cannot connect to server. Error: {error}", error=str(e) ) if "init" in self.application.config["viper.mysql"] \ and self.application.config["viper.mysql"]["init"]["runIfEmpty"]: self._checkIfDatabaseIsEmpty( lambda isEmpty: self._scheduleDatabaseInit(isEmpty) , lambda error: self.log.error("[Viper.MySQL] Cannot check if database is empty. Error {error}", error=error) )
[ "def", "_applicationStart", "(", "self", ",", "data", ")", ":", "checkup", "=", "False", "if", "\"viper.mysql\"", "in", "self", ".", "application", ".", "config", "and", "isinstance", "(", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", ",", "dict", ")", ":", "if", "\"host\"", "in", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "and", "\"port\"", "in", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "and", "\"name\"", "in", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", ":", "if", "len", "(", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"host\"", "]", ")", ">", "0", "and", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"port\"", "]", ">", "0", "and", "len", "(", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"name\"", "]", ")", ">", "0", ":", "checkup", "=", "True", "if", "checkup", "is", "not", "True", ":", "return", "try", ":", "self", ".", "_connectionPool", "=", "adbapi", ".", "ConnectionPool", "(", "\"MySQLdb\"", ",", "host", "=", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"host\"", "]", ",", "port", "=", "int", "(", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"port\"", "]", ")", ",", "user", "=", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"username\"", "]", ",", "passwd", "=", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"password\"", "]", ",", "db", "=", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"name\"", "]", ",", "charset", "=", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"charset\"", "]", ",", "cp_min", "=", "int", "(", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"connectionsMinimum\"", "]", ")", ",", "cp_max", "=", "int", "(", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"connectionsMaximum\"", "]", ")", ",", "cp_reconnect", "=", "True", ")", "except", "Exception", "as", "e", ":", "self", ".", "log", ".", "error", "(", "\"[Viper.MySQL] Cannot connect to server. Error: {error}\"", ",", "error", "=", "str", "(", "e", ")", ")", "if", "\"init\"", "in", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "and", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"init\"", "]", "[", "\"runIfEmpty\"", "]", ":", "self", ".", "_checkIfDatabaseIsEmpty", "(", "lambda", "isEmpty", ":", "self", ".", "_scheduleDatabaseInit", "(", "isEmpty", ")", ",", "lambda", "error", ":", "self", ".", "log", ".", "error", "(", "\"[Viper.MySQL] Cannot check if database is empty. Error {error}\"", ",", "error", "=", "error", ")", ")" ]
Initializes the database connection pool. :param data: <object> event data object :return: <void>
[ "Initializes", "the", "database", "connection", "pool", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L27-L82
244,650
Nixiware/viper
nx/viper/service/mysql.py
Service._checkIfDatabaseIsEmpty
def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): """ Check if database contains any tables. :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument is a boolean flag specifying if the database is empty or not :param failHandler: <function(<str>)> method called if interrogation failed where the first argument is the error message :return: <void> """ def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() if failHandler is not None: reactor.callInThread(failHandler, errorMessage) def selectCallback(transaction, successHandler): querySelect = \ "SELECT `TABLE_NAME` " \ "FROM INFORMATION_SCHEMA.TABLES " \ "WHERE " \ "`TABLE_SCHEMA` = %s" \ ";" try: transaction.execute( querySelect, (self.application.config["viper.mysql"]["name"],) ) tables = transaction.fetchall() except Exception as e: failCallback(e) return if successHandler is not None: reactor.callInThread(successHandler, len(tables) == 0) interaction = self.runInteraction(selectCallback, successHandler) interaction.addErrback(failCallback)
python
def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): """ Check if database contains any tables. :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument is a boolean flag specifying if the database is empty or not :param failHandler: <function(<str>)> method called if interrogation failed where the first argument is the error message :return: <void> """ def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() if failHandler is not None: reactor.callInThread(failHandler, errorMessage) def selectCallback(transaction, successHandler): querySelect = \ "SELECT `TABLE_NAME` " \ "FROM INFORMATION_SCHEMA.TABLES " \ "WHERE " \ "`TABLE_SCHEMA` = %s" \ ";" try: transaction.execute( querySelect, (self.application.config["viper.mysql"]["name"],) ) tables = transaction.fetchall() except Exception as e: failCallback(e) return if successHandler is not None: reactor.callInThread(successHandler, len(tables) == 0) interaction = self.runInteraction(selectCallback, successHandler) interaction.addErrback(failCallback)
[ "def", "_checkIfDatabaseIsEmpty", "(", "self", ",", "successHandler", "=", "None", ",", "failHandler", "=", "None", ")", ":", "def", "failCallback", "(", "error", ")", ":", "errorMessage", "=", "str", "(", "error", ")", "if", "isinstance", "(", "error", ",", "Failure", ")", ":", "errorMessage", "=", "error", ".", "getErrorMessage", "(", ")", "if", "failHandler", "is", "not", "None", ":", "reactor", ".", "callInThread", "(", "failHandler", ",", "errorMessage", ")", "def", "selectCallback", "(", "transaction", ",", "successHandler", ")", ":", "querySelect", "=", "\"SELECT `TABLE_NAME` \"", "\"FROM INFORMATION_SCHEMA.TABLES \"", "\"WHERE \"", "\"`TABLE_SCHEMA` = %s\"", "\";\"", "try", ":", "transaction", ".", "execute", "(", "querySelect", ",", "(", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"name\"", "]", ",", ")", ")", "tables", "=", "transaction", ".", "fetchall", "(", ")", "except", "Exception", "as", "e", ":", "failCallback", "(", "e", ")", "return", "if", "successHandler", "is", "not", "None", ":", "reactor", ".", "callInThread", "(", "successHandler", ",", "len", "(", "tables", ")", "==", "0", ")", "interaction", "=", "self", ".", "runInteraction", "(", "selectCallback", ",", "successHandler", ")", "interaction", ".", "addErrback", "(", "failCallback", ")" ]
Check if database contains any tables. :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument is a boolean flag specifying if the database is empty or not :param failHandler: <function(<str>)> method called if interrogation failed where the first argument is the error message :return: <void>
[ "Check", "if", "database", "contains", "any", "tables", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L84-L125
244,651
Nixiware/viper
nx/viper/service/mysql.py
Service._initDatabase
def _initDatabase(self): """ Initializes the database structure based on application configuration. :return: <void> """ queries = [] if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: sqlFile = open(scriptFilePath, "r") queriesInFile = self.extractFromSQLFile(sqlFile) sqlFile.close() queries.extend(queriesInFile) def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() self.log.error( "[Viper.MySQL] _initDatabase() database error: {errorMessage}", errorMessage=errorMessage ) def runCallback(transaction, queries): try: for query in queries: transaction.execute(query) except Exception as e: failCallback(e) return interaction = self.runInteraction(runCallback, queries) interaction.addErrback(failCallback)
python
def _initDatabase(self): """ Initializes the database structure based on application configuration. :return: <void> """ queries = [] if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: sqlFile = open(scriptFilePath, "r") queriesInFile = self.extractFromSQLFile(sqlFile) sqlFile.close() queries.extend(queriesInFile) def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() self.log.error( "[Viper.MySQL] _initDatabase() database error: {errorMessage}", errorMessage=errorMessage ) def runCallback(transaction, queries): try: for query in queries: transaction.execute(query) except Exception as e: failCallback(e) return interaction = self.runInteraction(runCallback, queries) interaction.addErrback(failCallback)
[ "def", "_initDatabase", "(", "self", ")", ":", "queries", "=", "[", "]", "if", "len", "(", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"init\"", "]", "[", "\"scripts\"", "]", ")", ">", "0", ":", "for", "scriptFilePath", "in", "self", ".", "application", ".", "config", "[", "\"viper.mysql\"", "]", "[", "\"init\"", "]", "[", "\"scripts\"", "]", ":", "sqlFile", "=", "open", "(", "scriptFilePath", ",", "\"r\"", ")", "queriesInFile", "=", "self", ".", "extractFromSQLFile", "(", "sqlFile", ")", "sqlFile", ".", "close", "(", ")", "queries", ".", "extend", "(", "queriesInFile", ")", "def", "failCallback", "(", "error", ")", ":", "errorMessage", "=", "str", "(", "error", ")", "if", "isinstance", "(", "error", ",", "Failure", ")", ":", "errorMessage", "=", "error", ".", "getErrorMessage", "(", ")", "self", ".", "log", ".", "error", "(", "\"[Viper.MySQL] _initDatabase() database error: {errorMessage}\"", ",", "errorMessage", "=", "errorMessage", ")", "def", "runCallback", "(", "transaction", ",", "queries", ")", ":", "try", ":", "for", "query", "in", "queries", ":", "transaction", ".", "execute", "(", "query", ")", "except", "Exception", "as", "e", ":", "failCallback", "(", "e", ")", "return", "interaction", "=", "self", ".", "runInteraction", "(", "runCallback", ",", "queries", ")", "interaction", ".", "addErrback", "(", "failCallback", ")" ]
Initializes the database structure based on application configuration. :return: <void>
[ "Initializes", "the", "database", "structure", "based", "on", "application", "configuration", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L127-L162
244,652
Nixiware/viper
nx/viper/service/mysql.py
Service.extractFromSQLFile
def extractFromSQLFile(self, filePointer, delimiter=";"): """ Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file pointer to SQL file :return: <list> list of queries """ data = filePointer.read() # reading file and splitting it into lines dataLines = [] dataLinesIndex = 0 for c in data: if len(dataLines) - 1 < dataLinesIndex: dataLines.append("") if c == "\r\n" or c == "\r" or c == "\n": dataLinesIndex += 1 else: dataLines[dataLinesIndex] = "{}{}".format( dataLines[dataLinesIndex], c ) # forming SQL statements from all lines provided statements = [] statementsIndex = 0 for line in dataLines: # ignoring comments if line.startswith("--") or line.startswith("#"): continue # removing spaces line = line.strip() # ignoring blank lines if len(line) == 0: continue # appending each character to it's statement until delimiter is reached for c in line: if len(statements) - 1 < statementsIndex: statements.append("") statements[statementsIndex] = "{}{}".format( statements[statementsIndex], c ) if c == delimiter: statementsIndex += 1 return statements
python
def extractFromSQLFile(self, filePointer, delimiter=";"): """ Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file pointer to SQL file :return: <list> list of queries """ data = filePointer.read() # reading file and splitting it into lines dataLines = [] dataLinesIndex = 0 for c in data: if len(dataLines) - 1 < dataLinesIndex: dataLines.append("") if c == "\r\n" or c == "\r" or c == "\n": dataLinesIndex += 1 else: dataLines[dataLinesIndex] = "{}{}".format( dataLines[dataLinesIndex], c ) # forming SQL statements from all lines provided statements = [] statementsIndex = 0 for line in dataLines: # ignoring comments if line.startswith("--") or line.startswith("#"): continue # removing spaces line = line.strip() # ignoring blank lines if len(line) == 0: continue # appending each character to it's statement until delimiter is reached for c in line: if len(statements) - 1 < statementsIndex: statements.append("") statements[statementsIndex] = "{}{}".format( statements[statementsIndex], c ) if c == delimiter: statementsIndex += 1 return statements
[ "def", "extractFromSQLFile", "(", "self", ",", "filePointer", ",", "delimiter", "=", "\";\"", ")", ":", "data", "=", "filePointer", ".", "read", "(", ")", "# reading file and splitting it into lines", "dataLines", "=", "[", "]", "dataLinesIndex", "=", "0", "for", "c", "in", "data", ":", "if", "len", "(", "dataLines", ")", "-", "1", "<", "dataLinesIndex", ":", "dataLines", ".", "append", "(", "\"\"", ")", "if", "c", "==", "\"\\r\\n\"", "or", "c", "==", "\"\\r\"", "or", "c", "==", "\"\\n\"", ":", "dataLinesIndex", "+=", "1", "else", ":", "dataLines", "[", "dataLinesIndex", "]", "=", "\"{}{}\"", ".", "format", "(", "dataLines", "[", "dataLinesIndex", "]", ",", "c", ")", "# forming SQL statements from all lines provided", "statements", "=", "[", "]", "statementsIndex", "=", "0", "for", "line", "in", "dataLines", ":", "# ignoring comments", "if", "line", ".", "startswith", "(", "\"--\"", ")", "or", "line", ".", "startswith", "(", "\"#\"", ")", ":", "continue", "# removing spaces", "line", "=", "line", ".", "strip", "(", ")", "# ignoring blank lines", "if", "len", "(", "line", ")", "==", "0", ":", "continue", "# appending each character to it's statement until delimiter is reached", "for", "c", "in", "line", ":", "if", "len", "(", "statements", ")", "-", "1", "<", "statementsIndex", ":", "statements", ".", "append", "(", "\"\"", ")", "statements", "[", "statementsIndex", "]", "=", "\"{}{}\"", ".", "format", "(", "statements", "[", "statementsIndex", "]", ",", "c", ")", "if", "c", "==", "delimiter", ":", "statementsIndex", "+=", "1", "return", "statements" ]
Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file pointer to SQL file :return: <list> list of queries
[ "Process", "an", "SQL", "file", "and", "extract", "all", "the", "queries", "sorted", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L174-L226
244,653
Nixiware/viper
nx/viper/service/mysql.py
Service.runInteraction
def runInteraction(self, interaction, *args, **kwargs): """ Interact with the database and return the result. :param interaction: <function> method with first argument is a <adbapi.Transaction> instance :param args: additional positional arguments to be passed to interaction :param kwargs: keyword arguments to be passed to interaction :return: <defer> """ try: return self._connectionPool.runInteraction( interaction, *args, **kwargs ) except: d = defer.Deferred() d.errback() return d
python
def runInteraction(self, interaction, *args, **kwargs): """ Interact with the database and return the result. :param interaction: <function> method with first argument is a <adbapi.Transaction> instance :param args: additional positional arguments to be passed to interaction :param kwargs: keyword arguments to be passed to interaction :return: <defer> """ try: return self._connectionPool.runInteraction( interaction, *args, **kwargs ) except: d = defer.Deferred() d.errback() return d
[ "def", "runInteraction", "(", "self", ",", "interaction", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "_connectionPool", ".", "runInteraction", "(", "interaction", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", ":", "d", "=", "defer", ".", "Deferred", "(", ")", "d", ".", "errback", "(", ")", "return", "d" ]
Interact with the database and return the result. :param interaction: <function> method with first argument is a <adbapi.Transaction> instance :param args: additional positional arguments to be passed to interaction :param kwargs: keyword arguments to be passed to interaction :return: <defer>
[ "Interact", "with", "the", "database", "and", "return", "the", "result", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L228-L246
244,654
Nixiware/viper
nx/viper/service/mysql.py
Service.runQuery
def runQuery(self, *args, **kwargs): """ Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runQuery(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
python
def runQuery(self, *args, **kwargs): """ Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runQuery(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
[ "def", "runQuery", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "_connectionPool", ".", "runQuery", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ":", "d", "=", "defer", ".", "Deferred", "(", ")", "d", ".", "errback", "(", ")", "return", "d" ]
Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer>
[ "Execute", "an", "SQL", "query", "and", "return", "the", "result", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L248-L261
244,655
twidi/py-dataql
dataql/solvers/resources.py
Solver.solve
def solve(self, value, resource): """Solve a resource with a value. Arguments --------- value : ? A value to solve in combination with the given resource. The first filter of the resource will be applied on this value (next filters on the result of the previous filter). resource : dataql.resources.Resource An instance of a subclass of ``Resource`` to solve with the given value. Returns ------- (depends on the implementation of the ``coerce`` method) Raises ------ CannotSolve If a solver accepts to solve a resource but cannot finally solve it. Allows ``Registry.solve_resource`` to use the next available solver. Notes ----- This method simply calls ``solve_value``, then ``coerce`` with the result. To change the behavior, simply override at least one of these two methods. """ result = self.solve_value(value, resource) return self.coerce(result, resource)
python
def solve(self, value, resource): """Solve a resource with a value. Arguments --------- value : ? A value to solve in combination with the given resource. The first filter of the resource will be applied on this value (next filters on the result of the previous filter). resource : dataql.resources.Resource An instance of a subclass of ``Resource`` to solve with the given value. Returns ------- (depends on the implementation of the ``coerce`` method) Raises ------ CannotSolve If a solver accepts to solve a resource but cannot finally solve it. Allows ``Registry.solve_resource`` to use the next available solver. Notes ----- This method simply calls ``solve_value``, then ``coerce`` with the result. To change the behavior, simply override at least one of these two methods. """ result = self.solve_value(value, resource) return self.coerce(result, resource)
[ "def", "solve", "(", "self", ",", "value", ",", "resource", ")", ":", "result", "=", "self", ".", "solve_value", "(", "value", ",", "resource", ")", "return", "self", ".", "coerce", "(", "result", ",", "resource", ")" ]
Solve a resource with a value. Arguments --------- value : ? A value to solve in combination with the given resource. The first filter of the resource will be applied on this value (next filters on the result of the previous filter). resource : dataql.resources.Resource An instance of a subclass of ``Resource`` to solve with the given value. Returns ------- (depends on the implementation of the ``coerce`` method) Raises ------ CannotSolve If a solver accepts to solve a resource but cannot finally solve it. Allows ``Registry.solve_resource`` to use the next available solver. Notes ----- This method simply calls ``solve_value``, then ``coerce`` with the result. To change the behavior, simply override at least one of these two methods.
[ "Solve", "a", "resource", "with", "a", "value", "." ]
5841a3fd559829193ed709c255166085bdde1c52
https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/solvers/resources.py#L80-L110
244,656
twidi/py-dataql
dataql/solvers/resources.py
Solver.solve_value
def solve_value(self, value, resource): """Solve a resource with a value, without coercing. Arguments --------- value : ? A value to solve in combination with the given resource. The first filter of the resource will be applied on this value (next filters on the result of the previous filter). resource : dataql.resources.Resource An instance of a subclass of ``Resource`` to solve with the given value. Returns ------- The result of all filters applied on the value for the first filter, and result of the previous filter for next filters. Example ------- >>> from dataql.solvers.registry import Registry >>> registry = Registry() >>> from datetime import date >>> registry.register(date, allow_class=True) >>> registry.register(str) >>> class MySolver(Solver): ... def coerce(self, value, resource): return value >>> solver = MySolver(registry) >>> from dataql.resources import Filter, NamedArg, PosArg, SliceFilter >>> field = Field(None, ... filters=[ ... Filter(name='fromtimestamp', args=[PosArg(1433109600)]), ... Filter(name='replace', args=[NamedArg('year', '=', 2014)]), ... Filter(name='strftime', args=[PosArg('%F')]), ... Filter(name='replace', args=[PosArg('2014'), PosArg('2015')]), ... ] ... ) >>> solver.solve_value(date, field) '2015-06-01' >>> solver.solve_value(None, field) >>> d = {'foo': {'date': date(2015, 6, 1)}, 'bar': {'date': None}, 'baz': [{'date': None}]} >>> registry.register(dict) >>> solver.solve_value(d, Field(None, filters=[ ... Filter(name='foo'), ... Filter(name='date'), ... Filter(name='strftime', args=[PosArg('%F')]), ... ])) '2015-06-01' >>> solver.solve_value(d, Field(None, filters=[ ... Filter(name='bar'), ... Filter(name='date'), ... Filter(name='strftime', args=[PosArg('%F')]), ... ])) >>> solver.solve_value(d, Field(None, filters=[ ... Filter(name='baz'), ... SliceFilter(0), ... Filter(name='date'), ... Filter(name='strftime', args=[PosArg('%F')]), ... ])) # Example of how to raise a ``CannotSolve`` exception. >>> from dataql.solvers.exceptions import CannotSolve >>> raise CannotSolve(solver, Field('fromtimestamp'), date) # doctest: +ELLIPSIS Traceback (most recent call last): dataql...CannotSolve: Solver `<MySolver>` was not able to solve...`<Field[fromtimestamp]>`. """ # The given value is the starting point on which we apply the first filter. result = value # Apply filters one by one on the previous result. if result is not None: for filter_ in resource.filters: result = self.registry.solve_filter(result, filter_) if result is None: break return result
python
def solve_value(self, value, resource): """Solve a resource with a value, without coercing. Arguments --------- value : ? A value to solve in combination with the given resource. The first filter of the resource will be applied on this value (next filters on the result of the previous filter). resource : dataql.resources.Resource An instance of a subclass of ``Resource`` to solve with the given value. Returns ------- The result of all filters applied on the value for the first filter, and result of the previous filter for next filters. Example ------- >>> from dataql.solvers.registry import Registry >>> registry = Registry() >>> from datetime import date >>> registry.register(date, allow_class=True) >>> registry.register(str) >>> class MySolver(Solver): ... def coerce(self, value, resource): return value >>> solver = MySolver(registry) >>> from dataql.resources import Filter, NamedArg, PosArg, SliceFilter >>> field = Field(None, ... filters=[ ... Filter(name='fromtimestamp', args=[PosArg(1433109600)]), ... Filter(name='replace', args=[NamedArg('year', '=', 2014)]), ... Filter(name='strftime', args=[PosArg('%F')]), ... Filter(name='replace', args=[PosArg('2014'), PosArg('2015')]), ... ] ... ) >>> solver.solve_value(date, field) '2015-06-01' >>> solver.solve_value(None, field) >>> d = {'foo': {'date': date(2015, 6, 1)}, 'bar': {'date': None}, 'baz': [{'date': None}]} >>> registry.register(dict) >>> solver.solve_value(d, Field(None, filters=[ ... Filter(name='foo'), ... Filter(name='date'), ... Filter(name='strftime', args=[PosArg('%F')]), ... ])) '2015-06-01' >>> solver.solve_value(d, Field(None, filters=[ ... Filter(name='bar'), ... Filter(name='date'), ... Filter(name='strftime', args=[PosArg('%F')]), ... ])) >>> solver.solve_value(d, Field(None, filters=[ ... Filter(name='baz'), ... SliceFilter(0), ... Filter(name='date'), ... Filter(name='strftime', args=[PosArg('%F')]), ... ])) # Example of how to raise a ``CannotSolve`` exception. >>> from dataql.solvers.exceptions import CannotSolve >>> raise CannotSolve(solver, Field('fromtimestamp'), date) # doctest: +ELLIPSIS Traceback (most recent call last): dataql...CannotSolve: Solver `<MySolver>` was not able to solve...`<Field[fromtimestamp]>`. """ # The given value is the starting point on which we apply the first filter. result = value # Apply filters one by one on the previous result. if result is not None: for filter_ in resource.filters: result = self.registry.solve_filter(result, filter_) if result is None: break return result
[ "def", "solve_value", "(", "self", ",", "value", ",", "resource", ")", ":", "# The given value is the starting point on which we apply the first filter.", "result", "=", "value", "# Apply filters one by one on the previous result.", "if", "result", "is", "not", "None", ":", "for", "filter_", "in", "resource", ".", "filters", ":", "result", "=", "self", ".", "registry", ".", "solve_filter", "(", "result", ",", "filter_", ")", "if", "result", "is", "None", ":", "break", "return", "result" ]
Solve a resource with a value, without coercing. Arguments --------- value : ? A value to solve in combination with the given resource. The first filter of the resource will be applied on this value (next filters on the result of the previous filter). resource : dataql.resources.Resource An instance of a subclass of ``Resource`` to solve with the given value. Returns ------- The result of all filters applied on the value for the first filter, and result of the previous filter for next filters. Example ------- >>> from dataql.solvers.registry import Registry >>> registry = Registry() >>> from datetime import date >>> registry.register(date, allow_class=True) >>> registry.register(str) >>> class MySolver(Solver): ... def coerce(self, value, resource): return value >>> solver = MySolver(registry) >>> from dataql.resources import Filter, NamedArg, PosArg, SliceFilter >>> field = Field(None, ... filters=[ ... Filter(name='fromtimestamp', args=[PosArg(1433109600)]), ... Filter(name='replace', args=[NamedArg('year', '=', 2014)]), ... Filter(name='strftime', args=[PosArg('%F')]), ... Filter(name='replace', args=[PosArg('2014'), PosArg('2015')]), ... ] ... ) >>> solver.solve_value(date, field) '2015-06-01' >>> solver.solve_value(None, field) >>> d = {'foo': {'date': date(2015, 6, 1)}, 'bar': {'date': None}, 'baz': [{'date': None}]} >>> registry.register(dict) >>> solver.solve_value(d, Field(None, filters=[ ... Filter(name='foo'), ... Filter(name='date'), ... Filter(name='strftime', args=[PosArg('%F')]), ... ])) '2015-06-01' >>> solver.solve_value(d, Field(None, filters=[ ... Filter(name='bar'), ... Filter(name='date'), ... Filter(name='strftime', args=[PosArg('%F')]), ... ])) >>> solver.solve_value(d, Field(None, filters=[ ... Filter(name='baz'), ... SliceFilter(0), ... Filter(name='date'), ... Filter(name='strftime', args=[PosArg('%F')]), ... ])) # Example of how to raise a ``CannotSolve`` exception. >>> from dataql.solvers.exceptions import CannotSolve >>> raise CannotSolve(solver, Field('fromtimestamp'), date) # doctest: +ELLIPSIS Traceback (most recent call last): dataql...CannotSolve: Solver `<MySolver>` was not able to solve...`<Field[fromtimestamp]>`.
[ "Solve", "a", "resource", "with", "a", "value", "without", "coercing", "." ]
5841a3fd559829193ed709c255166085bdde1c52
https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/solvers/resources.py#L112-L192
244,657
twidi/py-dataql
dataql/solvers/resources.py
Solver.can_solve
def can_solve(cls, resource): """Tells if the solver is able to resolve the given resource. Arguments --------- resource : subclass of ``dataql.resources.Resource`` The resource to check if it is solvable by the current solver class Returns ------- boolean ``True`` if the current solver class can solve the given resource, ``False`` otherwise. Example ------- >>> AttributeSolver.solvable_resources (<class 'dataql.resources.Field'>,) >>> AttributeSolver.can_solve(Field('foo')) True >>> AttributeSolver.can_solve(Object('bar')) False """ for solvable_resource in cls.solvable_resources: if isinstance(resource, solvable_resource): return True return False
python
def can_solve(cls, resource): """Tells if the solver is able to resolve the given resource. Arguments --------- resource : subclass of ``dataql.resources.Resource`` The resource to check if it is solvable by the current solver class Returns ------- boolean ``True`` if the current solver class can solve the given resource, ``False`` otherwise. Example ------- >>> AttributeSolver.solvable_resources (<class 'dataql.resources.Field'>,) >>> AttributeSolver.can_solve(Field('foo')) True >>> AttributeSolver.can_solve(Object('bar')) False """ for solvable_resource in cls.solvable_resources: if isinstance(resource, solvable_resource): return True return False
[ "def", "can_solve", "(", "cls", ",", "resource", ")", ":", "for", "solvable_resource", "in", "cls", ".", "solvable_resources", ":", "if", "isinstance", "(", "resource", ",", "solvable_resource", ")", ":", "return", "True", "return", "False" ]
Tells if the solver is able to resolve the given resource. Arguments --------- resource : subclass of ``dataql.resources.Resource`` The resource to check if it is solvable by the current solver class Returns ------- boolean ``True`` if the current solver class can solve the given resource, ``False`` otherwise. Example ------- >>> AttributeSolver.solvable_resources (<class 'dataql.resources.Field'>,) >>> AttributeSolver.can_solve(Field('foo')) True >>> AttributeSolver.can_solve(Object('bar')) False
[ "Tells", "if", "the", "solver", "is", "able", "to", "resolve", "the", "given", "resource", "." ]
5841a3fd559829193ed709c255166085bdde1c52
https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/solvers/resources.py#L205-L233
244,658
twidi/py-dataql
dataql/solvers/resources.py
AttributeSolver.coerce
def coerce(self, value, resource): """Coerce the value to an acceptable one. Only these kinds of values are returned as is: - str - int - float - True - False - None For all others values, it will be coerced using ``self.coerce_default`` (with convert the value to a string in the default implementation). Arguments --------- value : ? The value to be coerced. resource : dataql.resources.Resource The ``Resource`` object used to obtain this value from the original one. Returns ------- str | int | float | True | False | None The coerced value. Example ------- >>> from dataql.solvers.registry import Registry >>> registry = Registry() >>> from datetime import date >>> registry.register(date) >>> solver = AttributeSolver(registry) >>> solver.coerce('foo', None) 'foo' >>> solver.coerce(11, None) 11 >>> solver.coerce(1.1, None) 1.1 >>> solver.coerce(True, None) True >>> solver.coerce(False, None) False >>> solver.coerce(date(2015, 6, 1), None) '2015-06-01' >>> solver.coerce(None, None) """ if value in (True, False, None): return value if isinstance(value, (int, float)): return value if isinstance(value, str): return value return self.coerce_default(value, resource)
python
def coerce(self, value, resource): """Coerce the value to an acceptable one. Only these kinds of values are returned as is: - str - int - float - True - False - None For all others values, it will be coerced using ``self.coerce_default`` (with convert the value to a string in the default implementation). Arguments --------- value : ? The value to be coerced. resource : dataql.resources.Resource The ``Resource`` object used to obtain this value from the original one. Returns ------- str | int | float | True | False | None The coerced value. Example ------- >>> from dataql.solvers.registry import Registry >>> registry = Registry() >>> from datetime import date >>> registry.register(date) >>> solver = AttributeSolver(registry) >>> solver.coerce('foo', None) 'foo' >>> solver.coerce(11, None) 11 >>> solver.coerce(1.1, None) 1.1 >>> solver.coerce(True, None) True >>> solver.coerce(False, None) False >>> solver.coerce(date(2015, 6, 1), None) '2015-06-01' >>> solver.coerce(None, None) """ if value in (True, False, None): return value if isinstance(value, (int, float)): return value if isinstance(value, str): return value return self.coerce_default(value, resource)
[ "def", "coerce", "(", "self", ",", "value", ",", "resource", ")", ":", "if", "value", "in", "(", "True", ",", "False", ",", "None", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "(", "int", ",", "float", ")", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "str", ")", ":", "return", "value", "return", "self", ".", "coerce_default", "(", "value", ",", "resource", ")" ]
Coerce the value to an acceptable one. Only these kinds of values are returned as is: - str - int - float - True - False - None For all others values, it will be coerced using ``self.coerce_default`` (with convert the value to a string in the default implementation). Arguments --------- value : ? The value to be coerced. resource : dataql.resources.Resource The ``Resource`` object used to obtain this value from the original one. Returns ------- str | int | float | True | False | None The coerced value. Example ------- >>> from dataql.solvers.registry import Registry >>> registry = Registry() >>> from datetime import date >>> registry.register(date) >>> solver = AttributeSolver(registry) >>> solver.coerce('foo', None) 'foo' >>> solver.coerce(11, None) 11 >>> solver.coerce(1.1, None) 1.1 >>> solver.coerce(True, None) True >>> solver.coerce(False, None) False >>> solver.coerce(date(2015, 6, 1), None) '2015-06-01' >>> solver.coerce(None, None)
[ "Coerce", "the", "value", "to", "an", "acceptable", "one", "." ]
5841a3fd559829193ed709c255166085bdde1c52
https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/solvers/resources.py#L261-L316
244,659
twidi/py-dataql
dataql/solvers/resources.py
ObjectSolver.coerce
def coerce(self, value, resource): """Get a dict with attributes from ``value``. Arguments --------- value : ? The value to get some resources from. resource : dataql.resources.Object The ``Object`` object used to obtain this value from the original one. Returns ------- dict A dictionary containing the wanted resources for the given value. Key are the ``name`` attributes of the resources, and the values are the solved values. """ return {r.name: self.registry.solve_resource(value, r) for r in resource.resources}
python
def coerce(self, value, resource): """Get a dict with attributes from ``value``. Arguments --------- value : ? The value to get some resources from. resource : dataql.resources.Object The ``Object`` object used to obtain this value from the original one. Returns ------- dict A dictionary containing the wanted resources for the given value. Key are the ``name`` attributes of the resources, and the values are the solved values. """ return {r.name: self.registry.solve_resource(value, r) for r in resource.resources}
[ "def", "coerce", "(", "self", ",", "value", ",", "resource", ")", ":", "return", "{", "r", ".", "name", ":", "self", ".", "registry", ".", "solve_resource", "(", "value", ",", "r", ")", "for", "r", "in", "resource", ".", "resources", "}" ]
Get a dict with attributes from ``value``. Arguments --------- value : ? The value to get some resources from. resource : dataql.resources.Object The ``Object`` object used to obtain this value from the original one. Returns ------- dict A dictionary containing the wanted resources for the given value. Key are the ``name`` attributes of the resources, and the values are the solved values.
[ "Get", "a", "dict", "with", "attributes", "from", "value", "." ]
5841a3fd559829193ed709c255166085bdde1c52
https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/solvers/resources.py#L382-L400
244,660
twidi/py-dataql
dataql/solvers/resources.py
ListSolver.coerce
def coerce(self, value, resource): """Convert a list of objects in a list of dicts. Arguments --------- value : iterable The list (or other iterable) to get values to get some resources from. resource : dataql.resources.List The ``List`` object used to obtain this value from the original one. Returns ------- list A list with one entry for each iteration get from ``value``. If the ``resource`` has only one sub-resource, each entry in the result list will be the result for the subresource for each iteration. If the ``resource`` has more that one sub-resource, each entry in the result list will be another list with an entry for each subresource for the current iteration. Raises ------ dataql.solvers.exceptions.NotIterable When the value is not iterable. """ if not isinstance(value, Iterable): raise NotIterable(resource, self.registry[value]) # Case #1: we only have one sub-resource, so we return a list with this item for # each iteration if len(resource.resources) == 1: res = resource.resources[0] return [self.registry.solve_resource(v, res) for v in value] # Case #2: we have many sub-resources, we return a list with, for each iteration, a # list with all entries return [ [self.registry.solve_resource(v, res) for res in resource.resources] for v in value ]
python
def coerce(self, value, resource): """Convert a list of objects in a list of dicts. Arguments --------- value : iterable The list (or other iterable) to get values to get some resources from. resource : dataql.resources.List The ``List`` object used to obtain this value from the original one. Returns ------- list A list with one entry for each iteration get from ``value``. If the ``resource`` has only one sub-resource, each entry in the result list will be the result for the subresource for each iteration. If the ``resource`` has more that one sub-resource, each entry in the result list will be another list with an entry for each subresource for the current iteration. Raises ------ dataql.solvers.exceptions.NotIterable When the value is not iterable. """ if not isinstance(value, Iterable): raise NotIterable(resource, self.registry[value]) # Case #1: we only have one sub-resource, so we return a list with this item for # each iteration if len(resource.resources) == 1: res = resource.resources[0] return [self.registry.solve_resource(v, res) for v in value] # Case #2: we have many sub-resources, we return a list with, for each iteration, a # list with all entries return [ [self.registry.solve_resource(v, res) for res in resource.resources] for v in value ]
[ "def", "coerce", "(", "self", ",", "value", ",", "resource", ")", ":", "if", "not", "isinstance", "(", "value", ",", "Iterable", ")", ":", "raise", "NotIterable", "(", "resource", ",", "self", ".", "registry", "[", "value", "]", ")", "# Case #1: we only have one sub-resource, so we return a list with this item for", "# each iteration", "if", "len", "(", "resource", ".", "resources", ")", "==", "1", ":", "res", "=", "resource", ".", "resources", "[", "0", "]", "return", "[", "self", ".", "registry", ".", "solve_resource", "(", "v", ",", "res", ")", "for", "v", "in", "value", "]", "# Case #2: we have many sub-resources, we return a list with, for each iteration, a", "# list with all entries", "return", "[", "[", "self", ".", "registry", ".", "solve_resource", "(", "v", ",", "res", ")", "for", "res", "in", "resource", ".", "resources", "]", "for", "v", "in", "value", "]" ]
Convert a list of objects in a list of dicts. Arguments --------- value : iterable The list (or other iterable) to get values to get some resources from. resource : dataql.resources.List The ``List`` object used to obtain this value from the original one. Returns ------- list A list with one entry for each iteration get from ``value``. If the ``resource`` has only one sub-resource, each entry in the result list will be the result for the subresource for each iteration. If the ``resource`` has more that one sub-resource, each entry in the result list will be another list with an entry for each subresource for the current iteration. Raises ------ dataql.solvers.exceptions.NotIterable When the value is not iterable.
[ "Convert", "a", "list", "of", "objects", "in", "a", "list", "of", "dicts", "." ]
5841a3fd559829193ed709c255166085bdde1c52
https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/solvers/resources.py#L469-L509
244,661
rikrd/inspire
inspirespeech/common.py
create_recordings_dictionary
def create_recordings_dictionary(list_selected, pronunciation_dictionary_filename, out_dictionary_filename, htk_trace, additional_dictionary_filenames=[]): """Create a pronunciation dictionary specific to a list of recordings""" temp_words_fd, temp_words_file = tempfile.mkstemp() words = set() for recording in list_selected: words |= set([w.upper() for w in get_words_from_recording(recording)]) with codecs.open(temp_words_file, 'w', 'utf-8') as f: f.writelines([u'{}\n'.format(w) for w in sorted(list(words))]) prepare_dictionary(temp_words_file, pronunciation_dictionary_filename, out_dictionary_filename, htk_trace, global_script_filename=config.project_path('etc/global.ded'), additional_dictionary_filenames=additional_dictionary_filenames) os.remove(temp_words_file) return
python
def create_recordings_dictionary(list_selected, pronunciation_dictionary_filename, out_dictionary_filename, htk_trace, additional_dictionary_filenames=[]): """Create a pronunciation dictionary specific to a list of recordings""" temp_words_fd, temp_words_file = tempfile.mkstemp() words = set() for recording in list_selected: words |= set([w.upper() for w in get_words_from_recording(recording)]) with codecs.open(temp_words_file, 'w', 'utf-8') as f: f.writelines([u'{}\n'.format(w) for w in sorted(list(words))]) prepare_dictionary(temp_words_file, pronunciation_dictionary_filename, out_dictionary_filename, htk_trace, global_script_filename=config.project_path('etc/global.ded'), additional_dictionary_filenames=additional_dictionary_filenames) os.remove(temp_words_file) return
[ "def", "create_recordings_dictionary", "(", "list_selected", ",", "pronunciation_dictionary_filename", ",", "out_dictionary_filename", ",", "htk_trace", ",", "additional_dictionary_filenames", "=", "[", "]", ")", ":", "temp_words_fd", ",", "temp_words_file", "=", "tempfile", ".", "mkstemp", "(", ")", "words", "=", "set", "(", ")", "for", "recording", "in", "list_selected", ":", "words", "|=", "set", "(", "[", "w", ".", "upper", "(", ")", "for", "w", "in", "get_words_from_recording", "(", "recording", ")", "]", ")", "with", "codecs", ".", "open", "(", "temp_words_file", ",", "'w'", ",", "'utf-8'", ")", "as", "f", ":", "f", ".", "writelines", "(", "[", "u'{}\\n'", ".", "format", "(", "w", ")", "for", "w", "in", "sorted", "(", "list", "(", "words", ")", ")", "]", ")", "prepare_dictionary", "(", "temp_words_file", ",", "pronunciation_dictionary_filename", ",", "out_dictionary_filename", ",", "htk_trace", ",", "global_script_filename", "=", "config", ".", "project_path", "(", "'etc/global.ded'", ")", ",", "additional_dictionary_filenames", "=", "additional_dictionary_filenames", ")", "os", ".", "remove", "(", "temp_words_file", ")", "return" ]
Create a pronunciation dictionary specific to a list of recordings
[ "Create", "a", "pronunciation", "dictionary", "specific", "to", "a", "list", "of", "recordings" ]
e281c0266a9a9633f34ab70f9c3ad58036c19b59
https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/common.py#L197-L218
244,662
rikrd/inspire
inspirespeech/common.py
utf8_normalize
def utf8_normalize(input_filename, comment_char='#', to_upper=False): """Normalize UTF-8 characters of a file """ # Prepare the input dictionary file in UTF-8 and NFC temp_dict_fd, output_filename = tempfile.mkstemp() logging.debug('to_nfc from file {} to file {}'.format(input_filename, output_filename)) with codecs.open(output_filename, 'w', 'utf-8') as f: with codecs.open(input_filename, 'r', 'utf-8') as input_f: lines = sorted([unicodedata.normalize(UTF8_NORMALIZATION, l) for l in input_f.readlines() if not l.strip().startswith(comment_char)]) if to_upper: lines = [l.upper() for l in lines] f.writelines(lines) return output_filename
python
def utf8_normalize(input_filename, comment_char='#', to_upper=False): """Normalize UTF-8 characters of a file """ # Prepare the input dictionary file in UTF-8 and NFC temp_dict_fd, output_filename = tempfile.mkstemp() logging.debug('to_nfc from file {} to file {}'.format(input_filename, output_filename)) with codecs.open(output_filename, 'w', 'utf-8') as f: with codecs.open(input_filename, 'r', 'utf-8') as input_f: lines = sorted([unicodedata.normalize(UTF8_NORMALIZATION, l) for l in input_f.readlines() if not l.strip().startswith(comment_char)]) if to_upper: lines = [l.upper() for l in lines] f.writelines(lines) return output_filename
[ "def", "utf8_normalize", "(", "input_filename", ",", "comment_char", "=", "'#'", ",", "to_upper", "=", "False", ")", ":", "# Prepare the input dictionary file in UTF-8 and NFC", "temp_dict_fd", ",", "output_filename", "=", "tempfile", ".", "mkstemp", "(", ")", "logging", ".", "debug", "(", "'to_nfc from file {} to file {}'", ".", "format", "(", "input_filename", ",", "output_filename", ")", ")", "with", "codecs", ".", "open", "(", "output_filename", ",", "'w'", ",", "'utf-8'", ")", "as", "f", ":", "with", "codecs", ".", "open", "(", "input_filename", ",", "'r'", ",", "'utf-8'", ")", "as", "input_f", ":", "lines", "=", "sorted", "(", "[", "unicodedata", ".", "normalize", "(", "UTF8_NORMALIZATION", ",", "l", ")", "for", "l", "in", "input_f", ".", "readlines", "(", ")", "if", "not", "l", ".", "strip", "(", ")", ".", "startswith", "(", "comment_char", ")", "]", ")", "if", "to_upper", ":", "lines", "=", "[", "l", ".", "upper", "(", ")", "for", "l", "in", "lines", "]", "f", ".", "writelines", "(", "lines", ")", "return", "output_filename" ]
Normalize UTF-8 characters of a file
[ "Normalize", "UTF", "-", "8", "characters", "of", "a", "file" ]
e281c0266a9a9633f34ab70f9c3ad58036c19b59
https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/common.py#L244-L262
244,663
rikrd/inspire
inspirespeech/common.py
create_flat_start_model
def create_flat_start_model(feature_filename, state_stay_probabilities, symbol_list, output_model_directory, output_prototype_filename, htk_trace): """ Creates a flat start model by using HCompV to compute the global mean and variance. Then uses these global mean and variance to create an N-state model for each symbol in the given list. :param feature_filename: The filename containing the audio and feature file pairs :param output_model_directory: The directory where to write the created model :param output_prototype_filename: The prototype model filename :param htk_trace: Trace level for HTK :rtype : None """ # Create a prototype model create_prototype_model(feature_filename, output_prototype_filename, state_stay_probabilities=state_stay_probabilities) # Compute the global mean and variance config.htk_command("HCompV -A -D -T {} -f 0.01 " "-S {} -m -o {} -M {} {}".format(htk_trace, feature_filename, 'proto', output_model_directory, output_prototype_filename)) # Create an hmmdefs using the global mean and variance for all states and symbols # Duplicate the model 'proto' -> symbol_list proto_model_filename = config.path(output_model_directory, 'proto') model = htk.load_model(proto_model_filename) model = htk_model_utils.map_hmms(model, {'proto': symbol_list}) # vFloors -> macros vfloors_filename = config.path(output_model_directory, 'vFloors') variance_model = htk.load_model(vfloors_filename) model['macros'] += variance_model['macros'] macros, hmmdefs = htk_model_utils.split_model(model) htk.save_model(macros, config.path(output_model_directory, 'macros')) htk.save_model(hmmdefs, config.path(output_model_directory, 'hmmdefs'))
python
def create_flat_start_model(feature_filename, state_stay_probabilities, symbol_list, output_model_directory, output_prototype_filename, htk_trace): """ Creates a flat start model by using HCompV to compute the global mean and variance. Then uses these global mean and variance to create an N-state model for each symbol in the given list. :param feature_filename: The filename containing the audio and feature file pairs :param output_model_directory: The directory where to write the created model :param output_prototype_filename: The prototype model filename :param htk_trace: Trace level for HTK :rtype : None """ # Create a prototype model create_prototype_model(feature_filename, output_prototype_filename, state_stay_probabilities=state_stay_probabilities) # Compute the global mean and variance config.htk_command("HCompV -A -D -T {} -f 0.01 " "-S {} -m -o {} -M {} {}".format(htk_trace, feature_filename, 'proto', output_model_directory, output_prototype_filename)) # Create an hmmdefs using the global mean and variance for all states and symbols # Duplicate the model 'proto' -> symbol_list proto_model_filename = config.path(output_model_directory, 'proto') model = htk.load_model(proto_model_filename) model = htk_model_utils.map_hmms(model, {'proto': symbol_list}) # vFloors -> macros vfloors_filename = config.path(output_model_directory, 'vFloors') variance_model = htk.load_model(vfloors_filename) model['macros'] += variance_model['macros'] macros, hmmdefs = htk_model_utils.split_model(model) htk.save_model(macros, config.path(output_model_directory, 'macros')) htk.save_model(hmmdefs, config.path(output_model_directory, 'hmmdefs'))
[ "def", "create_flat_start_model", "(", "feature_filename", ",", "state_stay_probabilities", ",", "symbol_list", ",", "output_model_directory", ",", "output_prototype_filename", ",", "htk_trace", ")", ":", "# Create a prototype model", "create_prototype_model", "(", "feature_filename", ",", "output_prototype_filename", ",", "state_stay_probabilities", "=", "state_stay_probabilities", ")", "# Compute the global mean and variance", "config", ".", "htk_command", "(", "\"HCompV -A -D -T {} -f 0.01 \"", "\"-S {} -m -o {} -M {} {}\"", ".", "format", "(", "htk_trace", ",", "feature_filename", ",", "'proto'", ",", "output_model_directory", ",", "output_prototype_filename", ")", ")", "# Create an hmmdefs using the global mean and variance for all states and symbols", "# Duplicate the model 'proto' -> symbol_list", "proto_model_filename", "=", "config", ".", "path", "(", "output_model_directory", ",", "'proto'", ")", "model", "=", "htk", ".", "load_model", "(", "proto_model_filename", ")", "model", "=", "htk_model_utils", ".", "map_hmms", "(", "model", ",", "{", "'proto'", ":", "symbol_list", "}", ")", "# vFloors -> macros", "vfloors_filename", "=", "config", ".", "path", "(", "output_model_directory", ",", "'vFloors'", ")", "variance_model", "=", "htk", ".", "load_model", "(", "vfloors_filename", ")", "model", "[", "'macros'", "]", "+=", "variance_model", "[", "'macros'", "]", "macros", ",", "hmmdefs", "=", "htk_model_utils", ".", "split_model", "(", "model", ")", "htk", ".", "save_model", "(", "macros", ",", "config", ".", "path", "(", "output_model_directory", ",", "'macros'", ")", ")", "htk", ".", "save_model", "(", "hmmdefs", ",", "config", ".", "path", "(", "output_model_directory", ",", "'hmmdefs'", ")", ")" ]
Creates a flat start model by using HCompV to compute the global mean and variance. Then uses these global mean and variance to create an N-state model for each symbol in the given list. :param feature_filename: The filename containing the audio and feature file pairs :param output_model_directory: The directory where to write the created model :param output_prototype_filename: The prototype model filename :param htk_trace: Trace level for HTK :rtype : None
[ "Creates", "a", "flat", "start", "model", "by", "using", "HCompV", "to", "compute", "the", "global", "mean", "and", "variance", ".", "Then", "uses", "these", "global", "mean", "and", "variance", "to", "create", "an", "N", "-", "state", "model", "for", "each", "symbol", "in", "the", "given", "list", "." ]
e281c0266a9a9633f34ab70f9c3ad58036c19b59
https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/common.py#L571-L615
244,664
rikrd/inspire
inspirespeech/common.py
recognise_model
def recognise_model(feature_filename, symbollist_filename, model_directory, recognition_filename, pronunciation_dictionary_filename, list_words_filename='', cmllr_directory=None, tokens_count=None, hypotheses_count=1, htk_trace=0): """ Perform recognition using a model and assuming a single word language. If the list_words_filename is == '' then all the words in the dictionary are used as language words. """ # Normalize UTF-8 to avoid Mac problems temp_dictionary_filename = utf8_normalize(pronunciation_dictionary_filename) # Create language word list if list_words_filename: list_words = parse_wordlist(list_words_filename) else: list_words = sorted(parse_dictionary(temp_dictionary_filename).keys()) # Create language model temp_directory = config.project_path('tmp', create=True) grammar_filename = config.path(temp_directory, 'grammar_words') wdnet_filename = config.path(temp_directory, 'wdnet') logging.debug('Create language model') create_language_model(list_words, grammar_filename, wdnet_filename) # Handle the Adaptation parameters cmllr_arguments = '' if cmllr_directory: if not os.path.isdir(cmllr_directory): logging.error('CMLLR adapatation directory not found: {}'.format(cmllr_directory)) cmllr_arguments = "-J {} mllr2 -h '*/*_s%.mfc' -k -J {}".format( os.path.abspath(config.path(cmllr_directory, 'xforms')), os.path.abspath(config.path(cmllr_directory, 'classes'))) # Handle the N-Best parameters hypotheses_count = hypotheses_count or 1 tokens_count = tokens_count or int(math.ceil(hypotheses_count / 5.0)) if hypotheses_count == 1 and tokens_count == 1: nbest_arguments = "" else: nbest_arguments = "-n {tokens_count} {hypotheses_count} ".format(tokens_count=tokens_count, hypotheses_count=hypotheses_count) # Run the HTK command config.htk_command("HVite -A -l '*' -T {htk_trace} " "-H {model_directory}/macros -H {model_directory}/hmmdefs " "-i {recognition_filename} -S {feature_filename} " "{cmllr_arguments} -w {wdnet_filename} " "{nbest_arguments} " "-p 0.0 -s 5.0 " "{pronunciation_dictionary_filename} " "{symbollist_filename}".format(htk_trace=htk_trace, model_directory=model_directory, recognition_filename=recognition_filename, feature_filename=feature_filename, symbollist_filename=symbollist_filename, nbest_arguments=nbest_arguments, pronunciation_dictionary_filename=temp_dictionary_filename, wdnet_filename=wdnet_filename, cmllr_arguments=cmllr_arguments)) # Remove temporary files os.remove(temp_dictionary_filename) os.remove(wdnet_filename) os.remove(grammar_filename)
python
def recognise_model(feature_filename, symbollist_filename, model_directory, recognition_filename, pronunciation_dictionary_filename, list_words_filename='', cmllr_directory=None, tokens_count=None, hypotheses_count=1, htk_trace=0): """ Perform recognition using a model and assuming a single word language. If the list_words_filename is == '' then all the words in the dictionary are used as language words. """ # Normalize UTF-8 to avoid Mac problems temp_dictionary_filename = utf8_normalize(pronunciation_dictionary_filename) # Create language word list if list_words_filename: list_words = parse_wordlist(list_words_filename) else: list_words = sorted(parse_dictionary(temp_dictionary_filename).keys()) # Create language model temp_directory = config.project_path('tmp', create=True) grammar_filename = config.path(temp_directory, 'grammar_words') wdnet_filename = config.path(temp_directory, 'wdnet') logging.debug('Create language model') create_language_model(list_words, grammar_filename, wdnet_filename) # Handle the Adaptation parameters cmllr_arguments = '' if cmllr_directory: if not os.path.isdir(cmllr_directory): logging.error('CMLLR adapatation directory not found: {}'.format(cmllr_directory)) cmllr_arguments = "-J {} mllr2 -h '*/*_s%.mfc' -k -J {}".format( os.path.abspath(config.path(cmllr_directory, 'xforms')), os.path.abspath(config.path(cmllr_directory, 'classes'))) # Handle the N-Best parameters hypotheses_count = hypotheses_count or 1 tokens_count = tokens_count or int(math.ceil(hypotheses_count / 5.0)) if hypotheses_count == 1 and tokens_count == 1: nbest_arguments = "" else: nbest_arguments = "-n {tokens_count} {hypotheses_count} ".format(tokens_count=tokens_count, hypotheses_count=hypotheses_count) # Run the HTK command config.htk_command("HVite -A -l '*' -T {htk_trace} " "-H {model_directory}/macros -H {model_directory}/hmmdefs " "-i {recognition_filename} -S {feature_filename} " "{cmllr_arguments} -w {wdnet_filename} " "{nbest_arguments} " "-p 0.0 -s 5.0 " "{pronunciation_dictionary_filename} " "{symbollist_filename}".format(htk_trace=htk_trace, model_directory=model_directory, recognition_filename=recognition_filename, feature_filename=feature_filename, symbollist_filename=symbollist_filename, nbest_arguments=nbest_arguments, pronunciation_dictionary_filename=temp_dictionary_filename, wdnet_filename=wdnet_filename, cmllr_arguments=cmllr_arguments)) # Remove temporary files os.remove(temp_dictionary_filename) os.remove(wdnet_filename) os.remove(grammar_filename)
[ "def", "recognise_model", "(", "feature_filename", ",", "symbollist_filename", ",", "model_directory", ",", "recognition_filename", ",", "pronunciation_dictionary_filename", ",", "list_words_filename", "=", "''", ",", "cmllr_directory", "=", "None", ",", "tokens_count", "=", "None", ",", "hypotheses_count", "=", "1", ",", "htk_trace", "=", "0", ")", ":", "# Normalize UTF-8 to avoid Mac problems", "temp_dictionary_filename", "=", "utf8_normalize", "(", "pronunciation_dictionary_filename", ")", "# Create language word list", "if", "list_words_filename", ":", "list_words", "=", "parse_wordlist", "(", "list_words_filename", ")", "else", ":", "list_words", "=", "sorted", "(", "parse_dictionary", "(", "temp_dictionary_filename", ")", ".", "keys", "(", ")", ")", "# Create language model", "temp_directory", "=", "config", ".", "project_path", "(", "'tmp'", ",", "create", "=", "True", ")", "grammar_filename", "=", "config", ".", "path", "(", "temp_directory", ",", "'grammar_words'", ")", "wdnet_filename", "=", "config", ".", "path", "(", "temp_directory", ",", "'wdnet'", ")", "logging", ".", "debug", "(", "'Create language model'", ")", "create_language_model", "(", "list_words", ",", "grammar_filename", ",", "wdnet_filename", ")", "# Handle the Adaptation parameters", "cmllr_arguments", "=", "''", "if", "cmllr_directory", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "cmllr_directory", ")", ":", "logging", ".", "error", "(", "'CMLLR adapatation directory not found: {}'", ".", "format", "(", "cmllr_directory", ")", ")", "cmllr_arguments", "=", "\"-J {} mllr2 -h '*/*_s%.mfc' -k -J {}\"", ".", "format", "(", "os", ".", "path", ".", "abspath", "(", "config", ".", "path", "(", "cmllr_directory", ",", "'xforms'", ")", ")", ",", "os", ".", "path", ".", "abspath", "(", "config", ".", "path", "(", "cmllr_directory", ",", "'classes'", ")", ")", ")", "# Handle the N-Best parameters", "hypotheses_count", "=", "hypotheses_count", "or", "1", "tokens_count", "=", "tokens_count", "or", "int", "(", "math", ".", "ceil", "(", "hypotheses_count", "/", "5.0", ")", ")", "if", "hypotheses_count", "==", "1", "and", "tokens_count", "==", "1", ":", "nbest_arguments", "=", "\"\"", "else", ":", "nbest_arguments", "=", "\"-n {tokens_count} {hypotheses_count} \"", ".", "format", "(", "tokens_count", "=", "tokens_count", ",", "hypotheses_count", "=", "hypotheses_count", ")", "# Run the HTK command", "config", ".", "htk_command", "(", "\"HVite -A -l '*' -T {htk_trace} \"", "\"-H {model_directory}/macros -H {model_directory}/hmmdefs \"", "\"-i {recognition_filename} -S {feature_filename} \"", "\"{cmllr_arguments} -w {wdnet_filename} \"", "\"{nbest_arguments} \"", "\"-p 0.0 -s 5.0 \"", "\"{pronunciation_dictionary_filename} \"", "\"{symbollist_filename}\"", ".", "format", "(", "htk_trace", "=", "htk_trace", ",", "model_directory", "=", "model_directory", ",", "recognition_filename", "=", "recognition_filename", ",", "feature_filename", "=", "feature_filename", ",", "symbollist_filename", "=", "symbollist_filename", ",", "nbest_arguments", "=", "nbest_arguments", ",", "pronunciation_dictionary_filename", "=", "temp_dictionary_filename", ",", "wdnet_filename", "=", "wdnet_filename", ",", "cmllr_arguments", "=", "cmllr_arguments", ")", ")", "# Remove temporary files", "os", ".", "remove", "(", "temp_dictionary_filename", ")", "os", ".", "remove", "(", "wdnet_filename", ")", "os", ".", "remove", "(", "grammar_filename", ")" ]
Perform recognition using a model and assuming a single word language. If the list_words_filename is == '' then all the words in the dictionary are used as language words.
[ "Perform", "recognition", "using", "a", "model", "and", "assuming", "a", "single", "word", "language", "." ]
e281c0266a9a9633f34ab70f9c3ad58036c19b59
https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/common.py#L989-L1061
244,665
sassoo/goldman
goldman/stores/postgres/connect.py
Connect.connect
def connect(self): """ Construct the psycopg2 connection instance :return: psycopg2.connect instance """ if self._conn: return self._conn self._conn = psycopg2.connect( self.config, cursor_factory=psycopg2.extras.RealDictCursor, ) self._conn.set_session(autocommit=True) psycopg2.extras.register_hstore(self._conn) return self._conn
python
def connect(self): """ Construct the psycopg2 connection instance :return: psycopg2.connect instance """ if self._conn: return self._conn self._conn = psycopg2.connect( self.config, cursor_factory=psycopg2.extras.RealDictCursor, ) self._conn.set_session(autocommit=True) psycopg2.extras.register_hstore(self._conn) return self._conn
[ "def", "connect", "(", "self", ")", ":", "if", "self", ".", "_conn", ":", "return", "self", ".", "_conn", "self", ".", "_conn", "=", "psycopg2", ".", "connect", "(", "self", ".", "config", ",", "cursor_factory", "=", "psycopg2", ".", "extras", ".", "RealDictCursor", ",", ")", "self", ".", "_conn", ".", "set_session", "(", "autocommit", "=", "True", ")", "psycopg2", ".", "extras", ".", "register_hstore", "(", "self", ".", "_conn", ")", "return", "self", ".", "_conn" ]
Construct the psycopg2 connection instance :return: psycopg2.connect instance
[ "Construct", "the", "psycopg2", "connection", "instance" ]
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/stores/postgres/connect.py#L27-L44
244,666
praekelt/panya
panya/templatetags/panya_inclusion_tags.py
pager
def pager(parser, token): """ Output pagination links. """ try: tag_name, page_obj = token.split_contents() except ValueError: raise template.TemplateSyntaxError('pager tag requires 1 argument (page_obj), %s given' % (len(token.split_contents()) - 1)) return PagerNode(page_obj)
python
def pager(parser, token): """ Output pagination links. """ try: tag_name, page_obj = token.split_contents() except ValueError: raise template.TemplateSyntaxError('pager tag requires 1 argument (page_obj), %s given' % (len(token.split_contents()) - 1)) return PagerNode(page_obj)
[ "def", "pager", "(", "parser", ",", "token", ")", ":", "try", ":", "tag_name", ",", "page_obj", "=", "token", ".", "split_contents", "(", ")", "except", "ValueError", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "'pager tag requires 1 argument (page_obj), %s given'", "%", "(", "len", "(", "token", ".", "split_contents", "(", ")", ")", "-", "1", ")", ")", "return", "PagerNode", "(", "page_obj", ")" ]
Output pagination links.
[ "Output", "pagination", "links", "." ]
0fd621e15a7c11a2716a9554a2f820d6259818e5
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/templatetags/panya_inclusion_tags.py#L34-L42
244,667
praekelt/panya
panya/templatetags/panya_inclusion_tags.py
view_modifier
def view_modifier(parser, token): """ Output view modifier. """ try: tag_name, view_modifier = token.split_contents() except ValueError: raise template.TemplateSyntaxError('view_modifier tag requires 1 argument (view_modifier), %s given' % (len(token.split_contents()) - 1)) return ViewModifierNode(view_modifier)
python
def view_modifier(parser, token): """ Output view modifier. """ try: tag_name, view_modifier = token.split_contents() except ValueError: raise template.TemplateSyntaxError('view_modifier tag requires 1 argument (view_modifier), %s given' % (len(token.split_contents()) - 1)) return ViewModifierNode(view_modifier)
[ "def", "view_modifier", "(", "parser", ",", "token", ")", ":", "try", ":", "tag_name", ",", "view_modifier", "=", "token", ".", "split_contents", "(", ")", "except", "ValueError", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "'view_modifier tag requires 1 argument (view_modifier), %s given'", "%", "(", "len", "(", "token", ".", "split_contents", "(", ")", ")", "-", "1", ")", ")", "return", "ViewModifierNode", "(", "view_modifier", ")" ]
Output view modifier.
[ "Output", "view", "modifier", "." ]
0fd621e15a7c11a2716a9554a2f820d6259818e5
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/templatetags/panya_inclusion_tags.py#L94-L102
244,668
caseyjlaw/activegit
activegit/activegit.py
ActiveGit.initializerepo
def initializerepo(self): """ Fill empty directory with products and make first commit """ try: os.mkdir(self.repopath) except OSError: pass cmd = self.repo.init(bare=self.bare, shared=self.shared) if not self.bare: self.write_testing_data([], []) self.write_training_data([], []) self.write_classifier(None) cmd = self.repo.add('training.pkl') cmd = self.repo.add('testing.pkl') cmd = self.repo.add('classifier.pkl') cmd = self.repo.commit(m='initial commit') cmd = self.repo.tag('initial') cmd = self.set_version('initial')
python
def initializerepo(self): """ Fill empty directory with products and make first commit """ try: os.mkdir(self.repopath) except OSError: pass cmd = self.repo.init(bare=self.bare, shared=self.shared) if not self.bare: self.write_testing_data([], []) self.write_training_data([], []) self.write_classifier(None) cmd = self.repo.add('training.pkl') cmd = self.repo.add('testing.pkl') cmd = self.repo.add('classifier.pkl') cmd = self.repo.commit(m='initial commit') cmd = self.repo.tag('initial') cmd = self.set_version('initial')
[ "def", "initializerepo", "(", "self", ")", ":", "try", ":", "os", ".", "mkdir", "(", "self", ".", "repopath", ")", "except", "OSError", ":", "pass", "cmd", "=", "self", ".", "repo", ".", "init", "(", "bare", "=", "self", ".", "bare", ",", "shared", "=", "self", ".", "shared", ")", "if", "not", "self", ".", "bare", ":", "self", ".", "write_testing_data", "(", "[", "]", ",", "[", "]", ")", "self", ".", "write_training_data", "(", "[", "]", ",", "[", "]", ")", "self", ".", "write_classifier", "(", "None", ")", "cmd", "=", "self", ".", "repo", ".", "add", "(", "'training.pkl'", ")", "cmd", "=", "self", ".", "repo", ".", "add", "(", "'testing.pkl'", ")", "cmd", "=", "self", ".", "repo", ".", "add", "(", "'classifier.pkl'", ")", "cmd", "=", "self", ".", "repo", ".", "commit", "(", "m", "=", "'initial commit'", ")", "cmd", "=", "self", ".", "repo", ".", "tag", "(", "'initial'", ")", "cmd", "=", "self", ".", "set_version", "(", "'initial'", ")" ]
Fill empty directory with products and make first commit
[ "Fill", "empty", "directory", "with", "products", "and", "make", "first", "commit" ]
2b4a0ee0fecf13345b5257130ba98b48f46e1098
https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L54-L75
244,669
caseyjlaw/activegit
activegit/activegit.py
ActiveGit.isvalid
def isvalid(self): """ Checks whether contents of repo are consistent with standard set. """ gcontents = [gf.rstrip('\n') for gf in self.repo.bake('ls-files')()] fcontents = os.listdir(self.repopath) return all([sf in gcontents for sf in std_files]) and all([sf in fcontents for sf in std_files])
python
def isvalid(self): """ Checks whether contents of repo are consistent with standard set. """ gcontents = [gf.rstrip('\n') for gf in self.repo.bake('ls-files')()] fcontents = os.listdir(self.repopath) return all([sf in gcontents for sf in std_files]) and all([sf in fcontents for sf in std_files])
[ "def", "isvalid", "(", "self", ")", ":", "gcontents", "=", "[", "gf", ".", "rstrip", "(", "'\\n'", ")", "for", "gf", "in", "self", ".", "repo", ".", "bake", "(", "'ls-files'", ")", "(", ")", "]", "fcontents", "=", "os", ".", "listdir", "(", "self", ".", "repopath", ")", "return", "all", "(", "[", "sf", "in", "gcontents", "for", "sf", "in", "std_files", "]", ")", "and", "all", "(", "[", "sf", "in", "fcontents", "for", "sf", "in", "std_files", "]", ")" ]
Checks whether contents of repo are consistent with standard set.
[ "Checks", "whether", "contents", "of", "repo", "are", "consistent", "with", "standard", "set", "." ]
2b4a0ee0fecf13345b5257130ba98b48f46e1098
https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L97-L102
244,670
caseyjlaw/activegit
activegit/activegit.py
ActiveGit.set_version
def set_version(self, version, force=True): """ Sets the version name for the current state of repo """ if version in self.versions: self._version = version if 'working' in self.repo.branch().stdout: if force: logger.info('Found working branch. Removing...') cmd = self.repo.checkout('master') cmd = self.repo.branch('working', d=True) else: logger.info('Found working branch from previous session. Use force=True to remove it and start anew.') return stdout = self.repo.checkout(version, b='working').stdout # active version set in 'working' branch logger.info('Version {0} set'.format(version)) else: raise AttributeError('Version {0} not found'.format(version))
python
def set_version(self, version, force=True): """ Sets the version name for the current state of repo """ if version in self.versions: self._version = version if 'working' in self.repo.branch().stdout: if force: logger.info('Found working branch. Removing...') cmd = self.repo.checkout('master') cmd = self.repo.branch('working', d=True) else: logger.info('Found working branch from previous session. Use force=True to remove it and start anew.') return stdout = self.repo.checkout(version, b='working').stdout # active version set in 'working' branch logger.info('Version {0} set'.format(version)) else: raise AttributeError('Version {0} not found'.format(version))
[ "def", "set_version", "(", "self", ",", "version", ",", "force", "=", "True", ")", ":", "if", "version", "in", "self", ".", "versions", ":", "self", ".", "_version", "=", "version", "if", "'working'", "in", "self", ".", "repo", ".", "branch", "(", ")", ".", "stdout", ":", "if", "force", ":", "logger", ".", "info", "(", "'Found working branch. Removing...'", ")", "cmd", "=", "self", ".", "repo", ".", "checkout", "(", "'master'", ")", "cmd", "=", "self", ".", "repo", ".", "branch", "(", "'working'", ",", "d", "=", "True", ")", "else", ":", "logger", ".", "info", "(", "'Found working branch from previous session. Use force=True to remove it and start anew.'", ")", "return", "stdout", "=", "self", ".", "repo", ".", "checkout", "(", "version", ",", "b", "=", "'working'", ")", ".", "stdout", "# active version set in 'working' branch", "logger", ".", "info", "(", "'Version {0} set'", ".", "format", "(", "version", ")", ")", "else", ":", "raise", "AttributeError", "(", "'Version {0} not found'", ".", "format", "(", "version", ")", ")" ]
Sets the version name for the current state of repo
[ "Sets", "the", "version", "name", "for", "the", "current", "state", "of", "repo" ]
2b4a0ee0fecf13345b5257130ba98b48f46e1098
https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L105-L122
244,671
caseyjlaw/activegit
activegit/activegit.py
ActiveGit.training_data
def training_data(self): """ Returns data dictionary from training.pkl """ data = pickle.load(open(os.path.join(self.repopath, 'training.pkl'))) return data.keys(), data.values()
python
def training_data(self): """ Returns data dictionary from training.pkl """ data = pickle.load(open(os.path.join(self.repopath, 'training.pkl'))) return data.keys(), data.values()
[ "def", "training_data", "(", "self", ")", ":", "data", "=", "pickle", ".", "load", "(", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "repopath", ",", "'training.pkl'", ")", ")", ")", "return", "data", ".", "keys", "(", ")", ",", "data", ".", "values", "(", ")" ]
Returns data dictionary from training.pkl
[ "Returns", "data", "dictionary", "from", "training", ".", "pkl" ]
2b4a0ee0fecf13345b5257130ba98b48f46e1098
https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L137-L141
244,672
caseyjlaw/activegit
activegit/activegit.py
ActiveGit.classifier
def classifier(self): """ Returns classifier from classifier.pkl """ clf = pickle.load(open(os.path.join(self.repopath, 'classifier.pkl'))) return clf
python
def classifier(self): """ Returns classifier from classifier.pkl """ clf = pickle.load(open(os.path.join(self.repopath, 'classifier.pkl'))) return clf
[ "def", "classifier", "(", "self", ")", ":", "clf", "=", "pickle", ".", "load", "(", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "repopath", ",", "'classifier.pkl'", ")", ")", ")", "return", "clf" ]
Returns classifier from classifier.pkl
[ "Returns", "classifier", "from", "classifier", ".", "pkl" ]
2b4a0ee0fecf13345b5257130ba98b48f46e1098
https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L153-L157
244,673
caseyjlaw/activegit
activegit/activegit.py
ActiveGit.write_training_data
def write_training_data(self, features, targets): """ Writes data dictionary to filename """ assert len(features) == len(targets) data = dict(zip(features, targets)) with open(os.path.join(self.repopath, 'training.pkl'), 'w') as fp: pickle.dump(data, fp)
python
def write_training_data(self, features, targets): """ Writes data dictionary to filename """ assert len(features) == len(targets) data = dict(zip(features, targets)) with open(os.path.join(self.repopath, 'training.pkl'), 'w') as fp: pickle.dump(data, fp)
[ "def", "write_training_data", "(", "self", ",", "features", ",", "targets", ")", ":", "assert", "len", "(", "features", ")", "==", "len", "(", "targets", ")", "data", "=", "dict", "(", "zip", "(", "features", ",", "targets", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "repopath", ",", "'training.pkl'", ")", ",", "'w'", ")", "as", "fp", ":", "pickle", ".", "dump", "(", "data", ",", "fp", ")" ]
Writes data dictionary to filename
[ "Writes", "data", "dictionary", "to", "filename" ]
2b4a0ee0fecf13345b5257130ba98b48f46e1098
https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L161-L169
244,674
caseyjlaw/activegit
activegit/activegit.py
ActiveGit.write_classifier
def write_classifier(self, clf): """ Writes classifier object to pickle file """ with open(os.path.join(self.repopath, 'classifier.pkl'), 'w') as fp: pickle.dump(clf, fp)
python
def write_classifier(self, clf): """ Writes classifier object to pickle file """ with open(os.path.join(self.repopath, 'classifier.pkl'), 'w') as fp: pickle.dump(clf, fp)
[ "def", "write_classifier", "(", "self", ",", "clf", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "repopath", ",", "'classifier.pkl'", ")", ",", "'w'", ")", "as", "fp", ":", "pickle", ".", "dump", "(", "clf", ",", "fp", ")" ]
Writes classifier object to pickle file
[ "Writes", "classifier", "object", "to", "pickle", "file" ]
2b4a0ee0fecf13345b5257130ba98b48f46e1098
https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L183-L187
244,675
caseyjlaw/activegit
activegit/activegit.py
ActiveGit.commit_version
def commit_version(self, version, msg=None): """ Add tag, commit, and push changes """ assert version not in self.versions, 'Will not overwrite a version name.' if not msg: feat, targ = self.training_data msg = 'Training set has {0} examples. '.format(len(feat)) feat, targ = self.testing_data msg += 'Testing set has {0} examples.'.format(len(feat)) cmd = self.repo.commit(m=msg, a=True) cmd = self.repo.tag(version) cmd = self.repo.checkout('master') self.update() cmd = self.repo.merge('working') cmd = self.repo.branch('working', d=True) self.set_version(version) try: stdout = self.repo.push('origin', 'master', '--tags').stdout logger.info(stdout) except: logger.info('Push not working. Remote not defined?')
python
def commit_version(self, version, msg=None): """ Add tag, commit, and push changes """ assert version not in self.versions, 'Will not overwrite a version name.' if not msg: feat, targ = self.training_data msg = 'Training set has {0} examples. '.format(len(feat)) feat, targ = self.testing_data msg += 'Testing set has {0} examples.'.format(len(feat)) cmd = self.repo.commit(m=msg, a=True) cmd = self.repo.tag(version) cmd = self.repo.checkout('master') self.update() cmd = self.repo.merge('working') cmd = self.repo.branch('working', d=True) self.set_version(version) try: stdout = self.repo.push('origin', 'master', '--tags').stdout logger.info(stdout) except: logger.info('Push not working. Remote not defined?')
[ "def", "commit_version", "(", "self", ",", "version", ",", "msg", "=", "None", ")", ":", "assert", "version", "not", "in", "self", ".", "versions", ",", "'Will not overwrite a version name.'", "if", "not", "msg", ":", "feat", ",", "targ", "=", "self", ".", "training_data", "msg", "=", "'Training set has {0} examples. '", ".", "format", "(", "len", "(", "feat", ")", ")", "feat", ",", "targ", "=", "self", ".", "testing_data", "msg", "+=", "'Testing set has {0} examples.'", ".", "format", "(", "len", "(", "feat", ")", ")", "cmd", "=", "self", ".", "repo", ".", "commit", "(", "m", "=", "msg", ",", "a", "=", "True", ")", "cmd", "=", "self", ".", "repo", ".", "tag", "(", "version", ")", "cmd", "=", "self", ".", "repo", ".", "checkout", "(", "'master'", ")", "self", ".", "update", "(", ")", "cmd", "=", "self", ".", "repo", ".", "merge", "(", "'working'", ")", "cmd", "=", "self", ".", "repo", ".", "branch", "(", "'working'", ",", "d", "=", "True", ")", "self", ".", "set_version", "(", "version", ")", "try", ":", "stdout", "=", "self", ".", "repo", ".", "push", "(", "'origin'", ",", "'master'", ",", "'--tags'", ")", ".", "stdout", "logger", ".", "info", "(", "stdout", ")", "except", ":", "logger", ".", "info", "(", "'Push not working. Remote not defined?'", ")" ]
Add tag, commit, and push changes
[ "Add", "tag", "commit", "and", "push", "changes" ]
2b4a0ee0fecf13345b5257130ba98b48f46e1098
https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L191-L214
244,676
pioneers/python-grizzly
grizzly/__init__.py
GrizzlyUSB.get_all_usb_devices
def get_all_usb_devices(idVendor, idProduct): """ Returns a list of all the usb devices matching the provided vendor ID and product ID.""" all_dev = list(usb.core.find(find_all = True, idVendor = idVendor, idProduct = idProduct)) for dev in all_dev: try: dev.detach_kernel_driver(0) except usb.USBError: pass return all_dev
python
def get_all_usb_devices(idVendor, idProduct): """ Returns a list of all the usb devices matching the provided vendor ID and product ID.""" all_dev = list(usb.core.find(find_all = True, idVendor = idVendor, idProduct = idProduct)) for dev in all_dev: try: dev.detach_kernel_driver(0) except usb.USBError: pass return all_dev
[ "def", "get_all_usb_devices", "(", "idVendor", ",", "idProduct", ")", ":", "all_dev", "=", "list", "(", "usb", ".", "core", ".", "find", "(", "find_all", "=", "True", ",", "idVendor", "=", "idVendor", ",", "idProduct", "=", "idProduct", ")", ")", "for", "dev", "in", "all_dev", ":", "try", ":", "dev", ".", "detach_kernel_driver", "(", "0", ")", "except", "usb", ".", "USBError", ":", "pass", "return", "all_dev" ]
Returns a list of all the usb devices matching the provided vendor ID and product ID.
[ "Returns", "a", "list", "of", "all", "the", "usb", "devices", "matching", "the", "provided", "vendor", "ID", "and", "product", "ID", "." ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L41-L49
244,677
pioneers/python-grizzly
grizzly/__init__.py
GrizzlyUSB.get_device_address
def get_device_address(usb_device): """ Returns the grizzly's internal address value. Returns a negative error value in case of error. """ try: usb_device.ctrl_transfer(0x21, 0x09, 0x0300, 0, GrizzlyUSB.COMMAND_GET_ADDR) internal_addr = usb_device.ctrl_transfer(0xa1, 0x01, 0x0301, 0, 2)[1] return internal_addr >> 1 except usb.USBError as e: return GrizzlyUSB.USB_DEVICE_ERROR
python
def get_device_address(usb_device): """ Returns the grizzly's internal address value. Returns a negative error value in case of error. """ try: usb_device.ctrl_transfer(0x21, 0x09, 0x0300, 0, GrizzlyUSB.COMMAND_GET_ADDR) internal_addr = usb_device.ctrl_transfer(0xa1, 0x01, 0x0301, 0, 2)[1] return internal_addr >> 1 except usb.USBError as e: return GrizzlyUSB.USB_DEVICE_ERROR
[ "def", "get_device_address", "(", "usb_device", ")", ":", "try", ":", "usb_device", ".", "ctrl_transfer", "(", "0x21", ",", "0x09", ",", "0x0300", ",", "0", ",", "GrizzlyUSB", ".", "COMMAND_GET_ADDR", ")", "internal_addr", "=", "usb_device", ".", "ctrl_transfer", "(", "0xa1", ",", "0x01", ",", "0x0301", ",", "0", ",", "2", ")", "[", "1", "]", "return", "internal_addr", ">>", "1", "except", "usb", ".", "USBError", "as", "e", ":", "return", "GrizzlyUSB", ".", "USB_DEVICE_ERROR" ]
Returns the grizzly's internal address value. Returns a negative error value in case of error.
[ "Returns", "the", "grizzly", "s", "internal", "address", "value", ".", "Returns", "a", "negative", "error", "value", "in", "case", "of", "error", "." ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L52-L59
244,678
pioneers/python-grizzly
grizzly/__init__.py
Grizzly.get_all_ids
def get_all_ids(idVendor = GrizzlyUSB.ID_VENDOR, idProduct=GrizzlyUSB.ID_PRODUCT): """ Scans for grizzlies that have not been bound, or constructed, and returns a list of their id's, or motor number.""" all_dev = GrizzlyUSB.get_all_usb_devices(idVendor, idProduct) if len(all_dev) <= 0: raise usb.USBError("Could not find any GrizzlyBear device (idVendor=%d, idProduct=%d)" % (idVendor, idProduct)) else: all_addresses = [] # bound devices is a list of devices that are already busy. bound_devices = [] for device in all_dev: internal_addr = GrizzlyUSB.get_device_address(device) if internal_addr == GrizzlyUSB.USB_DEVICE_ERROR: # device bound bound_devices.append(device) else: all_addresses.append(internal_addr) # we release all devices that we aren't using and aren't bound. for device in all_dev: if device not in bound_devices: usb.util.dispose_resources(device) return map(addr_to_id, all_addresses)
python
def get_all_ids(idVendor = GrizzlyUSB.ID_VENDOR, idProduct=GrizzlyUSB.ID_PRODUCT): """ Scans for grizzlies that have not been bound, or constructed, and returns a list of their id's, or motor number.""" all_dev = GrizzlyUSB.get_all_usb_devices(idVendor, idProduct) if len(all_dev) <= 0: raise usb.USBError("Could not find any GrizzlyBear device (idVendor=%d, idProduct=%d)" % (idVendor, idProduct)) else: all_addresses = [] # bound devices is a list of devices that are already busy. bound_devices = [] for device in all_dev: internal_addr = GrizzlyUSB.get_device_address(device) if internal_addr == GrizzlyUSB.USB_DEVICE_ERROR: # device bound bound_devices.append(device) else: all_addresses.append(internal_addr) # we release all devices that we aren't using and aren't bound. for device in all_dev: if device not in bound_devices: usb.util.dispose_resources(device) return map(addr_to_id, all_addresses)
[ "def", "get_all_ids", "(", "idVendor", "=", "GrizzlyUSB", ".", "ID_VENDOR", ",", "idProduct", "=", "GrizzlyUSB", ".", "ID_PRODUCT", ")", ":", "all_dev", "=", "GrizzlyUSB", ".", "get_all_usb_devices", "(", "idVendor", ",", "idProduct", ")", "if", "len", "(", "all_dev", ")", "<=", "0", ":", "raise", "usb", ".", "USBError", "(", "\"Could not find any GrizzlyBear device (idVendor=%d, idProduct=%d)\"", "%", "(", "idVendor", ",", "idProduct", ")", ")", "else", ":", "all_addresses", "=", "[", "]", "# bound devices is a list of devices that are already busy.", "bound_devices", "=", "[", "]", "for", "device", "in", "all_dev", ":", "internal_addr", "=", "GrizzlyUSB", ".", "get_device_address", "(", "device", ")", "if", "internal_addr", "==", "GrizzlyUSB", ".", "USB_DEVICE_ERROR", ":", "# device bound", "bound_devices", ".", "append", "(", "device", ")", "else", ":", "all_addresses", ".", "append", "(", "internal_addr", ")", "# we release all devices that we aren't using and aren't bound.", "for", "device", "in", "all_dev", ":", "if", "device", "not", "in", "bound_devices", ":", "usb", ".", "util", ".", "dispose_resources", "(", "device", ")", "return", "map", "(", "addr_to_id", ",", "all_addresses", ")" ]
Scans for grizzlies that have not been bound, or constructed, and returns a list of their id's, or motor number.
[ "Scans", "for", "grizzlies", "that", "have", "not", "been", "bound", "or", "constructed", "and", "returns", "a", "list", "of", "their", "id", "s", "or", "motor", "number", "." ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L100-L124
244,679
pioneers/python-grizzly
grizzly/__init__.py
Grizzly.set_register
def set_register(self, addr, data): """Sets an arbitrary register at @addr and subsequent registers depending on how much data you decide to write. It will automatically fill extra bytes with zeros. You cannot write more than 14 bytes at a time. @addr should be a static constant from the Addr class, e.g. Addr.Speed""" assert len(data) <= 14, "Cannot write more than 14 bytes at a time" cmd = chr(addr) + chr(len(data) | 0x80) for byte in data: cmd += chr(cast_to_byte(byte)) cmd += (16 - len(cmd)) * chr(0) self._dev.send_bytes(cmd)
python
def set_register(self, addr, data): """Sets an arbitrary register at @addr and subsequent registers depending on how much data you decide to write. It will automatically fill extra bytes with zeros. You cannot write more than 14 bytes at a time. @addr should be a static constant from the Addr class, e.g. Addr.Speed""" assert len(data) <= 14, "Cannot write more than 14 bytes at a time" cmd = chr(addr) + chr(len(data) | 0x80) for byte in data: cmd += chr(cast_to_byte(byte)) cmd += (16 - len(cmd)) * chr(0) self._dev.send_bytes(cmd)
[ "def", "set_register", "(", "self", ",", "addr", ",", "data", ")", ":", "assert", "len", "(", "data", ")", "<=", "14", ",", "\"Cannot write more than 14 bytes at a time\"", "cmd", "=", "chr", "(", "addr", ")", "+", "chr", "(", "len", "(", "data", ")", "|", "0x80", ")", "for", "byte", "in", "data", ":", "cmd", "+=", "chr", "(", "cast_to_byte", "(", "byte", ")", ")", "cmd", "+=", "(", "16", "-", "len", "(", "cmd", ")", ")", "*", "chr", "(", "0", ")", "self", ".", "_dev", ".", "send_bytes", "(", "cmd", ")" ]
Sets an arbitrary register at @addr and subsequent registers depending on how much data you decide to write. It will automatically fill extra bytes with zeros. You cannot write more than 14 bytes at a time. @addr should be a static constant from the Addr class, e.g. Addr.Speed
[ "Sets", "an", "arbitrary", "register", "at" ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L136-L146
244,680
pioneers/python-grizzly
grizzly/__init__.py
Grizzly.set_mode
def set_mode(self, controlmode, drivemode): """Higher level abstraction for setting the mode register. This will set the mode according the the @controlmode and @drivemode you specify. @controlmode and @drivemode should come from the ControlMode and DriveMode class respectively.""" self.set_register(Addr.Mode, [0x01 | controlmode | drivemode])
python
def set_mode(self, controlmode, drivemode): """Higher level abstraction for setting the mode register. This will set the mode according the the @controlmode and @drivemode you specify. @controlmode and @drivemode should come from the ControlMode and DriveMode class respectively.""" self.set_register(Addr.Mode, [0x01 | controlmode | drivemode])
[ "def", "set_mode", "(", "self", ",", "controlmode", ",", "drivemode", ")", ":", "self", ".", "set_register", "(", "Addr", ".", "Mode", ",", "[", "0x01", "|", "controlmode", "|", "drivemode", "]", ")" ]
Higher level abstraction for setting the mode register. This will set the mode according the the @controlmode and @drivemode you specify. @controlmode and @drivemode should come from the ControlMode and DriveMode class respectively.
[ "Higher", "level", "abstraction", "for", "setting", "the", "mode", "register", ".", "This", "will", "set", "the", "mode", "according", "the", "the" ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L158-L163
244,681
pioneers/python-grizzly
grizzly/__init__.py
Grizzly._read_as_int
def _read_as_int(self, addr, numBytes): """Convenience method. Oftentimes we need to read a range of registers to represent an int. This method will automatically read @numBytes registers starting at @addr and convert the array into an int.""" buf = self.read_register(addr, numBytes) if len(buf) >= 4: return struct.unpack_from("<i", buf)[0] else: rtn = 0 for i, byte in enumerate(buf): rtn |= byte << 8 * i return rtn
python
def _read_as_int(self, addr, numBytes): """Convenience method. Oftentimes we need to read a range of registers to represent an int. This method will automatically read @numBytes registers starting at @addr and convert the array into an int.""" buf = self.read_register(addr, numBytes) if len(buf) >= 4: return struct.unpack_from("<i", buf)[0] else: rtn = 0 for i, byte in enumerate(buf): rtn |= byte << 8 * i return rtn
[ "def", "_read_as_int", "(", "self", ",", "addr", ",", "numBytes", ")", ":", "buf", "=", "self", ".", "read_register", "(", "addr", ",", "numBytes", ")", "if", "len", "(", "buf", ")", ">=", "4", ":", "return", "struct", ".", "unpack_from", "(", "\"<i\"", ",", "buf", ")", "[", "0", "]", "else", ":", "rtn", "=", "0", "for", "i", ",", "byte", "in", "enumerate", "(", "buf", ")", ":", "rtn", "|=", "byte", "<<", "8", "*", "i", "return", "rtn" ]
Convenience method. Oftentimes we need to read a range of registers to represent an int. This method will automatically read @numBytes registers starting at @addr and convert the array into an int.
[ "Convenience", "method", ".", "Oftentimes", "we", "need", "to", "read", "a", "range", "of", "registers", "to", "represent", "an", "int", ".", "This", "method", "will", "automatically", "read" ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L191-L202
244,682
pioneers/python-grizzly
grizzly/__init__.py
Grizzly._set_as_int
def _set_as_int(self, addr, val, numBytes = 1): """Convenience method. Oftentimes we need to set a range of registers to represent an int. This method will automatically set @numBytes registers starting at @addr. It will convert the int @val into an array of bytes.""" if not isinstance(val, int): raise ValueError("val must be an int. You provided: %s" % str(val)) buf = [] for i in range(numBytes): buf.append(cast_to_byte(val >> 8 * i)) self.set_register(addr, buf)
python
def _set_as_int(self, addr, val, numBytes = 1): """Convenience method. Oftentimes we need to set a range of registers to represent an int. This method will automatically set @numBytes registers starting at @addr. It will convert the int @val into an array of bytes.""" if not isinstance(val, int): raise ValueError("val must be an int. You provided: %s" % str(val)) buf = [] for i in range(numBytes): buf.append(cast_to_byte(val >> 8 * i)) self.set_register(addr, buf)
[ "def", "_set_as_int", "(", "self", ",", "addr", ",", "val", ",", "numBytes", "=", "1", ")", ":", "if", "not", "isinstance", "(", "val", ",", "int", ")", ":", "raise", "ValueError", "(", "\"val must be an int. You provided: %s\"", "%", "str", "(", "val", ")", ")", "buf", "=", "[", "]", "for", "i", "in", "range", "(", "numBytes", ")", ":", "buf", ".", "append", "(", "cast_to_byte", "(", "val", ">>", "8", "*", "i", ")", ")", "self", ".", "set_register", "(", "addr", ",", "buf", ")" ]
Convenience method. Oftentimes we need to set a range of registers to represent an int. This method will automatically set @numBytes registers starting at @addr. It will convert the int @val into an array of bytes.
[ "Convenience", "method", ".", "Oftentimes", "we", "need", "to", "set", "a", "range", "of", "registers", "to", "represent", "an", "int", ".", "This", "method", "will", "automatically", "set" ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L204-L213
244,683
pioneers/python-grizzly
grizzly/__init__.py
Grizzly.has_reset
def has_reset(self): """Checks the grizzly to see if it reset itself because of voltage sag or other reasons. Useful to reinitialize acceleration or current limiting.""" currentTime = self._read_as_int(Addr.Uptime, 4) if currentTime <= self._ticks: self._ticks = currentTime return True self._ticks = currentTime return False
python
def has_reset(self): """Checks the grizzly to see if it reset itself because of voltage sag or other reasons. Useful to reinitialize acceleration or current limiting.""" currentTime = self._read_as_int(Addr.Uptime, 4) if currentTime <= self._ticks: self._ticks = currentTime return True self._ticks = currentTime return False
[ "def", "has_reset", "(", "self", ")", ":", "currentTime", "=", "self", ".", "_read_as_int", "(", "Addr", ".", "Uptime", ",", "4", ")", "if", "currentTime", "<=", "self", ".", "_ticks", ":", "self", ".", "_ticks", "=", "currentTime", "return", "True", "self", ".", "_ticks", "=", "currentTime", "return", "False" ]
Checks the grizzly to see if it reset itself because of voltage sag or other reasons. Useful to reinitialize acceleration or current limiting.
[ "Checks", "the", "grizzly", "to", "see", "if", "it", "reset", "itself", "because", "of", "voltage", "sag", "or", "other", "reasons", ".", "Useful", "to", "reinitialize", "acceleration", "or", "current", "limiting", "." ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L231-L240
244,684
pioneers/python-grizzly
grizzly/__init__.py
Grizzly.limit_current
def limit_current(self, curr): """Sets the current limit on the Grizzly. The units are in amps. The internal default value is 5 amps.""" if curr <= 0: raise ValueError("Current limit must be a positive number. You provided: %s" % str(curr)) current = int(curr * (1024.0 / 5.0) * (66.0 / 1000.0)) self._set_as_int(Addr.CurrentLimit, current, 2)
python
def limit_current(self, curr): """Sets the current limit on the Grizzly. The units are in amps. The internal default value is 5 amps.""" if curr <= 0: raise ValueError("Current limit must be a positive number. You provided: %s" % str(curr)) current = int(curr * (1024.0 / 5.0) * (66.0 / 1000.0)) self._set_as_int(Addr.CurrentLimit, current, 2)
[ "def", "limit_current", "(", "self", ",", "curr", ")", ":", "if", "curr", "<=", "0", ":", "raise", "ValueError", "(", "\"Current limit must be a positive number. You provided: %s\"", "%", "str", "(", "curr", ")", ")", "current", "=", "int", "(", "curr", "*", "(", "1024.0", "/", "5.0", ")", "*", "(", "66.0", "/", "1000.0", ")", ")", "self", ".", "_set_as_int", "(", "Addr", ".", "CurrentLimit", ",", "current", ",", "2", ")" ]
Sets the current limit on the Grizzly. The units are in amps. The internal default value is 5 amps.
[ "Sets", "the", "current", "limit", "on", "the", "Grizzly", ".", "The", "units", "are", "in", "amps", ".", "The", "internal", "default", "value", "is", "5", "amps", "." ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L255-L261
244,685
pioneers/python-grizzly
grizzly/__init__.py
Grizzly.init_pid
def init_pid(self, kp, ki, kd): """Sets the PID constants for the PID modes. Arguments are all floating point numbers.""" p, i, d = map(lambda x: int(x * (2 ** 16)), (kp, ki, kd)) self._set_as_int(Addr.PConstant, p, 4) self._set_as_int(Addr.IConstant, i, 4) self._set_as_int(Addr.DConstant, d, 4)
python
def init_pid(self, kp, ki, kd): """Sets the PID constants for the PID modes. Arguments are all floating point numbers.""" p, i, d = map(lambda x: int(x * (2 ** 16)), (kp, ki, kd)) self._set_as_int(Addr.PConstant, p, 4) self._set_as_int(Addr.IConstant, i, 4) self._set_as_int(Addr.DConstant, d, 4)
[ "def", "init_pid", "(", "self", ",", "kp", ",", "ki", ",", "kd", ")", ":", "p", ",", "i", ",", "d", "=", "map", "(", "lambda", "x", ":", "int", "(", "x", "*", "(", "2", "**", "16", ")", ")", ",", "(", "kp", ",", "ki", ",", "kd", ")", ")", "self", ".", "_set_as_int", "(", "Addr", ".", "PConstant", ",", "p", ",", "4", ")", "self", ".", "_set_as_int", "(", "Addr", ".", "IConstant", ",", "i", ",", "4", ")", "self", ".", "_set_as_int", "(", "Addr", ".", "DConstant", ",", "d", ",", "4", ")" ]
Sets the PID constants for the PID modes. Arguments are all floating point numbers.
[ "Sets", "the", "PID", "constants", "for", "the", "PID", "modes", ".", "Arguments", "are", "all", "floating", "point", "numbers", "." ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L263-L269
244,686
pioneers/python-grizzly
grizzly/__init__.py
Grizzly.read_pid_constants
def read_pid_constants(self): """Reads back the PID constants stored on the Grizzly.""" p = self._read_as_int(Addr.PConstant, 4) i = self._read_as_int(Addr.IConstant, 4) d = self._read_as_int(Addr.DConstant, 4) return map(lambda x: x / (2 ** 16), (p, i, d))
python
def read_pid_constants(self): """Reads back the PID constants stored on the Grizzly.""" p = self._read_as_int(Addr.PConstant, 4) i = self._read_as_int(Addr.IConstant, 4) d = self._read_as_int(Addr.DConstant, 4) return map(lambda x: x / (2 ** 16), (p, i, d))
[ "def", "read_pid_constants", "(", "self", ")", ":", "p", "=", "self", ".", "_read_as_int", "(", "Addr", ".", "PConstant", ",", "4", ")", "i", "=", "self", ".", "_read_as_int", "(", "Addr", ".", "IConstant", ",", "4", ")", "d", "=", "self", ".", "_read_as_int", "(", "Addr", ".", "DConstant", ",", "4", ")", "return", "map", "(", "lambda", "x", ":", "x", "/", "(", "2", "**", "16", ")", ",", "(", "p", ",", "i", ",", "d", ")", ")" ]
Reads back the PID constants stored on the Grizzly.
[ "Reads", "back", "the", "PID", "constants", "stored", "on", "the", "Grizzly", "." ]
a6482c722d5712d6ebe12d48921815276c826c7f
https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L271-L277
244,687
TC01/calcpkg
calcrepo/util.py
getReposPackageFolder
def getReposPackageFolder(): """Returns the folder the package is located in.""" libdir = sysconfig.get_python_lib() repodir = os.path.join(libdir, "calcrepo", "repos") return repodir
python
def getReposPackageFolder(): """Returns the folder the package is located in.""" libdir = sysconfig.get_python_lib() repodir = os.path.join(libdir, "calcrepo", "repos") return repodir
[ "def", "getReposPackageFolder", "(", ")", ":", "libdir", "=", "sysconfig", ".", "get_python_lib", "(", ")", "repodir", "=", "os", ".", "path", ".", "join", "(", "libdir", ",", "\"calcrepo\"", ",", "\"repos\"", ")", "return", "repodir" ]
Returns the folder the package is located in.
[ "Returns", "the", "folder", "the", "package", "is", "located", "in", "." ]
5168f606264620a090b42a64354331d208b00d5f
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/util.py#L7-L11
244,688
TC01/calcpkg
calcrepo/util.py
replaceNewlines
def replaceNewlines(string, newlineChar): """There's probably a way to do this with string functions but I was lazy. Replace all instances of \r or \n in a string with something else.""" if newlineChar in string: segments = string.split(newlineChar) string = "" for segment in segments: string += segment return string
python
def replaceNewlines(string, newlineChar): """There's probably a way to do this with string functions but I was lazy. Replace all instances of \r or \n in a string with something else.""" if newlineChar in string: segments = string.split(newlineChar) string = "" for segment in segments: string += segment return string
[ "def", "replaceNewlines", "(", "string", ",", "newlineChar", ")", ":", "if", "newlineChar", "in", "string", ":", "segments", "=", "string", ".", "split", "(", "newlineChar", ")", "string", "=", "\"\"", "for", "segment", "in", "segments", ":", "string", "+=", "segment", "return", "string" ]
There's probably a way to do this with string functions but I was lazy. Replace all instances of \r or \n in a string with something else.
[ "There", "s", "probably", "a", "way", "to", "do", "this", "with", "string", "functions", "but", "I", "was", "lazy", ".", "Replace", "all", "instances", "of", "\\", "r", "or", "\\", "n", "in", "a", "string", "with", "something", "else", "." ]
5168f606264620a090b42a64354331d208b00d5f
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/util.py#L13-L21
244,689
TC01/calcpkg
calcrepo/util.py
getScriptLocation
def getScriptLocation(): """Helper function to get the location of a Python file.""" location = os.path.abspath("./") if __file__.rfind("/") != -1: location = __file__[:__file__.rfind("/")] return location
python
def getScriptLocation(): """Helper function to get the location of a Python file.""" location = os.path.abspath("./") if __file__.rfind("/") != -1: location = __file__[:__file__.rfind("/")] return location
[ "def", "getScriptLocation", "(", ")", ":", "location", "=", "os", ".", "path", ".", "abspath", "(", "\"./\"", ")", "if", "__file__", ".", "rfind", "(", "\"/\"", ")", "!=", "-", "1", ":", "location", "=", "__file__", "[", ":", "__file__", ".", "rfind", "(", "\"/\"", ")", "]", "return", "location" ]
Helper function to get the location of a Python file.
[ "Helper", "function", "to", "get", "the", "location", "of", "a", "Python", "file", "." ]
5168f606264620a090b42a64354331d208b00d5f
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/util.py#L31-L36
244,690
sassoo/goldman
goldman/queryparams/fields.py
_parse_param
def _parse_param(key, val): """ Parse the query param looking for sparse fields params Ensure the `val` or what will become the sparse fields is always an array. If the query param is not a sparse fields query param then return None. :param key: the query parameter key in the request (left of =) :param val: the query parameter val in the request (right of =) :return: tuple of resource type to implement the sparse fields on & a array of the fields. """ regex = re.compile(r'fields\[([A-Za-z]+)\]') match = regex.match(key) if match: if not isinstance(val, list): val = val.split(',') fields = [field.lower() for field in val] rtype = match.groups()[0].lower() return rtype, fields
python
def _parse_param(key, val): """ Parse the query param looking for sparse fields params Ensure the `val` or what will become the sparse fields is always an array. If the query param is not a sparse fields query param then return None. :param key: the query parameter key in the request (left of =) :param val: the query parameter val in the request (right of =) :return: tuple of resource type to implement the sparse fields on & a array of the fields. """ regex = re.compile(r'fields\[([A-Za-z]+)\]') match = regex.match(key) if match: if not isinstance(val, list): val = val.split(',') fields = [field.lower() for field in val] rtype = match.groups()[0].lower() return rtype, fields
[ "def", "_parse_param", "(", "key", ",", "val", ")", ":", "regex", "=", "re", ".", "compile", "(", "r'fields\\[([A-Za-z]+)\\]'", ")", "match", "=", "regex", ".", "match", "(", "key", ")", "if", "match", ":", "if", "not", "isinstance", "(", "val", ",", "list", ")", ":", "val", "=", "val", ".", "split", "(", "','", ")", "fields", "=", "[", "field", ".", "lower", "(", ")", "for", "field", "in", "val", "]", "rtype", "=", "match", ".", "groups", "(", ")", "[", "0", "]", ".", "lower", "(", ")", "return", "rtype", ",", "fields" ]
Parse the query param looking for sparse fields params Ensure the `val` or what will become the sparse fields is always an array. If the query param is not a sparse fields query param then return None. :param key: the query parameter key in the request (left of =) :param val: the query parameter val in the request (right of =) :return: tuple of resource type to implement the sparse fields on & a array of the fields.
[ "Parse", "the", "query", "param", "looking", "for", "sparse", "fields", "params" ]
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/fields.py#L24-L50
244,691
sassoo/goldman
goldman/queryparams/fields.py
_validate_param
def _validate_param(rtype, fields): """ Ensure the sparse fields exists on the models """ try: # raises ValueError if not found model = rtype_to_model(rtype) model_fields = model.all_fields except ValueError: raise InvalidQueryParams(**{ 'detail': 'The fields query param provided with a ' 'field type of "%s" is unknown.' % rtype, 'links': LINK, 'parameter': PARAM, }) for field in fields: if field not in model_fields: raise InvalidQueryParams(**{ 'detail': 'The fields query param "TYPE" of "%s" ' 'is not possible. It does not have a field ' 'by the name of "%s".' % (rtype, field), 'links': LINK, 'parameter': PARAM, })
python
def _validate_param(rtype, fields): """ Ensure the sparse fields exists on the models """ try: # raises ValueError if not found model = rtype_to_model(rtype) model_fields = model.all_fields except ValueError: raise InvalidQueryParams(**{ 'detail': 'The fields query param provided with a ' 'field type of "%s" is unknown.' % rtype, 'links': LINK, 'parameter': PARAM, }) for field in fields: if field not in model_fields: raise InvalidQueryParams(**{ 'detail': 'The fields query param "TYPE" of "%s" ' 'is not possible. It does not have a field ' 'by the name of "%s".' % (rtype, field), 'links': LINK, 'parameter': PARAM, })
[ "def", "_validate_param", "(", "rtype", ",", "fields", ")", ":", "try", ":", "# raises ValueError if not found", "model", "=", "rtype_to_model", "(", "rtype", ")", "model_fields", "=", "model", ".", "all_fields", "except", "ValueError", ":", "raise", "InvalidQueryParams", "(", "*", "*", "{", "'detail'", ":", "'The fields query param provided with a '", "'field type of \"%s\" is unknown.'", "%", "rtype", ",", "'links'", ":", "LINK", ",", "'parameter'", ":", "PARAM", ",", "}", ")", "for", "field", "in", "fields", ":", "if", "field", "not", "in", "model_fields", ":", "raise", "InvalidQueryParams", "(", "*", "*", "{", "'detail'", ":", "'The fields query param \"TYPE\" of \"%s\" '", "'is not possible. It does not have a field '", "'by the name of \"%s\".'", "%", "(", "rtype", ",", "field", ")", ",", "'links'", ":", "LINK", ",", "'parameter'", ":", "PARAM", ",", "}", ")" ]
Ensure the sparse fields exists on the models
[ "Ensure", "the", "sparse", "fields", "exists", "on", "the", "models" ]
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/fields.py#L53-L76
244,692
sassoo/goldman
goldman/queryparams/fields.py
init
def init(req, model): # pylint: disable=unused-argument """ Determine the sparse fields to limit the response to Return a dict where the key is the resource type (rtype) & the value is an array of string fields names to whitelist against. :return: dict """ params = {} for key, val in req.params.items(): try: rtype, fields = _parse_param(key, val) params[rtype] = fields except TypeError: continue if params: _validate_req(req) for rtype, fields in params.items(): _validate_param(rtype, fields) return params
python
def init(req, model): # pylint: disable=unused-argument """ Determine the sparse fields to limit the response to Return a dict where the key is the resource type (rtype) & the value is an array of string fields names to whitelist against. :return: dict """ params = {} for key, val in req.params.items(): try: rtype, fields = _parse_param(key, val) params[rtype] = fields except TypeError: continue if params: _validate_req(req) for rtype, fields in params.items(): _validate_param(rtype, fields) return params
[ "def", "init", "(", "req", ",", "model", ")", ":", "# pylint: disable=unused-argument", "params", "=", "{", "}", "for", "key", ",", "val", "in", "req", ".", "params", ".", "items", "(", ")", ":", "try", ":", "rtype", ",", "fields", "=", "_parse_param", "(", "key", ",", "val", ")", "params", "[", "rtype", "]", "=", "fields", "except", "TypeError", ":", "continue", "if", "params", ":", "_validate_req", "(", "req", ")", "for", "rtype", ",", "fields", "in", "params", ".", "items", "(", ")", ":", "_validate_param", "(", "rtype", ",", "fields", ")", "return", "params" ]
Determine the sparse fields to limit the response to Return a dict where the key is the resource type (rtype) & the value is an array of string fields names to whitelist against. :return: dict
[ "Determine", "the", "sparse", "fields", "to", "limit", "the", "response", "to" ]
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/fields.py#L99-L123
244,693
jorgebg/lumpy
lumpy/mail.py
Mail.query_mxrecords
def query_mxrecords(self): """ Looks up for the MX DNS records of the recipient SMTP server """ import dns.resolver logging.info('Resolving DNS query...') answers = dns.resolver.query(self.domain, 'MX') addresses = [answer.exchange.to_text() for answer in answers] logging.info( '{} records found:\n{}'.format( len(addresses), '\n '.join(addresses))) return addresses
python
def query_mxrecords(self): """ Looks up for the MX DNS records of the recipient SMTP server """ import dns.resolver logging.info('Resolving DNS query...') answers = dns.resolver.query(self.domain, 'MX') addresses = [answer.exchange.to_text() for answer in answers] logging.info( '{} records found:\n{}'.format( len(addresses), '\n '.join(addresses))) return addresses
[ "def", "query_mxrecords", "(", "self", ")", ":", "import", "dns", ".", "resolver", "logging", ".", "info", "(", "'Resolving DNS query...'", ")", "answers", "=", "dns", ".", "resolver", ".", "query", "(", "self", ".", "domain", ",", "'MX'", ")", "addresses", "=", "[", "answer", ".", "exchange", ".", "to_text", "(", ")", "for", "answer", "in", "answers", "]", "logging", ".", "info", "(", "'{} records found:\\n{}'", ".", "format", "(", "len", "(", "addresses", ")", ",", "'\\n '", ".", "join", "(", "addresses", ")", ")", ")", "return", "addresses" ]
Looks up for the MX DNS records of the recipient SMTP server
[ "Looks", "up", "for", "the", "MX", "DNS", "records", "of", "the", "recipient", "SMTP", "server" ]
1555151a5c36a327591ff9ba7ca88d6812eb9949
https://github.com/jorgebg/lumpy/blob/1555151a5c36a327591ff9ba7ca88d6812eb9949/lumpy/mail.py#L48-L59
244,694
jorgebg/lumpy
lumpy/mail.py
Mail.send
def send(self): """ Attempts the delivery through recipient's domain MX records. """ try: for mx in self.mxrecords: logging.info('Connecting to {} {}...'.format(mx, self.port)) server = smtplib.SMTP(mx, self.port) server.set_debuglevel(logging.root.level < logging.WARN) server.sendmail( self.sender, [self.recipient], self.message.as_string()) server.quit() return True except Exception as e: logging.error(e) if (isinstance(e, IOError) and e.errno in (errno.ENETUNREACH, errno.ECONNREFUSED)): logging.error( 'Please check that port {} is open'.format(self.port)) if logging.root.level < logging.WARN: raise e return False
python
def send(self): """ Attempts the delivery through recipient's domain MX records. """ try: for mx in self.mxrecords: logging.info('Connecting to {} {}...'.format(mx, self.port)) server = smtplib.SMTP(mx, self.port) server.set_debuglevel(logging.root.level < logging.WARN) server.sendmail( self.sender, [self.recipient], self.message.as_string()) server.quit() return True except Exception as e: logging.error(e) if (isinstance(e, IOError) and e.errno in (errno.ENETUNREACH, errno.ECONNREFUSED)): logging.error( 'Please check that port {} is open'.format(self.port)) if logging.root.level < logging.WARN: raise e return False
[ "def", "send", "(", "self", ")", ":", "try", ":", "for", "mx", "in", "self", ".", "mxrecords", ":", "logging", ".", "info", "(", "'Connecting to {} {}...'", ".", "format", "(", "mx", ",", "self", ".", "port", ")", ")", "server", "=", "smtplib", ".", "SMTP", "(", "mx", ",", "self", ".", "port", ")", "server", ".", "set_debuglevel", "(", "logging", ".", "root", ".", "level", "<", "logging", ".", "WARN", ")", "server", ".", "sendmail", "(", "self", ".", "sender", ",", "[", "self", ".", "recipient", "]", ",", "self", ".", "message", ".", "as_string", "(", ")", ")", "server", ".", "quit", "(", ")", "return", "True", "except", "Exception", "as", "e", ":", "logging", ".", "error", "(", "e", ")", "if", "(", "isinstance", "(", "e", ",", "IOError", ")", "and", "e", ".", "errno", "in", "(", "errno", ".", "ENETUNREACH", ",", "errno", ".", "ECONNREFUSED", ")", ")", ":", "logging", ".", "error", "(", "'Please check that port {} is open'", ".", "format", "(", "self", ".", "port", ")", ")", "if", "logging", ".", "root", ".", "level", "<", "logging", ".", "WARN", ":", "raise", "e", "return", "False" ]
Attempts the delivery through recipient's domain MX records.
[ "Attempts", "the", "delivery", "through", "recipient", "s", "domain", "MX", "records", "." ]
1555151a5c36a327591ff9ba7ca88d6812eb9949
https://github.com/jorgebg/lumpy/blob/1555151a5c36a327591ff9ba7ca88d6812eb9949/lumpy/mail.py#L61-L82
244,695
Nixiware/viper
nx/viper/dispatcher.py
Dispatcher.dispatch
def dispatch(self, requestProtocol, requestPayload): """ Dispatch the request to the appropriate handler. :param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol :param requestPayload: <dict> request :param version: <float> version :param method: <str> method name :param parameters: <dict> data parameters :return: <void> """ # method decoding method = requestPayload["method"].split(".") if len(method) != 3: requestProtocol.failRequestWithErrors(["InvalidMethod"]) return # parsing method name methodModule = method[0] methodController = method[1] methodAction = method[2] # checking if module exists if not self.application.isModuleLoaded(methodModule): requestProtocol.failRequestWithErrors(["InvalidMethodModule"]) return # checking if controller exists controllerPath = os.path.join( "application", "module", methodModule, "controller", "{}.py".format(methodController) ) if not os.path.isfile(controllerPath): requestProtocol.failRequestWithErrors(["InvalidMethodController"]) return # importing controller controllerSpec = importlib.util.spec_from_file_location( methodController, controllerPath ) controller = importlib.util.module_from_spec(controllerSpec) controllerSpec.loader.exec_module(controller) # instancing controller controllerInstance = controller.Controller( self.application, requestProtocol, requestPayload["version"], requestPayload["parameters"] ) # checking if action exists action = getattr( controllerInstance, "{}Action".format(methodAction), None ) if not callable(action): requestProtocol.failRequestWithErrors(["InvalidMethodAction"]) return # executing action requestProtocol.requestPassedDispatcherValidation() preDispatchAction = getattr(controllerInstance, "preDispatch") postDispatchAction = getattr(controllerInstance, "postDispatch") preDispatchAction() action() postDispatchAction()
python
def dispatch(self, requestProtocol, requestPayload): """ Dispatch the request to the appropriate handler. :param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol :param requestPayload: <dict> request :param version: <float> version :param method: <str> method name :param parameters: <dict> data parameters :return: <void> """ # method decoding method = requestPayload["method"].split(".") if len(method) != 3: requestProtocol.failRequestWithErrors(["InvalidMethod"]) return # parsing method name methodModule = method[0] methodController = method[1] methodAction = method[2] # checking if module exists if not self.application.isModuleLoaded(methodModule): requestProtocol.failRequestWithErrors(["InvalidMethodModule"]) return # checking if controller exists controllerPath = os.path.join( "application", "module", methodModule, "controller", "{}.py".format(methodController) ) if not os.path.isfile(controllerPath): requestProtocol.failRequestWithErrors(["InvalidMethodController"]) return # importing controller controllerSpec = importlib.util.spec_from_file_location( methodController, controllerPath ) controller = importlib.util.module_from_spec(controllerSpec) controllerSpec.loader.exec_module(controller) # instancing controller controllerInstance = controller.Controller( self.application, requestProtocol, requestPayload["version"], requestPayload["parameters"] ) # checking if action exists action = getattr( controllerInstance, "{}Action".format(methodAction), None ) if not callable(action): requestProtocol.failRequestWithErrors(["InvalidMethodAction"]) return # executing action requestProtocol.requestPassedDispatcherValidation() preDispatchAction = getattr(controllerInstance, "preDispatch") postDispatchAction = getattr(controllerInstance, "postDispatch") preDispatchAction() action() postDispatchAction()
[ "def", "dispatch", "(", "self", ",", "requestProtocol", ",", "requestPayload", ")", ":", "# method decoding", "method", "=", "requestPayload", "[", "\"method\"", "]", ".", "split", "(", "\".\"", ")", "if", "len", "(", "method", ")", "!=", "3", ":", "requestProtocol", ".", "failRequestWithErrors", "(", "[", "\"InvalidMethod\"", "]", ")", "return", "# parsing method name", "methodModule", "=", "method", "[", "0", "]", "methodController", "=", "method", "[", "1", "]", "methodAction", "=", "method", "[", "2", "]", "# checking if module exists", "if", "not", "self", ".", "application", ".", "isModuleLoaded", "(", "methodModule", ")", ":", "requestProtocol", ".", "failRequestWithErrors", "(", "[", "\"InvalidMethodModule\"", "]", ")", "return", "# checking if controller exists", "controllerPath", "=", "os", ".", "path", ".", "join", "(", "\"application\"", ",", "\"module\"", ",", "methodModule", ",", "\"controller\"", ",", "\"{}.py\"", ".", "format", "(", "methodController", ")", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "controllerPath", ")", ":", "requestProtocol", ".", "failRequestWithErrors", "(", "[", "\"InvalidMethodController\"", "]", ")", "return", "# importing controller", "controllerSpec", "=", "importlib", ".", "util", ".", "spec_from_file_location", "(", "methodController", ",", "controllerPath", ")", "controller", "=", "importlib", ".", "util", ".", "module_from_spec", "(", "controllerSpec", ")", "controllerSpec", ".", "loader", ".", "exec_module", "(", "controller", ")", "# instancing controller", "controllerInstance", "=", "controller", ".", "Controller", "(", "self", ".", "application", ",", "requestProtocol", ",", "requestPayload", "[", "\"version\"", "]", ",", "requestPayload", "[", "\"parameters\"", "]", ")", "# checking if action exists", "action", "=", "getattr", "(", "controllerInstance", ",", "\"{}Action\"", ".", "format", "(", "methodAction", ")", ",", "None", ")", "if", "not", "callable", "(", "action", ")", ":", "requestProtocol", ".", "failRequestWithErrors", "(", "[", "\"InvalidMethodAction\"", "]", ")", "return", "# executing action", "requestProtocol", ".", "requestPassedDispatcherValidation", "(", ")", "preDispatchAction", "=", "getattr", "(", "controllerInstance", ",", "\"preDispatch\"", ")", "postDispatchAction", "=", "getattr", "(", "controllerInstance", ",", "\"postDispatch\"", ")", "preDispatchAction", "(", ")", "action", "(", ")", "postDispatchAction", "(", ")" ]
Dispatch the request to the appropriate handler. :param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol :param requestPayload: <dict> request :param version: <float> version :param method: <str> method name :param parameters: <dict> data parameters :return: <void>
[ "Dispatch", "the", "request", "to", "the", "appropriate", "handler", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/dispatcher.py#L16-L89
244,696
delfick/aws_syncr
aws_syncr/collector.py
Collector.prepare
def prepare(self, configuration_folder, args_dict, environment): """Make a temporary configuration file from the files in our folder""" self.configuration_folder = configuration_folder if not os.path.isdir(configuration_folder): raise BadOption("Specified configuration folder is not a directory!", wanted=configuration_folder) available = [os.path.join(configuration_folder, name) for name in os.listdir(configuration_folder)] available_environments = [os.path.basename(path) for path in available if os.path.isdir(path)] available_environments = [e for e in available_environments if not e.startswith('.')] # Make sure the environment exists if environment and environment not in available_environments: raise BadOption("Specified environment doesn't exist", available=available_environments, wanted=environment) if environment: environment_files = [os.path.join(configuration_folder, "accounts.yaml")] for root, dirs, files in os.walk(os.path.join(configuration_folder, environment)): environment_files.extend(os.path.join(root, filename) for filename in files) with tempfile.NamedTemporaryFile() as fle: contents = json.dumps({"includes": environment_files}) fle.write(contents.encode('utf-8')) fle.flush() args_dict['aws_syncr']['environment'] = os.path.split(environment)[-1] super(Collector, self).prepare(fle.name, args_dict)
python
def prepare(self, configuration_folder, args_dict, environment): """Make a temporary configuration file from the files in our folder""" self.configuration_folder = configuration_folder if not os.path.isdir(configuration_folder): raise BadOption("Specified configuration folder is not a directory!", wanted=configuration_folder) available = [os.path.join(configuration_folder, name) for name in os.listdir(configuration_folder)] available_environments = [os.path.basename(path) for path in available if os.path.isdir(path)] available_environments = [e for e in available_environments if not e.startswith('.')] # Make sure the environment exists if environment and environment not in available_environments: raise BadOption("Specified environment doesn't exist", available=available_environments, wanted=environment) if environment: environment_files = [os.path.join(configuration_folder, "accounts.yaml")] for root, dirs, files in os.walk(os.path.join(configuration_folder, environment)): environment_files.extend(os.path.join(root, filename) for filename in files) with tempfile.NamedTemporaryFile() as fle: contents = json.dumps({"includes": environment_files}) fle.write(contents.encode('utf-8')) fle.flush() args_dict['aws_syncr']['environment'] = os.path.split(environment)[-1] super(Collector, self).prepare(fle.name, args_dict)
[ "def", "prepare", "(", "self", ",", "configuration_folder", ",", "args_dict", ",", "environment", ")", ":", "self", ".", "configuration_folder", "=", "configuration_folder", "if", "not", "os", ".", "path", ".", "isdir", "(", "configuration_folder", ")", ":", "raise", "BadOption", "(", "\"Specified configuration folder is not a directory!\"", ",", "wanted", "=", "configuration_folder", ")", "available", "=", "[", "os", ".", "path", ".", "join", "(", "configuration_folder", ",", "name", ")", "for", "name", "in", "os", ".", "listdir", "(", "configuration_folder", ")", "]", "available_environments", "=", "[", "os", ".", "path", ".", "basename", "(", "path", ")", "for", "path", "in", "available", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "]", "available_environments", "=", "[", "e", "for", "e", "in", "available_environments", "if", "not", "e", ".", "startswith", "(", "'.'", ")", "]", "# Make sure the environment exists", "if", "environment", "and", "environment", "not", "in", "available_environments", ":", "raise", "BadOption", "(", "\"Specified environment doesn't exist\"", ",", "available", "=", "available_environments", ",", "wanted", "=", "environment", ")", "if", "environment", ":", "environment_files", "=", "[", "os", ".", "path", ".", "join", "(", "configuration_folder", ",", "\"accounts.yaml\"", ")", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "os", ".", "path", ".", "join", "(", "configuration_folder", ",", "environment", ")", ")", ":", "environment_files", ".", "extend", "(", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")", "for", "filename", "in", "files", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", ")", "as", "fle", ":", "contents", "=", "json", ".", "dumps", "(", "{", "\"includes\"", ":", "environment_files", "}", ")", "fle", ".", "write", "(", "contents", ".", "encode", "(", "'utf-8'", ")", ")", "fle", ".", "flush", "(", ")", "args_dict", "[", "'aws_syncr'", "]", "[", "'environment'", "]", "=", "os", ".", "path", ".", "split", "(", "environment", ")", "[", "-", "1", "]", "super", "(", "Collector", ",", "self", ")", ".", "prepare", "(", "fle", ".", "name", ",", "args_dict", ")" ]
Make a temporary configuration file from the files in our folder
[ "Make", "a", "temporary", "configuration", "file", "from", "the", "files", "in", "our", "folder" ]
8cd214b27c1eee98dfba4632cbb8bc0ae36356bd
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/collector.py#L38-L61
244,697
delfick/aws_syncr
aws_syncr/collector.py
Collector.extra_prepare_after_activation
def extra_prepare_after_activation(self, configuration, args_dict): """Setup our connection to amazon""" aws_syncr = configuration['aws_syncr'] configuration["amazon"] = Amazon(configuration['aws_syncr'].environment, configuration['accounts'], debug=aws_syncr.debug, dry_run=aws_syncr.dry_run)
python
def extra_prepare_after_activation(self, configuration, args_dict): """Setup our connection to amazon""" aws_syncr = configuration['aws_syncr'] configuration["amazon"] = Amazon(configuration['aws_syncr'].environment, configuration['accounts'], debug=aws_syncr.debug, dry_run=aws_syncr.dry_run)
[ "def", "extra_prepare_after_activation", "(", "self", ",", "configuration", ",", "args_dict", ")", ":", "aws_syncr", "=", "configuration", "[", "'aws_syncr'", "]", "configuration", "[", "\"amazon\"", "]", "=", "Amazon", "(", "configuration", "[", "'aws_syncr'", "]", ".", "environment", ",", "configuration", "[", "'accounts'", "]", ",", "debug", "=", "aws_syncr", ".", "debug", ",", "dry_run", "=", "aws_syncr", ".", "dry_run", ")" ]
Setup our connection to amazon
[ "Setup", "our", "connection", "to", "amazon" ]
8cd214b27c1eee98dfba4632cbb8bc0ae36356bd
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/collector.py#L81-L84
244,698
delfick/aws_syncr
aws_syncr/collector.py
Collector.add_configuration
def add_configuration(self, configuration, collect_another_source, done, result, src): """Used to add a file to the configuration, result here is the yaml.load of the src""" if "includes" in result: for include in result["includes"]: collect_another_source(include) configuration.update(result, source=src)
python
def add_configuration(self, configuration, collect_another_source, done, result, src): """Used to add a file to the configuration, result here is the yaml.load of the src""" if "includes" in result: for include in result["includes"]: collect_another_source(include) configuration.update(result, source=src)
[ "def", "add_configuration", "(", "self", ",", "configuration", ",", "collect_another_source", ",", "done", ",", "result", ",", "src", ")", ":", "if", "\"includes\"", "in", "result", ":", "for", "include", "in", "result", "[", "\"includes\"", "]", ":", "collect_another_source", "(", "include", ")", "configuration", ".", "update", "(", "result", ",", "source", "=", "src", ")" ]
Used to add a file to the configuration, result here is the yaml.load of the src
[ "Used", "to", "add", "a", "file", "to", "the", "configuration", "result", "here", "is", "the", "yaml", ".", "load", "of", "the", "src" ]
8cd214b27c1eee98dfba4632cbb8bc0ae36356bd
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/collector.py#L100-L105
244,699
stephanepechard/projy
projy/cmdline.py
template_name_from_class_name
def template_name_from_class_name(class_name): """ Remove the last 'Template' in the name. """ suffix = 'Template' output = class_name if (class_name.endswith(suffix)): output = class_name[:-len(suffix)] return output
python
def template_name_from_class_name(class_name): """ Remove the last 'Template' in the name. """ suffix = 'Template' output = class_name if (class_name.endswith(suffix)): output = class_name[:-len(suffix)] return output
[ "def", "template_name_from_class_name", "(", "class_name", ")", ":", "suffix", "=", "'Template'", "output", "=", "class_name", "if", "(", "class_name", ".", "endswith", "(", "suffix", ")", ")", ":", "output", "=", "class_name", "[", ":", "-", "len", "(", "suffix", ")", "]", "return", "output" ]
Remove the last 'Template' in the name.
[ "Remove", "the", "last", "Template", "in", "the", "name", "." ]
3146b0e3c207b977e1b51fcb33138746dae83c23
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L32-L38