repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
klahnakoski/mo-times
mo_times/vendor/dateutil/tzwin.py
tzwinbase.list
def list(): """Return a list of all time zones known to the system.""" handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) tzkey = winreg.OpenKey(handle, TZKEYNAME) result = [winreg.EnumKey(tzkey, i) for i in range(winreg.QueryInfoKey(tzkey)[0])] tzkey.Close() handle.Close() return result
python
def list(): """Return a list of all time zones known to the system.""" handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) tzkey = winreg.OpenKey(handle, TZKEYNAME) result = [winreg.EnumKey(tzkey, i) for i in range(winreg.QueryInfoKey(tzkey)[0])] tzkey.Close() handle.Close() return result
[ "def", "list", "(", ")", ":", "handle", "=", "winreg", ".", "ConnectRegistry", "(", "None", ",", "winreg", ".", "HKEY_LOCAL_MACHINE", ")", "tzkey", "=", "winreg", ".", "OpenKey", "(", "handle", ",", "TZKEYNAME", ")", "result", "=", "[", "winreg", ".", ...
Return a list of all time zones known to the system.
[ "Return", "a", "list", "of", "all", "time", "zones", "known", "to", "the", "system", "." ]
train
https://github.com/klahnakoski/mo-times/blob/e64a720b9796e076adeb0d5773ec6915ca045b9d/mo_times/vendor/dateutil/tzwin.py#L49-L57
mixmastamyk/fr
fr/ansi.py
colorstart
def colorstart(fgcolor, bgcolor, weight): ''' Begin a text style. ''' if weight: weight = bold else: weight = norm if bgcolor: out('\x1b[%s;%s;%sm' % (weight, fgcolor, bgcolor)) else: out('\x1b[%s;%sm' % (weight, fgcolor))
python
def colorstart(fgcolor, bgcolor, weight): ''' Begin a text style. ''' if weight: weight = bold else: weight = norm if bgcolor: out('\x1b[%s;%s;%sm' % (weight, fgcolor, bgcolor)) else: out('\x1b[%s;%sm' % (weight, fgcolor))
[ "def", "colorstart", "(", "fgcolor", ",", "bgcolor", ",", "weight", ")", ":", "if", "weight", ":", "weight", "=", "bold", "else", ":", "weight", "=", "norm", "if", "bgcolor", ":", "out", "(", "'\\x1b[%s;%s;%sm'", "%", "(", "weight", ",", "fgcolor", ","...
Begin a text style.
[ "Begin", "a", "text", "style", "." ]
train
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/ansi.py#L108-L117
mixmastamyk/fr
fr/ansi.py
cprint
def cprint(text, fg=grey, bg=blackbg, w=norm, cr=False, encoding='utf8'): ''' Print a string in a specified color style and then return to normal. def cprint(text, fg=white, bg=blackbg, w=norm, cr=True): ''' colorstart(fg, bg, w) out(text) colorend(cr)
python
def cprint(text, fg=grey, bg=blackbg, w=norm, cr=False, encoding='utf8'): ''' Print a string in a specified color style and then return to normal. def cprint(text, fg=white, bg=blackbg, w=norm, cr=True): ''' colorstart(fg, bg, w) out(text) colorend(cr)
[ "def", "cprint", "(", "text", ",", "fg", "=", "grey", ",", "bg", "=", "blackbg", ",", "w", "=", "norm", ",", "cr", "=", "False", ",", "encoding", "=", "'utf8'", ")", ":", "colorstart", "(", "fg", ",", "bg", ",", "w", ")", "out", "(", "text", ...
Print a string in a specified color style and then return to normal. def cprint(text, fg=white, bg=blackbg, w=norm, cr=True):
[ "Print", "a", "string", "in", "a", "specified", "color", "style", "and", "then", "return", "to", "normal", ".", "def", "cprint", "(", "text", "fg", "=", "white", "bg", "=", "blackbg", "w", "=", "norm", "cr", "=", "True", ")", ":" ]
train
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/ansi.py#L128-L134
mixmastamyk/fr
fr/ansi.py
bargraph
def bargraph(data, maxwidth, incolor=True, cbrackets=('\u2595', '\u258F')): ''' Creates a monochrome or two-color bar graph. ''' threshold = 100.0 // (maxwidth * 2) # if smaller than 1/2 of one char wide position = 0 begpcnt = data[0][1] * 100 endpcnt = data[-1][1] * 100 if len(data) < 1: return # Nada to do maxwidth = maxwidth - 2 # because of brackets datalen = len(data) # Print left bracket in correct color: if cbrackets and incolor: # and not (begpcnt == 0 and endpcnt == 0): if begpcnt < threshold: bkcolor = data[-1][2] # greenbg else: bkcolor = data[0][2] # redbg cprint(cbrackets[0], data[0][2], bkcolor, None, None) else: out(cbrackets[0]) for i, part in enumerate(data): # unpack data char, pcnt, fgcolor, bgcolor, bold = part width = int(round(pcnt/100.0 * maxwidth, 0)) position = position + width # and graph if incolor and not (fgcolor is None): cprint(char * width, fgcolor, bgcolor, bold, False) else: out((char * width)) if i == (datalen - 1): # correct last one if position < maxwidth: if incolor: # char cprint(char * (maxwidth-position), fgcolor, bgcolor, bold, False) else: out(char * (maxwidth-position)) elif position > maxwidth: out(chr(8) + ' ' + chr(8)) # backspace # Print right bracket in correct color: if cbrackets and incolor: if endpcnt < threshold: bkcolor = data[0][3] # redbg else: bkcolor = data[1][3] # greenbg cprint(cbrackets[1], data[-1][2], bkcolor, None, None) else: out(cbrackets[1])
python
def bargraph(data, maxwidth, incolor=True, cbrackets=('\u2595', '\u258F')): ''' Creates a monochrome or two-color bar graph. ''' threshold = 100.0 // (maxwidth * 2) # if smaller than 1/2 of one char wide position = 0 begpcnt = data[0][1] * 100 endpcnt = data[-1][1] * 100 if len(data) < 1: return # Nada to do maxwidth = maxwidth - 2 # because of brackets datalen = len(data) # Print left bracket in correct color: if cbrackets and incolor: # and not (begpcnt == 0 and endpcnt == 0): if begpcnt < threshold: bkcolor = data[-1][2] # greenbg else: bkcolor = data[0][2] # redbg cprint(cbrackets[0], data[0][2], bkcolor, None, None) else: out(cbrackets[0]) for i, part in enumerate(data): # unpack data char, pcnt, fgcolor, bgcolor, bold = part width = int(round(pcnt/100.0 * maxwidth, 0)) position = position + width # and graph if incolor and not (fgcolor is None): cprint(char * width, fgcolor, bgcolor, bold, False) else: out((char * width)) if i == (datalen - 1): # correct last one if position < maxwidth: if incolor: # char cprint(char * (maxwidth-position), fgcolor, bgcolor, bold, False) else: out(char * (maxwidth-position)) elif position > maxwidth: out(chr(8) + ' ' + chr(8)) # backspace # Print right bracket in correct color: if cbrackets and incolor: if endpcnt < threshold: bkcolor = data[0][3] # redbg else: bkcolor = data[1][3] # greenbg cprint(cbrackets[1], data[-1][2], bkcolor, None, None) else: out(cbrackets[1])
[ "def", "bargraph", "(", "data", ",", "maxwidth", ",", "incolor", "=", "True", ",", "cbrackets", "=", "(", "'\\u2595'", ",", "'\\u258F'", ")", ")", ":", "threshold", "=", "100.0", "//", "(", "maxwidth", "*", "2", ")", "# if smaller than 1/2 of one char wide",...
Creates a monochrome or two-color bar graph.
[ "Creates", "a", "monochrome", "or", "two", "-", "color", "bar", "graph", "." ]
train
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/ansi.py#L137-L184
mixmastamyk/fr
fr/ansi.py
rainbar
def rainbar(data, maxwidth, incolor=True, hicolor=True, cbrackets=('\u2595', '\u258F')): ''' Creates a "rainbar" style bar graph. ''' if not data: return # Nada to do datalen = len(data) endpcnt = data[-1][1] maxwidth = maxwidth - 2 # because of brackets # setup csi, csib, _, pal, rst, plen = get_palette(hicolor) empty = data[-1][0] bucket = float(maxwidth) / plen position = 0 # Print left bracket in correct color: if incolor: out((csi % pal[0]) + cbrackets[0]) # start bracket else: out(cbrackets[0]) for i, part in enumerate(data): char, pcnt, fgcolor, bgcolor, bold = part if fgcolor and hicolor: fgcolor = map8[fgcolor] if not bold: csib = csi lastind = None width = int(maxwidth * (pcnt / 100.0)) offset = position position += width if incolor: for j in range(width): # faster? colorind = fgcolor or min(int((j+offset)/bucket), (plen-1)) #~ colorind=fgcolor or get_color_index(j, offset,maxwidth,plen) if colorind == lastind: out(char) else: color = fgcolor or pal[colorind] out((csib % color) + char) lastind = colorind else: out((char * width)) if i == (datalen - 1): # check if last one correct if position < maxwidth: rest = maxwidth - position if incolor: out((csib % pal[-1]) + (empty * rest)) else: out(char * rest) elif position > maxwidth: out(chr(8) + ' ' + chr(8)) # backspace # Print right bracket in correct color: if incolor: lastcolor = darkred if (hicolor and endpcnt > 1) else pal[-1] out((csi % lastcolor) + cbrackets[1]) # end bracket colorend() else: out(cbrackets[1])
python
def rainbar(data, maxwidth, incolor=True, hicolor=True, cbrackets=('\u2595', '\u258F')): ''' Creates a "rainbar" style bar graph. ''' if not data: return # Nada to do datalen = len(data) endpcnt = data[-1][1] maxwidth = maxwidth - 2 # because of brackets # setup csi, csib, _, pal, rst, plen = get_palette(hicolor) empty = data[-1][0] bucket = float(maxwidth) / plen position = 0 # Print left bracket in correct color: if incolor: out((csi % pal[0]) + cbrackets[0]) # start bracket else: out(cbrackets[0]) for i, part in enumerate(data): char, pcnt, fgcolor, bgcolor, bold = part if fgcolor and hicolor: fgcolor = map8[fgcolor] if not bold: csib = csi lastind = None width = int(maxwidth * (pcnt / 100.0)) offset = position position += width if incolor: for j in range(width): # faster? colorind = fgcolor or min(int((j+offset)/bucket), (plen-1)) #~ colorind=fgcolor or get_color_index(j, offset,maxwidth,plen) if colorind == lastind: out(char) else: color = fgcolor or pal[colorind] out((csib % color) + char) lastind = colorind else: out((char * width)) if i == (datalen - 1): # check if last one correct if position < maxwidth: rest = maxwidth - position if incolor: out((csib % pal[-1]) + (empty * rest)) else: out(char * rest) elif position > maxwidth: out(chr(8) + ' ' + chr(8)) # backspace # Print right bracket in correct color: if incolor: lastcolor = darkred if (hicolor and endpcnt > 1) else pal[-1] out((csi % lastcolor) + cbrackets[1]) # end bracket colorend() else: out(cbrackets[1])
[ "def", "rainbar", "(", "data", ",", "maxwidth", ",", "incolor", "=", "True", ",", "hicolor", "=", "True", ",", "cbrackets", "=", "(", "'\\u2595'", ",", "'\\u258F'", ")", ")", ":", "if", "not", "data", ":", "return", "# Nada to do", "datalen", "=", "len...
Creates a "rainbar" style bar graph.
[ "Creates", "a", "rainbar", "style", "bar", "graph", "." ]
train
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/ansi.py#L207-L270
cemsbr/yala
yala/config.py
Config._set_linters
def _set_linters(self): """Use user linters or all available when not specified.""" if 'linters' in self._config: self.user_linters = list(self._parse_cfg_linters()) self.linters = {linter: self._all_linters[linter] for linter in self.user_linters} else: self.linters = self._all_linters
python
def _set_linters(self): """Use user linters or all available when not specified.""" if 'linters' in self._config: self.user_linters = list(self._parse_cfg_linters()) self.linters = {linter: self._all_linters[linter] for linter in self.user_linters} else: self.linters = self._all_linters
[ "def", "_set_linters", "(", "self", ")", ":", "if", "'linters'", "in", "self", ".", "_config", ":", "self", ".", "user_linters", "=", "list", "(", "self", ".", "_parse_cfg_linters", "(", ")", ")", "self", ".", "linters", "=", "{", "linter", ":", "self"...
Use user linters or all available when not specified.
[ "Use", "user", "linters", "or", "all", "available", "when", "not", "specified", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/config.py#L37-L44
cemsbr/yala
yala/config.py
Config.print_config
def print_config(self): """Print all yala configurations, including default and user's.""" linters = self.user_linters or list(self.linters) print('linters:', ', '.join(linters)) for key, value in self._config.items(): if key != 'linters': print('{}: {}'.format(key, value))
python
def print_config(self): """Print all yala configurations, including default and user's.""" linters = self.user_linters or list(self.linters) print('linters:', ', '.join(linters)) for key, value in self._config.items(): if key != 'linters': print('{}: {}'.format(key, value))
[ "def", "print_config", "(", "self", ")", ":", "linters", "=", "self", ".", "user_linters", "or", "list", "(", "self", ".", "linters", ")", "print", "(", "'linters:'", ",", "', '", ".", "join", "(", "linters", ")", ")", "for", "key", ",", "value", "in...
Print all yala configurations, including default and user's.
[ "Print", "all", "yala", "configurations", "including", "default", "and", "user", "s", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/config.py#L46-L52
cemsbr/yala
yala/config.py
Config._parse_cfg_linters
def _parse_cfg_linters(self): """Return valid linter names found in config files.""" user_value = self._config.get('linters', '') # For each line of "linters" value, use comma as separator for line in user_value.splitlines(): yield from self._parse_linters_line(line)
python
def _parse_cfg_linters(self): """Return valid linter names found in config files.""" user_value = self._config.get('linters', '') # For each line of "linters" value, use comma as separator for line in user_value.splitlines(): yield from self._parse_linters_line(line)
[ "def", "_parse_cfg_linters", "(", "self", ")", ":", "user_value", "=", "self", ".", "_config", ".", "get", "(", "'linters'", ",", "''", ")", "# For each line of \"linters\" value, use comma as separator", "for", "line", "in", "user_value", ".", "splitlines", "(", ...
Return valid linter names found in config files.
[ "Return", "valid", "linter", "names", "found", "in", "config", "files", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/config.py#L58-L63
cemsbr/yala
yala/config.py
Config.get_linter_config
def get_linter_config(self, name): """Return linter options without linter name prefix.""" prefix = name + ' ' return {k[len(prefix):]: v for k, v in self._config.items() if k.startswith(prefix)}
python
def get_linter_config(self, name): """Return linter options without linter name prefix.""" prefix = name + ' ' return {k[len(prefix):]: v for k, v in self._config.items() if k.startswith(prefix)}
[ "def", "get_linter_config", "(", "self", ",", "name", ")", ":", "prefix", "=", "name", "+", "' '", "return", "{", "k", "[", "len", "(", "prefix", ")", ":", "]", ":", "v", "for", "k", ",", "v", "in", "self", ".", "_config", ".", "items", "(", ")...
Return linter options without linter name prefix.
[ "Return", "linter", "options", "without", "linter", "name", "prefix", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/config.py#L73-L78
cemsbr/yala
yala/config.py
Config._merge
def _merge(cls, default, user): """Append user options to default options. Return yala section.""" section = cls._CFG_SECTION merged = default[section] if section not in user: return merged user = user[section] for key, value in user.items(): if key in merged: merged[key] += ' ' + value else: merged[key] = value return merged
python
def _merge(cls, default, user): """Append user options to default options. Return yala section.""" section = cls._CFG_SECTION merged = default[section] if section not in user: return merged user = user[section] for key, value in user.items(): if key in merged: merged[key] += ' ' + value else: merged[key] = value return merged
[ "def", "_merge", "(", "cls", ",", "default", ",", "user", ")", ":", "section", "=", "cls", ".", "_CFG_SECTION", "merged", "=", "default", "[", "section", "]", "if", "section", "not", "in", "user", ":", "return", "merged", "user", "=", "user", "[", "s...
Append user options to default options. Return yala section.
[ "Append", "user", "options", "to", "default", "options", ".", "Return", "yala", "section", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/config.py#L103-L117
TheOstrichIO/ostrichlib
ostrich/utils/text.py
as_text
def as_text(str_or_bytes, encoding='utf-8', errors='strict'): """Return input string as a text string. Should work for input string that's unicode or bytes, given proper encoding. >>> print(as_text(b'foo')) foo >>> b'foo'.decode('utf-8') == u'foo' True """ if isinstance(str_or_bytes, text): return str_or_bytes return str_or_bytes.decode(encoding, errors)
python
def as_text(str_or_bytes, encoding='utf-8', errors='strict'): """Return input string as a text string. Should work for input string that's unicode or bytes, given proper encoding. >>> print(as_text(b'foo')) foo >>> b'foo'.decode('utf-8') == u'foo' True """ if isinstance(str_or_bytes, text): return str_or_bytes return str_or_bytes.decode(encoding, errors)
[ "def", "as_text", "(", "str_or_bytes", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "str_or_bytes", ",", "text", ")", ":", "return", "str_or_bytes", "return", "str_or_bytes", ".", "decode", "(", "encodin...
Return input string as a text string. Should work for input string that's unicode or bytes, given proper encoding. >>> print(as_text(b'foo')) foo >>> b'foo'.decode('utf-8') == u'foo' True
[ "Return", "input", "string", "as", "a", "text", "string", "." ]
train
https://github.com/TheOstrichIO/ostrichlib/blob/ed97634ccbfb8b5042e61fbd0ac9a27aef281bcb/ostrich/utils/text.py#L27-L40
TheOstrichIO/ostrichlib
ostrich/utils/text.py
get_safe_path
def get_safe_path(in_str): """Return `in_str` converted to a string that can be be safely used as a path (either filename, or directory name). >>> print(get_safe_path("hello world, what's up?.txt")) hello_world__what_s_up_.txt Surrounding spaces are removed, and other "bad characters" are replaced with an underscore. The function attempts to replace unicode symbols (outside ASCII range) with ASCII equivalents (NFKD normalization). Everything else is also replaced with underscore. :warning: The function just returns a safe string to be used as a path. It DOES NOT promise anything about the existence or uniqueness of the path in the filesystem! Because of the conversions, many input strings will result the same output string, so it is the responsibility of the caller to decide how to handle this! >>> get_safe_path(' foo/bar.baz') == get_safe_path('foo$bar.baz ') True """ norm_str = _SAFE_PATH_RE.sub( '_', unicodedata.normalize('NFKD', as_text(in_str)).strip()) if len(norm_str.strip('.')) == 0: # making sure the normalized result is non-empty, and not just dots raise ValueError(in_str) return norm_str[:_MAX_PATH_NAME_LEN]
python
def get_safe_path(in_str): """Return `in_str` converted to a string that can be be safely used as a path (either filename, or directory name). >>> print(get_safe_path("hello world, what's up?.txt")) hello_world__what_s_up_.txt Surrounding spaces are removed, and other "bad characters" are replaced with an underscore. The function attempts to replace unicode symbols (outside ASCII range) with ASCII equivalents (NFKD normalization). Everything else is also replaced with underscore. :warning: The function just returns a safe string to be used as a path. It DOES NOT promise anything about the existence or uniqueness of the path in the filesystem! Because of the conversions, many input strings will result the same output string, so it is the responsibility of the caller to decide how to handle this! >>> get_safe_path(' foo/bar.baz') == get_safe_path('foo$bar.baz ') True """ norm_str = _SAFE_PATH_RE.sub( '_', unicodedata.normalize('NFKD', as_text(in_str)).strip()) if len(norm_str.strip('.')) == 0: # making sure the normalized result is non-empty, and not just dots raise ValueError(in_str) return norm_str[:_MAX_PATH_NAME_LEN]
[ "def", "get_safe_path", "(", "in_str", ")", ":", "norm_str", "=", "_SAFE_PATH_RE", ".", "sub", "(", "'_'", ",", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "as_text", "(", "in_str", ")", ")", ".", "strip", "(", ")", ")", "if", "len", "(", "n...
Return `in_str` converted to a string that can be be safely used as a path (either filename, or directory name). >>> print(get_safe_path("hello world, what's up?.txt")) hello_world__what_s_up_.txt Surrounding spaces are removed, and other "bad characters" are replaced with an underscore. The function attempts to replace unicode symbols (outside ASCII range) with ASCII equivalents (NFKD normalization). Everything else is also replaced with underscore. :warning: The function just returns a safe string to be used as a path. It DOES NOT promise anything about the existence or uniqueness of the path in the filesystem! Because of the conversions, many input strings will result the same output string, so it is the responsibility of the caller to decide how to handle this! >>> get_safe_path(' foo/bar.baz') == get_safe_path('foo$bar.baz ') True
[ "Return", "in_str", "converted", "to", "a", "string", "that", "can", "be", "be", "safely", "used", "as", "a", "path", "(", "either", "filename", "or", "directory", "name", ")", "." ]
train
https://github.com/TheOstrichIO/ostrichlib/blob/ed97634ccbfb8b5042e61fbd0ac9a27aef281bcb/ostrich/utils/text.py#L43-L70
reinout/syseggrecipe
syseggrecipe/recipe.py
Recipe.attempt_dev_link_via_import
def attempt_dev_link_via_import(self, egg): """Create egg-link to FS location if an egg is found through importing. Sometimes an egg *is* installed, but without a proper egg-info file. So we attempt to import the egg in order to return a link anyway. TODO: currently it only works with simple package names like "psycopg2" and "mapnik". """ try: imported = __import__(egg) except ImportError: self.logger.warn("Tried importing '%s', but that also didn't work.", egg) self.logger.debug("For reference, sys.path is %s", sys.path) return self.logger.info("Importing %s works, however", egg) try: probable_location = os.path.dirname(imported.__file__) except: # Bare except self.logger.exception("Determining the location failed, however") return filesystem_egg_link = os.path.join( self.dev_egg_dir, '%s.egg-link' % egg) f = open(filesystem_egg_link, 'w') f.write(probable_location) f.close() self.logger.info('Using sysegg %s for %s', probable_location, egg) self.added.append(filesystem_egg_link) return True
python
def attempt_dev_link_via_import(self, egg): """Create egg-link to FS location if an egg is found through importing. Sometimes an egg *is* installed, but without a proper egg-info file. So we attempt to import the egg in order to return a link anyway. TODO: currently it only works with simple package names like "psycopg2" and "mapnik". """ try: imported = __import__(egg) except ImportError: self.logger.warn("Tried importing '%s', but that also didn't work.", egg) self.logger.debug("For reference, sys.path is %s", sys.path) return self.logger.info("Importing %s works, however", egg) try: probable_location = os.path.dirname(imported.__file__) except: # Bare except self.logger.exception("Determining the location failed, however") return filesystem_egg_link = os.path.join( self.dev_egg_dir, '%s.egg-link' % egg) f = open(filesystem_egg_link, 'w') f.write(probable_location) f.close() self.logger.info('Using sysegg %s for %s', probable_location, egg) self.added.append(filesystem_egg_link) return True
[ "def", "attempt_dev_link_via_import", "(", "self", ",", "egg", ")", ":", "try", ":", "imported", "=", "__import__", "(", "egg", ")", "except", "ImportError", ":", "self", ".", "logger", ".", "warn", "(", "\"Tried importing '%s', but that also didn't work.\"", ",",...
Create egg-link to FS location if an egg is found through importing. Sometimes an egg *is* installed, but without a proper egg-info file. So we attempt to import the egg in order to return a link anyway. TODO: currently it only works with simple package names like "psycopg2" and "mapnik".
[ "Create", "egg", "-", "link", "to", "FS", "location", "if", "an", "egg", "is", "found", "through", "importing", "." ]
train
https://github.com/reinout/syseggrecipe/blob/1062038181178fa08b6a6d6755c4d51f47d28b0a/syseggrecipe/recipe.py#L99-L129
onyxfish/clan
clan/__init__.py
Clan._install_exception_handler
def _install_exception_handler(self): """ Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions. """ def handler(t, value, traceback): if self.args.verbose: sys.__excepthook__(t, value, traceback) else: sys.stderr.write('%s\n' % unicode(value).encode('utf-8')) sys.excepthook = handler
python
def _install_exception_handler(self): """ Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions. """ def handler(t, value, traceback): if self.args.verbose: sys.__excepthook__(t, value, traceback) else: sys.stderr.write('%s\n' % unicode(value).encode('utf-8')) sys.excepthook = handler
[ "def", "_install_exception_handler", "(", "self", ")", ":", "def", "handler", "(", "t", ",", "value", ",", "traceback", ")", ":", "if", "self", ".", "args", ".", "verbose", ":", "sys", ".", "__excepthook__", "(", "t", ",", "value", ",", "traceback", ")...
Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions.
[ "Installs", "a", "replacement", "for", "sys", ".", "excepthook", "which", "handles", "pretty", "-", "printing", "uncaught", "exceptions", "." ]
train
https://github.com/onyxfish/clan/blob/415ddd027ea81013f2d62d75aec6da70703df49c/clan/__init__.py#L49-L59
asmodehn/filefinder2
filefinder2/_encoding_utils.py
strip_encoding_cookie
def strip_encoding_cookie(filelike): """Generator to pull lines from a text-mode file, skipping the encoding cookie if it is found in the first two lines. """ it = iter(filelike) try: first = next(it) if not cookie_comment_re.match(first): yield first second = next(it) if not cookie_comment_re.match(second): yield second except StopIteration: return for line in it: yield line
python
def strip_encoding_cookie(filelike): """Generator to pull lines from a text-mode file, skipping the encoding cookie if it is found in the first two lines. """ it = iter(filelike) try: first = next(it) if not cookie_comment_re.match(first): yield first second = next(it) if not cookie_comment_re.match(second): yield second except StopIteration: return for line in it: yield line
[ "def", "strip_encoding_cookie", "(", "filelike", ")", ":", "it", "=", "iter", "(", "filelike", ")", "try", ":", "first", "=", "next", "(", "it", ")", "if", "not", "cookie_comment_re", ".", "match", "(", "first", ")", ":", "yield", "first", "second", "=...
Generator to pull lines from a text-mode file, skipping the encoding cookie if it is found in the first two lines.
[ "Generator", "to", "pull", "lines", "from", "a", "text", "-", "mode", "file", "skipping", "the", "encoding", "cookie", "if", "it", "is", "found", "in", "the", "first", "two", "lines", "." ]
train
https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_encoding_utils.py#L107-L123
asmodehn/filefinder2
filefinder2/_encoding_utils.py
source_to_unicode
def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True): """Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buffer or a string containing the source code. """ if isinstance(txt, six.text_type): return txt if isinstance(txt, six.binary_type): buffer = io.BytesIO(txt) else: buffer = txt try: encoding, _ = detect_encoding(buffer.readline) except SyntaxError: encoding = "ascii" buffer.seek(0) newline_decoder = io.IncrementalNewlineDecoder(None, True) text = io.TextIOWrapper(buffer, encoding, errors=errors, line_buffering=True) text.mode = 'r' if skip_encoding_cookie: return u"".join(strip_encoding_cookie(text)) else: return text.read()
python
def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True): """Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buffer or a string containing the source code. """ if isinstance(txt, six.text_type): return txt if isinstance(txt, six.binary_type): buffer = io.BytesIO(txt) else: buffer = txt try: encoding, _ = detect_encoding(buffer.readline) except SyntaxError: encoding = "ascii" buffer.seek(0) newline_decoder = io.IncrementalNewlineDecoder(None, True) text = io.TextIOWrapper(buffer, encoding, errors=errors, line_buffering=True) text.mode = 'r' if skip_encoding_cookie: return u"".join(strip_encoding_cookie(text)) else: return text.read()
[ "def", "source_to_unicode", "(", "txt", ",", "errors", "=", "'replace'", ",", "skip_encoding_cookie", "=", "True", ")", ":", "if", "isinstance", "(", "txt", ",", "six", ".", "text_type", ")", ":", "return", "txt", "if", "isinstance", "(", "txt", ",", "si...
Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buffer or a string containing the source code.
[ "Converts", "a", "bytes", "string", "with", "python", "source", "code", "to", "unicode", ".", "Unicode", "strings", "are", "passed", "through", "unchanged", ".", "Byte", "strings", "are", "checked", "for", "the", "python", "source", "file", "encoding", "cookie...
train
https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_encoding_utils.py#L126-L152
asmodehn/filefinder2
filefinder2/_encoding_utils.py
decode_source
def decode_source(source_bytes): """Decode bytes representing source code and return the string. Universal newline support is used in the decoding. """ # source_bytes_readline = io.BytesIO(source_bytes).readline # encoding, _ = detect_encoding(source_bytes_readline) newline_decoder = io.IncrementalNewlineDecoder(None, True) return newline_decoder.decode(source_to_unicode(source_bytes))
python
def decode_source(source_bytes): """Decode bytes representing source code and return the string. Universal newline support is used in the decoding. """ # source_bytes_readline = io.BytesIO(source_bytes).readline # encoding, _ = detect_encoding(source_bytes_readline) newline_decoder = io.IncrementalNewlineDecoder(None, True) return newline_decoder.decode(source_to_unicode(source_bytes))
[ "def", "decode_source", "(", "source_bytes", ")", ":", "# source_bytes_readline = io.BytesIO(source_bytes).readline", "# encoding, _ = detect_encoding(source_bytes_readline)", "newline_decoder", "=", "io", ".", "IncrementalNewlineDecoder", "(", "None", ",", "True", ")", "return",...
Decode bytes representing source code and return the string. Universal newline support is used in the decoding.
[ "Decode", "bytes", "representing", "source", "code", "and", "return", "the", "string", ".", "Universal", "newline", "support", "is", "used", "in", "the", "decoding", "." ]
train
https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_encoding_utils.py#L155-L162
wtsi-hgi/python-git-subrepo
gitsubrepo/subrepo.py
requires_subrepo
def requires_subrepo(func: Callable) -> Callable: """ Decorator that requires the `git subrepo` command to be accessible before calling the given function. :param func: the function to wrap :return: the wrapped function """ def decorated(*args, **kwargs): try: run([GIT_COMMAND, _GIT_SUBREPO_COMMAND, "--version"]) except RunException as e: raise RuntimeError("`git subrepo` does not appear to be working") from e return func(*args, **kwargs) return decorated
python
def requires_subrepo(func: Callable) -> Callable: """ Decorator that requires the `git subrepo` command to be accessible before calling the given function. :param func: the function to wrap :return: the wrapped function """ def decorated(*args, **kwargs): try: run([GIT_COMMAND, _GIT_SUBREPO_COMMAND, "--version"]) except RunException as e: raise RuntimeError("`git subrepo` does not appear to be working") from e return func(*args, **kwargs) return decorated
[ "def", "requires_subrepo", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "run", "(", "[", "GIT_COMMAND", ",", "_GIT_SUBREPO_COMMAND", ",", "\"--version\"", "...
Decorator that requires the `git subrepo` command to be accessible before calling the given function. :param func: the function to wrap :return: the wrapped function
[ "Decorator", "that", "requires", "the", "git", "subrepo", "command", "to", "be", "accessible", "before", "calling", "the", "given", "function", ".", ":", "param", "func", ":", "the", "function", "to", "wrap", ":", "return", ":", "the", "wrapped", "function" ...
train
https://github.com/wtsi-hgi/python-git-subrepo/blob/bb2eb2bd9a7e51b862298ddb4168cc5b8633dad0/gitsubrepo/subrepo.py#L29-L42
wtsi-hgi/python-git-subrepo
gitsubrepo/subrepo.py
clone
def clone(location: str, directory: str, *, branch: str=None, tag: str=None, commit: str=None, author_name: str=None, author_email: str=None) -> Commit: """ Clones the repository at the given location as a subrepo in the given directory. :param location: the location of the repository to clone :param directory: the directory that the subrepo will occupy (i.e. not the git repository root) :param branch: the specific branch to clone :param tag: the specific tag to clone :param commit: the specific commit to clone (may also require tag/branch to be specified if not fetched) :param author_name: the name of the author to assign to the clone commit (uses system specified if not set) :param author_email: the email of the author to assign to the clone commit (uses system specified if not set) :return: the commit reference of the checkout """ if os.path.exists(directory): raise ValueError(f"The directory \"{directory}\" already exists") if not os.path.isabs(directory): raise ValueError(f"Directory must be absolute: {directory}") if branch and tag: raise ValueError(f"Cannot specify both branch \"{branch}\" and tag \"{tag}\"") if not branch and not tag and not commit: branch = _DEFAULT_BRANCH existing_parent_directory = directory while not os.path.exists(existing_parent_directory): assert existing_parent_directory != "" existing_parent_directory = os.path.dirname(existing_parent_directory) git_root = get_git_root_directory(existing_parent_directory) git_relative_directory = os.path.relpath(os.path.realpath(directory), git_root) if (branch or tag) and commit: run([GIT_COMMAND, "fetch", location, branch if branch else tag], execution_directory=git_root) branch, tag = None, None reference = branch if branch else (tag if tag else commit) execution_environment = os.environ.copy() if author_name is not None: execution_environment[_GIT_AUTHOR_NAME_ENVIRONMENT_VARIABLE] = author_name if author_email is not None: execution_environment[_GIT_AUTHOR_EMAIL_ENVIRONMENT_VARIABLE] = author_email try: run([GIT_COMMAND, _GIT_SUBREPO_COMMAND, _GIT_SUBREPO_CLONE_COMMAND, _GIT_SUBREPO_VERBOSE_FLAG, _GIT_SUBREPO_BRANCH_FLAG, reference, location, git_relative_directory], execution_directory=git_root, execution_environment=execution_environment) except RunException as e: if re.search("Can't clone subrepo. (Unstaged|Index has) changes", e.stderr) is not None: raise UnstagedChangeException(git_root) from e elif "Command failed:" in e.stderr: try: repo_info = run([GIT_COMMAND, _GIT_LS_REMOTE_COMMAND, location]) if not branch and not tag and commit: raise NotAGitReferenceException( f"Commit \"{commit}\" not found (specify branch/tag to fetch that first if required)") else: references = re.findall("^.+\srefs\/.+\/(.+)", repo_info, flags=re.MULTILINE) if reference not in references: raise NotAGitReferenceException(f"{reference} not found in {references}") from e except RunException as debug_e: if re.match("fatal: repository .* not found", debug_e.stderr): raise NotAGitRepositoryException(location) from e raise e assert os.path.exists(directory) return status(directory)[2]
python
def clone(location: str, directory: str, *, branch: str=None, tag: str=None, commit: str=None, author_name: str=None, author_email: str=None) -> Commit: """ Clones the repository at the given location as a subrepo in the given directory. :param location: the location of the repository to clone :param directory: the directory that the subrepo will occupy (i.e. not the git repository root) :param branch: the specific branch to clone :param tag: the specific tag to clone :param commit: the specific commit to clone (may also require tag/branch to be specified if not fetched) :param author_name: the name of the author to assign to the clone commit (uses system specified if not set) :param author_email: the email of the author to assign to the clone commit (uses system specified if not set) :return: the commit reference of the checkout """ if os.path.exists(directory): raise ValueError(f"The directory \"{directory}\" already exists") if not os.path.isabs(directory): raise ValueError(f"Directory must be absolute: {directory}") if branch and tag: raise ValueError(f"Cannot specify both branch \"{branch}\" and tag \"{tag}\"") if not branch and not tag and not commit: branch = _DEFAULT_BRANCH existing_parent_directory = directory while not os.path.exists(existing_parent_directory): assert existing_parent_directory != "" existing_parent_directory = os.path.dirname(existing_parent_directory) git_root = get_git_root_directory(existing_parent_directory) git_relative_directory = os.path.relpath(os.path.realpath(directory), git_root) if (branch or tag) and commit: run([GIT_COMMAND, "fetch", location, branch if branch else tag], execution_directory=git_root) branch, tag = None, None reference = branch if branch else (tag if tag else commit) execution_environment = os.environ.copy() if author_name is not None: execution_environment[_GIT_AUTHOR_NAME_ENVIRONMENT_VARIABLE] = author_name if author_email is not None: execution_environment[_GIT_AUTHOR_EMAIL_ENVIRONMENT_VARIABLE] = author_email try: run([GIT_COMMAND, _GIT_SUBREPO_COMMAND, _GIT_SUBREPO_CLONE_COMMAND, _GIT_SUBREPO_VERBOSE_FLAG, _GIT_SUBREPO_BRANCH_FLAG, reference, location, git_relative_directory], execution_directory=git_root, execution_environment=execution_environment) except RunException as e: if re.search("Can't clone subrepo. (Unstaged|Index has) changes", e.stderr) is not None: raise UnstagedChangeException(git_root) from e elif "Command failed:" in e.stderr: try: repo_info = run([GIT_COMMAND, _GIT_LS_REMOTE_COMMAND, location]) if not branch and not tag and commit: raise NotAGitReferenceException( f"Commit \"{commit}\" not found (specify branch/tag to fetch that first if required)") else: references = re.findall("^.+\srefs\/.+\/(.+)", repo_info, flags=re.MULTILINE) if reference not in references: raise NotAGitReferenceException(f"{reference} not found in {references}") from e except RunException as debug_e: if re.match("fatal: repository .* not found", debug_e.stderr): raise NotAGitRepositoryException(location) from e raise e assert os.path.exists(directory) return status(directory)[2]
[ "def", "clone", "(", "location", ":", "str", ",", "directory", ":", "str", ",", "*", ",", "branch", ":", "str", "=", "None", ",", "tag", ":", "str", "=", "None", ",", "commit", ":", "str", "=", "None", ",", "author_name", ":", "str", "=", "None",...
Clones the repository at the given location as a subrepo in the given directory. :param location: the location of the repository to clone :param directory: the directory that the subrepo will occupy (i.e. not the git repository root) :param branch: the specific branch to clone :param tag: the specific tag to clone :param commit: the specific commit to clone (may also require tag/branch to be specified if not fetched) :param author_name: the name of the author to assign to the clone commit (uses system specified if not set) :param author_email: the email of the author to assign to the clone commit (uses system specified if not set) :return: the commit reference of the checkout
[ "Clones", "the", "repository", "at", "the", "given", "location", "as", "a", "subrepo", "in", "the", "given", "directory", ".", ":", "param", "location", ":", "the", "location", "of", "the", "repository", "to", "clone", ":", "param", "directory", ":", "the"...
train
https://github.com/wtsi-hgi/python-git-subrepo/blob/bb2eb2bd9a7e51b862298ddb4168cc5b8633dad0/gitsubrepo/subrepo.py#L46-L111
wtsi-hgi/python-git-subrepo
gitsubrepo/subrepo.py
status
def status(directory: str) -> Tuple[RepositoryLocation, Branch, Commit]: """ Gets the status of the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: a tuple consisting of the URL the subrepo is tracking, the branch that has been checked out and the commit reference """ if not os.path.exists(directory): raise ValueError(f"No subrepo found in \"{directory}\"") try: result = run([GIT_COMMAND, _GIT_SUBREPO_COMMAND, _GIT_SUBREPO_STATUS_COMMAND, _GIT_SUBREPO_VERBOSE_FLAG, get_directory_relative_to_git_root(directory)], execution_directory=get_git_root_directory(directory)) except RunException as e: if "Command failed: 'git rev-parse --verify HEAD'" in e.stderr: raise NotAGitSubrepoException(directory) from e raise e if re.search("is not a subrepo$", result): raise NotAGitSubrepoException(directory) url = re.search("Remote URL:\s*(.*)", result).group(1) branch = re.search("Tracking Branch:\s*(.*)", result).group(1) commit = re.search("Pulled Commit:\s*(.*)", result).group(1) return url, branch, commit
python
def status(directory: str) -> Tuple[RepositoryLocation, Branch, Commit]: """ Gets the status of the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: a tuple consisting of the URL the subrepo is tracking, the branch that has been checked out and the commit reference """ if not os.path.exists(directory): raise ValueError(f"No subrepo found in \"{directory}\"") try: result = run([GIT_COMMAND, _GIT_SUBREPO_COMMAND, _GIT_SUBREPO_STATUS_COMMAND, _GIT_SUBREPO_VERBOSE_FLAG, get_directory_relative_to_git_root(directory)], execution_directory=get_git_root_directory(directory)) except RunException as e: if "Command failed: 'git rev-parse --verify HEAD'" in e.stderr: raise NotAGitSubrepoException(directory) from e raise e if re.search("is not a subrepo$", result): raise NotAGitSubrepoException(directory) url = re.search("Remote URL:\s*(.*)", result).group(1) branch = re.search("Tracking Branch:\s*(.*)", result).group(1) commit = re.search("Pulled Commit:\s*(.*)", result).group(1) return url, branch, commit
[ "def", "status", "(", "directory", ":", "str", ")", "->", "Tuple", "[", "RepositoryLocation", ",", "Branch", ",", "Commit", "]", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "raise", "ValueError", "(", "f\"No subrepo fo...
Gets the status of the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: a tuple consisting of the URL the subrepo is tracking, the branch that has been checked out and the commit reference
[ "Gets", "the", "status", "of", "the", "subrepo", "that", "has", "been", "cloned", "into", "the", "given", "directory", ".", ":", "param", "directory", ":", "the", "directory", "containing", "the", "subrepo", ":", "return", ":", "a", "tuple", "consisting", ...
train
https://github.com/wtsi-hgi/python-git-subrepo/blob/bb2eb2bd9a7e51b862298ddb4168cc5b8633dad0/gitsubrepo/subrepo.py#L115-L140
wtsi-hgi/python-git-subrepo
gitsubrepo/subrepo.py
pull
def pull(directory: str) -> Commit: """ Pulls the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: the commit the subrepo is on """ if not os.path.exists(directory): raise ValueError(f"No subrepo found in \"{directory}\"") try: result = run([GIT_COMMAND, _GIT_SUBREPO_COMMAND, _GIT_SUBREPO_PULL_COMMAND, _GIT_SUBREPO_VERBOSE_FLAG, get_directory_relative_to_git_root(directory)], execution_directory=get_git_root_directory(directory)) except RunException as e: if "Can't pull subrepo. Working tree has changes" in e.stderr: raise UnstagedChangeException() from e return status(directory)[2]
python
def pull(directory: str) -> Commit: """ Pulls the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: the commit the subrepo is on """ if not os.path.exists(directory): raise ValueError(f"No subrepo found in \"{directory}\"") try: result = run([GIT_COMMAND, _GIT_SUBREPO_COMMAND, _GIT_SUBREPO_PULL_COMMAND, _GIT_SUBREPO_VERBOSE_FLAG, get_directory_relative_to_git_root(directory)], execution_directory=get_git_root_directory(directory)) except RunException as e: if "Can't pull subrepo. Working tree has changes" in e.stderr: raise UnstagedChangeException() from e return status(directory)[2]
[ "def", "pull", "(", "directory", ":", "str", ")", "->", "Commit", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "raise", "ValueError", "(", "f\"No subrepo found in \\\"{directory}\\\"\"", ")", "try", ":", "result", "=", "r...
Pulls the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: the commit the subrepo is on
[ "Pulls", "the", "subrepo", "that", "has", "been", "cloned", "into", "the", "given", "directory", ".", ":", "param", "directory", ":", "the", "directory", "containing", "the", "subrepo", ":", "return", ":", "the", "commit", "the", "subrepo", "is", "on" ]
train
https://github.com/wtsi-hgi/python-git-subrepo/blob/bb2eb2bd9a7e51b862298ddb4168cc5b8633dad0/gitsubrepo/subrepo.py#L144-L159
CodyKochmann/strict_functions
strict_functions/cached2.py
cached
def cached(fn, size=32): ''' this decorator creates a type safe lru_cache around the decorated function. Unlike functools.lru_cache, this will not crash when unhashable arguments are passed to the function''' assert callable(fn) assert isinstance(size, int) return overload(fn)(lru_cache(size, typed=True)(fn))
python
def cached(fn, size=32): ''' this decorator creates a type safe lru_cache around the decorated function. Unlike functools.lru_cache, this will not crash when unhashable arguments are passed to the function''' assert callable(fn) assert isinstance(size, int) return overload(fn)(lru_cache(size, typed=True)(fn))
[ "def", "cached", "(", "fn", ",", "size", "=", "32", ")", ":", "assert", "callable", "(", "fn", ")", "assert", "isinstance", "(", "size", ",", "int", ")", "return", "overload", "(", "fn", ")", "(", "lru_cache", "(", "size", ",", "typed", "=", "True"...
this decorator creates a type safe lru_cache around the decorated function. Unlike functools.lru_cache, this will not crash when unhashable arguments are passed to the function
[ "this", "decorator", "creates", "a", "type", "safe", "lru_cache", "around", "the", "decorated", "function", ".", "Unlike", "functools", ".", "lru_cache", "this", "will", "not", "crash", "when", "unhashable", "arguments", "are", "passed", "to", "the", "function" ...
train
https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/cached2.py#L3-L10
jaraco/jaraco.translate
jaraco/translate/pmxbot.py
translate
def translate(client, event, channel, nick, rest): """ Translate a phrase using Google Translate. First argument should be the language[s]. It is a 2 letter abbreviation. It will auto detect the orig lang if you only give one; or two languages joined by a |, for example 'en|de' to trans from English to German. Follow this by the phrase you want to translate. """ try: set_key() except Exception: return ( "No API key configured. Google charges for translation. " "Please register for an API key at " "https://code.google.com/apis/console/?api=translate&promo=tr " "and set the 'Google API key' config variable to a valid key") rest = rest.strip() langpair, _, rest = rest.partition(' ') source_lang, _, target_lang = langpair.rpartition('|') try: return google.translate(rest.encode('utf-8'), target_lang, source_lang) except Exception: log.exception("Error occurred in translate") tmpl = ( "An error occurred. " "Are you sure {langpair} is a valid language?") return tmpl.format(**vars())
python
def translate(client, event, channel, nick, rest): """ Translate a phrase using Google Translate. First argument should be the language[s]. It is a 2 letter abbreviation. It will auto detect the orig lang if you only give one; or two languages joined by a |, for example 'en|de' to trans from English to German. Follow this by the phrase you want to translate. """ try: set_key() except Exception: return ( "No API key configured. Google charges for translation. " "Please register for an API key at " "https://code.google.com/apis/console/?api=translate&promo=tr " "and set the 'Google API key' config variable to a valid key") rest = rest.strip() langpair, _, rest = rest.partition(' ') source_lang, _, target_lang = langpair.rpartition('|') try: return google.translate(rest.encode('utf-8'), target_lang, source_lang) except Exception: log.exception("Error occurred in translate") tmpl = ( "An error occurred. " "Are you sure {langpair} is a valid language?") return tmpl.format(**vars())
[ "def", "translate", "(", "client", ",", "event", ",", "channel", ",", "nick", ",", "rest", ")", ":", "try", ":", "set_key", "(", ")", "except", "Exception", ":", "return", "(", "\"No API key configured. Google charges for translation. \"", "\"Please register for an ...
Translate a phrase using Google Translate. First argument should be the language[s]. It is a 2 letter abbreviation. It will auto detect the orig lang if you only give one; or two languages joined by a |, for example 'en|de' to trans from English to German. Follow this by the phrase you want to translate.
[ "Translate", "a", "phrase", "using", "Google", "Translate", ".", "First", "argument", "should", "be", "the", "language", "[", "s", "]", ".", "It", "is", "a", "2", "letter", "abbreviation", ".", "It", "will", "auto", "detect", "the", "orig", "lang", "if",...
train
https://github.com/jaraco/jaraco.translate/blob/21a83d6378bec84c308d0c950f073fced01d36e7/jaraco/translate/pmxbot.py#L20-L46
colecrtr/django-naguine
naguine/apps/models.py
get_model
def get_model(app_dot_model): """ Returns Django model class corresponding to passed-in `app_dot_model` string. This is helpful for preventing circular-import errors in a Django project. Positional Arguments: ===================== - `app_dot_model`: Django's `<app_name>.<model_name>` syntax. For example, the default Django User model would be `auth.User`, where `auth` is the app and `User` is the model. """ try: app, model = app_dot_model.split('.') except ValueError: msg = (f'Passed in value \'{app_dot_model}\' was not in the format ' '`<app_name>.<model_name>`.') raise ValueError(msg) return apps.get_app_config(app).get_model(model)
python
def get_model(app_dot_model): """ Returns Django model class corresponding to passed-in `app_dot_model` string. This is helpful for preventing circular-import errors in a Django project. Positional Arguments: ===================== - `app_dot_model`: Django's `<app_name>.<model_name>` syntax. For example, the default Django User model would be `auth.User`, where `auth` is the app and `User` is the model. """ try: app, model = app_dot_model.split('.') except ValueError: msg = (f'Passed in value \'{app_dot_model}\' was not in the format ' '`<app_name>.<model_name>`.') raise ValueError(msg) return apps.get_app_config(app).get_model(model)
[ "def", "get_model", "(", "app_dot_model", ")", ":", "try", ":", "app", ",", "model", "=", "app_dot_model", ".", "split", "(", "'.'", ")", "except", "ValueError", ":", "msg", "=", "(", "f'Passed in value \\'{app_dot_model}\\' was not in the format '", "'`<app_name>.<...
Returns Django model class corresponding to passed-in `app_dot_model` string. This is helpful for preventing circular-import errors in a Django project. Positional Arguments: ===================== - `app_dot_model`: Django's `<app_name>.<model_name>` syntax. For example, the default Django User model would be `auth.User`, where `auth` is the app and `User` is the model.
[ "Returns", "Django", "model", "class", "corresponding", "to", "passed", "-", "in", "app_dot_model", "string", ".", "This", "is", "helpful", "for", "preventing", "circular", "-", "import", "errors", "in", "a", "Django", "project", "." ]
train
https://github.com/colecrtr/django-naguine/blob/984da05dec15a4139788831e7fc060c2b7cb7fd3/naguine/apps/models.py#L6-L26
harlowja/failure
failure/finders.py
match_modules
def match_modules(allowed_modules): """Creates a matcher that matches a list/set/tuple of allowed modules.""" cleaned_allowed_modules = [ utils.mod_to_mod_name(tmp_mod) for tmp_mod in allowed_modules ] cleaned_split_allowed_modules = [ tmp_mod.split(".") for tmp_mod in cleaned_allowed_modules ] cleaned_allowed_modules = [] del cleaned_allowed_modules def matcher(cause): cause_cls = None cause_type_name = cause.exception_type_names[0] # Rip off the class name (usually at the end). cause_type_name_pieces = cause_type_name.split(".") cause_type_name_mod_pieces = cause_type_name_pieces[0:-1] # Do any modules provided match the provided causes module? mod_match = any( utils.array_prefix_matches(mod_pieces, cause_type_name_mod_pieces) for mod_pieces in cleaned_split_allowed_modules) if mod_match: cause_cls = importutils.import_class(cause_type_name) cause_cls = ensure_base_exception(cause_type_name, cause_cls) return cause_cls return matcher
python
def match_modules(allowed_modules): """Creates a matcher that matches a list/set/tuple of allowed modules.""" cleaned_allowed_modules = [ utils.mod_to_mod_name(tmp_mod) for tmp_mod in allowed_modules ] cleaned_split_allowed_modules = [ tmp_mod.split(".") for tmp_mod in cleaned_allowed_modules ] cleaned_allowed_modules = [] del cleaned_allowed_modules def matcher(cause): cause_cls = None cause_type_name = cause.exception_type_names[0] # Rip off the class name (usually at the end). cause_type_name_pieces = cause_type_name.split(".") cause_type_name_mod_pieces = cause_type_name_pieces[0:-1] # Do any modules provided match the provided causes module? mod_match = any( utils.array_prefix_matches(mod_pieces, cause_type_name_mod_pieces) for mod_pieces in cleaned_split_allowed_modules) if mod_match: cause_cls = importutils.import_class(cause_type_name) cause_cls = ensure_base_exception(cause_type_name, cause_cls) return cause_cls return matcher
[ "def", "match_modules", "(", "allowed_modules", ")", ":", "cleaned_allowed_modules", "=", "[", "utils", ".", "mod_to_mod_name", "(", "tmp_mod", ")", "for", "tmp_mod", "in", "allowed_modules", "]", "cleaned_split_allowed_modules", "=", "[", "tmp_mod", ".", "split", ...
Creates a matcher that matches a list/set/tuple of allowed modules.
[ "Creates", "a", "matcher", "that", "matches", "a", "list", "/", "set", "/", "tuple", "of", "allowed", "modules", "." ]
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/finders.py#L44-L73
harlowja/failure
failure/finders.py
match_classes
def match_classes(allowed_classes): """Creates a matcher that matches a list/tuple of allowed classes.""" cleaned_allowed_classes = [ utils.cls_to_cls_name(tmp_cls) for tmp_cls in allowed_classes ] def matcher(cause): cause_cls = None cause_type_name = cause.exception_type_names[0] try: cause_cls_idx = cleaned_allowed_classes.index(cause_type_name) except ValueError: pass else: cause_cls = allowed_classes[cause_cls_idx] if not isinstance(cause_cls, type): cause_cls = importutils.import_class(cause_cls) cause_cls = ensure_base_exception(cause_type_name, cause_cls) return cause_cls return matcher
python
def match_classes(allowed_classes): """Creates a matcher that matches a list/tuple of allowed classes.""" cleaned_allowed_classes = [ utils.cls_to_cls_name(tmp_cls) for tmp_cls in allowed_classes ] def matcher(cause): cause_cls = None cause_type_name = cause.exception_type_names[0] try: cause_cls_idx = cleaned_allowed_classes.index(cause_type_name) except ValueError: pass else: cause_cls = allowed_classes[cause_cls_idx] if not isinstance(cause_cls, type): cause_cls = importutils.import_class(cause_cls) cause_cls = ensure_base_exception(cause_type_name, cause_cls) return cause_cls return matcher
[ "def", "match_classes", "(", "allowed_classes", ")", ":", "cleaned_allowed_classes", "=", "[", "utils", ".", "cls_to_cls_name", "(", "tmp_cls", ")", "for", "tmp_cls", "in", "allowed_classes", "]", "def", "matcher", "(", "cause", ")", ":", "cause_cls", "=", "No...
Creates a matcher that matches a list/tuple of allowed classes.
[ "Creates", "a", "matcher", "that", "matches", "a", "list", "/", "tuple", "of", "allowed", "classes", "." ]
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/finders.py#L76-L97
harlowja/failure
failure/finders.py
combine_or
def combine_or(matcher, *more_matchers): """Combines more than one matcher together (first that matches wins).""" def matcher(cause): for sub_matcher in itertools.chain([matcher], more_matchers): cause_cls = sub_matcher(cause) if cause_cls is not None: return cause_cls return None return matcher
python
def combine_or(matcher, *more_matchers): """Combines more than one matcher together (first that matches wins).""" def matcher(cause): for sub_matcher in itertools.chain([matcher], more_matchers): cause_cls = sub_matcher(cause) if cause_cls is not None: return cause_cls return None return matcher
[ "def", "combine_or", "(", "matcher", ",", "*", "more_matchers", ")", ":", "def", "matcher", "(", "cause", ")", ":", "for", "sub_matcher", "in", "itertools", ".", "chain", "(", "[", "matcher", "]", ",", "more_matchers", ")", ":", "cause_cls", "=", "sub_ma...
Combines more than one matcher together (first that matches wins).
[ "Combines", "more", "than", "one", "matcher", "together", "(", "first", "that", "matches", "wins", ")", "." ]
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/finders.py#L100-L110
ttm/socialLegacy
social/collections.py
DatafileCollections.getTWFiles
def getTWFiles(self): """Get data files with Twitter messages (tweets). Each item is a list of pickle files on the ../data/tw/ directory (probably with some hashtag or common theme). Use social.tw.search and social.tw.stream to get tweets. Tweets are excluded from package to ease sharing.""" ddir="../data/tw/" # get files in dir # order by size, if size # group them so that the total filesize is smaller then 1GB-1.4GB files=os.path.listdir(ddir) files=[i for i in files if os.path.getsize(i)] files.sort(key=lambda i: os.path.getsize(i)) filegroups=self.groupTwitterFilesByEquivalents(files) filegroups_grouped=self.groupTwitterFileGroupsForPublishing(filegroups) return filegroups_grouped
python
def getTWFiles(self): """Get data files with Twitter messages (tweets). Each item is a list of pickle files on the ../data/tw/ directory (probably with some hashtag or common theme). Use social.tw.search and social.tw.stream to get tweets. Tweets are excluded from package to ease sharing.""" ddir="../data/tw/" # get files in dir # order by size, if size # group them so that the total filesize is smaller then 1GB-1.4GB files=os.path.listdir(ddir) files=[i for i in files if os.path.getsize(i)] files.sort(key=lambda i: os.path.getsize(i)) filegroups=self.groupTwitterFilesByEquivalents(files) filegroups_grouped=self.groupTwitterFileGroupsForPublishing(filegroups) return filegroups_grouped
[ "def", "getTWFiles", "(", "self", ")", ":", "ddir", "=", "\"../data/tw/\"", "# get files in dir", "# order by size, if size", "# group them so that the total filesize is smaller then 1GB-1.4GB", "files", "=", "os", ".", "path", ".", "listdir", "(", "ddir", ")", "files", ...
Get data files with Twitter messages (tweets). Each item is a list of pickle files on the ../data/tw/ directory (probably with some hashtag or common theme). Use social.tw.search and social.tw.stream to get tweets. Tweets are excluded from package to ease sharing.
[ "Get", "data", "files", "with", "Twitter", "messages", "(", "tweets", ")", ".", "Each", "item", "is", "a", "list", "of", "pickle", "files", "on", "the", "..", "/", "data", "/", "tw", "/", "directory", "(", "probably", "with", "some", "hashtag", "or", ...
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/collections.py#L97-L114
aerogear/digger-build-cli
digger/helpers/common.py
run_cmd
def run_cmd(cmd, log='log.log', cwd='.', stdout=sys.stdout, bufsize=1, encode='utf-8'): """ Runs a command in the backround by creating a new process and writes the output to a specified log file. :param log(str) - log filename to be used :param cwd(str) - basedir to write/create the log file :param stdout(pipe) - stdout process pipe (can be default stdout, a file, etc) :param bufsize(int) - set the output buffering, default is 1 (per line) :param encode(str) - string encoding to decode the logged content, default is utf-8 Returns: The process object """ logfile = '%s/%s' % (cwd, log) if os.path.exists(logfile): os.remove(logfile) proc_args = { 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, 'cwd': cwd, 'universal_newlines': True } proc = subprocess.Popen(cmd, **proc_args) while True: line = proc.stdout.readline() if proc.poll() is None: stdout.write(line) else: break out, err = proc.communicate() with open(logfile, 'w') as f: if out: f.write(out) else: f.write(err)
python
def run_cmd(cmd, log='log.log', cwd='.', stdout=sys.stdout, bufsize=1, encode='utf-8'): """ Runs a command in the backround by creating a new process and writes the output to a specified log file. :param log(str) - log filename to be used :param cwd(str) - basedir to write/create the log file :param stdout(pipe) - stdout process pipe (can be default stdout, a file, etc) :param bufsize(int) - set the output buffering, default is 1 (per line) :param encode(str) - string encoding to decode the logged content, default is utf-8 Returns: The process object """ logfile = '%s/%s' % (cwd, log) if os.path.exists(logfile): os.remove(logfile) proc_args = { 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, 'cwd': cwd, 'universal_newlines': True } proc = subprocess.Popen(cmd, **proc_args) while True: line = proc.stdout.readline() if proc.poll() is None: stdout.write(line) else: break out, err = proc.communicate() with open(logfile, 'w') as f: if out: f.write(out) else: f.write(err)
[ "def", "run_cmd", "(", "cmd", ",", "log", "=", "'log.log'", ",", "cwd", "=", "'.'", ",", "stdout", "=", "sys", ".", "stdout", ",", "bufsize", "=", "1", ",", "encode", "=", "'utf-8'", ")", ":", "logfile", "=", "'%s/%s'", "%", "(", "cwd", ",", "log...
Runs a command in the backround by creating a new process and writes the output to a specified log file. :param log(str) - log filename to be used :param cwd(str) - basedir to write/create the log file :param stdout(pipe) - stdout process pipe (can be default stdout, a file, etc) :param bufsize(int) - set the output buffering, default is 1 (per line) :param encode(str) - string encoding to decode the logged content, default is utf-8 Returns: The process object
[ "Runs", "a", "command", "in", "the", "backround", "by", "creating", "a", "new", "process", "and", "writes", "the", "output", "to", "a", "specified", "log", "file", "." ]
train
https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/helpers/common.py#L10-L48
aerogear/digger-build-cli
digger/helpers/common.py
touch_log
def touch_log(log, cwd='.'): """ Touches the log file. Creates if not exists OR updates the modification date if exists. :param log: :return: nothing """ logfile = '%s/%s' % (cwd, log) with open(logfile, 'a'): os.utime(logfile, None)
python
def touch_log(log, cwd='.'): """ Touches the log file. Creates if not exists OR updates the modification date if exists. :param log: :return: nothing """ logfile = '%s/%s' % (cwd, log) with open(logfile, 'a'): os.utime(logfile, None)
[ "def", "touch_log", "(", "log", ",", "cwd", "=", "'.'", ")", ":", "logfile", "=", "'%s/%s'", "%", "(", "cwd", ",", "log", ")", "with", "open", "(", "logfile", ",", "'a'", ")", ":", "os", ".", "utime", "(", "logfile", ",", "None", ")" ]
Touches the log file. Creates if not exists OR updates the modification date if exists. :param log: :return: nothing
[ "Touches", "the", "log", "file", ".", "Creates", "if", "not", "exists", "OR", "updates", "the", "modification", "date", "if", "exists", ".", ":", "param", "log", ":", ":", "return", ":", "nothing" ]
train
https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/helpers/common.py#L59-L67
dependencies-io/cli
dependencies_cli/cli.py
create
def create(output_dir): """Create a new collector or actor""" template_path = os.path.join(os.path.dirname(__file__), 'project_template') click.secho('Let\'s create a new component!', fg='green') name = click.prompt('What is the name of this component (ex. python-pip)?') click.secho('') click.secho('We assume this will be pushed to GitHub and Docker Hub eventually, but these don\'t have to exist yet.', fg='green') repo_owner = click.prompt('GitHub repo owner (i.e. your username or organization name)') repo_name = click.prompt('GitHub repo name', default=name) dockerhub_owner = click.prompt('Docker Hub repo owner', default=repo_owner) dockerhub_name = click.prompt('Docker Hub repo name', default=repo_name) license_owner = click.prompt('Who should be the copyright owner on project?', default=repo_owner) extra_context = { 'name': name, 'name_shields_io': name.replace('-', '--'), 'current_year': datetime.datetime.now().year, 'dependencies_cli_version': __version__, 'repo_owner': repo_owner, 'repo_name': repo_name, 'dockerhub_owner': dockerhub_owner, 'dockerhub_name': dockerhub_name, 'license_owner': license_owner, } project_dir = cookiecutter(template_path, no_input=True, extra_context=extra_context, output_dir=output_dir) click.secho('') click.secho('{name} is ready to go, `cd {project_dir}` and try running `dependencies test`!'.format(name=name, project_dir=project_dir), fg='green') click.secho( 'We started you out with a fully functioning component based in python.\n' + 'Once you\'ve got a handle on how it works then you can change it to whatever language you want.' )
python
def create(output_dir): """Create a new collector or actor""" template_path = os.path.join(os.path.dirname(__file__), 'project_template') click.secho('Let\'s create a new component!', fg='green') name = click.prompt('What is the name of this component (ex. python-pip)?') click.secho('') click.secho('We assume this will be pushed to GitHub and Docker Hub eventually, but these don\'t have to exist yet.', fg='green') repo_owner = click.prompt('GitHub repo owner (i.e. your username or organization name)') repo_name = click.prompt('GitHub repo name', default=name) dockerhub_owner = click.prompt('Docker Hub repo owner', default=repo_owner) dockerhub_name = click.prompt('Docker Hub repo name', default=repo_name) license_owner = click.prompt('Who should be the copyright owner on project?', default=repo_owner) extra_context = { 'name': name, 'name_shields_io': name.replace('-', '--'), 'current_year': datetime.datetime.now().year, 'dependencies_cli_version': __version__, 'repo_owner': repo_owner, 'repo_name': repo_name, 'dockerhub_owner': dockerhub_owner, 'dockerhub_name': dockerhub_name, 'license_owner': license_owner, } project_dir = cookiecutter(template_path, no_input=True, extra_context=extra_context, output_dir=output_dir) click.secho('') click.secho('{name} is ready to go, `cd {project_dir}` and try running `dependencies test`!'.format(name=name, project_dir=project_dir), fg='green') click.secho( 'We started you out with a fully functioning component based in python.\n' + 'Once you\'ve got a handle on how it works then you can change it to whatever language you want.' )
[ "def", "create", "(", "output_dir", ")", ":", "template_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'project_template'", ")", "click", ".", "secho", "(", "'Let\\'s create a new component!'",...
Create a new collector or actor
[ "Create", "a", "new", "collector", "or", "actor" ]
train
https://github.com/dependencies-io/cli/blob/d8ae97343c48a61d6614d3e8af6a981b4cfb1bcb/dependencies_cli/cli.py#L22-L56
dependencies-io/cli
dependencies_cli/cli.py
validate
def validate(text, file, schema_type): """Validate JSON input using dependencies-schema""" content = None if text: print('Validating text input...') content = text if file: print('Validating file input...') content = file.read() if content is None: click.secho('Please give either text input or a file path. See help for more details.', fg='red') exit(1) try: if schema_type == 'dependencies': validator = DependenciesSchemaValidator() elif schema_type == 'actions': validator = ActionsSchemaValidator() else: raise Exception('Unknown type') validator.validate_json(content) click.secho('Valid JSON schema!', fg='green') except Exception as e: click.secho('Invalid JSON schema!', fg='red') raise e
python
def validate(text, file, schema_type): """Validate JSON input using dependencies-schema""" content = None if text: print('Validating text input...') content = text if file: print('Validating file input...') content = file.read() if content is None: click.secho('Please give either text input or a file path. See help for more details.', fg='red') exit(1) try: if schema_type == 'dependencies': validator = DependenciesSchemaValidator() elif schema_type == 'actions': validator = ActionsSchemaValidator() else: raise Exception('Unknown type') validator.validate_json(content) click.secho('Valid JSON schema!', fg='green') except Exception as e: click.secho('Invalid JSON schema!', fg='red') raise e
[ "def", "validate", "(", "text", ",", "file", ",", "schema_type", ")", ":", "content", "=", "None", "if", "text", ":", "print", "(", "'Validating text input...'", ")", "content", "=", "text", "if", "file", ":", "print", "(", "'Validating file input...'", ")",...
Validate JSON input using dependencies-schema
[ "Validate", "JSON", "input", "using", "dependencies", "-", "schema" ]
train
https://github.com/dependencies-io/cli/blob/d8ae97343c48a61d6614d3e8af6a981b4cfb1bcb/dependencies_cli/cli.py#L122-L150
Synerty/peek-plugin-base
peek_plugin_base/storage/AlembicEnvBase.py
AlembicEnvBase.run
def run(self): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = engine_from_config( self._config.get_section(self._config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool) with connectable.connect() as connection: ensureSchemaExists(connectable, self._schemaName) context.configure( connection=connection, target_metadata=self._targetMetadata, include_object=self._includeObjectFilter, include_schemas=True, version_table_schema=self._schemaName ) with context.begin_transaction(): context.run_migrations()
python
def run(self): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = engine_from_config( self._config.get_section(self._config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool) with connectable.connect() as connection: ensureSchemaExists(connectable, self._schemaName) context.configure( connection=connection, target_metadata=self._targetMetadata, include_object=self._includeObjectFilter, include_schemas=True, version_table_schema=self._schemaName ) with context.begin_transaction(): context.run_migrations()
[ "def", "run", "(", "self", ")", ":", "connectable", "=", "engine_from_config", "(", "self", ".", "_config", ".", "get_section", "(", "self", ".", "_config", ".", "config_ini_section", ")", ",", "prefix", "=", "'sqlalchemy.'", ",", "poolclass", "=", "pool", ...
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
[ "Run", "migrations", "in", "online", "mode", ".", "In", "this", "scenario", "we", "need", "to", "create", "an", "Engine", "and", "associate", "a", "connection", "with", "the", "context", "." ]
train
https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/AlembicEnvBase.py#L42-L66
etcher-be/epab
epab/cmd/_release.py
_clean
def _clean(): """ Cleans up build dir """ LOGGER.info('Cleaning project directory...') folders_to_cleanup = [ '.eggs', 'build', f'{config.PACKAGE_NAME()}.egg-info', ] for folder in folders_to_cleanup: if os.path.exists(folder): LOGGER.info('\tremoving: %s', folder) shutil.rmtree(folder)
python
def _clean(): """ Cleans up build dir """ LOGGER.info('Cleaning project directory...') folders_to_cleanup = [ '.eggs', 'build', f'{config.PACKAGE_NAME()}.egg-info', ] for folder in folders_to_cleanup: if os.path.exists(folder): LOGGER.info('\tremoving: %s', folder) shutil.rmtree(folder)
[ "def", "_clean", "(", ")", ":", "LOGGER", ".", "info", "(", "'Cleaning project directory...'", ")", "folders_to_cleanup", "=", "[", "'.eggs'", ",", "'build'", ",", "f'{config.PACKAGE_NAME()}.egg-info'", ",", "]", "for", "folder", "in", "folders_to_cleanup", ":", "...
Cleans up build dir
[ "Cleans", "up", "build", "dir" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/cmd/_release.py#L23-L36
mozilla/socorrolib
socorrolib/app/for_application_defaults.py
ApplicationDefaultsProxy.str_to_application_class
def str_to_application_class(self, an_app_key): """a configman compatible str_to_* converter""" try: app_class = str_to_python_object(self.apps[an_app_key]) except KeyError: app_class = str_to_python_object(an_app_key) try: self.application_defaults = DotDict( app_class.get_application_defaults() ) except AttributeError: # no get_application_defaults, skip this step pass return app_class
python
def str_to_application_class(self, an_app_key): """a configman compatible str_to_* converter""" try: app_class = str_to_python_object(self.apps[an_app_key]) except KeyError: app_class = str_to_python_object(an_app_key) try: self.application_defaults = DotDict( app_class.get_application_defaults() ) except AttributeError: # no get_application_defaults, skip this step pass return app_class
[ "def", "str_to_application_class", "(", "self", ",", "an_app_key", ")", ":", "try", ":", "app_class", "=", "str_to_python_object", "(", "self", ".", "apps", "[", "an_app_key", "]", ")", "except", "KeyError", ":", "app_class", "=", "str_to_python_object", "(", ...
a configman compatible str_to_* converter
[ "a", "configman", "compatible", "str_to_", "*", "converter" ]
train
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/app/for_application_defaults.py#L26-L39
funkybob/knights-templater
knights/lexer.py
tokenise
def tokenise(template): '''A generator which yields Token instances''' upto = 0 lineno = 0 for m in tag_re.finditer(template): start, end = m.span() lineno = template.count('\n', 0, start) + 1 # Humans count from 1 # If there's a gap between our start and the end of the last match, # there's a Text node between. if upto < start: yield Token(TokenType.text, template[upto:start], lineno) upto = end mode = m.lastgroup content = m.group(mode) yield Token(TokenType[mode], content, lineno) # if the last match ended before the end of the source, we have a tail Text # node. if upto < len(template): yield Token(TokenType.text, template[upto:], lineno)
python
def tokenise(template): '''A generator which yields Token instances''' upto = 0 lineno = 0 for m in tag_re.finditer(template): start, end = m.span() lineno = template.count('\n', 0, start) + 1 # Humans count from 1 # If there's a gap between our start and the end of the last match, # there's a Text node between. if upto < start: yield Token(TokenType.text, template[upto:start], lineno) upto = end mode = m.lastgroup content = m.group(mode) yield Token(TokenType[mode], content, lineno) # if the last match ended before the end of the source, we have a tail Text # node. if upto < len(template): yield Token(TokenType.text, template[upto:], lineno)
[ "def", "tokenise", "(", "template", ")", ":", "upto", "=", "0", "lineno", "=", "0", "for", "m", "in", "tag_re", ".", "finditer", "(", "template", ")", ":", "start", ",", "end", "=", "m", ".", "span", "(", ")", "lineno", "=", "template", ".", "cou...
A generator which yields Token instances
[ "A", "generator", "which", "yields", "Token", "instances" ]
train
https://github.com/funkybob/knights-templater/blob/b15cdbaae7d824d02f7f03ca04599ae94bb759dd/knights/lexer.py#L29-L51
NerdWalletOSS/savage
src/savage/api/data.py
delete
def delete(table, session, conds): """Performs a hard delete on a row, which means the row is deleted from the Savage table as well as the archive table. :param table: the model class which inherits from :class:`~savage.models.user_table.SavageModelMixin` and specifies the model of the user table from which we are querying :param session: a sqlalchemy session with connections to the database :param conds: a list of dictionary of key value pairs where keys are columns in the table and values are values the column should take on. If specified, this query will only return rows where the columns meet all the conditions. The columns specified in this dictionary must be exactly the unique columns that versioning pivots around. """ with session.begin_nested(): archive_conds_list = _get_conditions_list(table, conds) session.execute( sa.delete(table.ArchiveTable, whereclause=_get_conditions(archive_conds_list)) ) conds_list = _get_conditions_list(table, conds, archive=False) session.execute( sa.delete(table, whereclause=_get_conditions(conds_list)) )
python
def delete(table, session, conds): """Performs a hard delete on a row, which means the row is deleted from the Savage table as well as the archive table. :param table: the model class which inherits from :class:`~savage.models.user_table.SavageModelMixin` and specifies the model of the user table from which we are querying :param session: a sqlalchemy session with connections to the database :param conds: a list of dictionary of key value pairs where keys are columns in the table and values are values the column should take on. If specified, this query will only return rows where the columns meet all the conditions. The columns specified in this dictionary must be exactly the unique columns that versioning pivots around. """ with session.begin_nested(): archive_conds_list = _get_conditions_list(table, conds) session.execute( sa.delete(table.ArchiveTable, whereclause=_get_conditions(archive_conds_list)) ) conds_list = _get_conditions_list(table, conds, archive=False) session.execute( sa.delete(table, whereclause=_get_conditions(conds_list)) )
[ "def", "delete", "(", "table", ",", "session", ",", "conds", ")", ":", "with", "session", ".", "begin_nested", "(", ")", ":", "archive_conds_list", "=", "_get_conditions_list", "(", "table", ",", "conds", ")", "session", ".", "execute", "(", "sa", ".", "...
Performs a hard delete on a row, which means the row is deleted from the Savage table as well as the archive table. :param table: the model class which inherits from :class:`~savage.models.user_table.SavageModelMixin` and specifies the model of the user table from which we are querying :param session: a sqlalchemy session with connections to the database :param conds: a list of dictionary of key value pairs where keys are columns in the table and values are values the column should take on. If specified, this query will only return rows where the columns meet all the conditions. The columns specified in this dictionary must be exactly the unique columns that versioning pivots around.
[ "Performs", "a", "hard", "delete", "on", "a", "row", "which", "means", "the", "row", "is", "deleted", "from", "the", "Savage", "table", "as", "well", "as", "the", "archive", "table", "." ]
train
https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/api/data.py#L8-L29
NerdWalletOSS/savage
src/savage/api/data.py
get
def get( table, session, version_id=None, t1=None, t2=None, fields=None, conds=None, include_deleted=True, page=1, page_size=100, ): """ :param table: the model class which inherits from :class:`~savage.models.user_table.SavageModelMixin` and specifies the model of the user table from which we are querying :param session: a sqlalchemy session with connections to the database :param version_id: if specified, the value of t1 and t2 will be ignored. If specified, this will return all records after the specified version_id. :param t1: lower bound time for this query; if None or unspecified, defaults to the unix epoch. If this is specified and t2 is not, this query will simply return the time slice of data at t1. This must either be a valid sql time string or a datetime.datetime object. :param t2: upper bound time for this query; if both t1 and t2 are none or unspecified, this will return the latest data (i.e. time slice of data now). This must either be a valid sql time string or a datetime.datetime object. :param fields: a list of strings which corresponds to columns in the table; If None or unspecified, returns all fields in the table. :param conds: a list of dictionary of key value pairs where keys are columns in the table and values are values the column should take on. If specified, this query will only return rows where the columns meet all the conditions. The columns specified in this dictionary must be exactly the unique columns that versioning pivots around. :param include_deleted: if ``True``, the response will include deleted changes. Else it will only include changes where ``deleted = 0`` i.e. the data was in the user table. :param page: the offset of the result set (1-indexed); i.e. if page_size is 100 and page is 2, the result set will contain results 100 - 199 :param page_size: upper bound on number of results to display. Note the actual returned result set may be smaller than this due to the roll up. """ limit, offset = _get_limit_and_offset(page, page_size) version_col_names = table.version_columns if fields is None: fields = [name for name in utils.get_column_names(table) if name != 'version_id'] if version_id is not None: return _format_response(utils.result_to_dict(session.execute( sa.select([table.ArchiveTable]) .where(table.ArchiveTable.version_id > version_id) .order_by(*_get_order_clause(table.ArchiveTable)) .limit(page_size) .offset(offset) )), fields, version_col_names) if t1 is None and t2 is None: rows = _get_latest_time_slice(table, session, conds, include_deleted, limit, offset) return _format_response(rows, fields, version_col_names) if t2 is None: # return a historical time slice rows = _get_historical_time_slice( table, session, t1, conds, include_deleted, limit, offset ) return _format_response(rows, fields, version_col_names) if t1 is None: t1 = datetime.utcfromtimestamp(0) rows = _get_historical_changes( table, session, conds, t1, t2, include_deleted, limit, offset ) return _format_response(rows, fields, version_col_names)
python
def get( table, session, version_id=None, t1=None, t2=None, fields=None, conds=None, include_deleted=True, page=1, page_size=100, ): """ :param table: the model class which inherits from :class:`~savage.models.user_table.SavageModelMixin` and specifies the model of the user table from which we are querying :param session: a sqlalchemy session with connections to the database :param version_id: if specified, the value of t1 and t2 will be ignored. If specified, this will return all records after the specified version_id. :param t1: lower bound time for this query; if None or unspecified, defaults to the unix epoch. If this is specified and t2 is not, this query will simply return the time slice of data at t1. This must either be a valid sql time string or a datetime.datetime object. :param t2: upper bound time for this query; if both t1 and t2 are none or unspecified, this will return the latest data (i.e. time slice of data now). This must either be a valid sql time string or a datetime.datetime object. :param fields: a list of strings which corresponds to columns in the table; If None or unspecified, returns all fields in the table. :param conds: a list of dictionary of key value pairs where keys are columns in the table and values are values the column should take on. If specified, this query will only return rows where the columns meet all the conditions. The columns specified in this dictionary must be exactly the unique columns that versioning pivots around. :param include_deleted: if ``True``, the response will include deleted changes. Else it will only include changes where ``deleted = 0`` i.e. the data was in the user table. :param page: the offset of the result set (1-indexed); i.e. if page_size is 100 and page is 2, the result set will contain results 100 - 199 :param page_size: upper bound on number of results to display. Note the actual returned result set may be smaller than this due to the roll up. """ limit, offset = _get_limit_and_offset(page, page_size) version_col_names = table.version_columns if fields is None: fields = [name for name in utils.get_column_names(table) if name != 'version_id'] if version_id is not None: return _format_response(utils.result_to_dict(session.execute( sa.select([table.ArchiveTable]) .where(table.ArchiveTable.version_id > version_id) .order_by(*_get_order_clause(table.ArchiveTable)) .limit(page_size) .offset(offset) )), fields, version_col_names) if t1 is None and t2 is None: rows = _get_latest_time_slice(table, session, conds, include_deleted, limit, offset) return _format_response(rows, fields, version_col_names) if t2 is None: # return a historical time slice rows = _get_historical_time_slice( table, session, t1, conds, include_deleted, limit, offset ) return _format_response(rows, fields, version_col_names) if t1 is None: t1 = datetime.utcfromtimestamp(0) rows = _get_historical_changes( table, session, conds, t1, t2, include_deleted, limit, offset ) return _format_response(rows, fields, version_col_names)
[ "def", "get", "(", "table", ",", "session", ",", "version_id", "=", "None", ",", "t1", "=", "None", ",", "t2", "=", "None", ",", "fields", "=", "None", ",", "conds", "=", "None", ",", "include_deleted", "=", "True", ",", "page", "=", "1", ",", "p...
:param table: the model class which inherits from :class:`~savage.models.user_table.SavageModelMixin` and specifies the model of the user table from which we are querying :param session: a sqlalchemy session with connections to the database :param version_id: if specified, the value of t1 and t2 will be ignored. If specified, this will return all records after the specified version_id. :param t1: lower bound time for this query; if None or unspecified, defaults to the unix epoch. If this is specified and t2 is not, this query will simply return the time slice of data at t1. This must either be a valid sql time string or a datetime.datetime object. :param t2: upper bound time for this query; if both t1 and t2 are none or unspecified, this will return the latest data (i.e. time slice of data now). This must either be a valid sql time string or a datetime.datetime object. :param fields: a list of strings which corresponds to columns in the table; If None or unspecified, returns all fields in the table. :param conds: a list of dictionary of key value pairs where keys are columns in the table and values are values the column should take on. If specified, this query will only return rows where the columns meet all the conditions. The columns specified in this dictionary must be exactly the unique columns that versioning pivots around. :param include_deleted: if ``True``, the response will include deleted changes. Else it will only include changes where ``deleted = 0`` i.e. the data was in the user table. :param page: the offset of the result set (1-indexed); i.e. if page_size is 100 and page is 2, the result set will contain results 100 - 199 :param page_size: upper bound on number of results to display. Note the actual returned result set may be smaller than this due to the roll up.
[ ":", "param", "table", ":", "the", "model", "class", "which", "inherits", "from", ":", "class", ":", "~savage", ".", "models", ".", "user_table", ".", "SavageModelMixin", "and", "specifies", "the", "model", "of", "the", "user", "table", "from", "which", "w...
train
https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/api/data.py#L32-L101
NerdWalletOSS/savage
src/savage/api/data.py
_format_response
def _format_response(rows, fields, unique_col_names): """This function will look at the data column of rows and extract the specified fields. It will also dedup changes where the specified fields have not changed. The list of rows should be ordered by the compound primary key which versioning pivots around and be in ascending version order. This function will return a list of dictionaries where each dictionary has the following schema: { 'updated_at': timestamp of the change, 'version': version number for the change, 'data': a nested dictionary containing all keys specified in fields and values corresponding to values in the user table. } Note that some versions may be omitted in the output for the same key if the specified fields were not changed between versions. :param rows: a list of dictionaries representing rows from the ArchiveTable. :param fields: a list of strings of fields to be extracted from the archived row. """ output = [] old_id = None for row in rows: id_ = {k: row[k] for k in unique_col_names} formatted = {k: row[k] for k in row if k != 'data'} if id_ != old_id: # new unique versioned row data = row['data'] formatted['data'] = {k: data.get(k) for k in fields} output.append(formatted) else: data = row['data'] pruned_data = {k: data.get(k) for k in fields} if ( pruned_data != output[-1]['data'] or row['deleted'] != output[-1]['deleted'] ): formatted['data'] = pruned_data output.append(formatted) old_id = id_ return output
python
def _format_response(rows, fields, unique_col_names): """This function will look at the data column of rows and extract the specified fields. It will also dedup changes where the specified fields have not changed. The list of rows should be ordered by the compound primary key which versioning pivots around and be in ascending version order. This function will return a list of dictionaries where each dictionary has the following schema: { 'updated_at': timestamp of the change, 'version': version number for the change, 'data': a nested dictionary containing all keys specified in fields and values corresponding to values in the user table. } Note that some versions may be omitted in the output for the same key if the specified fields were not changed between versions. :param rows: a list of dictionaries representing rows from the ArchiveTable. :param fields: a list of strings of fields to be extracted from the archived row. """ output = [] old_id = None for row in rows: id_ = {k: row[k] for k in unique_col_names} formatted = {k: row[k] for k in row if k != 'data'} if id_ != old_id: # new unique versioned row data = row['data'] formatted['data'] = {k: data.get(k) for k in fields} output.append(formatted) else: data = row['data'] pruned_data = {k: data.get(k) for k in fields} if ( pruned_data != output[-1]['data'] or row['deleted'] != output[-1]['deleted'] ): formatted['data'] = pruned_data output.append(formatted) old_id = id_ return output
[ "def", "_format_response", "(", "rows", ",", "fields", ",", "unique_col_names", ")", ":", "output", "=", "[", "]", "old_id", "=", "None", "for", "row", "in", "rows", ":", "id_", "=", "{", "k", ":", "row", "[", "k", "]", "for", "k", "in", "unique_co...
This function will look at the data column of rows and extract the specified fields. It will also dedup changes where the specified fields have not changed. The list of rows should be ordered by the compound primary key which versioning pivots around and be in ascending version order. This function will return a list of dictionaries where each dictionary has the following schema: { 'updated_at': timestamp of the change, 'version': version number for the change, 'data': a nested dictionary containing all keys specified in fields and values corresponding to values in the user table. } Note that some versions may be omitted in the output for the same key if the specified fields were not changed between versions. :param rows: a list of dictionaries representing rows from the ArchiveTable. :param fields: a list of strings of fields to be extracted from the archived row.
[ "This", "function", "will", "look", "at", "the", "data", "column", "of", "rows", "and", "extract", "the", "specified", "fields", ".", "It", "will", "also", "dedup", "changes", "where", "the", "specified", "fields", "have", "not", "changed", ".", "The", "li...
train
https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/api/data.py#L104-L144
NerdWalletOSS/savage
src/savage/api/data.py
_get_conditions
def _get_conditions(pk_conds, and_conds=None): """If and_conds = [a1, a2, ..., an] and pk_conds = [[b11, b12, ..., b1m], ... [bk1, ..., bkm]], this function will return the mysql condition clause: a1 & a2 & ... an & ((b11 and ... b1m) or ... (b11 and ... b1m)) :param pk_conds: a list of list of primary key constraints returned by _get_conditions_list :param and_conds: additional and conditions to be placed on the query """ if and_conds is None: and_conds = [] if len(and_conds) == 0 and len(pk_conds) == 0: return sa.and_() condition1 = sa.and_(*and_conds) condition2 = sa.or_(*[sa.and_(*cond) for cond in pk_conds]) return sa.and_(condition1, condition2)
python
def _get_conditions(pk_conds, and_conds=None): """If and_conds = [a1, a2, ..., an] and pk_conds = [[b11, b12, ..., b1m], ... [bk1, ..., bkm]], this function will return the mysql condition clause: a1 & a2 & ... an & ((b11 and ... b1m) or ... (b11 and ... b1m)) :param pk_conds: a list of list of primary key constraints returned by _get_conditions_list :param and_conds: additional and conditions to be placed on the query """ if and_conds is None: and_conds = [] if len(and_conds) == 0 and len(pk_conds) == 0: return sa.and_() condition1 = sa.and_(*and_conds) condition2 = sa.or_(*[sa.and_(*cond) for cond in pk_conds]) return sa.and_(condition1, condition2)
[ "def", "_get_conditions", "(", "pk_conds", ",", "and_conds", "=", "None", ")", ":", "if", "and_conds", "is", "None", ":", "and_conds", "=", "[", "]", "if", "len", "(", "and_conds", ")", "==", "0", "and", "len", "(", "pk_conds", ")", "==", "0", ":", ...
If and_conds = [a1, a2, ..., an] and pk_conds = [[b11, b12, ..., b1m], ... [bk1, ..., bkm]], this function will return the mysql condition clause: a1 & a2 & ... an & ((b11 and ... b1m) or ... (b11 and ... b1m)) :param pk_conds: a list of list of primary key constraints returned by _get_conditions_list :param and_conds: additional and conditions to be placed on the query
[ "If", "and_conds", "=", "[", "a1", "a2", "...", "an", "]", "and", "pk_conds", "=", "[[", "b11", "b12", "...", "b1m", "]", "...", "[", "bk1", "...", "bkm", "]]", "this", "function", "will", "return", "the", "mysql", "condition", "clause", ":", "a1", ...
train
https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/api/data.py#L147-L163
NerdWalletOSS/savage
src/savage/api/data.py
_get_conditions_list
def _get_conditions_list(table, conds, archive=True): """This function returns a list of list of == conditions on sqlalchemy columns given conds. This should be treated as an or of ands. :param table: the user table model class which inherits from savage.models.SavageModelMixin :param conds: a list of dictionaries of key value pairs where keys are column names and values are conditions to be placed on the column. :param archive: If true, the condition is with columns from the archive table. Else its from the user table. """ if conds is None: conds = [] all_conditions = [] for cond in conds: if len(cond) != len(table.version_columns): raise ValueError('Conditions must specify all unique constraints.') conditions = [] t = table.ArchiveTable if archive else table for col_name, value in cond.iteritems(): if col_name not in table.version_columns: raise ValueError('{} is not one of the unique columns <{}>'.format( col_name, ','.join(table.version_columns) )) conditions.append(getattr(t, col_name) == value) all_conditions.append(conditions) return all_conditions
python
def _get_conditions_list(table, conds, archive=True): """This function returns a list of list of == conditions on sqlalchemy columns given conds. This should be treated as an or of ands. :param table: the user table model class which inherits from savage.models.SavageModelMixin :param conds: a list of dictionaries of key value pairs where keys are column names and values are conditions to be placed on the column. :param archive: If true, the condition is with columns from the archive table. Else its from the user table. """ if conds is None: conds = [] all_conditions = [] for cond in conds: if len(cond) != len(table.version_columns): raise ValueError('Conditions must specify all unique constraints.') conditions = [] t = table.ArchiveTable if archive else table for col_name, value in cond.iteritems(): if col_name not in table.version_columns: raise ValueError('{} is not one of the unique columns <{}>'.format( col_name, ','.join(table.version_columns) )) conditions.append(getattr(t, col_name) == value) all_conditions.append(conditions) return all_conditions
[ "def", "_get_conditions_list", "(", "table", ",", "conds", ",", "archive", "=", "True", ")", ":", "if", "conds", "is", "None", ":", "conds", "=", "[", "]", "all_conditions", "=", "[", "]", "for", "cond", "in", "conds", ":", "if", "len", "(", "cond", ...
This function returns a list of list of == conditions on sqlalchemy columns given conds. This should be treated as an or of ands. :param table: the user table model class which inherits from savage.models.SavageModelMixin :param conds: a list of dictionaries of key value pairs where keys are column names and values are conditions to be placed on the column. :param archive: If true, the condition is with columns from the archive table. Else its from the user table.
[ "This", "function", "returns", "a", "list", "of", "list", "of", "==", "conditions", "on", "sqlalchemy", "columns", "given", "conds", ".", "This", "should", "be", "treated", "as", "an", "or", "of", "ands", "." ]
train
https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/api/data.py#L166-L195
NerdWalletOSS/savage
src/savage/api/data.py
_get_limit_and_offset
def _get_limit_and_offset(page, page_size): """Returns a 0-indexed offset and limit based on page and page_size for a MySQL query. """ if page < 1: raise ValueError('page must be >= 1') limit = page_size offset = (page - 1) * page_size return limit, offset
python
def _get_limit_and_offset(page, page_size): """Returns a 0-indexed offset and limit based on page and page_size for a MySQL query. """ if page < 1: raise ValueError('page must be >= 1') limit = page_size offset = (page - 1) * page_size return limit, offset
[ "def", "_get_limit_and_offset", "(", "page", ",", "page_size", ")", ":", "if", "page", "<", "1", ":", "raise", "ValueError", "(", "'page must be >= 1'", ")", "limit", "=", "page_size", "offset", "=", "(", "page", "-", "1", ")", "*", "page_size", "return", ...
Returns a 0-indexed offset and limit based on page and page_size for a MySQL query.
[ "Returns", "a", "0", "-", "indexed", "offset", "and", "limit", "based", "on", "page", "and", "page_size", "for", "a", "MySQL", "query", "." ]
train
https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/api/data.py#L269-L276
NerdWalletOSS/savage
src/savage/api/data.py
_get_order_clause
def _get_order_clause(archive_table): """Returns an ascending order clause on the versioned unique constraint as well as the version column. """ order_clause = [ sa.asc(getattr(archive_table, col_name)) for col_name in archive_table._version_col_names ] order_clause.append(sa.asc(archive_table.version_id)) return order_clause
python
def _get_order_clause(archive_table): """Returns an ascending order clause on the versioned unique constraint as well as the version column. """ order_clause = [ sa.asc(getattr(archive_table, col_name)) for col_name in archive_table._version_col_names ] order_clause.append(sa.asc(archive_table.version_id)) return order_clause
[ "def", "_get_order_clause", "(", "archive_table", ")", ":", "order_clause", "=", "[", "sa", ".", "asc", "(", "getattr", "(", "archive_table", ",", "col_name", ")", ")", "for", "col_name", "in", "archive_table", ".", "_version_col_names", "]", "order_clause", "...
Returns an ascending order clause on the versioned unique constraint as well as the version column.
[ "Returns", "an", "ascending", "order", "clause", "on", "the", "versioned", "unique", "constraint", "as", "well", "as", "the", "version", "column", "." ]
train
https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/api/data.py#L279-L287
SYNHAK/spiff
spiff/api/models.py
add_resource_permissions
def add_resource_permissions(*args, **kwargs): """ This syncdb hooks takes care of adding a view permission too all our content types. """ # for each of our content types for resource in find_api_classes('v1_api', ModelResource): auth = resource._meta.authorization content_type = ContentType.objects.get_for_model(resource._meta.queryset.model) if isinstance(auth, SpiffAuthorization): conditions = auth.conditions() operations = auth.operations() if len(conditions) == 0: conditions = (None,) for condition in conditions: for operation in operations: # build our permission slug if condition: codename = "%s_%s_%s" % (operation[0], condition[0], content_type.model) name = "Can %s %s, when %s" % (operation[1], content_type.name, condition[1]) else: codename = "%s_%s" % (operation[1], content_type.model) name = "Can %s %s" % (operation[1], content_type.name) # if it doesn't exist.. if not Permission.objects.filter(content_type=content_type, codename=codename): # add it Permission.objects.create(content_type=content_type, codename=codename, name=name[:49]) funcLog().debug("Created permission %s.%s (%s)", content_type.app_label, codename, name)
python
def add_resource_permissions(*args, **kwargs): """ This syncdb hooks takes care of adding a view permission too all our content types. """ # for each of our content types for resource in find_api_classes('v1_api', ModelResource): auth = resource._meta.authorization content_type = ContentType.objects.get_for_model(resource._meta.queryset.model) if isinstance(auth, SpiffAuthorization): conditions = auth.conditions() operations = auth.operations() if len(conditions) == 0: conditions = (None,) for condition in conditions: for operation in operations: # build our permission slug if condition: codename = "%s_%s_%s" % (operation[0], condition[0], content_type.model) name = "Can %s %s, when %s" % (operation[1], content_type.name, condition[1]) else: codename = "%s_%s" % (operation[1], content_type.model) name = "Can %s %s" % (operation[1], content_type.name) # if it doesn't exist.. if not Permission.objects.filter(content_type=content_type, codename=codename): # add it Permission.objects.create(content_type=content_type, codename=codename, name=name[:49]) funcLog().debug("Created permission %s.%s (%s)", content_type.app_label, codename, name)
[ "def", "add_resource_permissions", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# for each of our content types", "for", "resource", "in", "find_api_classes", "(", "'v1_api'", ",", "ModelResource", ")", ":", "auth", "=", "resource", ".", "_meta", ".", ...
This syncdb hooks takes care of adding a view permission too all our content types.
[ "This", "syncdb", "hooks", "takes", "care", "of", "adding", "a", "view", "permission", "too", "all", "our", "content", "types", "." ]
train
https://github.com/SYNHAK/spiff/blob/5e5c731f67954ddc11d2fb75371cfcfd0fef49b7/spiff/api/models.py#L10-L42
fredericklussier/ObservablePy
observablePy/ObservableStore.py
ObservableStore.areObservableElements
def areObservableElements(self, elementNames): """ Mention if all elements are observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool """ if not(hasattr(elementNames, "__len__")): raise TypeError( "Element name should be a array of strings." + "I receive this {0}" .format(elementNames)) return self._evaluateArray(elementNames)
python
def areObservableElements(self, elementNames): """ Mention if all elements are observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool """ if not(hasattr(elementNames, "__len__")): raise TypeError( "Element name should be a array of strings." + "I receive this {0}" .format(elementNames)) return self._evaluateArray(elementNames)
[ "def", "areObservableElements", "(", "self", ",", "elementNames", ")", ":", "if", "not", "(", "hasattr", "(", "elementNames", ",", "\"__len__\"", ")", ")", ":", "raise", "TypeError", "(", "\"Element name should be a array of strings.\"", "+", "\"I receive this {0}\"",...
Mention if all elements are observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool
[ "Mention", "if", "all", "elements", "are", "observable", "element", "." ]
train
https://github.com/fredericklussier/ObservablePy/blob/fd7926a0568621f80b1d567d18f199976f1fa4e8/observablePy/ObservableStore.py#L27-L41
fredericklussier/ObservablePy
observablePy/ObservableStore.py
ObservableStore.isObservableElement
def isObservableElement(self, elementName): """ Mention if an element is an observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool """ if not(isinstance(elementName, str)): raise TypeError( "Element name should be a string ." + "I receive this {0}" .format(elementName)) return (True if (elementName == "*") else self._evaluateString(elementName))
python
def isObservableElement(self, elementName): """ Mention if an element is an observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool """ if not(isinstance(elementName, str)): raise TypeError( "Element name should be a string ." + "I receive this {0}" .format(elementName)) return (True if (elementName == "*") else self._evaluateString(elementName))
[ "def", "isObservableElement", "(", "self", ",", "elementName", ")", ":", "if", "not", "(", "isinstance", "(", "elementName", ",", "str", ")", ")", ":", "raise", "TypeError", "(", "\"Element name should be a string .\"", "+", "\"I receive this {0}\"", ".", "format"...
Mention if an element is an observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool
[ "Mention", "if", "an", "element", "is", "an", "observable", "element", "." ]
train
https://github.com/fredericklussier/ObservablePy/blob/fd7926a0568621f80b1d567d18f199976f1fa4e8/observablePy/ObservableStore.py#L43-L58
fredericklussier/ObservablePy
observablePy/ObservableStore.py
ObservableStore.add
def add(self, observableElement): """ add an observable element :param str observableElement: the name of the observable element :raises RuntimeError: if element name already exist in the store """ if observableElement not in self._observables: self._observables.append(observableElement) else: raise RuntimeError( "{0} is already an observable element" .format(observableElement))
python
def add(self, observableElement): """ add an observable element :param str observableElement: the name of the observable element :raises RuntimeError: if element name already exist in the store """ if observableElement not in self._observables: self._observables.append(observableElement) else: raise RuntimeError( "{0} is already an observable element" .format(observableElement))
[ "def", "add", "(", "self", ",", "observableElement", ")", ":", "if", "observableElement", "not", "in", "self", ".", "_observables", ":", "self", ".", "_observables", ".", "append", "(", "observableElement", ")", "else", ":", "raise", "RuntimeError", "(", "\"...
add an observable element :param str observableElement: the name of the observable element :raises RuntimeError: if element name already exist in the store
[ "add", "an", "observable", "element" ]
train
https://github.com/fredericklussier/ObservablePy/blob/fd7926a0568621f80b1d567d18f199976f1fa4e8/observablePy/ObservableStore.py#L72-L84
fredericklussier/ObservablePy
observablePy/ObservableStore.py
ObservableStore.remove
def remove(self, observableElement): """ remove an obsrvable element :param str observableElement: the name of the observable element """ if observableElement in self._observables: self._observables.remove(observableElement)
python
def remove(self, observableElement): """ remove an obsrvable element :param str observableElement: the name of the observable element """ if observableElement in self._observables: self._observables.remove(observableElement)
[ "def", "remove", "(", "self", ",", "observableElement", ")", ":", "if", "observableElement", "in", "self", ".", "_observables", ":", "self", ".", "_observables", ".", "remove", "(", "observableElement", ")" ]
remove an obsrvable element :param str observableElement: the name of the observable element
[ "remove", "an", "obsrvable", "element" ]
train
https://github.com/fredericklussier/ObservablePy/blob/fd7926a0568621f80b1d567d18f199976f1fa4e8/observablePy/ObservableStore.py#L86-L93
zhexiao/ezhost
ezhost/BigDataArchi.py
BigDataArchi.install_config_kafka
def install_config_kafka(self): """ install and config kafka :return: """ if self.prompt_check("Download and install kafka"): self.kafka_install() if self.prompt_check("Configure and autostart kafka"): self.kafka_config()
python
def install_config_kafka(self): """ install and config kafka :return: """ if self.prompt_check("Download and install kafka"): self.kafka_install() if self.prompt_check("Configure and autostart kafka"): self.kafka_config()
[ "def", "install_config_kafka", "(", "self", ")", ":", "if", "self", ".", "prompt_check", "(", "\"Download and install kafka\"", ")", ":", "self", ".", "kafka_install", "(", ")", "if", "self", ".", "prompt_check", "(", "\"Configure and autostart kafka\"", ")", ":",...
install and config kafka :return:
[ "install", "and", "config", "kafka", ":", "return", ":" ]
train
https://github.com/zhexiao/ezhost/blob/4146bc0be14bb1bfe98ec19283d19fab420871b3/ezhost/BigDataArchi.py#L61-L70
zhexiao/ezhost
ezhost/BigDataArchi.py
BigDataArchi.install_config_elastic
def install_config_elastic(self): """ install and config elasticsearch :return: """ if self.prompt_check("Download and install elasticsearch"): self.elastic_install() if self.prompt_check("Configure and autostart elasticsearch"): self.elastic_config()
python
def install_config_elastic(self): """ install and config elasticsearch :return: """ if self.prompt_check("Download and install elasticsearch"): self.elastic_install() if self.prompt_check("Configure and autostart elasticsearch"): self.elastic_config()
[ "def", "install_config_elastic", "(", "self", ")", ":", "if", "self", ".", "prompt_check", "(", "\"Download and install elasticsearch\"", ")", ":", "self", ".", "elastic_install", "(", ")", "if", "self", ".", "prompt_check", "(", "\"Configure and autostart elasticsear...
install and config elasticsearch :return:
[ "install", "and", "config", "elasticsearch", ":", "return", ":" ]
train
https://github.com/zhexiao/ezhost/blob/4146bc0be14bb1bfe98ec19283d19fab420871b3/ezhost/BigDataArchi.py#L72-L81
zhexiao/ezhost
ezhost/BigDataArchi.py
BigDataArchi.install_config_logstash
def install_config_logstash(self): """ install and config logstash :return: """ if self.prompt_check("Download and install logstash"): self.logstash_install() if self.prompt_check("Configure and autostart logstash"): self.logstash_config()
python
def install_config_logstash(self): """ install and config logstash :return: """ if self.prompt_check("Download and install logstash"): self.logstash_install() if self.prompt_check("Configure and autostart logstash"): self.logstash_config()
[ "def", "install_config_logstash", "(", "self", ")", ":", "if", "self", ".", "prompt_check", "(", "\"Download and install logstash\"", ")", ":", "self", ".", "logstash_install", "(", ")", "if", "self", ".", "prompt_check", "(", "\"Configure and autostart logstash\"", ...
install and config logstash :return:
[ "install", "and", "config", "logstash", ":", "return", ":" ]
train
https://github.com/zhexiao/ezhost/blob/4146bc0be14bb1bfe98ec19283d19fab420871b3/ezhost/BigDataArchi.py#L83-L92
zhexiao/ezhost
ezhost/BigDataArchi.py
BigDataArchi.install_config_kibana
def install_config_kibana(self): """ install and config kibana :return: """ if self.prompt_check("Download and install kibana"): self.kibana_install() if self.prompt_check("Configure and autostart kibana"): self.kibana_config()
python
def install_config_kibana(self): """ install and config kibana :return: """ if self.prompt_check("Download and install kibana"): self.kibana_install() if self.prompt_check("Configure and autostart kibana"): self.kibana_config()
[ "def", "install_config_kibana", "(", "self", ")", ":", "if", "self", ".", "prompt_check", "(", "\"Download and install kibana\"", ")", ":", "self", ".", "kibana_install", "(", ")", "if", "self", ".", "prompt_check", "(", "\"Configure and autostart kibana\"", ")", ...
install and config kibana :return:
[ "install", "and", "config", "kibana", ":", "return", ":" ]
train
https://github.com/zhexiao/ezhost/blob/4146bc0be14bb1bfe98ec19283d19fab420871b3/ezhost/BigDataArchi.py#L94-L103
zhexiao/ezhost
ezhost/BigDataArchi.py
BigDataArchi.install_config_spark
def install_config_spark(self): """ install and config spark :return: """ if self.prompt_check("Download and install hadoop"): self.hadoop_install() if self.prompt_check("Download and install spark"): self.spark_install() if self.prompt_check("Configure spark"): self.spark_config()
python
def install_config_spark(self): """ install and config spark :return: """ if self.prompt_check("Download and install hadoop"): self.hadoop_install() if self.prompt_check("Download and install spark"): self.spark_install() if self.prompt_check("Configure spark"): self.spark_config()
[ "def", "install_config_spark", "(", "self", ")", ":", "if", "self", ".", "prompt_check", "(", "\"Download and install hadoop\"", ")", ":", "self", ".", "hadoop_install", "(", ")", "if", "self", ".", "prompt_check", "(", "\"Download and install spark\"", ")", ":", ...
install and config spark :return:
[ "install", "and", "config", "spark", ":", "return", ":" ]
train
https://github.com/zhexiao/ezhost/blob/4146bc0be14bb1bfe98ec19283d19fab420871b3/ezhost/BigDataArchi.py#L114-L126
zhexiao/ezhost
ezhost/BigDataArchi.py
BigDataArchi.add_slave_server
def add_slave_server(self): """ 添加slave服务器 :return: """ master = self.args.config[1] slave = self.args.add_slave # install java at slave server self.reset_server_env(slave, self.configure) if self.prompt_check("Update package at slave server"): self.update_source_list() self.common_update_sys() if self.prompt_check("Install java and python at slave server"): self.java_install() sudo('apt-get install -y python python3 python-dev python3-dev') # generate ssh key at master server if not self.args.skip_master: if self.prompt_check("Generate ssh key at Master Server"): self.generate_ssh(master, self.args, self.configure) # generate ssh key at slave server and make slave connect with master if self.prompt_check("Make ssh connection within master and slave"): self.generate_ssh(slave, self.args, self.configure) # scp slave server ssh key to master server run('scp ~/.ssh/id_rsa.pub {0}@{1}:~/.ssh/id_rsa.pub.{2}'.format( self.configure[master]['user'], self.configure[master]['host'], slave )) # add slave ssh key to master authorized_keys self.reset_server_env(master, self.configure) run('cat ~/.ssh/id_rsa.pub* >> ~/.ssh/authorized_keys') # scp master authorized_keys to slave authorized_keys run('scp ~/.ssh/authorized_keys {0}@{1}:~/.ssh'.format( self.configure[slave]['user'], self.configure[slave]['host'] )) # config slave and master if self.prompt_check("Configure master and slave server"): master = self.args.config[1] slave = self.args.add_slave if self.args.bigdata_app == 'spark': self.add_spark_slave(master, slave, self.configure)
python
def add_slave_server(self): """ 添加slave服务器 :return: """ master = self.args.config[1] slave = self.args.add_slave # install java at slave server self.reset_server_env(slave, self.configure) if self.prompt_check("Update package at slave server"): self.update_source_list() self.common_update_sys() if self.prompt_check("Install java and python at slave server"): self.java_install() sudo('apt-get install -y python python3 python-dev python3-dev') # generate ssh key at master server if not self.args.skip_master: if self.prompt_check("Generate ssh key at Master Server"): self.generate_ssh(master, self.args, self.configure) # generate ssh key at slave server and make slave connect with master if self.prompt_check("Make ssh connection within master and slave"): self.generate_ssh(slave, self.args, self.configure) # scp slave server ssh key to master server run('scp ~/.ssh/id_rsa.pub {0}@{1}:~/.ssh/id_rsa.pub.{2}'.format( self.configure[master]['user'], self.configure[master]['host'], slave )) # add slave ssh key to master authorized_keys self.reset_server_env(master, self.configure) run('cat ~/.ssh/id_rsa.pub* >> ~/.ssh/authorized_keys') # scp master authorized_keys to slave authorized_keys run('scp ~/.ssh/authorized_keys {0}@{1}:~/.ssh'.format( self.configure[slave]['user'], self.configure[slave]['host'] )) # config slave and master if self.prompt_check("Configure master and slave server"): master = self.args.config[1] slave = self.args.add_slave if self.args.bigdata_app == 'spark': self.add_spark_slave(master, slave, self.configure)
[ "def", "add_slave_server", "(", "self", ")", ":", "master", "=", "self", ".", "args", ".", "config", "[", "1", "]", "slave", "=", "self", ".", "args", ".", "add_slave", "# install java at slave server", "self", ".", "reset_server_env", "(", "slave", ",", "...
添加slave服务器 :return:
[ "添加slave服务器", ":", "return", ":" ]
train
https://github.com/zhexiao/ezhost/blob/4146bc0be14bb1bfe98ec19283d19fab420871b3/ezhost/BigDataArchi.py#L128-L178
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py
get_file_content
def get_file_content(url, comes_from=None): """Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content)""" match = _scheme_re.search(url) if match: scheme = match.group(1).lower() if (scheme == 'file' and comes_from and comes_from.startswith('http')): raise InstallationError( 'Requirements file %s references URL %s, which is local' % (comes_from, url)) if scheme == 'file': path = url.split(':', 1)[1] path = path.replace('\\', '/') match = _url_slash_drive_re.match(path) if match: path = match.group(1) + ':' + path.split('|', 1)[1] path = urllib.unquote(path) if path.startswith('/'): path = '/' + path.lstrip('/') url = path else: ## FIXME: catch some errors resp = urlopen(url) return geturl(resp), resp.read() try: f = open(url) content = f.read() except IOError: e = sys.exc_info()[1] raise InstallationError('Could not open requirements file: %s' % str(e)) else: f.close() return url, content
python
def get_file_content(url, comes_from=None): """Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content)""" match = _scheme_re.search(url) if match: scheme = match.group(1).lower() if (scheme == 'file' and comes_from and comes_from.startswith('http')): raise InstallationError( 'Requirements file %s references URL %s, which is local' % (comes_from, url)) if scheme == 'file': path = url.split(':', 1)[1] path = path.replace('\\', '/') match = _url_slash_drive_re.match(path) if match: path = match.group(1) + ':' + path.split('|', 1)[1] path = urllib.unquote(path) if path.startswith('/'): path = '/' + path.lstrip('/') url = path else: ## FIXME: catch some errors resp = urlopen(url) return geturl(resp), resp.read() try: f = open(url) content = f.read() except IOError: e = sys.exc_info()[1] raise InstallationError('Could not open requirements file: %s' % str(e)) else: f.close() return url, content
[ "def", "get_file_content", "(", "url", ",", "comes_from", "=", "None", ")", ":", "match", "=", "_scheme_re", ".", "search", "(", "url", ")", "if", "match", ":", "scheme", "=", "match", ".", "group", "(", "1", ")", ".", "lower", "(", ")", "if", "(",...
Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content)
[ "Gets", "the", "content", "of", "a", "file", ";", "it", "may", "be", "a", "filename", "file", ":", "URL", "or", "http", ":", "URL", ".", "Returns", "(", "location", "content", ")" ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L28-L61
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py
url_to_path
def url_to_path(url): """ Convert a file: URL to a path. """ assert url.startswith('file:'), ( "You can only turn file: urls into filenames (not %r)" % url) path = url[len('file:'):].lstrip('/') path = urllib.unquote(path) if _url_drive_re.match(path): path = path[0] + ':' + path[2:] else: path = '/' + path return path
python
def url_to_path(url): """ Convert a file: URL to a path. """ assert url.startswith('file:'), ( "You can only turn file: urls into filenames (not %r)" % url) path = url[len('file:'):].lstrip('/') path = urllib.unquote(path) if _url_drive_re.match(path): path = path[0] + ':' + path[2:] else: path = '/' + path return path
[ "def", "url_to_path", "(", "url", ")", ":", "assert", "url", ".", "startswith", "(", "'file:'", ")", ",", "(", "\"You can only turn file: urls into filenames (not %r)\"", "%", "url", ")", "path", "=", "url", "[", "len", "(", "'file:'", ")", ":", "]", ".", ...
Convert a file: URL to a path.
[ "Convert", "a", "file", ":", "URL", "to", "a", "path", "." ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L209-L221
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py
path_to_url
def path_to_url(path): """ Convert a path to a file: URL. The path will be made absolute. """ path = os.path.normcase(os.path.abspath(path)) if _drive_re.match(path): path = path[0] + '|' + path[2:] url = urllib.quote(path) url = url.replace(os.path.sep, '/') url = url.lstrip('/') return 'file:///' + url
python
def path_to_url(path): """ Convert a path to a file: URL. The path will be made absolute. """ path = os.path.normcase(os.path.abspath(path)) if _drive_re.match(path): path = path[0] + '|' + path[2:] url = urllib.quote(path) url = url.replace(os.path.sep, '/') url = url.lstrip('/') return 'file:///' + url
[ "def", "path_to_url", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", "if", "_drive_re", ".", "match", "(", "path", ")", ":", "path", "=", "path", "[", "0", ...
Convert a path to a file: URL. The path will be made absolute.
[ "Convert", "a", "path", "to", "a", "file", ":", "URL", ".", "The", "path", "will", "be", "made", "absolute", "." ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L228-L238
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py
path_to_url2
def path_to_url2(path): """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) drive, path = os.path.splitdrive(path) filepath = path.split(os.path.sep) url = '/'.join([urllib.quote(part) for part in filepath]) if not drive: url = url.lstrip('/') return 'file:///' + drive + url
python
def path_to_url2(path): """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) drive, path = os.path.splitdrive(path) filepath = path.split(os.path.sep) url = '/'.join([urllib.quote(part) for part in filepath]) if not drive: url = url.lstrip('/') return 'file:///' + drive + url
[ "def", "path_to_url2", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", "drive", ",", "path", "=", "os", ".", "path", ".", "splitdrive", "(", "path", ")", "file...
Convert a path to a file: URL. The path will be made absolute and have quoted path parts.
[ "Convert", "a", "path", "to", "a", "file", ":", "URL", ".", "The", "path", "will", "be", "made", "absolute", "and", "have", "quoted", "path", "parts", "." ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L241-L252
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py
geturl
def geturl(urllib2_resp): """ Use instead of urllib.addinfourl.geturl(), which appears to have some issues with dropping the double slash for certain schemes (e.g. file://). This implementation is probably over-eager, as it always restores '://' if it is missing, and it appears some url schemata aren't always followed by '//' after the colon, but as far as I know pip doesn't need any of those. The URI RFC can be found at: http://tools.ietf.org/html/rfc1630 This function assumes that scheme:/foo/bar is the same as scheme:///foo/bar """ url = urllib2_resp.geturl() scheme, rest = url.split(':', 1) if rest.startswith('//'): return url else: # FIXME: write a good test to cover it return '%s://%s' % (scheme, rest)
python
def geturl(urllib2_resp): """ Use instead of urllib.addinfourl.geturl(), which appears to have some issues with dropping the double slash for certain schemes (e.g. file://). This implementation is probably over-eager, as it always restores '://' if it is missing, and it appears some url schemata aren't always followed by '//' after the colon, but as far as I know pip doesn't need any of those. The URI RFC can be found at: http://tools.ietf.org/html/rfc1630 This function assumes that scheme:/foo/bar is the same as scheme:///foo/bar """ url = urllib2_resp.geturl() scheme, rest = url.split(':', 1) if rest.startswith('//'): return url else: # FIXME: write a good test to cover it return '%s://%s' % (scheme, rest)
[ "def", "geturl", "(", "urllib2_resp", ")", ":", "url", "=", "urllib2_resp", ".", "geturl", "(", ")", "scheme", ",", "rest", "=", "url", ".", "split", "(", "':'", ",", "1", ")", "if", "rest", ".", "startswith", "(", "'//'", ")", ":", "return", "url"...
Use instead of urllib.addinfourl.geturl(), which appears to have some issues with dropping the double slash for certain schemes (e.g. file://). This implementation is probably over-eager, as it always restores '://' if it is missing, and it appears some url schemata aren't always followed by '//' after the colon, but as far as I know pip doesn't need any of those. The URI RFC can be found at: http://tools.ietf.org/html/rfc1630 This function assumes that scheme:/foo/bar is the same as scheme:///foo/bar
[ "Use", "instead", "of", "urllib", ".", "addinfourl", ".", "geturl", "()", "which", "appears", "to", "have", "some", "issues", "with", "dropping", "the", "double", "slash", "for", "certain", "schemes", "(", "e", ".", "g", ".", "file", ":", "//", ")", "....
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L255-L276
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py
URLOpener.get_request
def get_request(self, url): """ Wraps the URL to retrieve to protects against "creative" interpretation of the RFC: http://bugs.python.org/issue8732 """ if isinstance(url, string_types): url = urllib2.Request(url, headers={'Accept-encoding': 'identity'}) return url
python
def get_request(self, url): """ Wraps the URL to retrieve to protects against "creative" interpretation of the RFC: http://bugs.python.org/issue8732 """ if isinstance(url, string_types): url = urllib2.Request(url, headers={'Accept-encoding': 'identity'}) return url
[ "def", "get_request", "(", "self", ",", "url", ")", ":", "if", "isinstance", "(", "url", ",", "string_types", ")", ":", "url", "=", "urllib2", ".", "Request", "(", "url", ",", "headers", "=", "{", "'Accept-encoding'", ":", "'identity'", "}", ")", "retu...
Wraps the URL to retrieve to protects against "creative" interpretation of the RFC: http://bugs.python.org/issue8732
[ "Wraps", "the", "URL", "to", "retrieve", "to", "protects", "against", "creative", "interpretation", "of", "the", "RFC", ":", "http", ":", "//", "bugs", ".", "python", ".", "org", "/", "issue8732" ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L94-L101
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py
URLOpener.get_response
def get_response(self, url, username=None, password=None): """ does the dirty work of actually getting the rsponse object using urllib2 and its HTTP auth builtins. """ scheme, netloc, path, query, frag = urlparse.urlsplit(url) req = self.get_request(url) stored_username, stored_password = self.passman.find_user_password(None, netloc) # see if we have a password stored if stored_username is None: if username is None and self.prompting: username = urllib.quote(raw_input('User for %s: ' % netloc)) password = urllib.quote(getpass.getpass('Password: ')) if username and password: self.passman.add_password(None, netloc, username, password) stored_username, stored_password = self.passman.find_user_password(None, netloc) authhandler = urllib2.HTTPBasicAuthHandler(self.passman) opener = urllib2.build_opener(authhandler) # FIXME: should catch a 401 and offer to let the user reenter credentials return opener.open(req)
python
def get_response(self, url, username=None, password=None): """ does the dirty work of actually getting the rsponse object using urllib2 and its HTTP auth builtins. """ scheme, netloc, path, query, frag = urlparse.urlsplit(url) req = self.get_request(url) stored_username, stored_password = self.passman.find_user_password(None, netloc) # see if we have a password stored if stored_username is None: if username is None and self.prompting: username = urllib.quote(raw_input('User for %s: ' % netloc)) password = urllib.quote(getpass.getpass('Password: ')) if username and password: self.passman.add_password(None, netloc, username, password) stored_username, stored_password = self.passman.find_user_password(None, netloc) authhandler = urllib2.HTTPBasicAuthHandler(self.passman) opener = urllib2.build_opener(authhandler) # FIXME: should catch a 401 and offer to let the user reenter credentials return opener.open(req)
[ "def", "get_response", "(", "self", ",", "url", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "frag", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "req", "=", "s...
does the dirty work of actually getting the rsponse object using urllib2 and its HTTP auth builtins.
[ "does", "the", "dirty", "work", "of", "actually", "getting", "the", "rsponse", "object", "using", "urllib2", "and", "its", "HTTP", "auth", "builtins", "." ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L103-L123
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py
URLOpener.setup
def setup(self, proxystr='', prompting=True): """ Sets the proxy handler given the option passed on the command line. If an empty string is passed it looks at the HTTP_PROXY environment variable. """ self.prompting = prompting proxy = self.get_proxy(proxystr) if proxy: proxy_support = urllib2.ProxyHandler({"http": proxy, "ftp": proxy}) opener = urllib2.build_opener(proxy_support, urllib2.CacheFTPHandler) urllib2.install_opener(opener)
python
def setup(self, proxystr='', prompting=True): """ Sets the proxy handler given the option passed on the command line. If an empty string is passed it looks at the HTTP_PROXY environment variable. """ self.prompting = prompting proxy = self.get_proxy(proxystr) if proxy: proxy_support = urllib2.ProxyHandler({"http": proxy, "ftp": proxy}) opener = urllib2.build_opener(proxy_support, urllib2.CacheFTPHandler) urllib2.install_opener(opener)
[ "def", "setup", "(", "self", ",", "proxystr", "=", "''", ",", "prompting", "=", "True", ")", ":", "self", ".", "prompting", "=", "prompting", "proxy", "=", "self", ".", "get_proxy", "(", "proxystr", ")", "if", "proxy", ":", "proxy_support", "=", "urlli...
Sets the proxy handler given the option passed on the command line. If an empty string is passed it looks at the HTTP_PROXY environment variable.
[ "Sets", "the", "proxy", "handler", "given", "the", "option", "passed", "on", "the", "command", "line", ".", "If", "an", "empty", "string", "is", "passed", "it", "looks", "at", "the", "HTTP_PROXY", "environment", "variable", "." ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L125-L136
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py
URLOpener.extract_credentials
def extract_credentials(self, url): """ Extracts user/password from a url. Returns a tuple: (url-without-auth, username, password) """ if isinstance(url, urllib2.Request): result = urlparse.urlsplit(url.get_full_url()) else: result = urlparse.urlsplit(url) scheme, netloc, path, query, frag = result username, password = self.parse_credentials(netloc) if username is None: return url, None, None elif password is None and self.prompting: # remove the auth credentials from the url part netloc = netloc.replace('%s@' % username, '', 1) # prompt for the password prompt = 'Password for %s@%s: ' % (username, netloc) password = urllib.quote(getpass.getpass(prompt)) else: # remove the auth credentials from the url part netloc = netloc.replace('%s:%s@' % (username, password), '', 1) target_url = urlparse.urlunsplit((scheme, netloc, path, query, frag)) return target_url, username, password
python
def extract_credentials(self, url): """ Extracts user/password from a url. Returns a tuple: (url-without-auth, username, password) """ if isinstance(url, urllib2.Request): result = urlparse.urlsplit(url.get_full_url()) else: result = urlparse.urlsplit(url) scheme, netloc, path, query, frag = result username, password = self.parse_credentials(netloc) if username is None: return url, None, None elif password is None and self.prompting: # remove the auth credentials from the url part netloc = netloc.replace('%s@' % username, '', 1) # prompt for the password prompt = 'Password for %s@%s: ' % (username, netloc) password = urllib.quote(getpass.getpass(prompt)) else: # remove the auth credentials from the url part netloc = netloc.replace('%s:%s@' % (username, password), '', 1) target_url = urlparse.urlunsplit((scheme, netloc, path, query, frag)) return target_url, username, password
[ "def", "extract_credentials", "(", "self", ",", "url", ")", ":", "if", "isinstance", "(", "url", ",", "urllib2", ".", "Request", ")", ":", "result", "=", "urlparse", ".", "urlsplit", "(", "url", ".", "get_full_url", "(", ")", ")", "else", ":", "result"...
Extracts user/password from a url. Returns a tuple: (url-without-auth, username, password)
[ "Extracts", "user", "/", "password", "from", "a", "url", "." ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L146-L173
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py
URLOpener.get_proxy
def get_proxy(self, proxystr=''): """ Get the proxy given the option passed on the command line. If an empty string is passed it looks at the HTTP_PROXY environment variable. """ if not proxystr: proxystr = os.environ.get('HTTP_PROXY', '') if proxystr: if '@' in proxystr: user_password, server_port = proxystr.split('@', 1) if ':' in user_password: user, password = user_password.split(':', 1) else: user = user_password prompt = 'Password for %s@%s: ' % (user, server_port) password = urllib.quote(getpass.getpass(prompt)) return '%s:%s@%s' % (user, password, server_port) else: return proxystr else: return None
python
def get_proxy(self, proxystr=''): """ Get the proxy given the option passed on the command line. If an empty string is passed it looks at the HTTP_PROXY environment variable. """ if not proxystr: proxystr = os.environ.get('HTTP_PROXY', '') if proxystr: if '@' in proxystr: user_password, server_port = proxystr.split('@', 1) if ':' in user_password: user, password = user_password.split(':', 1) else: user = user_password prompt = 'Password for %s@%s: ' % (user, server_port) password = urllib.quote(getpass.getpass(prompt)) return '%s:%s@%s' % (user, password, server_port) else: return proxystr else: return None
[ "def", "get_proxy", "(", "self", ",", "proxystr", "=", "''", ")", ":", "if", "not", "proxystr", ":", "proxystr", "=", "os", ".", "environ", ".", "get", "(", "'HTTP_PROXY'", ",", "''", ")", "if", "proxystr", ":", "if", "'@'", "in", "proxystr", ":", ...
Get the proxy given the option passed on the command line. If an empty string is passed it looks at the HTTP_PROXY environment variable.
[ "Get", "the", "proxy", "given", "the", "option", "passed", "on", "the", "command", "line", ".", "If", "an", "empty", "string", "is", "passed", "it", "looks", "at", "the", "HTTP_PROXY", "environment", "variable", "." ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L175-L196
John-Lin/pydcard
pydcard/pydcard.py
pageassert
def pageassert(func): ''' Decorator that assert page number ''' @wraps(func) def wrapper(*args, **kwargs): if args[0] < 1 or args[0] > 40: raise ValueError('Page Number not found') return func(*args, **kwargs) return wrapper
python
def pageassert(func): ''' Decorator that assert page number ''' @wraps(func) def wrapper(*args, **kwargs): if args[0] < 1 or args[0] > 40: raise ValueError('Page Number not found') return func(*args, **kwargs) return wrapper
[ "def", "pageassert", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "[", "0", "]", "<", "1", "or", "args", "[", "0", "]", ">", "40", ":", "raise", ...
Decorator that assert page number
[ "Decorator", "that", "assert", "page", "number" ]
train
https://github.com/John-Lin/pydcard/blob/57b57cca2c69dc0c260f5b05ae440341860d8ce4/pydcard/pydcard.py#L9-L18
earlye/nephele
nephele/AwsProcessor.py
AwsProcessor.do_mfa
def do_mfa(self, args): """ Enter a 6-digit MFA token. Nephele will execute the appropriate `aws` command line to authenticate that token. mfa -h for more details """ parser = CommandArgumentParser("mfa") parser.add_argument(dest='token',help='MFA token value'); parser.add_argument("-p","--profile",dest='awsProfile',default=AwsConnectionFactory.instance.getProfile(),help='MFA token value'); args = vars(parser.parse_args(args)) token = args['token'] awsProfile = args['awsProfile'] arn = AwsConnectionFactory.instance.load_arn(awsProfile) credentials_command = ["aws","--profile",awsProfile,"--output","json","sts","get-session-token","--serial-number",arn,"--token-code",token] output = run_cmd(credentials_command) # Throws on non-zero exit :yey: credentials = json.loads("\n".join(output.stdout))['Credentials'] AwsConnectionFactory.instance.setMfaCredentials(credentials,awsProfile)
python
def do_mfa(self, args): """ Enter a 6-digit MFA token. Nephele will execute the appropriate `aws` command line to authenticate that token. mfa -h for more details """ parser = CommandArgumentParser("mfa") parser.add_argument(dest='token',help='MFA token value'); parser.add_argument("-p","--profile",dest='awsProfile',default=AwsConnectionFactory.instance.getProfile(),help='MFA token value'); args = vars(parser.parse_args(args)) token = args['token'] awsProfile = args['awsProfile'] arn = AwsConnectionFactory.instance.load_arn(awsProfile) credentials_command = ["aws","--profile",awsProfile,"--output","json","sts","get-session-token","--serial-number",arn,"--token-code",token] output = run_cmd(credentials_command) # Throws on non-zero exit :yey: credentials = json.loads("\n".join(output.stdout))['Credentials'] AwsConnectionFactory.instance.setMfaCredentials(credentials,awsProfile)
[ "def", "do_mfa", "(", "self", ",", "args", ")", ":", "parser", "=", "CommandArgumentParser", "(", "\"mfa\"", ")", "parser", ".", "add_argument", "(", "dest", "=", "'token'", ",", "help", "=", "'MFA token value'", ")", "parser", ".", "add_argument", "(", "\...
Enter a 6-digit MFA token. Nephele will execute the appropriate `aws` command line to authenticate that token. mfa -h for more details
[ "Enter", "a", "6", "-", "digit", "MFA", "token", ".", "Nephele", "will", "execute", "the", "appropriate", "aws", "command", "line", "to", "authenticate", "that", "token", "." ]
train
https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsProcessor.py#L140-L161
earlye/nephele
nephele/AwsProcessor.py
AwsProcessor.do_up
def do_up(self,args): """ Navigate up by one level. For example, if you are in `(aws)/stack:.../asg:.../`, executing `up` will place you in `(aws)/stack:.../`. up -h for more details """ parser = CommandArgumentParser("up") args = vars(parser.parse_args(args)) if None == self.parent: print "You're at the root. Try 'quit' to quit" else: return True
python
def do_up(self,args): """ Navigate up by one level. For example, if you are in `(aws)/stack:.../asg:.../`, executing `up` will place you in `(aws)/stack:.../`. up -h for more details """ parser = CommandArgumentParser("up") args = vars(parser.parse_args(args)) if None == self.parent: print "You're at the root. Try 'quit' to quit" else: return True
[ "def", "do_up", "(", "self", ",", "args", ")", ":", "parser", "=", "CommandArgumentParser", "(", "\"up\"", ")", "args", "=", "vars", "(", "parser", ".", "parse_args", "(", "args", ")", ")", "if", "None", "==", "self", ".", "parent", ":", "print", "\"...
Navigate up by one level. For example, if you are in `(aws)/stack:.../asg:.../`, executing `up` will place you in `(aws)/stack:.../`. up -h for more details
[ "Navigate", "up", "by", "one", "level", "." ]
train
https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsProcessor.py#L163-L176
earlye/nephele
nephele/AwsProcessor.py
AwsProcessor.do_slash
def do_slash(self,args): """ Navigate back to the root level. For example, if you are in `(aws)/stack:.../asg:.../`, executing `slash` will place you in `(aws)/`. slash -h for more details """ parser = CommandArgumentParser("slash") args = vars(parser.parse_args(args)) if None == self.parent: print "You're at the root. Try 'quit' to quit" else: raise SlashException()
python
def do_slash(self,args): """ Navigate back to the root level. For example, if you are in `(aws)/stack:.../asg:.../`, executing `slash` will place you in `(aws)/`. slash -h for more details """ parser = CommandArgumentParser("slash") args = vars(parser.parse_args(args)) if None == self.parent: print "You're at the root. Try 'quit' to quit" else: raise SlashException()
[ "def", "do_slash", "(", "self", ",", "args", ")", ":", "parser", "=", "CommandArgumentParser", "(", "\"slash\"", ")", "args", "=", "vars", "(", "parser", ".", "parse_args", "(", "args", ")", ")", "if", "None", "==", "self", ".", "parent", ":", "print",...
Navigate back to the root level. For example, if you are in `(aws)/stack:.../asg:.../`, executing `slash` will place you in `(aws)/`. slash -h for more details
[ "Navigate", "back", "to", "the", "root", "level", "." ]
train
https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsProcessor.py#L178-L191
earlye/nephele
nephele/AwsProcessor.py
AwsProcessor.do_profile
def do_profile(self,args): """ Select nephele profile profile -h for more details """ parser = CommandArgumentParser("profile") parser.add_argument(dest="profile",help="Profile name") parser.add_argument('-v','--verbose',dest="verbose",action='store_true',help='verbose') args = vars(parser.parse_args(args)) profile = args['profile'] verbose = args['verbose'] if verbose: print "Selecting profile '{}'".format(profile) selectedProfile = {} if profile in Config.config['profiles']: selectedProfile = Config.config['profiles'][profile] selectedProfile['name'] = profile Config.config['selectedProfile'] = selectedProfile awsProfile = profile if 'awsProfile' in selectedProfile: awsProfile = selectedProfile['awsProfile'] AwsConnectionFactory.resetInstance(profile=awsProfile)
python
def do_profile(self,args): """ Select nephele profile profile -h for more details """ parser = CommandArgumentParser("profile") parser.add_argument(dest="profile",help="Profile name") parser.add_argument('-v','--verbose',dest="verbose",action='store_true',help='verbose') args = vars(parser.parse_args(args)) profile = args['profile'] verbose = args['verbose'] if verbose: print "Selecting profile '{}'".format(profile) selectedProfile = {} if profile in Config.config['profiles']: selectedProfile = Config.config['profiles'][profile] selectedProfile['name'] = profile Config.config['selectedProfile'] = selectedProfile awsProfile = profile if 'awsProfile' in selectedProfile: awsProfile = selectedProfile['awsProfile'] AwsConnectionFactory.resetInstance(profile=awsProfile)
[ "def", "do_profile", "(", "self", ",", "args", ")", ":", "parser", "=", "CommandArgumentParser", "(", "\"profile\"", ")", "parser", ".", "add_argument", "(", "dest", "=", "\"profile\"", ",", "help", "=", "\"Profile name\"", ")", "parser", ".", "add_argument", ...
Select nephele profile profile -h for more details
[ "Select", "nephele", "profile" ]
train
https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsProcessor.py#L193-L219
earlye/nephele
nephele/AwsProcessor.py
AwsProcessor.do_config
def do_config(self,args): """ Deal with configuration. Available subcommands: * config print - print the current configuration * config reload - reload the current configuration from disk * config set - change a setting in the configuration * config save - save the configuration to disk config -h for more details """ parser = CommandArgumentParser("config") subparsers = parser.add_subparsers(help='sub-command help',dest='command') # subparsers.required= subparsers._parser_class = argparse.ArgumentParser # This is to work around `TypeError: __init__() got an unexpected keyword argument 'prog'` parserPrint = subparsers.add_parser('print',help='Print the current configuration') parserPrint.add_argument(dest='keys',nargs='*',help='Key(s) to print') parserSet = subparsers.add_parser('set',help='Set a configuration value') parserSave = subparsers.add_parser('save',help='Save the current configuration') parserReload = subparsers.add_parser('reload',help='Reload the configuration from disk') args = vars(parser.parse_args(args)) print("Command:{}".format(args['command'])) { 'print' : AwsProcessor.sub_configPrint, 'set' : AwsProcessor.sub_configSet, 'save' : AwsProcessor.sub_configSave, 'reload' : AwsProcessor.sub_configReload }[args['command']]( self, args )
python
def do_config(self,args): """ Deal with configuration. Available subcommands: * config print - print the current configuration * config reload - reload the current configuration from disk * config set - change a setting in the configuration * config save - save the configuration to disk config -h for more details """ parser = CommandArgumentParser("config") subparsers = parser.add_subparsers(help='sub-command help',dest='command') # subparsers.required= subparsers._parser_class = argparse.ArgumentParser # This is to work around `TypeError: __init__() got an unexpected keyword argument 'prog'` parserPrint = subparsers.add_parser('print',help='Print the current configuration') parserPrint.add_argument(dest='keys',nargs='*',help='Key(s) to print') parserSet = subparsers.add_parser('set',help='Set a configuration value') parserSave = subparsers.add_parser('save',help='Save the current configuration') parserReload = subparsers.add_parser('reload',help='Reload the configuration from disk') args = vars(parser.parse_args(args)) print("Command:{}".format(args['command'])) { 'print' : AwsProcessor.sub_configPrint, 'set' : AwsProcessor.sub_configSet, 'save' : AwsProcessor.sub_configSave, 'reload' : AwsProcessor.sub_configReload }[args['command']]( self, args )
[ "def", "do_config", "(", "self", ",", "args", ")", ":", "parser", "=", "CommandArgumentParser", "(", "\"config\"", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", "help", "=", "'sub-command help'", ",", "dest", "=", "'command'", ")", "# subparser...
Deal with configuration. Available subcommands: * config print - print the current configuration * config reload - reload the current configuration from disk * config set - change a setting in the configuration * config save - save the configuration to disk config -h for more details
[ "Deal", "with", "configuration", ".", "Available", "subcommands", ":" ]
train
https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsProcessor.py#L315-L345
gisgroup/statbank-python
statbank/time.py
parse
def parse(timestring): """Convert a statbank time string to a python datetime object. """ for parser in _PARSERS: match = parser['pattern'].match(timestring) if match: groups = match.groups() ints = tuple(map(int, groups)) time = parser['factory'](ints) return time raise TimeError('Unsupported time format {}'.format(timestring))
python
def parse(timestring): """Convert a statbank time string to a python datetime object. """ for parser in _PARSERS: match = parser['pattern'].match(timestring) if match: groups = match.groups() ints = tuple(map(int, groups)) time = parser['factory'](ints) return time raise TimeError('Unsupported time format {}'.format(timestring))
[ "def", "parse", "(", "timestring", ")", ":", "for", "parser", "in", "_PARSERS", ":", "match", "=", "parser", "[", "'pattern'", "]", ".", "match", "(", "timestring", ")", "if", "match", ":", "groups", "=", "match", ".", "groups", "(", ")", "ints", "="...
Convert a statbank time string to a python datetime object.
[ "Convert", "a", "statbank", "time", "string", "to", "a", "python", "datetime", "object", "." ]
train
https://github.com/gisgroup/statbank-python/blob/3678820d8da35f225d706ea5096c1f08bf0b9c68/statbank/time.py#L10-L21
infinite-library/ghetto
ghetto.py
confirm
def confirm(text, default=True): """ Console confirmation dialog based on raw_input. """ if default: legend = "[y]/n" else: legend = "y/[n]" res = "" while (res != "y") and (res != "n"): res = raw_input(text + " ({}): ".format(legend)).lower() if not res and default: res = "y" elif not res and not default: res = "n" if res[0] == "y": return True else: return False
python
def confirm(text, default=True): """ Console confirmation dialog based on raw_input. """ if default: legend = "[y]/n" else: legend = "y/[n]" res = "" while (res != "y") and (res != "n"): res = raw_input(text + " ({}): ".format(legend)).lower() if not res and default: res = "y" elif not res and not default: res = "n" if res[0] == "y": return True else: return False
[ "def", "confirm", "(", "text", ",", "default", "=", "True", ")", ":", "if", "default", ":", "legend", "=", "\"[y]/n\"", "else", ":", "legend", "=", "\"y/[n]\"", "res", "=", "\"\"", "while", "(", "res", "!=", "\"y\"", ")", "and", "(", "res", "!=", "...
Console confirmation dialog based on raw_input.
[ "Console", "confirmation", "dialog", "based", "on", "raw_input", "." ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L29-L47
infinite-library/ghetto
ghetto.py
read_file
def read_file(fname): """ Read file, convert wildcards into regular expressions, skip empty lines and comments. """ res = [] try: with open(fname, 'r') as f: for line in f: line = line.rstrip('\n').rstrip('\r') if line and (line[0] != '#'): regexline = ".*" + re.sub("\*", ".*", line) + ".*" res.append(regexline.lower()) except IOError: pass return res
python
def read_file(fname): """ Read file, convert wildcards into regular expressions, skip empty lines and comments. """ res = [] try: with open(fname, 'r') as f: for line in f: line = line.rstrip('\n').rstrip('\r') if line and (line[0] != '#'): regexline = ".*" + re.sub("\*", ".*", line) + ".*" res.append(regexline.lower()) except IOError: pass return res
[ "def", "read_file", "(", "fname", ")", ":", "res", "=", "[", "]", "try", ":", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "line", "=", "line", ".", "rstrip", "(", "'\\n'", ")", ".", "rstrip", ...
Read file, convert wildcards into regular expressions, skip empty lines and comments.
[ "Read", "file", "convert", "wildcards", "into", "regular", "expressions", "skip", "empty", "lines", "and", "comments", "." ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L58-L73
infinite-library/ghetto
ghetto.py
drop_it
def drop_it(title, filters, blacklist): """ The found torrents should be in filters list and shouldn't be in blacklist. """ title = title.lower() matched = False for f in filters: if re.match(f, title): matched = True if not matched: return True for b in blacklist: if re.match(b, title): return True return False
python
def drop_it(title, filters, blacklist): """ The found torrents should be in filters list and shouldn't be in blacklist. """ title = title.lower() matched = False for f in filters: if re.match(f, title): matched = True if not matched: return True for b in blacklist: if re.match(b, title): return True return False
[ "def", "drop_it", "(", "title", ",", "filters", ",", "blacklist", ")", ":", "title", "=", "title", ".", "lower", "(", ")", "matched", "=", "False", "for", "f", "in", "filters", ":", "if", "re", ".", "match", "(", "f", ",", "title", ")", ":", "mat...
The found torrents should be in filters list and shouldn't be in blacklist.
[ "The", "found", "torrents", "should", "be", "in", "filters", "list", "and", "shouldn", "t", "be", "in", "blacklist", "." ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L76-L90
infinite-library/ghetto
ghetto.py
do_list
def do_list(): """ CLI action "list configurations". """ dirs = os.walk(CONFIG_ROOT).next()[1] if dirs: print "List of available configurations:\n" for d in dirs: print " * {}".format(d) else: print "No configurations available."
python
def do_list(): """ CLI action "list configurations". """ dirs = os.walk(CONFIG_ROOT).next()[1] if dirs: print "List of available configurations:\n" for d in dirs: print " * {}".format(d) else: print "No configurations available."
[ "def", "do_list", "(", ")", ":", "dirs", "=", "os", ".", "walk", "(", "CONFIG_ROOT", ")", ".", "next", "(", ")", "[", "1", "]", "if", "dirs", ":", "print", "\"List of available configurations:\\n\"", "for", "d", "in", "dirs", ":", "print", "\" * {}\"", ...
CLI action "list configurations".
[ "CLI", "action", "list", "configurations", "." ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L93-L103
infinite-library/ghetto
ghetto.py
do_create
def do_create(config, config_dir): """ CLI action "create new configuration". """ if os.path.exists(config_dir): print "Configuration '{}' already exists.".format(config) exit(1) os.makedirs(config_dir) print "Configuration directory created." url = raw_input("RSS URL for processing []: ") torrent_dir = raw_input("Output directory for found .torrent files [{}]: "\ .format(DEFAULT_TORRRENT_DIR)) or DEFAULT_TORRRENT_DIR update_interval = raw_input("Update interval (mins) [{}]: "\ .format(DEFAULT_UPDATE_INTERVAL)) or DEFAULT_UPDATE_INTERVAL editor = os.environ["EDITOR"] config_filter = os.path.join(config_dir, 'filter') if confirm("Do you want to create filters list?", False): call([editor, config_filter]) print "Filter configuration has been saved." config_blacklist = os.path.join(config_dir, 'blacklist') if confirm("Do you want to create blacklist?", False): call([editor, config_filter]) print "Blacklist configuration has been saved." config_file = os.path.join(config_dir, 'config') config_data = json.dumps({ "url": url, "torrent_dir": torrent_dir, "update_interval": update_interval }, sort_keys=True, indent=4, separators=(',', ': ')) with open(config_file, 'w') as f: f.write(config_data) ct = CronTab(user=True) cmd = "{} {} -e {}".format(sys.executable, os.path.abspath(__file__), config) job = ct.new(command=cmd) job.minute.every(update_interval) job.enable() ct.write() print "Crontab updated." print "Config '{}' has been saved.".format(config)
python
def do_create(config, config_dir): """ CLI action "create new configuration". """ if os.path.exists(config_dir): print "Configuration '{}' already exists.".format(config) exit(1) os.makedirs(config_dir) print "Configuration directory created." url = raw_input("RSS URL for processing []: ") torrent_dir = raw_input("Output directory for found .torrent files [{}]: "\ .format(DEFAULT_TORRRENT_DIR)) or DEFAULT_TORRRENT_DIR update_interval = raw_input("Update interval (mins) [{}]: "\ .format(DEFAULT_UPDATE_INTERVAL)) or DEFAULT_UPDATE_INTERVAL editor = os.environ["EDITOR"] config_filter = os.path.join(config_dir, 'filter') if confirm("Do you want to create filters list?", False): call([editor, config_filter]) print "Filter configuration has been saved." config_blacklist = os.path.join(config_dir, 'blacklist') if confirm("Do you want to create blacklist?", False): call([editor, config_filter]) print "Blacklist configuration has been saved." config_file = os.path.join(config_dir, 'config') config_data = json.dumps({ "url": url, "torrent_dir": torrent_dir, "update_interval": update_interval }, sort_keys=True, indent=4, separators=(',', ': ')) with open(config_file, 'w') as f: f.write(config_data) ct = CronTab(user=True) cmd = "{} {} -e {}".format(sys.executable, os.path.abspath(__file__), config) job = ct.new(command=cmd) job.minute.every(update_interval) job.enable() ct.write() print "Crontab updated." print "Config '{}' has been saved.".format(config)
[ "def", "do_create", "(", "config", ",", "config_dir", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "config_dir", ")", ":", "print", "\"Configuration '{}' already exists.\"", ".", "format", "(", "config", ")", "exit", "(", "1", ")", "os", ".", "...
CLI action "create new configuration".
[ "CLI", "action", "create", "new", "configuration", "." ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L106-L153
infinite-library/ghetto
ghetto.py
do_update
def do_update(config, config_dir): """ CLI action "update new configuration". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) config_file = os.path.join(config_dir, 'config') with open(config_file, 'r') as f: old_config_data = json.load(f) old_url = old_config_data['url'] old_torrent_dir = old_config_data['torrent_dir'] old_update_interval = old_config_data['update_interval'] url = raw_input("RSS URL for processing [{}]: "\ .format(old_url)) or old_url torrent_dir = raw_input("Output directory for found .torrent files [{}]: "\ .format(old_torrent_dir)) or old_torrent_dir update_interval = raw_input("Update interval (mins) [{}]: "\ .format(old_update_interval)) or old_update_interval editor = os.environ["EDITOR"] config_filter = os.path.join(config_dir, 'filter') if confirm("Do you want to edit filters list?", False): call([editor, config_filter]) print "Filter configuration has been saved." config_blacklist = os.path.join(config_dir, 'blacklist') if confirm("Do you want to edit blacklist?", False): call([editor, config_filter]) print "Blacklist configuration has been saved." config_data = json.dumps({ "url": url, "torrent_dir": torrent_dir, "update_interval": update_interval }, sort_keys=True, indent=4, separators=(',', ': ')) with open(config_file, 'w') as f: f.write(config_data) ct = CronTab(user=True) for job in ct: if re.match('.*ghetto.*\-e\s{}'.format(config), job.command): ct.remove(job) cmd = "{} {} -e {}".format(sys.executable, os.path.abspath(__file__), config) new_job = ct.new(command=cmd) new_job.minute.every(update_interval) new_job.enable() ct.write() print "Crontab updated." print "Configuration '{}' has been updated.".format(config)
python
def do_update(config, config_dir): """ CLI action "update new configuration". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) config_file = os.path.join(config_dir, 'config') with open(config_file, 'r') as f: old_config_data = json.load(f) old_url = old_config_data['url'] old_torrent_dir = old_config_data['torrent_dir'] old_update_interval = old_config_data['update_interval'] url = raw_input("RSS URL for processing [{}]: "\ .format(old_url)) or old_url torrent_dir = raw_input("Output directory for found .torrent files [{}]: "\ .format(old_torrent_dir)) or old_torrent_dir update_interval = raw_input("Update interval (mins) [{}]: "\ .format(old_update_interval)) or old_update_interval editor = os.environ["EDITOR"] config_filter = os.path.join(config_dir, 'filter') if confirm("Do you want to edit filters list?", False): call([editor, config_filter]) print "Filter configuration has been saved." config_blacklist = os.path.join(config_dir, 'blacklist') if confirm("Do you want to edit blacklist?", False): call([editor, config_filter]) print "Blacklist configuration has been saved." config_data = json.dumps({ "url": url, "torrent_dir": torrent_dir, "update_interval": update_interval }, sort_keys=True, indent=4, separators=(',', ': ')) with open(config_file, 'w') as f: f.write(config_data) ct = CronTab(user=True) for job in ct: if re.match('.*ghetto.*\-e\s{}'.format(config), job.command): ct.remove(job) cmd = "{} {} -e {}".format(sys.executable, os.path.abspath(__file__), config) new_job = ct.new(command=cmd) new_job.minute.every(update_interval) new_job.enable() ct.write() print "Crontab updated." print "Configuration '{}' has been updated.".format(config)
[ "def", "do_update", "(", "config", ",", "config_dir", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "config_dir", ")", ":", "print", "\"Configuration '{}' does not exist.\"", ".", "format", "(", "config", ")", "exit", "(", "1", ")", "config...
CLI action "update new configuration".
[ "CLI", "action", "update", "new", "configuration", "." ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L156-L213
infinite-library/ghetto
ghetto.py
do_remove
def do_remove(config, config_dir): """ CLI action "remove configuration". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) if confirm("Confirm removal of the configuration '{}'".format(config)): shutil.rmtree(config_dir) print "Configuration '{}' has been removed.".format(config) else: print "Removal cancelled."
python
def do_remove(config, config_dir): """ CLI action "remove configuration". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) if confirm("Confirm removal of the configuration '{}'".format(config)): shutil.rmtree(config_dir) print "Configuration '{}' has been removed.".format(config) else: print "Removal cancelled."
[ "def", "do_remove", "(", "config", ",", "config_dir", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "config_dir", ")", ":", "print", "\"Configuration '{}' does not exist.\"", ".", "format", "(", "config", ")", "exit", "(", "1", ")", "if", ...
CLI action "remove configuration".
[ "CLI", "action", "remove", "configuration", "." ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L216-L227
infinite-library/ghetto
ghetto.py
do_exec
def do_exec(config, config_dir): """ CLI action "process the feed from specified configuration". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) print "The parser for '{}' config has been initialized.".format(config) config_file = os.path.join(config_dir, 'config') with open(config_file, 'r') as f: config_data = json.load(f) url = config_data['url'] torrent_dir = config_data['torrent_dir'] ensure_dir(torrent_dir) filters_file = os.path.join(config_dir, 'filter') filters = read_file(filters_file) blacklist_file = os.path.join(config_dir, 'blacklist') blacklist = read_file(blacklist_file) print "Fetching URL {}".format(url) r = requests.get(url) if r.status_code != 200: print "Failed to fetch RSS feed." xml = r.text.encode('utf-8') parser = etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8') tree = etree.fromstring(xml, parser) items = tree.xpath('//item') downloaded = 0 for e in items: e_title = e.xpath('title')[0].text e_link = e.xpath('link')[0].text if not drop_it(e_title, filters, blacklist): downloaded += 1 target_file = os.path.join(torrent_dir, e_title + '.torrent') r = requests.get(e_link, stream=True) with open(target_file, 'wb') as f: for chunk in r.iter_content(4096): f.write(chunk) print "Items found: {}, items downloaded: {}."\ .format(len(items), downloaded)
python
def do_exec(config, config_dir): """ CLI action "process the feed from specified configuration". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) print "The parser for '{}' config has been initialized.".format(config) config_file = os.path.join(config_dir, 'config') with open(config_file, 'r') as f: config_data = json.load(f) url = config_data['url'] torrent_dir = config_data['torrent_dir'] ensure_dir(torrent_dir) filters_file = os.path.join(config_dir, 'filter') filters = read_file(filters_file) blacklist_file = os.path.join(config_dir, 'blacklist') blacklist = read_file(blacklist_file) print "Fetching URL {}".format(url) r = requests.get(url) if r.status_code != 200: print "Failed to fetch RSS feed." xml = r.text.encode('utf-8') parser = etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8') tree = etree.fromstring(xml, parser) items = tree.xpath('//item') downloaded = 0 for e in items: e_title = e.xpath('title')[0].text e_link = e.xpath('link')[0].text if not drop_it(e_title, filters, blacklist): downloaded += 1 target_file = os.path.join(torrent_dir, e_title + '.torrent') r = requests.get(e_link, stream=True) with open(target_file, 'wb') as f: for chunk in r.iter_content(4096): f.write(chunk) print "Items found: {}, items downloaded: {}."\ .format(len(items), downloaded)
[ "def", "do_exec", "(", "config", ",", "config_dir", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "config_dir", ")", ":", "print", "\"Configuration '{}' does not exist.\"", ".", "format", "(", "config", ")", "exit", "(", "1", ")", "print", ...
CLI action "process the feed from specified configuration".
[ "CLI", "action", "process", "the", "feed", "from", "specified", "configuration", "." ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L230-L276
infinite-library/ghetto
ghetto.py
do_filter
def do_filter(config, config_dir): """ CLI action "run editor for filters list". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) editor = os.environ["EDITOR"] config_filter = os.path.join(config_dir, 'filter') call([editor, config_filter]) print "Filter configuration has been updated."
python
def do_filter(config, config_dir): """ CLI action "run editor for filters list". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) editor = os.environ["EDITOR"] config_filter = os.path.join(config_dir, 'filter') call([editor, config_filter]) print "Filter configuration has been updated."
[ "def", "do_filter", "(", "config", ",", "config_dir", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "config_dir", ")", ":", "print", "\"Configuration '{}' does not exist.\"", ".", "format", "(", "config", ")", "exit", "(", "1", ")", "editor...
CLI action "run editor for filters list".
[ "CLI", "action", "run", "editor", "for", "filters", "list", "." ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L279-L291
infinite-library/ghetto
ghetto.py
do_blacklist
def do_blacklist(config, config_dir): """ CLI action "run editor for blacklist". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) editor = os.environ["EDITOR"] config_blacklist = os.path.join(config_dir, 'blacklist') call([editor, config_blacklist]) print "Blacklist configuration has been updated."
python
def do_blacklist(config, config_dir): """ CLI action "run editor for blacklist". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) editor = os.environ["EDITOR"] config_blacklist = os.path.join(config_dir, 'blacklist') call([editor, config_blacklist]) print "Blacklist configuration has been updated."
[ "def", "do_blacklist", "(", "config", ",", "config_dir", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "config_dir", ")", ":", "print", "\"Configuration '{}' does not exist.\"", ".", "format", "(", "config", ")", "exit", "(", "1", ")", "edi...
CLI action "run editor for blacklist".
[ "CLI", "action", "run", "editor", "for", "blacklist", "." ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L294-L306
infinite-library/ghetto
ghetto.py
action
def action(act, config): """ CLI action preprocessor """ if not config: pass elif act is "list": do_list() else: config_dir = os.path.join(CONFIG_ROOT, config) globals()["do_" + act](config, config_dir)
python
def action(act, config): """ CLI action preprocessor """ if not config: pass elif act is "list": do_list() else: config_dir = os.path.join(CONFIG_ROOT, config) globals()["do_" + act](config, config_dir)
[ "def", "action", "(", "act", ",", "config", ")", ":", "if", "not", "config", ":", "pass", "elif", "act", "is", "\"list\"", ":", "do_list", "(", ")", "else", ":", "config_dir", "=", "os", ".", "path", ".", "join", "(", "CONFIG_ROOT", ",", "config", ...
CLI action preprocessor
[ "CLI", "action", "preprocessor" ]
train
https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L309-L319
jreinhardt/constraining-order
src/constrainingorder/__init__.py
Space.is_discrete
def is_discrete(self): """ Return whether this space is discrete """ for domain in self.domains.values(): if not domain.is_discrete(): return False return True
python
def is_discrete(self): """ Return whether this space is discrete """ for domain in self.domains.values(): if not domain.is_discrete(): return False return True
[ "def", "is_discrete", "(", "self", ")", ":", "for", "domain", "in", "self", ".", "domains", ".", "values", "(", ")", ":", "if", "not", "domain", ".", "is_discrete", "(", ")", ":", "return", "False", "return", "True" ]
Return whether this space is discrete
[ "Return", "whether", "this", "space", "is", "discrete" ]
train
https://github.com/jreinhardt/constraining-order/blob/04d00e4cad0fa9bedf15f2e89b8fd667c0495edc/src/constrainingorder/__init__.py#L53-L60
jreinhardt/constraining-order
src/constrainingorder/__init__.py
Space.consistent
def consistent(self,lab): """ Check whether the labeling is consistent with all constraints """ for const in self.constraints: if not const.consistent(lab): return False return True
python
def consistent(self,lab): """ Check whether the labeling is consistent with all constraints """ for const in self.constraints: if not const.consistent(lab): return False return True
[ "def", "consistent", "(", "self", ",", "lab", ")", ":", "for", "const", "in", "self", ".", "constraints", ":", "if", "not", "const", ".", "consistent", "(", "lab", ")", ":", "return", "False", "return", "True" ]
Check whether the labeling is consistent with all constraints
[ "Check", "whether", "the", "labeling", "is", "consistent", "with", "all", "constraints" ]
train
https://github.com/jreinhardt/constraining-order/blob/04d00e4cad0fa9bedf15f2e89b8fd667c0495edc/src/constrainingorder/__init__.py#L61-L68
jreinhardt/constraining-order
src/constrainingorder/__init__.py
Space.satisfied
def satisfied(self,lab): """ Check whether the labeling satisfies all constraints """ for const in self.constraints: if not const.satisfied(lab): return False return True
python
def satisfied(self,lab): """ Check whether the labeling satisfies all constraints """ for const in self.constraints: if not const.satisfied(lab): return False return True
[ "def", "satisfied", "(", "self", ",", "lab", ")", ":", "for", "const", "in", "self", ".", "constraints", ":", "if", "not", "const", ".", "satisfied", "(", "lab", ")", ":", "return", "False", "return", "True" ]
Check whether the labeling satisfies all constraints
[ "Check", "whether", "the", "labeling", "satisfies", "all", "constraints" ]
train
https://github.com/jreinhardt/constraining-order/blob/04d00e4cad0fa9bedf15f2e89b8fd667c0495edc/src/constrainingorder/__init__.py#L69-L76
duniter/duniter-python-api
duniterpy/documents/membership.py
Membership.from_inline
def from_inline(cls: Type[MembershipType], version: int, currency: str, membership_type: str, inline: str) -> MembershipType: """ Return Membership instance from inline format :param version: Version of the document :param currency: Name of the currency :param membership_type: "IN" or "OUT" to enter or exit membership :param inline: Inline string format :return: """ data = Membership.re_inline.match(inline) if data is None: raise MalformedDocumentError("Inline membership ({0})".format(inline)) issuer = data.group(1) signature = data.group(2) membership_ts = BlockUID.from_str(data.group(3)) identity_ts = BlockUID.from_str(data.group(4)) uid = data.group(5) return cls(version, currency, issuer, membership_ts, membership_type, uid, identity_ts, signature)
python
def from_inline(cls: Type[MembershipType], version: int, currency: str, membership_type: str, inline: str) -> MembershipType: """ Return Membership instance from inline format :param version: Version of the document :param currency: Name of the currency :param membership_type: "IN" or "OUT" to enter or exit membership :param inline: Inline string format :return: """ data = Membership.re_inline.match(inline) if data is None: raise MalformedDocumentError("Inline membership ({0})".format(inline)) issuer = data.group(1) signature = data.group(2) membership_ts = BlockUID.from_str(data.group(3)) identity_ts = BlockUID.from_str(data.group(4)) uid = data.group(5) return cls(version, currency, issuer, membership_ts, membership_type, uid, identity_ts, signature)
[ "def", "from_inline", "(", "cls", ":", "Type", "[", "MembershipType", "]", ",", "version", ":", "int", ",", "currency", ":", "str", ",", "membership_type", ":", "str", ",", "inline", ":", "str", ")", "->", "MembershipType", ":", "data", "=", "Membership"...
Return Membership instance from inline format :param version: Version of the document :param currency: Name of the currency :param membership_type: "IN" or "OUT" to enter or exit membership :param inline: Inline string format :return:
[ "Return", "Membership", "instance", "from", "inline", "format" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/membership.py#L76-L95
duniter/duniter-python-api
duniterpy/documents/membership.py
Membership.from_signed_raw
def from_signed_raw(cls: Type[MembershipType], signed_raw: str) -> MembershipType: """ Return Membership instance from signed raw format :param signed_raw: Signed raw format string :return: """ lines = signed_raw.splitlines(True) n = 0 version = int(Membership.parse_field("Version", lines[n])) n += 1 Membership.parse_field("Type", lines[n]) n += 1 currency = Membership.parse_field("Currency", lines[n]) n += 1 issuer = Membership.parse_field("Issuer", lines[n]) n += 1 membership_ts = BlockUID.from_str(Membership.parse_field("Block", lines[n])) n += 1 membership_type = Membership.parse_field("Membership", lines[n]) n += 1 uid = Membership.parse_field("UserID", lines[n]) n += 1 identity_ts = BlockUID.from_str(Membership.parse_field("CertTS", lines[n])) n += 1 signature = Membership.parse_field("Signature", lines[n]) n += 1 return cls(version, currency, issuer, membership_ts, membership_type, uid, identity_ts, signature)
python
def from_signed_raw(cls: Type[MembershipType], signed_raw: str) -> MembershipType: """ Return Membership instance from signed raw format :param signed_raw: Signed raw format string :return: """ lines = signed_raw.splitlines(True) n = 0 version = int(Membership.parse_field("Version", lines[n])) n += 1 Membership.parse_field("Type", lines[n]) n += 1 currency = Membership.parse_field("Currency", lines[n]) n += 1 issuer = Membership.parse_field("Issuer", lines[n]) n += 1 membership_ts = BlockUID.from_str(Membership.parse_field("Block", lines[n])) n += 1 membership_type = Membership.parse_field("Membership", lines[n]) n += 1 uid = Membership.parse_field("UserID", lines[n]) n += 1 identity_ts = BlockUID.from_str(Membership.parse_field("CertTS", lines[n])) n += 1 signature = Membership.parse_field("Signature", lines[n]) n += 1 return cls(version, currency, issuer, membership_ts, membership_type, uid, identity_ts, signature)
[ "def", "from_signed_raw", "(", "cls", ":", "Type", "[", "MembershipType", "]", ",", "signed_raw", ":", "str", ")", "->", "MembershipType", ":", "lines", "=", "signed_raw", ".", "splitlines", "(", "True", ")", "n", "=", "0", "version", "=", "int", "(", ...
Return Membership instance from signed raw format :param signed_raw: Signed raw format string :return:
[ "Return", "Membership", "instance", "from", "signed", "raw", "format" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/membership.py#L98-L136
duniter/duniter-python-api
duniterpy/documents/membership.py
Membership.raw
def raw(self) -> str: """ Return signed raw format string of the Membership instance :return: """ return """Version: {0} Type: Membership Currency: {1} Issuer: {2} Block: {3} Membership: {4} UserID: {5} CertTS: {6} """.format(self.version, self.currency, self.issuer, self.membership_ts, self.membership_type, self.uid, self.identity_ts)
python
def raw(self) -> str: """ Return signed raw format string of the Membership instance :return: """ return """Version: {0} Type: Membership Currency: {1} Issuer: {2} Block: {3} Membership: {4} UserID: {5} CertTS: {6} """.format(self.version, self.currency, self.issuer, self.membership_ts, self.membership_type, self.uid, self.identity_ts)
[ "def", "raw", "(", "self", ")", "->", "str", ":", "return", "\"\"\"Version: {0}\nType: Membership\nCurrency: {1}\nIssuer: {2}\nBlock: {3}\nMembership: {4}\nUserID: {5}\nCertTS: {6}\n\"\"\"", ".", "format", "(", "self", ".", "version", ",", "self", ".", "currency", ",", "sel...
Return signed raw format string of the Membership instance :return:
[ "Return", "signed", "raw", "format", "string", "of", "the", "Membership", "instance" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/membership.py#L138-L158
duniter/duniter-python-api
duniterpy/documents/membership.py
Membership.inline
def inline(self) -> str: """ Return inline string format of the Membership instance :return: """ return "{0}:{1}:{2}:{3}:{4}".format(self.issuer, self.signatures[0], self.membership_ts, self.identity_ts, self.uid)
python
def inline(self) -> str: """ Return inline string format of the Membership instance :return: """ return "{0}:{1}:{2}:{3}:{4}".format(self.issuer, self.signatures[0], self.membership_ts, self.identity_ts, self.uid)
[ "def", "inline", "(", "self", ")", "->", "str", ":", "return", "\"{0}:{1}:{2}:{3}:{4}\"", ".", "format", "(", "self", ".", "issuer", ",", "self", ".", "signatures", "[", "0", "]", ",", "self", ".", "membership_ts", ",", "self", ".", "identity_ts", ",", ...
Return inline string format of the Membership instance :return:
[ "Return", "inline", "string", "format", "of", "the", "Membership", "instance", ":", "return", ":" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/membership.py#L160-L169
nikoladimitroff/Adder
adder/logic.py
is_subsumed_by
def is_subsumed_by(x, y): """ Returns true if y subsumes x (for example P(x) subsumes P(A) as it is more abstract) """ varsX = __split_expression(x)[1] theta = unify(x, y) if theta is problem.FAILURE: return False return all(__is_variable(theta[var]) for var in theta.keys() if var in varsX)
python
def is_subsumed_by(x, y): """ Returns true if y subsumes x (for example P(x) subsumes P(A) as it is more abstract) """ varsX = __split_expression(x)[1] theta = unify(x, y) if theta is problem.FAILURE: return False return all(__is_variable(theta[var]) for var in theta.keys() if var in varsX)
[ "def", "is_subsumed_by", "(", "x", ",", "y", ")", ":", "varsX", "=", "__split_expression", "(", "x", ")", "[", "1", "]", "theta", "=", "unify", "(", "x", ",", "y", ")", "if", "theta", "is", "problem", ".", "FAILURE", ":", "return", "False", "return...
Returns true if y subsumes x (for example P(x) subsumes P(A) as it is more abstract)
[ "Returns", "true", "if", "y", "subsumes", "x", "(", "for", "example", "P", "(", "x", ")", "subsumes", "P", "(", "A", ")", "as", "it", "is", "more", "abstract", ")" ]
train
https://github.com/nikoladimitroff/Adder/blob/034f301d3a850d2cbeb2b17c8973f363f90f390e/adder/logic.py#L418-L428
scieloorg/processing
clients/search.py
Search._do_request
def _do_request(self, url, params=None, data=None, headers=None): """ Realiza as requisições diversas utilizando a biblioteca requests, tratando de forma genérica as exceções. """ if not headers: headers = {'content-type': 'application/json'} try: response = requests.get( url, params=params, data=data, headers=headers) except: return None if response.status_code == 200: return response
python
def _do_request(self, url, params=None, data=None, headers=None): """ Realiza as requisições diversas utilizando a biblioteca requests, tratando de forma genérica as exceções. """ if not headers: headers = {'content-type': 'application/json'} try: response = requests.get( url, params=params, data=data, headers=headers) except: return None if response.status_code == 200: return response
[ "def", "_do_request", "(", "self", ",", "url", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "not", "headers", ":", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", "try", ":", ...
Realiza as requisições diversas utilizando a biblioteca requests, tratando de forma genérica as exceções.
[ "Realiza", "as", "requisições", "diversas", "utilizando", "a", "biblioteca", "requests", "tratando", "de", "forma", "genérica", "as", "exceções", "." ]
train
https://github.com/scieloorg/processing/blob/629b50b45ba7a176651cd3bfcdb441dab6fddfcc/clients/search.py#L28-L44
scieloorg/processing
clients/search.py
Search.update_document_indicators
def update_document_indicators(self, doc_id, citations, accesses): """ Atualiza os indicadores de acessos e citações de um determinado doc_id. exemplo de doc_id: S0021-25712009000400007-spa """ headers = {'content-type': 'application/json'} data = { "add": { "doc": { "id": doc_id } } } if citations: data['add']['doc']['total_received'] = {'set': str(citations)} if accesses: data['add']['doc']['total_access'] = {'set': str(accesses)} params = {'wt': 'json'} response = self._do_request( self.UPDATE_ENDPOINT, params=params, data=json.dumps(data), headers=headers ) if not response: logger.debug('Document (%s) could not be updated' % doc_id) logger.debug('Document (%s) updated' % doc_id)
python
def update_document_indicators(self, doc_id, citations, accesses): """ Atualiza os indicadores de acessos e citações de um determinado doc_id. exemplo de doc_id: S0021-25712009000400007-spa """ headers = {'content-type': 'application/json'} data = { "add": { "doc": { "id": doc_id } } } if citations: data['add']['doc']['total_received'] = {'set': str(citations)} if accesses: data['add']['doc']['total_access'] = {'set': str(accesses)} params = {'wt': 'json'} response = self._do_request( self.UPDATE_ENDPOINT, params=params, data=json.dumps(data), headers=headers ) if not response: logger.debug('Document (%s) could not be updated' % doc_id) logger.debug('Document (%s) updated' % doc_id)
[ "def", "update_document_indicators", "(", "self", ",", "doc_id", ",", "citations", ",", "accesses", ")", ":", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", "data", "=", "{", "\"add\"", ":", "{", "\"doc\"", ":", "{", "\"id\"", ":", ...
Atualiza os indicadores de acessos e citações de um determinado doc_id. exemplo de doc_id: S0021-25712009000400007-spa
[ "Atualiza", "os", "indicadores", "de", "acessos", "e", "citações", "de", "um", "determinado", "doc_id", ".", "exemplo", "de", "doc_id", ":", "S0021", "-", "25712009000400007", "-", "spa" ]
train
https://github.com/scieloorg/processing/blob/629b50b45ba7a176651cd3bfcdb441dab6fddfcc/clients/search.py#L46-L81
scieloorg/processing
clients/search.py
Search._commit
def _commit(self): """ Envia requisição de commit do indice através da API. """ params = {'commit': 'true'} response = self._do_request( self.UPDATE_ENDPOINT, params=params ) if response and response.status_code == 200: logger.debug('Index commited') return None logger.warning('Fail to commite index')
python
def _commit(self): """ Envia requisição de commit do indice através da API. """ params = {'commit': 'true'} response = self._do_request( self.UPDATE_ENDPOINT, params=params ) if response and response.status_code == 200: logger.debug('Index commited') return None logger.warning('Fail to commite index')
[ "def", "_commit", "(", "self", ")", ":", "params", "=", "{", "'commit'", ":", "'true'", "}", "response", "=", "self", ".", "_do_request", "(", "self", ".", "UPDATE_ENDPOINT", ",", "params", "=", "params", ")", "if", "response", "and", "response", ".", ...
Envia requisição de commit do indice através da API.
[ "Envia", "requisição", "de", "commit", "do", "indice", "através", "da", "API", "." ]
train
https://github.com/scieloorg/processing/blob/629b50b45ba7a176651cd3bfcdb441dab6fddfcc/clients/search.py#L83-L99
appstore-zencore/daemon-application
src/daemon_application/base.py
make_basic_daemon
def make_basic_daemon(workspace=None): """Make basic daemon. """ workspace = workspace or os.getcwd() # first fork if os.fork(): os._exit(0) # change env os.chdir(workspace) os.setsid() os.umask(0o22) # second fork if os.fork(): os._exit(0) # reset stdin/stdout/stderr to /dev/null null = os.open('/dev/null', os.O_RDWR) try: for i in range(0, 3): try: os.dup2(null, i) except OSError as error: if error.errno != errno.EBADF: raise finally: os.close(null)
python
def make_basic_daemon(workspace=None): """Make basic daemon. """ workspace = workspace or os.getcwd() # first fork if os.fork(): os._exit(0) # change env os.chdir(workspace) os.setsid() os.umask(0o22) # second fork if os.fork(): os._exit(0) # reset stdin/stdout/stderr to /dev/null null = os.open('/dev/null', os.O_RDWR) try: for i in range(0, 3): try: os.dup2(null, i) except OSError as error: if error.errno != errno.EBADF: raise finally: os.close(null)
[ "def", "make_basic_daemon", "(", "workspace", "=", "None", ")", ":", "workspace", "=", "workspace", "or", "os", ".", "getcwd", "(", ")", "# first fork", "if", "os", ".", "fork", "(", ")", ":", "os", ".", "_exit", "(", "0", ")", "# change env", "os", ...
Make basic daemon.
[ "Make", "basic", "daemon", "." ]
train
https://github.com/appstore-zencore/daemon-application/blob/e8d716dbaa7becfda95e144cce51558b0c9615e5/src/daemon_application/base.py#L28-L52
appstore-zencore/daemon-application
src/daemon_application/base.py
process_kill
def process_kill(pid, sig=None): """Send signal to process. """ sig = sig or signal.SIGTERM os.kill(pid, sig)
python
def process_kill(pid, sig=None): """Send signal to process. """ sig = sig or signal.SIGTERM os.kill(pid, sig)
[ "def", "process_kill", "(", "pid", ",", "sig", "=", "None", ")", ":", "sig", "=", "sig", "or", "signal", ".", "SIGTERM", "os", ".", "kill", "(", "pid", ",", "sig", ")" ]
Send signal to process.
[ "Send", "signal", "to", "process", "." ]
train
https://github.com/appstore-zencore/daemon-application/blob/e8d716dbaa7becfda95e144cce51558b0c9615e5/src/daemon_application/base.py#L55-L59
appstore-zencore/daemon-application
src/daemon_application/base.py
load_pid
def load_pid(pidfile): """read pid from pidfile. """ if pidfile and os.path.isfile(pidfile): with open(pidfile, "r", encoding="utf-8") as fobj: return int(fobj.readline().strip()) return 0
python
def load_pid(pidfile): """read pid from pidfile. """ if pidfile and os.path.isfile(pidfile): with open(pidfile, "r", encoding="utf-8") as fobj: return int(fobj.readline().strip()) return 0
[ "def", "load_pid", "(", "pidfile", ")", ":", "if", "pidfile", "and", "os", ".", "path", ".", "isfile", "(", "pidfile", ")", ":", "with", "open", "(", "pidfile", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "fobj", ":", "return", "int",...
read pid from pidfile.
[ "read", "pid", "from", "pidfile", "." ]
train
https://github.com/appstore-zencore/daemon-application/blob/e8d716dbaa7becfda95e144cce51558b0c9615e5/src/daemon_application/base.py#L62-L68
appstore-zencore/daemon-application
src/daemon_application/base.py
write_pidfile
def write_pidfile(pidfile): """write current pid to pidfile. """ pid = os.getpid() if pidfile: with open(pidfile, "w", encoding="utf-8") as fobj: fobj.write(six.u(str(pid))) return pid
python
def write_pidfile(pidfile): """write current pid to pidfile. """ pid = os.getpid() if pidfile: with open(pidfile, "w", encoding="utf-8") as fobj: fobj.write(six.u(str(pid))) return pid
[ "def", "write_pidfile", "(", "pidfile", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "if", "pidfile", ":", "with", "open", "(", "pidfile", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "fobj", ":", "fobj", ".", "write", "(", "...
write current pid to pidfile.
[ "write", "current", "pid", "to", "pidfile", "." ]
train
https://github.com/appstore-zencore/daemon-application/blob/e8d716dbaa7becfda95e144cce51558b0c9615e5/src/daemon_application/base.py#L71-L78
appstore-zencore/daemon-application
src/daemon_application/base.py
is_running
def is_running(pid): """check if the process with given pid still running """ process = get_process(pid) if process and process.is_running() and process.status() != "zombie": return True else: return False
python
def is_running(pid): """check if the process with given pid still running """ process = get_process(pid) if process and process.is_running() and process.status() != "zombie": return True else: return False
[ "def", "is_running", "(", "pid", ")", ":", "process", "=", "get_process", "(", "pid", ")", "if", "process", "and", "process", ".", "is_running", "(", ")", "and", "process", ".", "status", "(", ")", "!=", "\"zombie\"", ":", "return", "True", "else", ":"...
check if the process with given pid still running
[ "check", "if", "the", "process", "with", "given", "pid", "still", "running" ]
train
https://github.com/appstore-zencore/daemon-application/blob/e8d716dbaa7becfda95e144cce51558b0c9615e5/src/daemon_application/base.py#L90-L97
appstore-zencore/daemon-application
src/daemon_application/base.py
clean_pid_file
def clean_pid_file(pidfile): """clean pid file. """ if pidfile and os.path.exists(pidfile): os.unlink(pidfile)
python
def clean_pid_file(pidfile): """clean pid file. """ if pidfile and os.path.exists(pidfile): os.unlink(pidfile)
[ "def", "clean_pid_file", "(", "pidfile", ")", ":", "if", "pidfile", "and", "os", ".", "path", ".", "exists", "(", "pidfile", ")", ":", "os", ".", "unlink", "(", "pidfile", ")" ]
clean pid file.
[ "clean", "pid", "file", "." ]
train
https://github.com/appstore-zencore/daemon-application/blob/e8d716dbaa7becfda95e144cce51558b0c9615e5/src/daemon_application/base.py#L100-L104
appstore-zencore/daemon-application
src/daemon_application/base.py
daemon_start
def daemon_start(main, pidfile, daemon=True, workspace=None): """Start application in background mode if required and available. If not then in front mode. """ logger.debug("start daemon application pidfile={pidfile} daemon={daemon} workspace={workspace}.".format(pidfile=pidfile, daemon=daemon, workspace=workspace)) new_pid = os.getpid() workspace = workspace or os.getcwd() os.chdir(workspace) daemon_flag = False if pidfile and daemon: old_pid = load_pid(pidfile) if old_pid: logger.debug("pidfile {pidfile} already exists, pid={pid}.".format(pidfile=pidfile, pid=old_pid)) # if old service is running, just exit. if old_pid and is_running(old_pid): error_message = "Service is running in process: {pid}.".format(pid=old_pid) logger.error(error_message) six.print_(error_message, file=os.sys.stderr) os.sys.exit(95) # clean old pid file. clean_pid_file(pidfile) # start as background mode if required and available. if daemon and os.name == "posix": make_basic_daemon() daemon_flag = True if daemon_flag: logger.info("Start application in DAEMON mode, pidfile={pidfile} pid={pid}".format(pidfile=pidfile, pid=new_pid)) else: logger.info("Start application in FRONT mode, pid={pid}.".format(pid=new_pid)) write_pidfile(pidfile) atexit.register(clean_pid_file, pidfile) main() return
python
def daemon_start(main, pidfile, daemon=True, workspace=None): """Start application in background mode if required and available. If not then in front mode. """ logger.debug("start daemon application pidfile={pidfile} daemon={daemon} workspace={workspace}.".format(pidfile=pidfile, daemon=daemon, workspace=workspace)) new_pid = os.getpid() workspace = workspace or os.getcwd() os.chdir(workspace) daemon_flag = False if pidfile and daemon: old_pid = load_pid(pidfile) if old_pid: logger.debug("pidfile {pidfile} already exists, pid={pid}.".format(pidfile=pidfile, pid=old_pid)) # if old service is running, just exit. if old_pid and is_running(old_pid): error_message = "Service is running in process: {pid}.".format(pid=old_pid) logger.error(error_message) six.print_(error_message, file=os.sys.stderr) os.sys.exit(95) # clean old pid file. clean_pid_file(pidfile) # start as background mode if required and available. if daemon and os.name == "posix": make_basic_daemon() daemon_flag = True if daemon_flag: logger.info("Start application in DAEMON mode, pidfile={pidfile} pid={pid}".format(pidfile=pidfile, pid=new_pid)) else: logger.info("Start application in FRONT mode, pid={pid}.".format(pid=new_pid)) write_pidfile(pidfile) atexit.register(clean_pid_file, pidfile) main() return
[ "def", "daemon_start", "(", "main", ",", "pidfile", ",", "daemon", "=", "True", ",", "workspace", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"start daemon application pidfile={pidfile} daemon={daemon} workspace={workspace}.\"", ".", "format", "(", "pidfile"...
Start application in background mode if required and available. If not then in front mode.
[ "Start", "application", "in", "background", "mode", "if", "required", "and", "available", ".", "If", "not", "then", "in", "front", "mode", "." ]
train
https://github.com/appstore-zencore/daemon-application/blob/e8d716dbaa7becfda95e144cce51558b0c9615e5/src/daemon_application/base.py#L107-L138