id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
239,700
kaniblu/pydumper
dumper/__init__.py
load
def load(name, path=None, ext="dat", silent=False): """ Loads an object from file with given name and extension. Optionally the path can be specified as well. """ filename = __get_filename(path, name, ext) if not os.path.exists(filename): if not silent: raise ValueException("Specified input filename doesn't exist.") return None with open(filename, "rb") as f: return pickle.load(f)
python
def load(name, path=None, ext="dat", silent=False): """ Loads an object from file with given name and extension. Optionally the path can be specified as well. """ filename = __get_filename(path, name, ext) if not os.path.exists(filename): if not silent: raise ValueException("Specified input filename doesn't exist.") return None with open(filename, "rb") as f: return pickle.load(f)
[ "def", "load", "(", "name", ",", "path", "=", "None", ",", "ext", "=", "\"dat\"", ",", "silent", "=", "False", ")", ":", "filename", "=", "__get_filename", "(", "path", ",", "name", ",", "ext", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "if", "not", "silent", ":", "raise", "ValueException", "(", "\"Specified input filename doesn't exist.\"", ")", "return", "None", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "f", ":", "return", "pickle", ".", "load", "(", "f", ")" ]
Loads an object from file with given name and extension. Optionally the path can be specified as well.
[ "Loads", "an", "object", "from", "file", "with", "given", "name", "and", "extension", ".", "Optionally", "the", "path", "can", "be", "specified", "as", "well", "." ]
ce61b96b09604b52d4bab667ac1862755ca21f3b
https://github.com/kaniblu/pydumper/blob/ce61b96b09604b52d4bab667ac1862755ca21f3b/dumper/__init__.py#L33-L46
239,701
bufferapp/pipub
pipub/cli.py
standard_input
def standard_input(): """Generator that yields lines from standard input.""" with click.get_text_stream("stdin") as stdin: while stdin.readable(): line = stdin.readline() if line: yield line.strip().encode("utf-8")
python
def standard_input(): """Generator that yields lines from standard input.""" with click.get_text_stream("stdin") as stdin: while stdin.readable(): line = stdin.readline() if line: yield line.strip().encode("utf-8")
[ "def", "standard_input", "(", ")", ":", "with", "click", ".", "get_text_stream", "(", "\"stdin\"", ")", "as", "stdin", ":", "while", "stdin", ".", "readable", "(", ")", ":", "line", "=", "stdin", ".", "readline", "(", ")", "if", "line", ":", "yield", "line", ".", "strip", "(", ")", ".", "encode", "(", "\"utf-8\"", ")" ]
Generator that yields lines from standard input.
[ "Generator", "that", "yields", "lines", "from", "standard", "input", "." ]
1270b2cc3b72ddbe57874757dcf5537d3d36e189
https://github.com/bufferapp/pipub/blob/1270b2cc3b72ddbe57874757dcf5537d3d36e189/pipub/cli.py#L6-L12
239,702
rtluckie/seria
seria/cli.py
cli
def cli(out_fmt, input, output): """Converts text.""" _input = StringIO() for l in input: try: _input.write(str(l)) except TypeError: _input.write(bytes(l, 'utf-8')) _input = seria.load(_input) _out = (_input.dump(out_fmt)) output.write(_out)
python
def cli(out_fmt, input, output): """Converts text.""" _input = StringIO() for l in input: try: _input.write(str(l)) except TypeError: _input.write(bytes(l, 'utf-8')) _input = seria.load(_input) _out = (_input.dump(out_fmt)) output.write(_out)
[ "def", "cli", "(", "out_fmt", ",", "input", ",", "output", ")", ":", "_input", "=", "StringIO", "(", ")", "for", "l", "in", "input", ":", "try", ":", "_input", ".", "write", "(", "str", "(", "l", ")", ")", "except", "TypeError", ":", "_input", ".", "write", "(", "bytes", "(", "l", ",", "'utf-8'", ")", ")", "_input", "=", "seria", ".", "load", "(", "_input", ")", "_out", "=", "(", "_input", ".", "dump", "(", "out_fmt", ")", ")", "output", ".", "write", "(", "_out", ")" ]
Converts text.
[ "Converts", "text", "." ]
8ae4f71237e69085d8f974a024720f45b34ab963
https://github.com/rtluckie/seria/blob/8ae4f71237e69085d8f974a024720f45b34ab963/seria/cli.py#L23-L33
239,703
jespino/anillo
anillo/utils/multipart.py
MultipartPart.value
def value(self): ''' Data decoded with the specified charset ''' pos = self.file.tell() self.file.seek(0) val = self.file.read() self.file.seek(pos) return val.decode(self.charset)
python
def value(self): ''' Data decoded with the specified charset ''' pos = self.file.tell() self.file.seek(0) val = self.file.read() self.file.seek(pos) return val.decode(self.charset)
[ "def", "value", "(", "self", ")", ":", "pos", "=", "self", ".", "file", ".", "tell", "(", ")", "self", ".", "file", ".", "seek", "(", "0", ")", "val", "=", "self", ".", "file", ".", "read", "(", ")", "self", ".", "file", ".", "seek", "(", "pos", ")", "return", "val", ".", "decode", "(", "self", ".", "charset", ")" ]
Data decoded with the specified charset
[ "Data", "decoded", "with", "the", "specified", "charset" ]
901a84fd2b4fa909bc06e8bd76090457990576a7
https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/utils/multipart.py#L358-L364
239,704
perimosocordiae/viztricks
viztricks/shims.py
_violinplot
def _violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False, showextrema=True, showmedians=False, points=100, bw_method=None, ax=None): '''Local version of the matplotlib violinplot.''' if ax is None: ax = plt.gca() if positions is None: positions = np.arange(1, len(dataset)+1) amp = widths / 2.0 result = dict(bodies=[], means=[], mins=[], maxes=[], bars=[], medians=[]) for pos, d in zip(positions, dataset): result['bodies'].append(_violin(d, pos, amp, ax=ax)) x0 = pos - amp/2. x1 = pos + amp/2. d_min, d_max = np.min(d), np.max(d) result['bars'].append(ax.vlines(pos, d_min, d_max)) if showmedians: m1 = np.median(d) result['medians'].append(ax.plot([x0,x1], [m1,m1], 'k-')) if showmeans: m1 = np.mean(d) result['means'].append(ax.plot([x0,x1], [m1,m1], 'k-')) if showextrema: result['mins'].append(ax.plot([x0,x1], [d_min,d_min], 'k-')) result['maxes'].append(ax.plot([x0,x1], [d_max,d_max], 'k-')) ax.set_xticks(positions) return result
python
def _violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False, showextrema=True, showmedians=False, points=100, bw_method=None, ax=None): '''Local version of the matplotlib violinplot.''' if ax is None: ax = plt.gca() if positions is None: positions = np.arange(1, len(dataset)+1) amp = widths / 2.0 result = dict(bodies=[], means=[], mins=[], maxes=[], bars=[], medians=[]) for pos, d in zip(positions, dataset): result['bodies'].append(_violin(d, pos, amp, ax=ax)) x0 = pos - amp/2. x1 = pos + amp/2. d_min, d_max = np.min(d), np.max(d) result['bars'].append(ax.vlines(pos, d_min, d_max)) if showmedians: m1 = np.median(d) result['medians'].append(ax.plot([x0,x1], [m1,m1], 'k-')) if showmeans: m1 = np.mean(d) result['means'].append(ax.plot([x0,x1], [m1,m1], 'k-')) if showextrema: result['mins'].append(ax.plot([x0,x1], [d_min,d_min], 'k-')) result['maxes'].append(ax.plot([x0,x1], [d_max,d_max], 'k-')) ax.set_xticks(positions) return result
[ "def", "_violinplot", "(", "dataset", ",", "positions", "=", "None", ",", "vert", "=", "True", ",", "widths", "=", "0.5", ",", "showmeans", "=", "False", ",", "showextrema", "=", "True", ",", "showmedians", "=", "False", ",", "points", "=", "100", ",", "bw_method", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "if", "positions", "is", "None", ":", "positions", "=", "np", ".", "arange", "(", "1", ",", "len", "(", "dataset", ")", "+", "1", ")", "amp", "=", "widths", "/", "2.0", "result", "=", "dict", "(", "bodies", "=", "[", "]", ",", "means", "=", "[", "]", ",", "mins", "=", "[", "]", ",", "maxes", "=", "[", "]", ",", "bars", "=", "[", "]", ",", "medians", "=", "[", "]", ")", "for", "pos", ",", "d", "in", "zip", "(", "positions", ",", "dataset", ")", ":", "result", "[", "'bodies'", "]", ".", "append", "(", "_violin", "(", "d", ",", "pos", ",", "amp", ",", "ax", "=", "ax", ")", ")", "x0", "=", "pos", "-", "amp", "/", "2.", "x1", "=", "pos", "+", "amp", "/", "2.", "d_min", ",", "d_max", "=", "np", ".", "min", "(", "d", ")", ",", "np", ".", "max", "(", "d", ")", "result", "[", "'bars'", "]", ".", "append", "(", "ax", ".", "vlines", "(", "pos", ",", "d_min", ",", "d_max", ")", ")", "if", "showmedians", ":", "m1", "=", "np", ".", "median", "(", "d", ")", "result", "[", "'medians'", "]", ".", "append", "(", "ax", ".", "plot", "(", "[", "x0", ",", "x1", "]", ",", "[", "m1", ",", "m1", "]", ",", "'k-'", ")", ")", "if", "showmeans", ":", "m1", "=", "np", ".", "mean", "(", "d", ")", "result", "[", "'means'", "]", ".", "append", "(", "ax", ".", "plot", "(", "[", "x0", ",", "x1", "]", ",", "[", "m1", ",", "m1", "]", ",", "'k-'", ")", ")", "if", "showextrema", ":", "result", "[", "'mins'", "]", ".", "append", "(", "ax", ".", "plot", "(", "[", "x0", ",", "x1", "]", ",", "[", "d_min", ",", "d_min", "]", ",", "'k-'", ")", ")", "result", "[", "'maxes'", "]", ".", "append", "(", "ax", ".", "plot", "(", "[", "x0", ",", "x1", "]", ",", "[", "d_max", ",", "d_max", "]", ",", "'k-'", ")", ")", "ax", ".", "set_xticks", "(", "positions", ")", "return", "result" ]
Local version of the matplotlib violinplot.
[ "Local", "version", "of", "the", "matplotlib", "violinplot", "." ]
bae2f8a9ce9278ce0197f8efc34cc4fef1dfe1eb
https://github.com/perimosocordiae/viztricks/blob/bae2f8a9ce9278ce0197f8efc34cc4fef1dfe1eb/viztricks/shims.py#L25-L51
239,705
mbr/volatile
volatile/__init__.py
dir
def dir(suffix='', prefix='tmp', dir=None, force=True): """Create a temporary directory. A contextmanager that creates and returns a temporary directory, cleaning it up on exit. The force option specifies whether or not the directory is removed recursively. If set to `False` (the default is `True`), only an empty temporary directory will be removed. This is helpful to create temporary directories for things like mountpoints; otherwise a failing unmount would result in all files on the mounted volume to be deleted. :param suffix: Passed on to :func:`tempfile.mkdtemp`. :param prefix: Passed on to :func:`tempfile.mkdtemp`. :param dir: Passed on to :func:`tempfile.mkdtemp`. :param force: If true, recursively removes directory, otherwise just removes if empty. If directory isn't empty and `force` is `False`, :class:`OSError` is raised. :return: Path to the newly created temporary directory. """ name = tempfile.mkdtemp(suffix, prefix, dir) try: yield name finally: try: if force: shutil.rmtree(name) else: os.rmdir(name) except OSError as e: if e.errno != 2: # not found raise
python
def dir(suffix='', prefix='tmp', dir=None, force=True): """Create a temporary directory. A contextmanager that creates and returns a temporary directory, cleaning it up on exit. The force option specifies whether or not the directory is removed recursively. If set to `False` (the default is `True`), only an empty temporary directory will be removed. This is helpful to create temporary directories for things like mountpoints; otherwise a failing unmount would result in all files on the mounted volume to be deleted. :param suffix: Passed on to :func:`tempfile.mkdtemp`. :param prefix: Passed on to :func:`tempfile.mkdtemp`. :param dir: Passed on to :func:`tempfile.mkdtemp`. :param force: If true, recursively removes directory, otherwise just removes if empty. If directory isn't empty and `force` is `False`, :class:`OSError` is raised. :return: Path to the newly created temporary directory. """ name = tempfile.mkdtemp(suffix, prefix, dir) try: yield name finally: try: if force: shutil.rmtree(name) else: os.rmdir(name) except OSError as e: if e.errno != 2: # not found raise
[ "def", "dir", "(", "suffix", "=", "''", ",", "prefix", "=", "'tmp'", ",", "dir", "=", "None", ",", "force", "=", "True", ")", ":", "name", "=", "tempfile", ".", "mkdtemp", "(", "suffix", ",", "prefix", ",", "dir", ")", "try", ":", "yield", "name", "finally", ":", "try", ":", "if", "force", ":", "shutil", ".", "rmtree", "(", "name", ")", "else", ":", "os", ".", "rmdir", "(", "name", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "2", ":", "# not found", "raise" ]
Create a temporary directory. A contextmanager that creates and returns a temporary directory, cleaning it up on exit. The force option specifies whether or not the directory is removed recursively. If set to `False` (the default is `True`), only an empty temporary directory will be removed. This is helpful to create temporary directories for things like mountpoints; otherwise a failing unmount would result in all files on the mounted volume to be deleted. :param suffix: Passed on to :func:`tempfile.mkdtemp`. :param prefix: Passed on to :func:`tempfile.mkdtemp`. :param dir: Passed on to :func:`tempfile.mkdtemp`. :param force: If true, recursively removes directory, otherwise just removes if empty. If directory isn't empty and `force` is `False`, :class:`OSError` is raised. :return: Path to the newly created temporary directory.
[ "Create", "a", "temporary", "directory", "." ]
b526eda708e3c26b330d0f3f2a98c1f0feb8ec50
https://github.com/mbr/volatile/blob/b526eda708e3c26b330d0f3f2a98c1f0feb8ec50/volatile/__init__.py#L10-L42
239,706
mbr/volatile
volatile/__init__.py
file
def file(mode='w+b', suffix='', prefix='tmp', dir=None, ignore_missing=False): """Create a temporary file. A contextmanager that creates and returns a named temporary file and removes it on exit. Differs from temporary file functions in :mod:`tempfile` by not deleting the file once it is closed, making it safe to write and close the file and then processing it with an external program. If the temporary file is moved elsewhere later on, `ignore_missing` should be set to `True`. :param mode: Passed on to :func:`tempfile.NamedTemporaryFile`. :param suffix: Passed on to :func:`tempfile.NamedTemporaryFile`. :param prefix: Passed on to :func:`tempfile.NamedTemporaryFile`. :param dir: Passed on to :func:`tempfile.NamedTemporaryFile`. :param ignore_missing: If set to `True`, no exception will be raised if the temporary file has been deleted when trying to clean it up. :return: A file object with a `.name`. """ # note: bufsize is not supported in Python3, try to prevent problems # stemming from incorrect api usage if isinstance(suffix, int): raise ValueError('Passed an integer as suffix. Did you want to ' 'specify the deprecated parameter `bufsize`?') fp = tempfile.NamedTemporaryFile(mode=mode, suffix=suffix, prefix=prefix, dir=dir, delete=False) try: yield fp finally: try: os.unlink(fp.name) except OSError as e: # if the file does not exist anymore, ignore if e.errno != ENOENT or ignore_missing is False: raise
python
def file(mode='w+b', suffix='', prefix='tmp', dir=None, ignore_missing=False): """Create a temporary file. A contextmanager that creates and returns a named temporary file and removes it on exit. Differs from temporary file functions in :mod:`tempfile` by not deleting the file once it is closed, making it safe to write and close the file and then processing it with an external program. If the temporary file is moved elsewhere later on, `ignore_missing` should be set to `True`. :param mode: Passed on to :func:`tempfile.NamedTemporaryFile`. :param suffix: Passed on to :func:`tempfile.NamedTemporaryFile`. :param prefix: Passed on to :func:`tempfile.NamedTemporaryFile`. :param dir: Passed on to :func:`tempfile.NamedTemporaryFile`. :param ignore_missing: If set to `True`, no exception will be raised if the temporary file has been deleted when trying to clean it up. :return: A file object with a `.name`. """ # note: bufsize is not supported in Python3, try to prevent problems # stemming from incorrect api usage if isinstance(suffix, int): raise ValueError('Passed an integer as suffix. Did you want to ' 'specify the deprecated parameter `bufsize`?') fp = tempfile.NamedTemporaryFile(mode=mode, suffix=suffix, prefix=prefix, dir=dir, delete=False) try: yield fp finally: try: os.unlink(fp.name) except OSError as e: # if the file does not exist anymore, ignore if e.errno != ENOENT or ignore_missing is False: raise
[ "def", "file", "(", "mode", "=", "'w+b'", ",", "suffix", "=", "''", ",", "prefix", "=", "'tmp'", ",", "dir", "=", "None", ",", "ignore_missing", "=", "False", ")", ":", "# note: bufsize is not supported in Python3, try to prevent problems", "# stemming from incorrect api usage", "if", "isinstance", "(", "suffix", ",", "int", ")", ":", "raise", "ValueError", "(", "'Passed an integer as suffix. Did you want to '", "'specify the deprecated parameter `bufsize`?'", ")", "fp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "mode", ",", "suffix", "=", "suffix", ",", "prefix", "=", "prefix", ",", "dir", "=", "dir", ",", "delete", "=", "False", ")", "try", ":", "yield", "fp", "finally", ":", "try", ":", "os", ".", "unlink", "(", "fp", ".", "name", ")", "except", "OSError", "as", "e", ":", "# if the file does not exist anymore, ignore", "if", "e", ".", "errno", "!=", "ENOENT", "or", "ignore_missing", "is", "False", ":", "raise" ]
Create a temporary file. A contextmanager that creates and returns a named temporary file and removes it on exit. Differs from temporary file functions in :mod:`tempfile` by not deleting the file once it is closed, making it safe to write and close the file and then processing it with an external program. If the temporary file is moved elsewhere later on, `ignore_missing` should be set to `True`. :param mode: Passed on to :func:`tempfile.NamedTemporaryFile`. :param suffix: Passed on to :func:`tempfile.NamedTemporaryFile`. :param prefix: Passed on to :func:`tempfile.NamedTemporaryFile`. :param dir: Passed on to :func:`tempfile.NamedTemporaryFile`. :param ignore_missing: If set to `True`, no exception will be raised if the temporary file has been deleted when trying to clean it up. :return: A file object with a `.name`.
[ "Create", "a", "temporary", "file", "." ]
b526eda708e3c26b330d0f3f2a98c1f0feb8ec50
https://github.com/mbr/volatile/blob/b526eda708e3c26b330d0f3f2a98c1f0feb8ec50/volatile/__init__.py#L46-L86
239,707
mbr/volatile
volatile/__init__.py
unix_socket
def unix_socket(sock=None, socket_name='tmp.socket', close=True): """Create temporary unix socket. Creates and binds a temporary unix socket that will be closed and removed on exit. :param sock: If not `None`, will not created a new unix socket, but bind the passed in one instead. :param socket_name: The name for the socket file (will be placed in a temporary directory). Do not pass in an absolute path! :param close: If `False`, does not close the socket before removing the temporary directory. :return: A tuple of `(socket, addr)`, where `addr` is the location of the bound socket on the filesystem. """ sock = sock or socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) with dir() as dtmp: addr = os.path.join(dtmp, socket_name) sock.bind(addr) try: yield sock, addr finally: if close: sock.close()
python
def unix_socket(sock=None, socket_name='tmp.socket', close=True): """Create temporary unix socket. Creates and binds a temporary unix socket that will be closed and removed on exit. :param sock: If not `None`, will not created a new unix socket, but bind the passed in one instead. :param socket_name: The name for the socket file (will be placed in a temporary directory). Do not pass in an absolute path! :param close: If `False`, does not close the socket before removing the temporary directory. :return: A tuple of `(socket, addr)`, where `addr` is the location of the bound socket on the filesystem. """ sock = sock or socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) with dir() as dtmp: addr = os.path.join(dtmp, socket_name) sock.bind(addr) try: yield sock, addr finally: if close: sock.close()
[ "def", "unix_socket", "(", "sock", "=", "None", ",", "socket_name", "=", "'tmp.socket'", ",", "close", "=", "True", ")", ":", "sock", "=", "sock", "or", "socket", ".", "socket", "(", "socket", ".", "AF_UNIX", ",", "socket", ".", "SOCK_STREAM", ")", "with", "dir", "(", ")", "as", "dtmp", ":", "addr", "=", "os", ".", "path", ".", "join", "(", "dtmp", ",", "socket_name", ")", "sock", ".", "bind", "(", "addr", ")", "try", ":", "yield", "sock", ",", "addr", "finally", ":", "if", "close", ":", "sock", ".", "close", "(", ")" ]
Create temporary unix socket. Creates and binds a temporary unix socket that will be closed and removed on exit. :param sock: If not `None`, will not created a new unix socket, but bind the passed in one instead. :param socket_name: The name for the socket file (will be placed in a temporary directory). Do not pass in an absolute path! :param close: If `False`, does not close the socket before removing the temporary directory. :return: A tuple of `(socket, addr)`, where `addr` is the location of the bound socket on the filesystem.
[ "Create", "temporary", "unix", "socket", "." ]
b526eda708e3c26b330d0f3f2a98c1f0feb8ec50
https://github.com/mbr/volatile/blob/b526eda708e3c26b330d0f3f2a98c1f0feb8ec50/volatile/__init__.py#L90-L115
239,708
sbarham/dsrt
build/lib/dsrt/config/ConfigurationLoader.py
ConfigurationLoader.load_config
def load_config(self, path): '''Load a configuration file; eventually, support dicts, .yaml, .csv, etc.''' # if no path was provided, resort to defaults if path == None: print("Path to config was null; using defaults.") return if not os.path.exists(path): print("[No user config file found at default location; using defaults.]\n") return user_config = None # read in the user's configuration file (for now, we hope it's yaml) with open(path) as f: user_config = f.read() # load the user's configuration file into a Config object extension = os.path.splitext(path) if extension == 'yaml': user_config = yaml.load(user_config) else: raise Error('Configuration file type "{}" not supported'.format(extension)) # copy the user's preferences into the default configurations self.merge_config(user_config) # build the udpated configuration self.configuration = Configuration(self.data_config, self.model_config, self.conversation_config)
python
def load_config(self, path): '''Load a configuration file; eventually, support dicts, .yaml, .csv, etc.''' # if no path was provided, resort to defaults if path == None: print("Path to config was null; using defaults.") return if not os.path.exists(path): print("[No user config file found at default location; using defaults.]\n") return user_config = None # read in the user's configuration file (for now, we hope it's yaml) with open(path) as f: user_config = f.read() # load the user's configuration file into a Config object extension = os.path.splitext(path) if extension == 'yaml': user_config = yaml.load(user_config) else: raise Error('Configuration file type "{}" not supported'.format(extension)) # copy the user's preferences into the default configurations self.merge_config(user_config) # build the udpated configuration self.configuration = Configuration(self.data_config, self.model_config, self.conversation_config)
[ "def", "load_config", "(", "self", ",", "path", ")", ":", "# if no path was provided, resort to defaults", "if", "path", "==", "None", ":", "print", "(", "\"Path to config was null; using defaults.\"", ")", "return", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "print", "(", "\"[No user config file found at default location; using defaults.]\\n\"", ")", "return", "user_config", "=", "None", "# read in the user's configuration file (for now, we hope it's yaml)", "with", "open", "(", "path", ")", "as", "f", ":", "user_config", "=", "f", ".", "read", "(", ")", "# load the user's configuration file into a Config object", "extension", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "if", "extension", "==", "'yaml'", ":", "user_config", "=", "yaml", ".", "load", "(", "user_config", ")", "else", ":", "raise", "Error", "(", "'Configuration file type \"{}\" not supported'", ".", "format", "(", "extension", ")", ")", "# copy the user's preferences into the default configurations", "self", ".", "merge_config", "(", "user_config", ")", "# build the udpated configuration", "self", ".", "configuration", "=", "Configuration", "(", "self", ".", "data_config", ",", "self", ".", "model_config", ",", "self", ".", "conversation_config", ")" ]
Load a configuration file; eventually, support dicts, .yaml, .csv, etc.
[ "Load", "a", "configuration", "file", ";", "eventually", "support", "dicts", ".", "yaml", ".", "csv", "etc", "." ]
bc664739f2f52839461d3e72773b71146fd56a9a
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/config/ConfigurationLoader.py#L24-L54
239,709
sbarham/dsrt
build/lib/dsrt/config/ConfigurationLoader.py
ConfigurationLoader.merge_config
def merge_config(self, user_config): ''' Take a dictionary of user preferences and use them to update the default data, model, and conversation configurations. ''' # provisioanlly update the default configurations with the user preferences temp_data_config = copy.deepcopy(self.data_config).update(user_config) temp_model_config = copy.deepcopy(self.model_config).update(user_config) temp_conversation_config = copy.deepcopy(self.conversation_config).update(user_config) # if the new configurations validate, apply them if validate_data_config(temp_data_config): self.data_config = temp_data_config if validate_model_config(temp_model_config): self.model_config = temp_model_config if validate_conversation_config(temp_conversation_config): self.conversation_config = temp_conversation_config
python
def merge_config(self, user_config): ''' Take a dictionary of user preferences and use them to update the default data, model, and conversation configurations. ''' # provisioanlly update the default configurations with the user preferences temp_data_config = copy.deepcopy(self.data_config).update(user_config) temp_model_config = copy.deepcopy(self.model_config).update(user_config) temp_conversation_config = copy.deepcopy(self.conversation_config).update(user_config) # if the new configurations validate, apply them if validate_data_config(temp_data_config): self.data_config = temp_data_config if validate_model_config(temp_model_config): self.model_config = temp_model_config if validate_conversation_config(temp_conversation_config): self.conversation_config = temp_conversation_config
[ "def", "merge_config", "(", "self", ",", "user_config", ")", ":", "# provisioanlly update the default configurations with the user preferences", "temp_data_config", "=", "copy", ".", "deepcopy", "(", "self", ".", "data_config", ")", ".", "update", "(", "user_config", ")", "temp_model_config", "=", "copy", ".", "deepcopy", "(", "self", ".", "model_config", ")", ".", "update", "(", "user_config", ")", "temp_conversation_config", "=", "copy", ".", "deepcopy", "(", "self", ".", "conversation_config", ")", ".", "update", "(", "user_config", ")", "# if the new configurations validate, apply them", "if", "validate_data_config", "(", "temp_data_config", ")", ":", "self", ".", "data_config", "=", "temp_data_config", "if", "validate_model_config", "(", "temp_model_config", ")", ":", "self", ".", "model_config", "=", "temp_model_config", "if", "validate_conversation_config", "(", "temp_conversation_config", ")", ":", "self", ".", "conversation_config", "=", "temp_conversation_config" ]
Take a dictionary of user preferences and use them to update the default data, model, and conversation configurations.
[ "Take", "a", "dictionary", "of", "user", "preferences", "and", "use", "them", "to", "update", "the", "default", "data", "model", "and", "conversation", "configurations", "." ]
bc664739f2f52839461d3e72773b71146fd56a9a
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/config/ConfigurationLoader.py#L56-L73
239,710
hwstovall/seaplane
seaplane/utils/which.py
which
def which(program): """ A python implementation of which. https://stackoverflow.com/a/2969007 """ path_ext = [""] ext_list = None if sys.platform == "win32": ext_list = [ext.lower() for ext in os.environ["PATHEXT"].split(";")] def is_exe(fpath): exe = os.path.isfile(fpath) and os.access(fpath, os.X_OK) # search for executable under windows if not exe: if ext_list: for ext in ext_list: exe_path = f"{fpath}{ext}" if os.path.isfile(exe_path) and os.access(exe_path, os.X_OK): path_ext[0] = ext return True return False return exe fpath, fname = os.path.split(program) if fpath: if is_exe(program): return f"{program}{path_ext[0]}" else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return f"{exe_file}{path_ext[0]}" return None
python
def which(program): """ A python implementation of which. https://stackoverflow.com/a/2969007 """ path_ext = [""] ext_list = None if sys.platform == "win32": ext_list = [ext.lower() for ext in os.environ["PATHEXT"].split(";")] def is_exe(fpath): exe = os.path.isfile(fpath) and os.access(fpath, os.X_OK) # search for executable under windows if not exe: if ext_list: for ext in ext_list: exe_path = f"{fpath}{ext}" if os.path.isfile(exe_path) and os.access(exe_path, os.X_OK): path_ext[0] = ext return True return False return exe fpath, fname = os.path.split(program) if fpath: if is_exe(program): return f"{program}{path_ext[0]}" else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return f"{exe_file}{path_ext[0]}" return None
[ "def", "which", "(", "program", ")", ":", "path_ext", "=", "[", "\"\"", "]", "ext_list", "=", "None", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "ext_list", "=", "[", "ext", ".", "lower", "(", ")", "for", "ext", "in", "os", ".", "environ", "[", "\"PATHEXT\"", "]", ".", "split", "(", "\";\"", ")", "]", "def", "is_exe", "(", "fpath", ")", ":", "exe", "=", "os", ".", "path", ".", "isfile", "(", "fpath", ")", "and", "os", ".", "access", "(", "fpath", ",", "os", ".", "X_OK", ")", "# search for executable under windows", "if", "not", "exe", ":", "if", "ext_list", ":", "for", "ext", "in", "ext_list", ":", "exe_path", "=", "f\"{fpath}{ext}\"", "if", "os", ".", "path", ".", "isfile", "(", "exe_path", ")", "and", "os", ".", "access", "(", "exe_path", ",", "os", ".", "X_OK", ")", ":", "path_ext", "[", "0", "]", "=", "ext", "return", "True", "return", "False", "return", "exe", "fpath", ",", "fname", "=", "os", ".", "path", ".", "split", "(", "program", ")", "if", "fpath", ":", "if", "is_exe", "(", "program", ")", ":", "return", "f\"{program}{path_ext[0]}\"", "else", ":", "for", "path", "in", "os", ".", "environ", "[", "\"PATH\"", "]", ".", "split", "(", "os", ".", "pathsep", ")", ":", "path", "=", "path", ".", "strip", "(", "'\"'", ")", "exe_file", "=", "os", ".", "path", ".", "join", "(", "path", ",", "program", ")", "if", "is_exe", "(", "exe_file", ")", ":", "return", "f\"{exe_file}{path_ext[0]}\"", "return", "None" ]
A python implementation of which. https://stackoverflow.com/a/2969007
[ "A", "python", "implementation", "of", "which", "." ]
6acb240b51afeead692cf720e15704fd9275907c
https://github.com/hwstovall/seaplane/blob/6acb240b51afeead692cf720e15704fd9275907c/seaplane/utils/which.py#L6-L42
239,711
baguette-io/baguette-messaging
farine/connectors/sql/entrypoints.py
migrate
def migrate(module=None): """ Entrypoint to migrate the schema. For the moment only create tables. """ if not module: #Parsing parser = argparse.ArgumentParser() parser.add_argument('-s', '--service', type=str, help='Migrate the module', required=True, dest='module') args = parser.parse_args() module = args.module #1. Load settings farine.settings.load() #2. Load the module models = farine.discovery.import_models(module) #3. Get the connection db = farine.connectors.sql.setup(getattr(farine.settings, module)) #4. Create tables for model in models: model._meta.database = db model.create_table(fail_silently=True)
python
def migrate(module=None): """ Entrypoint to migrate the schema. For the moment only create tables. """ if not module: #Parsing parser = argparse.ArgumentParser() parser.add_argument('-s', '--service', type=str, help='Migrate the module', required=True, dest='module') args = parser.parse_args() module = args.module #1. Load settings farine.settings.load() #2. Load the module models = farine.discovery.import_models(module) #3. Get the connection db = farine.connectors.sql.setup(getattr(farine.settings, module)) #4. Create tables for model in models: model._meta.database = db model.create_table(fail_silently=True)
[ "def", "migrate", "(", "module", "=", "None", ")", ":", "if", "not", "module", ":", "#Parsing", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--service'", ",", "type", "=", "str", ",", "help", "=", "'Migrate the module'", ",", "required", "=", "True", ",", "dest", "=", "'module'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "module", "=", "args", ".", "module", "#1. Load settings", "farine", ".", "settings", ".", "load", "(", ")", "#2. Load the module", "models", "=", "farine", ".", "discovery", ".", "import_models", "(", "module", ")", "#3. Get the connection", "db", "=", "farine", ".", "connectors", ".", "sql", ".", "setup", "(", "getattr", "(", "farine", ".", "settings", ",", "module", ")", ")", "#4. Create tables", "for", "model", "in", "models", ":", "model", ".", "_meta", ".", "database", "=", "db", "model", ".", "create_table", "(", "fail_silently", "=", "True", ")" ]
Entrypoint to migrate the schema. For the moment only create tables.
[ "Entrypoint", "to", "migrate", "the", "schema", ".", "For", "the", "moment", "only", "create", "tables", "." ]
8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1
https://github.com/baguette-io/baguette-messaging/blob/8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1/farine/connectors/sql/entrypoints.py#L13-L34
239,712
wooga/play-deliver
playdeliver/playdeliver.py
execute
def execute(options): """execute the tool with given options.""" # Load the key in PKCS 12 format that you downloaded from the Google APIs # Console when you created your Service account. package_name = options['<package>'] source_directory = options['<output_dir>'] if options['upload'] is True: upstream = True else: upstream = False sub_tasks = {'images': options['--images'], 'listings': options['--listings'], 'inapp': options['--inapp']} if sub_tasks == {'images': False, 'listings': False, 'inapp': False}: sub_tasks = {'images': True, 'listings': True, 'inapp': True} credentials = create_credentials(credentials_file=options['--credentials'], service_email=options['--service-email'], service_key=options['--key']) command = SyncCommand( package_name, source_directory, upstream, credentials, **sub_tasks) command.execute()
python
def execute(options): """execute the tool with given options.""" # Load the key in PKCS 12 format that you downloaded from the Google APIs # Console when you created your Service account. package_name = options['<package>'] source_directory = options['<output_dir>'] if options['upload'] is True: upstream = True else: upstream = False sub_tasks = {'images': options['--images'], 'listings': options['--listings'], 'inapp': options['--inapp']} if sub_tasks == {'images': False, 'listings': False, 'inapp': False}: sub_tasks = {'images': True, 'listings': True, 'inapp': True} credentials = create_credentials(credentials_file=options['--credentials'], service_email=options['--service-email'], service_key=options['--key']) command = SyncCommand( package_name, source_directory, upstream, credentials, **sub_tasks) command.execute()
[ "def", "execute", "(", "options", ")", ":", "# Load the key in PKCS 12 format that you downloaded from the Google APIs", "# Console when you created your Service account.", "package_name", "=", "options", "[", "'<package>'", "]", "source_directory", "=", "options", "[", "'<output_dir>'", "]", "if", "options", "[", "'upload'", "]", "is", "True", ":", "upstream", "=", "True", "else", ":", "upstream", "=", "False", "sub_tasks", "=", "{", "'images'", ":", "options", "[", "'--images'", "]", ",", "'listings'", ":", "options", "[", "'--listings'", "]", ",", "'inapp'", ":", "options", "[", "'--inapp'", "]", "}", "if", "sub_tasks", "==", "{", "'images'", ":", "False", ",", "'listings'", ":", "False", ",", "'inapp'", ":", "False", "}", ":", "sub_tasks", "=", "{", "'images'", ":", "True", ",", "'listings'", ":", "True", ",", "'inapp'", ":", "True", "}", "credentials", "=", "create_credentials", "(", "credentials_file", "=", "options", "[", "'--credentials'", "]", ",", "service_email", "=", "options", "[", "'--service-email'", "]", ",", "service_key", "=", "options", "[", "'--key'", "]", ")", "command", "=", "SyncCommand", "(", "package_name", ",", "source_directory", ",", "upstream", ",", "credentials", ",", "*", "*", "sub_tasks", ")", "command", ".", "execute", "(", ")" ]
execute the tool with given options.
[ "execute", "the", "tool", "with", "given", "options", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/playdeliver.py#L20-L42
239,713
wooga/play-deliver
playdeliver/playdeliver.py
create_credentials
def create_credentials(credentials_file=None, service_email=None, service_key=None, scope='https://www.googleapis.com/auth/androidpublisher'): """ Create Google credentials object. If given credentials_file is None, try to retrieve file path from environment or look up file in homefolder. """ credentials = None if service_email is None and service_key is None: print(credentials_file) if credentials_file is None: # try load file from env key = 'PLAY_DELIVER_CREDENTIALS' if key in os.environ: credentials_file = os.environ[key] if credentials_file is None: # try to find the file in home path = os.path.expanduser('~/.playdeliver/credentials.json') if os.path.exists(path): credentials_file = path if credentials_file is not None: credentials = client.GoogleCredentials.from_stream( credentials_file) credentials = credentials.create_scoped(scope) else: sys.exit("no credentials") else: credentials = client.SignedJwtAssertionCredentials( service_email, _load_key(service_key), scope=scope) return credentials
python
def create_credentials(credentials_file=None, service_email=None, service_key=None, scope='https://www.googleapis.com/auth/androidpublisher'): """ Create Google credentials object. If given credentials_file is None, try to retrieve file path from environment or look up file in homefolder. """ credentials = None if service_email is None and service_key is None: print(credentials_file) if credentials_file is None: # try load file from env key = 'PLAY_DELIVER_CREDENTIALS' if key in os.environ: credentials_file = os.environ[key] if credentials_file is None: # try to find the file in home path = os.path.expanduser('~/.playdeliver/credentials.json') if os.path.exists(path): credentials_file = path if credentials_file is not None: credentials = client.GoogleCredentials.from_stream( credentials_file) credentials = credentials.create_scoped(scope) else: sys.exit("no credentials") else: credentials = client.SignedJwtAssertionCredentials( service_email, _load_key(service_key), scope=scope) return credentials
[ "def", "create_credentials", "(", "credentials_file", "=", "None", ",", "service_email", "=", "None", ",", "service_key", "=", "None", ",", "scope", "=", "'https://www.googleapis.com/auth/androidpublisher'", ")", ":", "credentials", "=", "None", "if", "service_email", "is", "None", "and", "service_key", "is", "None", ":", "print", "(", "credentials_file", ")", "if", "credentials_file", "is", "None", ":", "# try load file from env", "key", "=", "'PLAY_DELIVER_CREDENTIALS'", "if", "key", "in", "os", ".", "environ", ":", "credentials_file", "=", "os", ".", "environ", "[", "key", "]", "if", "credentials_file", "is", "None", ":", "# try to find the file in home", "path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.playdeliver/credentials.json'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "credentials_file", "=", "path", "if", "credentials_file", "is", "not", "None", ":", "credentials", "=", "client", ".", "GoogleCredentials", ".", "from_stream", "(", "credentials_file", ")", "credentials", "=", "credentials", ".", "create_scoped", "(", "scope", ")", "else", ":", "sys", ".", "exit", "(", "\"no credentials\"", ")", "else", ":", "credentials", "=", "client", ".", "SignedJwtAssertionCredentials", "(", "service_email", ",", "_load_key", "(", "service_key", ")", ",", "scope", "=", "scope", ")", "return", "credentials" ]
Create Google credentials object. If given credentials_file is None, try to retrieve file path from environment or look up file in homefolder.
[ "Create", "Google", "credentials", "object", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/playdeliver.py#L45-L79
239,714
roboogle/gtkmvc3
gtkmvco/gtkmvc3/support/decorators.py
good_classmethod_decorator
def good_classmethod_decorator(decorator): """This decorator makes class method decorators behave well wrt to decorated class method names, doc, etc.""" def new_decorator(cls, f): g = decorator(cls, f) g.__name__ = f.__name__ g.__doc__ = f.__doc__ g.__dict__.update(f.__dict__) return g new_decorator.__name__ = decorator.__name__ new_decorator.__doc__ = decorator.__doc__ new_decorator.__dict__.update(decorator.__dict__) return new_decorator
python
def good_classmethod_decorator(decorator): """This decorator makes class method decorators behave well wrt to decorated class method names, doc, etc.""" def new_decorator(cls, f): g = decorator(cls, f) g.__name__ = f.__name__ g.__doc__ = f.__doc__ g.__dict__.update(f.__dict__) return g new_decorator.__name__ = decorator.__name__ new_decorator.__doc__ = decorator.__doc__ new_decorator.__dict__.update(decorator.__dict__) return new_decorator
[ "def", "good_classmethod_decorator", "(", "decorator", ")", ":", "def", "new_decorator", "(", "cls", ",", "f", ")", ":", "g", "=", "decorator", "(", "cls", ",", "f", ")", "g", ".", "__name__", "=", "f", ".", "__name__", "g", ".", "__doc__", "=", "f", ".", "__doc__", "g", ".", "__dict__", ".", "update", "(", "f", ".", "__dict__", ")", "return", "g", "new_decorator", ".", "__name__", "=", "decorator", ".", "__name__", "new_decorator", ".", "__doc__", "=", "decorator", ".", "__doc__", "new_decorator", ".", "__dict__", ".", "update", "(", "decorator", ".", "__dict__", ")", "return", "new_decorator" ]
This decorator makes class method decorators behave well wrt to decorated class method names, doc, etc.
[ "This", "decorator", "makes", "class", "method", "decorators", "behave", "well", "wrt", "to", "decorated", "class", "method", "names", "doc", "etc", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/support/decorators.py#L50-L64
239,715
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/genesis/genesis.py
GenesisWin.update_descriptor_le
def update_descriptor_le(self, lineedit, tf): """Update the given line edit to show the descriptor that is stored in the index :param lineedit: the line edit to update with the descriptor :type lineedit: QLineEdit :param tf: the selected taskfileinfo :type tf: :class:`TaskFileInfo` | None :returns: None :rtype: None :raises: None """ if tf: descriptor = tf.descriptor lineedit.setText(descriptor) else: lineedit.setText("")
python
def update_descriptor_le(self, lineedit, tf): """Update the given line edit to show the descriptor that is stored in the index :param lineedit: the line edit to update with the descriptor :type lineedit: QLineEdit :param tf: the selected taskfileinfo :type tf: :class:`TaskFileInfo` | None :returns: None :rtype: None :raises: None """ if tf: descriptor = tf.descriptor lineedit.setText(descriptor) else: lineedit.setText("")
[ "def", "update_descriptor_le", "(", "self", ",", "lineedit", ",", "tf", ")", ":", "if", "tf", ":", "descriptor", "=", "tf", ".", "descriptor", "lineedit", ".", "setText", "(", "descriptor", ")", "else", ":", "lineedit", ".", "setText", "(", "\"\"", ")" ]
Update the given line edit to show the descriptor that is stored in the index :param lineedit: the line edit to update with the descriptor :type lineedit: QLineEdit :param tf: the selected taskfileinfo :type tf: :class:`TaskFileInfo` | None :returns: None :rtype: None :raises: None
[ "Update", "the", "given", "line", "edit", "to", "show", "the", "descriptor", "that", "is", "stored", "in", "the", "index" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/genesis/genesis.py#L191-L206
239,716
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/genesis/genesis.py
GenesisWin._save_tfi
def _save_tfi(self, tfi, asset=False): """Save currently open scene with the information in the given taskfile info :param tfi: taskfile info :type tfi: :class:`TaskFileInfo` :returns: None :rtype: None :raises: None """ jbfile = JB_File(tfi) self.create_dir(jbfile) tf, note = self.create_db_entry(tfi) try: js = JukeboxSignals.get() if asset: js.before_save_asset.emit(jbfile, tf) self.save_asset(jbfile, tf) js.after_save_asset.emit(jbfile, tf) else: js.before_save_shot.emit(jbfile, tf) self.save_shot(jbfile, tf) js.after_save_shot.emit(jbfile, tf) except: tf.delete() note.delete() self.statusbar.showMessage('Saving failed!') log.exception("Saving failed!") return self.browser.update_model(tfi)
python
def _save_tfi(self, tfi, asset=False): """Save currently open scene with the information in the given taskfile info :param tfi: taskfile info :type tfi: :class:`TaskFileInfo` :returns: None :rtype: None :raises: None """ jbfile = JB_File(tfi) self.create_dir(jbfile) tf, note = self.create_db_entry(tfi) try: js = JukeboxSignals.get() if asset: js.before_save_asset.emit(jbfile, tf) self.save_asset(jbfile, tf) js.after_save_asset.emit(jbfile, tf) else: js.before_save_shot.emit(jbfile, tf) self.save_shot(jbfile, tf) js.after_save_shot.emit(jbfile, tf) except: tf.delete() note.delete() self.statusbar.showMessage('Saving failed!') log.exception("Saving failed!") return self.browser.update_model(tfi)
[ "def", "_save_tfi", "(", "self", ",", "tfi", ",", "asset", "=", "False", ")", ":", "jbfile", "=", "JB_File", "(", "tfi", ")", "self", ".", "create_dir", "(", "jbfile", ")", "tf", ",", "note", "=", "self", ".", "create_db_entry", "(", "tfi", ")", "try", ":", "js", "=", "JukeboxSignals", ".", "get", "(", ")", "if", "asset", ":", "js", ".", "before_save_asset", ".", "emit", "(", "jbfile", ",", "tf", ")", "self", ".", "save_asset", "(", "jbfile", ",", "tf", ")", "js", ".", "after_save_asset", ".", "emit", "(", "jbfile", ",", "tf", ")", "else", ":", "js", ".", "before_save_shot", ".", "emit", "(", "jbfile", ",", "tf", ")", "self", ".", "save_shot", "(", "jbfile", ",", "tf", ")", "js", ".", "after_save_shot", ".", "emit", "(", "jbfile", ",", "tf", ")", "except", ":", "tf", ".", "delete", "(", ")", "note", ".", "delete", "(", ")", "self", ".", "statusbar", ".", "showMessage", "(", "'Saving failed!'", ")", "log", ".", "exception", "(", "\"Saving failed!\"", ")", "return", "self", ".", "browser", ".", "update_model", "(", "tfi", ")" ]
Save currently open scene with the information in the given taskfile info :param tfi: taskfile info :type tfi: :class:`TaskFileInfo` :returns: None :rtype: None :raises: None
[ "Save", "currently", "open", "scene", "with", "the", "information", "in", "the", "given", "taskfile", "info" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/genesis/genesis.py#L303-L333
239,717
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/genesis/genesis.py
GenesisWin.create_dir
def create_dir(self, jbfile): """Create a dir for the given dirfile and display an error message, if it fails. :param jbfile: the jb file to make the directory for :type jbfile: class:`JB_File` :returns: None :rtype: None :raises: None """ try: jbfile.create_directory() except os.error: self.statusbar.showMessage('Could not create path: %s' % jbfile.get_path())
python
def create_dir(self, jbfile): """Create a dir for the given dirfile and display an error message, if it fails. :param jbfile: the jb file to make the directory for :type jbfile: class:`JB_File` :returns: None :rtype: None :raises: None """ try: jbfile.create_directory() except os.error: self.statusbar.showMessage('Could not create path: %s' % jbfile.get_path())
[ "def", "create_dir", "(", "self", ",", "jbfile", ")", ":", "try", ":", "jbfile", ".", "create_directory", "(", ")", "except", "os", ".", "error", ":", "self", ".", "statusbar", ".", "showMessage", "(", "'Could not create path: %s'", "%", "jbfile", ".", "get_path", "(", ")", ")" ]
Create a dir for the given dirfile and display an error message, if it fails. :param jbfile: the jb file to make the directory for :type jbfile: class:`JB_File` :returns: None :rtype: None :raises: None
[ "Create", "a", "dir", "for", "the", "given", "dirfile", "and", "display", "an", "error", "message", "if", "it", "fails", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/genesis/genesis.py#L335-L347
239,718
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/genesis/genesis.py
GenesisWin.check_selection_for_save
def check_selection_for_save(self, task, releasetype, descriptor): """Emit warnings if the descriptor is None or the current file is of a different task. :param task: the selected task :type task: :class:`djadapter.models.Task` :param releasetype: the releasetype to save (probably work) :type releasetype: str :param descriptor: the descriptor :type descriptor: str :returns: True if check was successfull. :rtype: bool :raises: None """ if not descriptor: self.statusbar.showMessage("Please provide a descriptor!") return False try: jukedj.validators.alphanum_vld(descriptor) except ValidationError: self.statusbar.showMessage("Descriptor contains characters other than alphanumerical ones.") return False cur = self.get_current_file() if cur and task != cur.task: self.statusbar.showMessage("Task is different. Not supported atm!") return False elif cur and releasetype != cur.releasetype: self.statusbar.showMessage("Releasetype is different. Not supported atm!") return False return True
python
def check_selection_for_save(self, task, releasetype, descriptor): """Emit warnings if the descriptor is None or the current file is of a different task. :param task: the selected task :type task: :class:`djadapter.models.Task` :param releasetype: the releasetype to save (probably work) :type releasetype: str :param descriptor: the descriptor :type descriptor: str :returns: True if check was successfull. :rtype: bool :raises: None """ if not descriptor: self.statusbar.showMessage("Please provide a descriptor!") return False try: jukedj.validators.alphanum_vld(descriptor) except ValidationError: self.statusbar.showMessage("Descriptor contains characters other than alphanumerical ones.") return False cur = self.get_current_file() if cur and task != cur.task: self.statusbar.showMessage("Task is different. Not supported atm!") return False elif cur and releasetype != cur.releasetype: self.statusbar.showMessage("Releasetype is different. Not supported atm!") return False return True
[ "def", "check_selection_for_save", "(", "self", ",", "task", ",", "releasetype", ",", "descriptor", ")", ":", "if", "not", "descriptor", ":", "self", ".", "statusbar", ".", "showMessage", "(", "\"Please provide a descriptor!\"", ")", "return", "False", "try", ":", "jukedj", ".", "validators", ".", "alphanum_vld", "(", "descriptor", ")", "except", "ValidationError", ":", "self", ".", "statusbar", ".", "showMessage", "(", "\"Descriptor contains characters other than alphanumerical ones.\"", ")", "return", "False", "cur", "=", "self", ".", "get_current_file", "(", ")", "if", "cur", "and", "task", "!=", "cur", ".", "task", ":", "self", ".", "statusbar", ".", "showMessage", "(", "\"Task is different. Not supported atm!\"", ")", "return", "False", "elif", "cur", "and", "releasetype", "!=", "cur", ".", "releasetype", ":", "self", ".", "statusbar", ".", "showMessage", "(", "\"Releasetype is different. Not supported atm!\"", ")", "return", "False", "return", "True" ]
Emit warnings if the descriptor is None or the current file is of a different task. :param task: the selected task :type task: :class:`djadapter.models.Task` :param releasetype: the releasetype to save (probably work) :type releasetype: str :param descriptor: the descriptor :type descriptor: str :returns: True if check was successfull. :rtype: bool :raises: None
[ "Emit", "warnings", "if", "the", "descriptor", "is", "None", "or", "the", "current", "file", "is", "of", "a", "different", "task", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/genesis/genesis.py#L414-L443
239,719
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/genesis/genesis.py
GenesisWin.create_db_entry
def create_db_entry(self, tfi): """Create a db entry for the given task file info :param tfi: the info for a TaskFile entry in the db :type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: the created taskfile and note :rtype: tuple :raises: ValidationError """ if tfi.task.department.assetflag: comment = self.asset_comment_pte.toPlainText() else: comment = self.shot_comment_pte.toPlainText() return tfi.create_db_entry(comment)
python
def create_db_entry(self, tfi): """Create a db entry for the given task file info :param tfi: the info for a TaskFile entry in the db :type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: the created taskfile and note :rtype: tuple :raises: ValidationError """ if tfi.task.department.assetflag: comment = self.asset_comment_pte.toPlainText() else: comment = self.shot_comment_pte.toPlainText() return tfi.create_db_entry(comment)
[ "def", "create_db_entry", "(", "self", ",", "tfi", ")", ":", "if", "tfi", ".", "task", ".", "department", ".", "assetflag", ":", "comment", "=", "self", ".", "asset_comment_pte", ".", "toPlainText", "(", ")", "else", ":", "comment", "=", "self", ".", "shot_comment_pte", ".", "toPlainText", "(", ")", "return", "tfi", ".", "create_db_entry", "(", "comment", ")" ]
Create a db entry for the given task file info :param tfi: the info for a TaskFile entry in the db :type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: the created taskfile and note :rtype: tuple :raises: ValidationError
[ "Create", "a", "db", "entry", "for", "the", "given", "task", "file", "info" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/genesis/genesis.py#L445-L458
239,720
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/genesis/genesis.py
GenesisWin.closeEvent
def closeEvent(self, event): """Send last file signal on close event :param event: The close event :type event: :returns: None :rtype: None :raises: None """ lf = self.browser.get_current_selection() if lf: self.last_file.emit(lf) return super(GenesisWin, self).close()
python
def closeEvent(self, event): """Send last file signal on close event :param event: The close event :type event: :returns: None :rtype: None :raises: None """ lf = self.browser.get_current_selection() if lf: self.last_file.emit(lf) return super(GenesisWin, self).close()
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "lf", "=", "self", ".", "browser", ".", "get_current_selection", "(", ")", "if", "lf", ":", "self", ".", "last_file", ".", "emit", "(", "lf", ")", "return", "super", "(", "GenesisWin", ",", "self", ")", ".", "close", "(", ")" ]
Send last file signal on close event :param event: The close event :type event: :returns: None :rtype: None :raises: None
[ "Send", "last", "file", "signal", "on", "close", "event" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/genesis/genesis.py#L460-L472
239,721
wooga/play-deliver
playdeliver/listing.py
upload
def upload(client, source_dir): """Upload listing files in source_dir. folder herachy.""" print('') print('upload store listings') print('---------------------') listings_folder = os.path.join(source_dir, 'listings') langfolders = filter(os.path.isdir, list_dir_abspath(listings_folder)) for language_dir in langfolders: language = os.path.basename(language_dir) with open(os.path.join(language_dir, 'listing.json')) as listings_file: listing = json.load(listings_file) listing_response = client.update( 'listings', language=language, body=listing) print(' Listing for language %s was updated.' % listing_response['language'])
python
def upload(client, source_dir): """Upload listing files in source_dir. folder herachy.""" print('') print('upload store listings') print('---------------------') listings_folder = os.path.join(source_dir, 'listings') langfolders = filter(os.path.isdir, list_dir_abspath(listings_folder)) for language_dir in langfolders: language = os.path.basename(language_dir) with open(os.path.join(language_dir, 'listing.json')) as listings_file: listing = json.load(listings_file) listing_response = client.update( 'listings', language=language, body=listing) print(' Listing for language %s was updated.' % listing_response['language'])
[ "def", "upload", "(", "client", ",", "source_dir", ")", ":", "print", "(", "''", ")", "print", "(", "'upload store listings'", ")", "print", "(", "'---------------------'", ")", "listings_folder", "=", "os", ".", "path", ".", "join", "(", "source_dir", ",", "'listings'", ")", "langfolders", "=", "filter", "(", "os", ".", "path", ".", "isdir", ",", "list_dir_abspath", "(", "listings_folder", ")", ")", "for", "language_dir", "in", "langfolders", ":", "language", "=", "os", ".", "path", ".", "basename", "(", "language_dir", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "language_dir", ",", "'listing.json'", ")", ")", "as", "listings_file", ":", "listing", "=", "json", ".", "load", "(", "listings_file", ")", "listing_response", "=", "client", ".", "update", "(", "'listings'", ",", "language", "=", "language", ",", "body", "=", "listing", ")", "print", "(", "' Listing for language %s was updated.'", "%", "listing_response", "[", "'language'", "]", ")" ]
Upload listing files in source_dir. folder herachy.
[ "Upload", "listing", "files", "in", "source_dir", ".", "folder", "herachy", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/listing.py#L8-L24
239,722
wooga/play-deliver
playdeliver/listing.py
download
def download(client, target_dir): """Download listing files from play and saves them into folder herachy.""" print('') print('download store listings') print('---------------------') listings = client.list('listings') for listing in listings: path = os.path.join(target_dir, 'listings', listing['language']) mkdir_p(path) with open(os.path.join(path, 'listing.json'), 'w') as outfile: print("save listing for {0}".format(listing['language'])) json.dump( listing, outfile, sort_keys=True, indent=4, separators=(',', ': '))
python
def download(client, target_dir): """Download listing files from play and saves them into folder herachy.""" print('') print('download store listings') print('---------------------') listings = client.list('listings') for listing in listings: path = os.path.join(target_dir, 'listings', listing['language']) mkdir_p(path) with open(os.path.join(path, 'listing.json'), 'w') as outfile: print("save listing for {0}".format(listing['language'])) json.dump( listing, outfile, sort_keys=True, indent=4, separators=(',', ': '))
[ "def", "download", "(", "client", ",", "target_dir", ")", ":", "print", "(", "''", ")", "print", "(", "'download store listings'", ")", "print", "(", "'---------------------'", ")", "listings", "=", "client", ".", "list", "(", "'listings'", ")", "for", "listing", "in", "listings", ":", "path", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "'listings'", ",", "listing", "[", "'language'", "]", ")", "mkdir_p", "(", "path", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'listing.json'", ")", ",", "'w'", ")", "as", "outfile", ":", "print", "(", "\"save listing for {0}\"", ".", "format", "(", "listing", "[", "'language'", "]", ")", ")", "json", ".", "dump", "(", "listing", ",", "outfile", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
Download listing files from play and saves them into folder herachy.
[ "Download", "listing", "files", "from", "play", "and", "saves", "them", "into", "folder", "herachy", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/listing.py#L27-L40
239,723
twneale/hercules
hercules/dict.py
DictFilterMixin.filter
def filter(self, **kwargs): '''Assumes all the dict's items are hashable. ''' # So we don't return anything more than once. yielded = set() dunder = '__' filter_items = set() for k, v in kwargs.items(): if dunder in k: k, op = k.split(dunder) try: handler = getattr(self, 'handle__%s' % op) except AttributeError: msg = '%s has no %r method to handle operator %r.' raise NonExistentHandler(msg % (self, handler, op)) for dicty in self: if handler(k, v, dicty): dicty_id = id(dicty) if dicty_id not in yielded: yield dicty yielded.add(dicty_id) else: filter_items.add((k, v)) for dicty in self: dicty_items = set(dicty.items()) if filter_items.issubset(dicty_items): yield dicty
python
def filter(self, **kwargs): '''Assumes all the dict's items are hashable. ''' # So we don't return anything more than once. yielded = set() dunder = '__' filter_items = set() for k, v in kwargs.items(): if dunder in k: k, op = k.split(dunder) try: handler = getattr(self, 'handle__%s' % op) except AttributeError: msg = '%s has no %r method to handle operator %r.' raise NonExistentHandler(msg % (self, handler, op)) for dicty in self: if handler(k, v, dicty): dicty_id = id(dicty) if dicty_id not in yielded: yield dicty yielded.add(dicty_id) else: filter_items.add((k, v)) for dicty in self: dicty_items = set(dicty.items()) if filter_items.issubset(dicty_items): yield dicty
[ "def", "filter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# So we don't return anything more than once.", "yielded", "=", "set", "(", ")", "dunder", "=", "'__'", "filter_items", "=", "set", "(", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "dunder", "in", "k", ":", "k", ",", "op", "=", "k", ".", "split", "(", "dunder", ")", "try", ":", "handler", "=", "getattr", "(", "self", ",", "'handle__%s'", "%", "op", ")", "except", "AttributeError", ":", "msg", "=", "'%s has no %r method to handle operator %r.'", "raise", "NonExistentHandler", "(", "msg", "%", "(", "self", ",", "handler", ",", "op", ")", ")", "for", "dicty", "in", "self", ":", "if", "handler", "(", "k", ",", "v", ",", "dicty", ")", ":", "dicty_id", "=", "id", "(", "dicty", ")", "if", "dicty_id", "not", "in", "yielded", ":", "yield", "dicty", "yielded", ".", "add", "(", "dicty_id", ")", "else", ":", "filter_items", ".", "add", "(", "(", "k", ",", "v", ")", ")", "for", "dicty", "in", "self", ":", "dicty_items", "=", "set", "(", "dicty", ".", "items", "(", ")", ")", "if", "filter_items", ".", "issubset", "(", "dicty_items", ")", ":", "yield", "dicty" ]
Assumes all the dict's items are hashable.
[ "Assumes", "all", "the", "dict", "s", "items", "are", "hashable", "." ]
cd61582ef7e593093e9b28b56798df4203d1467a
https://github.com/twneale/hercules/blob/cd61582ef7e593093e9b28b56798df4203d1467a/hercules/dict.py#L53-L81
239,724
samuel-phan/mssh-copy-id
msshcopyid/cli.py
Main.copy_ssh_keys_to_hosts
def copy_ssh_keys_to_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False): """ Copy the SSH keys to the given hosts. :param hosts: the list of `Host` objects to copy the SSH keys to. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run. :raise msshcopyid.errors.CopySSHKeysError: """ exceptions = [] # list of `CopySSHKeyError` for host in hosts: logger.info('[%s] Copy the SSH public key [%s]...', host.hostname, self.sshcopyid.pub_key) if not dry: try: self.copy_ssh_keys_to_host(host, known_hosts=known_hosts) except (paramiko.ssh_exception.SSHException, socket.error) as ex: logger.error(format_error(format_exception(ex))) logger.debug(traceback.format_exc()) exceptions.append(CopySSHKeyError(host=host, exception=ex)) if exceptions: raise CopySSHKeysError(exceptions=exceptions)
python
def copy_ssh_keys_to_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False): """ Copy the SSH keys to the given hosts. :param hosts: the list of `Host` objects to copy the SSH keys to. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run. :raise msshcopyid.errors.CopySSHKeysError: """ exceptions = [] # list of `CopySSHKeyError` for host in hosts: logger.info('[%s] Copy the SSH public key [%s]...', host.hostname, self.sshcopyid.pub_key) if not dry: try: self.copy_ssh_keys_to_host(host, known_hosts=known_hosts) except (paramiko.ssh_exception.SSHException, socket.error) as ex: logger.error(format_error(format_exception(ex))) logger.debug(traceback.format_exc()) exceptions.append(CopySSHKeyError(host=host, exception=ex)) if exceptions: raise CopySSHKeysError(exceptions=exceptions)
[ "def", "copy_ssh_keys_to_hosts", "(", "self", ",", "hosts", ",", "known_hosts", "=", "DEFAULT_KNOWN_HOSTS", ",", "dry", "=", "False", ")", ":", "exceptions", "=", "[", "]", "# list of `CopySSHKeyError`", "for", "host", "in", "hosts", ":", "logger", ".", "info", "(", "'[%s] Copy the SSH public key [%s]...'", ",", "host", ".", "hostname", ",", "self", ".", "sshcopyid", ".", "pub_key", ")", "if", "not", "dry", ":", "try", ":", "self", ".", "copy_ssh_keys_to_host", "(", "host", ",", "known_hosts", "=", "known_hosts", ")", "except", "(", "paramiko", ".", "ssh_exception", ".", "SSHException", ",", "socket", ".", "error", ")", "as", "ex", ":", "logger", ".", "error", "(", "format_error", "(", "format_exception", "(", "ex", ")", ")", ")", "logger", ".", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "exceptions", ".", "append", "(", "CopySSHKeyError", "(", "host", "=", "host", ",", "exception", "=", "ex", ")", ")", "if", "exceptions", ":", "raise", "CopySSHKeysError", "(", "exceptions", "=", "exceptions", ")" ]
Copy the SSH keys to the given hosts. :param hosts: the list of `Host` objects to copy the SSH keys to. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run. :raise msshcopyid.errors.CopySSHKeysError:
[ "Copy", "the", "SSH", "keys", "to", "the", "given", "hosts", "." ]
59c50eabb74c4e0eeb729266df57c285e6661b0b
https://github.com/samuel-phan/mssh-copy-id/blob/59c50eabb74c4e0eeb729266df57c285e6661b0b/msshcopyid/cli.py#L175-L196
239,725
laco/python-hexconnector
hexconnector/connector.py
HexConnector.call_fn
def call_fn(self, what, *args, **kwargs): """ Lazy call init_adapter then call the function """ logger.debug('f_{0}:{1}{2}({3})'.format( self.call_stack_level, ' ' * 4 * self.call_stack_level, what, arguments_as_string(args, kwargs))) port, fn_name = self._what(what) if port not in self['_initialized_ports']: self._call_fn(port, 'init_adapter') self['_initialized_ports'].append(port) return self._call_fn(port, fn_name, *args, **kwargs)
python
def call_fn(self, what, *args, **kwargs): """ Lazy call init_adapter then call the function """ logger.debug('f_{0}:{1}{2}({3})'.format( self.call_stack_level, ' ' * 4 * self.call_stack_level, what, arguments_as_string(args, kwargs))) port, fn_name = self._what(what) if port not in self['_initialized_ports']: self._call_fn(port, 'init_adapter') self['_initialized_ports'].append(port) return self._call_fn(port, fn_name, *args, **kwargs)
[ "def", "call_fn", "(", "self", ",", "what", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'f_{0}:{1}{2}({3})'", ".", "format", "(", "self", ".", "call_stack_level", ",", "' '", "*", "4", "*", "self", ".", "call_stack_level", ",", "what", ",", "arguments_as_string", "(", "args", ",", "kwargs", ")", ")", ")", "port", ",", "fn_name", "=", "self", ".", "_what", "(", "what", ")", "if", "port", "not", "in", "self", "[", "'_initialized_ports'", "]", ":", "self", ".", "_call_fn", "(", "port", ",", "'init_adapter'", ")", "self", "[", "'_initialized_ports'", "]", ".", "append", "(", "port", ")", "return", "self", ".", "_call_fn", "(", "port", ",", "fn_name", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Lazy call init_adapter then call the function
[ "Lazy", "call", "init_adapter", "then", "call", "the", "function" ]
99d7bc7a768252e9622c5dc6b1518fc91e08561b
https://github.com/laco/python-hexconnector/blob/99d7bc7a768252e9622c5dc6b1518fc91e08561b/hexconnector/connector.py#L62-L73
239,726
demosdemon/format-pipfile
ci/appveyor-download.py
unpack_zipfile
def unpack_zipfile(filename): """Unpack a zipfile, using the names in the zip.""" with open(filename, "rb") as fzip: z = zipfile.ZipFile(fzip) for name in z.namelist(): print((" extracting {}".format(name))) ensure_dirs(name) z.extract(name)
python
def unpack_zipfile(filename): """Unpack a zipfile, using the names in the zip.""" with open(filename, "rb") as fzip: z = zipfile.ZipFile(fzip) for name in z.namelist(): print((" extracting {}".format(name))) ensure_dirs(name) z.extract(name)
[ "def", "unpack_zipfile", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "fzip", ":", "z", "=", "zipfile", ".", "ZipFile", "(", "fzip", ")", "for", "name", "in", "z", ".", "namelist", "(", ")", ":", "print", "(", "(", "\" extracting {}\"", ".", "format", "(", "name", ")", ")", ")", "ensure_dirs", "(", "name", ")", "z", ".", "extract", "(", "name", ")" ]
Unpack a zipfile, using the names in the zip.
[ "Unpack", "a", "zipfile", "using", "the", "names", "in", "the", "zip", "." ]
f95162c49d8fc13153080ddb11ac5a5dcd4d2e7c
https://github.com/demosdemon/format-pipfile/blob/f95162c49d8fc13153080ddb11ac5a5dcd4d2e7c/ci/appveyor-download.py#L95-L102
239,727
cyrus-/cypy
cypy/__init__.py
prog_iter
def prog_iter(bounded_iterable, delta=0.01, line_size=50): '''Wraps the provided sequence with an iterator that tracks its progress on the console. >>> for i in prog_iter(xrange(100)): pass .................................................. .................................................. (0.000331163406372 s) More specifically, the behavior is as follows: - Produces a progress bar on stdout, at ``delta`` increments, where ``delta`` is a percentage (represented as a float from 0.0 to 1.0) - Newline every line_size dots (defaults to 50) - Displays the time the loop took, as in toc() (without interfering with toc) - A prog_iter nested in another prog_iter will not produce any of these side effects. That is, only one progress bar will ever be printing at a time. ''' # TODO: Technically, this should have a __len__. global _prog_iterin_loop if not _prog_iterin_loop: startTime = _time.time() _prog_iterin_loop = True length = float(len(bounded_iterable)) _sys.stdout.write(".") dots = 1 next = delta for i, item in enumerate(bounded_iterable): if (i + 1) / length >= next: next += delta dots += 1 _sys.stdout.write(".") if dots % line_size == 0: _sys.stdout.write("\n") _sys.stdout.flush() yield item print((" (" + str(_time.time() - startTime) + " s)")) _prog_iterin_loop = False else: for item in bounded_iterable: yield item
python
def prog_iter(bounded_iterable, delta=0.01, line_size=50): '''Wraps the provided sequence with an iterator that tracks its progress on the console. >>> for i in prog_iter(xrange(100)): pass .................................................. .................................................. (0.000331163406372 s) More specifically, the behavior is as follows: - Produces a progress bar on stdout, at ``delta`` increments, where ``delta`` is a percentage (represented as a float from 0.0 to 1.0) - Newline every line_size dots (defaults to 50) - Displays the time the loop took, as in toc() (without interfering with toc) - A prog_iter nested in another prog_iter will not produce any of these side effects. That is, only one progress bar will ever be printing at a time. ''' # TODO: Technically, this should have a __len__. global _prog_iterin_loop if not _prog_iterin_loop: startTime = _time.time() _prog_iterin_loop = True length = float(len(bounded_iterable)) _sys.stdout.write(".") dots = 1 next = delta for i, item in enumerate(bounded_iterable): if (i + 1) / length >= next: next += delta dots += 1 _sys.stdout.write(".") if dots % line_size == 0: _sys.stdout.write("\n") _sys.stdout.flush() yield item print((" (" + str(_time.time() - startTime) + " s)")) _prog_iterin_loop = False else: for item in bounded_iterable: yield item
[ "def", "prog_iter", "(", "bounded_iterable", ",", "delta", "=", "0.01", ",", "line_size", "=", "50", ")", ":", "# TODO: Technically, this should have a __len__.", "global", "_prog_iterin_loop", "if", "not", "_prog_iterin_loop", ":", "startTime", "=", "_time", ".", "time", "(", ")", "_prog_iterin_loop", "=", "True", "length", "=", "float", "(", "len", "(", "bounded_iterable", ")", ")", "_sys", ".", "stdout", ".", "write", "(", "\".\"", ")", "dots", "=", "1", "next", "=", "delta", "for", "i", ",", "item", "in", "enumerate", "(", "bounded_iterable", ")", ":", "if", "(", "i", "+", "1", ")", "/", "length", ">=", "next", ":", "next", "+=", "delta", "dots", "+=", "1", "_sys", ".", "stdout", ".", "write", "(", "\".\"", ")", "if", "dots", "%", "line_size", "==", "0", ":", "_sys", ".", "stdout", ".", "write", "(", "\"\\n\"", ")", "_sys", ".", "stdout", ".", "flush", "(", ")", "yield", "item", "print", "(", "(", "\" (\"", "+", "str", "(", "_time", ".", "time", "(", ")", "-", "startTime", ")", "+", "\" s)\"", ")", ")", "_prog_iterin_loop", "=", "False", "else", ":", "for", "item", "in", "bounded_iterable", ":", "yield", "item" ]
Wraps the provided sequence with an iterator that tracks its progress on the console. >>> for i in prog_iter(xrange(100)): pass .................................................. .................................................. (0.000331163406372 s) More specifically, the behavior is as follows: - Produces a progress bar on stdout, at ``delta`` increments, where ``delta`` is a percentage (represented as a float from 0.0 to 1.0) - Newline every line_size dots (defaults to 50) - Displays the time the loop took, as in toc() (without interfering with toc) - A prog_iter nested in another prog_iter will not produce any of these side effects. That is, only one progress bar will ever be printing at a time.
[ "Wraps", "the", "provided", "sequence", "with", "an", "iterator", "that", "tracks", "its", "progress", "on", "the", "console", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L210-L252
239,728
cyrus-/cypy
cypy/__init__.py
include
def include(gset, elem, value=True): """Do whatever it takes to make ``elem in gset`` true. >>> L, S, D = [ ], set(), { } >>> include(L, "Lucy"); include(S, "Sky"); include(D, "Diamonds"); >>> print L, S, D ['Lucy'] set(['Sky']) {'Diamonds': True} Works for sets (using ``add``), lists (using ``append``) and dicts (using ``__setitem__``). ``value`` if ``gset`` is a dict, does ``gset[elem] = value``. Returns ``elem``, or raises an Error if none of these operations are supported. """ add = getattr(gset, 'add', None) # sets if add is None: add = getattr(gset, 'append', None) # lists if add is not None: add(elem) else: # dicts if not hasattr(gset, '__setitem__'): raise Error("gset is not a supported container.") gset[elem] = value return elem
python
def include(gset, elem, value=True): """Do whatever it takes to make ``elem in gset`` true. >>> L, S, D = [ ], set(), { } >>> include(L, "Lucy"); include(S, "Sky"); include(D, "Diamonds"); >>> print L, S, D ['Lucy'] set(['Sky']) {'Diamonds': True} Works for sets (using ``add``), lists (using ``append``) and dicts (using ``__setitem__``). ``value`` if ``gset`` is a dict, does ``gset[elem] = value``. Returns ``elem``, or raises an Error if none of these operations are supported. """ add = getattr(gset, 'add', None) # sets if add is None: add = getattr(gset, 'append', None) # lists if add is not None: add(elem) else: # dicts if not hasattr(gset, '__setitem__'): raise Error("gset is not a supported container.") gset[elem] = value return elem
[ "def", "include", "(", "gset", ",", "elem", ",", "value", "=", "True", ")", ":", "add", "=", "getattr", "(", "gset", ",", "'add'", ",", "None", ")", "# sets", "if", "add", "is", "None", ":", "add", "=", "getattr", "(", "gset", ",", "'append'", ",", "None", ")", "# lists", "if", "add", "is", "not", "None", ":", "add", "(", "elem", ")", "else", ":", "# dicts", "if", "not", "hasattr", "(", "gset", ",", "'__setitem__'", ")", ":", "raise", "Error", "(", "\"gset is not a supported container.\"", ")", "gset", "[", "elem", "]", "=", "value", "return", "elem" ]
Do whatever it takes to make ``elem in gset`` true. >>> L, S, D = [ ], set(), { } >>> include(L, "Lucy"); include(S, "Sky"); include(D, "Diamonds"); >>> print L, S, D ['Lucy'] set(['Sky']) {'Diamonds': True} Works for sets (using ``add``), lists (using ``append``) and dicts (using ``__setitem__``). ``value`` if ``gset`` is a dict, does ``gset[elem] = value``. Returns ``elem``, or raises an Error if none of these operations are supported.
[ "Do", "whatever", "it", "takes", "to", "make", "elem", "in", "gset", "true", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L268-L291
239,729
cyrus-/cypy
cypy/__init__.py
remove_all
def remove_all(gset, elem): """Removes every occurrence of ``elem`` from ``gset``. Returns the number of times ``elem`` was removed. """ n = 0 while True: try: remove_once(gset, elem) n = n + 1 except RemoveError: return n
python
def remove_all(gset, elem): """Removes every occurrence of ``elem`` from ``gset``. Returns the number of times ``elem`` was removed. """ n = 0 while True: try: remove_once(gset, elem) n = n + 1 except RemoveError: return n
[ "def", "remove_all", "(", "gset", ",", "elem", ")", ":", "n", "=", "0", "while", "True", ":", "try", ":", "remove_once", "(", "gset", ",", "elem", ")", "n", "=", "n", "+", "1", "except", "RemoveError", ":", "return", "n" ]
Removes every occurrence of ``elem`` from ``gset``. Returns the number of times ``elem`` was removed.
[ "Removes", "every", "occurrence", "of", "elem", "from", "gset", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L336-L347
239,730
cyrus-/cypy
cypy/__init__.py
flatten
def flatten(iterable, check=is_iterable): """Produces a recursively flattened version of ``iterable`` ``check`` Recurses only if check(value) is true. """ for value in iterable: if check(value): for flat in flatten(value, check): yield flat else: yield value
python
def flatten(iterable, check=is_iterable): """Produces a recursively flattened version of ``iterable`` ``check`` Recurses only if check(value) is true. """ for value in iterable: if check(value): for flat in flatten(value, check): yield flat else: yield value
[ "def", "flatten", "(", "iterable", ",", "check", "=", "is_iterable", ")", ":", "for", "value", "in", "iterable", ":", "if", "check", "(", "value", ")", ":", "for", "flat", "in", "flatten", "(", "value", ",", "check", ")", ":", "yield", "flat", "else", ":", "yield", "value" ]
Produces a recursively flattened version of ``iterable`` ``check`` Recurses only if check(value) is true.
[ "Produces", "a", "recursively", "flattened", "version", "of", "iterable" ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L423-L434
239,731
cyrus-/cypy
cypy/__init__.py
xflatten
def xflatten(iterable, transform, check=is_iterable): """Apply a transform to iterable before flattening at each level.""" for value in transform(iterable): if check(value): for flat in xflatten(value, transform, check): yield flat else: yield value
python
def xflatten(iterable, transform, check=is_iterable): """Apply a transform to iterable before flattening at each level.""" for value in transform(iterable): if check(value): for flat in xflatten(value, transform, check): yield flat else: yield value
[ "def", "xflatten", "(", "iterable", ",", "transform", ",", "check", "=", "is_iterable", ")", ":", "for", "value", "in", "transform", "(", "iterable", ")", ":", "if", "check", "(", "value", ")", ":", "for", "flat", "in", "xflatten", "(", "value", ",", "transform", ",", "check", ")", ":", "yield", "flat", "else", ":", "yield", "value" ]
Apply a transform to iterable before flattening at each level.
[ "Apply", "a", "transform", "to", "iterable", "before", "flattening", "at", "each", "level", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L469-L476
239,732
cyrus-/cypy
cypy/__init__.py
flatten_once
def flatten_once(iterable, check=is_iterable): """Flattens only the first level.""" for value in iterable: if check(value): for item in value: yield item else: yield value
python
def flatten_once(iterable, check=is_iterable): """Flattens only the first level.""" for value in iterable: if check(value): for item in value: yield item else: yield value
[ "def", "flatten_once", "(", "iterable", ",", "check", "=", "is_iterable", ")", ":", "for", "value", "in", "iterable", ":", "if", "check", "(", "value", ")", ":", "for", "item", "in", "value", ":", "yield", "item", "else", ":", "yield", "value" ]
Flattens only the first level.
[ "Flattens", "only", "the", "first", "level", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L480-L487
239,733
cyrus-/cypy
cypy/__init__.py
join
def join(iterable, sep): """Like str.join, but yields an iterable.""" i = 0 for i, item in enumerate(iterable): if i == 0: yield item else: yield sep yield item
python
def join(iterable, sep): """Like str.join, but yields an iterable.""" i = 0 for i, item in enumerate(iterable): if i == 0: yield item else: yield sep yield item
[ "def", "join", "(", "iterable", ",", "sep", ")", ":", "i", "=", "0", "for", "i", ",", "item", "in", "enumerate", "(", "iterable", ")", ":", "if", "i", "==", "0", ":", "yield", "item", "else", ":", "yield", "sep", "yield", "item" ]
Like str.join, but yields an iterable.
[ "Like", "str", ".", "join", "but", "yields", "an", "iterable", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L497-L505
239,734
cyrus-/cypy
cypy/__init__.py
stop_at
def stop_at(iterable, idx): """Stops iterating before yielding the specified idx.""" for i, item in enumerate(iterable): if i == idx: return yield item
python
def stop_at(iterable, idx): """Stops iterating before yielding the specified idx.""" for i, item in enumerate(iterable): if i == idx: return yield item
[ "def", "stop_at", "(", "iterable", ",", "idx", ")", ":", "for", "i", ",", "item", "in", "enumerate", "(", "iterable", ")", ":", "if", "i", "==", "idx", ":", "return", "yield", "item" ]
Stops iterating before yielding the specified idx.
[ "Stops", "iterating", "before", "yielding", "the", "specified", "idx", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L508-L512
239,735
cyrus-/cypy
cypy/__init__.py
all_pairs
def all_pairs(seq1, seq2=None): """Yields all pairs drawn from ``seq1`` and ``seq2``. If ``seq2`` is ``None``, ``seq2 = seq1``. >>> stop_at.ed(all_pairs(xrange(100000), xrange(100000)), 8) ((0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7)) """ if seq2 is None: seq2 = seq1 for item1 in seq1: for item2 in seq2: yield (item1, item2)
python
def all_pairs(seq1, seq2=None): """Yields all pairs drawn from ``seq1`` and ``seq2``. If ``seq2`` is ``None``, ``seq2 = seq1``. >>> stop_at.ed(all_pairs(xrange(100000), xrange(100000)), 8) ((0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7)) """ if seq2 is None: seq2 = seq1 for item1 in seq1: for item2 in seq2: yield (item1, item2)
[ "def", "all_pairs", "(", "seq1", ",", "seq2", "=", "None", ")", ":", "if", "seq2", "is", "None", ":", "seq2", "=", "seq1", "for", "item1", "in", "seq1", ":", "for", "item2", "in", "seq2", ":", "yield", "(", "item1", ",", "item2", ")" ]
Yields all pairs drawn from ``seq1`` and ``seq2``. If ``seq2`` is ``None``, ``seq2 = seq1``. >>> stop_at.ed(all_pairs(xrange(100000), xrange(100000)), 8) ((0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7))
[ "Yields", "all", "pairs", "drawn", "from", "seq1", "and", "seq2", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L515-L526
239,736
cyrus-/cypy
cypy/__init__.py
padded_to_same_length
def padded_to_same_length(seq1, seq2, item=0): """Return a pair of sequences of the same length by padding the shorter sequence with ``item``. The padded sequence is a tuple. The unpadded sequence is returned as-is. """ len1, len2 = len(seq1), len(seq2) if len1 == len2: return (seq1, seq2) elif len1 < len2: return (cons.ed(seq1, yield_n(len2-len1, item)), seq2) else: return (seq1, cons.ed(seq2, yield_n(len1-len2, item)))
python
def padded_to_same_length(seq1, seq2, item=0): """Return a pair of sequences of the same length by padding the shorter sequence with ``item``. The padded sequence is a tuple. The unpadded sequence is returned as-is. """ len1, len2 = len(seq1), len(seq2) if len1 == len2: return (seq1, seq2) elif len1 < len2: return (cons.ed(seq1, yield_n(len2-len1, item)), seq2) else: return (seq1, cons.ed(seq2, yield_n(len1-len2, item)))
[ "def", "padded_to_same_length", "(", "seq1", ",", "seq2", ",", "item", "=", "0", ")", ":", "len1", ",", "len2", "=", "len", "(", "seq1", ")", ",", "len", "(", "seq2", ")", "if", "len1", "==", "len2", ":", "return", "(", "seq1", ",", "seq2", ")", "elif", "len1", "<", "len2", ":", "return", "(", "cons", ".", "ed", "(", "seq1", ",", "yield_n", "(", "len2", "-", "len1", ",", "item", ")", ")", ",", "seq2", ")", "else", ":", "return", "(", "seq1", ",", "cons", ".", "ed", "(", "seq2", ",", "yield_n", "(", "len1", "-", "len2", ",", "item", ")", ")", ")" ]
Return a pair of sequences of the same length by padding the shorter sequence with ``item``. The padded sequence is a tuple. The unpadded sequence is returned as-is.
[ "Return", "a", "pair", "of", "sequences", "of", "the", "same", "length", "by", "padding", "the", "shorter", "sequence", "with", "item", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L536-L548
239,737
cyrus-/cypy
cypy/__init__.py
is_int_like
def is_int_like(value): """Returns whether the value can be used as a standard integer. >>> is_int_like(4) True >>> is_int_like(4.0) False >>> is_int_like("4") False >>> is_int_like("abc") False """ try: if isinstance(value, int): return True return int(value) == value and str(value).isdigit() except: return False
python
def is_int_like(value): """Returns whether the value can be used as a standard integer. >>> is_int_like(4) True >>> is_int_like(4.0) False >>> is_int_like("4") False >>> is_int_like("abc") False """ try: if isinstance(value, int): return True return int(value) == value and str(value).isdigit() except: return False
[ "def", "is_int_like", "(", "value", ")", ":", "try", ":", "if", "isinstance", "(", "value", ",", "int", ")", ":", "return", "True", "return", "int", "(", "value", ")", "==", "value", "and", "str", "(", "value", ")", ".", "isdigit", "(", ")", "except", ":", "return", "False" ]
Returns whether the value can be used as a standard integer. >>> is_int_like(4) True >>> is_int_like(4.0) False >>> is_int_like("4") False >>> is_int_like("abc") False
[ "Returns", "whether", "the", "value", "can", "be", "used", "as", "a", "standard", "integer", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L583-L600
239,738
cyrus-/cypy
cypy/__init__.py
is_float_like
def is_float_like(value): """Returns whether the value acts like a standard float. >>> is_float_like(4.0) True >>> is_float_like(numpy.float32(4.0)) True >>> is_float_like(numpy.int32(4.0)) False >>> is_float_like(4) False """ try: if isinstance(value, float): return True return float(value) == value and not str(value).isdigit() except: return False
python
def is_float_like(value): """Returns whether the value acts like a standard float. >>> is_float_like(4.0) True >>> is_float_like(numpy.float32(4.0)) True >>> is_float_like(numpy.int32(4.0)) False >>> is_float_like(4) False """ try: if isinstance(value, float): return True return float(value) == value and not str(value).isdigit() except: return False
[ "def", "is_float_like", "(", "value", ")", ":", "try", ":", "if", "isinstance", "(", "value", ",", "float", ")", ":", "return", "True", "return", "float", "(", "value", ")", "==", "value", "and", "not", "str", "(", "value", ")", ".", "isdigit", "(", ")", "except", ":", "return", "False" ]
Returns whether the value acts like a standard float. >>> is_float_like(4.0) True >>> is_float_like(numpy.float32(4.0)) True >>> is_float_like(numpy.int32(4.0)) False >>> is_float_like(4) False
[ "Returns", "whether", "the", "value", "acts", "like", "a", "standard", "float", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L602-L619
239,739
cyrus-/cypy
cypy/__init__.py
make_symmetric
def make_symmetric(dict): """Makes the given dictionary symmetric. Values are assumed to be unique.""" for key, value in list(dict.items()): dict[value] = key return dict
python
def make_symmetric(dict): """Makes the given dictionary symmetric. Values are assumed to be unique.""" for key, value in list(dict.items()): dict[value] = key return dict
[ "def", "make_symmetric", "(", "dict", ")", ":", "for", "key", ",", "value", "in", "list", "(", "dict", ".", "items", "(", ")", ")", ":", "dict", "[", "value", "]", "=", "key", "return", "dict" ]
Makes the given dictionary symmetric. Values are assumed to be unique.
[ "Makes", "the", "given", "dictionary", "symmetric", ".", "Values", "are", "assumed", "to", "be", "unique", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L657-L661
239,740
cyrus-/cypy
cypy/__init__.py
fn_kwargs
def fn_kwargs(callable): """Returns a dict with the kwargs from the provided function. Example >>> def x(a, b=0, *args, **kwargs): pass >>> func_kwargs(x) == { 'b': 0 } """ fn = get_fn(callable) (args, _, _, defaults) = _inspect.getargspec(fn) if defaults is None: return { } return dict(list(zip(reversed(args), reversed(defaults))))
python
def fn_kwargs(callable): """Returns a dict with the kwargs from the provided function. Example >>> def x(a, b=0, *args, **kwargs): pass >>> func_kwargs(x) == { 'b': 0 } """ fn = get_fn(callable) (args, _, _, defaults) = _inspect.getargspec(fn) if defaults is None: return { } return dict(list(zip(reversed(args), reversed(defaults))))
[ "def", "fn_kwargs", "(", "callable", ")", ":", "fn", "=", "get_fn", "(", "callable", ")", "(", "args", ",", "_", ",", "_", ",", "defaults", ")", "=", "_inspect", ".", "getargspec", "(", "fn", ")", "if", "defaults", "is", "None", ":", "return", "{", "}", "return", "dict", "(", "list", "(", "zip", "(", "reversed", "(", "args", ")", ",", "reversed", "(", "defaults", ")", ")", ")", ")" ]
Returns a dict with the kwargs from the provided function. Example >>> def x(a, b=0, *args, **kwargs): pass >>> func_kwargs(x) == { 'b': 0 }
[ "Returns", "a", "dict", "with", "the", "kwargs", "from", "the", "provided", "function", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L742-L754
239,741
cyrus-/cypy
cypy/__init__.py
fn_available_argcount
def fn_available_argcount(callable): """Returns the number of explicit non-keyword arguments that the callable can be called with. Bound methods are called with an implicit first argument, so this takes that into account. Excludes *args and **kwargs declarations. """ fn = get_fn_or_method(callable) if _inspect.isfunction(fn): return fn.__code__.co_argcount else: # method if fn.__self__ is None: return fn.__func__.__code__.co_argcount else: return fn.__func__.__code__.co_argcount - 1
python
def fn_available_argcount(callable): """Returns the number of explicit non-keyword arguments that the callable can be called with. Bound methods are called with an implicit first argument, so this takes that into account. Excludes *args and **kwargs declarations. """ fn = get_fn_or_method(callable) if _inspect.isfunction(fn): return fn.__code__.co_argcount else: # method if fn.__self__ is None: return fn.__func__.__code__.co_argcount else: return fn.__func__.__code__.co_argcount - 1
[ "def", "fn_available_argcount", "(", "callable", ")", ":", "fn", "=", "get_fn_or_method", "(", "callable", ")", "if", "_inspect", ".", "isfunction", "(", "fn", ")", ":", "return", "fn", ".", "__code__", ".", "co_argcount", "else", ":", "# method", "if", "fn", ".", "__self__", "is", "None", ":", "return", "fn", ".", "__func__", ".", "__code__", ".", "co_argcount", "else", ":", "return", "fn", ".", "__func__", ".", "__code__", ".", "co_argcount", "-", "1" ]
Returns the number of explicit non-keyword arguments that the callable can be called with. Bound methods are called with an implicit first argument, so this takes that into account. Excludes *args and **kwargs declarations.
[ "Returns", "the", "number", "of", "explicit", "non", "-", "keyword", "arguments", "that", "the", "callable", "can", "be", "called", "with", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L756-L772
239,742
cyrus-/cypy
cypy/__init__.py
fn_minimum_argcount
def fn_minimum_argcount(callable): """Returns the minimum number of arguments that must be provided for the call to succeed.""" fn = get_fn(callable) available_argcount = fn_available_argcount(callable) try: return available_argcount - len(fn.__defaults__) except TypeError: return available_argcount
python
def fn_minimum_argcount(callable): """Returns the minimum number of arguments that must be provided for the call to succeed.""" fn = get_fn(callable) available_argcount = fn_available_argcount(callable) try: return available_argcount - len(fn.__defaults__) except TypeError: return available_argcount
[ "def", "fn_minimum_argcount", "(", "callable", ")", ":", "fn", "=", "get_fn", "(", "callable", ")", "available_argcount", "=", "fn_available_argcount", "(", "callable", ")", "try", ":", "return", "available_argcount", "-", "len", "(", "fn", ".", "__defaults__", ")", "except", "TypeError", ":", "return", "available_argcount" ]
Returns the minimum number of arguments that must be provided for the call to succeed.
[ "Returns", "the", "minimum", "number", "of", "arguments", "that", "must", "be", "provided", "for", "the", "call", "to", "succeed", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L774-L781
239,743
cyrus-/cypy
cypy/__init__.py
fn_signature
def fn_signature(callable, argument_transform=(lambda name: name), default_transform=(lambda name, value: "%s=%s" % (name, repr(value))), vararg_transform=(lambda name: "*" + name), kwargs_transform=(lambda name: "**" + name)): """Returns the signature of the provided callable as a tuple of strings.""" signature = [] fn = get_fn(callable) avail_ac = fn_available_argcount(fn) kwargs = fn_kwargs(fn) argnames = fn_argnames(fn) for name in stop_at(argnames, avail_ac): if name in kwargs: signature.append(default_transform(name, kwargs[name])) else: signature.append(argument_transform(name)) if fn_has_args(fn): if fn_has_kwargs(fn): signature.append(vararg_transform(argnames[-2])) signature.append(kwargs_transform(argnames[-1])) else: signature.append(vararg_transform(argnames[-1])) elif fn_has_kwargs(fn): signature.append(kwargs_transform(argnames[-1])) return signature
python
def fn_signature(callable, argument_transform=(lambda name: name), default_transform=(lambda name, value: "%s=%s" % (name, repr(value))), vararg_transform=(lambda name: "*" + name), kwargs_transform=(lambda name: "**" + name)): """Returns the signature of the provided callable as a tuple of strings.""" signature = [] fn = get_fn(callable) avail_ac = fn_available_argcount(fn) kwargs = fn_kwargs(fn) argnames = fn_argnames(fn) for name in stop_at(argnames, avail_ac): if name in kwargs: signature.append(default_transform(name, kwargs[name])) else: signature.append(argument_transform(name)) if fn_has_args(fn): if fn_has_kwargs(fn): signature.append(vararg_transform(argnames[-2])) signature.append(kwargs_transform(argnames[-1])) else: signature.append(vararg_transform(argnames[-1])) elif fn_has_kwargs(fn): signature.append(kwargs_transform(argnames[-1])) return signature
[ "def", "fn_signature", "(", "callable", ",", "argument_transform", "=", "(", "lambda", "name", ":", "name", ")", ",", "default_transform", "=", "(", "lambda", "name", ",", "value", ":", "\"%s=%s\"", "%", "(", "name", ",", "repr", "(", "value", ")", ")", ")", ",", "vararg_transform", "=", "(", "lambda", "name", ":", "\"*\"", "+", "name", ")", ",", "kwargs_transform", "=", "(", "lambda", "name", ":", "\"**\"", "+", "name", ")", ")", ":", "signature", "=", "[", "]", "fn", "=", "get_fn", "(", "callable", ")", "avail_ac", "=", "fn_available_argcount", "(", "fn", ")", "kwargs", "=", "fn_kwargs", "(", "fn", ")", "argnames", "=", "fn_argnames", "(", "fn", ")", "for", "name", "in", "stop_at", "(", "argnames", ",", "avail_ac", ")", ":", "if", "name", "in", "kwargs", ":", "signature", ".", "append", "(", "default_transform", "(", "name", ",", "kwargs", "[", "name", "]", ")", ")", "else", ":", "signature", ".", "append", "(", "argument_transform", "(", "name", ")", ")", "if", "fn_has_args", "(", "fn", ")", ":", "if", "fn_has_kwargs", "(", "fn", ")", ":", "signature", ".", "append", "(", "vararg_transform", "(", "argnames", "[", "-", "2", "]", ")", ")", "signature", ".", "append", "(", "kwargs_transform", "(", "argnames", "[", "-", "1", "]", ")", ")", "else", ":", "signature", ".", "append", "(", "vararg_transform", "(", "argnames", "[", "-", "1", "]", ")", ")", "elif", "fn_has_kwargs", "(", "fn", ")", ":", "signature", ".", "append", "(", "kwargs_transform", "(", "argnames", "[", "-", "1", "]", ")", ")", "return", "signature" ]
Returns the signature of the provided callable as a tuple of strings.
[ "Returns", "the", "signature", "of", "the", "provided", "callable", "as", "a", "tuple", "of", "strings", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L793-L819
239,744
cyrus-/cypy
cypy/__init__.py
decorator
def decorator(d): """Creates a proper decorator. If the default for the first (function) argument is None, creates a version which be invoked as either @decorator or @decorator(kwargs...). See examples below. """ defaults = d.__defaults__ if defaults and defaults[0] is None: # Can be applied as @decorator or @decorator(kwargs) because # first argument is None def decorate(fn=None, **kwargs): if fn is None: return _functools.partial(decorate, **kwargs) else: decorated = d(fn, **kwargs) _functools.update_wrapper(decorated, fn) return decorated else: # Can only be applied as @decorator def decorate(fn): decorated = d(fn) _functools.update_wrapper(decorated, fn) return decorated _functools.update_wrapper(decorate, d) return decorate
python
def decorator(d): """Creates a proper decorator. If the default for the first (function) argument is None, creates a version which be invoked as either @decorator or @decorator(kwargs...). See examples below. """ defaults = d.__defaults__ if defaults and defaults[0] is None: # Can be applied as @decorator or @decorator(kwargs) because # first argument is None def decorate(fn=None, **kwargs): if fn is None: return _functools.partial(decorate, **kwargs) else: decorated = d(fn, **kwargs) _functools.update_wrapper(decorated, fn) return decorated else: # Can only be applied as @decorator def decorate(fn): decorated = d(fn) _functools.update_wrapper(decorated, fn) return decorated _functools.update_wrapper(decorate, d) return decorate
[ "def", "decorator", "(", "d", ")", ":", "defaults", "=", "d", ".", "__defaults__", "if", "defaults", "and", "defaults", "[", "0", "]", "is", "None", ":", "# Can be applied as @decorator or @decorator(kwargs) because", "# first argument is None", "def", "decorate", "(", "fn", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "fn", "is", "None", ":", "return", "_functools", ".", "partial", "(", "decorate", ",", "*", "*", "kwargs", ")", "else", ":", "decorated", "=", "d", "(", "fn", ",", "*", "*", "kwargs", ")", "_functools", ".", "update_wrapper", "(", "decorated", ",", "fn", ")", "return", "decorated", "else", ":", "# Can only be applied as @decorator", "def", "decorate", "(", "fn", ")", ":", "decorated", "=", "d", "(", "fn", ")", "_functools", ".", "update_wrapper", "(", "decorated", ",", "fn", ")", "return", "decorated", "_functools", ".", "update_wrapper", "(", "decorate", ",", "d", ")", "return", "decorate" ]
Creates a proper decorator. If the default for the first (function) argument is None, creates a version which be invoked as either @decorator or @decorator(kwargs...). See examples below.
[ "Creates", "a", "proper", "decorator", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L910-L936
239,745
cyrus-/cypy
cypy/__init__.py
memoize
def memoize(fn=None): """Caches the result of the provided function.""" cache = { } arg_hash_fn = fn_arg_hash_function(fn) def decorated(*args, **kwargs): try: hash_ = arg_hash_fn(*args, **kwargs) except TypeError: return fn(*args, **kwargs) try: return cache[hash_] except KeyError: return_val = fn(*args, **kwargs) cache[hash_] = return_val return return_val _functools.update_wrapper(decorated, fn) return decorated
python
def memoize(fn=None): """Caches the result of the provided function.""" cache = { } arg_hash_fn = fn_arg_hash_function(fn) def decorated(*args, **kwargs): try: hash_ = arg_hash_fn(*args, **kwargs) except TypeError: return fn(*args, **kwargs) try: return cache[hash_] except KeyError: return_val = fn(*args, **kwargs) cache[hash_] = return_val return return_val _functools.update_wrapper(decorated, fn) return decorated
[ "def", "memoize", "(", "fn", "=", "None", ")", ":", "cache", "=", "{", "}", "arg_hash_fn", "=", "fn_arg_hash_function", "(", "fn", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "hash_", "=", "arg_hash_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "TypeError", ":", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "return", "cache", "[", "hash_", "]", "except", "KeyError", ":", "return_val", "=", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "cache", "[", "hash_", "]", "=", "return_val", "return", "return_val", "_functools", ".", "update_wrapper", "(", "decorated", ",", "fn", ")", "return", "decorated" ]
Caches the result of the provided function.
[ "Caches", "the", "result", "of", "the", "provided", "function", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L940-L959
239,746
cyrus-/cypy
cypy/__init__.py
safe_setattr
def safe_setattr(obj, name, value): """Attempt to setattr but catch AttributeErrors.""" try: setattr(obj, name, value) return True except AttributeError: return False
python
def safe_setattr(obj, name, value): """Attempt to setattr but catch AttributeErrors.""" try: setattr(obj, name, value) return True except AttributeError: return False
[ "def", "safe_setattr", "(", "obj", ",", "name", ",", "value", ")", ":", "try", ":", "setattr", "(", "obj", ",", "name", ",", "value", ")", "return", "True", "except", "AttributeError", ":", "return", "False" ]
Attempt to setattr but catch AttributeErrors.
[ "Attempt", "to", "setattr", "but", "catch", "AttributeErrors", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L979-L985
239,747
cyrus-/cypy
cypy/__init__.py
method_call_if_def
def method_call_if_def(obj, attr_name, m_name, default, *args, **kwargs): """Calls the provided method if it is defined. Returns default if not defined. """ try: attr = getattr(obj, attr_name) except AttributeError: return default else: return getattr(attr, m_name)(*args, **kwargs)
python
def method_call_if_def(obj, attr_name, m_name, default, *args, **kwargs): """Calls the provided method if it is defined. Returns default if not defined. """ try: attr = getattr(obj, attr_name) except AttributeError: return default else: return getattr(attr, m_name)(*args, **kwargs)
[ "def", "method_call_if_def", "(", "obj", ",", "attr_name", ",", "m_name", ",", "default", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "attr", "=", "getattr", "(", "obj", ",", "attr_name", ")", "except", "AttributeError", ":", "return", "default", "else", ":", "return", "getattr", "(", "attr", ",", "m_name", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Calls the provided method if it is defined. Returns default if not defined.
[ "Calls", "the", "provided", "method", "if", "it", "is", "defined", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L987-L997
239,748
cyrus-/cypy
cypy/__init__.py
call_on_if_def
def call_on_if_def(obj, attr_name, callable, default, *args, **kwargs): """Calls the provided callable on the provided attribute of ``obj`` if it is defined. If not, returns default. """ try: attr = getattr(obj, attr_name) except AttributeError: return default else: return callable(attr, *args, **kwargs)
python
def call_on_if_def(obj, attr_name, callable, default, *args, **kwargs): """Calls the provided callable on the provided attribute of ``obj`` if it is defined. If not, returns default. """ try: attr = getattr(obj, attr_name) except AttributeError: return default else: return callable(attr, *args, **kwargs)
[ "def", "call_on_if_def", "(", "obj", ",", "attr_name", ",", "callable", ",", "default", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "attr", "=", "getattr", "(", "obj", ",", "attr_name", ")", "except", "AttributeError", ":", "return", "default", "else", ":", "return", "callable", "(", "attr", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Calls the provided callable on the provided attribute of ``obj`` if it is defined. If not, returns default.
[ "Calls", "the", "provided", "callable", "on", "the", "provided", "attribute", "of", "obj", "if", "it", "is", "defined", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L999-L1009
239,749
cyrus-/cypy
cypy/__init__.py
is_senior_subclass
def is_senior_subclass(obj, cls, testcls): """Determines whether the cls is the senior subclass of basecls for obj. The most senior subclass is the first class in the mro which is a subclass of testcls. Use for inheritance schemes where a method should only be called once by the most senior subclass. Don't use if it is optional to call the base method! In that case, the most reasonable way to do it is to ensure the method is idempotent and deal with the hopefully small inefficiency of calling it multiple times. Doing a hasattr check in these implementations should be relatively efficient. In particular, __init__ for mixins tends to act like this. """ for base in obj.__class__.mro(): if base is cls: return True else: if issubclass(base, testcls): return False
python
def is_senior_subclass(obj, cls, testcls): """Determines whether the cls is the senior subclass of basecls for obj. The most senior subclass is the first class in the mro which is a subclass of testcls. Use for inheritance schemes where a method should only be called once by the most senior subclass. Don't use if it is optional to call the base method! In that case, the most reasonable way to do it is to ensure the method is idempotent and deal with the hopefully small inefficiency of calling it multiple times. Doing a hasattr check in these implementations should be relatively efficient. In particular, __init__ for mixins tends to act like this. """ for base in obj.__class__.mro(): if base is cls: return True else: if issubclass(base, testcls): return False
[ "def", "is_senior_subclass", "(", "obj", ",", "cls", ",", "testcls", ")", ":", "for", "base", "in", "obj", ".", "__class__", ".", "mro", "(", ")", ":", "if", "base", "is", "cls", ":", "return", "True", "else", ":", "if", "issubclass", "(", "base", ",", "testcls", ")", ":", "return", "False" ]
Determines whether the cls is the senior subclass of basecls for obj. The most senior subclass is the first class in the mro which is a subclass of testcls. Use for inheritance schemes where a method should only be called once by the most senior subclass. Don't use if it is optional to call the base method! In that case, the most reasonable way to do it is to ensure the method is idempotent and deal with the hopefully small inefficiency of calling it multiple times. Doing a hasattr check in these implementations should be relatively efficient. In particular, __init__ for mixins tends to act like this.
[ "Determines", "whether", "the", "cls", "is", "the", "senior", "subclass", "of", "basecls", "for", "obj", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1403-L1426
239,750
cyrus-/cypy
cypy/__init__.py
string_escape
def string_escape(string, delimiter='"'): """Turns special characters into escape sequences in the provided string. Supports both byte strings and unicode strings properly. Any other values will produce None. Example: >>> string_escape("a line\t") "a line\\t" >>> string_escape(u"some fancy character: \\u9999") u"\\u9999" >>> string_escape(5) None """ if isinstance(string, str): escaped = string.encode("string-escape") elif isinstance(string, str): escaped = str(string.encode("unicode-escape")) else: raise Error("Unexpected string type.") return delimiter + escape_quotes(escaped, delimiter) + delimiter
python
def string_escape(string, delimiter='"'): """Turns special characters into escape sequences in the provided string. Supports both byte strings and unicode strings properly. Any other values will produce None. Example: >>> string_escape("a line\t") "a line\\t" >>> string_escape(u"some fancy character: \\u9999") u"\\u9999" >>> string_escape(5) None """ if isinstance(string, str): escaped = string.encode("string-escape") elif isinstance(string, str): escaped = str(string.encode("unicode-escape")) else: raise Error("Unexpected string type.") return delimiter + escape_quotes(escaped, delimiter) + delimiter
[ "def", "string_escape", "(", "string", ",", "delimiter", "=", "'\"'", ")", ":", "if", "isinstance", "(", "string", ",", "str", ")", ":", "escaped", "=", "string", ".", "encode", "(", "\"string-escape\"", ")", "elif", "isinstance", "(", "string", ",", "str", ")", ":", "escaped", "=", "str", "(", "string", ".", "encode", "(", "\"unicode-escape\"", ")", ")", "else", ":", "raise", "Error", "(", "\"Unexpected string type.\"", ")", "return", "delimiter", "+", "escape_quotes", "(", "escaped", ",", "delimiter", ")", "+", "delimiter" ]
Turns special characters into escape sequences in the provided string. Supports both byte strings and unicode strings properly. Any other values will produce None. Example: >>> string_escape("a line\t") "a line\\t" >>> string_escape(u"some fancy character: \\u9999") u"\\u9999" >>> string_escape(5) None
[ "Turns", "special", "characters", "into", "escape", "sequences", "in", "the", "provided", "string", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1579-L1599
239,751
cyrus-/cypy
cypy/__init__.py
re_line_and_indentation
def re_line_and_indentation(base_indentation, modifiers=(True, True)): """Returns a re matching newline + base_indentation. modifiers is a tuple, (include_first, include_final). If include_first, matches indentation at the beginning of the string. If include_final, matches indentation at the end of the string. Cached. """ cache = re_line_and_indentation.cache[modifiers] compiled = cache.get(base_indentation, None) if compiled is None: [prefix, suffix] = re_line_and_indentation.tuple[modifiers] compiled = cache[modifiers] = \ _re.compile(prefix + base_indentation + suffix) return compiled
python
def re_line_and_indentation(base_indentation, modifiers=(True, True)): """Returns a re matching newline + base_indentation. modifiers is a tuple, (include_first, include_final). If include_first, matches indentation at the beginning of the string. If include_final, matches indentation at the end of the string. Cached. """ cache = re_line_and_indentation.cache[modifiers] compiled = cache.get(base_indentation, None) if compiled is None: [prefix, suffix] = re_line_and_indentation.tuple[modifiers] compiled = cache[modifiers] = \ _re.compile(prefix + base_indentation + suffix) return compiled
[ "def", "re_line_and_indentation", "(", "base_indentation", ",", "modifiers", "=", "(", "True", ",", "True", ")", ")", ":", "cache", "=", "re_line_and_indentation", ".", "cache", "[", "modifiers", "]", "compiled", "=", "cache", ".", "get", "(", "base_indentation", ",", "None", ")", "if", "compiled", "is", "None", ":", "[", "prefix", ",", "suffix", "]", "=", "re_line_and_indentation", ".", "tuple", "[", "modifiers", "]", "compiled", "=", "cache", "[", "modifiers", "]", "=", "_re", ".", "compile", "(", "prefix", "+", "base_indentation", "+", "suffix", ")", "return", "compiled" ]
Returns a re matching newline + base_indentation. modifiers is a tuple, (include_first, include_final). If include_first, matches indentation at the beginning of the string. If include_final, matches indentation at the end of the string. Cached.
[ "Returns", "a", "re", "matching", "newline", "+", "base_indentation", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1629-L1646
239,752
cyrus-/cypy
cypy/__init__.py
get_base_indentation
def get_base_indentation(code, include_start=False): """Heuristically extracts the base indentation from the provided code. Finds the smallest indentation following a newline not at the end of the string. """ new_line_indentation = re_new_line_indentation[include_start].finditer(code) new_line_indentation = tuple(m.groups(0)[0] for m in new_line_indentation) if new_line_indentation: return min(new_line_indentation, key=len) else: return ""
python
def get_base_indentation(code, include_start=False): """Heuristically extracts the base indentation from the provided code. Finds the smallest indentation following a newline not at the end of the string. """ new_line_indentation = re_new_line_indentation[include_start].finditer(code) new_line_indentation = tuple(m.groups(0)[0] for m in new_line_indentation) if new_line_indentation: return min(new_line_indentation, key=len) else: return ""
[ "def", "get_base_indentation", "(", "code", ",", "include_start", "=", "False", ")", ":", "new_line_indentation", "=", "re_new_line_indentation", "[", "include_start", "]", ".", "finditer", "(", "code", ")", "new_line_indentation", "=", "tuple", "(", "m", ".", "groups", "(", "0", ")", "[", "0", "]", "for", "m", "in", "new_line_indentation", ")", "if", "new_line_indentation", ":", "return", "min", "(", "new_line_indentation", ",", "key", "=", "len", ")", "else", ":", "return", "\"\"" ]
Heuristically extracts the base indentation from the provided code. Finds the smallest indentation following a newline not at the end of the string.
[ "Heuristically", "extracts", "the", "base", "indentation", "from", "the", "provided", "code", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1661-L1672
239,753
cyrus-/cypy
cypy/__init__.py
fix_indentation
def fix_indentation(code, base_indentation=None, correct_indentation="", modifiers=(True, True)): """Replaces base_indentation at beginning of lines with correct_indentation. If base_indentation is None, tries to find it using get_base_indentation. modifiers are passed to re_line_and_indentation. See there for doc. """ if base_indentation is None: base_indentation = get_base_indentation(code, modifiers[0]) return re_line_and_indentation(base_indentation, modifiers).sub( "\n" + correct_indentation, code)
python
def fix_indentation(code, base_indentation=None, correct_indentation="", modifiers=(True, True)): """Replaces base_indentation at beginning of lines with correct_indentation. If base_indentation is None, tries to find it using get_base_indentation. modifiers are passed to re_line_and_indentation. See there for doc. """ if base_indentation is None: base_indentation = get_base_indentation(code, modifiers[0]) return re_line_and_indentation(base_indentation, modifiers).sub( "\n" + correct_indentation, code)
[ "def", "fix_indentation", "(", "code", ",", "base_indentation", "=", "None", ",", "correct_indentation", "=", "\"\"", ",", "modifiers", "=", "(", "True", ",", "True", ")", ")", ":", "if", "base_indentation", "is", "None", ":", "base_indentation", "=", "get_base_indentation", "(", "code", ",", "modifiers", "[", "0", "]", ")", "return", "re_line_and_indentation", "(", "base_indentation", ",", "modifiers", ")", ".", "sub", "(", "\"\\n\"", "+", "correct_indentation", ",", "code", ")" ]
Replaces base_indentation at beginning of lines with correct_indentation. If base_indentation is None, tries to find it using get_base_indentation. modifiers are passed to re_line_and_indentation. See there for doc.
[ "Replaces", "base_indentation", "at", "beginning", "of", "lines", "with", "correct_indentation", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1683-L1693
239,754
cyrus-/cypy
cypy/__init__.py
Naming.name
def name(self): """The unique name of this object, relative to the parent.""" basename = self.basename if basename is None: return None parent = self.Naming_parent if parent is None: return basename else: return parent.generate_unique_name(basename)
python
def name(self): """The unique name of this object, relative to the parent.""" basename = self.basename if basename is None: return None parent = self.Naming_parent if parent is None: return basename else: return parent.generate_unique_name(basename)
[ "def", "name", "(", "self", ")", ":", "basename", "=", "self", ".", "basename", "if", "basename", "is", "None", ":", "return", "None", "parent", "=", "self", ".", "Naming_parent", "if", "parent", "is", "None", ":", "return", "basename", "else", ":", "return", "parent", ".", "generate_unique_name", "(", "basename", ")" ]
The unique name of this object, relative to the parent.
[ "The", "unique", "name", "of", "this", "object", "relative", "to", "the", "parent", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2060-L2070
239,755
cyrus-/cypy
cypy/__init__.py
Naming.generate_unique_name
def generate_unique_name(self, basename): """Generates a unique name for a child given a base name.""" counts = self.__counts try: count = counts[basename] counts[basename] += 1 except KeyError: count = 0 counts[basename] = 1 prefix = self.Naming_prefix if count == 0: name = prefix + basename else: name = prefix + basename + "_" + str(count) if prefix != "" or count != 0: try: count = counts[name] return self.generate_unique_name(name) except KeyError: # wasn't already used so return it counts[name] = 1 return name
python
def generate_unique_name(self, basename): """Generates a unique name for a child given a base name.""" counts = self.__counts try: count = counts[basename] counts[basename] += 1 except KeyError: count = 0 counts[basename] = 1 prefix = self.Naming_prefix if count == 0: name = prefix + basename else: name = prefix + basename + "_" + str(count) if prefix != "" or count != 0: try: count = counts[name] return self.generate_unique_name(name) except KeyError: # wasn't already used so return it counts[name] = 1 return name
[ "def", "generate_unique_name", "(", "self", ",", "basename", ")", ":", "counts", "=", "self", ".", "__counts", "try", ":", "count", "=", "counts", "[", "basename", "]", "counts", "[", "basename", "]", "+=", "1", "except", "KeyError", ":", "count", "=", "0", "counts", "[", "basename", "]", "=", "1", "prefix", "=", "self", ".", "Naming_prefix", "if", "count", "==", "0", ":", "name", "=", "prefix", "+", "basename", "else", ":", "name", "=", "prefix", "+", "basename", "+", "\"_\"", "+", "str", "(", "count", ")", "if", "prefix", "!=", "\"\"", "or", "count", "!=", "0", ":", "try", ":", "count", "=", "counts", "[", "name", "]", "return", "self", ".", "generate_unique_name", "(", "name", ")", "except", "KeyError", ":", "# wasn't already used so return it", "counts", "[", "name", "]", "=", "1", "return", "name" ]
Generates a unique name for a child given a base name.
[ "Generates", "a", "unique", "name", "for", "a", "child", "given", "a", "base", "name", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2089-L2113
239,756
cyrus-/cypy
cypy/__init__.py
UpTree.add_to_parent
def add_to_parent(self): """Adds this node to the parent's ``children`` collection if it exists.""" parent = self.parent if parent is not None: try: children = parent.children except AttributeError: pass else: include(children, self)
python
def add_to_parent(self): """Adds this node to the parent's ``children`` collection if it exists.""" parent = self.parent if parent is not None: try: children = parent.children except AttributeError: pass else: include(children, self)
[ "def", "add_to_parent", "(", "self", ")", ":", "parent", "=", "self", ".", "parent", "if", "parent", "is", "not", "None", ":", "try", ":", "children", "=", "parent", ".", "children", "except", "AttributeError", ":", "pass", "else", ":", "include", "(", "children", ",", "self", ")" ]
Adds this node to the parent's ``children`` collection if it exists.
[ "Adds", "this", "node", "to", "the", "parent", "s", "children", "collection", "if", "it", "exists", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2171-L2179
239,757
cyrus-/cypy
cypy/__init__.py
UpTree.remove_from_parent
def remove_from_parent(self): """Removes this node from the parent's ``children`` collection if it exists.""" parent = self.parent if parent is not None: try: children = parent.children except AttributeError: pass else: remove_upto_once(children, self)
python
def remove_from_parent(self): """Removes this node from the parent's ``children`` collection if it exists.""" parent = self.parent if parent is not None: try: children = parent.children except AttributeError: pass else: remove_upto_once(children, self)
[ "def", "remove_from_parent", "(", "self", ")", ":", "parent", "=", "self", ".", "parent", "if", "parent", "is", "not", "None", ":", "try", ":", "children", "=", "parent", ".", "children", "except", "AttributeError", ":", "pass", "else", ":", "remove_upto_once", "(", "children", ",", "self", ")" ]
Removes this node from the parent's ``children`` collection if it exists.
[ "Removes", "this", "node", "from", "the", "parent", "s", "children", "collection", "if", "it", "exists", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2181-L2189
239,758
cyrus-/cypy
cypy/__init__.py
UpTree.iter_up
def iter_up(self, include_self=True): """Iterates up the tree to the root.""" if include_self: yield self parent = self.parent while parent is not None: yield parent try: parent = parent.parent except AttributeError: return
python
def iter_up(self, include_self=True): """Iterates up the tree to the root.""" if include_self: yield self parent = self.parent while parent is not None: yield parent try: parent = parent.parent except AttributeError: return
[ "def", "iter_up", "(", "self", ",", "include_self", "=", "True", ")", ":", "if", "include_self", ":", "yield", "self", "parent", "=", "self", ".", "parent", "while", "parent", "is", "not", "None", ":", "yield", "parent", "try", ":", "parent", "=", "parent", ".", "parent", "except", "AttributeError", ":", "return" ]
Iterates up the tree to the root.
[ "Iterates", "up", "the", "tree", "to", "the", "root", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2191-L2200
239,759
cyrus-/cypy
cypy/__init__.py
UpTree.getrec
def getrec(self, name, include_self=True, *default): """Look up an attribute in the path to the root.""" for node in self.iter_up(include_self): try: return getattr(node, name) except AttributeError: pass if default: return default[0] else: raise AttributeError(name)
python
def getrec(self, name, include_self=True, *default): """Look up an attribute in the path to the root.""" for node in self.iter_up(include_self): try: return getattr(node, name) except AttributeError: pass if default: return default[0] else: raise AttributeError(name)
[ "def", "getrec", "(", "self", ",", "name", ",", "include_self", "=", "True", ",", "*", "default", ")", ":", "for", "node", "in", "self", ".", "iter_up", "(", "include_self", ")", ":", "try", ":", "return", "getattr", "(", "node", ",", "name", ")", "except", "AttributeError", ":", "pass", "if", "default", ":", "return", "default", "[", "0", "]", "else", ":", "raise", "AttributeError", "(", "name", ")" ]
Look up an attribute in the path to the root.
[ "Look", "up", "an", "attribute", "in", "the", "path", "to", "the", "root", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2209-L2219
239,760
cyrus-/cypy
cypy/__init__.py
DownTree.trigger_hook
def trigger_hook(self, name, *args, **kwargs): """Recursively call a method named ``name`` with the provided args and keyword args if defined.""" method = getattr(self, name, None) if is_callable(method): method(*args, **kwargs) try: children = self.children except AttributeError: return else: if children is not None: for child in children: method = getattr(child, 'trigger_hook', None) if is_callable(method): method(name, *args, **kwargs) else: method = getattr(child, name, None) if is_callable(method): method(*args, **kwargs)
python
def trigger_hook(self, name, *args, **kwargs): """Recursively call a method named ``name`` with the provided args and keyword args if defined.""" method = getattr(self, name, None) if is_callable(method): method(*args, **kwargs) try: children = self.children except AttributeError: return else: if children is not None: for child in children: method = getattr(child, 'trigger_hook', None) if is_callable(method): method(name, *args, **kwargs) else: method = getattr(child, name, None) if is_callable(method): method(*args, **kwargs)
[ "def", "trigger_hook", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "method", "=", "getattr", "(", "self", ",", "name", ",", "None", ")", "if", "is_callable", "(", "method", ")", ":", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "children", "=", "self", ".", "children", "except", "AttributeError", ":", "return", "else", ":", "if", "children", "is", "not", "None", ":", "for", "child", "in", "children", ":", "method", "=", "getattr", "(", "child", ",", "'trigger_hook'", ",", "None", ")", "if", "is_callable", "(", "method", ")", ":", "method", "(", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "method", "=", "getattr", "(", "child", ",", "name", ",", "None", ")", "if", "is_callable", "(", "method", ")", ":", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Recursively call a method named ``name`` with the provided args and keyword args if defined.
[ "Recursively", "call", "a", "method", "named", "name", "with", "the", "provided", "args", "and", "keyword", "args", "if", "defined", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2236-L2256
239,761
kolypto/py-asynctools
asynctools/threading/Parallel.py
Parallel._spawn_thread
def _spawn_thread(self, target): """ Create a thread """ t = Thread(target=target) t.daemon = True t.start() return t
python
def _spawn_thread(self, target): """ Create a thread """ t = Thread(target=target) t.daemon = True t.start() return t
[ "def", "_spawn_thread", "(", "self", ",", "target", ")", ":", "t", "=", "Thread", "(", "target", "=", "target", ")", "t", ".", "daemon", "=", "True", "t", ".", "start", "(", ")", "return", "t" ]
Create a thread
[ "Create", "a", "thread" ]
04ff42d13b54d200d8cc88b3639937b63278e57c
https://github.com/kolypto/py-asynctools/blob/04ff42d13b54d200d8cc88b3639937b63278e57c/asynctools/threading/Parallel.py#L22-L27
239,762
kolypto/py-asynctools
asynctools/threading/Parallel.py
Parallel.join
def join(self): """ Wait for all current tasks to be finished """ self._jobs.join() try: return self._results, self._errors finally: self._clear()
python
def join(self): """ Wait for all current tasks to be finished """ self._jobs.join() try: return self._results, self._errors finally: self._clear()
[ "def", "join", "(", "self", ")", ":", "self", ".", "_jobs", ".", "join", "(", ")", "try", ":", "return", "self", ".", "_results", ",", "self", ".", "_errors", "finally", ":", "self", ".", "_clear", "(", ")" ]
Wait for all current tasks to be finished
[ "Wait", "for", "all", "current", "tasks", "to", "be", "finished" ]
04ff42d13b54d200d8cc88b3639937b63278e57c
https://github.com/kolypto/py-asynctools/blob/04ff42d13b54d200d8cc88b3639937b63278e57c/asynctools/threading/Parallel.py#L83-L89
239,763
glyph/secretly
secretly/_impl.py
call
def call(exe, *argv): """ Run a command, returning its output, or None if it fails. """ exes = which(exe) if not exes: returnValue(None) stdout, stderr, value = yield getProcessOutputAndValue( exes[0], argv, env=os.environ.copy() ) if value: returnValue(None) returnValue(stdout.decode('utf-8').rstrip('\n'))
python
def call(exe, *argv): """ Run a command, returning its output, or None if it fails. """ exes = which(exe) if not exes: returnValue(None) stdout, stderr, value = yield getProcessOutputAndValue( exes[0], argv, env=os.environ.copy() ) if value: returnValue(None) returnValue(stdout.decode('utf-8').rstrip('\n'))
[ "def", "call", "(", "exe", ",", "*", "argv", ")", ":", "exes", "=", "which", "(", "exe", ")", "if", "not", "exes", ":", "returnValue", "(", "None", ")", "stdout", ",", "stderr", ",", "value", "=", "yield", "getProcessOutputAndValue", "(", "exes", "[", "0", "]", ",", "argv", ",", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", ")", "if", "value", ":", "returnValue", "(", "None", ")", "returnValue", "(", "stdout", ".", "decode", "(", "'utf-8'", ")", ".", "rstrip", "(", "'\\n'", ")", ")" ]
Run a command, returning its output, or None if it fails.
[ "Run", "a", "command", "returning", "its", "output", "or", "None", "if", "it", "fails", "." ]
2f172750f37f91939008fa169e8e81ea41e06902
https://github.com/glyph/secretly/blob/2f172750f37f91939008fa169e8e81ea41e06902/secretly/_impl.py#L189-L201
239,764
glyph/secretly
secretly/_impl.py
SimpleAssuan.issueCommand
def issueCommand(self, command, *args): """ Issue the given Assuan command and return a Deferred that will fire with the response. """ result = Deferred() self._dq.append(result) self.sendLine(b" ".join([command] + list(args))) return result
python
def issueCommand(self, command, *args): """ Issue the given Assuan command and return a Deferred that will fire with the response. """ result = Deferred() self._dq.append(result) self.sendLine(b" ".join([command] + list(args))) return result
[ "def", "issueCommand", "(", "self", ",", "command", ",", "*", "args", ")", ":", "result", "=", "Deferred", "(", ")", "self", ".", "_dq", ".", "append", "(", "result", ")", "self", ".", "sendLine", "(", "b\" \"", ".", "join", "(", "[", "command", "]", "+", "list", "(", "args", ")", ")", ")", "return", "result" ]
Issue the given Assuan command and return a Deferred that will fire with the response.
[ "Issue", "the", "given", "Assuan", "command", "and", "return", "a", "Deferred", "that", "will", "fire", "with", "the", "response", "." ]
2f172750f37f91939008fa169e8e81ea41e06902
https://github.com/glyph/secretly/blob/2f172750f37f91939008fa169e8e81ea41e06902/secretly/_impl.py#L59-L67
239,765
glyph/secretly
secretly/_impl.py
SimpleAssuan._currentResponse
def _currentResponse(self, debugInfo): """ Pull the current response off the queue. """ bd = b''.join(self._bufferedData) self._bufferedData = [] return AssuanResponse(bd, debugInfo)
python
def _currentResponse(self, debugInfo): """ Pull the current response off the queue. """ bd = b''.join(self._bufferedData) self._bufferedData = [] return AssuanResponse(bd, debugInfo)
[ "def", "_currentResponse", "(", "self", ",", "debugInfo", ")", ":", "bd", "=", "b''", ".", "join", "(", "self", ".", "_bufferedData", ")", "self", ".", "_bufferedData", "=", "[", "]", "return", "AssuanResponse", "(", "bd", ",", "debugInfo", ")" ]
Pull the current response off the queue.
[ "Pull", "the", "current", "response", "off", "the", "queue", "." ]
2f172750f37f91939008fa169e8e81ea41e06902
https://github.com/glyph/secretly/blob/2f172750f37f91939008fa169e8e81ea41e06902/secretly/_impl.py#L70-L76
239,766
glyph/secretly
secretly/_impl.py
SimpleAssuan.lineReceived
def lineReceived(self, line): """ A line was received. """ if line.startswith(b"#"): # ignore it return if line.startswith(b"OK"): # if no command issued, then just 'ready' if self._ready: self._dq.pop(0).callback(self._currentResponse(line)) else: self._ready = True if line.startswith(b"D "): self._bufferedData.append(line[2:].replace(b"%0A", b"\r") .replace(b"%0D", b"\n") .replace(b"%25", b"%")) if line.startswith(b"ERR"): self._dq.pop(0).errback(AssuanError(line))
python
def lineReceived(self, line): """ A line was received. """ if line.startswith(b"#"): # ignore it return if line.startswith(b"OK"): # if no command issued, then just 'ready' if self._ready: self._dq.pop(0).callback(self._currentResponse(line)) else: self._ready = True if line.startswith(b"D "): self._bufferedData.append(line[2:].replace(b"%0A", b"\r") .replace(b"%0D", b"\n") .replace(b"%25", b"%")) if line.startswith(b"ERR"): self._dq.pop(0).errback(AssuanError(line))
[ "def", "lineReceived", "(", "self", ",", "line", ")", ":", "if", "line", ".", "startswith", "(", "b\"#\"", ")", ":", "# ignore it", "return", "if", "line", ".", "startswith", "(", "b\"OK\"", ")", ":", "# if no command issued, then just 'ready'", "if", "self", ".", "_ready", ":", "self", ".", "_dq", ".", "pop", "(", "0", ")", ".", "callback", "(", "self", ".", "_currentResponse", "(", "line", ")", ")", "else", ":", "self", ".", "_ready", "=", "True", "if", "line", ".", "startswith", "(", "b\"D \"", ")", ":", "self", ".", "_bufferedData", ".", "append", "(", "line", "[", "2", ":", "]", ".", "replace", "(", "b\"%0A\"", ",", "b\"\\r\"", ")", ".", "replace", "(", "b\"%0D\"", ",", "b\"\\n\"", ")", ".", "replace", "(", "b\"%25\"", ",", "b\"%\"", ")", ")", "if", "line", ".", "startswith", "(", "b\"ERR\"", ")", ":", "self", ".", "_dq", ".", "pop", "(", "0", ")", ".", "errback", "(", "AssuanError", "(", "line", ")", ")" ]
A line was received.
[ "A", "line", "was", "received", "." ]
2f172750f37f91939008fa169e8e81ea41e06902
https://github.com/glyph/secretly/blob/2f172750f37f91939008fa169e8e81ea41e06902/secretly/_impl.py#L79-L96
239,767
jaraco/jaraco.stream
jaraco/stream/gzip.py
read_chunks
def read_chunks(stream, block_size=2**10): """ Given a byte stream with reader, yield chunks of block_size until the stream is consusmed. """ while True: chunk = stream.read(block_size) if not chunk: break yield chunk
python
def read_chunks(stream, block_size=2**10): """ Given a byte stream with reader, yield chunks of block_size until the stream is consusmed. """ while True: chunk = stream.read(block_size) if not chunk: break yield chunk
[ "def", "read_chunks", "(", "stream", ",", "block_size", "=", "2", "**", "10", ")", ":", "while", "True", ":", "chunk", "=", "stream", ".", "read", "(", "block_size", ")", "if", "not", "chunk", ":", "break", "yield", "chunk" ]
Given a byte stream with reader, yield chunks of block_size until the stream is consusmed.
[ "Given", "a", "byte", "stream", "with", "reader", "yield", "chunks", "of", "block_size", "until", "the", "stream", "is", "consusmed", "." ]
960d6950b083e64c97d93e15443d486b52046a44
https://github.com/jaraco/jaraco.stream/blob/960d6950b083e64c97d93e15443d486b52046a44/jaraco/stream/gzip.py#L16-L25
239,768
jaraco/jaraco.stream
jaraco/stream/gzip.py
_load_stream_py3
def _load_stream_py3(dc, chunks): """ Given a decompression stream and chunks, yield chunks of decompressed data until the compression window ends. """ while not dc.eof: res = dc.decompress(dc.unconsumed_tail + next(chunks)) yield res
python
def _load_stream_py3(dc, chunks): """ Given a decompression stream and chunks, yield chunks of decompressed data until the compression window ends. """ while not dc.eof: res = dc.decompress(dc.unconsumed_tail + next(chunks)) yield res
[ "def", "_load_stream_py3", "(", "dc", ",", "chunks", ")", ":", "while", "not", "dc", ".", "eof", ":", "res", "=", "dc", ".", "decompress", "(", "dc", ".", "unconsumed_tail", "+", "next", "(", "chunks", ")", ")", "yield", "res" ]
Given a decompression stream and chunks, yield chunks of decompressed data until the compression window ends.
[ "Given", "a", "decompression", "stream", "and", "chunks", "yield", "chunks", "of", "decompressed", "data", "until", "the", "compression", "window", "ends", "." ]
960d6950b083e64c97d93e15443d486b52046a44
https://github.com/jaraco/jaraco.stream/blob/960d6950b083e64c97d93e15443d486b52046a44/jaraco/stream/gzip.py#L28-L35
239,769
jaraco/jaraco.stream
jaraco/stream/gzip.py
load_streams
def load_streams(chunks): """ Given a gzipped stream of data, yield streams of decompressed data. """ chunks = peekable(chunks) while chunks: if six.PY3: dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16) else: dc = zlib.decompressobj(zlib.MAX_WBITS | 16) yield load_stream(dc, chunks) if dc.unused_data: chunks = peekable(itertools.chain((dc.unused_data,), chunks))
python
def load_streams(chunks): """ Given a gzipped stream of data, yield streams of decompressed data. """ chunks = peekable(chunks) while chunks: if six.PY3: dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16) else: dc = zlib.decompressobj(zlib.MAX_WBITS | 16) yield load_stream(dc, chunks) if dc.unused_data: chunks = peekable(itertools.chain((dc.unused_data,), chunks))
[ "def", "load_streams", "(", "chunks", ")", ":", "chunks", "=", "peekable", "(", "chunks", ")", "while", "chunks", ":", "if", "six", ".", "PY3", ":", "dc", "=", "zlib", ".", "decompressobj", "(", "wbits", "=", "zlib", ".", "MAX_WBITS", "|", "16", ")", "else", ":", "dc", "=", "zlib", ".", "decompressobj", "(", "zlib", ".", "MAX_WBITS", "|", "16", ")", "yield", "load_stream", "(", "dc", ",", "chunks", ")", "if", "dc", ".", "unused_data", ":", "chunks", "=", "peekable", "(", "itertools", ".", "chain", "(", "(", "dc", ".", "unused_data", ",", ")", ",", "chunks", ")", ")" ]
Given a gzipped stream of data, yield streams of decompressed data.
[ "Given", "a", "gzipped", "stream", "of", "data", "yield", "streams", "of", "decompressed", "data", "." ]
960d6950b083e64c97d93e15443d486b52046a44
https://github.com/jaraco/jaraco.stream/blob/960d6950b083e64c97d93e15443d486b52046a44/jaraco/stream/gzip.py#L50-L62
239,770
jaraco/jaraco.stream
jaraco/stream/gzip.py
lines_from_stream
def lines_from_stream(chunks): """ Given data in chunks, yield lines of text """ buf = buffer.DecodingLineBuffer() for chunk in chunks: buf.feed(chunk) # when Python 3, yield from buf for _ in buf: yield _
python
def lines_from_stream(chunks): """ Given data in chunks, yield lines of text """ buf = buffer.DecodingLineBuffer() for chunk in chunks: buf.feed(chunk) # when Python 3, yield from buf for _ in buf: yield _
[ "def", "lines_from_stream", "(", "chunks", ")", ":", "buf", "=", "buffer", ".", "DecodingLineBuffer", "(", ")", "for", "chunk", "in", "chunks", ":", "buf", ".", "feed", "(", "chunk", ")", "# when Python 3, yield from buf", "for", "_", "in", "buf", ":", "yield", "_" ]
Given data in chunks, yield lines of text
[ "Given", "data", "in", "chunks", "yield", "lines", "of", "text" ]
960d6950b083e64c97d93e15443d486b52046a44
https://github.com/jaraco/jaraco.stream/blob/960d6950b083e64c97d93e15443d486b52046a44/jaraco/stream/gzip.py#L65-L74
239,771
TestInABox/stackInABox
stackinabox/util/requests_mock/core.py
session_registration
def session_registration(uri, session): """Requests-mock registration with a specific Session. :param uri: base URI to match against :param session: Python requests' Session object :returns: n/a """ # log the URI that is used to access the Stack-In-A-Box services logger.debug('Registering Stack-In-A-Box at {0} under Python Requests-Mock' .format(uri)) logger.debug('Session has id {0}'.format(id(session))) # tell Stack-In-A-Box what URI to match with StackInABox.update_uri(uri) # Create a Python Requests Adapter object for handling the session StackInABox.hold_onto('adapter', requests_mock.Adapter()) # Add the Request handler object for the URI StackInABox.hold_out('adapter').add_matcher(RequestMockCallable(uri)) # Tell the session about the adapter and the URI session.mount('http://{0}'.format(uri), StackInABox.hold_out('adapter')) session.mount('https://{0}'.format(uri), StackInABox.hold_out('adapter'))
python
def session_registration(uri, session): """Requests-mock registration with a specific Session. :param uri: base URI to match against :param session: Python requests' Session object :returns: n/a """ # log the URI that is used to access the Stack-In-A-Box services logger.debug('Registering Stack-In-A-Box at {0} under Python Requests-Mock' .format(uri)) logger.debug('Session has id {0}'.format(id(session))) # tell Stack-In-A-Box what URI to match with StackInABox.update_uri(uri) # Create a Python Requests Adapter object for handling the session StackInABox.hold_onto('adapter', requests_mock.Adapter()) # Add the Request handler object for the URI StackInABox.hold_out('adapter').add_matcher(RequestMockCallable(uri)) # Tell the session about the adapter and the URI session.mount('http://{0}'.format(uri), StackInABox.hold_out('adapter')) session.mount('https://{0}'.format(uri), StackInABox.hold_out('adapter'))
[ "def", "session_registration", "(", "uri", ",", "session", ")", ":", "# log the URI that is used to access the Stack-In-A-Box services", "logger", ".", "debug", "(", "'Registering Stack-In-A-Box at {0} under Python Requests-Mock'", ".", "format", "(", "uri", ")", ")", "logger", ".", "debug", "(", "'Session has id {0}'", ".", "format", "(", "id", "(", "session", ")", ")", ")", "# tell Stack-In-A-Box what URI to match with", "StackInABox", ".", "update_uri", "(", "uri", ")", "# Create a Python Requests Adapter object for handling the session", "StackInABox", ".", "hold_onto", "(", "'adapter'", ",", "requests_mock", ".", "Adapter", "(", ")", ")", "# Add the Request handler object for the URI", "StackInABox", ".", "hold_out", "(", "'adapter'", ")", ".", "add_matcher", "(", "RequestMockCallable", "(", "uri", ")", ")", "# Tell the session about the adapter and the URI", "session", ".", "mount", "(", "'http://{0}'", ".", "format", "(", "uri", ")", ",", "StackInABox", ".", "hold_out", "(", "'adapter'", ")", ")", "session", ".", "mount", "(", "'https://{0}'", ".", "format", "(", "uri", ")", ",", "StackInABox", ".", "hold_out", "(", "'adapter'", ")", ")" ]
Requests-mock registration with a specific Session. :param uri: base URI to match against :param session: Python requests' Session object :returns: n/a
[ "Requests", "-", "mock", "registration", "with", "a", "specific", "Session", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L161-L184
239,772
TestInABox/stackInABox
stackinabox/util/requests_mock/core.py
requests_request
def requests_request(method, url, **kwargs): """Requests-mock requests.request wrapper.""" session = local_sessions.session response = session.request(method=method, url=url, **kwargs) session.close() return response
python
def requests_request(method, url, **kwargs): """Requests-mock requests.request wrapper.""" session = local_sessions.session response = session.request(method=method, url=url, **kwargs) session.close() return response
[ "def", "requests_request", "(", "method", ",", "url", ",", "*", "*", "kwargs", ")", ":", "session", "=", "local_sessions", ".", "session", "response", "=", "session", ".", "request", "(", "method", "=", "method", ",", "url", "=", "url", ",", "*", "*", "kwargs", ")", "session", ".", "close", "(", ")", "return", "response" ]
Requests-mock requests.request wrapper.
[ "Requests", "-", "mock", "requests", ".", "request", "wrapper", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L200-L205
239,773
TestInABox/stackInABox
stackinabox/util/requests_mock/core.py
requests_post
def requests_post(url, data=None, json=None, **kwargs): """Requests-mock requests.post wrapper.""" return requests_request('post', url, data=data, json=json, **kwargs)
python
def requests_post(url, data=None, json=None, **kwargs): """Requests-mock requests.post wrapper.""" return requests_request('post', url, data=data, json=json, **kwargs)
[ "def", "requests_post", "(", "url", ",", "data", "=", "None", ",", "json", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "requests_request", "(", "'post'", ",", "url", ",", "data", "=", "data", ",", "json", "=", "json", ",", "*", "*", "kwargs", ")" ]
Requests-mock requests.post wrapper.
[ "Requests", "-", "mock", "requests", ".", "post", "wrapper", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L226-L228
239,774
TestInABox/stackInABox
stackinabox/util/requests_mock/core.py
RequestMockCallable.get_reason_for_status
def get_reason_for_status(status_code): """Lookup the HTTP reason text for a given status code. :param status_code: int - HTTP status code :returns: string - HTTP reason text """ if status_code in requests.status_codes.codes: return requests.status_codes._codes[status_code][0].replace('_', ' ') else: return 'Unknown status code - {0}'.format(status_code)
python
def get_reason_for_status(status_code): """Lookup the HTTP reason text for a given status code. :param status_code: int - HTTP status code :returns: string - HTTP reason text """ if status_code in requests.status_codes.codes: return requests.status_codes._codes[status_code][0].replace('_', ' ') else: return 'Unknown status code - {0}'.format(status_code)
[ "def", "get_reason_for_status", "(", "status_code", ")", ":", "if", "status_code", "in", "requests", ".", "status_codes", ".", "codes", ":", "return", "requests", ".", "status_codes", ".", "_codes", "[", "status_code", "]", "[", "0", "]", ".", "replace", "(", "'_'", ",", "' '", ")", "else", ":", "return", "'Unknown status code - {0}'", ".", "format", "(", "status_code", ")" ]
Lookup the HTTP reason text for a given status code. :param status_code: int - HTTP status code :returns: string - HTTP reason text
[ "Lookup", "the", "HTTP", "reason", "text", "for", "a", "given", "status", "code", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L63-L75
239,775
TestInABox/stackInABox
stackinabox/util/requests_mock/core.py
RequestMockCallable.split_status
def split_status(status): """Split a HTTP Status and Reason code string into a tuple. :param status string containing the status and reason text or the integer of the status code :returns: tuple - (int, string) containing the integer status code and reason text string """ # If the status is an integer, then lookup the reason text if isinstance(status, int): return (status, RequestMockCallable.get_reason_for_status( status)) # otherwise, ensure it is a string and try to split it based on the # standard HTTP status and reason text format elif isinstance(status, str) or isinstance(status, bytes): code, reason = status.split(' ', 1) return (code, reason) # otherwise, return with a default reason code else: return (status, 'Unknown')
python
def split_status(status): """Split a HTTP Status and Reason code string into a tuple. :param status string containing the status and reason text or the integer of the status code :returns: tuple - (int, string) containing the integer status code and reason text string """ # If the status is an integer, then lookup the reason text if isinstance(status, int): return (status, RequestMockCallable.get_reason_for_status( status)) # otherwise, ensure it is a string and try to split it based on the # standard HTTP status and reason text format elif isinstance(status, str) or isinstance(status, bytes): code, reason = status.split(' ', 1) return (code, reason) # otherwise, return with a default reason code else: return (status, 'Unknown')
[ "def", "split_status", "(", "status", ")", ":", "# If the status is an integer, then lookup the reason text", "if", "isinstance", "(", "status", ",", "int", ")", ":", "return", "(", "status", ",", "RequestMockCallable", ".", "get_reason_for_status", "(", "status", ")", ")", "# otherwise, ensure it is a string and try to split it based on the", "# standard HTTP status and reason text format", "elif", "isinstance", "(", "status", ",", "str", ")", "or", "isinstance", "(", "status", ",", "bytes", ")", ":", "code", ",", "reason", "=", "status", ".", "split", "(", "' '", ",", "1", ")", "return", "(", "code", ",", "reason", ")", "# otherwise, return with a default reason code", "else", ":", "return", "(", "status", ",", "'Unknown'", ")" ]
Split a HTTP Status and Reason code string into a tuple. :param status string containing the status and reason text or the integer of the status code :returns: tuple - (int, string) containing the integer status code and reason text string
[ "Split", "a", "HTTP", "Status", "and", "Reason", "code", "string", "into", "a", "tuple", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L78-L101
239,776
TestInABox/stackInABox
stackinabox/util/requests_mock/core.py
RequestMockCallable.handle
def handle(self, request, uri): """Request handler interface. :param request: Python requests Request object :param uri: URI of the request """ # Convert the call over to Stack-In-A-Box method = request.method headers = CaseInsensitiveDict() request_headers = CaseInsensitiveDict() request_headers.update(request.headers) request.headers = request_headers stackinabox_result = StackInABox.call_into(method, request, uri, headers) # reformat the result for easier use status_code, output_headers, body = stackinabox_result json_data = None text_data = None content_data = None body_data = None # if the body is a string-type... if isinstance(body, six.string_types): # Try to convert it to JSON text_data = body try: json_data = json.dumps(text_data) text_data = json_data except Exception: json_data = None text_data = body # if the body is binary, then it's the content elif isinstance(body, six.binary_type): content_data = body # by default, it's just body data else: # default to body data body_data = body # build the Python requests' Response object return requests_mock.response.create_response( request, headers=output_headers, status_code=status_code, body=body_data, json=json_data, text=text_data, content=content_data )
python
def handle(self, request, uri): """Request handler interface. :param request: Python requests Request object :param uri: URI of the request """ # Convert the call over to Stack-In-A-Box method = request.method headers = CaseInsensitiveDict() request_headers = CaseInsensitiveDict() request_headers.update(request.headers) request.headers = request_headers stackinabox_result = StackInABox.call_into(method, request, uri, headers) # reformat the result for easier use status_code, output_headers, body = stackinabox_result json_data = None text_data = None content_data = None body_data = None # if the body is a string-type... if isinstance(body, six.string_types): # Try to convert it to JSON text_data = body try: json_data = json.dumps(text_data) text_data = json_data except Exception: json_data = None text_data = body # if the body is binary, then it's the content elif isinstance(body, six.binary_type): content_data = body # by default, it's just body data else: # default to body data body_data = body # build the Python requests' Response object return requests_mock.response.create_response( request, headers=output_headers, status_code=status_code, body=body_data, json=json_data, text=text_data, content=content_data )
[ "def", "handle", "(", "self", ",", "request", ",", "uri", ")", ":", "# Convert the call over to Stack-In-A-Box", "method", "=", "request", ".", "method", "headers", "=", "CaseInsensitiveDict", "(", ")", "request_headers", "=", "CaseInsensitiveDict", "(", ")", "request_headers", ".", "update", "(", "request", ".", "headers", ")", "request", ".", "headers", "=", "request_headers", "stackinabox_result", "=", "StackInABox", ".", "call_into", "(", "method", ",", "request", ",", "uri", ",", "headers", ")", "# reformat the result for easier use", "status_code", ",", "output_headers", ",", "body", "=", "stackinabox_result", "json_data", "=", "None", "text_data", "=", "None", "content_data", "=", "None", "body_data", "=", "None", "# if the body is a string-type...", "if", "isinstance", "(", "body", ",", "six", ".", "string_types", ")", ":", "# Try to convert it to JSON", "text_data", "=", "body", "try", ":", "json_data", "=", "json", ".", "dumps", "(", "text_data", ")", "text_data", "=", "json_data", "except", "Exception", ":", "json_data", "=", "None", "text_data", "=", "body", "# if the body is binary, then it's the content", "elif", "isinstance", "(", "body", ",", "six", ".", "binary_type", ")", ":", "content_data", "=", "body", "# by default, it's just body data", "else", ":", "# default to body data", "body_data", "=", "body", "# build the Python requests' Response object", "return", "requests_mock", ".", "response", ".", "create_response", "(", "request", ",", "headers", "=", "output_headers", ",", "status_code", "=", "status_code", ",", "body", "=", "body_data", ",", "json", "=", "json_data", ",", "text", "=", "text_data", ",", "content", "=", "content_data", ")" ]
Request handler interface. :param request: Python requests Request object :param uri: URI of the request
[ "Request", "handler", "interface", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L103-L158
239,777
changecoin/changetip-python
changetip/bots/base.py
BaseBot.send_tip
def send_tip(self, sender, receiver, message, context_uid, meta): """ Send a request to the ChangeTip API, to be delivered immediately. """ assert self.channel is not None, "channel must be defined" # Add extra data to meta meta["mention_bot"] = self.mention_bot() data = json.dumps({ "channel": self.channel, "sender": sender, "receiver": receiver, "message": message, "context_uid": context_uid, "meta": meta, }) response = requests.post(self.get_api_url("/tips/"), data=data, headers={'content-type': 'application/json'}) if response.headers.get("Content-Type", None) == "application/json": out = response.json() out["state"] = response.reason.lower() return out else: return {"state": response.reason.lower(), "error": "%s error submitting tip" % response.status_code}
python
def send_tip(self, sender, receiver, message, context_uid, meta): """ Send a request to the ChangeTip API, to be delivered immediately. """ assert self.channel is not None, "channel must be defined" # Add extra data to meta meta["mention_bot"] = self.mention_bot() data = json.dumps({ "channel": self.channel, "sender": sender, "receiver": receiver, "message": message, "context_uid": context_uid, "meta": meta, }) response = requests.post(self.get_api_url("/tips/"), data=data, headers={'content-type': 'application/json'}) if response.headers.get("Content-Type", None) == "application/json": out = response.json() out["state"] = response.reason.lower() return out else: return {"state": response.reason.lower(), "error": "%s error submitting tip" % response.status_code}
[ "def", "send_tip", "(", "self", ",", "sender", ",", "receiver", ",", "message", ",", "context_uid", ",", "meta", ")", ":", "assert", "self", ".", "channel", "is", "not", "None", ",", "\"channel must be defined\"", "# Add extra data to meta", "meta", "[", "\"mention_bot\"", "]", "=", "self", ".", "mention_bot", "(", ")", "data", "=", "json", ".", "dumps", "(", "{", "\"channel\"", ":", "self", ".", "channel", ",", "\"sender\"", ":", "sender", ",", "\"receiver\"", ":", "receiver", ",", "\"message\"", ":", "message", ",", "\"context_uid\"", ":", "context_uid", ",", "\"meta\"", ":", "meta", ",", "}", ")", "response", "=", "requests", ".", "post", "(", "self", ".", "get_api_url", "(", "\"/tips/\"", ")", ",", "data", "=", "data", ",", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", ")", "if", "response", ".", "headers", ".", "get", "(", "\"Content-Type\"", ",", "None", ")", "==", "\"application/json\"", ":", "out", "=", "response", ".", "json", "(", ")", "out", "[", "\"state\"", "]", "=", "response", ".", "reason", ".", "lower", "(", ")", "return", "out", "else", ":", "return", "{", "\"state\"", ":", "response", ".", "reason", ".", "lower", "(", ")", ",", "\"error\"", ":", "\"%s error submitting tip\"", "%", "response", ".", "status_code", "}" ]
Send a request to the ChangeTip API, to be delivered immediately.
[ "Send", "a", "request", "to", "the", "ChangeTip", "API", "to", "be", "delivered", "immediately", "." ]
daa6e2f41712eb58d16c537af34f9f0a1b74a14e
https://github.com/changecoin/changetip-python/blob/daa6e2f41712eb58d16c537af34f9f0a1b74a14e/changetip/bots/base.py#L49-L70
239,778
bear/ninka
ninka/micropub.py
discoverEndpoint
def discoverEndpoint(domain, endpoint, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True): """Find the given endpoint for the given domain. Only scan html element matching all criteria in look_in. optionally the content to be scanned can be given as an argument. :param domain: the URL of the domain to handle :param endpoint: list of endpoints to look for :param content: the content to be scanned for the endpoint :param look_in: dictionary with name, id and class_. only element matching all of these will be scanned :param test_urls: optional flag to test URLs for validation :param validateCerts: optional flag to enforce HTTPS certificates if present :rtype: list of endpoints """ if test_urls: ronkyuu.URLValidator(message='invalid domain URL')(domain) if content: result = {'status': requests.codes.ok, 'headers': None, 'content': content } else: r = requests.get(domain, verify=validateCerts) result = {'status': r.status_code, 'headers': r.headers } # check for character encodings and use 'correct' data if 'charset' in r.headers.get('content-type', ''): result['content'] = r.text else: result['content'] = r.content for key in endpoint: result.update({key: set()}) result.update({'domain': domain}) if result['status'] == requests.codes.ok: if 'link' in r.headers: all_links = r.headers['link'].split(',', 1) for link in all_links: if ';' in link: href, rel = link.split(';') url = urlparse(href.strip()[1:-1]) if url.scheme in ('http', 'https') and rel in endpoint: result[rel].add(url) all_links = BeautifulSoup(result['content'], _html_parser, parse_only=SoupStrainer(**look_in)).find_all('link') for link in all_links: rel = link.get('rel', None)[0] if rel in endpoint: href = link.get('href', None) if href: url = urlparse(href) if url.scheme == '' or url.netloc == '': url = urlparse(urljoin(domain, href)) if url.scheme in ('http', 'https'): result[rel].add(url) return result
python
def discoverEndpoint(domain, endpoint, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True): """Find the given endpoint for the given domain. Only scan html element matching all criteria in look_in. optionally the content to be scanned can be given as an argument. :param domain: the URL of the domain to handle :param endpoint: list of endpoints to look for :param content: the content to be scanned for the endpoint :param look_in: dictionary with name, id and class_. only element matching all of these will be scanned :param test_urls: optional flag to test URLs for validation :param validateCerts: optional flag to enforce HTTPS certificates if present :rtype: list of endpoints """ if test_urls: ronkyuu.URLValidator(message='invalid domain URL')(domain) if content: result = {'status': requests.codes.ok, 'headers': None, 'content': content } else: r = requests.get(domain, verify=validateCerts) result = {'status': r.status_code, 'headers': r.headers } # check for character encodings and use 'correct' data if 'charset' in r.headers.get('content-type', ''): result['content'] = r.text else: result['content'] = r.content for key in endpoint: result.update({key: set()}) result.update({'domain': domain}) if result['status'] == requests.codes.ok: if 'link' in r.headers: all_links = r.headers['link'].split(',', 1) for link in all_links: if ';' in link: href, rel = link.split(';') url = urlparse(href.strip()[1:-1]) if url.scheme in ('http', 'https') and rel in endpoint: result[rel].add(url) all_links = BeautifulSoup(result['content'], _html_parser, parse_only=SoupStrainer(**look_in)).find_all('link') for link in all_links: rel = link.get('rel', None)[0] if rel in endpoint: href = link.get('href', None) if href: url = urlparse(href) if url.scheme == '' or url.netloc == '': url = urlparse(urljoin(domain, href)) if url.scheme in ('http', 'https'): result[rel].add(url) return result
[ "def", "discoverEndpoint", "(", "domain", ",", "endpoint", ",", "content", "=", "None", ",", "look_in", "=", "{", "'name'", ":", "'link'", "}", ",", "test_urls", "=", "True", ",", "validateCerts", "=", "True", ")", ":", "if", "test_urls", ":", "ronkyuu", ".", "URLValidator", "(", "message", "=", "'invalid domain URL'", ")", "(", "domain", ")", "if", "content", ":", "result", "=", "{", "'status'", ":", "requests", ".", "codes", ".", "ok", ",", "'headers'", ":", "None", ",", "'content'", ":", "content", "}", "else", ":", "r", "=", "requests", ".", "get", "(", "domain", ",", "verify", "=", "validateCerts", ")", "result", "=", "{", "'status'", ":", "r", ".", "status_code", ",", "'headers'", ":", "r", ".", "headers", "}", "# check for character encodings and use 'correct' data", "if", "'charset'", "in", "r", ".", "headers", ".", "get", "(", "'content-type'", ",", "''", ")", ":", "result", "[", "'content'", "]", "=", "r", ".", "text", "else", ":", "result", "[", "'content'", "]", "=", "r", ".", "content", "for", "key", "in", "endpoint", ":", "result", ".", "update", "(", "{", "key", ":", "set", "(", ")", "}", ")", "result", ".", "update", "(", "{", "'domain'", ":", "domain", "}", ")", "if", "result", "[", "'status'", "]", "==", "requests", ".", "codes", ".", "ok", ":", "if", "'link'", "in", "r", ".", "headers", ":", "all_links", "=", "r", ".", "headers", "[", "'link'", "]", ".", "split", "(", "','", ",", "1", ")", "for", "link", "in", "all_links", ":", "if", "';'", "in", "link", ":", "href", ",", "rel", "=", "link", ".", "split", "(", "';'", ")", "url", "=", "urlparse", "(", "href", ".", "strip", "(", ")", "[", "1", ":", "-", "1", "]", ")", "if", "url", ".", "scheme", "in", "(", "'http'", ",", "'https'", ")", "and", "rel", "in", "endpoint", ":", "result", "[", "rel", "]", ".", "add", "(", "url", ")", "all_links", "=", "BeautifulSoup", "(", "result", "[", "'content'", "]", ",", "_html_parser", ",", "parse_only", "=", "SoupStrainer", "(", "*", "*", "look_in", ")", ")", ".", "find_all", "(", "'link'", ")", "for", "link", "in", "all_links", ":", "rel", "=", "link", ".", "get", "(", "'rel'", ",", "None", ")", "[", "0", "]", "if", "rel", "in", "endpoint", ":", "href", "=", "link", ".", "get", "(", "'href'", ",", "None", ")", "if", "href", ":", "url", "=", "urlparse", "(", "href", ")", "if", "url", ".", "scheme", "==", "''", "or", "url", ".", "netloc", "==", "''", ":", "url", "=", "urlparse", "(", "urljoin", "(", "domain", ",", "href", ")", ")", "if", "url", ".", "scheme", "in", "(", "'http'", ",", "'https'", ")", ":", "result", "[", "rel", "]", ".", "add", "(", "url", ")", "return", "result" ]
Find the given endpoint for the given domain. Only scan html element matching all criteria in look_in. optionally the content to be scanned can be given as an argument. :param domain: the URL of the domain to handle :param endpoint: list of endpoints to look for :param content: the content to be scanned for the endpoint :param look_in: dictionary with name, id and class_. only element matching all of these will be scanned :param test_urls: optional flag to test URLs for validation :param validateCerts: optional flag to enforce HTTPS certificates if present :rtype: list of endpoints
[ "Find", "the", "given", "endpoint", "for", "the", "given", "domain", ".", "Only", "scan", "html", "element", "matching", "all", "criteria", "in", "look_in", "." ]
4d13a48d2b8857496f7fc470b0c379486351c89b
https://github.com/bear/ninka/blob/4d13a48d2b8857496f7fc470b0c379486351c89b/ninka/micropub.py#L31-L89
239,779
bear/ninka
ninka/micropub.py
discoverMicropubEndpoints
def discoverMicropubEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True): """Find the micropub for the given domain. Only scan html element matching all criteria in look_in. optionally the content to be scanned can be given as an argument. :param domain: the URL of the domain to handle :param content: the content to be scanned for the endpoint :param look_in: dictionary with name, id and class_. only element matching all of these will be scanned :param test_urls: optional flag to test URLs for validation :param validateCerts: optional flag to enforce HTTPS certificates if present :rtype: list of endpoints """ return discoverEndpoint(domain, ('micropub',), content, look_in, test_urls, validateCerts)
python
def discoverMicropubEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True): """Find the micropub for the given domain. Only scan html element matching all criteria in look_in. optionally the content to be scanned can be given as an argument. :param domain: the URL of the domain to handle :param content: the content to be scanned for the endpoint :param look_in: dictionary with name, id and class_. only element matching all of these will be scanned :param test_urls: optional flag to test URLs for validation :param validateCerts: optional flag to enforce HTTPS certificates if present :rtype: list of endpoints """ return discoverEndpoint(domain, ('micropub',), content, look_in, test_urls, validateCerts)
[ "def", "discoverMicropubEndpoints", "(", "domain", ",", "content", "=", "None", ",", "look_in", "=", "{", "'name'", ":", "'link'", "}", ",", "test_urls", "=", "True", ",", "validateCerts", "=", "True", ")", ":", "return", "discoverEndpoint", "(", "domain", ",", "(", "'micropub'", ",", ")", ",", "content", ",", "look_in", ",", "test_urls", ",", "validateCerts", ")" ]
Find the micropub for the given domain. Only scan html element matching all criteria in look_in. optionally the content to be scanned can be given as an argument. :param domain: the URL of the domain to handle :param content: the content to be scanned for the endpoint :param look_in: dictionary with name, id and class_. only element matching all of these will be scanned :param test_urls: optional flag to test URLs for validation :param validateCerts: optional flag to enforce HTTPS certificates if present :rtype: list of endpoints
[ "Find", "the", "micropub", "for", "the", "given", "domain", ".", "Only", "scan", "html", "element", "matching", "all", "criteria", "in", "look_in", "." ]
4d13a48d2b8857496f7fc470b0c379486351c89b
https://github.com/bear/ninka/blob/4d13a48d2b8857496f7fc470b0c379486351c89b/ninka/micropub.py#L91-L104
239,780
bear/ninka
ninka/micropub.py
discoverTokenEndpoints
def discoverTokenEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True): """Find the token for the given domain. Only scan html element matching all criteria in look_in. optionally the content to be scanned can be given as an argument. :param domain: the URL of the domain to handle :param content: the content to be scanned for the endpoint :param look_in: dictionary with name, id and class_. only element matching all of these will be scanned :param test_urls: optional flag to test URLs for validation :param validateCerts: optional flag to enforce HTTPS certificates if present :rtype: list of endpoints """ return discoverEndpoint(domain, ('token_endpoint',), content, look_in, test_urls, validateCerts)
python
def discoverTokenEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True): """Find the token for the given domain. Only scan html element matching all criteria in look_in. optionally the content to be scanned can be given as an argument. :param domain: the URL of the domain to handle :param content: the content to be scanned for the endpoint :param look_in: dictionary with name, id and class_. only element matching all of these will be scanned :param test_urls: optional flag to test URLs for validation :param validateCerts: optional flag to enforce HTTPS certificates if present :rtype: list of endpoints """ return discoverEndpoint(domain, ('token_endpoint',), content, look_in, test_urls, validateCerts)
[ "def", "discoverTokenEndpoints", "(", "domain", ",", "content", "=", "None", ",", "look_in", "=", "{", "'name'", ":", "'link'", "}", ",", "test_urls", "=", "True", ",", "validateCerts", "=", "True", ")", ":", "return", "discoverEndpoint", "(", "domain", ",", "(", "'token_endpoint'", ",", ")", ",", "content", ",", "look_in", ",", "test_urls", ",", "validateCerts", ")" ]
Find the token for the given domain. Only scan html element matching all criteria in look_in. optionally the content to be scanned can be given as an argument. :param domain: the URL of the domain to handle :param content: the content to be scanned for the endpoint :param look_in: dictionary with name, id and class_. only element matching all of these will be scanned :param test_urls: optional flag to test URLs for validation :param validateCerts: optional flag to enforce HTTPS certificates if present :rtype: list of endpoints
[ "Find", "the", "token", "for", "the", "given", "domain", ".", "Only", "scan", "html", "element", "matching", "all", "criteria", "in", "look_in", "." ]
4d13a48d2b8857496f7fc470b0c379486351c89b
https://github.com/bear/ninka/blob/4d13a48d2b8857496f7fc470b0c379486351c89b/ninka/micropub.py#L106-L119
239,781
siemens/django-dingos
dingos/core/http_helpers.py
get_query_string
def get_query_string(request, new_params=None, remove=None): """ Given the request, return the query string. Parameters can be added or removed as necessary. Code snippet taken from Django admin app (views/main.py) (c) Copyright Django Software Foundation and individual contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Django nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ if new_params is None: new_params = {} if remove is None: remove = [] p = dict(request.GET.items()) for r in remove: for k in p.keys(): if k.startswith(r): del p[k] for k, v in new_params.items(): if v is None: if k in p: del p[k] else: p[k] = v return '?%s' % urlencode(p)
python
def get_query_string(request, new_params=None, remove=None): """ Given the request, return the query string. Parameters can be added or removed as necessary. Code snippet taken from Django admin app (views/main.py) (c) Copyright Django Software Foundation and individual contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Django nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ if new_params is None: new_params = {} if remove is None: remove = [] p = dict(request.GET.items()) for r in remove: for k in p.keys(): if k.startswith(r): del p[k] for k, v in new_params.items(): if v is None: if k in p: del p[k] else: p[k] = v return '?%s' % urlencode(p)
[ "def", "get_query_string", "(", "request", ",", "new_params", "=", "None", ",", "remove", "=", "None", ")", ":", "if", "new_params", "is", "None", ":", "new_params", "=", "{", "}", "if", "remove", "is", "None", ":", "remove", "=", "[", "]", "p", "=", "dict", "(", "request", ".", "GET", ".", "items", "(", ")", ")", "for", "r", "in", "remove", ":", "for", "k", "in", "p", ".", "keys", "(", ")", ":", "if", "k", ".", "startswith", "(", "r", ")", ":", "del", "p", "[", "k", "]", "for", "k", ",", "v", "in", "new_params", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "if", "k", "in", "p", ":", "del", "p", "[", "k", "]", "else", ":", "p", "[", "k", "]", "=", "v", "return", "'?%s'", "%", "urlencode", "(", "p", ")" ]
Given the request, return the query string. Parameters can be added or removed as necessary. Code snippet taken from Django admin app (views/main.py) (c) Copyright Django Software Foundation and individual contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Django nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[ "Given", "the", "request", "return", "the", "query", "string", "." ]
7154f75b06d2538568e2f2455a76f3d0db0b7d70
https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/http_helpers.py#L22-L71
239,782
koriakin/binflakes
binflakes/sexpr/nodes.py
form_node
def form_node(cls): """A class decorator to finalize fully derived FormNode subclasses.""" assert issubclass(cls, FormNode) res = attrs(init=False, slots=True)(cls) res._args = [] res._required_args = 0 res._rest_arg = None state = _FormArgMode.REQUIRED for field in fields(res): if 'arg_mode' in field.metadata: if state is _FormArgMode.REST: raise RuntimeError('rest argument must be last') if field.metadata['arg_mode'] is _FormArgMode.REQUIRED: if state is _FormArgMode.OPTIONAL: raise RuntimeError('required arg after optional arg') res._args.append(field) res._required_args += 1 elif field.metadata['arg_mode'] is _FormArgMode.OPTIONAL: state = _FormArgMode.OPTIONAL res._args.append(field) elif field.metadata['arg_mode'] is _FormArgMode.REST: state = _FormArgMode.REST res._rest_arg = field else: assert 0 return res
python
def form_node(cls): """A class decorator to finalize fully derived FormNode subclasses.""" assert issubclass(cls, FormNode) res = attrs(init=False, slots=True)(cls) res._args = [] res._required_args = 0 res._rest_arg = None state = _FormArgMode.REQUIRED for field in fields(res): if 'arg_mode' in field.metadata: if state is _FormArgMode.REST: raise RuntimeError('rest argument must be last') if field.metadata['arg_mode'] is _FormArgMode.REQUIRED: if state is _FormArgMode.OPTIONAL: raise RuntimeError('required arg after optional arg') res._args.append(field) res._required_args += 1 elif field.metadata['arg_mode'] is _FormArgMode.OPTIONAL: state = _FormArgMode.OPTIONAL res._args.append(field) elif field.metadata['arg_mode'] is _FormArgMode.REST: state = _FormArgMode.REST res._rest_arg = field else: assert 0 return res
[ "def", "form_node", "(", "cls", ")", ":", "assert", "issubclass", "(", "cls", ",", "FormNode", ")", "res", "=", "attrs", "(", "init", "=", "False", ",", "slots", "=", "True", ")", "(", "cls", ")", "res", ".", "_args", "=", "[", "]", "res", ".", "_required_args", "=", "0", "res", ".", "_rest_arg", "=", "None", "state", "=", "_FormArgMode", ".", "REQUIRED", "for", "field", "in", "fields", "(", "res", ")", ":", "if", "'arg_mode'", "in", "field", ".", "metadata", ":", "if", "state", "is", "_FormArgMode", ".", "REST", ":", "raise", "RuntimeError", "(", "'rest argument must be last'", ")", "if", "field", ".", "metadata", "[", "'arg_mode'", "]", "is", "_FormArgMode", ".", "REQUIRED", ":", "if", "state", "is", "_FormArgMode", ".", "OPTIONAL", ":", "raise", "RuntimeError", "(", "'required arg after optional arg'", ")", "res", ".", "_args", ".", "append", "(", "field", ")", "res", ".", "_required_args", "+=", "1", "elif", "field", ".", "metadata", "[", "'arg_mode'", "]", "is", "_FormArgMode", ".", "OPTIONAL", ":", "state", "=", "_FormArgMode", ".", "OPTIONAL", "res", ".", "_args", ".", "append", "(", "field", ")", "elif", "field", ".", "metadata", "[", "'arg_mode'", "]", "is", "_FormArgMode", ".", "REST", ":", "state", "=", "_FormArgMode", ".", "REST", "res", ".", "_rest_arg", "=", "field", "else", ":", "assert", "0", "return", "res" ]
A class decorator to finalize fully derived FormNode subclasses.
[ "A", "class", "decorator", "to", "finalize", "fully", "derived", "FormNode", "subclasses", "." ]
f059cecadf1c605802a713c62375b5bd5606d53f
https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/sexpr/nodes.py#L222-L247
239,783
host-anshu/simpleInterceptor
interceptor.py
intercept
def intercept(aspects): """Decorate class to intercept its matching methods and apply advices on them. Advices are the cross-cutting concerns that need to be separated out from the business logic. This decorator applies such advices to the decorated class. :arg aspects: mapping of joint-points to dictionary of advices. joint-points are regex patterns to be matched against methods of class. If the pattern matches to name of a method, the advices available for the joint-point are applied to the method. Advices from all matching joint-points are applied to the method. In case of conflicting advices for a joint-point, joint-point exactly matching the name of the method is given preference. Following are the identified advices: before: Runs before around before around_before: Runs before the method after_exc: Runs when method encounters exception around_after: Runs after method is successful after_success: Runs after method is successful after_finally: Runs after method is run successfully or unsuccessfully. """ if not isinstance(aspects, dict): raise TypeError("Aspects must be a dictionary of joint-points and advices") def get_matching_advices(name): """Get all advices matching method name""" all_advices = dict() for joint_point, advices in aspects.iteritems(): if re.match(joint_point, name): for advice, impl in advices.items(): # Whole word matching regex might have \b around. if advice in all_advices and joint_point.strip(r'\b') != name: # Give priority to exactly matching method joint-points over wild-card # joint points. continue all_advices[advice] = impl return all_advices def apply_advices(advices): """Decorating method""" def decorate(method): # pylint: disable=C0111 @wraps(method) def trivial(self, *arg, **kw): # pylint: disable=C0111 def run_advices(advice, extra_arg=None): """Run all the advices for the joint-point""" if advice not in advices: return advice_impl = advices[advice] if not isinstance(advice_impl, (list, tuple, set)): advice_impl = [advice_impl] for impl in advice_impl: impl(self, method, extra_arg, *arg, **kw) run_advices('before') run_advices('around_before') try: if method.__self__ is None: ret = method(self, *arg, **kw) else: # classmethods ret = method(*arg, **kw) except Exception as e: # pylint: disable=W0703 run_advices('after_exc', e) ret = None raise e else: run_advices('around_after', ret) run_advices('after_success', ret) finally: run_advices('after_finally', ret) return ret return trivial return decorate def decorate_class(cls): """Decorating class""" # TODO: handle staticmethods for name, method in inspect.getmembers(cls, inspect.ismethod): if method.__self__ is not None: # TODO: handle classmethods continue if name not in ('__init__',) and name.startswith('__'): continue matching_advices = get_matching_advices(name) if not matching_advices: continue setattr(cls, name, apply_advices(matching_advices)(method)) return cls return decorate_class
python
def intercept(aspects): """Decorate class to intercept its matching methods and apply advices on them. Advices are the cross-cutting concerns that need to be separated out from the business logic. This decorator applies such advices to the decorated class. :arg aspects: mapping of joint-points to dictionary of advices. joint-points are regex patterns to be matched against methods of class. If the pattern matches to name of a method, the advices available for the joint-point are applied to the method. Advices from all matching joint-points are applied to the method. In case of conflicting advices for a joint-point, joint-point exactly matching the name of the method is given preference. Following are the identified advices: before: Runs before around before around_before: Runs before the method after_exc: Runs when method encounters exception around_after: Runs after method is successful after_success: Runs after method is successful after_finally: Runs after method is run successfully or unsuccessfully. """ if not isinstance(aspects, dict): raise TypeError("Aspects must be a dictionary of joint-points and advices") def get_matching_advices(name): """Get all advices matching method name""" all_advices = dict() for joint_point, advices in aspects.iteritems(): if re.match(joint_point, name): for advice, impl in advices.items(): # Whole word matching regex might have \b around. if advice in all_advices and joint_point.strip(r'\b') != name: # Give priority to exactly matching method joint-points over wild-card # joint points. continue all_advices[advice] = impl return all_advices def apply_advices(advices): """Decorating method""" def decorate(method): # pylint: disable=C0111 @wraps(method) def trivial(self, *arg, **kw): # pylint: disable=C0111 def run_advices(advice, extra_arg=None): """Run all the advices for the joint-point""" if advice not in advices: return advice_impl = advices[advice] if not isinstance(advice_impl, (list, tuple, set)): advice_impl = [advice_impl] for impl in advice_impl: impl(self, method, extra_arg, *arg, **kw) run_advices('before') run_advices('around_before') try: if method.__self__ is None: ret = method(self, *arg, **kw) else: # classmethods ret = method(*arg, **kw) except Exception as e: # pylint: disable=W0703 run_advices('after_exc', e) ret = None raise e else: run_advices('around_after', ret) run_advices('after_success', ret) finally: run_advices('after_finally', ret) return ret return trivial return decorate def decorate_class(cls): """Decorating class""" # TODO: handle staticmethods for name, method in inspect.getmembers(cls, inspect.ismethod): if method.__self__ is not None: # TODO: handle classmethods continue if name not in ('__init__',) and name.startswith('__'): continue matching_advices = get_matching_advices(name) if not matching_advices: continue setattr(cls, name, apply_advices(matching_advices)(method)) return cls return decorate_class
[ "def", "intercept", "(", "aspects", ")", ":", "if", "not", "isinstance", "(", "aspects", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"Aspects must be a dictionary of joint-points and advices\"", ")", "def", "get_matching_advices", "(", "name", ")", ":", "\"\"\"Get all advices matching method name\"\"\"", "all_advices", "=", "dict", "(", ")", "for", "joint_point", ",", "advices", "in", "aspects", ".", "iteritems", "(", ")", ":", "if", "re", ".", "match", "(", "joint_point", ",", "name", ")", ":", "for", "advice", ",", "impl", "in", "advices", ".", "items", "(", ")", ":", "# Whole word matching regex might have \\b around.", "if", "advice", "in", "all_advices", "and", "joint_point", ".", "strip", "(", "r'\\b'", ")", "!=", "name", ":", "# Give priority to exactly matching method joint-points over wild-card", "# joint points.", "continue", "all_advices", "[", "advice", "]", "=", "impl", "return", "all_advices", "def", "apply_advices", "(", "advices", ")", ":", "\"\"\"Decorating method\"\"\"", "def", "decorate", "(", "method", ")", ":", "# pylint: disable=C0111", "@", "wraps", "(", "method", ")", "def", "trivial", "(", "self", ",", "*", "arg", ",", "*", "*", "kw", ")", ":", "# pylint: disable=C0111", "def", "run_advices", "(", "advice", ",", "extra_arg", "=", "None", ")", ":", "\"\"\"Run all the advices for the joint-point\"\"\"", "if", "advice", "not", "in", "advices", ":", "return", "advice_impl", "=", "advices", "[", "advice", "]", "if", "not", "isinstance", "(", "advice_impl", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "advice_impl", "=", "[", "advice_impl", "]", "for", "impl", "in", "advice_impl", ":", "impl", "(", "self", ",", "method", ",", "extra_arg", ",", "*", "arg", ",", "*", "*", "kw", ")", "run_advices", "(", "'before'", ")", "run_advices", "(", "'around_before'", ")", "try", ":", "if", "method", ".", "__self__", "is", "None", ":", "ret", "=", "method", "(", "self", ",", "*", "arg", ",", "*", "*", "kw", ")", "else", ":", "# classmethods", "ret", "=", "method", "(", "*", "arg", ",", "*", "*", "kw", ")", "except", "Exception", "as", "e", ":", "# pylint: disable=W0703", "run_advices", "(", "'after_exc'", ",", "e", ")", "ret", "=", "None", "raise", "e", "else", ":", "run_advices", "(", "'around_after'", ",", "ret", ")", "run_advices", "(", "'after_success'", ",", "ret", ")", "finally", ":", "run_advices", "(", "'after_finally'", ",", "ret", ")", "return", "ret", "return", "trivial", "return", "decorate", "def", "decorate_class", "(", "cls", ")", ":", "\"\"\"Decorating class\"\"\"", "# TODO: handle staticmethods", "for", "name", ",", "method", "in", "inspect", ".", "getmembers", "(", "cls", ",", "inspect", ".", "ismethod", ")", ":", "if", "method", ".", "__self__", "is", "not", "None", ":", "# TODO: handle classmethods", "continue", "if", "name", "not", "in", "(", "'__init__'", ",", ")", "and", "name", ".", "startswith", "(", "'__'", ")", ":", "continue", "matching_advices", "=", "get_matching_advices", "(", "name", ")", "if", "not", "matching_advices", ":", "continue", "setattr", "(", "cls", ",", "name", ",", "apply_advices", "(", "matching_advices", ")", "(", "method", ")", ")", "return", "cls", "return", "decorate_class" ]
Decorate class to intercept its matching methods and apply advices on them. Advices are the cross-cutting concerns that need to be separated out from the business logic. This decorator applies such advices to the decorated class. :arg aspects: mapping of joint-points to dictionary of advices. joint-points are regex patterns to be matched against methods of class. If the pattern matches to name of a method, the advices available for the joint-point are applied to the method. Advices from all matching joint-points are applied to the method. In case of conflicting advices for a joint-point, joint-point exactly matching the name of the method is given preference. Following are the identified advices: before: Runs before around before around_before: Runs before the method after_exc: Runs when method encounters exception around_after: Runs after method is successful after_success: Runs after method is successful after_finally: Runs after method is run successfully or unsuccessfully.
[ "Decorate", "class", "to", "intercept", "its", "matching", "methods", "and", "apply", "advices", "on", "them", "." ]
71238fed57c62b5f77ce32d0c9b98acad73ab6a8
https://github.com/host-anshu/simpleInterceptor/blob/71238fed57c62b5f77ce32d0c9b98acad73ab6a8/interceptor.py#L9-L95
239,784
mikeboers/sitetools
sitetools/environ.py
_get_diff
def _get_diff(environ, label, pop=False): """Get previously frozen key-value pairs. :param str label: The name for the frozen environment. :param bool pop: Destroy the freeze after use; only allow application once. :returns: ``dict`` of frozen values. """ if pop: blob = environ.pop(_variable_name(label), None) else: blob = environ.get(_variable_name(label)) return _loads(blob) if blob else {}
python
def _get_diff(environ, label, pop=False): """Get previously frozen key-value pairs. :param str label: The name for the frozen environment. :param bool pop: Destroy the freeze after use; only allow application once. :returns: ``dict`` of frozen values. """ if pop: blob = environ.pop(_variable_name(label), None) else: blob = environ.get(_variable_name(label)) return _loads(blob) if blob else {}
[ "def", "_get_diff", "(", "environ", ",", "label", ",", "pop", "=", "False", ")", ":", "if", "pop", ":", "blob", "=", "environ", ".", "pop", "(", "_variable_name", "(", "label", ")", ",", "None", ")", "else", ":", "blob", "=", "environ", ".", "get", "(", "_variable_name", "(", "label", ")", ")", "return", "_loads", "(", "blob", ")", "if", "blob", "else", "{", "}" ]
Get previously frozen key-value pairs. :param str label: The name for the frozen environment. :param bool pop: Destroy the freeze after use; only allow application once. :returns: ``dict`` of frozen values.
[ "Get", "previously", "frozen", "key", "-", "value", "pairs", "." ]
1ec4eea6902b4a276f868a711b783dd965c123b7
https://github.com/mikeboers/sitetools/blob/1ec4eea6902b4a276f868a711b783dd965c123b7/sitetools/environ.py#L100-L113
239,785
mikeboers/sitetools
sitetools/environ.py
_apply_diff
def _apply_diff(environ, diff): """Apply a frozen environment. :param dict diff: key-value pairs to apply to the environment. :returns: A dict of the key-value pairs that are being changed. """ original = {} if diff: for k, v in diff.iteritems(): if v is None: log.log(5, 'unset %s', k) else: log.log(5, '%s="%s"', k, v) original[k] = environ.get(k) if original[k] is None: log.log(1, '%s was not set', k) else: log.log(1, '%s was "%s"', k, original[k]) if v is None: environ.pop(k, None) else: environ[k] = v else: log.log(5, 'nothing to apply') return original
python
def _apply_diff(environ, diff): """Apply a frozen environment. :param dict diff: key-value pairs to apply to the environment. :returns: A dict of the key-value pairs that are being changed. """ original = {} if diff: for k, v in diff.iteritems(): if v is None: log.log(5, 'unset %s', k) else: log.log(5, '%s="%s"', k, v) original[k] = environ.get(k) if original[k] is None: log.log(1, '%s was not set', k) else: log.log(1, '%s was "%s"', k, original[k]) if v is None: environ.pop(k, None) else: environ[k] = v else: log.log(5, 'nothing to apply') return original
[ "def", "_apply_diff", "(", "environ", ",", "diff", ")", ":", "original", "=", "{", "}", "if", "diff", ":", "for", "k", ",", "v", "in", "diff", ".", "iteritems", "(", ")", ":", "if", "v", "is", "None", ":", "log", ".", "log", "(", "5", ",", "'unset %s'", ",", "k", ")", "else", ":", "log", ".", "log", "(", "5", ",", "'%s=\"%s\"'", ",", "k", ",", "v", ")", "original", "[", "k", "]", "=", "environ", ".", "get", "(", "k", ")", "if", "original", "[", "k", "]", "is", "None", ":", "log", ".", "log", "(", "1", ",", "'%s was not set'", ",", "k", ")", "else", ":", "log", ".", "log", "(", "1", ",", "'%s was \"%s\"'", ",", "k", ",", "original", "[", "k", "]", ")", "if", "v", "is", "None", ":", "environ", ".", "pop", "(", "k", ",", "None", ")", "else", ":", "environ", "[", "k", "]", "=", "v", "else", ":", "log", ".", "log", "(", "5", ",", "'nothing to apply'", ")", "return", "original" ]
Apply a frozen environment. :param dict diff: key-value pairs to apply to the environment. :returns: A dict of the key-value pairs that are being changed.
[ "Apply", "a", "frozen", "environment", "." ]
1ec4eea6902b4a276f868a711b783dd965c123b7
https://github.com/mikeboers/sitetools/blob/1ec4eea6902b4a276f868a711b783dd965c123b7/sitetools/environ.py#L116-L147
239,786
gnullByte/dotcolors
dotcolors/core.py
get_current
def get_current(): """return current Xresources color theme""" global current if exists( SETTINGSFILE ): f = open( SETTINGSFILE ).read() current = re.findall('config[^\s]+.+', f)[1].split('/')[-1] return current else: return "** Not Set **"
python
def get_current(): """return current Xresources color theme""" global current if exists( SETTINGSFILE ): f = open( SETTINGSFILE ).read() current = re.findall('config[^\s]+.+', f)[1].split('/')[-1] return current else: return "** Not Set **"
[ "def", "get_current", "(", ")", ":", "global", "current", "if", "exists", "(", "SETTINGSFILE", ")", ":", "f", "=", "open", "(", "SETTINGSFILE", ")", ".", "read", "(", ")", "current", "=", "re", ".", "findall", "(", "'config[^\\s]+.+'", ",", "f", ")", "[", "1", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "return", "current", "else", ":", "return", "\"** Not Set **\"" ]
return current Xresources color theme
[ "return", "current", "Xresources", "color", "theme" ]
4b09ff9862b88b3125fe9cd86aa054694ed3e46e
https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/core.py#L33-L41
239,787
gnullByte/dotcolors
dotcolors/core.py
get_colors
def get_colors(): """return list of available Xresources color themes""" if exists( THEMEDIR ): contents = os.listdir( THEMEDIR ) themes = [theme for theme in contents if '.' not in theme] if len(themes) > 0: themes.sort() return themes else: print "** No themes in themedir **" print " run:" print " dotcolors (-s | --sync) <limit>" sys.exit(0) else: print "** Theme directory not found **" print " run: " print " dotcolors --setup" sys.exit(0)
python
def get_colors(): """return list of available Xresources color themes""" if exists( THEMEDIR ): contents = os.listdir( THEMEDIR ) themes = [theme for theme in contents if '.' not in theme] if len(themes) > 0: themes.sort() return themes else: print "** No themes in themedir **" print " run:" print " dotcolors (-s | --sync) <limit>" sys.exit(0) else: print "** Theme directory not found **" print " run: " print " dotcolors --setup" sys.exit(0)
[ "def", "get_colors", "(", ")", ":", "if", "exists", "(", "THEMEDIR", ")", ":", "contents", "=", "os", ".", "listdir", "(", "THEMEDIR", ")", "themes", "=", "[", "theme", "for", "theme", "in", "contents", "if", "'.'", "not", "in", "theme", "]", "if", "len", "(", "themes", ")", ">", "0", ":", "themes", ".", "sort", "(", ")", "return", "themes", "else", ":", "print", "\"** No themes in themedir **\"", "print", "\" run:\"", "print", "\" dotcolors (-s | --sync) <limit>\"", "sys", ".", "exit", "(", "0", ")", "else", ":", "print", "\"** Theme directory not found **\"", "print", "\" run: \"", "print", "\" dotcolors --setup\"", "sys", ".", "exit", "(", "0", ")" ]
return list of available Xresources color themes
[ "return", "list", "of", "available", "Xresources", "color", "themes" ]
4b09ff9862b88b3125fe9cd86aa054694ed3e46e
https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/core.py#L43-L61
239,788
gnullByte/dotcolors
dotcolors/core.py
getch_selection
def getch_selection(colors, per_page=15): """prompt for selection, validate input, return selection""" global transparency, prefix, current get_transparency() page = 1 length = len(colors) last_page = length / per_page if (last_page * per_page) < length: last_page += 1 getch = _Getch() valid = False while valid == False: menu_pages(colors, page, True, per_page) sys.stdout.write(">") char = getch() try: int(char) entry = raw_input_with_default(' Selection: ', char) entry = int(entry) if colors[entry - 1]: valid = True except ValueError: pass if( char == 'j' ): page += 1 if page > last_page: page = last_page menu_pages(colors, page, True, per_page) if( char == 'k' ): if(page > 1): page -= 1 else: page = 1 menu_pages(colors, page, True, per_page) if( char.lower() == 'q' ): c = os.system('clear') sys.exit(0) if( char == 'J' ): if transparency > 0: transparency -= 1 menu_pages(colors, page, True, per_page) if( char == 'K' ): if transparency < 100: transparency += 1 menu_pages(colors, page, True, per_page) if( char.lower() == 'p' ): prefix = raw_input_with_default(' prefix: ', 'urxvt') if( char == '\r' ): return current return colors[entry - 1]
python
def getch_selection(colors, per_page=15): """prompt for selection, validate input, return selection""" global transparency, prefix, current get_transparency() page = 1 length = len(colors) last_page = length / per_page if (last_page * per_page) < length: last_page += 1 getch = _Getch() valid = False while valid == False: menu_pages(colors, page, True, per_page) sys.stdout.write(">") char = getch() try: int(char) entry = raw_input_with_default(' Selection: ', char) entry = int(entry) if colors[entry - 1]: valid = True except ValueError: pass if( char == 'j' ): page += 1 if page > last_page: page = last_page menu_pages(colors, page, True, per_page) if( char == 'k' ): if(page > 1): page -= 1 else: page = 1 menu_pages(colors, page, True, per_page) if( char.lower() == 'q' ): c = os.system('clear') sys.exit(0) if( char == 'J' ): if transparency > 0: transparency -= 1 menu_pages(colors, page, True, per_page) if( char == 'K' ): if transparency < 100: transparency += 1 menu_pages(colors, page, True, per_page) if( char.lower() == 'p' ): prefix = raw_input_with_default(' prefix: ', 'urxvt') if( char == '\r' ): return current return colors[entry - 1]
[ "def", "getch_selection", "(", "colors", ",", "per_page", "=", "15", ")", ":", "global", "transparency", ",", "prefix", ",", "current", "get_transparency", "(", ")", "page", "=", "1", "length", "=", "len", "(", "colors", ")", "last_page", "=", "length", "/", "per_page", "if", "(", "last_page", "*", "per_page", ")", "<", "length", ":", "last_page", "+=", "1", "getch", "=", "_Getch", "(", ")", "valid", "=", "False", "while", "valid", "==", "False", ":", "menu_pages", "(", "colors", ",", "page", ",", "True", ",", "per_page", ")", "sys", ".", "stdout", ".", "write", "(", "\">\"", ")", "char", "=", "getch", "(", ")", "try", ":", "int", "(", "char", ")", "entry", "=", "raw_input_with_default", "(", "' Selection: '", ",", "char", ")", "entry", "=", "int", "(", "entry", ")", "if", "colors", "[", "entry", "-", "1", "]", ":", "valid", "=", "True", "except", "ValueError", ":", "pass", "if", "(", "char", "==", "'j'", ")", ":", "page", "+=", "1", "if", "page", ">", "last_page", ":", "page", "=", "last_page", "menu_pages", "(", "colors", ",", "page", ",", "True", ",", "per_page", ")", "if", "(", "char", "==", "'k'", ")", ":", "if", "(", "page", ">", "1", ")", ":", "page", "-=", "1", "else", ":", "page", "=", "1", "menu_pages", "(", "colors", ",", "page", ",", "True", ",", "per_page", ")", "if", "(", "char", ".", "lower", "(", ")", "==", "'q'", ")", ":", "c", "=", "os", ".", "system", "(", "'clear'", ")", "sys", ".", "exit", "(", "0", ")", "if", "(", "char", "==", "'J'", ")", ":", "if", "transparency", ">", "0", ":", "transparency", "-=", "1", "menu_pages", "(", "colors", ",", "page", ",", "True", ",", "per_page", ")", "if", "(", "char", "==", "'K'", ")", ":", "if", "transparency", "<", "100", ":", "transparency", "+=", "1", "menu_pages", "(", "colors", ",", "page", ",", "True", ",", "per_page", ")", "if", "(", "char", ".", "lower", "(", ")", "==", "'p'", ")", ":", "prefix", "=", "raw_input_with_default", "(", "' prefix: '", ",", "'urxvt'", ")", "if", "(", "char", "==", "'\\r'", ")", ":", "return", "current", "return", "colors", "[", "entry", "-", "1", "]" ]
prompt for selection, validate input, return selection
[ "prompt", "for", "selection", "validate", "input", "return", "selection" ]
4b09ff9862b88b3125fe9cd86aa054694ed3e46e
https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/core.py#L99-L164
239,789
gnullByte/dotcolors
dotcolors/core.py
format_theme
def format_theme(selection): """removes any non-color related lines from theme file""" global themefile text = open(THEMEDIR + '/' + selection).read() if '!dotcolors' in text[:10]: themefile = text return lines = ['!dotcolors auto formatted\n'] for line in text.split('\n'): lline = line.lower() background = 'background' in lline foreground = 'foreground' in lline color = 'color' in lline if background: if 'rgb' in line: # rbga: 0000/0000/0000/dddd rgb = line.split(':')[2].replace(' ', '') rgb = rgb_to_hex(rgb) lines.append('*background:\t%s' % rgb) else: lines.append('\t#'.join(line \ .replace(' ', '') \ .replace('\t', '') \ .split('#'))) if foreground: if 'rgb' in line: # rbga: 0000/0000/0000/dddd rgb = line.split(':')[2].replace(' ', '') rgb = rgb_to_hex(rgb) lines.append('*foreground:\t%s' % rgb) else: lines.append('\t#'.join(line \ .replace(' ', '') \ .replace('\t', '') \ .split('#'))) if color: if lline[0] != '!': lines.append('\t#'.join(line \ .replace(' ', '') \ .replace('\t', '') \ .split('#'))) themefile = '\n'.join(lines) + '\n' fd, tmpfile = tempfile.mkstemp() if exists( THEMEDIR + '/' + selection ): old = open( THEMEDIR + '/' + selection ) new = os.fdopen(fd, 'w') os.write(fd, themefile) old.close() new.close() move( tmpfile, THEMEDIR + '/' + selection )
python
def format_theme(selection): """removes any non-color related lines from theme file""" global themefile text = open(THEMEDIR + '/' + selection).read() if '!dotcolors' in text[:10]: themefile = text return lines = ['!dotcolors auto formatted\n'] for line in text.split('\n'): lline = line.lower() background = 'background' in lline foreground = 'foreground' in lline color = 'color' in lline if background: if 'rgb' in line: # rbga: 0000/0000/0000/dddd rgb = line.split(':')[2].replace(' ', '') rgb = rgb_to_hex(rgb) lines.append('*background:\t%s' % rgb) else: lines.append('\t#'.join(line \ .replace(' ', '') \ .replace('\t', '') \ .split('#'))) if foreground: if 'rgb' in line: # rbga: 0000/0000/0000/dddd rgb = line.split(':')[2].replace(' ', '') rgb = rgb_to_hex(rgb) lines.append('*foreground:\t%s' % rgb) else: lines.append('\t#'.join(line \ .replace(' ', '') \ .replace('\t', '') \ .split('#'))) if color: if lline[0] != '!': lines.append('\t#'.join(line \ .replace(' ', '') \ .replace('\t', '') \ .split('#'))) themefile = '\n'.join(lines) + '\n' fd, tmpfile = tempfile.mkstemp() if exists( THEMEDIR + '/' + selection ): old = open( THEMEDIR + '/' + selection ) new = os.fdopen(fd, 'w') os.write(fd, themefile) old.close() new.close() move( tmpfile, THEMEDIR + '/' + selection )
[ "def", "format_theme", "(", "selection", ")", ":", "global", "themefile", "text", "=", "open", "(", "THEMEDIR", "+", "'/'", "+", "selection", ")", ".", "read", "(", ")", "if", "'!dotcolors'", "in", "text", "[", ":", "10", "]", ":", "themefile", "=", "text", "return", "lines", "=", "[", "'!dotcolors auto formatted\\n'", "]", "for", "line", "in", "text", ".", "split", "(", "'\\n'", ")", ":", "lline", "=", "line", ".", "lower", "(", ")", "background", "=", "'background'", "in", "lline", "foreground", "=", "'foreground'", "in", "lline", "color", "=", "'color'", "in", "lline", "if", "background", ":", "if", "'rgb'", "in", "line", ":", "# rbga: 0000/0000/0000/dddd", "rgb", "=", "line", ".", "split", "(", "':'", ")", "[", "2", "]", ".", "replace", "(", "' '", ",", "''", ")", "rgb", "=", "rgb_to_hex", "(", "rgb", ")", "lines", ".", "append", "(", "'*background:\\t%s'", "%", "rgb", ")", "else", ":", "lines", ".", "append", "(", "'\\t#'", ".", "join", "(", "line", ".", "replace", "(", "' '", ",", "''", ")", ".", "replace", "(", "'\\t'", ",", "''", ")", ".", "split", "(", "'#'", ")", ")", ")", "if", "foreground", ":", "if", "'rgb'", "in", "line", ":", "# rbga: 0000/0000/0000/dddd", "rgb", "=", "line", ".", "split", "(", "':'", ")", "[", "2", "]", ".", "replace", "(", "' '", ",", "''", ")", "rgb", "=", "rgb_to_hex", "(", "rgb", ")", "lines", ".", "append", "(", "'*foreground:\\t%s'", "%", "rgb", ")", "else", ":", "lines", ".", "append", "(", "'\\t#'", ".", "join", "(", "line", ".", "replace", "(", "' '", ",", "''", ")", ".", "replace", "(", "'\\t'", ",", "''", ")", ".", "split", "(", "'#'", ")", ")", ")", "if", "color", ":", "if", "lline", "[", "0", "]", "!=", "'!'", ":", "lines", ".", "append", "(", "'\\t#'", ".", "join", "(", "line", ".", "replace", "(", "' '", ",", "''", ")", ".", "replace", "(", "'\\t'", ",", "''", ")", ".", "split", "(", "'#'", ")", ")", ")", "themefile", "=", "'\\n'", ".", "join", "(", "lines", ")", "+", "'\\n'", "fd", ",", "tmpfile", "=", "tempfile", ".", "mkstemp", "(", ")", "if", "exists", "(", "THEMEDIR", "+", "'/'", "+", "selection", ")", ":", "old", "=", "open", "(", "THEMEDIR", "+", "'/'", "+", "selection", ")", "new", "=", "os", ".", "fdopen", "(", "fd", ",", "'w'", ")", "os", ".", "write", "(", "fd", ",", "themefile", ")", "old", ".", "close", "(", ")", "new", ".", "close", "(", ")", "move", "(", "tmpfile", ",", "THEMEDIR", "+", "'/'", "+", "selection", ")" ]
removes any non-color related lines from theme file
[ "removes", "any", "non", "-", "color", "related", "lines", "from", "theme", "file" ]
4b09ff9862b88b3125fe9cd86aa054694ed3e46e
https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/core.py#L167-L222
239,790
voicecom/pgtool
pgtool/util.py
pretty_size
def pretty_size(value): """Convert a number of bytes into a human-readable string. Output is 2...5 characters. Values >= 1000 always produce output in form: x.xxxU, xx.xxU, xxxU, xxxxU. """ exp = int(math.log(value, 1024)) if value > 0 else 0 unit = 'bkMGTPEZY'[exp] if exp == 0: return '%d%s' % (value, unit) # value < 1024, result is always without fractions unit_value = value / (1024.0 ** exp) # value in the relevant units places = int(math.log(unit_value, 10)) # number of digits before decimal point return '%.*f%s' % (2 - places, unit_value, unit)
python
def pretty_size(value): """Convert a number of bytes into a human-readable string. Output is 2...5 characters. Values >= 1000 always produce output in form: x.xxxU, xx.xxU, xxxU, xxxxU. """ exp = int(math.log(value, 1024)) if value > 0 else 0 unit = 'bkMGTPEZY'[exp] if exp == 0: return '%d%s' % (value, unit) # value < 1024, result is always without fractions unit_value = value / (1024.0 ** exp) # value in the relevant units places = int(math.log(unit_value, 10)) # number of digits before decimal point return '%.*f%s' % (2 - places, unit_value, unit)
[ "def", "pretty_size", "(", "value", ")", ":", "exp", "=", "int", "(", "math", ".", "log", "(", "value", ",", "1024", ")", ")", "if", "value", ">", "0", "else", "0", "unit", "=", "'bkMGTPEZY'", "[", "exp", "]", "if", "exp", "==", "0", ":", "return", "'%d%s'", "%", "(", "value", ",", "unit", ")", "# value < 1024, result is always without fractions", "unit_value", "=", "value", "/", "(", "1024.0", "**", "exp", ")", "# value in the relevant units", "places", "=", "int", "(", "math", ".", "log", "(", "unit_value", ",", "10", ")", ")", "# number of digits before decimal point", "return", "'%.*f%s'", "%", "(", "2", "-", "places", ",", "unit_value", ",", "unit", ")" ]
Convert a number of bytes into a human-readable string. Output is 2...5 characters. Values >= 1000 always produce output in form: x.xxxU, xx.xxU, xxxU, xxxxU.
[ "Convert", "a", "number", "of", "bytes", "into", "a", "human", "-", "readable", "string", "." ]
36b8682bfca614d784fe58451e0cbc41315bc72e
https://github.com/voicecom/pgtool/blob/36b8682bfca614d784fe58451e0cbc41315bc72e/pgtool/util.py#L8-L20
239,791
neelkamath/hclib
hclib.py
HackChat._on_open
def _on_open(self, _): """Joins the hack.chat channel and starts pinging.""" nick = self._format_nick(self._nick, self._pwd) data = {"cmd": "join", "channel": self._channel, "nick": nick} self._send_packet(data) self._thread = True threading.Thread(target=self._ping).start()
python
def _on_open(self, _): """Joins the hack.chat channel and starts pinging.""" nick = self._format_nick(self._nick, self._pwd) data = {"cmd": "join", "channel": self._channel, "nick": nick} self._send_packet(data) self._thread = True threading.Thread(target=self._ping).start()
[ "def", "_on_open", "(", "self", ",", "_", ")", ":", "nick", "=", "self", ".", "_format_nick", "(", "self", ".", "_nick", ",", "self", ".", "_pwd", ")", "data", "=", "{", "\"cmd\"", ":", "\"join\"", ",", "\"channel\"", ":", "self", ".", "_channel", ",", "\"nick\"", ":", "nick", "}", "self", ".", "_send_packet", "(", "data", ")", "self", ".", "_thread", "=", "True", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_ping", ")", ".", "start", "(", ")" ]
Joins the hack.chat channel and starts pinging.
[ "Joins", "the", "hack", ".", "chat", "channel", "and", "starts", "pinging", "." ]
8678e7abe619796af85f219e280417cfa9a703f2
https://github.com/neelkamath/hclib/blob/8678e7abe619796af85f219e280417cfa9a703f2/hclib.py#L117-L123
239,792
neelkamath/hclib
hclib.py
HackChat.join
def join(self, new_channel, nick, pwd=None): """Joins a new channel. Keyword arguments: new_channel: <str>; the channel to connect to nick: <str>; the nickname to use pwd: <str>; the (optional) password to use """ self._send_packet({"cmd": "join", "channel": new_channel, "nick": self._format_nick(nick, pwd)})
python
def join(self, new_channel, nick, pwd=None): """Joins a new channel. Keyword arguments: new_channel: <str>; the channel to connect to nick: <str>; the nickname to use pwd: <str>; the (optional) password to use """ self._send_packet({"cmd": "join", "channel": new_channel, "nick": self._format_nick(nick, pwd)})
[ "def", "join", "(", "self", ",", "new_channel", ",", "nick", ",", "pwd", "=", "None", ")", ":", "self", ".", "_send_packet", "(", "{", "\"cmd\"", ":", "\"join\"", ",", "\"channel\"", ":", "new_channel", ",", "\"nick\"", ":", "self", ".", "_format_nick", "(", "nick", ",", "pwd", ")", "}", ")" ]
Joins a new channel. Keyword arguments: new_channel: <str>; the channel to connect to nick: <str>; the nickname to use pwd: <str>; the (optional) password to use
[ "Joins", "a", "new", "channel", "." ]
8678e7abe619796af85f219e280417cfa9a703f2
https://github.com/neelkamath/hclib/blob/8678e7abe619796af85f219e280417cfa9a703f2/hclib.py#L333-L342
239,793
wooga/play-deliver
playdeliver/image.py
upload
def upload(client, source_dir): """ Upload images to play store. The function will iterate through source_dir and upload all matching image_types found in folder herachy. """ print('') print('upload images') print('-------------') base_image_folders = [ os.path.join(source_dir, 'images', x) for x in image_types] for type_folder in base_image_folders: if os.path.exists(type_folder): image_type = os.path.basename(type_folder) langfolders = filter(os.path.isdir, list_dir_abspath(type_folder)) for language_dir in langfolders: language = os.path.basename(language_dir) delete_and_upload_images( client, image_type, language, type_folder)
python
def upload(client, source_dir): """ Upload images to play store. The function will iterate through source_dir and upload all matching image_types found in folder herachy. """ print('') print('upload images') print('-------------') base_image_folders = [ os.path.join(source_dir, 'images', x) for x in image_types] for type_folder in base_image_folders: if os.path.exists(type_folder): image_type = os.path.basename(type_folder) langfolders = filter(os.path.isdir, list_dir_abspath(type_folder)) for language_dir in langfolders: language = os.path.basename(language_dir) delete_and_upload_images( client, image_type, language, type_folder)
[ "def", "upload", "(", "client", ",", "source_dir", ")", ":", "print", "(", "''", ")", "print", "(", "'upload images'", ")", "print", "(", "'-------------'", ")", "base_image_folders", "=", "[", "os", ".", "path", ".", "join", "(", "source_dir", ",", "'images'", ",", "x", ")", "for", "x", "in", "image_types", "]", "for", "type_folder", "in", "base_image_folders", ":", "if", "os", ".", "path", ".", "exists", "(", "type_folder", ")", ":", "image_type", "=", "os", ".", "path", ".", "basename", "(", "type_folder", ")", "langfolders", "=", "filter", "(", "os", ".", "path", ".", "isdir", ",", "list_dir_abspath", "(", "type_folder", ")", ")", "for", "language_dir", "in", "langfolders", ":", "language", "=", "os", ".", "path", ".", "basename", "(", "language_dir", ")", "delete_and_upload_images", "(", "client", ",", "image_type", ",", "language", ",", "type_folder", ")" ]
Upload images to play store. The function will iterate through source_dir and upload all matching image_types found in folder herachy.
[ "Upload", "images", "to", "play", "store", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L23-L43
239,794
wooga/play-deliver
playdeliver/image.py
delete_and_upload_images
def delete_and_upload_images(client, image_type, language, base_dir): """ Delete and upload images with given image_type and language. Function will stage delete and stage upload all found images in matching folders. """ print('{0} {1}'.format(image_type, language)) files_in_dir = os.listdir(os.path.join(base_dir, language)) delete_result = client.deleteall( 'images', imageType=image_type, language=language) deleted = delete_result.get('deleted', list()) for deleted_files in deleted: print(' delete image: {0}'.format(deleted_files['id'])) for image_file in files_in_dir[:8]: image_file_path = os.path.join(base_dir, language, image_file) image_response = client.upload( 'images', imageType=image_type, language=language, media_body=image_file_path) print(" upload image {0} new id {1}".format(image_file, image_response['image']['id']))
python
def delete_and_upload_images(client, image_type, language, base_dir): """ Delete and upload images with given image_type and language. Function will stage delete and stage upload all found images in matching folders. """ print('{0} {1}'.format(image_type, language)) files_in_dir = os.listdir(os.path.join(base_dir, language)) delete_result = client.deleteall( 'images', imageType=image_type, language=language) deleted = delete_result.get('deleted', list()) for deleted_files in deleted: print(' delete image: {0}'.format(deleted_files['id'])) for image_file in files_in_dir[:8]: image_file_path = os.path.join(base_dir, language, image_file) image_response = client.upload( 'images', imageType=image_type, language=language, media_body=image_file_path) print(" upload image {0} new id {1}".format(image_file, image_response['image']['id']))
[ "def", "delete_and_upload_images", "(", "client", ",", "image_type", ",", "language", ",", "base_dir", ")", ":", "print", "(", "'{0} {1}'", ".", "format", "(", "image_type", ",", "language", ")", ")", "files_in_dir", "=", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "base_dir", ",", "language", ")", ")", "delete_result", "=", "client", ".", "deleteall", "(", "'images'", ",", "imageType", "=", "image_type", ",", "language", "=", "language", ")", "deleted", "=", "delete_result", ".", "get", "(", "'deleted'", ",", "list", "(", ")", ")", "for", "deleted_files", "in", "deleted", ":", "print", "(", "' delete image: {0}'", ".", "format", "(", "deleted_files", "[", "'id'", "]", ")", ")", "for", "image_file", "in", "files_in_dir", "[", ":", "8", "]", ":", "image_file_path", "=", "os", ".", "path", ".", "join", "(", "base_dir", ",", "language", ",", "image_file", ")", "image_response", "=", "client", ".", "upload", "(", "'images'", ",", "imageType", "=", "image_type", ",", "language", "=", "language", ",", "media_body", "=", "image_file_path", ")", "print", "(", "\" upload image {0} new id {1}\"", ".", "format", "(", "image_file", ",", "image_response", "[", "'image'", "]", "[", "'id'", "]", ")", ")" ]
Delete and upload images with given image_type and language. Function will stage delete and stage upload all found images in matching folders.
[ "Delete", "and", "upload", "images", "with", "given", "image_type", "and", "language", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L46-L69
239,795
wooga/play-deliver
playdeliver/image.py
download
def download(client, target_dir): """Download images from play store into folder herachy.""" print('download image previews') print( "Warning! Downloaded images are only previews!" "They may be to small for upload.") tree = {} listings = client.list('listings') languages = map(lambda listing: listing['language'], listings) parameters = [{'imageType': image_type, 'language': language} for image_type in image_types for language in languages] tree = {image_type: {language: list() for language in languages} for image_type in image_types} for params in parameters: result = client.list('images', **params) image_type = params['imageType'] language = params['language'] tree[image_type][language] = map( lambda r: r['url'], result) for image_type, language_map in tree.items(): for language, files in language_map.items(): if len(files) > 0: mkdir_p( os.path.join(target_dir, 'images', image_type, language)) if image_type in single_image_types: if len(files) > 0: image_url = files[0] path = os.path.join( target_dir, 'images', image_type, language, image_type) load_and_save_image(image_url, path) else: for idx, image_url in enumerate(files): path = os.path.join( target_dir, 'images', image_type, language, image_type + '_' + str(idx)) load_and_save_image(image_url, path)
python
def download(client, target_dir): """Download images from play store into folder herachy.""" print('download image previews') print( "Warning! Downloaded images are only previews!" "They may be to small for upload.") tree = {} listings = client.list('listings') languages = map(lambda listing: listing['language'], listings) parameters = [{'imageType': image_type, 'language': language} for image_type in image_types for language in languages] tree = {image_type: {language: list() for language in languages} for image_type in image_types} for params in parameters: result = client.list('images', **params) image_type = params['imageType'] language = params['language'] tree[image_type][language] = map( lambda r: r['url'], result) for image_type, language_map in tree.items(): for language, files in language_map.items(): if len(files) > 0: mkdir_p( os.path.join(target_dir, 'images', image_type, language)) if image_type in single_image_types: if len(files) > 0: image_url = files[0] path = os.path.join( target_dir, 'images', image_type, language, image_type) load_and_save_image(image_url, path) else: for idx, image_url in enumerate(files): path = os.path.join( target_dir, 'images', image_type, language, image_type + '_' + str(idx)) load_and_save_image(image_url, path)
[ "def", "download", "(", "client", ",", "target_dir", ")", ":", "print", "(", "'download image previews'", ")", "print", "(", "\"Warning! Downloaded images are only previews!\"", "\"They may be to small for upload.\"", ")", "tree", "=", "{", "}", "listings", "=", "client", ".", "list", "(", "'listings'", ")", "languages", "=", "map", "(", "lambda", "listing", ":", "listing", "[", "'language'", "]", ",", "listings", ")", "parameters", "=", "[", "{", "'imageType'", ":", "image_type", ",", "'language'", ":", "language", "}", "for", "image_type", "in", "image_types", "for", "language", "in", "languages", "]", "tree", "=", "{", "image_type", ":", "{", "language", ":", "list", "(", ")", "for", "language", "in", "languages", "}", "for", "image_type", "in", "image_types", "}", "for", "params", "in", "parameters", ":", "result", "=", "client", ".", "list", "(", "'images'", ",", "*", "*", "params", ")", "image_type", "=", "params", "[", "'imageType'", "]", "language", "=", "params", "[", "'language'", "]", "tree", "[", "image_type", "]", "[", "language", "]", "=", "map", "(", "lambda", "r", ":", "r", "[", "'url'", "]", ",", "result", ")", "for", "image_type", ",", "language_map", "in", "tree", ".", "items", "(", ")", ":", "for", "language", ",", "files", "in", "language_map", ".", "items", "(", ")", ":", "if", "len", "(", "files", ")", ">", "0", ":", "mkdir_p", "(", "os", ".", "path", ".", "join", "(", "target_dir", ",", "'images'", ",", "image_type", ",", "language", ")", ")", "if", "image_type", "in", "single_image_types", ":", "if", "len", "(", "files", ")", ">", "0", ":", "image_url", "=", "files", "[", "0", "]", "path", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "'images'", ",", "image_type", ",", "language", ",", "image_type", ")", "load_and_save_image", "(", "image_url", ",", "path", ")", "else", ":", "for", "idx", ",", "image_url", "in", "enumerate", "(", "files", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "'images'", ",", "image_type", ",", "language", ",", "image_type", "+", "'_'", "+", "str", "(", "idx", ")", ")", "load_and_save_image", "(", "image_url", ",", "path", ")" ]
Download images from play store into folder herachy.
[ "Download", "images", "from", "play", "store", "into", "folder", "herachy", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L72-L118
239,796
wooga/play-deliver
playdeliver/image.py
load_and_save_image
def load_and_save_image(url, destination): """Download image from given url and saves it to destination.""" from urllib2 import Request, urlopen, URLError, HTTPError # create the url and the request req = Request(url) # Open the url try: f = urlopen(req) print "downloading " + url # Open our local file for writing local_file = open(destination, "wb") # Write to our local file local_file.write(f.read()) local_file.close() file_type = imghdr.what(destination) local_file = open(destination, "rb") data = local_file.read() local_file.close() final_file = open(destination + '.' + file_type, "wb") final_file.write(data) final_file.close() print('save image preview {0}'.format(destination + '.' + file_type)) os.remove(destination) # handle errors except HTTPError, e: print "HTTP Error:", e.code, url except URLError, e: print "URL Error:", e.reason, url
python
def load_and_save_image(url, destination): """Download image from given url and saves it to destination.""" from urllib2 import Request, urlopen, URLError, HTTPError # create the url and the request req = Request(url) # Open the url try: f = urlopen(req) print "downloading " + url # Open our local file for writing local_file = open(destination, "wb") # Write to our local file local_file.write(f.read()) local_file.close() file_type = imghdr.what(destination) local_file = open(destination, "rb") data = local_file.read() local_file.close() final_file = open(destination + '.' + file_type, "wb") final_file.write(data) final_file.close() print('save image preview {0}'.format(destination + '.' + file_type)) os.remove(destination) # handle errors except HTTPError, e: print "HTTP Error:", e.code, url except URLError, e: print "URL Error:", e.reason, url
[ "def", "load_and_save_image", "(", "url", ",", "destination", ")", ":", "from", "urllib2", "import", "Request", ",", "urlopen", ",", "URLError", ",", "HTTPError", "# create the url and the request", "req", "=", "Request", "(", "url", ")", "# Open the url", "try", ":", "f", "=", "urlopen", "(", "req", ")", "print", "\"downloading \"", "+", "url", "# Open our local file for writing", "local_file", "=", "open", "(", "destination", ",", "\"wb\"", ")", "# Write to our local file", "local_file", ".", "write", "(", "f", ".", "read", "(", ")", ")", "local_file", ".", "close", "(", ")", "file_type", "=", "imghdr", ".", "what", "(", "destination", ")", "local_file", "=", "open", "(", "destination", ",", "\"rb\"", ")", "data", "=", "local_file", ".", "read", "(", ")", "local_file", ".", "close", "(", ")", "final_file", "=", "open", "(", "destination", "+", "'.'", "+", "file_type", ",", "\"wb\"", ")", "final_file", ".", "write", "(", "data", ")", "final_file", ".", "close", "(", ")", "print", "(", "'save image preview {0}'", ".", "format", "(", "destination", "+", "'.'", "+", "file_type", ")", ")", "os", ".", "remove", "(", "destination", ")", "# handle errors", "except", "HTTPError", ",", "e", ":", "print", "\"HTTP Error:\"", ",", "e", ".", "code", ",", "url", "except", "URLError", ",", "e", ":", "print", "\"URL Error:\"", ",", "e", ".", "reason", ",", "url" ]
Download image from given url and saves it to destination.
[ "Download", "image", "from", "given", "url", "and", "saves", "it", "to", "destination", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L121-L154
239,797
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/main.py
get_qapp
def get_qapp(): """Return an instance of QApplication. Creates one if neccessary. :returns: a QApplication instance :rtype: QApplication :raises: None """ global app app = QtGui.QApplication.instance() if app is None: app = QtGui.QApplication([], QtGui.QApplication.GuiClient) return app
python
def get_qapp(): """Return an instance of QApplication. Creates one if neccessary. :returns: a QApplication instance :rtype: QApplication :raises: None """ global app app = QtGui.QApplication.instance() if app is None: app = QtGui.QApplication([], QtGui.QApplication.GuiClient) return app
[ "def", "get_qapp", "(", ")", ":", "global", "app", "app", "=", "QtGui", ".", "QApplication", ".", "instance", "(", ")", "if", "app", "is", "None", ":", "app", "=", "QtGui", ".", "QApplication", "(", "[", "]", ",", "QtGui", ".", "QApplication", ".", "GuiClient", ")", "return", "app" ]
Return an instance of QApplication. Creates one if neccessary. :returns: a QApplication instance :rtype: QApplication :raises: None
[ "Return", "an", "instance", "of", "QApplication", ".", "Creates", "one", "if", "neccessary", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L30-L41
239,798
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/main.py
load_all_resources
def load_all_resources(): """Load all resources inside this package When compiling qt resources, the compiled python file will register the resource on import. .. Warning:: This will simply import all modules inside this package """ pkgname = resources.__name__ for importer, mod_name, _ in pkgutil.iter_modules(resources.__path__): full_mod_name = '%s.%s' % (pkgname, mod_name) if full_mod_name not in sys.modules: module = importer.find_module(mod_name ).load_module(full_mod_name) log.debug("Loaded resource from: %s", module)
python
def load_all_resources(): """Load all resources inside this package When compiling qt resources, the compiled python file will register the resource on import. .. Warning:: This will simply import all modules inside this package """ pkgname = resources.__name__ for importer, mod_name, _ in pkgutil.iter_modules(resources.__path__): full_mod_name = '%s.%s' % (pkgname, mod_name) if full_mod_name not in sys.modules: module = importer.find_module(mod_name ).load_module(full_mod_name) log.debug("Loaded resource from: %s", module)
[ "def", "load_all_resources", "(", ")", ":", "pkgname", "=", "resources", ".", "__name__", "for", "importer", ",", "mod_name", ",", "_", "in", "pkgutil", ".", "iter_modules", "(", "resources", ".", "__path__", ")", ":", "full_mod_name", "=", "'%s.%s'", "%", "(", "pkgname", ",", "mod_name", ")", "if", "full_mod_name", "not", "in", "sys", ".", "modules", ":", "module", "=", "importer", ".", "find_module", "(", "mod_name", ")", ".", "load_module", "(", "full_mod_name", ")", "log", ".", "debug", "(", "\"Loaded resource from: %s\"", ",", "module", ")" ]
Load all resources inside this package When compiling qt resources, the compiled python file will register the resource on import. .. Warning:: This will simply import all modules inside this package
[ "Load", "all", "resources", "inside", "this", "package" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L44-L58
239,799
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/main.py
set_main_style
def set_main_style(widget): """Load the main.qss and apply it to the application :param widget: The widget to apply the stylesheet to. Can also be a QApplication. ``setStylesheet`` is called on the widget. :type widget: :class:`QtGui.QWidget` :returns: None :rtype: None :raises: None """ load_all_resources() with open(MAIN_STYLESHEET, 'r') as qss: sheet = qss.read() widget.setStyleSheet(sheet)
python
def set_main_style(widget): """Load the main.qss and apply it to the application :param widget: The widget to apply the stylesheet to. Can also be a QApplication. ``setStylesheet`` is called on the widget. :type widget: :class:`QtGui.QWidget` :returns: None :rtype: None :raises: None """ load_all_resources() with open(MAIN_STYLESHEET, 'r') as qss: sheet = qss.read() widget.setStyleSheet(sheet)
[ "def", "set_main_style", "(", "widget", ")", ":", "load_all_resources", "(", ")", "with", "open", "(", "MAIN_STYLESHEET", ",", "'r'", ")", "as", "qss", ":", "sheet", "=", "qss", ".", "read", "(", ")", "widget", ".", "setStyleSheet", "(", "sheet", ")" ]
Load the main.qss and apply it to the application :param widget: The widget to apply the stylesheet to. Can also be a QApplication. ``setStylesheet`` is called on the widget. :type widget: :class:`QtGui.QWidget` :returns: None :rtype: None :raises: None
[ "Load", "the", "main", ".", "qss", "and", "apply", "it", "to", "the", "application" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L61-L74