repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
bpython/curtsies
curtsies/formatstring.py
FmtStr.from_str
def from_str(cls, s): # type: (Union[Text, bytes]) -> FmtStr r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue')+"|") '|'+on_blue(red('hey'))+'|' >>> fmtstr('|\x1b[31m\x1b[44mhey\x1b[49m\x1b[39m|') '|'+on_blue(red('hey'))+'|' """ if '\x1b[' in s: try: tokens_and_strings = parse(s) except ValueError: return FmtStr(Chunk(remove_ansi(s))) else: chunks = [] cur_fmt = {} for x in tokens_and_strings: if isinstance(x, dict): cur_fmt.update(x) elif isinstance(x, (bytes, unicode)): atts = parse_args('', dict((k, v) for k, v in cur_fmt.items() if v is not None)) chunks.append(Chunk(x, atts=atts)) else: raise Exception("logic error") return FmtStr(*chunks) else: return FmtStr(Chunk(s))
python
def from_str(cls, s): # type: (Union[Text, bytes]) -> FmtStr r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue')+"|") '|'+on_blue(red('hey'))+'|' >>> fmtstr('|\x1b[31m\x1b[44mhey\x1b[49m\x1b[39m|') '|'+on_blue(red('hey'))+'|' """ if '\x1b[' in s: try: tokens_and_strings = parse(s) except ValueError: return FmtStr(Chunk(remove_ansi(s))) else: chunks = [] cur_fmt = {} for x in tokens_and_strings: if isinstance(x, dict): cur_fmt.update(x) elif isinstance(x, (bytes, unicode)): atts = parse_args('', dict((k, v) for k, v in cur_fmt.items() if v is not None)) chunks.append(Chunk(x, atts=atts)) else: raise Exception("logic error") return FmtStr(*chunks) else: return FmtStr(Chunk(s))
[ "def", "from_str", "(", "cls", ",", "s", ")", ":", "# type: (Union[Text, bytes]) -> FmtStr", "if", "'\\x1b['", "in", "s", ":", "try", ":", "tokens_and_strings", "=", "parse", "(", "s", ")", "except", "ValueError", ":", "return", "FmtStr", "(", "Chunk", "(", "remove_ansi", "(", "s", ")", ")", ")", "else", ":", "chunks", "=", "[", "]", "cur_fmt", "=", "{", "}", "for", "x", "in", "tokens_and_strings", ":", "if", "isinstance", "(", "x", ",", "dict", ")", ":", "cur_fmt", ".", "update", "(", "x", ")", "elif", "isinstance", "(", "x", ",", "(", "bytes", ",", "unicode", ")", ")", ":", "atts", "=", "parse_args", "(", "''", ",", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "cur_fmt", ".", "items", "(", ")", "if", "v", "is", "not", "None", ")", ")", "chunks", ".", "append", "(", "Chunk", "(", "x", ",", "atts", "=", "atts", ")", ")", "else", ":", "raise", "Exception", "(", "\"logic error\"", ")", "return", "FmtStr", "(", "*", "chunks", ")", "else", ":", "return", "FmtStr", "(", "Chunk", "(", "s", ")", ")" ]
r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue')+"|") '|'+on_blue(red('hey'))+'|' >>> fmtstr('|\x1b[31m\x1b[44mhey\x1b[49m\x1b[39m|') '|'+on_blue(red('hey'))+'|'
[ "r", "Return", "a", "FmtStr", "representing", "input", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L239-L273
bpython/curtsies
curtsies/formatstring.py
FmtStr.copy_with_new_str
def copy_with_new_str(self, new_str): """Copies the current FmtStr's attributes while changing its string.""" # What to do when there are multiple Chunks with conflicting atts? old_atts = dict((att, value) for bfs in self.chunks for (att, value) in bfs.atts.items()) return FmtStr(Chunk(new_str, old_atts))
python
def copy_with_new_str(self, new_str): """Copies the current FmtStr's attributes while changing its string.""" # What to do when there are multiple Chunks with conflicting atts? old_atts = dict((att, value) for bfs in self.chunks for (att, value) in bfs.atts.items()) return FmtStr(Chunk(new_str, old_atts))
[ "def", "copy_with_new_str", "(", "self", ",", "new_str", ")", ":", "# What to do when there are multiple Chunks with conflicting atts?", "old_atts", "=", "dict", "(", "(", "att", ",", "value", ")", "for", "bfs", "in", "self", ".", "chunks", "for", "(", "att", ",", "value", ")", "in", "bfs", ".", "atts", ".", "items", "(", ")", ")", "return", "FmtStr", "(", "Chunk", "(", "new_str", ",", "old_atts", ")", ")" ]
Copies the current FmtStr's attributes while changing its string.
[ "Copies", "the", "current", "FmtStr", "s", "attributes", "while", "changing", "its", "string", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L275-L280
bpython/curtsies
curtsies/formatstring.py
FmtStr.setitem
def setitem(self, startindex, fs): """Shim for easily converting old __setitem__ calls""" return self.setslice_with_length(startindex, startindex+1, fs, len(self))
python
def setitem(self, startindex, fs): """Shim for easily converting old __setitem__ calls""" return self.setslice_with_length(startindex, startindex+1, fs, len(self))
[ "def", "setitem", "(", "self", ",", "startindex", ",", "fs", ")", ":", "return", "self", ".", "setslice_with_length", "(", "startindex", ",", "startindex", "+", "1", ",", "fs", ",", "len", "(", "self", ")", ")" ]
Shim for easily converting old __setitem__ calls
[ "Shim", "for", "easily", "converting", "old", "__setitem__", "calls" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L282-L284
bpython/curtsies
curtsies/formatstring.py
FmtStr.setslice_with_length
def setslice_with_length(self, startindex, endindex, fs, length): """Shim for easily converting old __setitem__ calls""" if len(self) < startindex: fs = ' '*(startindex - len(self)) + fs if len(self) > endindex: fs = fs + ' '*(endindex - startindex - len(fs)) assert len(fs) == endindex - startindex, (len(fs), startindex, endindex) result = self.splice(fs, startindex, endindex) assert len(result) <= length return result
python
def setslice_with_length(self, startindex, endindex, fs, length): """Shim for easily converting old __setitem__ calls""" if len(self) < startindex: fs = ' '*(startindex - len(self)) + fs if len(self) > endindex: fs = fs + ' '*(endindex - startindex - len(fs)) assert len(fs) == endindex - startindex, (len(fs), startindex, endindex) result = self.splice(fs, startindex, endindex) assert len(result) <= length return result
[ "def", "setslice_with_length", "(", "self", ",", "startindex", ",", "endindex", ",", "fs", ",", "length", ")", ":", "if", "len", "(", "self", ")", "<", "startindex", ":", "fs", "=", "' '", "*", "(", "startindex", "-", "len", "(", "self", ")", ")", "+", "fs", "if", "len", "(", "self", ")", ">", "endindex", ":", "fs", "=", "fs", "+", "' '", "*", "(", "endindex", "-", "startindex", "-", "len", "(", "fs", ")", ")", "assert", "len", "(", "fs", ")", "==", "endindex", "-", "startindex", ",", "(", "len", "(", "fs", ")", ",", "startindex", ",", "endindex", ")", "result", "=", "self", ".", "splice", "(", "fs", ",", "startindex", ",", "endindex", ")", "assert", "len", "(", "result", ")", "<=", "length", "return", "result" ]
Shim for easily converting old __setitem__ calls
[ "Shim", "for", "easily", "converting", "old", "__setitem__", "calls" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L286-L295
bpython/curtsies
curtsies/formatstring.py
FmtStr.splice
def splice(self, new_str, start, end=None): """Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided, new_str will replace the substring self.s[start:end-1]. """ if len(new_str) == 0: return self new_fs = new_str if isinstance(new_str, FmtStr) else fmtstr(new_str) assert len(new_fs.chunks) > 0, (new_fs.chunks, new_fs) new_components = [] inserted = False if end is None: end = start tail = None for bfs, bfs_start, bfs_end in zip(self.chunks, self.divides[:-1], self.divides[1:]): if end == bfs_start == 0: new_components.extend(new_fs.chunks) new_components.append(bfs) inserted = True elif bfs_start <= start < bfs_end: divide = start - bfs_start head = Chunk(bfs.s[:divide], atts=bfs.atts) tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.extend([head] + new_fs.chunks) inserted = True if bfs_start < end < bfs_end: tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.append(tail) elif bfs_start < end < bfs_end: divide = start - bfs_start tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.append(tail) elif bfs_start >= end or bfs_end <= start: new_components.append(bfs) if not inserted: new_components.extend(new_fs.chunks) inserted = True return FmtStr(*[s for s in new_components if s.s])
python
def splice(self, new_str, start, end=None): """Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided, new_str will replace the substring self.s[start:end-1]. """ if len(new_str) == 0: return self new_fs = new_str if isinstance(new_str, FmtStr) else fmtstr(new_str) assert len(new_fs.chunks) > 0, (new_fs.chunks, new_fs) new_components = [] inserted = False if end is None: end = start tail = None for bfs, bfs_start, bfs_end in zip(self.chunks, self.divides[:-1], self.divides[1:]): if end == bfs_start == 0: new_components.extend(new_fs.chunks) new_components.append(bfs) inserted = True elif bfs_start <= start < bfs_end: divide = start - bfs_start head = Chunk(bfs.s[:divide], atts=bfs.atts) tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.extend([head] + new_fs.chunks) inserted = True if bfs_start < end < bfs_end: tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.append(tail) elif bfs_start < end < bfs_end: divide = start - bfs_start tail = Chunk(bfs.s[end - bfs_start:], atts=bfs.atts) new_components.append(tail) elif bfs_start >= end or bfs_end <= start: new_components.append(bfs) if not inserted: new_components.extend(new_fs.chunks) inserted = True return FmtStr(*[s for s in new_components if s.s])
[ "def", "splice", "(", "self", ",", "new_str", ",", "start", ",", "end", "=", "None", ")", ":", "if", "len", "(", "new_str", ")", "==", "0", ":", "return", "self", "new_fs", "=", "new_str", "if", "isinstance", "(", "new_str", ",", "FmtStr", ")", "else", "fmtstr", "(", "new_str", ")", "assert", "len", "(", "new_fs", ".", "chunks", ")", ">", "0", ",", "(", "new_fs", ".", "chunks", ",", "new_fs", ")", "new_components", "=", "[", "]", "inserted", "=", "False", "if", "end", "is", "None", ":", "end", "=", "start", "tail", "=", "None", "for", "bfs", ",", "bfs_start", ",", "bfs_end", "in", "zip", "(", "self", ".", "chunks", ",", "self", ".", "divides", "[", ":", "-", "1", "]", ",", "self", ".", "divides", "[", "1", ":", "]", ")", ":", "if", "end", "==", "bfs_start", "==", "0", ":", "new_components", ".", "extend", "(", "new_fs", ".", "chunks", ")", "new_components", ".", "append", "(", "bfs", ")", "inserted", "=", "True", "elif", "bfs_start", "<=", "start", "<", "bfs_end", ":", "divide", "=", "start", "-", "bfs_start", "head", "=", "Chunk", "(", "bfs", ".", "s", "[", ":", "divide", "]", ",", "atts", "=", "bfs", ".", "atts", ")", "tail", "=", "Chunk", "(", "bfs", ".", "s", "[", "end", "-", "bfs_start", ":", "]", ",", "atts", "=", "bfs", ".", "atts", ")", "new_components", ".", "extend", "(", "[", "head", "]", "+", "new_fs", ".", "chunks", ")", "inserted", "=", "True", "if", "bfs_start", "<", "end", "<", "bfs_end", ":", "tail", "=", "Chunk", "(", "bfs", ".", "s", "[", "end", "-", "bfs_start", ":", "]", ",", "atts", "=", "bfs", ".", "atts", ")", "new_components", ".", "append", "(", "tail", ")", "elif", "bfs_start", "<", "end", "<", "bfs_end", ":", "divide", "=", "start", "-", "bfs_start", "tail", "=", "Chunk", "(", "bfs", ".", "s", "[", "end", "-", "bfs_start", ":", "]", ",", "atts", "=", "bfs", ".", "atts", ")", "new_components", ".", "append", "(", "tail", ")", "elif", "bfs_start", ">=", "end", "or", "bfs_end", "<=", "start", ":", "new_components", ".", "append", "(", "bfs", ")", "if", "not", "inserted", ":", "new_components", ".", "extend", "(", "new_fs", ".", "chunks", ")", "inserted", "=", "True", "return", "FmtStr", "(", "*", "[", "s", "for", "s", "in", "new_components", "if", "s", ".", "s", "]", ")" ]
Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided, new_str will replace the substring self.s[start:end-1].
[ "Returns", "a", "new", "FmtStr", "with", "the", "input", "string", "spliced", "into", "the", "the", "original", "FmtStr", "at", "start", "and", "end", ".", "If", "end", "is", "provided", "new_str", "will", "replace", "the", "substring", "self", ".", "s", "[", "start", ":", "end", "-", "1", "]", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L297-L343
bpython/curtsies
curtsies/formatstring.py
FmtStr.copy_with_new_atts
def copy_with_new_atts(self, **attributes): """Returns a new FmtStr with the same content but new formatting""" return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes)) for bfs in self.chunks])
python
def copy_with_new_atts(self, **attributes): """Returns a new FmtStr with the same content but new formatting""" return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes)) for bfs in self.chunks])
[ "def", "copy_with_new_atts", "(", "self", ",", "*", "*", "attributes", ")", ":", "return", "FmtStr", "(", "*", "[", "Chunk", "(", "bfs", ".", "s", ",", "bfs", ".", "atts", ".", "extend", "(", "attributes", ")", ")", "for", "bfs", "in", "self", ".", "chunks", "]", ")" ]
Returns a new FmtStr with the same content but new formatting
[ "Returns", "a", "new", "FmtStr", "with", "the", "same", "content", "but", "new", "formatting" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L348-L351
bpython/curtsies
curtsies/formatstring.py
FmtStr.join
def join(self, iterable): """Joins an iterable yielding strings or FmtStrs with self as separator""" before = [] chunks = [] for i, s in enumerate(iterable): chunks.extend(before) before = self.chunks if isinstance(s, FmtStr): chunks.extend(s.chunks) elif isinstance(s, (bytes, unicode)): chunks.extend(fmtstr(s).chunks) #TODO just make a chunk directly else: raise TypeError("expected str or FmtStr, %r found" % type(s)) return FmtStr(*chunks)
python
def join(self, iterable): """Joins an iterable yielding strings or FmtStrs with self as separator""" before = [] chunks = [] for i, s in enumerate(iterable): chunks.extend(before) before = self.chunks if isinstance(s, FmtStr): chunks.extend(s.chunks) elif isinstance(s, (bytes, unicode)): chunks.extend(fmtstr(s).chunks) #TODO just make a chunk directly else: raise TypeError("expected str or FmtStr, %r found" % type(s)) return FmtStr(*chunks)
[ "def", "join", "(", "self", ",", "iterable", ")", ":", "before", "=", "[", "]", "chunks", "=", "[", "]", "for", "i", ",", "s", "in", "enumerate", "(", "iterable", ")", ":", "chunks", ".", "extend", "(", "before", ")", "before", "=", "self", ".", "chunks", "if", "isinstance", "(", "s", ",", "FmtStr", ")", ":", "chunks", ".", "extend", "(", "s", ".", "chunks", ")", "elif", "isinstance", "(", "s", ",", "(", "bytes", ",", "unicode", ")", ")", ":", "chunks", ".", "extend", "(", "fmtstr", "(", "s", ")", ".", "chunks", ")", "#TODO just make a chunk directly", "else", ":", "raise", "TypeError", "(", "\"expected str or FmtStr, %r found\"", "%", "type", "(", "s", ")", ")", "return", "FmtStr", "(", "*", "chunks", ")" ]
Joins an iterable yielding strings or FmtStrs with self as separator
[ "Joins", "an", "iterable", "yielding", "strings", "or", "FmtStrs", "with", "self", "as", "separator" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L353-L366
bpython/curtsies
curtsies/formatstring.py
FmtStr.split
def split(self, sep=None, maxsplit=None, regex=False): """Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.""" if maxsplit is not None: raise NotImplementedError('no maxsplit yet') s = self.s if sep is None: sep = r'\s+' elif not regex: sep = re.escape(sep) matches = list(re.finditer(sep, s)) return [self[start:end] for start, end in zip( [0] + [m.end() for m in matches], [m.start() for m in matches] + [len(s)])]
python
def split(self, sep=None, maxsplit=None, regex=False): """Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.""" if maxsplit is not None: raise NotImplementedError('no maxsplit yet') s = self.s if sep is None: sep = r'\s+' elif not regex: sep = re.escape(sep) matches = list(re.finditer(sep, s)) return [self[start:end] for start, end in zip( [0] + [m.end() for m in matches], [m.start() for m in matches] + [len(s)])]
[ "def", "split", "(", "self", ",", "sep", "=", "None", ",", "maxsplit", "=", "None", ",", "regex", "=", "False", ")", ":", "if", "maxsplit", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "'no maxsplit yet'", ")", "s", "=", "self", ".", "s", "if", "sep", "is", "None", ":", "sep", "=", "r'\\s+'", "elif", "not", "regex", ":", "sep", "=", "re", ".", "escape", "(", "sep", ")", "matches", "=", "list", "(", "re", ".", "finditer", "(", "sep", ",", "s", ")", ")", "return", "[", "self", "[", "start", ":", "end", "]", "for", "start", ",", "end", "in", "zip", "(", "[", "0", "]", "+", "[", "m", ".", "end", "(", ")", "for", "m", "in", "matches", "]", ",", "[", "m", ".", "start", "(", ")", "for", "m", "in", "matches", "]", "+", "[", "len", "(", "s", ")", "]", ")", "]" ]
Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.
[ "Split", "based", "on", "seperator", "optionally", "using", "a", "regex" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L369-L384
bpython/curtsies
curtsies/formatstring.py
FmtStr.splitlines
def splitlines(self, keepends=False): """Return a list of lines, split on newline characters, include line boundaries, if keepends is true.""" lines = self.split('\n') return [line+'\n' for line in lines] if keepends else ( lines if lines[-1] else lines[:-1])
python
def splitlines(self, keepends=False): """Return a list of lines, split on newline characters, include line boundaries, if keepends is true.""" lines = self.split('\n') return [line+'\n' for line in lines] if keepends else ( lines if lines[-1] else lines[:-1])
[ "def", "splitlines", "(", "self", ",", "keepends", "=", "False", ")", ":", "lines", "=", "self", ".", "split", "(", "'\\n'", ")", "return", "[", "line", "+", "'\\n'", "for", "line", "in", "lines", "]", "if", "keepends", "else", "(", "lines", "if", "lines", "[", "-", "1", "]", "else", "lines", "[", ":", "-", "1", "]", ")" ]
Return a list of lines, split on newline characters, include line boundaries, if keepends is true.
[ "Return", "a", "list", "of", "lines", "split", "on", "newline", "characters", "include", "line", "boundaries", "if", "keepends", "is", "true", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L386-L391
bpython/curtsies
curtsies/formatstring.py
FmtStr.ljust
def ljust(self, width, fillchar=None): """S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved """ if fillchar is not None: return fmtstr(self.s.ljust(width, fillchar), **self.shared_atts) to_add = ' ' * (width - len(self.s)) shared = self.shared_atts if 'bg' in shared: return self + fmtstr(to_add, bg=shared[str('bg')]) if to_add else self else: uniform = self.new_with_atts_removed('bg') return uniform + fmtstr(to_add, **self.shared_atts) if to_add else uniform
python
def ljust(self, width, fillchar=None): """S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved """ if fillchar is not None: return fmtstr(self.s.ljust(width, fillchar), **self.shared_atts) to_add = ' ' * (width - len(self.s)) shared = self.shared_atts if 'bg' in shared: return self + fmtstr(to_add, bg=shared[str('bg')]) if to_add else self else: uniform = self.new_with_atts_removed('bg') return uniform + fmtstr(to_add, **self.shared_atts) if to_add else uniform
[ "def", "ljust", "(", "self", ",", "width", ",", "fillchar", "=", "None", ")", ":", "if", "fillchar", "is", "not", "None", ":", "return", "fmtstr", "(", "self", ".", "s", ".", "ljust", "(", "width", ",", "fillchar", ")", ",", "*", "*", "self", ".", "shared_atts", ")", "to_add", "=", "' '", "*", "(", "width", "-", "len", "(", "self", ".", "s", ")", ")", "shared", "=", "self", ".", "shared_atts", "if", "'bg'", "in", "shared", ":", "return", "self", "+", "fmtstr", "(", "to_add", ",", "bg", "=", "shared", "[", "str", "(", "'bg'", ")", "]", ")", "if", "to_add", "else", "self", "else", ":", "uniform", "=", "self", ".", "new_with_atts_removed", "(", "'bg'", ")", "return", "uniform", "+", "fmtstr", "(", "to_add", ",", "*", "*", "self", ".", "shared_atts", ")", "if", "to_add", "else", "uniform" ]
S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved
[ "S", ".", "ljust", "(", "width", "[", "fillchar", "]", ")", "-", ">", "string" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L395-L408
bpython/curtsies
curtsies/formatstring.py
FmtStr.width
def width(self): """The number of columns it would take to display this string""" if self._width is not None: return self._width self._width = sum(fs.width for fs in self.chunks) return self._width
python
def width(self): """The number of columns it would take to display this string""" if self._width is not None: return self._width self._width = sum(fs.width for fs in self.chunks) return self._width
[ "def", "width", "(", "self", ")", ":", "if", "self", ".", "_width", "is", "not", "None", ":", "return", "self", ".", "_width", "self", ".", "_width", "=", "sum", "(", "fs", ".", "width", "for", "fs", "in", "self", ".", "chunks", ")", "return", "self", ".", "_width" ]
The number of columns it would take to display this string
[ "The", "number", "of", "columns", "it", "would", "take", "to", "display", "this", "string" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L447-L452
bpython/curtsies
curtsies/formatstring.py
FmtStr.width_at_offset
def width_at_offset(self, n): """Returns the horizontal position of character n of the string""" #TODO make more efficient? width = wcswidth(self.s[:n]) assert width != -1 return width
python
def width_at_offset(self, n): """Returns the horizontal position of character n of the string""" #TODO make more efficient? width = wcswidth(self.s[:n]) assert width != -1 return width
[ "def", "width_at_offset", "(", "self", ",", "n", ")", ":", "#TODO make more efficient?", "width", "=", "wcswidth", "(", "self", ".", "s", "[", ":", "n", "]", ")", "assert", "width", "!=", "-", "1", "return", "width" ]
Returns the horizontal position of character n of the string
[ "Returns", "the", "horizontal", "position", "of", "character", "n", "of", "the", "string" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L454-L459
bpython/curtsies
curtsies/formatstring.py
FmtStr.shared_atts
def shared_atts(self): """Gets atts shared among all nonzero length component Chunk""" #TODO cache this, could get ugly for large FmtStrs atts = {} first = self.chunks[0] for att in sorted(first.atts): #TODO how to write this without the '???'? if all(fs.atts.get(att, '???') == first.atts[att] for fs in self.chunks if len(fs) > 0): atts[att] = first.atts[att] return atts
python
def shared_atts(self): """Gets atts shared among all nonzero length component Chunk""" #TODO cache this, could get ugly for large FmtStrs atts = {} first = self.chunks[0] for att in sorted(first.atts): #TODO how to write this without the '???'? if all(fs.atts.get(att, '???') == first.atts[att] for fs in self.chunks if len(fs) > 0): atts[att] = first.atts[att] return atts
[ "def", "shared_atts", "(", "self", ")", ":", "#TODO cache this, could get ugly for large FmtStrs", "atts", "=", "{", "}", "first", "=", "self", ".", "chunks", "[", "0", "]", "for", "att", "in", "sorted", "(", "first", ".", "atts", ")", ":", "#TODO how to write this without the '???'?", "if", "all", "(", "fs", ".", "atts", ".", "get", "(", "att", ",", "'???'", ")", "==", "first", ".", "atts", "[", "att", "]", "for", "fs", "in", "self", ".", "chunks", "if", "len", "(", "fs", ")", ">", "0", ")", ":", "atts", "[", "att", "]", "=", "first", ".", "atts", "[", "att", "]", "return", "atts" ]
Gets atts shared among all nonzero length component Chunk
[ "Gets", "atts", "shared", "among", "all", "nonzero", "length", "component", "Chunk" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L494-L503
bpython/curtsies
curtsies/formatstring.py
FmtStr.new_with_atts_removed
def new_with_atts_removed(self, *attributes): """Returns a new FmtStr with the same content but some attributes removed""" return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes)) for bfs in self.chunks])
python
def new_with_atts_removed(self, *attributes): """Returns a new FmtStr with the same content but some attributes removed""" return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes)) for bfs in self.chunks])
[ "def", "new_with_atts_removed", "(", "self", ",", "*", "attributes", ")", ":", "return", "FmtStr", "(", "*", "[", "Chunk", "(", "bfs", ".", "s", ",", "bfs", ".", "atts", ".", "remove", "(", "*", "attributes", ")", ")", "for", "bfs", "in", "self", ".", "chunks", "]", ")" ]
Returns a new FmtStr with the same content but some attributes removed
[ "Returns", "a", "new", "FmtStr", "with", "the", "same", "content", "but", "some", "attributes", "removed" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L505-L508
bpython/curtsies
curtsies/formatstring.py
FmtStr.divides
def divides(self): """List of indices of divisions between the constituent chunks.""" acc = [0] for s in self.chunks: acc.append(acc[-1] + len(s)) return acc
python
def divides(self): """List of indices of divisions between the constituent chunks.""" acc = [0] for s in self.chunks: acc.append(acc[-1] + len(s)) return acc
[ "def", "divides", "(", "self", ")", ":", "acc", "=", "[", "0", "]", "for", "s", "in", "self", ".", "chunks", ":", "acc", ".", "append", "(", "acc", "[", "-", "1", "]", "+", "len", "(", "s", ")", ")", "return", "acc" ]
List of indices of divisions between the constituent chunks.
[ "List", "of", "indices", "of", "divisions", "between", "the", "constituent", "chunks", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L525-L530
bpython/curtsies
curtsies/formatstring.py
FmtStr.width_aware_slice
def width_aware_slice(self, index): """Slice based on the number of columns it would take to display the substring.""" if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') index = normalize_slice(self.width, index) counter = 0 parts = [] for chunk in self.chunks: if index.start < counter + chunk.width and index.stop > counter: start = max(0, index.start - counter) end = min(index.stop - counter, chunk.width) if end - start == chunk.width: parts.append(chunk) else: s_part = width_aware_slice(chunk.s, max(0, index.start - counter), index.stop - counter) parts.append(Chunk(s_part, chunk.atts)) counter += chunk.width if index.stop < counter: break return FmtStr(*parts) if parts else fmtstr('')
python
def width_aware_slice(self, index): """Slice based on the number of columns it would take to display the substring.""" if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') index = normalize_slice(self.width, index) counter = 0 parts = [] for chunk in self.chunks: if index.start < counter + chunk.width and index.stop > counter: start = max(0, index.start - counter) end = min(index.stop - counter, chunk.width) if end - start == chunk.width: parts.append(chunk) else: s_part = width_aware_slice(chunk.s, max(0, index.start - counter), index.stop - counter) parts.append(Chunk(s_part, chunk.atts)) counter += chunk.width if index.stop < counter: break return FmtStr(*parts) if parts else fmtstr('')
[ "def", "width_aware_slice", "(", "self", ",", "index", ")", ":", "if", "wcswidth", "(", "self", ".", "s", ")", "==", "-", "1", ":", "raise", "ValueError", "(", "'bad values for width aware slicing'", ")", "index", "=", "normalize_slice", "(", "self", ".", "width", ",", "index", ")", "counter", "=", "0", "parts", "=", "[", "]", "for", "chunk", "in", "self", ".", "chunks", ":", "if", "index", ".", "start", "<", "counter", "+", "chunk", ".", "width", "and", "index", ".", "stop", ">", "counter", ":", "start", "=", "max", "(", "0", ",", "index", ".", "start", "-", "counter", ")", "end", "=", "min", "(", "index", ".", "stop", "-", "counter", ",", "chunk", ".", "width", ")", "if", "end", "-", "start", "==", "chunk", ".", "width", ":", "parts", ".", "append", "(", "chunk", ")", "else", ":", "s_part", "=", "width_aware_slice", "(", "chunk", ".", "s", ",", "max", "(", "0", ",", "index", ".", "start", "-", "counter", ")", ",", "index", ".", "stop", "-", "counter", ")", "parts", ".", "append", "(", "Chunk", "(", "s_part", ",", "chunk", ".", "atts", ")", ")", "counter", "+=", "chunk", ".", "width", "if", "index", ".", "stop", "<", "counter", ":", "break", "return", "FmtStr", "(", "*", "parts", ")", "if", "parts", "else", "fmtstr", "(", "''", ")" ]
Slice based on the number of columns it would take to display the substring.
[ "Slice", "based", "on", "the", "number", "of", "columns", "it", "would", "take", "to", "display", "the", "substring", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L557-L576
bpython/curtsies
curtsies/formatstring.py
FmtStr.width_aware_splitlines
def width_aware_splitlines(self, columns): # type: (int) -> Iterator[FmtStr] """Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line. """ if columns < 2: raise ValueError("Column width %s is too narrow." % columns) if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') return self._width_aware_splitlines(columns)
python
def width_aware_splitlines(self, columns): # type: (int) -> Iterator[FmtStr] """Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line. """ if columns < 2: raise ValueError("Column width %s is too narrow." % columns) if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') return self._width_aware_splitlines(columns)
[ "def", "width_aware_splitlines", "(", "self", ",", "columns", ")", ":", "# type: (int) -> Iterator[FmtStr]", "if", "columns", "<", "2", ":", "raise", "ValueError", "(", "\"Column width %s is too narrow.\"", "%", "columns", ")", "if", "wcswidth", "(", "self", ".", "s", ")", "==", "-", "1", ":", "raise", "ValueError", "(", "'bad values for width aware slicing'", ")", "return", "self", ".", "_width_aware_splitlines", "(", "columns", ")" ]
Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line.
[ "Split", "into", "lines", "pushing", "doublewidth", "characters", "at", "the", "end", "of", "a", "line", "to", "the", "next", "line", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L578-L588
bpython/curtsies
curtsies/formatstring.py
FmtStr._getitem_normalized
def _getitem_normalized(self, index): """Builds the more compact fmtstrs by using fromstr( of the control sequences)""" index = normalize_slice(len(self), index) counter = 0 output = '' for fs in self.chunks: if index.start < counter + len(fs) and index.stop > counter: s_part = fs.s[max(0, index.start - counter):index.stop - counter] piece = Chunk(s_part, fs.atts).color_str output += piece counter += len(fs) if index.stop < counter: break return fmtstr(output)
python
def _getitem_normalized(self, index): """Builds the more compact fmtstrs by using fromstr( of the control sequences)""" index = normalize_slice(len(self), index) counter = 0 output = '' for fs in self.chunks: if index.start < counter + len(fs) and index.stop > counter: s_part = fs.s[max(0, index.start - counter):index.stop - counter] piece = Chunk(s_part, fs.atts).color_str output += piece counter += len(fs) if index.stop < counter: break return fmtstr(output)
[ "def", "_getitem_normalized", "(", "self", ",", "index", ")", ":", "index", "=", "normalize_slice", "(", "len", "(", "self", ")", ",", "index", ")", "counter", "=", "0", "output", "=", "''", "for", "fs", "in", "self", ".", "chunks", ":", "if", "index", ".", "start", "<", "counter", "+", "len", "(", "fs", ")", "and", "index", ".", "stop", ">", "counter", ":", "s_part", "=", "fs", ".", "s", "[", "max", "(", "0", ",", "index", ".", "start", "-", "counter", ")", ":", "index", ".", "stop", "-", "counter", "]", "piece", "=", "Chunk", "(", "s_part", ",", "fs", ".", "atts", ")", ".", "color_str", "output", "+=", "piece", "counter", "+=", "len", "(", "fs", ")", "if", "index", ".", "stop", "<", "counter", ":", "break", "return", "fmtstr", "(", "output", ")" ]
Builds the more compact fmtstrs by using fromstr( of the control sequences)
[ "Builds", "the", "more", "compact", "fmtstrs", "by", "using", "fromstr", "(", "of", "the", "control", "sequences", ")" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L613-L626
peterwittek/ncpol2sdpa
ncpol2sdpa/moroder_hierarchy.py
MoroderHierarchy._calculate_block_structure
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the output file. """ block_struct = [] if self.verbose > 0: print("Calculating block structure...") block_struct.append(len(self.monomial_sets[0]) * len(self.monomial_sets[1])) if extramomentmatrix is not None: for _ in extramomentmatrix: block_struct.append(len(self.monomial_sets[0]) * len(self.monomial_sets[1])) super(MoroderHierarchy, self).\ _calculate_block_structure(inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=block_struct)
python
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the output file. """ block_struct = [] if self.verbose > 0: print("Calculating block structure...") block_struct.append(len(self.monomial_sets[0]) * len(self.monomial_sets[1])) if extramomentmatrix is not None: for _ in extramomentmatrix: block_struct.append(len(self.monomial_sets[0]) * len(self.monomial_sets[1])) super(MoroderHierarchy, self).\ _calculate_block_structure(inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=block_struct)
[ "def", "_calculate_block_structure", "(", "self", ",", "inequalities", ",", "equalities", ",", "momentinequalities", ",", "momentequalities", ",", "extramomentmatrix", ",", "removeequalities", ",", "block_struct", "=", "None", ")", ":", "block_struct", "=", "[", "]", "if", "self", ".", "verbose", ">", "0", ":", "print", "(", "\"Calculating block structure...\"", ")", "block_struct", ".", "append", "(", "len", "(", "self", ".", "monomial_sets", "[", "0", "]", ")", "*", "len", "(", "self", ".", "monomial_sets", "[", "1", "]", ")", ")", "if", "extramomentmatrix", "is", "not", "None", ":", "for", "_", "in", "extramomentmatrix", ":", "block_struct", ".", "append", "(", "len", "(", "self", ".", "monomial_sets", "[", "0", "]", ")", "*", "len", "(", "self", ".", "monomial_sets", "[", "1", "]", ")", ")", "super", "(", "MoroderHierarchy", ",", "self", ")", ".", "_calculate_block_structure", "(", "inequalities", ",", "equalities", ",", "momentinequalities", ",", "momentequalities", ",", "extramomentmatrix", ",", "removeequalities", ",", "block_struct", "=", "block_struct", ")" ]
Calculates the block_struct array for the output file.
[ "Calculates", "the", "block_struct", "array", "for", "the", "output", "file", "." ]
train
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/moroder_hierarchy.py#L81-L101
bpython/curtsies
examples/initial_input.py
main
def main(): """Ideally we shouldn't lose the first second of events""" time.sleep(1) with Input() as input_generator: for e in input_generator: print(repr(e))
python
def main(): """Ideally we shouldn't lose the first second of events""" time.sleep(1) with Input() as input_generator: for e in input_generator: print(repr(e))
[ "def", "main", "(", ")", ":", "time", ".", "sleep", "(", "1", ")", "with", "Input", "(", ")", "as", "input_generator", ":", "for", "e", "in", "input_generator", ":", "print", "(", "repr", "(", "e", ")", ")" ]
Ideally we shouldn't lose the first second of events
[ "Ideally", "we", "shouldn", "t", "lose", "the", "first", "second", "of", "events" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/initial_input.py#L5-L10
peterwittek/ncpol2sdpa
ncpol2sdpa/steering_hierarchy.py
SteeringHierarchy._process_monomial
def _process_monomial(self, monomial, n_vars): """Process a single monomial when building the moment matrix. """ coeff, monomial = monomial.as_coeff_Mul() k = 0 # Have we seen this monomial before? conjugate = False try: # If yes, then we improve sparsity by reusing the # previous variable to denote this entry in the matrix k = self.monomial_index[monomial] except KeyError: # An extra round of substitutions is granted on the conjugate of # the monomial if all the variables are Hermitian daggered_monomial = \ apply_substitutions(Dagger(monomial), self.substitutions, self.pure_substitution_rules) try: k = self.monomial_index[daggered_monomial] conjugate = True except KeyError: # Otherwise we define a new entry in the associated # array recording the monomials, and add an entry in # the moment matrix k = n_vars + 1 self.monomial_index[monomial] = k if conjugate: k = -k return k, coeff
python
def _process_monomial(self, monomial, n_vars): """Process a single monomial when building the moment matrix. """ coeff, monomial = monomial.as_coeff_Mul() k = 0 # Have we seen this monomial before? conjugate = False try: # If yes, then we improve sparsity by reusing the # previous variable to denote this entry in the matrix k = self.monomial_index[monomial] except KeyError: # An extra round of substitutions is granted on the conjugate of # the monomial if all the variables are Hermitian daggered_monomial = \ apply_substitutions(Dagger(monomial), self.substitutions, self.pure_substitution_rules) try: k = self.monomial_index[daggered_monomial] conjugate = True except KeyError: # Otherwise we define a new entry in the associated # array recording the monomials, and add an entry in # the moment matrix k = n_vars + 1 self.monomial_index[monomial] = k if conjugate: k = -k return k, coeff
[ "def", "_process_monomial", "(", "self", ",", "monomial", ",", "n_vars", ")", ":", "coeff", ",", "monomial", "=", "monomial", ".", "as_coeff_Mul", "(", ")", "k", "=", "0", "# Have we seen this monomial before?", "conjugate", "=", "False", "try", ":", "# If yes, then we improve sparsity by reusing the", "# previous variable to denote this entry in the matrix", "k", "=", "self", ".", "monomial_index", "[", "monomial", "]", "except", "KeyError", ":", "# An extra round of substitutions is granted on the conjugate of", "# the monomial if all the variables are Hermitian", "daggered_monomial", "=", "apply_substitutions", "(", "Dagger", "(", "monomial", ")", ",", "self", ".", "substitutions", ",", "self", ".", "pure_substitution_rules", ")", "try", ":", "k", "=", "self", ".", "monomial_index", "[", "daggered_monomial", "]", "conjugate", "=", "True", "except", "KeyError", ":", "# Otherwise we define a new entry in the associated", "# array recording the monomials, and add an entry in", "# the moment matrix", "k", "=", "n_vars", "+", "1", "self", ".", "monomial_index", "[", "monomial", "]", "=", "k", "if", "conjugate", ":", "k", "=", "-", "k", "return", "k", ",", "coeff" ]
Process a single monomial when building the moment matrix.
[ "Process", "a", "single", "monomial", "when", "building", "the", "moment", "matrix", "." ]
train
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L80-L108
peterwittek/ncpol2sdpa
ncpol2sdpa/steering_hierarchy.py
SteeringHierarchy.__get_trace_facvar
def __get_trace_facvar(self, polynomial): """Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse, but instead of pushing sparse entries to the constraint matrices, it returns a dense vector. """ facvar = [0] * (self.n_vars + 1) F = {} for i in range(self.matrix_var_dim): for j in range(self.matrix_var_dim): for key, value in \ polynomial[i, j].as_coefficients_dict().items(): skey = apply_substitutions(key, self.substitutions, self.pure_substitution_rules) try: Fk = F[skey] except KeyError: Fk = zeros(self.matrix_var_dim, self.matrix_var_dim) Fk[i, j] += value F[skey] = Fk # This is the tracing part for key, Fk in F.items(): if key == S.One: k = 1 else: k = self.monomial_index[key] for i in range(self.matrix_var_dim): for j in range(self.matrix_var_dim): sym_matrix = zeros(self.matrix_var_dim, self.matrix_var_dim) sym_matrix[i, j] = 1 facvar[k+i*self.matrix_var_dim+j] = (sym_matrix*Fk).trace() facvar = [float(f) for f in facvar] return facvar
python
def __get_trace_facvar(self, polynomial): """Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse, but instead of pushing sparse entries to the constraint matrices, it returns a dense vector. """ facvar = [0] * (self.n_vars + 1) F = {} for i in range(self.matrix_var_dim): for j in range(self.matrix_var_dim): for key, value in \ polynomial[i, j].as_coefficients_dict().items(): skey = apply_substitutions(key, self.substitutions, self.pure_substitution_rules) try: Fk = F[skey] except KeyError: Fk = zeros(self.matrix_var_dim, self.matrix_var_dim) Fk[i, j] += value F[skey] = Fk # This is the tracing part for key, Fk in F.items(): if key == S.One: k = 1 else: k = self.monomial_index[key] for i in range(self.matrix_var_dim): for j in range(self.matrix_var_dim): sym_matrix = zeros(self.matrix_var_dim, self.matrix_var_dim) sym_matrix[i, j] = 1 facvar[k+i*self.matrix_var_dim+j] = (sym_matrix*Fk).trace() facvar = [float(f) for f in facvar] return facvar
[ "def", "__get_trace_facvar", "(", "self", ",", "polynomial", ")", ":", "facvar", "=", "[", "0", "]", "*", "(", "self", ".", "n_vars", "+", "1", ")", "F", "=", "{", "}", "for", "i", "in", "range", "(", "self", ".", "matrix_var_dim", ")", ":", "for", "j", "in", "range", "(", "self", ".", "matrix_var_dim", ")", ":", "for", "key", ",", "value", "in", "polynomial", "[", "i", ",", "j", "]", ".", "as_coefficients_dict", "(", ")", ".", "items", "(", ")", ":", "skey", "=", "apply_substitutions", "(", "key", ",", "self", ".", "substitutions", ",", "self", ".", "pure_substitution_rules", ")", "try", ":", "Fk", "=", "F", "[", "skey", "]", "except", "KeyError", ":", "Fk", "=", "zeros", "(", "self", ".", "matrix_var_dim", ",", "self", ".", "matrix_var_dim", ")", "Fk", "[", "i", ",", "j", "]", "+=", "value", "F", "[", "skey", "]", "=", "Fk", "# This is the tracing part", "for", "key", ",", "Fk", "in", "F", ".", "items", "(", ")", ":", "if", "key", "==", "S", ".", "One", ":", "k", "=", "1", "else", ":", "k", "=", "self", ".", "monomial_index", "[", "key", "]", "for", "i", "in", "range", "(", "self", ".", "matrix_var_dim", ")", ":", "for", "j", "in", "range", "(", "self", ".", "matrix_var_dim", ")", ":", "sym_matrix", "=", "zeros", "(", "self", ".", "matrix_var_dim", ",", "self", ".", "matrix_var_dim", ")", "sym_matrix", "[", "i", ",", "j", "]", "=", "1", "facvar", "[", "k", "+", "i", "*", "self", ".", "matrix_var_dim", "+", "j", "]", "=", "(", "sym_matrix", "*", "Fk", ")", ".", "trace", "(", ")", "facvar", "=", "[", "float", "(", "f", ")", "for", "f", "in", "facvar", "]", "return", "facvar" ]
Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse, but instead of pushing sparse entries to the constraint matrices, it returns a dense vector.
[ "Return", "dense", "vector", "representation", "of", "a", "polynomial", ".", "This", "function", "is", "nearly", "identical", "to", "__push_facvar_sparse", "but", "instead", "of", "pushing", "sparse", "entries", "to", "the", "constraint", "matrices", "it", "returns", "a", "dense", "vector", "." ]
train
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L186-L219
peterwittek/ncpol2sdpa
ncpol2sdpa/steering_hierarchy.py
SteeringHierarchy.set_objective
def set_objective(self, objective, extraobjexpr=None): """Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function :type extraobjexpr: str. """ if objective is not None and self.matrix_var_dim is not None: facvar = self.__get_trace_facvar(objective) self.obj_facvar = facvar[1:] self.constant_term = facvar[0] if self.verbose > 0 and facvar[0] != 0: print("Warning: The objective function has a non-zero %s " "constant term. It is not included in the SDP objective." % facvar[0]) else: super(SteeringHierarchy, self).\ set_objective(objective, extraobjexpr=extraobjexpr)
python
def set_objective(self, objective, extraobjexpr=None): """Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function :type extraobjexpr: str. """ if objective is not None and self.matrix_var_dim is not None: facvar = self.__get_trace_facvar(objective) self.obj_facvar = facvar[1:] self.constant_term = facvar[0] if self.verbose > 0 and facvar[0] != 0: print("Warning: The objective function has a non-zero %s " "constant term. It is not included in the SDP objective." % facvar[0]) else: super(SteeringHierarchy, self).\ set_objective(objective, extraobjexpr=extraobjexpr)
[ "def", "set_objective", "(", "self", ",", "objective", ",", "extraobjexpr", "=", "None", ")", ":", "if", "objective", "is", "not", "None", "and", "self", ".", "matrix_var_dim", "is", "not", "None", ":", "facvar", "=", "self", ".", "__get_trace_facvar", "(", "objective", ")", "self", ".", "obj_facvar", "=", "facvar", "[", "1", ":", "]", "self", ".", "constant_term", "=", "facvar", "[", "0", "]", "if", "self", ".", "verbose", ">", "0", "and", "facvar", "[", "0", "]", "!=", "0", ":", "print", "(", "\"Warning: The objective function has a non-zero %s \"", "\"constant term. It is not included in the SDP objective.\"", "%", "facvar", "[", "0", "]", ")", "else", ":", "super", "(", "SteeringHierarchy", ",", "self", ")", ".", "set_objective", "(", "objective", ",", "extraobjexpr", "=", "extraobjexpr", ")" ]
Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function :type extraobjexpr: str.
[ "Set", "or", "change", "the", "objective", "function", "of", "the", "polynomial", "optimization", "problem", "." ]
train
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L221-L242
peterwittek/ncpol2sdpa
ncpol2sdpa/steering_hierarchy.py
SteeringHierarchy._calculate_block_structure
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the output file. """ super(SteeringHierarchy, self).\ _calculate_block_structure(inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities) if self.matrix_var_dim is not None: self.block_struct = [self.matrix_var_dim*bs for bs in self.block_struct]
python
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the output file. """ super(SteeringHierarchy, self).\ _calculate_block_structure(inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities) if self.matrix_var_dim is not None: self.block_struct = [self.matrix_var_dim*bs for bs in self.block_struct]
[ "def", "_calculate_block_structure", "(", "self", ",", "inequalities", ",", "equalities", ",", "momentinequalities", ",", "momentequalities", ",", "extramomentmatrix", ",", "removeequalities", ",", "block_struct", "=", "None", ")", ":", "super", "(", "SteeringHierarchy", ",", "self", ")", ".", "_calculate_block_structure", "(", "inequalities", ",", "equalities", ",", "momentinequalities", ",", "momentequalities", ",", "extramomentmatrix", ",", "removeequalities", ")", "if", "self", ".", "matrix_var_dim", "is", "not", "None", ":", "self", ".", "block_struct", "=", "[", "self", ".", "matrix_var_dim", "*", "bs", "for", "bs", "in", "self", ".", "block_struct", "]" ]
Calculates the block_struct array for the output file.
[ "Calculates", "the", "block_struct", "array", "for", "the", "output", "file", "." ]
train
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L244-L256
peterwittek/ncpol2sdpa
ncpol2sdpa/steering_hierarchy.py
SteeringHierarchy.write_to_file
def write_to_file(self, filename, filetype=None): """Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or .txt for a symbolic export :type filename: str. :param filetype: Optional parameter to define the filetype. It can be "sdpa" for SDPA , "mosek" for Mosek, "csv" for human readable format, or "txt" for a symbolic export. :type filetype: str. """ if filetype == "txt" and not filename.endswith(".txt"): raise Exception("TXT files must have .txt extension!") elif filetype is None and filename.endswith(".txt"): filetype = "txt" else: return super(SteeringHierarchy, self).write_to_file(filename, filetype=filetype) tempfile_ = tempfile.NamedTemporaryFile() tmp_filename = tempfile_.name tempfile_.close() tmp_dats_filename = tmp_filename + ".dat-s" write_to_sdpa(self, tmp_dats_filename) f = open(tmp_dats_filename, 'r') f.readline();f.readline();f.readline() blocks = ((f.readline().strip().split(" = ")[0])[1:-1]).split(", ") block_offset, matrix_size = [0], 0 for block in blocks: matrix_size += abs(int(block)) block_offset.append(matrix_size) f.readline() matrix = [[0 for _ in range(matrix_size)] for _ in range(matrix_size)] for line in f: entry = line.strip().split("\t") var, block = int(entry[0]), int(entry[1])-1 row, column = int(entry[2]) - 1, int(entry[3]) - 1 value = float(entry[4]) offset = block_offset[block] matrix[offset+row][offset+column] = int(value*var) matrix[offset+column][offset+row] = int(value*var) f.close() f = open(filename, 'w') for matrix_line in matrix: f.write(str(matrix_line).replace('[', '').replace(']', '') + '\n') f.close() os.remove(tmp_dats_filename)
python
def write_to_file(self, filename, filetype=None): """Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or .txt for a symbolic export :type filename: str. :param filetype: Optional parameter to define the filetype. It can be "sdpa" for SDPA , "mosek" for Mosek, "csv" for human readable format, or "txt" for a symbolic export. :type filetype: str. """ if filetype == "txt" and not filename.endswith(".txt"): raise Exception("TXT files must have .txt extension!") elif filetype is None and filename.endswith(".txt"): filetype = "txt" else: return super(SteeringHierarchy, self).write_to_file(filename, filetype=filetype) tempfile_ = tempfile.NamedTemporaryFile() tmp_filename = tempfile_.name tempfile_.close() tmp_dats_filename = tmp_filename + ".dat-s" write_to_sdpa(self, tmp_dats_filename) f = open(tmp_dats_filename, 'r') f.readline();f.readline();f.readline() blocks = ((f.readline().strip().split(" = ")[0])[1:-1]).split(", ") block_offset, matrix_size = [0], 0 for block in blocks: matrix_size += abs(int(block)) block_offset.append(matrix_size) f.readline() matrix = [[0 for _ in range(matrix_size)] for _ in range(matrix_size)] for line in f: entry = line.strip().split("\t") var, block = int(entry[0]), int(entry[1])-1 row, column = int(entry[2]) - 1, int(entry[3]) - 1 value = float(entry[4]) offset = block_offset[block] matrix[offset+row][offset+column] = int(value*var) matrix[offset+column][offset+row] = int(value*var) f.close() f = open(filename, 'w') for matrix_line in matrix: f.write(str(matrix_line).replace('[', '').replace(']', '') + '\n') f.close() os.remove(tmp_dats_filename)
[ "def", "write_to_file", "(", "self", ",", "filename", ",", "filetype", "=", "None", ")", ":", "if", "filetype", "==", "\"txt\"", "and", "not", "filename", ".", "endswith", "(", "\".txt\"", ")", ":", "raise", "Exception", "(", "\"TXT files must have .txt extension!\"", ")", "elif", "filetype", "is", "None", "and", "filename", ".", "endswith", "(", "\".txt\"", ")", ":", "filetype", "=", "\"txt\"", "else", ":", "return", "super", "(", "SteeringHierarchy", ",", "self", ")", ".", "write_to_file", "(", "filename", ",", "filetype", "=", "filetype", ")", "tempfile_", "=", "tempfile", ".", "NamedTemporaryFile", "(", ")", "tmp_filename", "=", "tempfile_", ".", "name", "tempfile_", ".", "close", "(", ")", "tmp_dats_filename", "=", "tmp_filename", "+", "\".dat-s\"", "write_to_sdpa", "(", "self", ",", "tmp_dats_filename", ")", "f", "=", "open", "(", "tmp_dats_filename", ",", "'r'", ")", "f", ".", "readline", "(", ")", "f", ".", "readline", "(", ")", "f", ".", "readline", "(", ")", "blocks", "=", "(", "(", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "\" = \"", ")", "[", "0", "]", ")", "[", "1", ":", "-", "1", "]", ")", ".", "split", "(", "\", \"", ")", "block_offset", ",", "matrix_size", "=", "[", "0", "]", ",", "0", "for", "block", "in", "blocks", ":", "matrix_size", "+=", "abs", "(", "int", "(", "block", ")", ")", "block_offset", ".", "append", "(", "matrix_size", ")", "f", ".", "readline", "(", ")", "matrix", "=", "[", "[", "0", "for", "_", "in", "range", "(", "matrix_size", ")", "]", "for", "_", "in", "range", "(", "matrix_size", ")", "]", "for", "line", "in", "f", ":", "entry", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "\"\\t\"", ")", "var", ",", "block", "=", "int", "(", "entry", "[", "0", "]", ")", ",", "int", "(", "entry", "[", "1", "]", ")", "-", "1", "row", ",", "column", "=", "int", "(", "entry", "[", "2", "]", ")", "-", "1", ",", "int", "(", "entry", "[", "3", "]", ")", "-", "1", "value", "=", "float", "(", "entry", "[", "4", "]", ")", "offset", "=", "block_offset", "[", "block", "]", "matrix", "[", "offset", "+", "row", "]", "[", "offset", "+", "column", "]", "=", "int", "(", "value", "*", "var", ")", "matrix", "[", "offset", "+", "column", "]", "[", "offset", "+", "row", "]", "=", "int", "(", "value", "*", "var", ")", "f", ".", "close", "(", ")", "f", "=", "open", "(", "filename", ",", "'w'", ")", "for", "matrix_line", "in", "matrix", ":", "f", ".", "write", "(", "str", "(", "matrix_line", ")", ".", "replace", "(", "'['", ",", "''", ")", ".", "replace", "(", "']'", ",", "''", ")", "+", "'\\n'", ")", "f", ".", "close", "(", ")", "os", ".", "remove", "(", "tmp_dats_filename", ")" ]
Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or .txt for a symbolic export :type filename: str. :param filetype: Optional parameter to define the filetype. It can be "sdpa" for SDPA , "mosek" for Mosek, "csv" for human readable format, or "txt" for a symbolic export. :type filetype: str.
[ "Write", "the", "relaxation", "to", "a", "file", "." ]
train
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L268-L315
laike9m/ezcf
ezcf/_base.py
BaseFinder.get_outerframe_skip_importlib_frame
def get_outerframe_skip_importlib_frame(level): """ There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bug is fixed """ if sys.version_info < (3, 4): return sys._getframe(level) else: currentframe = inspect.currentframe() levelup = 0 while levelup < level: currentframe = currentframe.f_back if currentframe.f_globals['__name__'] == 'importlib._bootstrap': continue else: levelup += 1 return currentframe
python
def get_outerframe_skip_importlib_frame(level): """ There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bug is fixed """ if sys.version_info < (3, 4): return sys._getframe(level) else: currentframe = inspect.currentframe() levelup = 0 while levelup < level: currentframe = currentframe.f_back if currentframe.f_globals['__name__'] == 'importlib._bootstrap': continue else: levelup += 1 return currentframe
[ "def", "get_outerframe_skip_importlib_frame", "(", "level", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "4", ")", ":", "return", "sys", ".", "_getframe", "(", "level", ")", "else", ":", "currentframe", "=", "inspect", ".", "currentframe", "(", ")", "levelup", "=", "0", "while", "levelup", "<", "level", ":", "currentframe", "=", "currentframe", ".", "f_back", "if", "currentframe", ".", "f_globals", "[", "'__name__'", "]", "==", "'importlib._bootstrap'", ":", "continue", "else", ":", "levelup", "+=", "1", "return", "currentframe" ]
There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bug is fixed
[ "There", "s", "a", "bug", "in", "Python3", ".", "4", "+", "see", "http", ":", "//", "bugs", ".", "python", ".", "org", "/", "issue23773", "remove", "this", "and", "use", "sys", ".", "_getframe", "(", "3", ")", "when", "bug", "is", "fixed" ]
train
https://github.com/laike9m/ezcf/blob/30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12/ezcf/_base.py#L46-L62
kmn/coincheck
coincheck/market.py
Market.public_api
def public_api(self,url): ''' template function of public api''' try : url in api_urls return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text) except Exception as e: print(e)
python
def public_api(self,url): ''' template function of public api''' try : url in api_urls return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text) except Exception as e: print(e)
[ "def", "public_api", "(", "self", ",", "url", ")", ":", "try", ":", "url", "in", "api_urls", "return", "ast", ".", "literal_eval", "(", "requests", ".", "get", "(", "base_url", "+", "api_urls", ".", "get", "(", "url", ")", ")", ".", "text", ")", "except", "Exception", "as", "e", ":", "print", "(", "e", ")" ]
template function of public api
[ "template", "function", "of", "public", "api" ]
train
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/market.py#L19-L25
bpython/curtsies
curtsies/escseqparse.py
parse
def parse(s): r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m") """ stuff = [] rest = s while True: front, token, rest = peel_off_esc_code(rest) if front: stuff.append(front) if token: try: tok = token_type(token) if tok: stuff.extend(tok) except ValueError: raise ValueError("Can't parse escape sequence: %r %r %r %r" % (s, repr(front), token, repr(rest))) if not rest: break return stuff
python
def parse(s): r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m") """ stuff = [] rest = s while True: front, token, rest = peel_off_esc_code(rest) if front: stuff.append(front) if token: try: tok = token_type(token) if tok: stuff.extend(tok) except ValueError: raise ValueError("Can't parse escape sequence: %r %r %r %r" % (s, repr(front), token, repr(rest))) if not rest: break return stuff
[ "def", "parse", "(", "s", ")", ":", "stuff", "=", "[", "]", "rest", "=", "s", "while", "True", ":", "front", ",", "token", ",", "rest", "=", "peel_off_esc_code", "(", "rest", ")", "if", "front", ":", "stuff", ".", "append", "(", "front", ")", "if", "token", ":", "try", ":", "tok", "=", "token_type", "(", "token", ")", "if", "tok", ":", "stuff", ".", "extend", "(", "tok", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Can't parse escape sequence: %r %r %r %r\"", "%", "(", "s", ",", "repr", "(", "front", ")", ",", "token", ",", "repr", "(", "rest", ")", ")", ")", "if", "not", "rest", ":", "break", "return", "stuff" ]
r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m")
[ "r", "Returns", "a", "list", "of", "strings", "or", "format", "dictionaries", "to", "describe", "the", "strings", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/escseqparse.py#L23-L48
bpython/curtsies
curtsies/escseqparse.py
peel_off_esc_code
def peel_off_esc_code(s): r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True """ p = r"""(?P<front>.*?) (?P<seq> (?P<csi> (?:[]\[) | ["""+'\x9b' + r"""]) (?P<private>) (?P<numbers> (?:\d+;)* (?:\d+)?) (?P<intermed>""" + '[\x20-\x2f]*)' + r""" (?P<command>""" + '[\x40-\x7e]))' + r""" (?P<rest>.*)""" m1 = re.match(p, s, re.VERBOSE) # multibyte esc seq m2 = re.match('(?P<front>.*?)(?P<seq>(?P<csi>)(?P<command>[\x40-\x5f]))(?P<rest>.*)', s) # 2 byte escape sequence if m1 and m2: m = m1 if len(m1.groupdict()['front']) <= len(m2.groupdict()['front']) else m2 # choose the match which has less processed text in order to get the # first escape sequence elif m1: m = m1 elif m2: m = m2 else: m = None if m: d = m.groupdict() del d['front'] del d['rest'] if 'numbers' in d and all(d['numbers'].split(';')): d['numbers'] = [int(x) for x in d['numbers'].split(';')] return m.groupdict()['front'], d, m.groupdict()['rest'] else: return s, None, ''
python
def peel_off_esc_code(s): r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True """ p = r"""(?P<front>.*?) (?P<seq> (?P<csi> (?:[]\[) | ["""+'\x9b' + r"""]) (?P<private>) (?P<numbers> (?:\d+;)* (?:\d+)?) (?P<intermed>""" + '[\x20-\x2f]*)' + r""" (?P<command>""" + '[\x40-\x7e]))' + r""" (?P<rest>.*)""" m1 = re.match(p, s, re.VERBOSE) # multibyte esc seq m2 = re.match('(?P<front>.*?)(?P<seq>(?P<csi>)(?P<command>[\x40-\x5f]))(?P<rest>.*)', s) # 2 byte escape sequence if m1 and m2: m = m1 if len(m1.groupdict()['front']) <= len(m2.groupdict()['front']) else m2 # choose the match which has less processed text in order to get the # first escape sequence elif m1: m = m1 elif m2: m = m2 else: m = None if m: d = m.groupdict() del d['front'] del d['rest'] if 'numbers' in d and all(d['numbers'].split(';')): d['numbers'] = [int(x) for x in d['numbers'].split(';')] return m.groupdict()['front'], d, m.groupdict()['rest'] else: return s, None, ''
[ "def", "peel_off_esc_code", "(", "s", ")", ":", "p", "=", "r\"\"\"(?P<front>.*?)\n (?P<seq>\n (?P<csi>\n (?:[\u001b]\\[)\n |\n [\"\"\"", "+", "'\\x9b'", "+", "r\"\"\"])\n (?P<private>)\n (?P<numbers>\n (?:\\d+;)*\n (?:\\d+)?)\n (?P<intermed>\"\"\"", "+", "'[\\x20-\\x2f]*)'", "+", "r\"\"\"\n (?P<command>\"\"\"", "+", "'[\\x40-\\x7e]))'", "+", "r\"\"\"\n (?P<rest>.*)\"\"\"", "m1", "=", "re", ".", "match", "(", "p", ",", "s", ",", "re", ".", "VERBOSE", ")", "# multibyte esc seq", "m2", "=", "re", ".", "match", "(", "'(?P<front>.*?)(?P<seq>(?P<csi>\u001b)(?P<command>[\\x40-\\x5f]))(?P<rest>.*)'", ",", "s", ")", "# 2 byte escape sequence", "if", "m1", "and", "m2", ":", "m", "=", "m1", "if", "len", "(", "m1", ".", "groupdict", "(", ")", "[", "'front'", "]", ")", "<=", "len", "(", "m2", ".", "groupdict", "(", ")", "[", "'front'", "]", ")", "else", "m2", "# choose the match which has less processed text in order to get the", "# first escape sequence", "elif", "m1", ":", "m", "=", "m1", "elif", "m2", ":", "m", "=", "m2", "else", ":", "m", "=", "None", "if", "m", ":", "d", "=", "m", ".", "groupdict", "(", ")", "del", "d", "[", "'front'", "]", "del", "d", "[", "'rest'", "]", "if", "'numbers'", "in", "d", "and", "all", "(", "d", "[", "'numbers'", "]", ".", "split", "(", "';'", ")", ")", ":", "d", "[", "'numbers'", "]", "=", "[", "int", "(", "x", ")", "for", "x", "in", "d", "[", "'numbers'", "]", ".", "split", "(", "';'", ")", "]", "return", "m", ".", "groupdict", "(", ")", "[", "'front'", "]", ",", "d", ",", "m", ".", "groupdict", "(", ")", "[", "'rest'", "]", "else", ":", "return", "s", ",", "None", ",", "''" ]
r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True
[ "r", "Returns", "processed", "text", "the", "next", "token", "and", "unprocessed", "text" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/escseqparse.py#L51-L92
bpython/curtsies
curtsies/events.py
get_key
def get_key(bytes_, encoding, keynames='curtsies', full=False): """Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should match the terminal encoding. keynames is a string describing how keys should be named: * curtsies uses unicode strings like <F8> * curses uses unicode strings similar to those returned by the Python ncurses window.getkey function, like KEY_F(8), plus a nonstandard representation of meta keys (bytes 128-255) because returning the corresponding unicode code point would be indistinguishable from the multibyte sequence that encodes that character in the current encoding * bytes returns the original bytes from stdin (NOT unicode) if full, match a key even if it could be a prefix to another key (useful for detecting a plain escape key for instance, since escape is also a prefix to a bunch of char sequences for other keys) Events are subclasses of Event, or unicode strings Precondition: get_key(prefix, keynames) is None for all proper prefixes of bytes. This means get_key should be called on progressively larger inputs (for 'asdf', first on 'a', then on 'as', then on 'asd' - until a non-None value is returned) """ if not all(isinstance(c, type(b'')) for c in bytes_): raise ValueError("get key expects bytes, got %r" % bytes_) # expects raw bytes if keynames not in ['curtsies', 'curses', 'bytes']: raise ValueError("keynames must be one of 'curtsies', 'curses' or 'bytes'") seq = b''.join(bytes_) if len(seq) > MAX_KEYPRESS_SIZE: raise ValueError('unable to decode bytes %r' % seq) def key_name(): if keynames == 'curses': if seq in CURSES_NAMES: # may not be here (and still not decodable) curses names incomplete return CURSES_NAMES[seq] # Otherwise, there's no special curses name for this try: return seq.decode(encoding) # for normal decodable text or a special curtsies sequence with bytes that can be decoded except UnicodeDecodeError: # this sequence can't be decoded with this encoding, so we need to represent the bytes if len(seq) == 1: return u'x%02X' % ord(seq) #TODO figure out a better thing to return here else: raise NotImplementedError("are multibyte unnameable sequences possible?") return u'bytes: ' + u'-'.join(u'x%02X' % ord(seq[i:i+1]) for i in range(len(seq))) #TODO if this isn't possible, return multiple meta keys as a paste event if paste events enabled elif keynames == 'curtsies': if seq in CURTSIES_NAMES: return CURTSIES_NAMES[seq] return seq.decode(encoding) #assumes that curtsies names are a subset of curses ones else: assert keynames == 'bytes' return seq key_known = seq in CURTSIES_NAMES or seq in CURSES_NAMES or decodable(seq, encoding) if full and key_known: return key_name() elif seq in KEYMAP_PREFIXES or could_be_unfinished_char(seq, encoding): return None # need more input to make up a full keypress elif key_known: return key_name() else: seq.decode(encoding) # this will raise a unicode error (they're annoying to raise ourselves) assert False, 'should have raised an unicode decode error'
python
def get_key(bytes_, encoding, keynames='curtsies', full=False): """Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should match the terminal encoding. keynames is a string describing how keys should be named: * curtsies uses unicode strings like <F8> * curses uses unicode strings similar to those returned by the Python ncurses window.getkey function, like KEY_F(8), plus a nonstandard representation of meta keys (bytes 128-255) because returning the corresponding unicode code point would be indistinguishable from the multibyte sequence that encodes that character in the current encoding * bytes returns the original bytes from stdin (NOT unicode) if full, match a key even if it could be a prefix to another key (useful for detecting a plain escape key for instance, since escape is also a prefix to a bunch of char sequences for other keys) Events are subclasses of Event, or unicode strings Precondition: get_key(prefix, keynames) is None for all proper prefixes of bytes. This means get_key should be called on progressively larger inputs (for 'asdf', first on 'a', then on 'as', then on 'asd' - until a non-None value is returned) """ if not all(isinstance(c, type(b'')) for c in bytes_): raise ValueError("get key expects bytes, got %r" % bytes_) # expects raw bytes if keynames not in ['curtsies', 'curses', 'bytes']: raise ValueError("keynames must be one of 'curtsies', 'curses' or 'bytes'") seq = b''.join(bytes_) if len(seq) > MAX_KEYPRESS_SIZE: raise ValueError('unable to decode bytes %r' % seq) def key_name(): if keynames == 'curses': if seq in CURSES_NAMES: # may not be here (and still not decodable) curses names incomplete return CURSES_NAMES[seq] # Otherwise, there's no special curses name for this try: return seq.decode(encoding) # for normal decodable text or a special curtsies sequence with bytes that can be decoded except UnicodeDecodeError: # this sequence can't be decoded with this encoding, so we need to represent the bytes if len(seq) == 1: return u'x%02X' % ord(seq) #TODO figure out a better thing to return here else: raise NotImplementedError("are multibyte unnameable sequences possible?") return u'bytes: ' + u'-'.join(u'x%02X' % ord(seq[i:i+1]) for i in range(len(seq))) #TODO if this isn't possible, return multiple meta keys as a paste event if paste events enabled elif keynames == 'curtsies': if seq in CURTSIES_NAMES: return CURTSIES_NAMES[seq] return seq.decode(encoding) #assumes that curtsies names are a subset of curses ones else: assert keynames == 'bytes' return seq key_known = seq in CURTSIES_NAMES or seq in CURSES_NAMES or decodable(seq, encoding) if full and key_known: return key_name() elif seq in KEYMAP_PREFIXES or could_be_unfinished_char(seq, encoding): return None # need more input to make up a full keypress elif key_known: return key_name() else: seq.decode(encoding) # this will raise a unicode error (they're annoying to raise ourselves) assert False, 'should have raised an unicode decode error'
[ "def", "get_key", "(", "bytes_", ",", "encoding", ",", "keynames", "=", "'curtsies'", ",", "full", "=", "False", ")", ":", "if", "not", "all", "(", "isinstance", "(", "c", ",", "type", "(", "b''", ")", ")", "for", "c", "in", "bytes_", ")", ":", "raise", "ValueError", "(", "\"get key expects bytes, got %r\"", "%", "bytes_", ")", "# expects raw bytes", "if", "keynames", "not", "in", "[", "'curtsies'", ",", "'curses'", ",", "'bytes'", "]", ":", "raise", "ValueError", "(", "\"keynames must be one of 'curtsies', 'curses' or 'bytes'\"", ")", "seq", "=", "b''", ".", "join", "(", "bytes_", ")", "if", "len", "(", "seq", ")", ">", "MAX_KEYPRESS_SIZE", ":", "raise", "ValueError", "(", "'unable to decode bytes %r'", "%", "seq", ")", "def", "key_name", "(", ")", ":", "if", "keynames", "==", "'curses'", ":", "if", "seq", "in", "CURSES_NAMES", ":", "# may not be here (and still not decodable) curses names incomplete", "return", "CURSES_NAMES", "[", "seq", "]", "# Otherwise, there's no special curses name for this", "try", ":", "return", "seq", ".", "decode", "(", "encoding", ")", "# for normal decodable text or a special curtsies sequence with bytes that can be decoded", "except", "UnicodeDecodeError", ":", "# this sequence can't be decoded with this encoding, so we need to represent the bytes", "if", "len", "(", "seq", ")", "==", "1", ":", "return", "u'x%02X'", "%", "ord", "(", "seq", ")", "#TODO figure out a better thing to return here", "else", ":", "raise", "NotImplementedError", "(", "\"are multibyte unnameable sequences possible?\"", ")", "return", "u'bytes: '", "+", "u'-'", ".", "join", "(", "u'x%02X'", "%", "ord", "(", "seq", "[", "i", ":", "i", "+", "1", "]", ")", "for", "i", "in", "range", "(", "len", "(", "seq", ")", ")", ")", "#TODO if this isn't possible, return multiple meta keys as a paste event if paste events enabled", "elif", "keynames", "==", "'curtsies'", ":", "if", "seq", "in", "CURTSIES_NAMES", ":", "return", "CURTSIES_NAMES", "[", "seq", "]", "return", "seq", ".", "decode", "(", "encoding", ")", "#assumes that curtsies names are a subset of curses ones", "else", ":", "assert", "keynames", "==", "'bytes'", "return", "seq", "key_known", "=", "seq", "in", "CURTSIES_NAMES", "or", "seq", "in", "CURSES_NAMES", "or", "decodable", "(", "seq", ",", "encoding", ")", "if", "full", "and", "key_known", ":", "return", "key_name", "(", ")", "elif", "seq", "in", "KEYMAP_PREFIXES", "or", "could_be_unfinished_char", "(", "seq", ",", "encoding", ")", ":", "return", "None", "# need more input to make up a full keypress", "elif", "key_known", ":", "return", "key_name", "(", ")", "else", ":", "seq", ".", "decode", "(", "encoding", ")", "# this will raise a unicode error (they're annoying to raise ourselves)", "assert", "False", ",", "'should have raised an unicode decode error'" ]
Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should match the terminal encoding. keynames is a string describing how keys should be named: * curtsies uses unicode strings like <F8> * curses uses unicode strings similar to those returned by the Python ncurses window.getkey function, like KEY_F(8), plus a nonstandard representation of meta keys (bytes 128-255) because returning the corresponding unicode code point would be indistinguishable from the multibyte sequence that encodes that character in the current encoding * bytes returns the original bytes from stdin (NOT unicode) if full, match a key even if it could be a prefix to another key (useful for detecting a plain escape key for instance, since escape is also a prefix to a bunch of char sequences for other keys) Events are subclasses of Event, or unicode strings Precondition: get_key(prefix, keynames) is None for all proper prefixes of bytes. This means get_key should be called on progressively larger inputs (for 'asdf', first on 'a', then on 'as', then on 'asd' - until a non-None value is returned)
[ "Return", "key", "pressed", "from", "bytes_", "or", "None" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/events.py#L142-L218
bpython/curtsies
curtsies/events.py
could_be_unfinished_char
def could_be_unfinished_char(seq, encoding): """Whether seq bytes might create a char in encoding if more bytes were added""" if decodable(seq, encoding): return False # any sensible encoding surely doesn't require lookahead (right?) # (if seq bytes encoding a character, adding another byte shouldn't also encode something) if encodings.codecs.getdecoder('utf8') is encodings.codecs.getdecoder(encoding): return could_be_unfinished_utf8(seq) elif encodings.codecs.getdecoder('ascii') is encodings.codecs.getdecoder(encoding): return False else: return True
python
def could_be_unfinished_char(seq, encoding): """Whether seq bytes might create a char in encoding if more bytes were added""" if decodable(seq, encoding): return False # any sensible encoding surely doesn't require lookahead (right?) # (if seq bytes encoding a character, adding another byte shouldn't also encode something) if encodings.codecs.getdecoder('utf8') is encodings.codecs.getdecoder(encoding): return could_be_unfinished_utf8(seq) elif encodings.codecs.getdecoder('ascii') is encodings.codecs.getdecoder(encoding): return False else: return True
[ "def", "could_be_unfinished_char", "(", "seq", ",", "encoding", ")", ":", "if", "decodable", "(", "seq", ",", "encoding", ")", ":", "return", "False", "# any sensible encoding surely doesn't require lookahead (right?)", "# (if seq bytes encoding a character, adding another byte shouldn't also encode something)", "if", "encodings", ".", "codecs", ".", "getdecoder", "(", "'utf8'", ")", "is", "encodings", ".", "codecs", ".", "getdecoder", "(", "encoding", ")", ":", "return", "could_be_unfinished_utf8", "(", "seq", ")", "elif", "encodings", ".", "codecs", ".", "getdecoder", "(", "'ascii'", ")", "is", "encodings", ".", "codecs", ".", "getdecoder", "(", "encoding", ")", ":", "return", "False", "else", ":", "return", "True" ]
Whether seq bytes might create a char in encoding if more bytes were added
[ "Whether", "seq", "bytes", "might", "create", "a", "char", "in", "encoding", "if", "more", "bytes", "were", "added" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/events.py#L220-L231
bpython/curtsies
curtsies/events.py
pp_event
def pp_event(seq): """Returns pretty representation of an Event or keypress""" if isinstance(seq, Event): return str(seq) # Get the original sequence back if seq is a pretty name already rev_curses = dict((v, k) for k, v in CURSES_NAMES.items()) rev_curtsies = dict((v, k) for k, v in CURTSIES_NAMES.items()) if seq in rev_curses: seq = rev_curses[seq] elif seq in rev_curtsies: seq = rev_curtsies[seq] pretty = curtsies_name(seq) if pretty != seq: return pretty return repr(seq).lstrip('u')[1:-1]
python
def pp_event(seq): """Returns pretty representation of an Event or keypress""" if isinstance(seq, Event): return str(seq) # Get the original sequence back if seq is a pretty name already rev_curses = dict((v, k) for k, v in CURSES_NAMES.items()) rev_curtsies = dict((v, k) for k, v in CURTSIES_NAMES.items()) if seq in rev_curses: seq = rev_curses[seq] elif seq in rev_curtsies: seq = rev_curtsies[seq] pretty = curtsies_name(seq) if pretty != seq: return pretty return repr(seq).lstrip('u')[1:-1]
[ "def", "pp_event", "(", "seq", ")", ":", "if", "isinstance", "(", "seq", ",", "Event", ")", ":", "return", "str", "(", "seq", ")", "# Get the original sequence back if seq is a pretty name already", "rev_curses", "=", "dict", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "CURSES_NAMES", ".", "items", "(", ")", ")", "rev_curtsies", "=", "dict", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "CURTSIES_NAMES", ".", "items", "(", ")", ")", "if", "seq", "in", "rev_curses", ":", "seq", "=", "rev_curses", "[", "seq", "]", "elif", "seq", "in", "rev_curtsies", ":", "seq", "=", "rev_curtsies", "[", "seq", "]", "pretty", "=", "curtsies_name", "(", "seq", ")", "if", "pretty", "!=", "seq", ":", "return", "pretty", "return", "repr", "(", "seq", ")", ".", "lstrip", "(", "'u'", ")", "[", "1", ":", "-", "1", "]" ]
Returns pretty representation of an Event or keypress
[ "Returns", "pretty", "representation", "of", "an", "Event", "or", "keypress" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/events.py#L243-L260
chris1610/barnum-proj
barnum/gen_data.py
create_nouns
def create_nouns(max=2): """ Return a string of random nouns up to max number """ nouns = [] for noun in range(0, max): nouns.append(random.choice(noun_list)) return " ".join(nouns)
python
def create_nouns(max=2): """ Return a string of random nouns up to max number """ nouns = [] for noun in range(0, max): nouns.append(random.choice(noun_list)) return " ".join(nouns)
[ "def", "create_nouns", "(", "max", "=", "2", ")", ":", "nouns", "=", "[", "]", "for", "noun", "in", "range", "(", "0", ",", "max", ")", ":", "nouns", ".", "append", "(", "random", ".", "choice", "(", "noun_list", ")", ")", "return", "\" \"", ".", "join", "(", "nouns", ")" ]
Return a string of random nouns up to max number
[ "Return", "a", "string", "of", "random", "nouns", "up", "to", "max", "number" ]
train
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L112-L119
chris1610/barnum-proj
barnum/gen_data.py
create_date
def create_date(past=False, max_years_future=10, max_years_past=10): """ Create a random valid date If past, then dates can be in the past If into the future, then no more than max_years into the future If it's not, then it can't be any older than max_years_past """ if past: start = datetime.datetime.today() - datetime.timedelta(days=max_years_past * 365) #Anywhere between 1980 and today plus max_ears num_days = (max_years_future * 365) + start.day else: start = datetime.datetime.today() num_days = max_years_future * 365 random_days = random.randint(1, num_days) random_date = start + datetime.timedelta(days=random_days) return(random_date)
python
def create_date(past=False, max_years_future=10, max_years_past=10): """ Create a random valid date If past, then dates can be in the past If into the future, then no more than max_years into the future If it's not, then it can't be any older than max_years_past """ if past: start = datetime.datetime.today() - datetime.timedelta(days=max_years_past * 365) #Anywhere between 1980 and today plus max_ears num_days = (max_years_future * 365) + start.day else: start = datetime.datetime.today() num_days = max_years_future * 365 random_days = random.randint(1, num_days) random_date = start + datetime.timedelta(days=random_days) return(random_date)
[ "def", "create_date", "(", "past", "=", "False", ",", "max_years_future", "=", "10", ",", "max_years_past", "=", "10", ")", ":", "if", "past", ":", "start", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "max_years_past", "*", "365", ")", "#Anywhere between 1980 and today plus max_ears", "num_days", "=", "(", "max_years_future", "*", "365", ")", "+", "start", ".", "day", "else", ":", "start", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "num_days", "=", "max_years_future", "*", "365", "random_days", "=", "random", ".", "randint", "(", "1", ",", "num_days", ")", "random_date", "=", "start", "+", "datetime", ".", "timedelta", "(", "days", "=", "random_days", ")", "return", "(", "random_date", ")" ]
Create a random valid date If past, then dates can be in the past If into the future, then no more than max_years into the future If it's not, then it can't be any older than max_years_past
[ "Create", "a", "random", "valid", "date", "If", "past", "then", "dates", "can", "be", "in", "the", "past", "If", "into", "the", "future", "then", "no", "more", "than", "max_years", "into", "the", "future", "If", "it", "s", "not", "then", "it", "can", "t", "be", "any", "older", "than", "max_years_past" ]
train
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L122-L139
chris1610/barnum-proj
barnum/gen_data.py
create_birthday
def create_birthday(min_age=18, max_age=80): """ Create a random birthday fomr someone between the ages of min_age and max_age """ age = random.randint(min_age, max_age) start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365)) return start - datetime.timedelta(days=age * 365)
python
def create_birthday(min_age=18, max_age=80): """ Create a random birthday fomr someone between the ages of min_age and max_age """ age = random.randint(min_age, max_age) start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365)) return start - datetime.timedelta(days=age * 365)
[ "def", "create_birthday", "(", "min_age", "=", "18", ",", "max_age", "=", "80", ")", ":", "age", "=", "random", ".", "randint", "(", "min_age", ",", "max_age", ")", "start", "=", "datetime", ".", "date", ".", "today", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "random", ".", "randint", "(", "0", ",", "365", ")", ")", "return", "start", "-", "datetime", ".", "timedelta", "(", "days", "=", "age", "*", "365", ")" ]
Create a random birthday fomr someone between the ages of min_age and max_age
[ "Create", "a", "random", "birthday", "fomr", "someone", "between", "the", "ages", "of", "min_age", "and", "max_age" ]
train
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L142-L148
chris1610/barnum-proj
barnum/gen_data.py
create_pw
def create_pw(length=8, digits=2, upper=2, lower=2): """Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :param length: Maximum no. of characters in the password :type length: int :param digits: Minimum no. of digits in the password :type digits: int :param upper: Minimum no. of upper case letters in the password :type upper: int :param lower: Minimum no. of lower case letters in the password :type lower: int :returns: A random password with the above constaints :rtype: str """ seed(time()) lowercase = string.ascii_lowercase uppercase = string.ascii_uppercase letters = string.ascii_letters password = list( chain( (choice(uppercase) for _ in range(upper)), (choice(lowercase) for _ in range(lower)), (choice(string.digits) for _ in range(digits)), (choice(letters) for _ in range((length - digits - upper - lower))) ) ) return "".join(sample(password, len(password)))
python
def create_pw(length=8, digits=2, upper=2, lower=2): """Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :param length: Maximum no. of characters in the password :type length: int :param digits: Minimum no. of digits in the password :type digits: int :param upper: Minimum no. of upper case letters in the password :type upper: int :param lower: Minimum no. of lower case letters in the password :type lower: int :returns: A random password with the above constaints :rtype: str """ seed(time()) lowercase = string.ascii_lowercase uppercase = string.ascii_uppercase letters = string.ascii_letters password = list( chain( (choice(uppercase) for _ in range(upper)), (choice(lowercase) for _ in range(lower)), (choice(string.digits) for _ in range(digits)), (choice(letters) for _ in range((length - digits - upper - lower))) ) ) return "".join(sample(password, len(password)))
[ "def", "create_pw", "(", "length", "=", "8", ",", "digits", "=", "2", ",", "upper", "=", "2", ",", "lower", "=", "2", ")", ":", "seed", "(", "time", "(", ")", ")", "lowercase", "=", "string", ".", "ascii_lowercase", "uppercase", "=", "string", ".", "ascii_uppercase", "letters", "=", "string", ".", "ascii_letters", "password", "=", "list", "(", "chain", "(", "(", "choice", "(", "uppercase", ")", "for", "_", "in", "range", "(", "upper", ")", ")", ",", "(", "choice", "(", "lowercase", ")", "for", "_", "in", "range", "(", "lower", ")", ")", ",", "(", "choice", "(", "string", ".", "digits", ")", "for", "_", "in", "range", "(", "digits", ")", ")", ",", "(", "choice", "(", "letters", ")", "for", "_", "in", "range", "(", "(", "length", "-", "digits", "-", "upper", "-", "lower", ")", ")", ")", ")", ")", "return", "\"\"", ".", "join", "(", "sample", "(", "password", ",", "len", "(", "password", ")", ")", ")" ]
Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :param length: Maximum no. of characters in the password :type length: int :param digits: Minimum no. of digits in the password :type digits: int :param upper: Minimum no. of upper case letters in the password :type upper: int :param lower: Minimum no. of lower case letters in the password :type lower: int :returns: A random password with the above constaints :rtype: str
[ "Create", "a", "random", "password", "From", "Stackoverflow", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "7479442", "/", "high", "-", "quality", "-", "simple", "-", "random", "-", "password", "-", "generator" ]
train
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L189-L227
chris1610/barnum-proj
barnum/gen_data.py
show_examples
def show_examples(): """ Run through some simple examples """ first, last = create_name() add = create_street() zip, city, state = create_city_state_zip() phone = create_phone(zip) print(first, last) print(add) print("{0:s} {1:s} {2:s}".format(city, state, zip)) print(phone) print(create_sentence()) print(create_paragraphs(num=3)) print(create_cc_number()) expiry = create_date(max_years_future=3) print("{0:%m/%y}".format(expiry)) print(create_email(name=(first, last))) print("Password: {0:s}".format(create_pw())) print(create_company_name()) print(create_job_title()) print("Born on {0:%m/%d/%Y}".format(create_birthday()))
python
def show_examples(): """ Run through some simple examples """ first, last = create_name() add = create_street() zip, city, state = create_city_state_zip() phone = create_phone(zip) print(first, last) print(add) print("{0:s} {1:s} {2:s}".format(city, state, zip)) print(phone) print(create_sentence()) print(create_paragraphs(num=3)) print(create_cc_number()) expiry = create_date(max_years_future=3) print("{0:%m/%y}".format(expiry)) print(create_email(name=(first, last))) print("Password: {0:s}".format(create_pw())) print(create_company_name()) print(create_job_title()) print("Born on {0:%m/%d/%Y}".format(create_birthday()))
[ "def", "show_examples", "(", ")", ":", "first", ",", "last", "=", "create_name", "(", ")", "add", "=", "create_street", "(", ")", "zip", ",", "city", ",", "state", "=", "create_city_state_zip", "(", ")", "phone", "=", "create_phone", "(", "zip", ")", "print", "(", "first", ",", "last", ")", "print", "(", "add", ")", "print", "(", "\"{0:s} {1:s} {2:s}\"", ".", "format", "(", "city", ",", "state", ",", "zip", ")", ")", "print", "(", "phone", ")", "print", "(", "create_sentence", "(", ")", ")", "print", "(", "create_paragraphs", "(", "num", "=", "3", ")", ")", "print", "(", "create_cc_number", "(", ")", ")", "expiry", "=", "create_date", "(", "max_years_future", "=", "3", ")", "print", "(", "\"{0:%m/%y}\"", ".", "format", "(", "expiry", ")", ")", "print", "(", "create_email", "(", "name", "=", "(", "first", ",", "last", ")", ")", ")", "print", "(", "\"Password: {0:s}\"", ".", "format", "(", "create_pw", "(", ")", ")", ")", "print", "(", "create_company_name", "(", ")", ")", "print", "(", "create_job_title", "(", ")", ")", "print", "(", "\"Born on {0:%m/%d/%Y}\"", ".", "format", "(", "create_birthday", "(", ")", ")", ")" ]
Run through some simple examples
[ "Run", "through", "some", "simple", "examples" ]
train
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L229-L249
peterwittek/ncpol2sdpa
ncpol2sdpa/mosek_utils.py
convert_to_mosek_index
def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row): """MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA. """ block_index, i, j = convert_row_to_sdpa_index(block_struct, row_offsets, row) offset = block_offsets[block_index] ci = offset + i cj = offset + j return cj, ci
python
def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row): """MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA. """ block_index, i, j = convert_row_to_sdpa_index(block_struct, row_offsets, row) offset = block_offsets[block_index] ci = offset + i cj = offset + j return cj, ci
[ "def", "convert_to_mosek_index", "(", "block_struct", ",", "row_offsets", ",", "block_offsets", ",", "row", ")", ":", "block_index", ",", "i", ",", "j", "=", "convert_row_to_sdpa_index", "(", "block_struct", ",", "row_offsets", ",", "row", ")", "offset", "=", "block_offsets", "[", "block_index", "]", "ci", "=", "offset", "+", "i", "cj", "=", "offset", "+", "j", "return", "cj", ",", "ci" ]
MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA.
[ "MOSEK", "requires", "a", "specific", "sparse", "format", "to", "define", "the", "lower", "-", "triangular", "part", "of", "a", "symmetric", "matrix", ".", "This", "function", "does", "the", "conversion", "from", "the", "sparse", "upper", "triangular", "matrix", "format", "of", "Ncpol2SDPA", "." ]
train
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/mosek_utils.py#L102-L113
peterwittek/ncpol2sdpa
ncpol2sdpa/mosek_utils.py
convert_to_mosek_matrix
def convert_to_mosek_matrix(sdp): """Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices. """ barci = [] barcj = [] barcval = [] barai = [] baraj = [] baraval = [] for k in range(sdp.n_vars): barai.append([]) baraj.append([]) baraval.append([]) row_offsets = [0] block_offsets = [0] cumulative_sum = 0 cumulative_square_sum = 0 for block_size in sdp.block_struct: cumulative_sum += block_size cumulative_square_sum += block_size ** 2 row_offsets.append(cumulative_square_sum) block_offsets.append(cumulative_sum) for row in range(len(sdp.F.rows)): if len(sdp.F.rows[row]) > 0: col_index = 0 for k in sdp.F.rows[row]: value = sdp.F.data[row][col_index] i, j = convert_to_mosek_index(sdp.block_struct, row_offsets, block_offsets, row) if k > 0: barai[k - 1].append(i) baraj[k - 1].append(j) baraval[k - 1].append(-value) else: barci.append(i) barcj.append(j) barcval.append(value) col_index += 1 return barci, barcj, barcval, barai, baraj, baraval
python
def convert_to_mosek_matrix(sdp): """Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices. """ barci = [] barcj = [] barcval = [] barai = [] baraj = [] baraval = [] for k in range(sdp.n_vars): barai.append([]) baraj.append([]) baraval.append([]) row_offsets = [0] block_offsets = [0] cumulative_sum = 0 cumulative_square_sum = 0 for block_size in sdp.block_struct: cumulative_sum += block_size cumulative_square_sum += block_size ** 2 row_offsets.append(cumulative_square_sum) block_offsets.append(cumulative_sum) for row in range(len(sdp.F.rows)): if len(sdp.F.rows[row]) > 0: col_index = 0 for k in sdp.F.rows[row]: value = sdp.F.data[row][col_index] i, j = convert_to_mosek_index(sdp.block_struct, row_offsets, block_offsets, row) if k > 0: barai[k - 1].append(i) baraj[k - 1].append(j) baraval[k - 1].append(-value) else: barci.append(i) barcj.append(j) barcval.append(value) col_index += 1 return barci, barcj, barcval, barai, baraj, baraval
[ "def", "convert_to_mosek_matrix", "(", "sdp", ")", ":", "barci", "=", "[", "]", "barcj", "=", "[", "]", "barcval", "=", "[", "]", "barai", "=", "[", "]", "baraj", "=", "[", "]", "baraval", "=", "[", "]", "for", "k", "in", "range", "(", "sdp", ".", "n_vars", ")", ":", "barai", ".", "append", "(", "[", "]", ")", "baraj", ".", "append", "(", "[", "]", ")", "baraval", ".", "append", "(", "[", "]", ")", "row_offsets", "=", "[", "0", "]", "block_offsets", "=", "[", "0", "]", "cumulative_sum", "=", "0", "cumulative_square_sum", "=", "0", "for", "block_size", "in", "sdp", ".", "block_struct", ":", "cumulative_sum", "+=", "block_size", "cumulative_square_sum", "+=", "block_size", "**", "2", "row_offsets", ".", "append", "(", "cumulative_square_sum", ")", "block_offsets", ".", "append", "(", "cumulative_sum", ")", "for", "row", "in", "range", "(", "len", "(", "sdp", ".", "F", ".", "rows", ")", ")", ":", "if", "len", "(", "sdp", ".", "F", ".", "rows", "[", "row", "]", ")", ">", "0", ":", "col_index", "=", "0", "for", "k", "in", "sdp", ".", "F", ".", "rows", "[", "row", "]", ":", "value", "=", "sdp", ".", "F", ".", "data", "[", "row", "]", "[", "col_index", "]", "i", ",", "j", "=", "convert_to_mosek_index", "(", "sdp", ".", "block_struct", ",", "row_offsets", ",", "block_offsets", ",", "row", ")", "if", "k", ">", "0", ":", "barai", "[", "k", "-", "1", "]", ".", "append", "(", "i", ")", "baraj", "[", "k", "-", "1", "]", ".", "append", "(", "j", ")", "baraval", "[", "k", "-", "1", "]", ".", "append", "(", "-", "value", ")", "else", ":", "barci", ".", "append", "(", "i", ")", "barcj", ".", "append", "(", "j", ")", "barcval", ".", "append", "(", "value", ")", "col_index", "+=", "1", "return", "barci", ",", "barcj", ",", "barcval", ",", "barai", ",", "baraj", ",", "baraval" ]
Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices.
[ "Converts", "the", "entire", "sparse", "representation", "of", "the", "Fi", "constraint", "matrices", "to", "sparse", "MOSEK", "matrices", "." ]
train
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/mosek_utils.py#L116-L155
peterwittek/ncpol2sdpa
ncpol2sdpa/mosek_utils.py
convert_to_mosek
def convert_to_mosek(sdp): """Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`. """ import mosek # Cheat when variables are complex and convert with PICOS if sdp.complex_matrix: from .picos_utils import convert_to_picos Problem = convert_to_picos(sdp).to_real() Problem._make_mosek_instance() task = Problem.msk_task if sdp.verbose > 0: task.set_Stream(mosek.streamtype.log, streamprinter) return task barci, barcj, barcval, barai, baraj, baraval = \ convert_to_mosek_matrix(sdp) bkc = [mosek.boundkey.fx] * sdp.n_vars blc = [-v for v in sdp.obj_facvar] buc = [-v for v in sdp.obj_facvar] env = mosek.Env() task = env.Task(0, 0) if sdp.verbose > 0: task.set_Stream(mosek.streamtype.log, streamprinter) numvar = 0 numcon = len(bkc) BARVARDIM = [sum(sdp.block_struct)] task.appendvars(numvar) task.appendcons(numcon) task.appendbarvars(BARVARDIM) for i in range(numcon): task.putconbound(i, bkc[i], blc[i], buc[i]) symc = task.appendsparsesymmat(BARVARDIM[0], barci, barcj, barcval) task.putbarcj(0, [symc], [1.0]) for i in range(len(barai)): syma = task.appendsparsesymmat(BARVARDIM[0], barai[i], baraj[i], baraval[i]) task.putbaraij(i, 0, [syma], [1.0]) # Input the objective sense (minimize/maximize) task.putobjsense(mosek.objsense.minimize) return task
python
def convert_to_mosek(sdp): """Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`. """ import mosek # Cheat when variables are complex and convert with PICOS if sdp.complex_matrix: from .picos_utils import convert_to_picos Problem = convert_to_picos(sdp).to_real() Problem._make_mosek_instance() task = Problem.msk_task if sdp.verbose > 0: task.set_Stream(mosek.streamtype.log, streamprinter) return task barci, barcj, barcval, barai, baraj, baraval = \ convert_to_mosek_matrix(sdp) bkc = [mosek.boundkey.fx] * sdp.n_vars blc = [-v for v in sdp.obj_facvar] buc = [-v for v in sdp.obj_facvar] env = mosek.Env() task = env.Task(0, 0) if sdp.verbose > 0: task.set_Stream(mosek.streamtype.log, streamprinter) numvar = 0 numcon = len(bkc) BARVARDIM = [sum(sdp.block_struct)] task.appendvars(numvar) task.appendcons(numcon) task.appendbarvars(BARVARDIM) for i in range(numcon): task.putconbound(i, bkc[i], blc[i], buc[i]) symc = task.appendsparsesymmat(BARVARDIM[0], barci, barcj, barcval) task.putbarcj(0, [symc], [1.0]) for i in range(len(barai)): syma = task.appendsparsesymmat(BARVARDIM[0], barai[i], baraj[i], baraval[i]) task.putbaraij(i, 0, [syma], [1.0]) # Input the objective sense (minimize/maximize) task.putobjsense(mosek.objsense.minimize) return task
[ "def", "convert_to_mosek", "(", "sdp", ")", ":", "import", "mosek", "# Cheat when variables are complex and convert with PICOS", "if", "sdp", ".", "complex_matrix", ":", "from", ".", "picos_utils", "import", "convert_to_picos", "Problem", "=", "convert_to_picos", "(", "sdp", ")", ".", "to_real", "(", ")", "Problem", ".", "_make_mosek_instance", "(", ")", "task", "=", "Problem", ".", "msk_task", "if", "sdp", ".", "verbose", ">", "0", ":", "task", ".", "set_Stream", "(", "mosek", ".", "streamtype", ".", "log", ",", "streamprinter", ")", "return", "task", "barci", ",", "barcj", ",", "barcval", ",", "barai", ",", "baraj", ",", "baraval", "=", "convert_to_mosek_matrix", "(", "sdp", ")", "bkc", "=", "[", "mosek", ".", "boundkey", ".", "fx", "]", "*", "sdp", ".", "n_vars", "blc", "=", "[", "-", "v", "for", "v", "in", "sdp", ".", "obj_facvar", "]", "buc", "=", "[", "-", "v", "for", "v", "in", "sdp", ".", "obj_facvar", "]", "env", "=", "mosek", ".", "Env", "(", ")", "task", "=", "env", ".", "Task", "(", "0", ",", "0", ")", "if", "sdp", ".", "verbose", ">", "0", ":", "task", ".", "set_Stream", "(", "mosek", ".", "streamtype", ".", "log", ",", "streamprinter", ")", "numvar", "=", "0", "numcon", "=", "len", "(", "bkc", ")", "BARVARDIM", "=", "[", "sum", "(", "sdp", ".", "block_struct", ")", "]", "task", ".", "appendvars", "(", "numvar", ")", "task", ".", "appendcons", "(", "numcon", ")", "task", ".", "appendbarvars", "(", "BARVARDIM", ")", "for", "i", "in", "range", "(", "numcon", ")", ":", "task", ".", "putconbound", "(", "i", ",", "bkc", "[", "i", "]", ",", "blc", "[", "i", "]", ",", "buc", "[", "i", "]", ")", "symc", "=", "task", ".", "appendsparsesymmat", "(", "BARVARDIM", "[", "0", "]", ",", "barci", ",", "barcj", ",", "barcval", ")", "task", ".", "putbarcj", "(", "0", ",", "[", "symc", "]", ",", "[", "1.0", "]", ")", "for", "i", "in", "range", "(", "len", "(", "barai", ")", ")", ":", "syma", "=", "task", ".", "appendsparsesymmat", "(", "BARVARDIM", "[", "0", "]", ",", "barai", "[", "i", "]", ",", "baraj", "[", "i", "]", ",", "baraval", "[", "i", "]", ")", "task", ".", "putbaraij", "(", "i", ",", "0", ",", "[", "syma", "]", ",", "[", "1.0", "]", ")", "# Input the objective sense (minimize/maximize)", "task", ".", "putobjsense", "(", "mosek", ".", "objsense", ".", "minimize", ")", "return", "task" ]
Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`.
[ "Convert", "an", "SDP", "relaxation", "to", "a", "MOSEK", "task", "." ]
train
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/mosek_utils.py#L158-L208
bpython/curtsies
docs/ansi.py
ANSIColorParser._add_text
def _add_text(self, text): """ If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there are no pending nodes. """ if text: if self.pending_nodes: self.pending_nodes[-1].append(nodes.Text(text)) else: self.new_nodes.append(nodes.Text(text))
python
def _add_text(self, text): """ If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there are no pending nodes. """ if text: if self.pending_nodes: self.pending_nodes[-1].append(nodes.Text(text)) else: self.new_nodes.append(nodes.Text(text))
[ "def", "_add_text", "(", "self", ",", "text", ")", ":", "if", "text", ":", "if", "self", ".", "pending_nodes", ":", "self", ".", "pending_nodes", "[", "-", "1", "]", ".", "append", "(", "nodes", ".", "Text", "(", "text", ")", ")", "else", ":", "self", ".", "new_nodes", ".", "append", "(", "nodes", ".", "Text", "(", "text", ")", ")" ]
If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there are no pending nodes.
[ "If", "text", "is", "not", "empty", "append", "a", "new", "Text", "node", "to", "the", "most", "recent", "pending", "node", "if", "there", "is", "any", "or", "to", "the", "new", "nodes", "if", "there", "are", "no", "pending", "nodes", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/docs/ansi.py#L96-L106
bpython/curtsies
setup.py
version
def version(): """Return version string.""" with open(os.path.join('curtsies', '__init__.py')) as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
python
def version(): """Return version string.""" with open(os.path.join('curtsies', '__init__.py')) as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
[ "def", "version", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "'curtsies'", ",", "'__init__.py'", ")", ")", "as", "input_file", ":", "for", "line", "in", "input_file", ":", "if", "line", ".", "startswith", "(", "'__version__'", ")", ":", "return", "ast", ".", "parse", "(", "line", ")", ".", "body", "[", "0", "]", ".", "value", ".", "s" ]
Return version string.
[ "Return", "version", "string", "." ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/setup.py#L6-L11
bpython/curtsies
curtsies/formatstringarray.py
fsarray
def fsarray(strings, *args, **kwargs): """fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the strings are of length greater than this width""" strings = list(strings) if 'width' in kwargs: width = kwargs['width'] del kwargs['width'] if strings and max(len(s) for s in strings) > width: raise ValueError("Those strings won't fit for width %d" % width) else: width = max(len(s) for s in strings) if strings else 0 fstrings = [s if isinstance(s, FmtStr) else fmtstr(s, *args, **kwargs) for s in strings] arr = FSArray(len(fstrings), width, *args, **kwargs) rows = [fs.setslice_with_length(0, len(s), s, width) for fs, s in zip(arr.rows, fstrings)] arr.rows = rows return arr
python
def fsarray(strings, *args, **kwargs): """fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the strings are of length greater than this width""" strings = list(strings) if 'width' in kwargs: width = kwargs['width'] del kwargs['width'] if strings and max(len(s) for s in strings) > width: raise ValueError("Those strings won't fit for width %d" % width) else: width = max(len(s) for s in strings) if strings else 0 fstrings = [s if isinstance(s, FmtStr) else fmtstr(s, *args, **kwargs) for s in strings] arr = FSArray(len(fstrings), width, *args, **kwargs) rows = [fs.setslice_with_length(0, len(s), s, width) for fs, s in zip(arr.rows, fstrings)] arr.rows = rows return arr
[ "def", "fsarray", "(", "strings", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "strings", "=", "list", "(", "strings", ")", "if", "'width'", "in", "kwargs", ":", "width", "=", "kwargs", "[", "'width'", "]", "del", "kwargs", "[", "'width'", "]", "if", "strings", "and", "max", "(", "len", "(", "s", ")", "for", "s", "in", "strings", ")", ">", "width", ":", "raise", "ValueError", "(", "\"Those strings won't fit for width %d\"", "%", "width", ")", "else", ":", "width", "=", "max", "(", "len", "(", "s", ")", "for", "s", "in", "strings", ")", "if", "strings", "else", "0", "fstrings", "=", "[", "s", "if", "isinstance", "(", "s", ",", "FmtStr", ")", "else", "fmtstr", "(", "s", ",", "*", "args", ",", "*", "*", "kwargs", ")", "for", "s", "in", "strings", "]", "arr", "=", "FSArray", "(", "len", "(", "fstrings", ")", ",", "width", ",", "*", "args", ",", "*", "*", "kwargs", ")", "rows", "=", "[", "fs", ".", "setslice_with_length", "(", "0", ",", "len", "(", "s", ")", ",", "s", ",", "width", ")", "for", "fs", ",", "s", "in", "zip", "(", "arr", ".", "rows", ",", "fstrings", ")", "]", "arr", ".", "rows", "=", "rows", "return", "arr" ]
fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the strings are of length greater than this width
[ "fsarray", "(", "list_of_FmtStrs_or_strings", "width", "=", "None", ")", "-", ">", "FSArray" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstringarray.py#L40-L60
bpython/curtsies
curtsies/formatstringarray.py
FSArray.diff
def diff(cls, a, b, ignore_formatting=False): """Returns two FSArrays with differences underlined""" def underline(x): return u'\x1b[4m%s\x1b[0m' % (x,) def blink(x): return u'\x1b[5m%s\x1b[0m' % (x,) a_rows = [] b_rows = [] max_width = max([len(row) for row in a] + [len(row) for row in b]) a_lengths = [] b_lengths = [] for a_row, b_row in zip(a, b): a_lengths.append(len(a_row)) b_lengths.append(len(b_row)) extra_a = u'`' * (max_width - len(a_row)) extra_b = u'`' * (max_width - len(b_row)) a_line = u'' b_line = u'' for a_char, b_char in zip(a_row + extra_a, b_row + extra_b): if ignore_formatting: a_char_for_eval = a_char.s if isinstance(a_char, FmtStr) else a_char b_char_for_eval = b_char.s if isinstance(b_char, FmtStr) else b_char else: a_char_for_eval = a_char b_char_for_eval = b_char if a_char_for_eval == b_char_for_eval: a_line += actualize(a_char) b_line += actualize(b_char) else: a_line += underline(blink(actualize(a_char))) b_line += underline(blink(actualize(b_char))) a_rows.append(a_line) b_rows.append(b_line) hdiff = '\n'.join(a_line + u' %3d | %3d ' % (a_len, b_len) + b_line for a_line, b_line, a_len, b_len in zip(a_rows, b_rows, a_lengths, b_lengths)) return hdiff
python
def diff(cls, a, b, ignore_formatting=False): """Returns two FSArrays with differences underlined""" def underline(x): return u'\x1b[4m%s\x1b[0m' % (x,) def blink(x): return u'\x1b[5m%s\x1b[0m' % (x,) a_rows = [] b_rows = [] max_width = max([len(row) for row in a] + [len(row) for row in b]) a_lengths = [] b_lengths = [] for a_row, b_row in zip(a, b): a_lengths.append(len(a_row)) b_lengths.append(len(b_row)) extra_a = u'`' * (max_width - len(a_row)) extra_b = u'`' * (max_width - len(b_row)) a_line = u'' b_line = u'' for a_char, b_char in zip(a_row + extra_a, b_row + extra_b): if ignore_formatting: a_char_for_eval = a_char.s if isinstance(a_char, FmtStr) else a_char b_char_for_eval = b_char.s if isinstance(b_char, FmtStr) else b_char else: a_char_for_eval = a_char b_char_for_eval = b_char if a_char_for_eval == b_char_for_eval: a_line += actualize(a_char) b_line += actualize(b_char) else: a_line += underline(blink(actualize(a_char))) b_line += underline(blink(actualize(b_char))) a_rows.append(a_line) b_rows.append(b_line) hdiff = '\n'.join(a_line + u' %3d | %3d ' % (a_len, b_len) + b_line for a_line, b_line, a_len, b_len in zip(a_rows, b_rows, a_lengths, b_lengths)) return hdiff
[ "def", "diff", "(", "cls", ",", "a", ",", "b", ",", "ignore_formatting", "=", "False", ")", ":", "def", "underline", "(", "x", ")", ":", "return", "u'\\x1b[4m%s\\x1b[0m'", "%", "(", "x", ",", ")", "def", "blink", "(", "x", ")", ":", "return", "u'\\x1b[5m%s\\x1b[0m'", "%", "(", "x", ",", ")", "a_rows", "=", "[", "]", "b_rows", "=", "[", "]", "max_width", "=", "max", "(", "[", "len", "(", "row", ")", "for", "row", "in", "a", "]", "+", "[", "len", "(", "row", ")", "for", "row", "in", "b", "]", ")", "a_lengths", "=", "[", "]", "b_lengths", "=", "[", "]", "for", "a_row", ",", "b_row", "in", "zip", "(", "a", ",", "b", ")", ":", "a_lengths", ".", "append", "(", "len", "(", "a_row", ")", ")", "b_lengths", ".", "append", "(", "len", "(", "b_row", ")", ")", "extra_a", "=", "u'`'", "*", "(", "max_width", "-", "len", "(", "a_row", ")", ")", "extra_b", "=", "u'`'", "*", "(", "max_width", "-", "len", "(", "b_row", ")", ")", "a_line", "=", "u''", "b_line", "=", "u''", "for", "a_char", ",", "b_char", "in", "zip", "(", "a_row", "+", "extra_a", ",", "b_row", "+", "extra_b", ")", ":", "if", "ignore_formatting", ":", "a_char_for_eval", "=", "a_char", ".", "s", "if", "isinstance", "(", "a_char", ",", "FmtStr", ")", "else", "a_char", "b_char_for_eval", "=", "b_char", ".", "s", "if", "isinstance", "(", "b_char", ",", "FmtStr", ")", "else", "b_char", "else", ":", "a_char_for_eval", "=", "a_char", "b_char_for_eval", "=", "b_char", "if", "a_char_for_eval", "==", "b_char_for_eval", ":", "a_line", "+=", "actualize", "(", "a_char", ")", "b_line", "+=", "actualize", "(", "b_char", ")", "else", ":", "a_line", "+=", "underline", "(", "blink", "(", "actualize", "(", "a_char", ")", ")", ")", "b_line", "+=", "underline", "(", "blink", "(", "actualize", "(", "b_char", ")", ")", ")", "a_rows", ".", "append", "(", "a_line", ")", "b_rows", ".", "append", "(", "b_line", ")", "hdiff", "=", "'\\n'", ".", "join", "(", "a_line", "+", "u' %3d | %3d '", "%", "(", "a_len", ",", "b_len", ")", "+", "b_line", "for", "a_line", ",", "b_line", ",", "a_len", ",", "b_len", "in", "zip", "(", "a_rows", ",", "b_rows", ",", "a_lengths", ",", "b_lengths", ")", ")", "return", "hdiff" ]
Returns two FSArrays with differences underlined
[ "Returns", "two", "FSArrays", "with", "differences", "underlined" ]
train
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstringarray.py#L139-L171
kmn/coincheck
coincheck/order.py
Order.create
def create(self,rate, amount, order_type, pair): ''' create new order function :param rate: float :param amount: float :param order_type: str; set 'buy' or 'sell' :param pair: str; set 'btc_jpy' ''' nonce = nounce() payload = { 'rate': rate, 'amount': amount, 'order_type': order_type, 'pair': pair } url= 'https://coincheck.com/api/exchange/orders' body = 'rate={rate}&amount={amount}&order_type={order_type}&pair={pair}'.format(**payload) message = nonce + url + body signature = hmac.new(self.secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest() headers = { 'ACCESS-KEY' : self.access_key, 'ACCESS-NONCE' : nonce, 'ACCESS-SIGNATURE': signature } r = requests.post(url,headers=headers,data=body) return json.loads(r.text)
python
def create(self,rate, amount, order_type, pair): ''' create new order function :param rate: float :param amount: float :param order_type: str; set 'buy' or 'sell' :param pair: str; set 'btc_jpy' ''' nonce = nounce() payload = { 'rate': rate, 'amount': amount, 'order_type': order_type, 'pair': pair } url= 'https://coincheck.com/api/exchange/orders' body = 'rate={rate}&amount={amount}&order_type={order_type}&pair={pair}'.format(**payload) message = nonce + url + body signature = hmac.new(self.secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest() headers = { 'ACCESS-KEY' : self.access_key, 'ACCESS-NONCE' : nonce, 'ACCESS-SIGNATURE': signature } r = requests.post(url,headers=headers,data=body) return json.loads(r.text)
[ "def", "create", "(", "self", ",", "rate", ",", "amount", ",", "order_type", ",", "pair", ")", ":", "nonce", "=", "nounce", "(", ")", "payload", "=", "{", "'rate'", ":", "rate", ",", "'amount'", ":", "amount", ",", "'order_type'", ":", "order_type", ",", "'pair'", ":", "pair", "}", "url", "=", "'https://coincheck.com/api/exchange/orders'", "body", "=", "'rate={rate}&amount={amount}&order_type={order_type}&pair={pair}'", ".", "format", "(", "*", "*", "payload", ")", "message", "=", "nonce", "+", "url", "+", "body", "signature", "=", "hmac", ".", "new", "(", "self", ".", "secret_key", ".", "encode", "(", "'utf-8'", ")", ",", "message", ".", "encode", "(", "'utf-8'", ")", ",", "hashlib", ".", "sha256", ")", ".", "hexdigest", "(", ")", "headers", "=", "{", "'ACCESS-KEY'", ":", "self", ".", "access_key", ",", "'ACCESS-NONCE'", ":", "nonce", ",", "'ACCESS-SIGNATURE'", ":", "signature", "}", "r", "=", "requests", ".", "post", "(", "url", ",", "headers", "=", "headers", ",", "data", "=", "body", ")", "return", "json", ".", "loads", "(", "r", ".", "text", ")" ]
create new order function :param rate: float :param amount: float :param order_type: str; set 'buy' or 'sell' :param pair: str; set 'btc_jpy'
[ "create", "new", "order", "function", ":", "param", "rate", ":", "float", ":", "param", "amount", ":", "float", ":", "param", "order_type", ":", "str", ";", "set", "buy", "or", "sell", ":", "param", "pair", ":", "str", ";", "set", "btc_jpy" ]
train
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/order.py#L20-L43
kmn/coincheck
coincheck/order.py
Order.cancel
def cancel(self,order_id): ''' cancel the specified order :param order_id: order_id to be canceled ''' url= 'https://coincheck.com/api/exchange/orders/' + order_id headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.delete(url,headers=headers) return json.loads(r.text)
python
def cancel(self,order_id): ''' cancel the specified order :param order_id: order_id to be canceled ''' url= 'https://coincheck.com/api/exchange/orders/' + order_id headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.delete(url,headers=headers) return json.loads(r.text)
[ "def", "cancel", "(", "self", ",", "order_id", ")", ":", "url", "=", "'https://coincheck.com/api/exchange/orders/'", "+", "order_id", "headers", "=", "make_header", "(", "url", ",", "access_key", "=", "self", ".", "access_key", ",", "secret_key", "=", "self", ".", "secret_key", ")", "r", "=", "requests", ".", "delete", "(", "url", ",", "headers", "=", "headers", ")", "return", "json", ".", "loads", "(", "r", ".", "text", ")" ]
cancel the specified order :param order_id: order_id to be canceled
[ "cancel", "the", "specified", "order", ":", "param", "order_id", ":", "order_id", "to", "be", "canceled" ]
train
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/order.py#L59-L66
kmn/coincheck
coincheck/order.py
Order.history
def history(self): ''' show payment history ''' url= 'https://coincheck.com/api/exchange/orders/transactions' headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.get(url,headers=headers) return json.loads(r.text)
python
def history(self): ''' show payment history ''' url= 'https://coincheck.com/api/exchange/orders/transactions' headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.get(url,headers=headers) return json.loads(r.text)
[ "def", "history", "(", "self", ")", ":", "url", "=", "'https://coincheck.com/api/exchange/orders/transactions'", "headers", "=", "make_header", "(", "url", ",", "access_key", "=", "self", ".", "access_key", ",", "secret_key", "=", "self", ".", "secret_key", ")", "r", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ")", "return", "json", ".", "loads", "(", "r", ".", "text", ")" ]
show payment history
[ "show", "payment", "history" ]
train
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/order.py#L68-L74
mottosso/be
be/vendor/click/_termui_impl.py
_length_hint
def _length_hint(obj): """Returns the length hint of an object.""" try: return len(obj) except TypeError: try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hint(obj) except TypeError: return None if hint is NotImplemented or \ not isinstance(hint, (int, long)) or \ hint < 0: return None return hint
python
def _length_hint(obj): """Returns the length hint of an object.""" try: return len(obj) except TypeError: try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hint(obj) except TypeError: return None if hint is NotImplemented or \ not isinstance(hint, (int, long)) or \ hint < 0: return None return hint
[ "def", "_length_hint", "(", "obj", ")", ":", "try", ":", "return", "len", "(", "obj", ")", "except", "TypeError", ":", "try", ":", "get_hint", "=", "type", "(", "obj", ")", ".", "__length_hint__", "except", "AttributeError", ":", "return", "None", "try", ":", "hint", "=", "get_hint", "(", "obj", ")", "except", "TypeError", ":", "return", "None", "if", "hint", "is", "NotImplemented", "or", "not", "isinstance", "(", "hint", ",", "(", "int", ",", "long", ")", ")", "or", "hint", "<", "0", ":", "return", "None", "return", "hint" ]
Returns the length hint of an object.
[ "Returns", "the", "length", "hint", "of", "an", "object", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/_termui_impl.py#L30-L47
mottosso/be
be/vendor/click/_termui_impl.py
pager
def pager(text, color=None): """Decide what method to use for paging through text.""" stdout = _default_text_stdout() if not isatty(sys.stdin) or not isatty(stdout): return _nullpager(stdout, text, color) if 'PAGER' in os.environ: if WIN: return _tempfilepager(text, os.environ['PAGER'], color) return _pipepager(text, os.environ['PAGER'], color) if os.environ.get('TERM') in ('dumb', 'emacs'): return _nullpager(stdout, text, color) if WIN or sys.platform.startswith('os2'): return _tempfilepager(text, 'more <', color) if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: return _pipepager(text, 'less', color) import tempfile fd, filename = tempfile.mkstemp() os.close(fd) try: if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0: return _pipepager(text, 'more', color) return _nullpager(stdout, text, color) finally: os.unlink(filename)
python
def pager(text, color=None): """Decide what method to use for paging through text.""" stdout = _default_text_stdout() if not isatty(sys.stdin) or not isatty(stdout): return _nullpager(stdout, text, color) if 'PAGER' in os.environ: if WIN: return _tempfilepager(text, os.environ['PAGER'], color) return _pipepager(text, os.environ['PAGER'], color) if os.environ.get('TERM') in ('dumb', 'emacs'): return _nullpager(stdout, text, color) if WIN or sys.platform.startswith('os2'): return _tempfilepager(text, 'more <', color) if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: return _pipepager(text, 'less', color) import tempfile fd, filename = tempfile.mkstemp() os.close(fd) try: if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0: return _pipepager(text, 'more', color) return _nullpager(stdout, text, color) finally: os.unlink(filename)
[ "def", "pager", "(", "text", ",", "color", "=", "None", ")", ":", "stdout", "=", "_default_text_stdout", "(", ")", "if", "not", "isatty", "(", "sys", ".", "stdin", ")", "or", "not", "isatty", "(", "stdout", ")", ":", "return", "_nullpager", "(", "stdout", ",", "text", ",", "color", ")", "if", "'PAGER'", "in", "os", ".", "environ", ":", "if", "WIN", ":", "return", "_tempfilepager", "(", "text", ",", "os", ".", "environ", "[", "'PAGER'", "]", ",", "color", ")", "return", "_pipepager", "(", "text", ",", "os", ".", "environ", "[", "'PAGER'", "]", ",", "color", ")", "if", "os", ".", "environ", ".", "get", "(", "'TERM'", ")", "in", "(", "'dumb'", ",", "'emacs'", ")", ":", "return", "_nullpager", "(", "stdout", ",", "text", ",", "color", ")", "if", "WIN", "or", "sys", ".", "platform", ".", "startswith", "(", "'os2'", ")", ":", "return", "_tempfilepager", "(", "text", ",", "'more <'", ",", "color", ")", "if", "hasattr", "(", "os", ",", "'system'", ")", "and", "os", ".", "system", "(", "'(less) 2>/dev/null'", ")", "==", "0", ":", "return", "_pipepager", "(", "text", ",", "'less'", ",", "color", ")", "import", "tempfile", "fd", ",", "filename", "=", "tempfile", ".", "mkstemp", "(", ")", "os", ".", "close", "(", "fd", ")", "try", ":", "if", "hasattr", "(", "os", ",", "'system'", ")", "and", "os", ".", "system", "(", "'more \"%s\"'", "%", "filename", ")", "==", "0", ":", "return", "_pipepager", "(", "text", ",", "'more'", ",", "color", ")", "return", "_nullpager", "(", "stdout", ",", "text", ",", "color", ")", "finally", ":", "os", ".", "unlink", "(", "filename", ")" ]
Decide what method to use for paging through text.
[ "Decide", "what", "method", "to", "use", "for", "paging", "through", "text", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/_termui_impl.py#L255-L279
mottosso/be
be/vendor/requests/packages/urllib3/util/retry.py
Retry.from_int
def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redirect) and None new_retries = cls(retries, redirect=redirect) log.debug("Converted retries value: %r -> %r" % (retries, new_retries)) return new_retries
python
def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redirect) and None new_retries = cls(retries, redirect=redirect) log.debug("Converted retries value: %r -> %r" % (retries, new_retries)) return new_retries
[ "def", "from_int", "(", "cls", ",", "retries", ",", "redirect", "=", "True", ",", "default", "=", "None", ")", ":", "if", "retries", "is", "None", ":", "retries", "=", "default", "if", "default", "is", "not", "None", "else", "cls", ".", "DEFAULT", "if", "isinstance", "(", "retries", ",", "Retry", ")", ":", "return", "retries", "redirect", "=", "bool", "(", "redirect", ")", "and", "None", "new_retries", "=", "cls", "(", "retries", ",", "redirect", "=", "redirect", ")", "log", ".", "debug", "(", "\"Converted retries value: %r -> %r\"", "%", "(", "retries", ",", "new_retries", ")", ")", "return", "new_retries" ]
Backwards-compatibility for the old retries format.
[ "Backwards", "-", "compatibility", "for", "the", "old", "retries", "format", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/retry.py#L145-L156
mottosso/be
be/vendor/requests/packages/urllib3/util/retry.py
Retry.get_backoff_time
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ if self._observed_errors <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1)) return min(self.BACKOFF_MAX, backoff_value)
python
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ if self._observed_errors <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1)) return min(self.BACKOFF_MAX, backoff_value)
[ "def", "get_backoff_time", "(", "self", ")", ":", "if", "self", ".", "_observed_errors", "<=", "1", ":", "return", "0", "backoff_value", "=", "self", ".", "backoff_factor", "*", "(", "2", "**", "(", "self", ".", "_observed_errors", "-", "1", ")", ")", "return", "min", "(", "self", ".", "BACKOFF_MAX", ",", "backoff_value", ")" ]
Formula for computing the current backoff :rtype: float
[ "Formula", "for", "computing", "the", "current", "backoff" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/retry.py#L158-L167
mottosso/be
be/vendor/requests/packages/urllib3/util/retry.py
Retry.is_forced_retry
def is_forced_retry(self, method, status_code): """ Is this method/status code retryable? (Based on method/codes whitelists) """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False return self.status_forcelist and status_code in self.status_forcelist
python
def is_forced_retry(self, method, status_code): """ Is this method/status code retryable? (Based on method/codes whitelists) """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False return self.status_forcelist and status_code in self.status_forcelist
[ "def", "is_forced_retry", "(", "self", ",", "method", ",", "status_code", ")", ":", "if", "self", ".", "method_whitelist", "and", "method", ".", "upper", "(", ")", "not", "in", "self", ".", "method_whitelist", ":", "return", "False", "return", "self", ".", "status_forcelist", "and", "status_code", "in", "self", ".", "status_forcelist" ]
Is this method/status code retryable? (Based on method/codes whitelists)
[ "Is", "this", "method", "/", "status", "code", "retryable?", "(", "Based", "on", "method", "/", "codes", "whitelists", ")" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/retry.py#L192-L198
mottosso/be
be/vendor/click/types.py
convert_type
def convert_type(ty, default=None): """Converts a callable or python ty into the most appropriate param ty. """ if isinstance(ty, tuple): return Tuple(ty) if isinstance(ty, ParamType): return ty guessed_type = False if ty is None and default is not None: ty = type(default) guessed_type = True if ty is text_type or ty is str or ty is None: return STRING if ty is int: return INT # Booleans are only okay if not guessed. This is done because for # flags the default value is actually a bit of a lie in that it # indicates which of the flags is the one we want. See get_default() # for more information. if ty is bool and not guessed_type: return BOOL if ty is float: return FLOAT if guessed_type: return STRING # Catch a common mistake if __debug__: try: if issubclass(ty, ParamType): raise AssertionError('Attempted to use an uninstantiated ' 'parameter type (%s).' % ty) except TypeError: pass return FuncParamType(ty)
python
def convert_type(ty, default=None): """Converts a callable or python ty into the most appropriate param ty. """ if isinstance(ty, tuple): return Tuple(ty) if isinstance(ty, ParamType): return ty guessed_type = False if ty is None and default is not None: ty = type(default) guessed_type = True if ty is text_type or ty is str or ty is None: return STRING if ty is int: return INT # Booleans are only okay if not guessed. This is done because for # flags the default value is actually a bit of a lie in that it # indicates which of the flags is the one we want. See get_default() # for more information. if ty is bool and not guessed_type: return BOOL if ty is float: return FLOAT if guessed_type: return STRING # Catch a common mistake if __debug__: try: if issubclass(ty, ParamType): raise AssertionError('Attempted to use an uninstantiated ' 'parameter type (%s).' % ty) except TypeError: pass return FuncParamType(ty)
[ "def", "convert_type", "(", "ty", ",", "default", "=", "None", ")", ":", "if", "isinstance", "(", "ty", ",", "tuple", ")", ":", "return", "Tuple", "(", "ty", ")", "if", "isinstance", "(", "ty", ",", "ParamType", ")", ":", "return", "ty", "guessed_type", "=", "False", "if", "ty", "is", "None", "and", "default", "is", "not", "None", ":", "ty", "=", "type", "(", "default", ")", "guessed_type", "=", "True", "if", "ty", "is", "text_type", "or", "ty", "is", "str", "or", "ty", "is", "None", ":", "return", "STRING", "if", "ty", "is", "int", ":", "return", "INT", "# Booleans are only okay if not guessed. This is done because for", "# flags the default value is actually a bit of a lie in that it", "# indicates which of the flags is the one we want. See get_default()", "# for more information.", "if", "ty", "is", "bool", "and", "not", "guessed_type", ":", "return", "BOOL", "if", "ty", "is", "float", ":", "return", "FLOAT", "if", "guessed_type", ":", "return", "STRING", "# Catch a common mistake", "if", "__debug__", ":", "try", ":", "if", "issubclass", "(", "ty", ",", "ParamType", ")", ":", "raise", "AssertionError", "(", "'Attempted to use an uninstantiated '", "'parameter type (%s).'", "%", "ty", ")", "except", "TypeError", ":", "pass", "return", "FuncParamType", "(", "ty", ")" ]
Converts a callable or python ty into the most appropriate param ty.
[ "Converts", "a", "callable", "or", "python", "ty", "into", "the", "most", "appropriate", "param", "ty", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/types.py#L445-L480
mottosso/be
be/vendor/click/formatting.py
wrap_text
def wrap_text(text, width=78, initial_indent='', subsequent_indent='', preserve_paragraphs=False): """A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed with an empty line containing the ``\\b`` character (``\\x08``) to indicate that no rewrapping should happen in that block. :param text: the text that should be rewrapped. :param width: the maximum width for the text. :param initial_indent: the initial indent that should be placed on the first line as a string. :param subsequent_indent: the indent string that should be placed on each consecutive line. :param preserve_paragraphs: if this flag is set then the wrapping will intelligently handle paragraphs. """ from ._textwrap import TextWrapper text = text.expandtabs() post_wrap_indent = subsequent_indent[:-1] subsequent_indent = subsequent_indent[-1:] wrapper = TextWrapper(width, initial_indent=initial_indent, subsequent_indent=subsequent_indent, replace_whitespace=False) if not preserve_paragraphs: return add_subsequent_indent(wrapper.fill(text), post_wrap_indent) p = [] buf = [] indent = None def _flush_par(): if not buf: return if buf[0].strip() == '\b': p.append((indent or 0, True, '\n'.join(buf[1:]))) else: p.append((indent or 0, False, ' '.join(buf))) del buf[:] for line in text.splitlines(): if not line: _flush_par() indent = None else: if indent is None: orig_len = term_len(line) line = line.lstrip() indent = orig_len - term_len(line) buf.append(line) _flush_par() rv = [] for indent, raw, text in p: with wrapper.extra_indent(' ' * indent): if raw: rv.append(add_subsequent_indent(wrapper.indent_only(text), post_wrap_indent)) else: rv.append(add_subsequent_indent(wrapper.fill(text), post_wrap_indent)) return '\n\n'.join(rv)
python
def wrap_text(text, width=78, initial_indent='', subsequent_indent='', preserve_paragraphs=False): """A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed with an empty line containing the ``\\b`` character (``\\x08``) to indicate that no rewrapping should happen in that block. :param text: the text that should be rewrapped. :param width: the maximum width for the text. :param initial_indent: the initial indent that should be placed on the first line as a string. :param subsequent_indent: the indent string that should be placed on each consecutive line. :param preserve_paragraphs: if this flag is set then the wrapping will intelligently handle paragraphs. """ from ._textwrap import TextWrapper text = text.expandtabs() post_wrap_indent = subsequent_indent[:-1] subsequent_indent = subsequent_indent[-1:] wrapper = TextWrapper(width, initial_indent=initial_indent, subsequent_indent=subsequent_indent, replace_whitespace=False) if not preserve_paragraphs: return add_subsequent_indent(wrapper.fill(text), post_wrap_indent) p = [] buf = [] indent = None def _flush_par(): if not buf: return if buf[0].strip() == '\b': p.append((indent or 0, True, '\n'.join(buf[1:]))) else: p.append((indent or 0, False, ' '.join(buf))) del buf[:] for line in text.splitlines(): if not line: _flush_par() indent = None else: if indent is None: orig_len = term_len(line) line = line.lstrip() indent = orig_len - term_len(line) buf.append(line) _flush_par() rv = [] for indent, raw, text in p: with wrapper.extra_indent(' ' * indent): if raw: rv.append(add_subsequent_indent(wrapper.indent_only(text), post_wrap_indent)) else: rv.append(add_subsequent_indent(wrapper.fill(text), post_wrap_indent)) return '\n\n'.join(rv)
[ "def", "wrap_text", "(", "text", ",", "width", "=", "78", ",", "initial_indent", "=", "''", ",", "subsequent_indent", "=", "''", ",", "preserve_paragraphs", "=", "False", ")", ":", "from", ".", "_textwrap", "import", "TextWrapper", "text", "=", "text", ".", "expandtabs", "(", ")", "post_wrap_indent", "=", "subsequent_indent", "[", ":", "-", "1", "]", "subsequent_indent", "=", "subsequent_indent", "[", "-", "1", ":", "]", "wrapper", "=", "TextWrapper", "(", "width", ",", "initial_indent", "=", "initial_indent", ",", "subsequent_indent", "=", "subsequent_indent", ",", "replace_whitespace", "=", "False", ")", "if", "not", "preserve_paragraphs", ":", "return", "add_subsequent_indent", "(", "wrapper", ".", "fill", "(", "text", ")", ",", "post_wrap_indent", ")", "p", "=", "[", "]", "buf", "=", "[", "]", "indent", "=", "None", "def", "_flush_par", "(", ")", ":", "if", "not", "buf", ":", "return", "if", "buf", "[", "0", "]", ".", "strip", "(", ")", "==", "'\\b'", ":", "p", ".", "append", "(", "(", "indent", "or", "0", ",", "True", ",", "'\\n'", ".", "join", "(", "buf", "[", "1", ":", "]", ")", ")", ")", "else", ":", "p", ".", "append", "(", "(", "indent", "or", "0", ",", "False", ",", "' '", ".", "join", "(", "buf", ")", ")", ")", "del", "buf", "[", ":", "]", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "if", "not", "line", ":", "_flush_par", "(", ")", "indent", "=", "None", "else", ":", "if", "indent", "is", "None", ":", "orig_len", "=", "term_len", "(", "line", ")", "line", "=", "line", ".", "lstrip", "(", ")", "indent", "=", "orig_len", "-", "term_len", "(", "line", ")", "buf", ".", "append", "(", "line", ")", "_flush_par", "(", ")", "rv", "=", "[", "]", "for", "indent", ",", "raw", ",", "text", "in", "p", ":", "with", "wrapper", ".", "extra_indent", "(", "' '", "*", "indent", ")", ":", "if", "raw", ":", "rv", ".", "append", "(", "add_subsequent_indent", "(", "wrapper", ".", "indent_only", "(", "text", ")", ",", "post_wrap_indent", ")", ")", "else", ":", "rv", ".", "append", "(", "add_subsequent_indent", "(", "wrapper", ".", "fill", "(", "text", ")", ",", "post_wrap_indent", ")", ")", "return", "'\\n\\n'", ".", "join", "(", "rv", ")" ]
A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed with an empty line containing the ``\\b`` character (``\\x08``) to indicate that no rewrapping should happen in that block. :param text: the text that should be rewrapped. :param width: the maximum width for the text. :param initial_indent: the initial indent that should be placed on the first line as a string. :param subsequent_indent: the indent string that should be placed on each consecutive line. :param preserve_paragraphs: if this flag is set then the wrapping will intelligently handle paragraphs.
[ "A", "helper", "function", "that", "intelligently", "wraps", "text", ".", "By", "default", "it", "assumes", "that", "it", "operates", "on", "a", "single", "paragraph", "of", "text", "but", "if", "the", "preserve_paragraphs", "parameter", "is", "provided", "it", "will", "intelligently", "handle", "paragraphs", "(", "defined", "by", "two", "empty", "lines", ")", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/formatting.py#L27-L92
mottosso/be
be/vendor/click/formatting.py
HelpFormatter.write_usage
def write_usage(self, prog, args='', prefix='Usage: '): """Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line. """ prefix = '%*s%s' % (self.current_indent, prefix, prog) self.write(prefix) text_width = max(self.width - self.current_indent - term_len(prefix), 10) indent = ' ' * (term_len(prefix) + 1) self.write(wrap_text(args, text_width, initial_indent=' ', subsequent_indent=indent)) self.write('\n')
python
def write_usage(self, prog, args='', prefix='Usage: '): """Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line. """ prefix = '%*s%s' % (self.current_indent, prefix, prog) self.write(prefix) text_width = max(self.width - self.current_indent - term_len(prefix), 10) indent = ' ' * (term_len(prefix) + 1) self.write(wrap_text(args, text_width, initial_indent=' ', subsequent_indent=indent)) self.write('\n')
[ "def", "write_usage", "(", "self", ",", "prog", ",", "args", "=", "''", ",", "prefix", "=", "'Usage: '", ")", ":", "prefix", "=", "'%*s%s'", "%", "(", "self", ".", "current_indent", ",", "prefix", ",", "prog", ")", "self", ".", "write", "(", "prefix", ")", "text_width", "=", "max", "(", "self", ".", "width", "-", "self", ".", "current_indent", "-", "term_len", "(", "prefix", ")", ",", "10", ")", "indent", "=", "' '", "*", "(", "term_len", "(", "prefix", ")", "+", "1", ")", "self", ".", "write", "(", "wrap_text", "(", "args", ",", "text_width", ",", "initial_indent", "=", "' '", ",", "subsequent_indent", "=", "indent", ")", ")", "self", ".", "write", "(", "'\\n'", ")" ]
Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line.
[ "Writes", "a", "usage", "line", "into", "the", "buffer", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/formatting.py#L129-L145
mottosso/be
be/cli.py
in_
def in_(ctx, topics, yes, as_, enter): """Set the current topics to `topics` Environment: BE_PROJECT: First topic BE_CWD: Current `be` working directory BE_TOPICS: Arguments to `in` BE_DEVELOPMENTDIR: Absolute path to current development directory BE_PROJECTROOT: Absolute path to current project BE_PROJECTSROOT: Absolute path to where projects are located BE_ACTIVE: 0 or 1, indicates an active be environment BE_USER: Current user, overridden with `--as` BE_SCRIPT: User-supplied shell script BE_PYTHON: User-supplied python script BE_ENTER: 0 or 1 depending on whether the topic was entered BE_GITHUB_API_TOKEN: Optional GitHub API token BE_ENVIRONMENT: Space-separated list of user-added environment variables BE_TEMPDIR: Directory in which temporary files are stored BE_PRESETSDIR: Directory in which presets are searched BE_ALIASDIR: Directory in which aliases are written BE_BINDING: Binding between template and item in inventory \b Usage: $ be in project topics """ topics = map(str, topics) # They enter as unicode if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) # Determine topic syntax if len(topics[0].split("/")) == 3: topic_syntax = lib.FIXED project = topics[0].split("/")[0] else: topic_syntax = lib.POSITIONAL project = topics[0] project_dir = lib.project_dir(_extern.cwd(), project) if not os.path.exists(project_dir): lib.echo("Project \"%s\" not found. " % project) lib.echo("\nAvailable:") ctx.invoke(ls) sys.exit(lib.USER_ERROR) # Boot up context = lib.context(root=_extern.cwd(), project=project) be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) context.update({ "BE_PROJECT": project, "BE_USER": str(as_), "BE_ENTER": "1" if enter else "", "BE_TOPICS": " ".join(topics) }) # Remap topic syntax, for backwards compatibility # In cases where the topic is entered in a way that # differs from the template, remap topic to template. if any(re.findall("{\d+}", pattern) for pattern in templates.values()): template_syntax = lib.POSITIONAL else: template_syntax = lib.FIXED if topic_syntax & lib.POSITIONAL and not template_syntax & lib.POSITIONAL: topics = ["/".join(topics)] if topic_syntax & lib.FIXED and not template_syntax & lib.FIXED: topics[:] = topics[0].split("/") try: key = be.get("templates", {}).get("key") or "{1}" item = lib.item_from_topics(key, topics) binding = lib.binding_from_item(inventory, item) context["BE_BINDING"] = binding except IndexError as exc: lib.echo("At least %s topics are required" % str(exc)) sys.exit(lib.USER_ERROR) except KeyError as exc: lib.echo("\"%s\" not found" % item) if exc.bindings: lib.echo("\nAvailable:") for item_ in sorted(exc.bindings, key=lambda a: (exc.bindings[a], a)): lib.echo("- %s (%s)" % (item_, exc.bindings[item_])) sys.exit(lib.USER_ERROR) # Finally, determine a development directory # based on the template-, not topic-syntax. if template_syntax & lib.POSITIONAL: try: development_dir = lib.pos_development_directory( templates=templates, inventory=inventory, context=context, topics=topics, user=as_, item=item) except KeyError as exc: lib.echo("\"%s\" not found" % item) if exc.bindings: lib.echo("\nAvailable:") for item_ in sorted(exc.bindings, key=lambda a: (exc.bindings[a], a)): lib.echo("- %s (%s)" % (item_, exc.bindings[item_])) sys.exit(lib.USER_ERROR) else: # FIXED topic_syntax development_dir = lib.fixed_development_directory( templates, inventory, topics, as_) context["BE_DEVELOPMENTDIR"] = development_dir tempdir = (tempfile.mkdtemp() if not os.environ.get("BE_TEMPDIR") else os.environ["BE_TEMPDIR"]) context["BE_TEMPDIR"] = tempdir # Should it be entered? if enter and not os.path.exists(development_dir): create = False if yes: create = True else: sys.stdout.write("No development directory found. Create? [Y/n]: ") sys.stdout.flush() if raw_input().lower() in ("", "y", "yes"): create = True if create: ctx.invoke(mkdir, dir=development_dir) else: sys.stdout.write("Cancelled") sys.exit(lib.NORMAL) # Parse be.yaml if "script" in be: context["BE_SCRIPT"] = _extern.write_script( be["script"], tempdir).replace("\\", "/") if "python" in be: script = "\n".join(be["python"]) context["BE_PYTHON"] = script try: exec script in {"__name__": __name__} except Exception as e: lib.echo("ERROR: %s" % e) invalids = [v for v in context.values() if not isinstance(v, str)] assert all(isinstance(v, str) for v in context.values()), invalids # Create aliases aliases_dir = _extern.write_aliases( be.get("alias", {}), tempdir) context["PATH"] = (aliases_dir + os.pathsep + context.get("PATH", "")) context["BE_ALIASDIR"] = aliases_dir # Parse redirects lib.parse_redirect( be.get("redirect", {}), topics, context) # Override inherited context # with that coming from be.yaml. if "environment" in be: parsed = lib.parse_environment( fields=be["environment"], context=context, topics=topics) context["BE_ENVIRONMENT"] = " ".join(parsed.keys()) context.update(parsed) if "BE_TESTING" in context: os.chdir(development_dir) os.environ.update(context) else: parent = lib.parent() cmd = lib.cmd(parent) # Store reference to calling shell context["BE_SHELL"] = parent try: sys.exit(subprocess.call(cmd, env=context)) finally: import shutil shutil.rmtree(tempdir)
python
def in_(ctx, topics, yes, as_, enter): """Set the current topics to `topics` Environment: BE_PROJECT: First topic BE_CWD: Current `be` working directory BE_TOPICS: Arguments to `in` BE_DEVELOPMENTDIR: Absolute path to current development directory BE_PROJECTROOT: Absolute path to current project BE_PROJECTSROOT: Absolute path to where projects are located BE_ACTIVE: 0 or 1, indicates an active be environment BE_USER: Current user, overridden with `--as` BE_SCRIPT: User-supplied shell script BE_PYTHON: User-supplied python script BE_ENTER: 0 or 1 depending on whether the topic was entered BE_GITHUB_API_TOKEN: Optional GitHub API token BE_ENVIRONMENT: Space-separated list of user-added environment variables BE_TEMPDIR: Directory in which temporary files are stored BE_PRESETSDIR: Directory in which presets are searched BE_ALIASDIR: Directory in which aliases are written BE_BINDING: Binding between template and item in inventory \b Usage: $ be in project topics """ topics = map(str, topics) # They enter as unicode if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) # Determine topic syntax if len(topics[0].split("/")) == 3: topic_syntax = lib.FIXED project = topics[0].split("/")[0] else: topic_syntax = lib.POSITIONAL project = topics[0] project_dir = lib.project_dir(_extern.cwd(), project) if not os.path.exists(project_dir): lib.echo("Project \"%s\" not found. " % project) lib.echo("\nAvailable:") ctx.invoke(ls) sys.exit(lib.USER_ERROR) # Boot up context = lib.context(root=_extern.cwd(), project=project) be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) context.update({ "BE_PROJECT": project, "BE_USER": str(as_), "BE_ENTER": "1" if enter else "", "BE_TOPICS": " ".join(topics) }) # Remap topic syntax, for backwards compatibility # In cases where the topic is entered in a way that # differs from the template, remap topic to template. if any(re.findall("{\d+}", pattern) for pattern in templates.values()): template_syntax = lib.POSITIONAL else: template_syntax = lib.FIXED if topic_syntax & lib.POSITIONAL and not template_syntax & lib.POSITIONAL: topics = ["/".join(topics)] if topic_syntax & lib.FIXED and not template_syntax & lib.FIXED: topics[:] = topics[0].split("/") try: key = be.get("templates", {}).get("key") or "{1}" item = lib.item_from_topics(key, topics) binding = lib.binding_from_item(inventory, item) context["BE_BINDING"] = binding except IndexError as exc: lib.echo("At least %s topics are required" % str(exc)) sys.exit(lib.USER_ERROR) except KeyError as exc: lib.echo("\"%s\" not found" % item) if exc.bindings: lib.echo("\nAvailable:") for item_ in sorted(exc.bindings, key=lambda a: (exc.bindings[a], a)): lib.echo("- %s (%s)" % (item_, exc.bindings[item_])) sys.exit(lib.USER_ERROR) # Finally, determine a development directory # based on the template-, not topic-syntax. if template_syntax & lib.POSITIONAL: try: development_dir = lib.pos_development_directory( templates=templates, inventory=inventory, context=context, topics=topics, user=as_, item=item) except KeyError as exc: lib.echo("\"%s\" not found" % item) if exc.bindings: lib.echo("\nAvailable:") for item_ in sorted(exc.bindings, key=lambda a: (exc.bindings[a], a)): lib.echo("- %s (%s)" % (item_, exc.bindings[item_])) sys.exit(lib.USER_ERROR) else: # FIXED topic_syntax development_dir = lib.fixed_development_directory( templates, inventory, topics, as_) context["BE_DEVELOPMENTDIR"] = development_dir tempdir = (tempfile.mkdtemp() if not os.environ.get("BE_TEMPDIR") else os.environ["BE_TEMPDIR"]) context["BE_TEMPDIR"] = tempdir # Should it be entered? if enter and not os.path.exists(development_dir): create = False if yes: create = True else: sys.stdout.write("No development directory found. Create? [Y/n]: ") sys.stdout.flush() if raw_input().lower() in ("", "y", "yes"): create = True if create: ctx.invoke(mkdir, dir=development_dir) else: sys.stdout.write("Cancelled") sys.exit(lib.NORMAL) # Parse be.yaml if "script" in be: context["BE_SCRIPT"] = _extern.write_script( be["script"], tempdir).replace("\\", "/") if "python" in be: script = "\n".join(be["python"]) context["BE_PYTHON"] = script try: exec script in {"__name__": __name__} except Exception as e: lib.echo("ERROR: %s" % e) invalids = [v for v in context.values() if not isinstance(v, str)] assert all(isinstance(v, str) for v in context.values()), invalids # Create aliases aliases_dir = _extern.write_aliases( be.get("alias", {}), tempdir) context["PATH"] = (aliases_dir + os.pathsep + context.get("PATH", "")) context["BE_ALIASDIR"] = aliases_dir # Parse redirects lib.parse_redirect( be.get("redirect", {}), topics, context) # Override inherited context # with that coming from be.yaml. if "environment" in be: parsed = lib.parse_environment( fields=be["environment"], context=context, topics=topics) context["BE_ENVIRONMENT"] = " ".join(parsed.keys()) context.update(parsed) if "BE_TESTING" in context: os.chdir(development_dir) os.environ.update(context) else: parent = lib.parent() cmd = lib.cmd(parent) # Store reference to calling shell context["BE_SHELL"] = parent try: sys.exit(subprocess.call(cmd, env=context)) finally: import shutil shutil.rmtree(tempdir)
[ "def", "in_", "(", "ctx", ",", "topics", ",", "yes", ",", "as_", ",", "enter", ")", ":", "topics", "=", "map", "(", "str", ",", "topics", ")", "# They enter as unicode", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Exit current project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "# Determine topic syntax", "if", "len", "(", "topics", "[", "0", "]", ".", "split", "(", "\"/\"", ")", ")", "==", "3", ":", "topic_syntax", "=", "lib", ".", "FIXED", "project", "=", "topics", "[", "0", "]", ".", "split", "(", "\"/\"", ")", "[", "0", "]", "else", ":", "topic_syntax", "=", "lib", ".", "POSITIONAL", "project", "=", "topics", "[", "0", "]", "project_dir", "=", "lib", ".", "project_dir", "(", "_extern", ".", "cwd", "(", ")", ",", "project", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "project_dir", ")", ":", "lib", ".", "echo", "(", "\"Project \\\"%s\\\" not found. \"", "%", "project", ")", "lib", ".", "echo", "(", "\"\\nAvailable:\"", ")", "ctx", ".", "invoke", "(", "ls", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "# Boot up", "context", "=", "lib", ".", "context", "(", "root", "=", "_extern", ".", "cwd", "(", ")", ",", "project", "=", "project", ")", "be", "=", "_extern", ".", "load_be", "(", "project", ")", "templates", "=", "_extern", ".", "load_templates", "(", "project", ")", "inventory", "=", "_extern", ".", "load_inventory", "(", "project", ")", "context", ".", "update", "(", "{", "\"BE_PROJECT\"", ":", "project", ",", "\"BE_USER\"", ":", "str", "(", "as_", ")", ",", "\"BE_ENTER\"", ":", "\"1\"", "if", "enter", "else", "\"\"", ",", "\"BE_TOPICS\"", ":", "\" \"", ".", "join", "(", "topics", ")", "}", ")", "# Remap topic syntax, for backwards compatibility", "# In cases where the topic is entered in a way that", "# differs from the template, remap topic to template.", "if", "any", "(", "re", ".", "findall", "(", "\"{\\d+}\"", ",", "pattern", ")", "for", "pattern", "in", "templates", ".", "values", "(", ")", ")", ":", "template_syntax", "=", "lib", ".", "POSITIONAL", "else", ":", "template_syntax", "=", "lib", ".", "FIXED", "if", "topic_syntax", "&", "lib", ".", "POSITIONAL", "and", "not", "template_syntax", "&", "lib", ".", "POSITIONAL", ":", "topics", "=", "[", "\"/\"", ".", "join", "(", "topics", ")", "]", "if", "topic_syntax", "&", "lib", ".", "FIXED", "and", "not", "template_syntax", "&", "lib", ".", "FIXED", ":", "topics", "[", ":", "]", "=", "topics", "[", "0", "]", ".", "split", "(", "\"/\"", ")", "try", ":", "key", "=", "be", ".", "get", "(", "\"templates\"", ",", "{", "}", ")", ".", "get", "(", "\"key\"", ")", "or", "\"{1}\"", "item", "=", "lib", ".", "item_from_topics", "(", "key", ",", "topics", ")", "binding", "=", "lib", ".", "binding_from_item", "(", "inventory", ",", "item", ")", "context", "[", "\"BE_BINDING\"", "]", "=", "binding", "except", "IndexError", "as", "exc", ":", "lib", ".", "echo", "(", "\"At least %s topics are required\"", "%", "str", "(", "exc", ")", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "except", "KeyError", "as", "exc", ":", "lib", ".", "echo", "(", "\"\\\"%s\\\" not found\"", "%", "item", ")", "if", "exc", ".", "bindings", ":", "lib", ".", "echo", "(", "\"\\nAvailable:\"", ")", "for", "item_", "in", "sorted", "(", "exc", ".", "bindings", ",", "key", "=", "lambda", "a", ":", "(", "exc", ".", "bindings", "[", "a", "]", ",", "a", ")", ")", ":", "lib", ".", "echo", "(", "\"- %s (%s)\"", "%", "(", "item_", ",", "exc", ".", "bindings", "[", "item_", "]", ")", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "# Finally, determine a development directory", "# based on the template-, not topic-syntax.", "if", "template_syntax", "&", "lib", ".", "POSITIONAL", ":", "try", ":", "development_dir", "=", "lib", ".", "pos_development_directory", "(", "templates", "=", "templates", ",", "inventory", "=", "inventory", ",", "context", "=", "context", ",", "topics", "=", "topics", ",", "user", "=", "as_", ",", "item", "=", "item", ")", "except", "KeyError", "as", "exc", ":", "lib", ".", "echo", "(", "\"\\\"%s\\\" not found\"", "%", "item", ")", "if", "exc", ".", "bindings", ":", "lib", ".", "echo", "(", "\"\\nAvailable:\"", ")", "for", "item_", "in", "sorted", "(", "exc", ".", "bindings", ",", "key", "=", "lambda", "a", ":", "(", "exc", ".", "bindings", "[", "a", "]", ",", "a", ")", ")", ":", "lib", ".", "echo", "(", "\"- %s (%s)\"", "%", "(", "item_", ",", "exc", ".", "bindings", "[", "item_", "]", ")", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "else", ":", "# FIXED topic_syntax", "development_dir", "=", "lib", ".", "fixed_development_directory", "(", "templates", ",", "inventory", ",", "topics", ",", "as_", ")", "context", "[", "\"BE_DEVELOPMENTDIR\"", "]", "=", "development_dir", "tempdir", "=", "(", "tempfile", ".", "mkdtemp", "(", ")", "if", "not", "os", ".", "environ", ".", "get", "(", "\"BE_TEMPDIR\"", ")", "else", "os", ".", "environ", "[", "\"BE_TEMPDIR\"", "]", ")", "context", "[", "\"BE_TEMPDIR\"", "]", "=", "tempdir", "# Should it be entered?", "if", "enter", "and", "not", "os", ".", "path", ".", "exists", "(", "development_dir", ")", ":", "create", "=", "False", "if", "yes", ":", "create", "=", "True", "else", ":", "sys", ".", "stdout", ".", "write", "(", "\"No development directory found. Create? [Y/n]: \"", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "if", "raw_input", "(", ")", ".", "lower", "(", ")", "in", "(", "\"\"", ",", "\"y\"", ",", "\"yes\"", ")", ":", "create", "=", "True", "if", "create", ":", "ctx", ".", "invoke", "(", "mkdir", ",", "dir", "=", "development_dir", ")", "else", ":", "sys", ".", "stdout", ".", "write", "(", "\"Cancelled\"", ")", "sys", ".", "exit", "(", "lib", ".", "NORMAL", ")", "# Parse be.yaml", "if", "\"script\"", "in", "be", ":", "context", "[", "\"BE_SCRIPT\"", "]", "=", "_extern", ".", "write_script", "(", "be", "[", "\"script\"", "]", ",", "tempdir", ")", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", "if", "\"python\"", "in", "be", ":", "script", "=", "\"\\n\"", ".", "join", "(", "be", "[", "\"python\"", "]", ")", "context", "[", "\"BE_PYTHON\"", "]", "=", "script", "try", ":", "exec", "script", "in", "{", "\"__name__\"", ":", "__name__", "}", "except", "Exception", "as", "e", ":", "lib", ".", "echo", "(", "\"ERROR: %s\"", "%", "e", ")", "invalids", "=", "[", "v", "for", "v", "in", "context", ".", "values", "(", ")", "if", "not", "isinstance", "(", "v", ",", "str", ")", "]", "assert", "all", "(", "isinstance", "(", "v", ",", "str", ")", "for", "v", "in", "context", ".", "values", "(", ")", ")", ",", "invalids", "# Create aliases", "aliases_dir", "=", "_extern", ".", "write_aliases", "(", "be", ".", "get", "(", "\"alias\"", ",", "{", "}", ")", ",", "tempdir", ")", "context", "[", "\"PATH\"", "]", "=", "(", "aliases_dir", "+", "os", ".", "pathsep", "+", "context", ".", "get", "(", "\"PATH\"", ",", "\"\"", ")", ")", "context", "[", "\"BE_ALIASDIR\"", "]", "=", "aliases_dir", "# Parse redirects", "lib", ".", "parse_redirect", "(", "be", ".", "get", "(", "\"redirect\"", ",", "{", "}", ")", ",", "topics", ",", "context", ")", "# Override inherited context", "# with that coming from be.yaml.", "if", "\"environment\"", "in", "be", ":", "parsed", "=", "lib", ".", "parse_environment", "(", "fields", "=", "be", "[", "\"environment\"", "]", ",", "context", "=", "context", ",", "topics", "=", "topics", ")", "context", "[", "\"BE_ENVIRONMENT\"", "]", "=", "\" \"", ".", "join", "(", "parsed", ".", "keys", "(", ")", ")", "context", ".", "update", "(", "parsed", ")", "if", "\"BE_TESTING\"", "in", "context", ":", "os", ".", "chdir", "(", "development_dir", ")", "os", ".", "environ", ".", "update", "(", "context", ")", "else", ":", "parent", "=", "lib", ".", "parent", "(", ")", "cmd", "=", "lib", ".", "cmd", "(", "parent", ")", "# Store reference to calling shell", "context", "[", "\"BE_SHELL\"", "]", "=", "parent", "try", ":", "sys", ".", "exit", "(", "subprocess", ".", "call", "(", "cmd", ",", "env", "=", "context", ")", ")", "finally", ":", "import", "shutil", "shutil", ".", "rmtree", "(", "tempdir", ")" ]
Set the current topics to `topics` Environment: BE_PROJECT: First topic BE_CWD: Current `be` working directory BE_TOPICS: Arguments to `in` BE_DEVELOPMENTDIR: Absolute path to current development directory BE_PROJECTROOT: Absolute path to current project BE_PROJECTSROOT: Absolute path to where projects are located BE_ACTIVE: 0 or 1, indicates an active be environment BE_USER: Current user, overridden with `--as` BE_SCRIPT: User-supplied shell script BE_PYTHON: User-supplied python script BE_ENTER: 0 or 1 depending on whether the topic was entered BE_GITHUB_API_TOKEN: Optional GitHub API token BE_ENVIRONMENT: Space-separated list of user-added environment variables BE_TEMPDIR: Directory in which temporary files are stored BE_PRESETSDIR: Directory in which presets are searched BE_ALIASDIR: Directory in which aliases are written BE_BINDING: Binding between template and item in inventory \b Usage: $ be in project topics
[ "Set", "the", "current", "topics", "to", "topics" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L77-L274
mottosso/be
be/cli.py
new
def new(preset, name, silent, update): """Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be new film --name spiderman "spiderman" created """ if self.isactive(): lib.echo("Please exit current preset before starting a new") sys.exit(lib.USER_ERROR) if not name: count = 0 name = lib.random_name() while name in _extern.projects(): if count > 10: lib.echo("ERROR: Couldn't come up with a unique name :(") sys.exit(lib.USER_ERROR) name = lib.random_name() count += 1 project_dir = lib.project_dir(_extern.cwd(), name) if os.path.exists(project_dir): lib.echo("\"%s\" already exists" % name) sys.exit(lib.USER_ERROR) username, preset = ([None] + preset.split("/", 1))[-2:] presets_dir = _extern.presets_dir() preset_dir = os.path.join(presets_dir, preset) # Is the preset given referring to a repository directly? relative = False if username else True try: if not update and preset in _extern.local_presets(): _extern.copy_preset(preset_dir, project_dir) else: lib.echo("Finding preset for \"%s\".. " % preset, silent) time.sleep(1 if silent else 0) if relative: # Preset is relative, look it up from the Hub presets = _extern.github_presets() if preset not in presets: sys.stdout.write("\"%s\" not found" % preset) sys.exit(lib.USER_ERROR) time.sleep(1 if silent else 0) repository = presets[preset] else: # Absolute paths are pulled directly repository = username + "/" + preset lib.echo("Pulling %s.. " % repository, silent) repository = _extern.fetch_release(repository) # Remove existing preset if preset in _extern.local_presets(): _extern.remove_preset(preset) try: _extern.pull_preset(repository, preset_dir) except IOError as e: lib.echo("ERROR: Sorry, something went wrong.\n" "Use be --verbose for more") lib.echo(e) sys.exit(lib.USER_ERROR) try: _extern.copy_preset(preset_dir, project_dir) finally: # Absolute paths are not stored locally if not relative: _extern.remove_preset(preset) except IOError as exc: if self.verbose: lib.echo("ERROR: %s" % exc) else: lib.echo("ERROR: Could not write, do you have permission?") sys.exit(lib.PROGRAM_ERROR) lib.echo("\"%s\" created" % name, silent)
python
def new(preset, name, silent, update): """Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be new film --name spiderman "spiderman" created """ if self.isactive(): lib.echo("Please exit current preset before starting a new") sys.exit(lib.USER_ERROR) if not name: count = 0 name = lib.random_name() while name in _extern.projects(): if count > 10: lib.echo("ERROR: Couldn't come up with a unique name :(") sys.exit(lib.USER_ERROR) name = lib.random_name() count += 1 project_dir = lib.project_dir(_extern.cwd(), name) if os.path.exists(project_dir): lib.echo("\"%s\" already exists" % name) sys.exit(lib.USER_ERROR) username, preset = ([None] + preset.split("/", 1))[-2:] presets_dir = _extern.presets_dir() preset_dir = os.path.join(presets_dir, preset) # Is the preset given referring to a repository directly? relative = False if username else True try: if not update and preset in _extern.local_presets(): _extern.copy_preset(preset_dir, project_dir) else: lib.echo("Finding preset for \"%s\".. " % preset, silent) time.sleep(1 if silent else 0) if relative: # Preset is relative, look it up from the Hub presets = _extern.github_presets() if preset not in presets: sys.stdout.write("\"%s\" not found" % preset) sys.exit(lib.USER_ERROR) time.sleep(1 if silent else 0) repository = presets[preset] else: # Absolute paths are pulled directly repository = username + "/" + preset lib.echo("Pulling %s.. " % repository, silent) repository = _extern.fetch_release(repository) # Remove existing preset if preset in _extern.local_presets(): _extern.remove_preset(preset) try: _extern.pull_preset(repository, preset_dir) except IOError as e: lib.echo("ERROR: Sorry, something went wrong.\n" "Use be --verbose for more") lib.echo(e) sys.exit(lib.USER_ERROR) try: _extern.copy_preset(preset_dir, project_dir) finally: # Absolute paths are not stored locally if not relative: _extern.remove_preset(preset) except IOError as exc: if self.verbose: lib.echo("ERROR: %s" % exc) else: lib.echo("ERROR: Could not write, do you have permission?") sys.exit(lib.PROGRAM_ERROR) lib.echo("\"%s\" created" % name, silent)
[ "def", "new", "(", "preset", ",", "name", ",", "silent", ",", "update", ")", ":", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"Please exit current preset before starting a new\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "if", "not", "name", ":", "count", "=", "0", "name", "=", "lib", ".", "random_name", "(", ")", "while", "name", "in", "_extern", ".", "projects", "(", ")", ":", "if", "count", ">", "10", ":", "lib", ".", "echo", "(", "\"ERROR: Couldn't come up with a unique name :(\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "name", "=", "lib", ".", "random_name", "(", ")", "count", "+=", "1", "project_dir", "=", "lib", ".", "project_dir", "(", "_extern", ".", "cwd", "(", ")", ",", "name", ")", "if", "os", ".", "path", ".", "exists", "(", "project_dir", ")", ":", "lib", ".", "echo", "(", "\"\\\"%s\\\" already exists\"", "%", "name", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "username", ",", "preset", "=", "(", "[", "None", "]", "+", "preset", ".", "split", "(", "\"/\"", ",", "1", ")", ")", "[", "-", "2", ":", "]", "presets_dir", "=", "_extern", ".", "presets_dir", "(", ")", "preset_dir", "=", "os", ".", "path", ".", "join", "(", "presets_dir", ",", "preset", ")", "# Is the preset given referring to a repository directly?", "relative", "=", "False", "if", "username", "else", "True", "try", ":", "if", "not", "update", "and", "preset", "in", "_extern", ".", "local_presets", "(", ")", ":", "_extern", ".", "copy_preset", "(", "preset_dir", ",", "project_dir", ")", "else", ":", "lib", ".", "echo", "(", "\"Finding preset for \\\"%s\\\".. \"", "%", "preset", ",", "silent", ")", "time", ".", "sleep", "(", "1", "if", "silent", "else", "0", ")", "if", "relative", ":", "# Preset is relative, look it up from the Hub", "presets", "=", "_extern", ".", "github_presets", "(", ")", "if", "preset", "not", "in", "presets", ":", "sys", ".", "stdout", ".", "write", "(", "\"\\\"%s\\\" not found\"", "%", "preset", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "time", ".", "sleep", "(", "1", "if", "silent", "else", "0", ")", "repository", "=", "presets", "[", "preset", "]", "else", ":", "# Absolute paths are pulled directly", "repository", "=", "username", "+", "\"/\"", "+", "preset", "lib", ".", "echo", "(", "\"Pulling %s.. \"", "%", "repository", ",", "silent", ")", "repository", "=", "_extern", ".", "fetch_release", "(", "repository", ")", "# Remove existing preset", "if", "preset", "in", "_extern", ".", "local_presets", "(", ")", ":", "_extern", ".", "remove_preset", "(", "preset", ")", "try", ":", "_extern", ".", "pull_preset", "(", "repository", ",", "preset_dir", ")", "except", "IOError", "as", "e", ":", "lib", ".", "echo", "(", "\"ERROR: Sorry, something went wrong.\\n\"", "\"Use be --verbose for more\"", ")", "lib", ".", "echo", "(", "e", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "try", ":", "_extern", ".", "copy_preset", "(", "preset_dir", ",", "project_dir", ")", "finally", ":", "# Absolute paths are not stored locally", "if", "not", "relative", ":", "_extern", ".", "remove_preset", "(", "preset", ")", "except", "IOError", "as", "exc", ":", "if", "self", ".", "verbose", ":", "lib", ".", "echo", "(", "\"ERROR: %s\"", "%", "exc", ")", "else", ":", "lib", ".", "echo", "(", "\"ERROR: Could not write, do you have permission?\"", ")", "sys", ".", "exit", "(", "lib", ".", "PROGRAM_ERROR", ")", "lib", ".", "echo", "(", "\"\\\"%s\\\" created\"", "%", "name", ",", "silent", ")" ]
Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be new film --name spiderman "spiderman" created
[ "Create", "new", "default", "preset" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L284-L374
mottosso/be
be/cli.py
update
def update(preset, clean): """Update a local preset This command will cause `be` to pull a preset already available locally. \b Usage: $ be update ad Updating "ad".. """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) presets = _extern.github_presets() if preset not in presets: sys.stdout.write("\"%s\" not found" % preset) sys.exit(lib.USER_ERROR) lib.echo("Are you sure you want to update \"%s\", " "any changes will be lost?: [y/N]: ", newline=False) if raw_input().lower() in ("y", "yes"): presets_dir = _extern.presets_dir() preset_dir = os.path.join(presets_dir, preset) repository = presets[preset] if clean: try: _extern.remove_preset(preset) except: lib.echo("ERROR: Could not clean existing preset") sys.exit(lib.USER_ERROR) lib.echo("Updating %s.. " % repository) try: _extern.pull_preset(repository, preset_dir) except IOError as e: lib.echo(e) sys.exit(lib.USER_ERROR) else: lib.echo("Cancelled")
python
def update(preset, clean): """Update a local preset This command will cause `be` to pull a preset already available locally. \b Usage: $ be update ad Updating "ad".. """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) presets = _extern.github_presets() if preset not in presets: sys.stdout.write("\"%s\" not found" % preset) sys.exit(lib.USER_ERROR) lib.echo("Are you sure you want to update \"%s\", " "any changes will be lost?: [y/N]: ", newline=False) if raw_input().lower() in ("y", "yes"): presets_dir = _extern.presets_dir() preset_dir = os.path.join(presets_dir, preset) repository = presets[preset] if clean: try: _extern.remove_preset(preset) except: lib.echo("ERROR: Could not clean existing preset") sys.exit(lib.USER_ERROR) lib.echo("Updating %s.. " % repository) try: _extern.pull_preset(repository, preset_dir) except IOError as e: lib.echo(e) sys.exit(lib.USER_ERROR) else: lib.echo("Cancelled")
[ "def", "update", "(", "preset", ",", "clean", ")", ":", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Exit current project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "presets", "=", "_extern", ".", "github_presets", "(", ")", "if", "preset", "not", "in", "presets", ":", "sys", ".", "stdout", ".", "write", "(", "\"\\\"%s\\\" not found\"", "%", "preset", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "lib", ".", "echo", "(", "\"Are you sure you want to update \\\"%s\\\", \"", "\"any changes will be lost?: [y/N]: \"", ",", "newline", "=", "False", ")", "if", "raw_input", "(", ")", ".", "lower", "(", ")", "in", "(", "\"y\"", ",", "\"yes\"", ")", ":", "presets_dir", "=", "_extern", ".", "presets_dir", "(", ")", "preset_dir", "=", "os", ".", "path", ".", "join", "(", "presets_dir", ",", "preset", ")", "repository", "=", "presets", "[", "preset", "]", "if", "clean", ":", "try", ":", "_extern", ".", "remove_preset", "(", "preset", ")", "except", ":", "lib", ".", "echo", "(", "\"ERROR: Could not clean existing preset\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "lib", ".", "echo", "(", "\"Updating %s.. \"", "%", "repository", ")", "try", ":", "_extern", ".", "pull_preset", "(", "repository", ",", "preset_dir", ")", "except", "IOError", "as", "e", ":", "lib", ".", "echo", "(", "e", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "else", ":", "lib", ".", "echo", "(", "\"Cancelled\"", ")" ]
Update a local preset This command will cause `be` to pull a preset already available locally. \b Usage: $ be update ad Updating "ad"..
[ "Update", "a", "local", "preset" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L380-L427
mottosso/be
be/cli.py
tab
def tab(topics, complete): """Utility sub-command for tabcompletion This command is meant to be called by a tab completion function and is given a the currently entered topics, along with a boolean indicating whether or not the last entered argument is complete. """ # Discard `be tab` topics = list(topics)[2:] # When given an incomplete argument, # the argument is *sometimes* returned twice (?) # .. note:: Seen in Git Bash on Windows # $ be in giant [TAB] # -> ['giant'] # $ be in gi[TAB] # -> ['gi', 'gi'] if len(topics) > 1 and topics[-1] == topics[-2]: topics.pop() # Suggest projects if len(topics) == 0: projects = lib.list_projects(root=_extern.cwd()) sys.stdout.write(" ".join(projects)) elif len(topics) == 1: project = topics[0] projects = lib.list_projects(root=_extern.cwd()) # Complete project if not complete: projects = [i for i in projects if i.startswith(project)] sys.stdout.write(" ".join(projects)) else: # Suggest items from inventory inventory = _extern.load_inventory(project) inventory = lib.list_inventory(inventory) items = [i for i, b in inventory] sys.stdout.write(" ".join(items)) else: project, item = topics[:2] # Complete inventory item if len(topics) == 2 and not complete: inventory = _extern.load_inventory(project) inventory = lib.list_inventory(inventory) items = [i for i, b in inventory] items = [i for i in items if i.startswith(item)] sys.stdout.write(" ".join(items)) # Suggest items from template else: try: be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) item = topics[-1] items = lib.list_template(root=_extern.cwd(), topics=topics, templates=templates, inventory=inventory, be=be) if not complete: items = lib.list_template(root=_extern.cwd(), topics=topics[:-1], templates=templates, inventory=inventory, be=be) items = [i for i in items if i.startswith(item)] sys.stdout.write(" ".join(items) + " ") else: sys.stdout.write(" ".join(items) + " ") except IndexError: sys.exit(lib.NORMAL)
python
def tab(topics, complete): """Utility sub-command for tabcompletion This command is meant to be called by a tab completion function and is given a the currently entered topics, along with a boolean indicating whether or not the last entered argument is complete. """ # Discard `be tab` topics = list(topics)[2:] # When given an incomplete argument, # the argument is *sometimes* returned twice (?) # .. note:: Seen in Git Bash on Windows # $ be in giant [TAB] # -> ['giant'] # $ be in gi[TAB] # -> ['gi', 'gi'] if len(topics) > 1 and topics[-1] == topics[-2]: topics.pop() # Suggest projects if len(topics) == 0: projects = lib.list_projects(root=_extern.cwd()) sys.stdout.write(" ".join(projects)) elif len(topics) == 1: project = topics[0] projects = lib.list_projects(root=_extern.cwd()) # Complete project if not complete: projects = [i for i in projects if i.startswith(project)] sys.stdout.write(" ".join(projects)) else: # Suggest items from inventory inventory = _extern.load_inventory(project) inventory = lib.list_inventory(inventory) items = [i for i, b in inventory] sys.stdout.write(" ".join(items)) else: project, item = topics[:2] # Complete inventory item if len(topics) == 2 and not complete: inventory = _extern.load_inventory(project) inventory = lib.list_inventory(inventory) items = [i for i, b in inventory] items = [i for i in items if i.startswith(item)] sys.stdout.write(" ".join(items)) # Suggest items from template else: try: be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) item = topics[-1] items = lib.list_template(root=_extern.cwd(), topics=topics, templates=templates, inventory=inventory, be=be) if not complete: items = lib.list_template(root=_extern.cwd(), topics=topics[:-1], templates=templates, inventory=inventory, be=be) items = [i for i in items if i.startswith(item)] sys.stdout.write(" ".join(items) + " ") else: sys.stdout.write(" ".join(items) + " ") except IndexError: sys.exit(lib.NORMAL)
[ "def", "tab", "(", "topics", ",", "complete", ")", ":", "# Discard `be tab`", "topics", "=", "list", "(", "topics", ")", "[", "2", ":", "]", "# When given an incomplete argument,", "# the argument is *sometimes* returned twice (?)", "# .. note:: Seen in Git Bash on Windows", "# $ be in giant [TAB]", "# -> ['giant']", "# $ be in gi[TAB]", "# -> ['gi', 'gi']", "if", "len", "(", "topics", ")", ">", "1", "and", "topics", "[", "-", "1", "]", "==", "topics", "[", "-", "2", "]", ":", "topics", ".", "pop", "(", ")", "# Suggest projects", "if", "len", "(", "topics", ")", "==", "0", ":", "projects", "=", "lib", ".", "list_projects", "(", "root", "=", "_extern", ".", "cwd", "(", ")", ")", "sys", ".", "stdout", ".", "write", "(", "\" \"", ".", "join", "(", "projects", ")", ")", "elif", "len", "(", "topics", ")", "==", "1", ":", "project", "=", "topics", "[", "0", "]", "projects", "=", "lib", ".", "list_projects", "(", "root", "=", "_extern", ".", "cwd", "(", ")", ")", "# Complete project", "if", "not", "complete", ":", "projects", "=", "[", "i", "for", "i", "in", "projects", "if", "i", ".", "startswith", "(", "project", ")", "]", "sys", ".", "stdout", ".", "write", "(", "\" \"", ".", "join", "(", "projects", ")", ")", "else", ":", "# Suggest items from inventory", "inventory", "=", "_extern", ".", "load_inventory", "(", "project", ")", "inventory", "=", "lib", ".", "list_inventory", "(", "inventory", ")", "items", "=", "[", "i", "for", "i", ",", "b", "in", "inventory", "]", "sys", ".", "stdout", ".", "write", "(", "\" \"", ".", "join", "(", "items", ")", ")", "else", ":", "project", ",", "item", "=", "topics", "[", ":", "2", "]", "# Complete inventory item", "if", "len", "(", "topics", ")", "==", "2", "and", "not", "complete", ":", "inventory", "=", "_extern", ".", "load_inventory", "(", "project", ")", "inventory", "=", "lib", ".", "list_inventory", "(", "inventory", ")", "items", "=", "[", "i", "for", "i", ",", "b", "in", "inventory", "]", "items", "=", "[", "i", "for", "i", "in", "items", "if", "i", ".", "startswith", "(", "item", ")", "]", "sys", ".", "stdout", ".", "write", "(", "\" \"", ".", "join", "(", "items", ")", ")", "# Suggest items from template", "else", ":", "try", ":", "be", "=", "_extern", ".", "load_be", "(", "project", ")", "templates", "=", "_extern", ".", "load_templates", "(", "project", ")", "inventory", "=", "_extern", ".", "load_inventory", "(", "project", ")", "item", "=", "topics", "[", "-", "1", "]", "items", "=", "lib", ".", "list_template", "(", "root", "=", "_extern", ".", "cwd", "(", ")", ",", "topics", "=", "topics", ",", "templates", "=", "templates", ",", "inventory", "=", "inventory", ",", "be", "=", "be", ")", "if", "not", "complete", ":", "items", "=", "lib", ".", "list_template", "(", "root", "=", "_extern", ".", "cwd", "(", ")", ",", "topics", "=", "topics", "[", ":", "-", "1", "]", ",", "templates", "=", "templates", ",", "inventory", "=", "inventory", ",", "be", "=", "be", ")", "items", "=", "[", "i", "for", "i", "in", "items", "if", "i", ".", "startswith", "(", "item", ")", "]", "sys", ".", "stdout", ".", "write", "(", "\" \"", ".", "join", "(", "items", ")", "+", "\" \"", ")", "else", ":", "sys", ".", "stdout", ".", "write", "(", "\" \"", ".", "join", "(", "items", ")", "+", "\" \"", ")", "except", "IndexError", ":", "sys", ".", "exit", "(", "lib", ".", "NORMAL", ")" ]
Utility sub-command for tabcompletion This command is meant to be called by a tab completion function and is given a the currently entered topics, along with a boolean indicating whether or not the last entered argument is complete.
[ "Utility", "sub", "-", "command", "for", "tabcompletion" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L433-L512
mottosso/be
be/cli.py
activate
def activate(): """Enter into an environment with support for tab-completion This command drops you into a subshell, similar to the one generated via `be in ...`, except no topic is present and instead it enables tab-completion for supported shells. See documentation for further information. https://github.com/mottosso/be/wiki/cli """ parent = lib.parent() try: cmd = lib.cmd(parent) except SystemError as exc: lib.echo(exc) sys.exit(lib.PROGRAM_ERROR) # Store reference to calling shell context = lib.context(root=_extern.cwd()) context["BE_SHELL"] = parent if lib.platform() == "unix": context["BE_TABCOMPLETION"] = os.path.join( os.path.dirname(__file__), "_autocomplete.sh").replace("\\", "/") context.pop("BE_ACTIVE", None) sys.exit(subprocess.call(cmd, env=context))
python
def activate(): """Enter into an environment with support for tab-completion This command drops you into a subshell, similar to the one generated via `be in ...`, except no topic is present and instead it enables tab-completion for supported shells. See documentation for further information. https://github.com/mottosso/be/wiki/cli """ parent = lib.parent() try: cmd = lib.cmd(parent) except SystemError as exc: lib.echo(exc) sys.exit(lib.PROGRAM_ERROR) # Store reference to calling shell context = lib.context(root=_extern.cwd()) context["BE_SHELL"] = parent if lib.platform() == "unix": context["BE_TABCOMPLETION"] = os.path.join( os.path.dirname(__file__), "_autocomplete.sh").replace("\\", "/") context.pop("BE_ACTIVE", None) sys.exit(subprocess.call(cmd, env=context))
[ "def", "activate", "(", ")", ":", "parent", "=", "lib", ".", "parent", "(", ")", "try", ":", "cmd", "=", "lib", ".", "cmd", "(", "parent", ")", "except", "SystemError", "as", "exc", ":", "lib", ".", "echo", "(", "exc", ")", "sys", ".", "exit", "(", "lib", ".", "PROGRAM_ERROR", ")", "# Store reference to calling shell", "context", "=", "lib", ".", "context", "(", "root", "=", "_extern", ".", "cwd", "(", ")", ")", "context", "[", "\"BE_SHELL\"", "]", "=", "parent", "if", "lib", ".", "platform", "(", ")", "==", "\"unix\"", ":", "context", "[", "\"BE_TABCOMPLETION\"", "]", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"_autocomplete.sh\"", ")", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", "context", ".", "pop", "(", "\"BE_ACTIVE\"", ",", "None", ")", "sys", ".", "exit", "(", "subprocess", ".", "call", "(", "cmd", ",", "env", "=", "context", ")", ")" ]
Enter into an environment with support for tab-completion This command drops you into a subshell, similar to the one generated via `be in ...`, except no topic is present and instead it enables tab-completion for supported shells. See documentation for further information. https://github.com/mottosso/be/wiki/cli
[ "Enter", "into", "an", "environment", "with", "support", "for", "tab", "-", "completion" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L516-L546
mottosso/be
be/cli.py
ls
def ls(topics): """List contents of current context \b Usage: $ be ls - spiderman - hulk $ be ls spiderman - peter - mjay $ be ls spiderman seq01 - 1000 - 2000 - 2500 Return codes: 0 Normal 2 When insufficient arguments are supplied, or a template is unsupported. """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) # List projects if len(topics) == 0: for project in lib.list_projects(root=_extern.cwd()): lib.echo("- %s (project)" % project) sys.exit(lib.NORMAL) # List inventory of project elif len(topics) == 1: inventory = _extern.load_inventory(topics[0]) for item, binding in lib.list_inventory(inventory): lib.echo("- %s (%s)" % (item, binding)) sys.exit(lib.NORMAL) # List specific portion of template else: try: project = topics[0] be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) for item in lib.list_template(root=_extern.cwd(), topics=topics, templates=templates, inventory=inventory, be=be): lib.echo("- %s" % item) except IndexError as exc: lib.echo(exc) sys.exit(lib.USER_ERROR) sys.exit(lib.NORMAL)
python
def ls(topics): """List contents of current context \b Usage: $ be ls - spiderman - hulk $ be ls spiderman - peter - mjay $ be ls spiderman seq01 - 1000 - 2000 - 2500 Return codes: 0 Normal 2 When insufficient arguments are supplied, or a template is unsupported. """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) # List projects if len(topics) == 0: for project in lib.list_projects(root=_extern.cwd()): lib.echo("- %s (project)" % project) sys.exit(lib.NORMAL) # List inventory of project elif len(topics) == 1: inventory = _extern.load_inventory(topics[0]) for item, binding in lib.list_inventory(inventory): lib.echo("- %s (%s)" % (item, binding)) sys.exit(lib.NORMAL) # List specific portion of template else: try: project = topics[0] be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) for item in lib.list_template(root=_extern.cwd(), topics=topics, templates=templates, inventory=inventory, be=be): lib.echo("- %s" % item) except IndexError as exc: lib.echo(exc) sys.exit(lib.USER_ERROR) sys.exit(lib.NORMAL)
[ "def", "ls", "(", "topics", ")", ":", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Exit current project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "# List projects", "if", "len", "(", "topics", ")", "==", "0", ":", "for", "project", "in", "lib", ".", "list_projects", "(", "root", "=", "_extern", ".", "cwd", "(", ")", ")", ":", "lib", ".", "echo", "(", "\"- %s (project)\"", "%", "project", ")", "sys", ".", "exit", "(", "lib", ".", "NORMAL", ")", "# List inventory of project", "elif", "len", "(", "topics", ")", "==", "1", ":", "inventory", "=", "_extern", ".", "load_inventory", "(", "topics", "[", "0", "]", ")", "for", "item", ",", "binding", "in", "lib", ".", "list_inventory", "(", "inventory", ")", ":", "lib", ".", "echo", "(", "\"- %s (%s)\"", "%", "(", "item", ",", "binding", ")", ")", "sys", ".", "exit", "(", "lib", ".", "NORMAL", ")", "# List specific portion of template", "else", ":", "try", ":", "project", "=", "topics", "[", "0", "]", "be", "=", "_extern", ".", "load_be", "(", "project", ")", "templates", "=", "_extern", ".", "load_templates", "(", "project", ")", "inventory", "=", "_extern", ".", "load_inventory", "(", "project", ")", "for", "item", "in", "lib", ".", "list_template", "(", "root", "=", "_extern", ".", "cwd", "(", ")", ",", "topics", "=", "topics", ",", "templates", "=", "templates", ",", "inventory", "=", "inventory", ",", "be", "=", "be", ")", ":", "lib", ".", "echo", "(", "\"- %s\"", "%", "item", ")", "except", "IndexError", "as", "exc", ":", "lib", ".", "echo", "(", "exc", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "sys", ".", "exit", "(", "lib", ".", "NORMAL", ")" ]
List contents of current context \b Usage: $ be ls - spiderman - hulk $ be ls spiderman - peter - mjay $ be ls spiderman seq01 - 1000 - 2000 - 2500 Return codes: 0 Normal 2 When insufficient arguments are supplied, or a template is unsupported.
[ "List", "contents", "of", "current", "context" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L551-L608
mottosso/be
be/cli.py
mkdir
def mkdir(dir, enter): """Create directory with template for topic of the current environment """ if not os.path.exists(dir): os.makedirs(dir)
python
def mkdir(dir, enter): """Create directory with template for topic of the current environment """ if not os.path.exists(dir): os.makedirs(dir)
[ "def", "mkdir", "(", "dir", ",", "enter", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dir", ")", ":", "os", ".", "makedirs", "(", "dir", ")" ]
Create directory with template for topic of the current environment
[ "Create", "directory", "with", "template", "for", "topic", "of", "the", "current", "environment" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L614-L620
mottosso/be
be/cli.py
preset_ls
def preset_ls(remote): """List presets \b Usage: $ be preset ls - ad - game - film """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) if remote: presets = _extern.github_presets() else: presets = _extern.local_presets() if not presets: lib.echo("No presets found") sys.exit(lib.NORMAL) for preset in sorted(presets): lib.echo("- %s" % preset) sys.exit(lib.NORMAL)
python
def preset_ls(remote): """List presets \b Usage: $ be preset ls - ad - game - film """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) if remote: presets = _extern.github_presets() else: presets = _extern.local_presets() if not presets: lib.echo("No presets found") sys.exit(lib.NORMAL) for preset in sorted(presets): lib.echo("- %s" % preset) sys.exit(lib.NORMAL)
[ "def", "preset_ls", "(", "remote", ")", ":", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Exit current project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "if", "remote", ":", "presets", "=", "_extern", ".", "github_presets", "(", ")", "else", ":", "presets", "=", "_extern", ".", "local_presets", "(", ")", "if", "not", "presets", ":", "lib", ".", "echo", "(", "\"No presets found\"", ")", "sys", ".", "exit", "(", "lib", ".", "NORMAL", ")", "for", "preset", "in", "sorted", "(", "presets", ")", ":", "lib", ".", "echo", "(", "\"- %s\"", "%", "preset", ")", "sys", ".", "exit", "(", "lib", ".", "NORMAL", ")" ]
List presets \b Usage: $ be preset ls - ad - game - film
[ "List", "presets" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L630-L656
mottosso/be
be/cli.py
preset_find
def preset_find(query): """Find preset from hub \b $ be find ad https://github.com/mottosso/be-ad.git """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) found = _extern.github_presets().get(query) if found: lib.echo(found) else: lib.echo("Unable to locate preset \"%s\"" % query)
python
def preset_find(query): """Find preset from hub \b $ be find ad https://github.com/mottosso/be-ad.git """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) found = _extern.github_presets().get(query) if found: lib.echo(found) else: lib.echo("Unable to locate preset \"%s\"" % query)
[ "def", "preset_find", "(", "query", ")", ":", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Exit current project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "found", "=", "_extern", ".", "github_presets", "(", ")", ".", "get", "(", "query", ")", "if", "found", ":", "lib", ".", "echo", "(", "found", ")", "else", ":", "lib", ".", "echo", "(", "\"Unable to locate preset \\\"%s\\\"\"", "%", "query", ")" ]
Find preset from hub \b $ be find ad https://github.com/mottosso/be-ad.git
[ "Find", "preset", "from", "hub" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L661-L678
mottosso/be
be/cli.py
dump
def dump(): """Print current environment Environment is outputted in a YAML-friendly format \b Usage: $ be dump Prefixed: - BE_TOPICS=hulk bruce animation - ... """ if not self.isactive(): lib.echo("ERROR: Enter a project first") sys.exit(lib.USER_ERROR) # Print custom environment variables first custom = sorted(os.environ.get("BE_ENVIRONMENT", "").split()) if custom: lib.echo("Custom:") for key in custom: lib.echo("- %s=%s" % (key, os.environ.get(key))) # Then print redirected variables project = os.environ["BE_PROJECT"] root = os.environ["BE_PROJECTSROOT"] be = _extern.load(project, "be", optional=True, root=root) redirect = be.get("redirect", {}).items() if redirect: lib.echo("\nRedirect:") for map_source, map_dest in sorted(redirect): lib.echo("- %s=%s" % (map_dest, os.environ.get(map_dest))) # And then everything else prefixed = dict((k, v) for k, v in os.environ.iteritems() if k.startswith("BE_")) if prefixed: lib.echo("\nPrefixed:") for key in sorted(prefixed): if not key.startswith("BE_"): continue lib.echo("- %s=%s" % (key, os.environ.get(key))) sys.exit(lib.NORMAL)
python
def dump(): """Print current environment Environment is outputted in a YAML-friendly format \b Usage: $ be dump Prefixed: - BE_TOPICS=hulk bruce animation - ... """ if not self.isactive(): lib.echo("ERROR: Enter a project first") sys.exit(lib.USER_ERROR) # Print custom environment variables first custom = sorted(os.environ.get("BE_ENVIRONMENT", "").split()) if custom: lib.echo("Custom:") for key in custom: lib.echo("- %s=%s" % (key, os.environ.get(key))) # Then print redirected variables project = os.environ["BE_PROJECT"] root = os.environ["BE_PROJECTSROOT"] be = _extern.load(project, "be", optional=True, root=root) redirect = be.get("redirect", {}).items() if redirect: lib.echo("\nRedirect:") for map_source, map_dest in sorted(redirect): lib.echo("- %s=%s" % (map_dest, os.environ.get(map_dest))) # And then everything else prefixed = dict((k, v) for k, v in os.environ.iteritems() if k.startswith("BE_")) if prefixed: lib.echo("\nPrefixed:") for key in sorted(prefixed): if not key.startswith("BE_"): continue lib.echo("- %s=%s" % (key, os.environ.get(key))) sys.exit(lib.NORMAL)
[ "def", "dump", "(", ")", ":", "if", "not", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Enter a project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "# Print custom environment variables first", "custom", "=", "sorted", "(", "os", ".", "environ", ".", "get", "(", "\"BE_ENVIRONMENT\"", ",", "\"\"", ")", ".", "split", "(", ")", ")", "if", "custom", ":", "lib", ".", "echo", "(", "\"Custom:\"", ")", "for", "key", "in", "custom", ":", "lib", ".", "echo", "(", "\"- %s=%s\"", "%", "(", "key", ",", "os", ".", "environ", ".", "get", "(", "key", ")", ")", ")", "# Then print redirected variables", "project", "=", "os", ".", "environ", "[", "\"BE_PROJECT\"", "]", "root", "=", "os", ".", "environ", "[", "\"BE_PROJECTSROOT\"", "]", "be", "=", "_extern", ".", "load", "(", "project", ",", "\"be\"", ",", "optional", "=", "True", ",", "root", "=", "root", ")", "redirect", "=", "be", ".", "get", "(", "\"redirect\"", ",", "{", "}", ")", ".", "items", "(", ")", "if", "redirect", ":", "lib", ".", "echo", "(", "\"\\nRedirect:\"", ")", "for", "map_source", ",", "map_dest", "in", "sorted", "(", "redirect", ")", ":", "lib", ".", "echo", "(", "\"- %s=%s\"", "%", "(", "map_dest", ",", "os", ".", "environ", ".", "get", "(", "map_dest", ")", ")", ")", "# And then everything else", "prefixed", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "os", ".", "environ", ".", "iteritems", "(", ")", "if", "k", ".", "startswith", "(", "\"BE_\"", ")", ")", "if", "prefixed", ":", "lib", ".", "echo", "(", "\"\\nPrefixed:\"", ")", "for", "key", "in", "sorted", "(", "prefixed", ")", ":", "if", "not", "key", ".", "startswith", "(", "\"BE_\"", ")", ":", "continue", "lib", ".", "echo", "(", "\"- %s=%s\"", "%", "(", "key", ",", "os", ".", "environ", ".", "get", "(", "key", ")", ")", ")", "sys", ".", "exit", "(", "lib", ".", "NORMAL", ")" ]
Print current environment Environment is outputted in a YAML-friendly format \b Usage: $ be dump Prefixed: - BE_TOPICS=hulk bruce animation - ...
[ "Print", "current", "environment" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L682-L727
mottosso/be
be/cli.py
what
def what(): """Print current topics""" if not self.isactive(): lib.echo("No topic") sys.exit(lib.USER_ERROR) lib.echo(os.environ.get("BE_TOPICS", "This is a bug"))
python
def what(): """Print current topics""" if not self.isactive(): lib.echo("No topic") sys.exit(lib.USER_ERROR) lib.echo(os.environ.get("BE_TOPICS", "This is a bug"))
[ "def", "what", "(", ")", ":", "if", "not", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"No topic\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "lib", ".", "echo", "(", "os", ".", "environ", ".", "get", "(", "\"BE_TOPICS\"", ",", "\"This is a bug\"", ")", ")" ]
Print current topics
[ "Print", "current", "topics" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L731-L738
mottosso/be
be/vendor/requests/utils.py
get_netrc_auth
def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{0}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See http://bugs.python.org/issue20164 & # https://github.com/kennethreitz/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass # AppEngine hackiness. except (ImportError, AttributeError): pass
python
def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{0}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See http://bugs.python.org/issue20164 & # https://github.com/kennethreitz/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass # AppEngine hackiness. except (ImportError, AttributeError): pass
[ "def", "get_netrc_auth", "(", "url", ")", ":", "try", ":", "from", "netrc", "import", "netrc", ",", "NetrcParseError", "netrc_path", "=", "None", "for", "f", "in", "NETRC_FILES", ":", "try", ":", "loc", "=", "os", ".", "path", ".", "expanduser", "(", "'~/{0}'", ".", "format", "(", "f", ")", ")", "except", "KeyError", ":", "# os.path.expanduser can fail when $HOME is undefined and", "# getpwuid fails. See http://bugs.python.org/issue20164 &", "# https://github.com/kennethreitz/requests/issues/1846", "return", "if", "os", ".", "path", ".", "exists", "(", "loc", ")", ":", "netrc_path", "=", "loc", "break", "# Abort early if there isn't one.", "if", "netrc_path", "is", "None", ":", "return", "ri", "=", "urlparse", "(", "url", ")", "# Strip port numbers from netloc", "host", "=", "ri", ".", "netloc", ".", "split", "(", "':'", ")", "[", "0", "]", "try", ":", "_netrc", "=", "netrc", "(", "netrc_path", ")", ".", "authenticators", "(", "host", ")", "if", "_netrc", ":", "# Return with login / password", "login_i", "=", "(", "0", "if", "_netrc", "[", "0", "]", "else", "1", ")", "return", "(", "_netrc", "[", "login_i", "]", ",", "_netrc", "[", "2", "]", ")", "except", "(", "NetrcParseError", ",", "IOError", ")", ":", "# If there was a parsing error or a permissions issue reading the file,", "# we'll just skip netrc auth", "pass", "# AppEngine hackiness.", "except", "(", "ImportError", ",", "AttributeError", ")", ":", "pass" ]
Returns the Requests tuple auth for a given url from netrc.
[ "Returns", "the", "Requests", "tuple", "auth", "for", "a", "given", "url", "from", "netrc", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L70-L113
mottosso/be
be/vendor/requests/utils.py
add_dict_to_cookiejar
def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. """ cj2 = cookiejar_from_dict(cookie_dict) cj.update(cj2) return cj
python
def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. """ cj2 = cookiejar_from_dict(cookie_dict) cj.update(cj2) return cj
[ "def", "add_dict_to_cookiejar", "(", "cj", ",", "cookie_dict", ")", ":", "cj2", "=", "cookiejar_from_dict", "(", "cookie_dict", ")", "cj", ".", "update", "(", "cj2", ")", "return", "cj" ]
Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar.
[ "Returns", "a", "CookieJar", "from", "a", "key", "/", "value", "dictionary", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L276-L285
mottosso/be
be/vendor/requests/utils.py
should_bypass_proxies
def should_bypass_proxies(url): """ Returns whether we should bypass proxies or not. """ get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy = get_proxy('no_proxy') netloc = urlparse(url).netloc if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the netloc, both with and without the port. no_proxy = no_proxy.replace(' ', '').split(',') ip = netloc.split(':')[0] if is_ipv4_address(ip): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(ip, proxy_ip): return True else: for host in no_proxy: if netloc.endswith(host) or netloc.split(':')[0].endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True # If the system proxy settings indicate that this URL should be bypassed, # don't proxy. # The proxy_bypass function is incredibly buggy on OS X in early versions # of Python 2.6, so allow this call to fail. Only catch the specific # exceptions we've seen, though: this call failing in other ways can reveal # legitimate problems. try: bypass = proxy_bypass(netloc) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
python
def should_bypass_proxies(url): """ Returns whether we should bypass proxies or not. """ get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy = get_proxy('no_proxy') netloc = urlparse(url).netloc if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the netloc, both with and without the port. no_proxy = no_proxy.replace(' ', '').split(',') ip = netloc.split(':')[0] if is_ipv4_address(ip): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(ip, proxy_ip): return True else: for host in no_proxy: if netloc.endswith(host) or netloc.split(':')[0].endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True # If the system proxy settings indicate that this URL should be bypassed, # don't proxy. # The proxy_bypass function is incredibly buggy on OS X in early versions # of Python 2.6, so allow this call to fail. Only catch the specific # exceptions we've seen, though: this call failing in other ways can reveal # legitimate problems. try: bypass = proxy_bypass(netloc) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
[ "def", "should_bypass_proxies", "(", "url", ")", ":", "get_proxy", "=", "lambda", "k", ":", "os", ".", "environ", ".", "get", "(", "k", ")", "or", "os", ".", "environ", ".", "get", "(", "k", ".", "upper", "(", ")", ")", "# First check whether no_proxy is defined. If it is, check that the URL", "# we're getting isn't in the no_proxy list.", "no_proxy", "=", "get_proxy", "(", "'no_proxy'", ")", "netloc", "=", "urlparse", "(", "url", ")", ".", "netloc", "if", "no_proxy", ":", "# We need to check whether we match here. We need to see if we match", "# the end of the netloc, both with and without the port.", "no_proxy", "=", "no_proxy", ".", "replace", "(", "' '", ",", "''", ")", ".", "split", "(", "','", ")", "ip", "=", "netloc", ".", "split", "(", "':'", ")", "[", "0", "]", "if", "is_ipv4_address", "(", "ip", ")", ":", "for", "proxy_ip", "in", "no_proxy", ":", "if", "is_valid_cidr", "(", "proxy_ip", ")", ":", "if", "address_in_network", "(", "ip", ",", "proxy_ip", ")", ":", "return", "True", "else", ":", "for", "host", "in", "no_proxy", ":", "if", "netloc", ".", "endswith", "(", "host", ")", "or", "netloc", ".", "split", "(", "':'", ")", "[", "0", "]", ".", "endswith", "(", "host", ")", ":", "# The URL does match something in no_proxy, so we don't want", "# to apply the proxies on this URL.", "return", "True", "# If the system proxy settings indicate that this URL should be bypassed,", "# don't proxy.", "# The proxy_bypass function is incredibly buggy on OS X in early versions", "# of Python 2.6, so allow this call to fail. Only catch the specific", "# exceptions we've seen, though: this call failing in other ways can reveal", "# legitimate problems.", "try", ":", "bypass", "=", "proxy_bypass", "(", "netloc", ")", "except", "(", "TypeError", ",", "socket", ".", "gaierror", ")", ":", "bypass", "=", "False", "if", "bypass", ":", "return", "True", "return", "False" ]
Returns whether we should bypass proxies or not.
[ "Returns", "whether", "we", "should", "bypass", "proxies", "or", "not", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L487-L530
mottosso/be
be/vendor/requests/utils.py
default_user_agent
def default_user_agent(name="python-requests"): """Return a string representing the default user agent.""" _implementation = platform.python_implementation() if _implementation == 'CPython': _implementation_version = platform.python_version() elif _implementation == 'PyPy': _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel]) elif _implementation == 'Jython': _implementation_version = platform.python_version() # Complete Guess elif _implementation == 'IronPython': _implementation_version = platform.python_version() # Complete Guess else: _implementation_version = 'Unknown' try: p_system = platform.system() p_release = platform.release() except IOError: p_system = 'Unknown' p_release = 'Unknown' return " ".join(['%s/%s' % (name, __version__), '%s/%s' % (_implementation, _implementation_version), '%s/%s' % (p_system, p_release)])
python
def default_user_agent(name="python-requests"): """Return a string representing the default user agent.""" _implementation = platform.python_implementation() if _implementation == 'CPython': _implementation_version = platform.python_version() elif _implementation == 'PyPy': _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel]) elif _implementation == 'Jython': _implementation_version = platform.python_version() # Complete Guess elif _implementation == 'IronPython': _implementation_version = platform.python_version() # Complete Guess else: _implementation_version = 'Unknown' try: p_system = platform.system() p_release = platform.release() except IOError: p_system = 'Unknown' p_release = 'Unknown' return " ".join(['%s/%s' % (name, __version__), '%s/%s' % (_implementation, _implementation_version), '%s/%s' % (p_system, p_release)])
[ "def", "default_user_agent", "(", "name", "=", "\"python-requests\"", ")", ":", "_implementation", "=", "platform", ".", "python_implementation", "(", ")", "if", "_implementation", "==", "'CPython'", ":", "_implementation_version", "=", "platform", ".", "python_version", "(", ")", "elif", "_implementation", "==", "'PyPy'", ":", "_implementation_version", "=", "'%s.%s.%s'", "%", "(", "sys", ".", "pypy_version_info", ".", "major", ",", "sys", ".", "pypy_version_info", ".", "minor", ",", "sys", ".", "pypy_version_info", ".", "micro", ")", "if", "sys", ".", "pypy_version_info", ".", "releaselevel", "!=", "'final'", ":", "_implementation_version", "=", "''", ".", "join", "(", "[", "_implementation_version", ",", "sys", ".", "pypy_version_info", ".", "releaselevel", "]", ")", "elif", "_implementation", "==", "'Jython'", ":", "_implementation_version", "=", "platform", ".", "python_version", "(", ")", "# Complete Guess", "elif", "_implementation", "==", "'IronPython'", ":", "_implementation_version", "=", "platform", ".", "python_version", "(", ")", "# Complete Guess", "else", ":", "_implementation_version", "=", "'Unknown'", "try", ":", "p_system", "=", "platform", ".", "system", "(", ")", "p_release", "=", "platform", ".", "release", "(", ")", "except", "IOError", ":", "p_system", "=", "'Unknown'", "p_release", "=", "'Unknown'", "return", "\" \"", ".", "join", "(", "[", "'%s/%s'", "%", "(", "name", ",", "__version__", ")", ",", "'%s/%s'", "%", "(", "_implementation", ",", "_implementation_version", ")", ",", "'%s/%s'", "%", "(", "p_system", ",", "p_release", ")", "]", ")" ]
Return a string representing the default user agent.
[ "Return", "a", "string", "representing", "the", "default", "user", "agent", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L540-L568
mottosso/be
be/vendor/requests/utils.py
to_native_string
def to_native_string(string, encoding='ascii'): """ Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise. """ out = None if isinstance(string, builtin_str): out = string else: if is_py2: out = string.encode(encoding) else: out = string.decode(encoding) return out
python
def to_native_string(string, encoding='ascii'): """ Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise. """ out = None if isinstance(string, builtin_str): out = string else: if is_py2: out = string.encode(encoding) else: out = string.decode(encoding) return out
[ "def", "to_native_string", "(", "string", ",", "encoding", "=", "'ascii'", ")", ":", "out", "=", "None", "if", "isinstance", "(", "string", ",", "builtin_str", ")", ":", "out", "=", "string", "else", ":", "if", "is_py2", ":", "out", "=", "string", ".", "encode", "(", "encoding", ")", "else", ":", "out", "=", "string", ".", "decode", "(", "encoding", ")", "return", "out" ]
Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise.
[ "Given", "a", "string", "object", "regardless", "of", "type", "returns", "a", "representation", "of", "that", "string", "in", "the", "native", "string", "type", "encoding", "and", "decoding", "where", "necessary", ".", "This", "assumes", "ASCII", "unless", "told", "otherwise", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L676-L692
mottosso/be
be/vendor/click/core.py
_bashcomplete
def _bashcomplete(cmd, prog_name, complete_var=None): """Internal handler for the bash completion support.""" if complete_var is None: complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper() complete_instr = os.environ.get(complete_var) if not complete_instr: return from ._bashcomplete import bashcomplete if bashcomplete(cmd, prog_name, complete_var, complete_instr): sys.exit(1)
python
def _bashcomplete(cmd, prog_name, complete_var=None): """Internal handler for the bash completion support.""" if complete_var is None: complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper() complete_instr = os.environ.get(complete_var) if not complete_instr: return from ._bashcomplete import bashcomplete if bashcomplete(cmd, prog_name, complete_var, complete_instr): sys.exit(1)
[ "def", "_bashcomplete", "(", "cmd", ",", "prog_name", ",", "complete_var", "=", "None", ")", ":", "if", "complete_var", "is", "None", ":", "complete_var", "=", "'_%s_COMPLETE'", "%", "(", "prog_name", ".", "replace", "(", "'-'", ",", "'_'", ")", ")", ".", "upper", "(", ")", "complete_instr", "=", "os", ".", "environ", ".", "get", "(", "complete_var", ")", "if", "not", "complete_instr", ":", "return", "from", ".", "_bashcomplete", "import", "bashcomplete", "if", "bashcomplete", "(", "cmd", ",", "prog_name", ",", "complete_var", ",", "complete_instr", ")", ":", "sys", ".", "exit", "(", "1", ")" ]
Internal handler for the bash completion support.
[ "Internal", "handler", "for", "the", "bash", "completion", "support", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L25-L35
mottosso/be
be/vendor/click/core.py
Context.invoke
def invoke(*args, **kwargs): """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. """ self, callback = args[:2] ctx = self # This is just to improve the error message in cases where old # code incorrectly invoked this method. This will eventually be # removed. injected_arguments = False # It's also possible to invoke another command which might or # might not have a callback. In that case we also fill # in defaults and make a new context for this command. if isinstance(callback, Command): other_cmd = callback callback = other_cmd.callback ctx = Context(other_cmd, info_name=other_cmd.name, parent=self) if callback is None: raise TypeError('The given command does not have a ' 'callback that can be invoked.') for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.get_default(ctx) injected_arguments = True args = args[2:] if getattr(callback, '__click_pass_context__', False): args = (ctx,) + args with augment_usage_errors(self): try: with ctx: return callback(*args, **kwargs) except TypeError as e: if not injected_arguments: raise if 'got multiple values for' in str(e): raise RuntimeError( 'You called .invoke() on the context with a command ' 'but provided parameters as positional arguments. ' 'This is not supported but sometimes worked by chance ' 'in older versions of Click. To fix this see ' 'http://click.pocoo.org/upgrading/#upgrading-to-3.2') raise
python
def invoke(*args, **kwargs): """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. """ self, callback = args[:2] ctx = self # This is just to improve the error message in cases where old # code incorrectly invoked this method. This will eventually be # removed. injected_arguments = False # It's also possible to invoke another command which might or # might not have a callback. In that case we also fill # in defaults and make a new context for this command. if isinstance(callback, Command): other_cmd = callback callback = other_cmd.callback ctx = Context(other_cmd, info_name=other_cmd.name, parent=self) if callback is None: raise TypeError('The given command does not have a ' 'callback that can be invoked.') for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.get_default(ctx) injected_arguments = True args = args[2:] if getattr(callback, '__click_pass_context__', False): args = (ctx,) + args with augment_usage_errors(self): try: with ctx: return callback(*args, **kwargs) except TypeError as e: if not injected_arguments: raise if 'got multiple values for' in str(e): raise RuntimeError( 'You called .invoke() on the context with a command ' 'but provided parameters as positional arguments. ' 'This is not supported but sometimes worked by chance ' 'in older versions of Click. To fix this see ' 'http://click.pocoo.org/upgrading/#upgrading-to-3.2') raise
[ "def", "invoke", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ",", "callback", "=", "args", "[", ":", "2", "]", "ctx", "=", "self", "# This is just to improve the error message in cases where old", "# code incorrectly invoked this method. This will eventually be", "# removed.", "injected_arguments", "=", "False", "# It's also possible to invoke another command which might or", "# might not have a callback. In that case we also fill", "# in defaults and make a new context for this command.", "if", "isinstance", "(", "callback", ",", "Command", ")", ":", "other_cmd", "=", "callback", "callback", "=", "other_cmd", ".", "callback", "ctx", "=", "Context", "(", "other_cmd", ",", "info_name", "=", "other_cmd", ".", "name", ",", "parent", "=", "self", ")", "if", "callback", "is", "None", ":", "raise", "TypeError", "(", "'The given command does not have a '", "'callback that can be invoked.'", ")", "for", "param", "in", "other_cmd", ".", "params", ":", "if", "param", ".", "name", "not", "in", "kwargs", "and", "param", ".", "expose_value", ":", "kwargs", "[", "param", ".", "name", "]", "=", "param", ".", "get_default", "(", "ctx", ")", "injected_arguments", "=", "True", "args", "=", "args", "[", "2", ":", "]", "if", "getattr", "(", "callback", ",", "'__click_pass_context__'", ",", "False", ")", ":", "args", "=", "(", "ctx", ",", ")", "+", "args", "with", "augment_usage_errors", "(", "self", ")", ":", "try", ":", "with", "ctx", ":", "return", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "TypeError", "as", "e", ":", "if", "not", "injected_arguments", ":", "raise", "if", "'got multiple values for'", "in", "str", "(", "e", ")", ":", "raise", "RuntimeError", "(", "'You called .invoke() on the context with a command '", "'but provided parameters as positional arguments. '", "'This is not supported but sometimes worked by chance '", "'in older versions of Click. To fix this see '", "'http://click.pocoo.org/upgrading/#upgrading-to-3.2'", ")", "raise" ]
Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`.
[ "Invokes", "a", "command", "callback", "in", "exactly", "the", "way", "it", "expects", ".", "There", "are", "two", "ways", "to", "invoke", "this", "method", ":" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L418-L475
mottosso/be
be/vendor/click/core.py
BaseCommand.make_context
def make_context(self, info_name, args, parent=None, **extra): """This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it it's the name of the script. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor. """ for key, value in iteritems(self.context_settings): if key not in extra: extra[key] = value ctx = Context(self, info_name=info_name, parent=parent, **extra) self.parse_args(ctx, args) return ctx
python
def make_context(self, info_name, args, parent=None, **extra): """This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it it's the name of the script. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor. """ for key, value in iteritems(self.context_settings): if key not in extra: extra[key] = value ctx = Context(self, info_name=info_name, parent=parent, **extra) self.parse_args(ctx, args) return ctx
[ "def", "make_context", "(", "self", ",", "info_name", ",", "args", ",", "parent", "=", "None", ",", "*", "*", "extra", ")", ":", "for", "key", ",", "value", "in", "iteritems", "(", "self", ".", "context_settings", ")", ":", "if", "key", "not", "in", "extra", ":", "extra", "[", "key", "]", "=", "value", "ctx", "=", "Context", "(", "self", ",", "info_name", "=", "info_name", ",", "parent", "=", "parent", ",", "*", "*", "extra", ")", "self", ".", "parse_args", "(", "ctx", ",", "args", ")", "return", "ctx" ]
This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it it's the name of the script. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor.
[ "This", "function", "when", "given", "an", "info", "name", "and", "arguments", "will", "kick", "off", "the", "parsing", "and", "create", "a", "new", ":", "class", ":", "Context", ".", "It", "does", "not", "invoke", "the", "actual", "command", "callback", "though", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L541-L561
mottosso/be
be/vendor/click/core.py
BaseCommand.main
def main(self, args=None, prog_name=None, complete_var=None, standalone_mode=True, **extra): """This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. .. versionadded:: 3.0 Added the `standalone_mode` flag to control the standalone mode. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. """ # If we are in Python 3, we will verify that the environment is # sane at this point of reject further execution to avoid a # broken script. if not PY2: try: import locale fs_enc = codecs.lookup(locale.getpreferredencoding()).name except Exception: fs_enc = 'ascii' if fs_enc == 'ascii': raise RuntimeError('Click will abort further execution ' 'because Python 3 was configured to use ' 'ASCII as encoding for the environment. ' 'Either switch to Python 2 or consult ' 'http://click.pocoo.org/python3/ ' 'for mitigation steps.') if args is None: args = sys.argv[1:] else: args = list(args) if prog_name is None: prog_name = make_str(os.path.basename( sys.argv and sys.argv[0] or __file__)) # Hook for the Bash completion. This only activates if the Bash # completion is actually enabled, otherwise this is quite a fast # noop. _bashcomplete(self, prog_name, complete_var) try: try: with self.make_context(prog_name, args, **extra) as ctx: rv = self.invoke(ctx) if not standalone_mode: return rv ctx.exit() except (EOFError, KeyboardInterrupt): echo(file=sys.stderr) raise Abort() except ClickException as e: if not standalone_mode: raise e.show() sys.exit(e.exit_code) except Abort: if not standalone_mode: raise echo('Aborted!', file=sys.stderr) sys.exit(1)
python
def main(self, args=None, prog_name=None, complete_var=None, standalone_mode=True, **extra): """This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. .. versionadded:: 3.0 Added the `standalone_mode` flag to control the standalone mode. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. """ # If we are in Python 3, we will verify that the environment is # sane at this point of reject further execution to avoid a # broken script. if not PY2: try: import locale fs_enc = codecs.lookup(locale.getpreferredencoding()).name except Exception: fs_enc = 'ascii' if fs_enc == 'ascii': raise RuntimeError('Click will abort further execution ' 'because Python 3 was configured to use ' 'ASCII as encoding for the environment. ' 'Either switch to Python 2 or consult ' 'http://click.pocoo.org/python3/ ' 'for mitigation steps.') if args is None: args = sys.argv[1:] else: args = list(args) if prog_name is None: prog_name = make_str(os.path.basename( sys.argv and sys.argv[0] or __file__)) # Hook for the Bash completion. This only activates if the Bash # completion is actually enabled, otherwise this is quite a fast # noop. _bashcomplete(self, prog_name, complete_var) try: try: with self.make_context(prog_name, args, **extra) as ctx: rv = self.invoke(ctx) if not standalone_mode: return rv ctx.exit() except (EOFError, KeyboardInterrupt): echo(file=sys.stderr) raise Abort() except ClickException as e: if not standalone_mode: raise e.show() sys.exit(e.exit_code) except Abort: if not standalone_mode: raise echo('Aborted!', file=sys.stderr) sys.exit(1)
[ "def", "main", "(", "self", ",", "args", "=", "None", ",", "prog_name", "=", "None", ",", "complete_var", "=", "None", ",", "standalone_mode", "=", "True", ",", "*", "*", "extra", ")", ":", "# If we are in Python 3, we will verify that the environment is", "# sane at this point of reject further execution to avoid a", "# broken script.", "if", "not", "PY2", ":", "try", ":", "import", "locale", "fs_enc", "=", "codecs", ".", "lookup", "(", "locale", ".", "getpreferredencoding", "(", ")", ")", ".", "name", "except", "Exception", ":", "fs_enc", "=", "'ascii'", "if", "fs_enc", "==", "'ascii'", ":", "raise", "RuntimeError", "(", "'Click will abort further execution '", "'because Python 3 was configured to use '", "'ASCII as encoding for the environment. '", "'Either switch to Python 2 or consult '", "'http://click.pocoo.org/python3/ '", "'for mitigation steps.'", ")", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "else", ":", "args", "=", "list", "(", "args", ")", "if", "prog_name", "is", "None", ":", "prog_name", "=", "make_str", "(", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "and", "sys", ".", "argv", "[", "0", "]", "or", "__file__", ")", ")", "# Hook for the Bash completion. This only activates if the Bash", "# completion is actually enabled, otherwise this is quite a fast", "# noop.", "_bashcomplete", "(", "self", ",", "prog_name", ",", "complete_var", ")", "try", ":", "try", ":", "with", "self", ".", "make_context", "(", "prog_name", ",", "args", ",", "*", "*", "extra", ")", "as", "ctx", ":", "rv", "=", "self", ".", "invoke", "(", "ctx", ")", "if", "not", "standalone_mode", ":", "return", "rv", "ctx", ".", "exit", "(", ")", "except", "(", "EOFError", ",", "KeyboardInterrupt", ")", ":", "echo", "(", "file", "=", "sys", ".", "stderr", ")", "raise", "Abort", "(", ")", "except", "ClickException", "as", "e", ":", "if", "not", "standalone_mode", ":", "raise", "e", ".", "show", "(", ")", "sys", ".", "exit", "(", "e", ".", "exit_code", ")", "except", "Abort", ":", "if", "not", "standalone_mode", ":", "raise", "echo", "(", "'Aborted!'", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")" ]
This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. .. versionadded:: 3.0 Added the `standalone_mode` flag to control the standalone mode. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information.
[ "This", "is", "the", "way", "to", "invoke", "a", "script", "with", "all", "the", "bells", "and", "whistles", "as", "a", "command", "line", "application", ".", "This", "will", "always", "terminate", "the", "application", "after", "a", "call", ".", "If", "this", "is", "not", "wanted", "SystemExit", "needs", "to", "be", "caught", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L577-L660
mottosso/be
be/vendor/click/core.py
Command.make_parser
def make_parser(self, ctx): """Creates the underlying option parser for this command.""" parser = OptionParser(ctx) parser.allow_interspersed_args = ctx.allow_interspersed_args parser.ignore_unknown_options = ctx.ignore_unknown_options for param in self.get_params(ctx): param.add_to_parser(parser, ctx) return parser
python
def make_parser(self, ctx): """Creates the underlying option parser for this command.""" parser = OptionParser(ctx) parser.allow_interspersed_args = ctx.allow_interspersed_args parser.ignore_unknown_options = ctx.ignore_unknown_options for param in self.get_params(ctx): param.add_to_parser(parser, ctx) return parser
[ "def", "make_parser", "(", "self", ",", "ctx", ")", ":", "parser", "=", "OptionParser", "(", "ctx", ")", "parser", ".", "allow_interspersed_args", "=", "ctx", ".", "allow_interspersed_args", "parser", ".", "ignore_unknown_options", "=", "ctx", ".", "ignore_unknown_options", "for", "param", "in", "self", ".", "get_params", "(", "ctx", ")", ":", "param", ".", "add_to_parser", "(", "parser", ",", "ctx", ")", "return", "parser" ]
Creates the underlying option parser for this command.
[ "Creates", "the", "underlying", "option", "parser", "for", "this", "command", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L758-L765
mottosso/be
be/vendor/click/core.py
Command.format_help_text
def format_help_text(self, ctx, formatter): """Writes the help text to the formatter if it exists.""" if self.help: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.help)
python
def format_help_text(self, ctx, formatter): """Writes the help text to the formatter if it exists.""" if self.help: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.help)
[ "def", "format_help_text", "(", "self", ",", "ctx", ",", "formatter", ")", ":", "if", "self", ".", "help", ":", "formatter", ".", "write_paragraph", "(", ")", "with", "formatter", ".", "indentation", "(", ")", ":", "formatter", ".", "write_text", "(", "self", ".", "help", ")" ]
Writes the help text to the formatter if it exists.
[ "Writes", "the", "help", "text", "to", "the", "formatter", "if", "it", "exists", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L790-L795
mottosso/be
be/vendor/click/core.py
Group.add_command
def add_command(self, cmd, name=None): """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError('Command has no name.') self.commands[name] = cmd
python
def add_command(self, cmd, name=None): """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError('Command has no name.') self.commands[name] = cmd
[ "def", "add_command", "(", "self", ",", "cmd", ",", "name", "=", "None", ")", ":", "name", "=", "name", "or", "cmd", ".", "name", "if", "name", "is", "None", ":", "raise", "TypeError", "(", "'Command has no name.'", ")", "self", ".", "commands", "[", "name", "]", "=", "cmd" ]
Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used.
[ "Registers", "another", ":", "class", ":", "Command", "with", "this", "group", ".", "If", "the", "name", "is", "not", "provided", "the", "name", "of", "the", "command", "is", "used", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L1071-L1078
mottosso/be
be/vendor/click/decorators.py
pass_obj
def pass_obj(f): """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ @pass_context def new_func(*args, **kwargs): ctx = args[0] return ctx.invoke(f, ctx.obj, *args[1:], **kwargs) return update_wrapper(new_func, f)
python
def pass_obj(f): """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ @pass_context def new_func(*args, **kwargs): ctx = args[0] return ctx.invoke(f, ctx.obj, *args[1:], **kwargs) return update_wrapper(new_func, f)
[ "def", "pass_obj", "(", "f", ")", ":", "@", "pass_context", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "args", "[", "0", "]", "return", "ctx", ".", "invoke", "(", "f", ",", "ctx", ".", "obj", ",", "*", "args", "[", "1", ":", "]", ",", "*", "*", "kwargs", ")", "return", "update_wrapper", "(", "new_func", ",", "f", ")" ]
Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system.
[ "Similar", "to", ":", "func", ":", "pass_context", "but", "only", "pass", "the", "object", "on", "the", "context", "onwards", "(", ":", "attr", ":", "Context", ".", "obj", ")", ".", "This", "is", "useful", "if", "that", "object", "represents", "the", "state", "of", "a", "nested", "system", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/decorators.py#L18-L27
mottosso/be
be/vendor/click/decorators.py
option
def option(*param_decls, **attrs): """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the option class to instantiate. This defaults to :class:`Option`. """ def decorator(f): if 'help' in attrs: attrs['help'] = inspect.cleandoc(attrs['help']) OptionClass = attrs.pop('cls', Option) _param_memo(f, OptionClass(param_decls, **attrs)) return f return decorator
python
def option(*param_decls, **attrs): """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the option class to instantiate. This defaults to :class:`Option`. """ def decorator(f): if 'help' in attrs: attrs['help'] = inspect.cleandoc(attrs['help']) OptionClass = attrs.pop('cls', Option) _param_memo(f, OptionClass(param_decls, **attrs)) return f return decorator
[ "def", "option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "def", "decorator", "(", "f", ")", ":", "if", "'help'", "in", "attrs", ":", "attrs", "[", "'help'", "]", "=", "inspect", ".", "cleandoc", "(", "attrs", "[", "'help'", "]", ")", "OptionClass", "=", "attrs", ".", "pop", "(", "'cls'", ",", "Option", ")", "_param_memo", "(", "f", ",", "OptionClass", "(", "param_decls", ",", "*", "*", "attrs", ")", ")", "return", "f", "return", "decorator" ]
Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the option class to instantiate. This defaults to :class:`Option`.
[ "Attaches", "an", "option", "to", "the", "command", ".", "All", "positional", "arguments", "are", "passed", "as", "parameter", "declarations", "to", ":", "class", ":", "Option", ";", "all", "keyword", "arguments", "are", "forwarded", "unchanged", "(", "except", "cls", ")", ".", "This", "is", "equivalent", "to", "creating", "an", ":", "class", ":", "Option", "instance", "manually", "and", "attaching", "it", "to", "the", ":", "attr", ":", "Command", ".", "params", "list", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/decorators.py#L153-L169
mottosso/be
be/vendor/click/decorators.py
version_option
def version_option(version=None, *param_decls, **attrs): """Adds a ``--version`` option which immediately ends the program printing out the version number. This is implemented as an eager option that prints the version and exits the program in the callback. :param version: the version number to show. If not provided Click attempts an auto discovery via setuptools. :param prog_name: the name of the program (defaults to autodetection) :param message: custom message to show instead of the default (``'%(prog)s, version %(version)s'``) :param others: everything else is forwarded to :func:`option`. """ if version is None: module = sys._getframe(1).f_globals.get('__name__') def decorator(f): prog_name = attrs.pop('prog_name', None) message = attrs.pop('message', '%(prog)s, version %(version)s') def callback(ctx, param, value): if not value or ctx.resilient_parsing: return prog = prog_name if prog is None: prog = ctx.find_root().info_name ver = version if ver is None: try: import pkg_resources except ImportError: pass else: for dist in pkg_resources.working_set: scripts = dist.get_entry_map().get('console_scripts') or {} for script_name, entry_point in iteritems(scripts): if entry_point.module_name == module: ver = dist.version break if ver is None: raise RuntimeError('Could not determine version') echo(message % { 'prog': prog, 'version': ver, }, color=ctx.color) ctx.exit() attrs.setdefault('is_flag', True) attrs.setdefault('expose_value', False) attrs.setdefault('is_eager', True) attrs.setdefault('help', 'Show the version and exit.') attrs['callback'] = callback return option(*(param_decls or ('--version',)), **attrs)(f) return decorator
python
def version_option(version=None, *param_decls, **attrs): """Adds a ``--version`` option which immediately ends the program printing out the version number. This is implemented as an eager option that prints the version and exits the program in the callback. :param version: the version number to show. If not provided Click attempts an auto discovery via setuptools. :param prog_name: the name of the program (defaults to autodetection) :param message: custom message to show instead of the default (``'%(prog)s, version %(version)s'``) :param others: everything else is forwarded to :func:`option`. """ if version is None: module = sys._getframe(1).f_globals.get('__name__') def decorator(f): prog_name = attrs.pop('prog_name', None) message = attrs.pop('message', '%(prog)s, version %(version)s') def callback(ctx, param, value): if not value or ctx.resilient_parsing: return prog = prog_name if prog is None: prog = ctx.find_root().info_name ver = version if ver is None: try: import pkg_resources except ImportError: pass else: for dist in pkg_resources.working_set: scripts = dist.get_entry_map().get('console_scripts') or {} for script_name, entry_point in iteritems(scripts): if entry_point.module_name == module: ver = dist.version break if ver is None: raise RuntimeError('Could not determine version') echo(message % { 'prog': prog, 'version': ver, }, color=ctx.color) ctx.exit() attrs.setdefault('is_flag', True) attrs.setdefault('expose_value', False) attrs.setdefault('is_eager', True) attrs.setdefault('help', 'Show the version and exit.') attrs['callback'] = callback return option(*(param_decls or ('--version',)), **attrs)(f) return decorator
[ "def", "version_option", "(", "version", "=", "None", ",", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "if", "version", "is", "None", ":", "module", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", ".", "get", "(", "'__name__'", ")", "def", "decorator", "(", "f", ")", ":", "prog_name", "=", "attrs", ".", "pop", "(", "'prog_name'", ",", "None", ")", "message", "=", "attrs", ".", "pop", "(", "'message'", ",", "'%(prog)s, version %(version)s'", ")", "def", "callback", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "not", "value", "or", "ctx", ".", "resilient_parsing", ":", "return", "prog", "=", "prog_name", "if", "prog", "is", "None", ":", "prog", "=", "ctx", ".", "find_root", "(", ")", ".", "info_name", "ver", "=", "version", "if", "ver", "is", "None", ":", "try", ":", "import", "pkg_resources", "except", "ImportError", ":", "pass", "else", ":", "for", "dist", "in", "pkg_resources", ".", "working_set", ":", "scripts", "=", "dist", ".", "get_entry_map", "(", ")", ".", "get", "(", "'console_scripts'", ")", "or", "{", "}", "for", "script_name", ",", "entry_point", "in", "iteritems", "(", "scripts", ")", ":", "if", "entry_point", ".", "module_name", "==", "module", ":", "ver", "=", "dist", ".", "version", "break", "if", "ver", "is", "None", ":", "raise", "RuntimeError", "(", "'Could not determine version'", ")", "echo", "(", "message", "%", "{", "'prog'", ":", "prog", ",", "'version'", ":", "ver", ",", "}", ",", "color", "=", "ctx", ".", "color", ")", "ctx", ".", "exit", "(", ")", "attrs", ".", "setdefault", "(", "'is_flag'", ",", "True", ")", "attrs", ".", "setdefault", "(", "'expose_value'", ",", "False", ")", "attrs", ".", "setdefault", "(", "'is_eager'", ",", "True", ")", "attrs", ".", "setdefault", "(", "'help'", ",", "'Show the version and exit.'", ")", "attrs", "[", "'callback'", "]", "=", "callback", "return", "option", "(", "*", "(", "param_decls", "or", "(", "'--version'", ",", ")", ")", ",", "*", "*", "attrs", ")", "(", "f", ")", "return", "decorator" ]
Adds a ``--version`` option which immediately ends the program printing out the version number. This is implemented as an eager option that prints the version and exits the program in the callback. :param version: the version number to show. If not provided Click attempts an auto discovery via setuptools. :param prog_name: the name of the program (defaults to autodetection) :param message: custom message to show instead of the default (``'%(prog)s, version %(version)s'``) :param others: everything else is forwarded to :func:`option`.
[ "Adds", "a", "--", "version", "option", "which", "immediately", "ends", "the", "program", "printing", "out", "the", "version", "number", ".", "This", "is", "implemented", "as", "an", "eager", "option", "that", "prints", "the", "version", "and", "exits", "the", "program", "in", "the", "callback", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/decorators.py#L222-L273
mottosso/be
be/vendor/requests/auth.py
_basic_auth_str
def _basic_auth_str(username, password): """Returns a Basic Auth string.""" authstr = 'Basic ' + to_native_string( b64encode(('%s:%s' % (username, password)).encode('latin1')).strip() ) return authstr
python
def _basic_auth_str(username, password): """Returns a Basic Auth string.""" authstr = 'Basic ' + to_native_string( b64encode(('%s:%s' % (username, password)).encode('latin1')).strip() ) return authstr
[ "def", "_basic_auth_str", "(", "username", ",", "password", ")", ":", "authstr", "=", "'Basic '", "+", "to_native_string", "(", "b64encode", "(", "(", "'%s:%s'", "%", "(", "username", ",", "password", ")", ")", ".", "encode", "(", "'latin1'", ")", ")", ".", "strip", "(", ")", ")", "return", "authstr" ]
Returns a Basic Auth string.
[ "Returns", "a", "Basic", "Auth", "string", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/auth.py#L26-L33
mottosso/be
be/util.py
ls
def ls(*topic, **kwargs): """List topic from external datastore Arguments: topic (str): One or more topics, e.g. ("project", "item", "task") root (str, optional): Absolute path to where projects reside, defaults to os.getcwd() backend (callable, optional): Function to call with absolute path as argument to retrieve children. Defaults to os.listdir absolute (bool, optional): Whether to return relative or absolute paths Example: >> ls() /projects/thedeal /projects/hulk >> ls("thedeal") /projects/thedeal/assets/ben /projects/thedeal/assets/table >> ls("thedeal", "ben") /projects/thedeal/assets/ben/rigging /projects/thedeal/assets/ben/modeling """ context = dump() root = kwargs.get("root") or context.get("cwd") or os.getcwd() backend = kwargs.get("backend", os.listdir) absolute = kwargs.get("absolute", True) content = { 0: "projects", 1: "inventory", 2: "template" }[min(2, len(topic))] # List projects if content == "projects": projects = lib.list_projects(root=root, backend=backend) if absolute: return map(lambda p: os.path.join(root, p), projects) else: return projects # List items if content == "inventory": project = topic[0] be = _extern.load(project, "be", root=root) inventory = _extern.load(project, "inventory", root=root) inventory = lib.invert_inventory(inventory) templates = _extern.load(project, "templates", root=root) if absolute: paths = list() for item, binding in inventory.iteritems(): template = templates.get(binding) index = len(topic) sliced = lib.slice(index, template) paths.append(sliced.format(*(topic + (item,)), **context)) return paths else: return inventory.keys() # List template if content == "template": project = topic[0] be = _extern.load(project, "be", root=root) templates = _extern.load(project, "templates", root=root) inventory = _extern.load(project, "inventory", root=root) return lib.list_template(root=root, topics=topic, templates=templates, inventory=inventory, be=be, absolute=absolute)
python
def ls(*topic, **kwargs): """List topic from external datastore Arguments: topic (str): One or more topics, e.g. ("project", "item", "task") root (str, optional): Absolute path to where projects reside, defaults to os.getcwd() backend (callable, optional): Function to call with absolute path as argument to retrieve children. Defaults to os.listdir absolute (bool, optional): Whether to return relative or absolute paths Example: >> ls() /projects/thedeal /projects/hulk >> ls("thedeal") /projects/thedeal/assets/ben /projects/thedeal/assets/table >> ls("thedeal", "ben") /projects/thedeal/assets/ben/rigging /projects/thedeal/assets/ben/modeling """ context = dump() root = kwargs.get("root") or context.get("cwd") or os.getcwd() backend = kwargs.get("backend", os.listdir) absolute = kwargs.get("absolute", True) content = { 0: "projects", 1: "inventory", 2: "template" }[min(2, len(topic))] # List projects if content == "projects": projects = lib.list_projects(root=root, backend=backend) if absolute: return map(lambda p: os.path.join(root, p), projects) else: return projects # List items if content == "inventory": project = topic[0] be = _extern.load(project, "be", root=root) inventory = _extern.load(project, "inventory", root=root) inventory = lib.invert_inventory(inventory) templates = _extern.load(project, "templates", root=root) if absolute: paths = list() for item, binding in inventory.iteritems(): template = templates.get(binding) index = len(topic) sliced = lib.slice(index, template) paths.append(sliced.format(*(topic + (item,)), **context)) return paths else: return inventory.keys() # List template if content == "template": project = topic[0] be = _extern.load(project, "be", root=root) templates = _extern.load(project, "templates", root=root) inventory = _extern.load(project, "inventory", root=root) return lib.list_template(root=root, topics=topic, templates=templates, inventory=inventory, be=be, absolute=absolute)
[ "def", "ls", "(", "*", "topic", ",", "*", "*", "kwargs", ")", ":", "context", "=", "dump", "(", ")", "root", "=", "kwargs", ".", "get", "(", "\"root\"", ")", "or", "context", ".", "get", "(", "\"cwd\"", ")", "or", "os", ".", "getcwd", "(", ")", "backend", "=", "kwargs", ".", "get", "(", "\"backend\"", ",", "os", ".", "listdir", ")", "absolute", "=", "kwargs", ".", "get", "(", "\"absolute\"", ",", "True", ")", "content", "=", "{", "0", ":", "\"projects\"", ",", "1", ":", "\"inventory\"", ",", "2", ":", "\"template\"", "}", "[", "min", "(", "2", ",", "len", "(", "topic", ")", ")", "]", "# List projects", "if", "content", "==", "\"projects\"", ":", "projects", "=", "lib", ".", "list_projects", "(", "root", "=", "root", ",", "backend", "=", "backend", ")", "if", "absolute", ":", "return", "map", "(", "lambda", "p", ":", "os", ".", "path", ".", "join", "(", "root", ",", "p", ")", ",", "projects", ")", "else", ":", "return", "projects", "# List items", "if", "content", "==", "\"inventory\"", ":", "project", "=", "topic", "[", "0", "]", "be", "=", "_extern", ".", "load", "(", "project", ",", "\"be\"", ",", "root", "=", "root", ")", "inventory", "=", "_extern", ".", "load", "(", "project", ",", "\"inventory\"", ",", "root", "=", "root", ")", "inventory", "=", "lib", ".", "invert_inventory", "(", "inventory", ")", "templates", "=", "_extern", ".", "load", "(", "project", ",", "\"templates\"", ",", "root", "=", "root", ")", "if", "absolute", ":", "paths", "=", "list", "(", ")", "for", "item", ",", "binding", "in", "inventory", ".", "iteritems", "(", ")", ":", "template", "=", "templates", ".", "get", "(", "binding", ")", "index", "=", "len", "(", "topic", ")", "sliced", "=", "lib", ".", "slice", "(", "index", ",", "template", ")", "paths", ".", "append", "(", "sliced", ".", "format", "(", "*", "(", "topic", "+", "(", "item", ",", ")", ")", ",", "*", "*", "context", ")", ")", "return", "paths", "else", ":", "return", "inventory", ".", "keys", "(", ")", "# List template", "if", "content", "==", "\"template\"", ":", "project", "=", "topic", "[", "0", "]", "be", "=", "_extern", ".", "load", "(", "project", ",", "\"be\"", ",", "root", "=", "root", ")", "templates", "=", "_extern", ".", "load", "(", "project", ",", "\"templates\"", ",", "root", "=", "root", ")", "inventory", "=", "_extern", ".", "load", "(", "project", ",", "\"inventory\"", ",", "root", "=", "root", ")", "return", "lib", ".", "list_template", "(", "root", "=", "root", ",", "topics", "=", "topic", ",", "templates", "=", "templates", ",", "inventory", "=", "inventory", ",", "be", "=", "be", ",", "absolute", "=", "absolute", ")" ]
List topic from external datastore Arguments: topic (str): One or more topics, e.g. ("project", "item", "task") root (str, optional): Absolute path to where projects reside, defaults to os.getcwd() backend (callable, optional): Function to call with absolute path as argument to retrieve children. Defaults to os.listdir absolute (bool, optional): Whether to return relative or absolute paths Example: >> ls() /projects/thedeal /projects/hulk >> ls("thedeal") /projects/thedeal/assets/ben /projects/thedeal/assets/table >> ls("thedeal", "ben") /projects/thedeal/assets/ben/rigging /projects/thedeal/assets/ben/modeling
[ "List", "topic", "from", "external", "datastore" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/util.py#L7-L82
mottosso/be
be/util.py
dump
def dump(context=os.environ): """Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults to the current environment. """ output = {} for key, value in context.iteritems(): if not key.startswith("BE_"): continue output[key[3:].lower()] = value return output
python
def dump(context=os.environ): """Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults to the current environment. """ output = {} for key, value in context.iteritems(): if not key.startswith("BE_"): continue output[key[3:].lower()] = value return output
[ "def", "dump", "(", "context", "=", "os", ".", "environ", ")", ":", "output", "=", "{", "}", "for", "key", ",", "value", "in", "context", ".", "iteritems", "(", ")", ":", "if", "not", "key", ".", "startswith", "(", "\"BE_\"", ")", ":", "continue", "output", "[", "key", "[", "3", ":", "]", ".", "lower", "(", ")", "]", "=", "value", "return", "output" ]
Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults to the current environment.
[ "Dump", "current", "environment", "as", "a", "dictionary" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/util.py#L100-L115
mottosso/be
be/_extern.py
cwd
def cwd(): """Return the be current working directory""" cwd = os.environ.get("BE_CWD") if cwd and not os.path.isdir(cwd): sys.stderr.write("ERROR: %s is not a directory" % cwd) sys.exit(lib.USER_ERROR) return cwd or os.getcwd().replace("\\", "/")
python
def cwd(): """Return the be current working directory""" cwd = os.environ.get("BE_CWD") if cwd and not os.path.isdir(cwd): sys.stderr.write("ERROR: %s is not a directory" % cwd) sys.exit(lib.USER_ERROR) return cwd or os.getcwd().replace("\\", "/")
[ "def", "cwd", "(", ")", ":", "cwd", "=", "os", ".", "environ", ".", "get", "(", "\"BE_CWD\"", ")", "if", "cwd", "and", "not", "os", ".", "path", ".", "isdir", "(", "cwd", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"ERROR: %s is not a directory\"", "%", "cwd", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "return", "cwd", "or", "os", ".", "getcwd", "(", ")", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")" ]
Return the be current working directory
[ "Return", "the", "be", "current", "working", "directory" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L52-L58
mottosso/be
be/_extern.py
write_script
def write_script(script, tempdir): """Write script to a temporary directory Arguments: script (list): Commands which to put into a file Returns: Absolute path to script """ name = "script" + self.suffix path = os.path.join(tempdir, name) with open(path, "w") as f: f.write("\n".join(script)) return path
python
def write_script(script, tempdir): """Write script to a temporary directory Arguments: script (list): Commands which to put into a file Returns: Absolute path to script """ name = "script" + self.suffix path = os.path.join(tempdir, name) with open(path, "w") as f: f.write("\n".join(script)) return path
[ "def", "write_script", "(", "script", ",", "tempdir", ")", ":", "name", "=", "\"script\"", "+", "self", ".", "suffix", "path", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "name", ")", "with", "open", "(", "path", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "\"\\n\"", ".", "join", "(", "script", ")", ")", "return", "path" ]
Write script to a temporary directory Arguments: script (list): Commands which to put into a file Returns: Absolute path to script
[ "Write", "script", "to", "a", "temporary", "directory" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L105-L122
mottosso/be
be/_extern.py
write_aliases
def write_aliases(aliases, tempdir): """Write aliases to temporary directory Arguments: aliases (dict): {name: value} dict of aliases tempdir (str): Absolute path to where aliases will be stored """ platform = lib.platform() if platform == "unix": home_alias = "cd $BE_DEVELOPMENTDIR" else: home_alias = "cd %BE_DEVELOPMENTDIR%" aliases["home"] = home_alias tempdir = os.path.join(tempdir, "aliases") os.makedirs(tempdir) for alias, cmd in aliases.iteritems(): path = os.path.join(tempdir, alias) if platform == "windows": path += ".bat" with open(path, "w") as f: f.write(cmd) if platform == "unix": # Make executable st = os.stat(path) os.chmod(path, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) return tempdir
python
def write_aliases(aliases, tempdir): """Write aliases to temporary directory Arguments: aliases (dict): {name: value} dict of aliases tempdir (str): Absolute path to where aliases will be stored """ platform = lib.platform() if platform == "unix": home_alias = "cd $BE_DEVELOPMENTDIR" else: home_alias = "cd %BE_DEVELOPMENTDIR%" aliases["home"] = home_alias tempdir = os.path.join(tempdir, "aliases") os.makedirs(tempdir) for alias, cmd in aliases.iteritems(): path = os.path.join(tempdir, alias) if platform == "windows": path += ".bat" with open(path, "w") as f: f.write(cmd) if platform == "unix": # Make executable st = os.stat(path) os.chmod(path, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) return tempdir
[ "def", "write_aliases", "(", "aliases", ",", "tempdir", ")", ":", "platform", "=", "lib", ".", "platform", "(", ")", "if", "platform", "==", "\"unix\"", ":", "home_alias", "=", "\"cd $BE_DEVELOPMENTDIR\"", "else", ":", "home_alias", "=", "\"cd %BE_DEVELOPMENTDIR%\"", "aliases", "[", "\"home\"", "]", "=", "home_alias", "tempdir", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "\"aliases\"", ")", "os", ".", "makedirs", "(", "tempdir", ")", "for", "alias", ",", "cmd", "in", "aliases", ".", "iteritems", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "alias", ")", "if", "platform", "==", "\"windows\"", ":", "path", "+=", "\".bat\"", "with", "open", "(", "path", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "cmd", ")", "if", "platform", "==", "\"unix\"", ":", "# Make executable", "st", "=", "os", ".", "stat", "(", "path", ")", "os", ".", "chmod", "(", "path", ",", "st", ".", "st_mode", "|", "stat", ".", "S_IXUSR", "|", "stat", ".", "S_IXGRP", "|", "stat", ".", "S_IXOTH", ")", "return", "tempdir" ]
Write aliases to temporary directory Arguments: aliases (dict): {name: value} dict of aliases tempdir (str): Absolute path to where aliases will be stored
[ "Write", "aliases", "to", "temporary", "directory" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L125-L160
mottosso/be
be/_extern.py
presets_dir
def presets_dir(): """Return presets directory""" default_presets_dir = os.path.join( os.path.expanduser("~"), ".be", "presets") presets_dir = os.environ.get(BE_PRESETSDIR) or default_presets_dir if not os.path.exists(presets_dir): os.makedirs(presets_dir) return presets_dir
python
def presets_dir(): """Return presets directory""" default_presets_dir = os.path.join( os.path.expanduser("~"), ".be", "presets") presets_dir = os.environ.get(BE_PRESETSDIR) or default_presets_dir if not os.path.exists(presets_dir): os.makedirs(presets_dir) return presets_dir
[ "def", "presets_dir", "(", ")", ":", "default_presets_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", ",", "\".be\"", ",", "\"presets\"", ")", "presets_dir", "=", "os", ".", "environ", ".", "get", "(", "BE_PRESETSDIR", ")", "or", "default_presets_dir", "if", "not", "os", ".", "path", ".", "exists", "(", "presets_dir", ")", ":", "os", ".", "makedirs", "(", "presets_dir", ")", "return", "presets_dir" ]
Return presets directory
[ "Return", "presets", "directory" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L168-L175
mottosso/be
be/_extern.py
remove_preset
def remove_preset(preset): """Physically delete local preset Arguments: preset (str): Name of preset """ preset_dir = os.path.join(presets_dir(), preset) try: shutil.rmtree(preset_dir) except IOError: lib.echo("\"%s\" did not exist" % preset)
python
def remove_preset(preset): """Physically delete local preset Arguments: preset (str): Name of preset """ preset_dir = os.path.join(presets_dir(), preset) try: shutil.rmtree(preset_dir) except IOError: lib.echo("\"%s\" did not exist" % preset)
[ "def", "remove_preset", "(", "preset", ")", ":", "preset_dir", "=", "os", ".", "path", ".", "join", "(", "presets_dir", "(", ")", ",", "preset", ")", "try", ":", "shutil", ".", "rmtree", "(", "preset_dir", ")", "except", "IOError", ":", "lib", ".", "echo", "(", "\"\\\"%s\\\" did not exist\"", "%", "preset", ")" ]
Physically delete local preset Arguments: preset (str): Name of preset
[ "Physically", "delete", "local", "preset" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L178-L191
mottosso/be
be/_extern.py
get
def get(path, **kwargs): """requests.get wrapper""" token = os.environ.get(BE_GITHUB_API_TOKEN) if token: kwargs["headers"] = { "Authorization": "token %s" % token } try: response = requests.get(path, verify=False, **kwargs) if response.status_code == 403: lib.echo("Patience: You can't pull more than 60 " "presets per hour without an API token.\n" "See https://github.com/mottosso/be/wiki" "/advanced#extended-preset-access") sys.exit(lib.USER_ERROR) return response except Exception as e: if self.verbose: lib.echo("ERROR: %s" % e) else: lib.echo("ERROR: Something went wrong. " "See --verbose for more information")
python
def get(path, **kwargs): """requests.get wrapper""" token = os.environ.get(BE_GITHUB_API_TOKEN) if token: kwargs["headers"] = { "Authorization": "token %s" % token } try: response = requests.get(path, verify=False, **kwargs) if response.status_code == 403: lib.echo("Patience: You can't pull more than 60 " "presets per hour without an API token.\n" "See https://github.com/mottosso/be/wiki" "/advanced#extended-preset-access") sys.exit(lib.USER_ERROR) return response except Exception as e: if self.verbose: lib.echo("ERROR: %s" % e) else: lib.echo("ERROR: Something went wrong. " "See --verbose for more information")
[ "def", "get", "(", "path", ",", "*", "*", "kwargs", ")", ":", "token", "=", "os", ".", "environ", ".", "get", "(", "BE_GITHUB_API_TOKEN", ")", "if", "token", ":", "kwargs", "[", "\"headers\"", "]", "=", "{", "\"Authorization\"", ":", "\"token %s\"", "%", "token", "}", "try", ":", "response", "=", "requests", ".", "get", "(", "path", ",", "verify", "=", "False", ",", "*", "*", "kwargs", ")", "if", "response", ".", "status_code", "==", "403", ":", "lib", ".", "echo", "(", "\"Patience: You can't pull more than 60 \"", "\"presets per hour without an API token.\\n\"", "\"See https://github.com/mottosso/be/wiki\"", "\"/advanced#extended-preset-access\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "return", "response", "except", "Exception", "as", "e", ":", "if", "self", ".", "verbose", ":", "lib", ".", "echo", "(", "\"ERROR: %s\"", "%", "e", ")", "else", ":", "lib", ".", "echo", "(", "\"ERROR: Something went wrong. \"", "\"See --verbose for more information\"", ")" ]
requests.get wrapper
[ "requests", ".", "get", "wrapper" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L194-L216
mottosso/be
be/_extern.py
_gist_is_preset
def _gist_is_preset(repo): """Evaluate whether gist is a be package Arguments: gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde """ _, gistid = repo.split("/") gist_template = "https://api.github.com/gists/{}" gist_path = gist_template.format(gistid) response = get(gist_path) if response.status_code == 404: return False try: data = response.json() except: return False files = data.get("files", {}) package = files.get("package.json", {}) try: content = json.loads(package.get("content", "")) except: return False if content.get("type") != "bepreset": return False return True
python
def _gist_is_preset(repo): """Evaluate whether gist is a be package Arguments: gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde """ _, gistid = repo.split("/") gist_template = "https://api.github.com/gists/{}" gist_path = gist_template.format(gistid) response = get(gist_path) if response.status_code == 404: return False try: data = response.json() except: return False files = data.get("files", {}) package = files.get("package.json", {}) try: content = json.loads(package.get("content", "")) except: return False if content.get("type") != "bepreset": return False return True
[ "def", "_gist_is_preset", "(", "repo", ")", ":", "_", ",", "gistid", "=", "repo", ".", "split", "(", "\"/\"", ")", "gist_template", "=", "\"https://api.github.com/gists/{}\"", "gist_path", "=", "gist_template", ".", "format", "(", "gistid", ")", "response", "=", "get", "(", "gist_path", ")", "if", "response", ".", "status_code", "==", "404", ":", "return", "False", "try", ":", "data", "=", "response", ".", "json", "(", ")", "except", ":", "return", "False", "files", "=", "data", ".", "get", "(", "\"files\"", ",", "{", "}", ")", "package", "=", "files", ".", "get", "(", "\"package.json\"", ",", "{", "}", ")", "try", ":", "content", "=", "json", ".", "loads", "(", "package", ".", "get", "(", "\"content\"", ",", "\"\"", ")", ")", "except", ":", "return", "False", "if", "content", ".", "get", "(", "\"type\"", ")", "!=", "\"bepreset\"", ":", "return", "False", "return", "True" ]
Evaluate whether gist is a be package Arguments: gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde
[ "Evaluate", "whether", "gist", "is", "a", "be", "package" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L239-L272
mottosso/be
be/_extern.py
_repo_is_preset
def _repo_is_preset(repo): """Evaluate whether GitHub repository is a be package Arguments: gist (str): username/id pair e.g. mottosso/be-ad """ package_template = "https://raw.githubusercontent.com" package_template += "/{repo}/master/package.json" package_path = package_template.format(repo=repo) response = get(package_path) if response.status_code == 404: return False try: data = response.json() except: return False if not data.get("type") == "bepreset": return False return True
python
def _repo_is_preset(repo): """Evaluate whether GitHub repository is a be package Arguments: gist (str): username/id pair e.g. mottosso/be-ad """ package_template = "https://raw.githubusercontent.com" package_template += "/{repo}/master/package.json" package_path = package_template.format(repo=repo) response = get(package_path) if response.status_code == 404: return False try: data = response.json() except: return False if not data.get("type") == "bepreset": return False return True
[ "def", "_repo_is_preset", "(", "repo", ")", ":", "package_template", "=", "\"https://raw.githubusercontent.com\"", "package_template", "+=", "\"/{repo}/master/package.json\"", "package_path", "=", "package_template", ".", "format", "(", "repo", "=", "repo", ")", "response", "=", "get", "(", "package_path", ")", "if", "response", ".", "status_code", "==", "404", ":", "return", "False", "try", ":", "data", "=", "response", ".", "json", "(", ")", "except", ":", "return", "False", "if", "not", "data", ".", "get", "(", "\"type\"", ")", "==", "\"bepreset\"", ":", "return", "False", "return", "True" ]
Evaluate whether GitHub repository is a be package Arguments: gist (str): username/id pair e.g. mottosso/be-ad
[ "Evaluate", "whether", "GitHub", "repository", "is", "a", "be", "package" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L275-L299
mottosso/be
be/_extern.py
github_presets
def github_presets(): """Return remote presets hosted on GitHub""" addr = ("https://raw.githubusercontent.com" "/mottosso/be-presets/master/presets.json") response = get(addr) if response.status_code == 404: lib.echo("Could not connect with preset database") sys.exit(lib.PROGRAM_ERROR) return dict((package["name"], package["repository"]) for package in response.json().get("presets"))
python
def github_presets(): """Return remote presets hosted on GitHub""" addr = ("https://raw.githubusercontent.com" "/mottosso/be-presets/master/presets.json") response = get(addr) if response.status_code == 404: lib.echo("Could not connect with preset database") sys.exit(lib.PROGRAM_ERROR) return dict((package["name"], package["repository"]) for package in response.json().get("presets"))
[ "def", "github_presets", "(", ")", ":", "addr", "=", "(", "\"https://raw.githubusercontent.com\"", "\"/mottosso/be-presets/master/presets.json\"", ")", "response", "=", "get", "(", "addr", ")", "if", "response", ".", "status_code", "==", "404", ":", "lib", ".", "echo", "(", "\"Could not connect with preset database\"", ")", "sys", ".", "exit", "(", "lib", ".", "PROGRAM_ERROR", ")", "return", "dict", "(", "(", "package", "[", "\"name\"", "]", ",", "package", "[", "\"repository\"", "]", ")", "for", "package", "in", "response", ".", "json", "(", ")", ".", "get", "(", "\"presets\"", ")", ")" ]
Return remote presets hosted on GitHub
[ "Return", "remote", "presets", "hosted", "on", "GitHub" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L383-L394
mottosso/be
be/_extern.py
copy_preset
def copy_preset(preset_dir, project_dir): """Copy contents of preset into new project If package.json contains the key "contents", limit the files copied to those present in this list. Arguments: preset_dir (str): Absolute path to preset project_dir (str): Absolute path to new project """ os.makedirs(project_dir) package_file = os.path.join(preset_dir, "package.json") with open(package_file) as f: package = json.load(f) for fname in os.listdir(preset_dir): src = os.path.join(preset_dir, fname) contents = package.get("contents") or [] if fname not in self.files + contents: continue if os.path.isfile(src): shutil.copy2(src, project_dir) else: dest = os.path.join(project_dir, fname) shutil.copytree(src, dest)
python
def copy_preset(preset_dir, project_dir): """Copy contents of preset into new project If package.json contains the key "contents", limit the files copied to those present in this list. Arguments: preset_dir (str): Absolute path to preset project_dir (str): Absolute path to new project """ os.makedirs(project_dir) package_file = os.path.join(preset_dir, "package.json") with open(package_file) as f: package = json.load(f) for fname in os.listdir(preset_dir): src = os.path.join(preset_dir, fname) contents = package.get("contents") or [] if fname not in self.files + contents: continue if os.path.isfile(src): shutil.copy2(src, project_dir) else: dest = os.path.join(project_dir, fname) shutil.copytree(src, dest)
[ "def", "copy_preset", "(", "preset_dir", ",", "project_dir", ")", ":", "os", ".", "makedirs", "(", "project_dir", ")", "package_file", "=", "os", ".", "path", ".", "join", "(", "preset_dir", ",", "\"package.json\"", ")", "with", "open", "(", "package_file", ")", "as", "f", ":", "package", "=", "json", ".", "load", "(", "f", ")", "for", "fname", "in", "os", ".", "listdir", "(", "preset_dir", ")", ":", "src", "=", "os", ".", "path", ".", "join", "(", "preset_dir", ",", "fname", ")", "contents", "=", "package", ".", "get", "(", "\"contents\"", ")", "or", "[", "]", "if", "fname", "not", "in", "self", ".", "files", "+", "contents", ":", "continue", "if", "os", ".", "path", ".", "isfile", "(", "src", ")", ":", "shutil", ".", "copy2", "(", "src", ",", "project_dir", ")", "else", ":", "dest", "=", "os", ".", "path", ".", "join", "(", "project_dir", ",", "fname", ")", "shutil", ".", "copytree", "(", "src", ",", "dest", ")" ]
Copy contents of preset into new project If package.json contains the key "contents", limit the files copied to those present in this list. Arguments: preset_dir (str): Absolute path to preset project_dir (str): Absolute path to new project
[ "Copy", "contents", "of", "preset", "into", "new", "project" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L397-L427
mottosso/be
be/_extern.py
_resolve_references
def _resolve_references(templates): """Resolve {@} occurences by expansion Given a dictionary {"a": "{@b}/x", "b": "{key}/y"} Return {"a", "{key}/y/x", "b": "{key}/y"} { key: {@reference}/{variable} # pattern } In plain english, it looks within `pattern` for references and replaces them with the value of the matching key. { root: {cwd}/{project} item: {@root}/{item} } In the above case, `item` is referencing `root` which is resolved into this. { item: {cwd}/{project}/{item} } Example: >>> templates = {"a": "{@b}/x", "b": "{key}/y"} >>> resolved = _resolve_references(templates) >>> assert resolved["a"] == "{key}/y/x" """ def repl(match): lib.echo("Deprecation warning: The {@ref} syntax is being removed") key = pattern[match.start():match.end()].strip("@{}") if key not in templates: sys.stderr.write("Unresolvable reference: \"%s\"" % key) sys.exit(lib.USER_ERROR) return templates[key] for key, pattern in templates.copy().iteritems(): templates[key] = re.sub("{@\w+}", repl, pattern) return templates
python
def _resolve_references(templates): """Resolve {@} occurences by expansion Given a dictionary {"a": "{@b}/x", "b": "{key}/y"} Return {"a", "{key}/y/x", "b": "{key}/y"} { key: {@reference}/{variable} # pattern } In plain english, it looks within `pattern` for references and replaces them with the value of the matching key. { root: {cwd}/{project} item: {@root}/{item} } In the above case, `item` is referencing `root` which is resolved into this. { item: {cwd}/{project}/{item} } Example: >>> templates = {"a": "{@b}/x", "b": "{key}/y"} >>> resolved = _resolve_references(templates) >>> assert resolved["a"] == "{key}/y/x" """ def repl(match): lib.echo("Deprecation warning: The {@ref} syntax is being removed") key = pattern[match.start():match.end()].strip("@{}") if key not in templates: sys.stderr.write("Unresolvable reference: \"%s\"" % key) sys.exit(lib.USER_ERROR) return templates[key] for key, pattern in templates.copy().iteritems(): templates[key] = re.sub("{@\w+}", repl, pattern) return templates
[ "def", "_resolve_references", "(", "templates", ")", ":", "def", "repl", "(", "match", ")", ":", "lib", ".", "echo", "(", "\"Deprecation warning: The {@ref} syntax is being removed\"", ")", "key", "=", "pattern", "[", "match", ".", "start", "(", ")", ":", "match", ".", "end", "(", ")", "]", ".", "strip", "(", "\"@{}\"", ")", "if", "key", "not", "in", "templates", ":", "sys", ".", "stderr", ".", "write", "(", "\"Unresolvable reference: \\\"%s\\\"\"", "%", "key", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "return", "templates", "[", "key", "]", "for", "key", ",", "pattern", "in", "templates", ".", "copy", "(", ")", ".", "iteritems", "(", ")", ":", "templates", "[", "key", "]", "=", "re", ".", "sub", "(", "\"{@\\w+}\"", ",", "repl", ",", "pattern", ")", "return", "templates" ]
Resolve {@} occurences by expansion Given a dictionary {"a": "{@b}/x", "b": "{key}/y"} Return {"a", "{key}/y/x", "b": "{key}/y"} { key: {@reference}/{variable} # pattern } In plain english, it looks within `pattern` for references and replaces them with the value of the matching key. { root: {cwd}/{project} item: {@root}/{item} } In the above case, `item` is referencing `root` which is resolved into this. { item: {cwd}/{project}/{item} } Example: >>> templates = {"a": "{@b}/x", "b": "{key}/y"} >>> resolved = _resolve_references(templates) >>> assert resolved["a"] == "{key}/y/x"
[ "Resolve", "{", "@", "}", "occurences", "by", "expansion" ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L430-L474
mottosso/be
be/vendor/requests/packages/urllib3/_collections.py
HTTPHeaderDict.add
def add(self, key, val): """Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz' """ key_lower = key.lower() new_vals = key, val # Keep the common case aka no item present as fast as possible vals = _dict_setdefault(self, key_lower, new_vals) if new_vals is not vals: # new_vals was not inserted, as there was a previous one if isinstance(vals, list): # If already several items got inserted, we have a list vals.append(val) else: # vals should be a tuple then, i.e. only one item so far # Need to convert the tuple to list for further extension _dict_setitem(self, key_lower, [vals[0], vals[1], val])
python
def add(self, key, val): """Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz' """ key_lower = key.lower() new_vals = key, val # Keep the common case aka no item present as fast as possible vals = _dict_setdefault(self, key_lower, new_vals) if new_vals is not vals: # new_vals was not inserted, as there was a previous one if isinstance(vals, list): # If already several items got inserted, we have a list vals.append(val) else: # vals should be a tuple then, i.e. only one item so far # Need to convert the tuple to list for further extension _dict_setitem(self, key_lower, [vals[0], vals[1], val])
[ "def", "add", "(", "self", ",", "key", ",", "val", ")", ":", "key_lower", "=", "key", ".", "lower", "(", ")", "new_vals", "=", "key", ",", "val", "# Keep the common case aka no item present as fast as possible", "vals", "=", "_dict_setdefault", "(", "self", ",", "key_lower", ",", "new_vals", ")", "if", "new_vals", "is", "not", "vals", ":", "# new_vals was not inserted, as there was a previous one", "if", "isinstance", "(", "vals", ",", "list", ")", ":", "# If already several items got inserted, we have a list", "vals", ".", "append", "(", "val", ")", "else", ":", "# vals should be a tuple then, i.e. only one item so far", "# Need to convert the tuple to list for further extension", "_dict_setitem", "(", "self", ",", "key_lower", ",", "[", "vals", "[", "0", "]", ",", "vals", "[", "1", "]", ",", "val", "]", ")" ]
Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz'
[ "Adds", "a", "(", "name", "value", ")", "pair", "doesn", "t", "overwrite", "the", "value", "if", "it", "already", "exists", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/_collections.py#L207-L228
mottosso/be
be/vendor/requests/packages/urllib3/_collections.py
HTTPHeaderDict.getlist
def getlist(self, key): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = _dict_getitem(self, key.lower()) except KeyError: return [] else: if isinstance(vals, tuple): return [vals[1]] else: return vals[1:]
python
def getlist(self, key): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = _dict_getitem(self, key.lower()) except KeyError: return [] else: if isinstance(vals, tuple): return [vals[1]] else: return vals[1:]
[ "def", "getlist", "(", "self", ",", "key", ")", ":", "try", ":", "vals", "=", "_dict_getitem", "(", "self", ",", "key", ".", "lower", "(", ")", ")", "except", "KeyError", ":", "return", "[", "]", "else", ":", "if", "isinstance", "(", "vals", ",", "tuple", ")", ":", "return", "[", "vals", "[", "1", "]", "]", "else", ":", "return", "vals", "[", "1", ":", "]" ]
Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.
[ "Returns", "a", "list", "of", "all", "the", "values", "for", "the", "named", "field", ".", "Returns", "an", "empty", "list", "if", "the", "key", "doesn", "t", "exist", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/_collections.py#L256-L267
mottosso/be
be/vendor/requests/packages/urllib3/_collections.py
HTTPHeaderDict.iteritems
def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = _dict_getitem(self, key) for val in vals[1:]: yield vals[0], val
python
def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = _dict_getitem(self, key) for val in vals[1:]: yield vals[0], val
[ "def", "iteritems", "(", "self", ")", ":", "for", "key", "in", "self", ":", "vals", "=", "_dict_getitem", "(", "self", ",", "key", ")", "for", "val", "in", "vals", "[", "1", ":", "]", ":", "yield", "vals", "[", "0", "]", ",", "val" ]
Iterate over all header lines, including duplicate ones.
[ "Iterate", "over", "all", "header", "lines", "including", "duplicate", "ones", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/_collections.py#L290-L295
mottosso/be
be/vendor/requests/packages/urllib3/_collections.py
HTTPHeaderDict.itermerged
def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = _dict_getitem(self, key) yield val[0], ', '.join(val[1:])
python
def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = _dict_getitem(self, key) yield val[0], ', '.join(val[1:])
[ "def", "itermerged", "(", "self", ")", ":", "for", "key", "in", "self", ":", "val", "=", "_dict_getitem", "(", "self", ",", "key", ")", "yield", "val", "[", "0", "]", ",", "', '", ".", "join", "(", "val", "[", "1", ":", "]", ")" ]
Iterate over all headers, merging duplicate ones together.
[ "Iterate", "over", "all", "headers", "merging", "duplicate", "ones", "together", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/_collections.py#L297-L301
mottosso/be
be/vendor/requests/packages/urllib3/_collections.py
HTTPHeaderDict.from_httplib
def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2 """Read headers from a Python 2 httplib message object.""" ret = cls(message.items()) # ret now contains only the last header line for each duplicate. # Importing with all duplicates would be nice, but this would # mean to repeat most of the raw parsing already done, when the # message object was created. Extracting only the headers of interest # separately, the cookies, should be faster and requires less # extra code. for key in duplicates: ret.discard(key) for val in message.getheaders(key): ret.add(key, val) return ret
python
def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2 """Read headers from a Python 2 httplib message object.""" ret = cls(message.items()) # ret now contains only the last header line for each duplicate. # Importing with all duplicates would be nice, but this would # mean to repeat most of the raw parsing already done, when the # message object was created. Extracting only the headers of interest # separately, the cookies, should be faster and requires less # extra code. for key in duplicates: ret.discard(key) for val in message.getheaders(key): ret.add(key, val) return ret
[ "def", "from_httplib", "(", "cls", ",", "message", ",", "duplicates", "=", "(", "'set-cookie'", ",", ")", ")", ":", "# Python 2", "ret", "=", "cls", "(", "message", ".", "items", "(", ")", ")", "# ret now contains only the last header line for each duplicate.", "# Importing with all duplicates would be nice, but this would", "# mean to repeat most of the raw parsing already done, when the", "# message object was created. Extracting only the headers of interest ", "# separately, the cookies, should be faster and requires less", "# extra code.", "for", "key", "in", "duplicates", ":", "ret", ".", "discard", "(", "key", ")", "for", "val", "in", "message", ".", "getheaders", "(", "key", ")", ":", "ret", ".", "add", "(", "key", ",", "val", ")", "return", "ret" ]
Read headers from a Python 2 httplib message object.
[ "Read", "headers", "from", "a", "Python", "2", "httplib", "message", "object", "." ]
train
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/_collections.py#L307-L320