repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
ewiger/mlab | src/mlab/mlabwrap.py | MlabWrap._do | def _do(self, cmd, *args, **kwargs):
"""Semi-raw execution of a matlab command.
Smartly handle calls to matlab, figure out what to do with `args`,
and when to use function call syntax and not.
If no `args` are specified, the ``cmd`` not ``result = cmd()`` form is
used in Matlab -- this also makes literal Matlab commands legal
(eg. cmd=``get(gca, 'Children')``).
If ``nout=0`` is specified, the Matlab command is executed as
procedure, otherwise it is executed as function (default), nout
specifying how many values should be returned (default 1).
**Beware that if you use don't specify ``nout=0`` for a `cmd` that
never returns a value will raise an error** (because assigning a
variable to a call that doesn't return a value is illegal in matlab).
``cast`` specifies which typecast should be applied to the result
(e.g. `int`), it defaults to none.
XXX: should we add ``parens`` parameter?
"""
handle_out = kwargs.get('handle_out', _flush_write_stdout)
#self._session = self._session or mlabraw.open()
# HACK
if self._autosync_dirs:
mlabraw.eval(self._session, "cd('%s');" % os.getcwd().replace("'", "''"))
nout = kwargs.get('nout', 1)
#XXX what to do with matlab screen output
argnames = []
tempargs = []
try:
for count, arg in enumerate(args):
if isinstance(arg, MlabObjectProxy):
argnames.append(arg._name)
else:
nextName = 'arg%d__' % count
argnames.append(nextName)
tempargs.append(nextName)
# have to convert these by hand
## try:
## arg = self._as_mlabable_type(arg)
## except TypeError:
## raise TypeError("Illegal argument type (%s.:) for %d. argument" %
## (type(arg), type(count)))
mlabraw.put(self._session, argnames[-1], arg)
if args:
cmd = "%s(%s)%s" % (cmd, ", ".join(argnames),
('',';')[kwargs.get('show',0)])
# got three cases for nout:
# 0 -> None, 1 -> val, >1 -> [val1, val2, ...]
if nout == 0:
handle_out(mlabraw.eval(self._session, cmd))
return
# deal with matlab-style multiple value return
resSL = ((["RES%d__" % i for i in range(nout)]))
handle_out(mlabraw.eval(self._session, '[%s]=%s;' % (", ".join(resSL), cmd)))
res = self._get_values(resSL)
if nout == 1: res = res[0]
else: res = tuple(res)
if kwargs.has_key('cast'):
if nout == 0: raise TypeError("Can't cast: 0 nout")
return kwargs['cast'](res)
else:
return res
finally:
if len(tempargs) and self._clear_call_args:
mlabraw.eval(self._session, "clear('%s');" %
"','".join(tempargs)) | python | def _do(self, cmd, *args, **kwargs):
"""Semi-raw execution of a matlab command.
Smartly handle calls to matlab, figure out what to do with `args`,
and when to use function call syntax and not.
If no `args` are specified, the ``cmd`` not ``result = cmd()`` form is
used in Matlab -- this also makes literal Matlab commands legal
(eg. cmd=``get(gca, 'Children')``).
If ``nout=0`` is specified, the Matlab command is executed as
procedure, otherwise it is executed as function (default), nout
specifying how many values should be returned (default 1).
**Beware that if you use don't specify ``nout=0`` for a `cmd` that
never returns a value will raise an error** (because assigning a
variable to a call that doesn't return a value is illegal in matlab).
``cast`` specifies which typecast should be applied to the result
(e.g. `int`), it defaults to none.
XXX: should we add ``parens`` parameter?
"""
handle_out = kwargs.get('handle_out', _flush_write_stdout)
#self._session = self._session or mlabraw.open()
# HACK
if self._autosync_dirs:
mlabraw.eval(self._session, "cd('%s');" % os.getcwd().replace("'", "''"))
nout = kwargs.get('nout', 1)
#XXX what to do with matlab screen output
argnames = []
tempargs = []
try:
for count, arg in enumerate(args):
if isinstance(arg, MlabObjectProxy):
argnames.append(arg._name)
else:
nextName = 'arg%d__' % count
argnames.append(nextName)
tempargs.append(nextName)
# have to convert these by hand
## try:
## arg = self._as_mlabable_type(arg)
## except TypeError:
## raise TypeError("Illegal argument type (%s.:) for %d. argument" %
## (type(arg), type(count)))
mlabraw.put(self._session, argnames[-1], arg)
if args:
cmd = "%s(%s)%s" % (cmd, ", ".join(argnames),
('',';')[kwargs.get('show',0)])
# got three cases for nout:
# 0 -> None, 1 -> val, >1 -> [val1, val2, ...]
if nout == 0:
handle_out(mlabraw.eval(self._session, cmd))
return
# deal with matlab-style multiple value return
resSL = ((["RES%d__" % i for i in range(nout)]))
handle_out(mlabraw.eval(self._session, '[%s]=%s;' % (", ".join(resSL), cmd)))
res = self._get_values(resSL)
if nout == 1: res = res[0]
else: res = tuple(res)
if kwargs.has_key('cast'):
if nout == 0: raise TypeError("Can't cast: 0 nout")
return kwargs['cast'](res)
else:
return res
finally:
if len(tempargs) and self._clear_call_args:
mlabraw.eval(self._session, "clear('%s');" %
"','".join(tempargs)) | [
"def",
"_do",
"(",
"self",
",",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"handle_out",
"=",
"kwargs",
".",
"get",
"(",
"'handle_out'",
",",
"_flush_write_stdout",
")",
"#self._session = self._session or mlabraw.open()",
"# HACK",
"if",
"self",
".",
"_autosync_dirs",
":",
"mlabraw",
".",
"eval",
"(",
"self",
".",
"_session",
",",
"\"cd('%s');\"",
"%",
"os",
".",
"getcwd",
"(",
")",
".",
"replace",
"(",
"\"'\"",
",",
"\"''\"",
")",
")",
"nout",
"=",
"kwargs",
".",
"get",
"(",
"'nout'",
",",
"1",
")",
"#XXX what to do with matlab screen output",
"argnames",
"=",
"[",
"]",
"tempargs",
"=",
"[",
"]",
"try",
":",
"for",
"count",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"MlabObjectProxy",
")",
":",
"argnames",
".",
"append",
"(",
"arg",
".",
"_name",
")",
"else",
":",
"nextName",
"=",
"'arg%d__'",
"%",
"count",
"argnames",
".",
"append",
"(",
"nextName",
")",
"tempargs",
".",
"append",
"(",
"nextName",
")",
"# have to convert these by hand",
"## try:",
"## arg = self._as_mlabable_type(arg)",
"## except TypeError:",
"## raise TypeError(\"Illegal argument type (%s.:) for %d. argument\" %",
"## (type(arg), type(count)))",
"mlabraw",
".",
"put",
"(",
"self",
".",
"_session",
",",
"argnames",
"[",
"-",
"1",
"]",
",",
"arg",
")",
"if",
"args",
":",
"cmd",
"=",
"\"%s(%s)%s\"",
"%",
"(",
"cmd",
",",
"\", \"",
".",
"join",
"(",
"argnames",
")",
",",
"(",
"''",
",",
"';'",
")",
"[",
"kwargs",
".",
"get",
"(",
"'show'",
",",
"0",
")",
"]",
")",
"# got three cases for nout:",
"# 0 -> None, 1 -> val, >1 -> [val1, val2, ...]",
"if",
"nout",
"==",
"0",
":",
"handle_out",
"(",
"mlabraw",
".",
"eval",
"(",
"self",
".",
"_session",
",",
"cmd",
")",
")",
"return",
"# deal with matlab-style multiple value return",
"resSL",
"=",
"(",
"(",
"[",
"\"RES%d__\"",
"%",
"i",
"for",
"i",
"in",
"range",
"(",
"nout",
")",
"]",
")",
")",
"handle_out",
"(",
"mlabraw",
".",
"eval",
"(",
"self",
".",
"_session",
",",
"'[%s]=%s;'",
"%",
"(",
"\", \"",
".",
"join",
"(",
"resSL",
")",
",",
"cmd",
")",
")",
")",
"res",
"=",
"self",
".",
"_get_values",
"(",
"resSL",
")",
"if",
"nout",
"==",
"1",
":",
"res",
"=",
"res",
"[",
"0",
"]",
"else",
":",
"res",
"=",
"tuple",
"(",
"res",
")",
"if",
"kwargs",
".",
"has_key",
"(",
"'cast'",
")",
":",
"if",
"nout",
"==",
"0",
":",
"raise",
"TypeError",
"(",
"\"Can't cast: 0 nout\"",
")",
"return",
"kwargs",
"[",
"'cast'",
"]",
"(",
"res",
")",
"else",
":",
"return",
"res",
"finally",
":",
"if",
"len",
"(",
"tempargs",
")",
"and",
"self",
".",
"_clear_call_args",
":",
"mlabraw",
".",
"eval",
"(",
"self",
".",
"_session",
",",
"\"clear('%s');\"",
"%",
"\"','\"",
".",
"join",
"(",
"tempargs",
")",
")"
] | Semi-raw execution of a matlab command.
Smartly handle calls to matlab, figure out what to do with `args`,
and when to use function call syntax and not.
If no `args` are specified, the ``cmd`` not ``result = cmd()`` form is
used in Matlab -- this also makes literal Matlab commands legal
(eg. cmd=``get(gca, 'Children')``).
If ``nout=0`` is specified, the Matlab command is executed as
procedure, otherwise it is executed as function (default), nout
specifying how many values should be returned (default 1).
**Beware that if you use don't specify ``nout=0`` for a `cmd` that
never returns a value will raise an error** (because assigning a
variable to a call that doesn't return a value is illegal in matlab).
``cast`` specifies which typecast should be applied to the result
(e.g. `int`), it defaults to none.
XXX: should we add ``parens`` parameter? | [
"Semi",
"-",
"raw",
"execution",
"of",
"a",
"matlab",
"command",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/mlabwrap.py#L487-L559 | train |
ewiger/mlab | src/mlab/mlabwrap.py | MlabWrap._get | def _get(self, name, remove=False):
r"""Directly access a variable in matlab space.
This should normally not be used by user code."""
# FIXME should this really be needed in normal operation?
if name in self._proxies: return self._proxies[name]
varname = name
vartype = self._var_type(varname)
if vartype in self._mlabraw_can_convert:
var = mlabraw.get(self._session, varname)
if isinstance(var, ndarray):
if self._flatten_row_vecs and numpy.shape(var)[0] == 1:
var.shape = var.shape[1:2]
elif self._flatten_col_vecs and numpy.shape(var)[1] == 1:
var.shape = var.shape[0:1]
if self._array_cast:
var = self._array_cast(var)
else:
var = None
if self._dont_proxy.get(vartype):
# manual conversions may fail (e.g. for multidimensional
# cell arrays), in that case just fall back on proxying.
try:
var = self._manually_convert(varname, vartype)
except MlabConversionError: pass
if var is None:
# we can't convert this to a python object, so we just
# create a proxy, and don't delete the real matlab
# reference until the proxy is garbage collected
var = self._make_proxy(varname)
if remove:
mlabraw.eval(self._session, "clear('%s');" % varname)
return var | python | def _get(self, name, remove=False):
r"""Directly access a variable in matlab space.
This should normally not be used by user code."""
# FIXME should this really be needed in normal operation?
if name in self._proxies: return self._proxies[name]
varname = name
vartype = self._var_type(varname)
if vartype in self._mlabraw_can_convert:
var = mlabraw.get(self._session, varname)
if isinstance(var, ndarray):
if self._flatten_row_vecs and numpy.shape(var)[0] == 1:
var.shape = var.shape[1:2]
elif self._flatten_col_vecs and numpy.shape(var)[1] == 1:
var.shape = var.shape[0:1]
if self._array_cast:
var = self._array_cast(var)
else:
var = None
if self._dont_proxy.get(vartype):
# manual conversions may fail (e.g. for multidimensional
# cell arrays), in that case just fall back on proxying.
try:
var = self._manually_convert(varname, vartype)
except MlabConversionError: pass
if var is None:
# we can't convert this to a python object, so we just
# create a proxy, and don't delete the real matlab
# reference until the proxy is garbage collected
var = self._make_proxy(varname)
if remove:
mlabraw.eval(self._session, "clear('%s');" % varname)
return var | [
"def",
"_get",
"(",
"self",
",",
"name",
",",
"remove",
"=",
"False",
")",
":",
"# FIXME should this really be needed in normal operation?",
"if",
"name",
"in",
"self",
".",
"_proxies",
":",
"return",
"self",
".",
"_proxies",
"[",
"name",
"]",
"varname",
"=",
"name",
"vartype",
"=",
"self",
".",
"_var_type",
"(",
"varname",
")",
"if",
"vartype",
"in",
"self",
".",
"_mlabraw_can_convert",
":",
"var",
"=",
"mlabraw",
".",
"get",
"(",
"self",
".",
"_session",
",",
"varname",
")",
"if",
"isinstance",
"(",
"var",
",",
"ndarray",
")",
":",
"if",
"self",
".",
"_flatten_row_vecs",
"and",
"numpy",
".",
"shape",
"(",
"var",
")",
"[",
"0",
"]",
"==",
"1",
":",
"var",
".",
"shape",
"=",
"var",
".",
"shape",
"[",
"1",
":",
"2",
"]",
"elif",
"self",
".",
"_flatten_col_vecs",
"and",
"numpy",
".",
"shape",
"(",
"var",
")",
"[",
"1",
"]",
"==",
"1",
":",
"var",
".",
"shape",
"=",
"var",
".",
"shape",
"[",
"0",
":",
"1",
"]",
"if",
"self",
".",
"_array_cast",
":",
"var",
"=",
"self",
".",
"_array_cast",
"(",
"var",
")",
"else",
":",
"var",
"=",
"None",
"if",
"self",
".",
"_dont_proxy",
".",
"get",
"(",
"vartype",
")",
":",
"# manual conversions may fail (e.g. for multidimensional",
"# cell arrays), in that case just fall back on proxying.",
"try",
":",
"var",
"=",
"self",
".",
"_manually_convert",
"(",
"varname",
",",
"vartype",
")",
"except",
"MlabConversionError",
":",
"pass",
"if",
"var",
"is",
"None",
":",
"# we can't convert this to a python object, so we just",
"# create a proxy, and don't delete the real matlab",
"# reference until the proxy is garbage collected",
"var",
"=",
"self",
".",
"_make_proxy",
"(",
"varname",
")",
"if",
"remove",
":",
"mlabraw",
".",
"eval",
"(",
"self",
".",
"_session",
",",
"\"clear('%s');\"",
"%",
"varname",
")",
"return",
"var"
] | r"""Directly access a variable in matlab space.
This should normally not be used by user code. | [
"r",
"Directly",
"access",
"a",
"variable",
"in",
"matlab",
"space",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/mlabwrap.py#L561-L593 | train |
ewiger/mlab | src/mlab/mlabwrap.py | MlabWrap._set | def _set(self, name, value):
r"""Directly set a variable `name` in matlab space to `value`.
This should normally not be used in user code."""
if isinstance(value, MlabObjectProxy):
mlabraw.eval(self._session, "%s = %s;" % (name, value._name))
else:
## mlabraw.put(self._session, name, self._as_mlabable_type(value))
mlabraw.put(self._session, name, value) | python | def _set(self, name, value):
r"""Directly set a variable `name` in matlab space to `value`.
This should normally not be used in user code."""
if isinstance(value, MlabObjectProxy):
mlabraw.eval(self._session, "%s = %s;" % (name, value._name))
else:
## mlabraw.put(self._session, name, self._as_mlabable_type(value))
mlabraw.put(self._session, name, value) | [
"def",
"_set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"MlabObjectProxy",
")",
":",
"mlabraw",
".",
"eval",
"(",
"self",
".",
"_session",
",",
"\"%s = %s;\"",
"%",
"(",
"name",
",",
"value",
".",
"_name",
")",
")",
"else",
":",
"## mlabraw.put(self._session, name, self._as_mlabable_type(value))",
"mlabraw",
".",
"put",
"(",
"self",
".",
"_session",
",",
"name",
",",
"value",
")"
] | r"""Directly set a variable `name` in matlab space to `value`.
This should normally not be used in user code. | [
"r",
"Directly",
"set",
"a",
"variable",
"name",
"in",
"matlab",
"space",
"to",
"value",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/mlabwrap.py#L595-L603 | train |
ewiger/mlab | src/mlab/matlabcom.py | MatlabCom.open | def open(self, visible=False):
""" Dispatches the matlab COM client.
Note: If this method fails, try running matlab with the -regserver flag.
"""
if self.client:
raise MatlabConnectionError('Matlab(TM) COM client is still active. Use close to '
'close it')
self.client = win32com.client.Dispatch('matlab.application')
self.client.visible = visible | python | def open(self, visible=False):
""" Dispatches the matlab COM client.
Note: If this method fails, try running matlab with the -regserver flag.
"""
if self.client:
raise MatlabConnectionError('Matlab(TM) COM client is still active. Use close to '
'close it')
self.client = win32com.client.Dispatch('matlab.application')
self.client.visible = visible | [
"def",
"open",
"(",
"self",
",",
"visible",
"=",
"False",
")",
":",
"if",
"self",
".",
"client",
":",
"raise",
"MatlabConnectionError",
"(",
"'Matlab(TM) COM client is still active. Use close to '",
"'close it'",
")",
"self",
".",
"client",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
"'matlab.application'",
")",
"self",
".",
"client",
".",
"visible",
"=",
"visible"
] | Dispatches the matlab COM client.
Note: If this method fails, try running matlab with the -regserver flag. | [
"Dispatches",
"the",
"matlab",
"COM",
"client",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabcom.py#L54-L63 | train |
ewiger/mlab | src/mlab/matlabcom.py | MatlabCom.eval | def eval(self, expression, identify_erros=True):
""" Evaluates a matlab expression synchronously.
If identify_erros is true, and the last output line after evaluating the
expressions begins with '???' an excpetion is thrown with the matlab error
following the '???'.
The return value of the function is the matlab output following the call.
"""
#print expression
self._check_open()
ret = self.client.Execute(expression)
#print ret
if identify_erros and ret.rfind('???') != -1:
begin = ret.rfind('???') + 4
raise MatlabError(ret[begin:])
return ret | python | def eval(self, expression, identify_erros=True):
""" Evaluates a matlab expression synchronously.
If identify_erros is true, and the last output line after evaluating the
expressions begins with '???' an excpetion is thrown with the matlab error
following the '???'.
The return value of the function is the matlab output following the call.
"""
#print expression
self._check_open()
ret = self.client.Execute(expression)
#print ret
if identify_erros and ret.rfind('???') != -1:
begin = ret.rfind('???') + 4
raise MatlabError(ret[begin:])
return ret | [
"def",
"eval",
"(",
"self",
",",
"expression",
",",
"identify_erros",
"=",
"True",
")",
":",
"#print expression",
"self",
".",
"_check_open",
"(",
")",
"ret",
"=",
"self",
".",
"client",
".",
"Execute",
"(",
"expression",
")",
"#print ret",
"if",
"identify_erros",
"and",
"ret",
".",
"rfind",
"(",
"'???'",
")",
"!=",
"-",
"1",
":",
"begin",
"=",
"ret",
".",
"rfind",
"(",
"'???'",
")",
"+",
"4",
"raise",
"MatlabError",
"(",
"ret",
"[",
"begin",
":",
"]",
")",
"return",
"ret"
] | Evaluates a matlab expression synchronously.
If identify_erros is true, and the last output line after evaluating the
expressions begins with '???' an excpetion is thrown with the matlab error
following the '???'.
The return value of the function is the matlab output following the call. | [
"Evaluates",
"a",
"matlab",
"expression",
"synchronously",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabcom.py#L75-L90 | train |
ewiger/mlab | src/mlab/matlabcom.py | MatlabCom.get | def get(self, names_to_get, convert_to_numpy=True):
""" Loads the requested variables from the matlab com client.
names_to_get can be either a variable name or a list of variable names.
If it is a variable name, the values is returned.
If it is a list, a dictionary of variable_name -> value is returned.
If convert_to_numpy is true, the method will all array values to numpy
arrays. Scalars are left as regular python objects.
"""
self._check_open()
single_itme = isinstance(names_to_get, (unicode, str))
if single_itme:
names_to_get = [names_to_get]
ret = {}
for name in names_to_get:
ret[name] = self.client.GetWorkspaceData(name, 'base')
# TODO(daniv): Do we really want to reduce dimensions like that? what if this a row vector?
while isinstance(ret[name], (tuple, list)) and len(ret[name]) == 1:
ret[name] = ret[name][0]
if convert_to_numpy and isinstance(ret[name], (tuple, list)):
ret[name] = np.array(ret[name])
if single_itme:
return ret.values()[0]
return ret | python | def get(self, names_to_get, convert_to_numpy=True):
""" Loads the requested variables from the matlab com client.
names_to_get can be either a variable name or a list of variable names.
If it is a variable name, the values is returned.
If it is a list, a dictionary of variable_name -> value is returned.
If convert_to_numpy is true, the method will all array values to numpy
arrays. Scalars are left as regular python objects.
"""
self._check_open()
single_itme = isinstance(names_to_get, (unicode, str))
if single_itme:
names_to_get = [names_to_get]
ret = {}
for name in names_to_get:
ret[name] = self.client.GetWorkspaceData(name, 'base')
# TODO(daniv): Do we really want to reduce dimensions like that? what if this a row vector?
while isinstance(ret[name], (tuple, list)) and len(ret[name]) == 1:
ret[name] = ret[name][0]
if convert_to_numpy and isinstance(ret[name], (tuple, list)):
ret[name] = np.array(ret[name])
if single_itme:
return ret.values()[0]
return ret | [
"def",
"get",
"(",
"self",
",",
"names_to_get",
",",
"convert_to_numpy",
"=",
"True",
")",
":",
"self",
".",
"_check_open",
"(",
")",
"single_itme",
"=",
"isinstance",
"(",
"names_to_get",
",",
"(",
"unicode",
",",
"str",
")",
")",
"if",
"single_itme",
":",
"names_to_get",
"=",
"[",
"names_to_get",
"]",
"ret",
"=",
"{",
"}",
"for",
"name",
"in",
"names_to_get",
":",
"ret",
"[",
"name",
"]",
"=",
"self",
".",
"client",
".",
"GetWorkspaceData",
"(",
"name",
",",
"'base'",
")",
"# TODO(daniv): Do we really want to reduce dimensions like that? what if this a row vector?",
"while",
"isinstance",
"(",
"ret",
"[",
"name",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"len",
"(",
"ret",
"[",
"name",
"]",
")",
"==",
"1",
":",
"ret",
"[",
"name",
"]",
"=",
"ret",
"[",
"name",
"]",
"[",
"0",
"]",
"if",
"convert_to_numpy",
"and",
"isinstance",
"(",
"ret",
"[",
"name",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"ret",
"[",
"name",
"]",
"=",
"np",
".",
"array",
"(",
"ret",
"[",
"name",
"]",
")",
"if",
"single_itme",
":",
"return",
"ret",
".",
"values",
"(",
")",
"[",
"0",
"]",
"return",
"ret"
] | Loads the requested variables from the matlab com client.
names_to_get can be either a variable name or a list of variable names.
If it is a variable name, the values is returned.
If it is a list, a dictionary of variable_name -> value is returned.
If convert_to_numpy is true, the method will all array values to numpy
arrays. Scalars are left as regular python objects. | [
"Loads",
"the",
"requested",
"variables",
"from",
"the",
"matlab",
"com",
"client",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabcom.py#L92-L117 | train |
ewiger/mlab | src/mlab/matlabcom.py | MatlabCom.put | def put(self, name_to_val):
""" Loads a dictionary of variable names into the matlab com client.
"""
self._check_open()
for name, val in name_to_val.iteritems():
# First try to put data as a matrix:
try:
self.client.PutFullMatrix(name, 'base', val, None)
except:
self.client.PutWorkspaceData(name, 'base', val) | python | def put(self, name_to_val):
""" Loads a dictionary of variable names into the matlab com client.
"""
self._check_open()
for name, val in name_to_val.iteritems():
# First try to put data as a matrix:
try:
self.client.PutFullMatrix(name, 'base', val, None)
except:
self.client.PutWorkspaceData(name, 'base', val) | [
"def",
"put",
"(",
"self",
",",
"name_to_val",
")",
":",
"self",
".",
"_check_open",
"(",
")",
"for",
"name",
",",
"val",
"in",
"name_to_val",
".",
"iteritems",
"(",
")",
":",
"# First try to put data as a matrix:",
"try",
":",
"self",
".",
"client",
".",
"PutFullMatrix",
"(",
"name",
",",
"'base'",
",",
"val",
",",
"None",
")",
"except",
":",
"self",
".",
"client",
".",
"PutWorkspaceData",
"(",
"name",
",",
"'base'",
",",
"val",
")"
] | Loads a dictionary of variable names into the matlab com client. | [
"Loads",
"a",
"dictionary",
"of",
"variable",
"names",
"into",
"the",
"matlab",
"com",
"client",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabcom.py#L119-L128 | train |
ewiger/mlab | src/mlab/mlabraw.py | open | def open():
global _MATLAB_RELEASE
'''Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location '''
if is_win:
ret = MatlabConnection()
ret.open()
return ret
else:
if settings.MATLAB_PATH != 'guess':
matlab_path = settings.MATLAB_PATH + '/bin/matlab'
elif _MATLAB_RELEASE != 'latest':
matlab_path = discover_location(_MATLAB_RELEASE)
else:
# Latest release is found in __init__.by, i.e. higher logical level
raise MatlabReleaseNotFound('Please select a matlab release or set its location.')
try:
ret = MatlabConnection(matlab_path)
ret.open()
except Exception:
#traceback.print_exc(file=sys.stderr)
raise MatlabReleaseNotFound('Could not open matlab, is it in %s?' % matlab_path)
return ret | python | def open():
global _MATLAB_RELEASE
'''Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location '''
if is_win:
ret = MatlabConnection()
ret.open()
return ret
else:
if settings.MATLAB_PATH != 'guess':
matlab_path = settings.MATLAB_PATH + '/bin/matlab'
elif _MATLAB_RELEASE != 'latest':
matlab_path = discover_location(_MATLAB_RELEASE)
else:
# Latest release is found in __init__.by, i.e. higher logical level
raise MatlabReleaseNotFound('Please select a matlab release or set its location.')
try:
ret = MatlabConnection(matlab_path)
ret.open()
except Exception:
#traceback.print_exc(file=sys.stderr)
raise MatlabReleaseNotFound('Could not open matlab, is it in %s?' % matlab_path)
return ret | [
"def",
"open",
"(",
")",
":",
"global",
"_MATLAB_RELEASE",
"if",
"is_win",
":",
"ret",
"=",
"MatlabConnection",
"(",
")",
"ret",
".",
"open",
"(",
")",
"return",
"ret",
"else",
":",
"if",
"settings",
".",
"MATLAB_PATH",
"!=",
"'guess'",
":",
"matlab_path",
"=",
"settings",
".",
"MATLAB_PATH",
"+",
"'/bin/matlab'",
"elif",
"_MATLAB_RELEASE",
"!=",
"'latest'",
":",
"matlab_path",
"=",
"discover_location",
"(",
"_MATLAB_RELEASE",
")",
"else",
":",
"# Latest release is found in __init__.by, i.e. higher logical level",
"raise",
"MatlabReleaseNotFound",
"(",
"'Please select a matlab release or set its location.'",
")",
"try",
":",
"ret",
"=",
"MatlabConnection",
"(",
"matlab_path",
")",
"ret",
".",
"open",
"(",
")",
"except",
"Exception",
":",
"#traceback.print_exc(file=sys.stderr)",
"raise",
"MatlabReleaseNotFound",
"(",
"'Could not open matlab, is it in %s?'",
"%",
"matlab_path",
")",
"return",
"ret"
] | Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location | [
"Opens",
"MATLAB",
"using",
"specified",
"connection",
"(",
"or",
"DCOM",
"+",
"protocol",
"on",
"Windows",
")",
"where",
"matlab_location"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/mlabraw.py#L39-L60 | train |
ewiger/mlab | src/mlab/matlabpipe.py | _list_releases | def _list_releases():
'''
Tries to guess matlab process release version and location path on
osx machines.
The paths we will search are in the format:
/Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab
We will try the latest version first. If no path is found, None is reutrned.
'''
if is_linux():
base_path = '/usr/local/MATLAB/R%d%s/bin/matlab'
else:
# assume mac
base_path = '/Applications/MATLAB_R%d%s.app/bin/matlab'
years = range(2050,1990,-1)
release_letters = ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')
for year in years:
for letter in release_letters:
release = 'R%d%s' % (year, letter)
matlab_path = base_path % (year, letter)
if os.path.exists(matlab_path):
yield (release, matlab_path) | python | def _list_releases():
'''
Tries to guess matlab process release version and location path on
osx machines.
The paths we will search are in the format:
/Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab
We will try the latest version first. If no path is found, None is reutrned.
'''
if is_linux():
base_path = '/usr/local/MATLAB/R%d%s/bin/matlab'
else:
# assume mac
base_path = '/Applications/MATLAB_R%d%s.app/bin/matlab'
years = range(2050,1990,-1)
release_letters = ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')
for year in years:
for letter in release_letters:
release = 'R%d%s' % (year, letter)
matlab_path = base_path % (year, letter)
if os.path.exists(matlab_path):
yield (release, matlab_path) | [
"def",
"_list_releases",
"(",
")",
":",
"if",
"is_linux",
"(",
")",
":",
"base_path",
"=",
"'/usr/local/MATLAB/R%d%s/bin/matlab'",
"else",
":",
"# assume mac",
"base_path",
"=",
"'/Applications/MATLAB_R%d%s.app/bin/matlab'",
"years",
"=",
"range",
"(",
"2050",
",",
"1990",
",",
"-",
"1",
")",
"release_letters",
"=",
"(",
"'h'",
",",
"'g'",
",",
"'f'",
",",
"'e'",
",",
"'d'",
",",
"'c'",
",",
"'b'",
",",
"'a'",
")",
"for",
"year",
"in",
"years",
":",
"for",
"letter",
"in",
"release_letters",
":",
"release",
"=",
"'R%d%s'",
"%",
"(",
"year",
",",
"letter",
")",
"matlab_path",
"=",
"base_path",
"%",
"(",
"year",
",",
"letter",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"matlab_path",
")",
":",
"yield",
"(",
"release",
",",
"matlab_path",
")"
] | Tries to guess matlab process release version and location path on
osx machines.
The paths we will search are in the format:
/Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab
We will try the latest version first. If no path is found, None is reutrned. | [
"Tries",
"to",
"guess",
"matlab",
"process",
"release",
"version",
"and",
"location",
"path",
"on",
"osx",
"machines",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L41-L62 | train |
ewiger/mlab | src/mlab/matlabpipe.py | is_valid_release_version | def is_valid_release_version(version):
'''Checks that the given version code is valid.'''
return version is not None and len(version) == 6 and version[0] == 'R' \
and int(version[1:5]) in range(1990, 2050) \
and version[5] in ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a') | python | def is_valid_release_version(version):
'''Checks that the given version code is valid.'''
return version is not None and len(version) == 6 and version[0] == 'R' \
and int(version[1:5]) in range(1990, 2050) \
and version[5] in ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a') | [
"def",
"is_valid_release_version",
"(",
"version",
")",
":",
"return",
"version",
"is",
"not",
"None",
"and",
"len",
"(",
"version",
")",
"==",
"6",
"and",
"version",
"[",
"0",
"]",
"==",
"'R'",
"and",
"int",
"(",
"version",
"[",
"1",
":",
"5",
"]",
")",
"in",
"range",
"(",
"1990",
",",
"2050",
")",
"and",
"version",
"[",
"5",
"]",
"in",
"(",
"'h'",
",",
"'g'",
",",
"'f'",
",",
"'e'",
",",
"'d'",
",",
"'c'",
",",
"'b'",
",",
"'a'",
")"
] | Checks that the given version code is valid. | [
"Checks",
"that",
"the",
"given",
"version",
"code",
"is",
"valid",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L72-L76 | train |
ewiger/mlab | src/mlab/matlabpipe.py | find_matlab_version | def find_matlab_version(process_path):
""" Tries to guess matlab's version according to its process path.
If we couldn't gues the version, None is returned.
"""
bin_path = os.path.dirname(process_path)
matlab_path = os.path.dirname(bin_path)
matlab_dir_name = os.path.basename(matlab_path)
version = matlab_dir_name
if not is_linux():
version = matlab_dir_name.replace('MATLAB_', '').replace('.app', '')
if not is_valid_release_version(version):
return None
return version | python | def find_matlab_version(process_path):
""" Tries to guess matlab's version according to its process path.
If we couldn't gues the version, None is returned.
"""
bin_path = os.path.dirname(process_path)
matlab_path = os.path.dirname(bin_path)
matlab_dir_name = os.path.basename(matlab_path)
version = matlab_dir_name
if not is_linux():
version = matlab_dir_name.replace('MATLAB_', '').replace('.app', '')
if not is_valid_release_version(version):
return None
return version | [
"def",
"find_matlab_version",
"(",
"process_path",
")",
":",
"bin_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"process_path",
")",
"matlab_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"bin_path",
")",
"matlab_dir_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"matlab_path",
")",
"version",
"=",
"matlab_dir_name",
"if",
"not",
"is_linux",
"(",
")",
":",
"version",
"=",
"matlab_dir_name",
".",
"replace",
"(",
"'MATLAB_'",
",",
"''",
")",
".",
"replace",
"(",
"'.app'",
",",
"''",
")",
"if",
"not",
"is_valid_release_version",
"(",
"version",
")",
":",
"return",
"None",
"return",
"version"
] | Tries to guess matlab's version according to its process path.
If we couldn't gues the version, None is returned. | [
"Tries",
"to",
"guess",
"matlab",
"s",
"version",
"according",
"to",
"its",
"process",
"path",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L91-L104 | train |
ewiger/mlab | src/mlab/matlabpipe.py | MatlabPipe.open | def open(self, print_matlab_welcome=False):
'''Opens the matlab process.'''
if self.process and not self.process.returncode:
raise MatlabConnectionError('Matlab(TM) process is still active. Use close to '
'close it')
self.process = subprocess.Popen(
[self.matlab_process_path, '-nojvm', '-nodesktop'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
flags = fcntl.fcntl(self.process.stdout, fcntl.F_GETFL)
fcntl.fcntl(self.process.stdout, fcntl.F_SETFL, flags| os.O_NONBLOCK)
if print_matlab_welcome:
self._sync_output()
else:
self._sync_output(None) | python | def open(self, print_matlab_welcome=False):
'''Opens the matlab process.'''
if self.process and not self.process.returncode:
raise MatlabConnectionError('Matlab(TM) process is still active. Use close to '
'close it')
self.process = subprocess.Popen(
[self.matlab_process_path, '-nojvm', '-nodesktop'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
flags = fcntl.fcntl(self.process.stdout, fcntl.F_GETFL)
fcntl.fcntl(self.process.stdout, fcntl.F_SETFL, flags| os.O_NONBLOCK)
if print_matlab_welcome:
self._sync_output()
else:
self._sync_output(None) | [
"def",
"open",
"(",
"self",
",",
"print_matlab_welcome",
"=",
"False",
")",
":",
"if",
"self",
".",
"process",
"and",
"not",
"self",
".",
"process",
".",
"returncode",
":",
"raise",
"MatlabConnectionError",
"(",
"'Matlab(TM) process is still active. Use close to '",
"'close it'",
")",
"self",
".",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"self",
".",
"matlab_process_path",
",",
"'-nojvm'",
",",
"'-nodesktop'",
"]",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"flags",
"=",
"fcntl",
".",
"fcntl",
"(",
"self",
".",
"process",
".",
"stdout",
",",
"fcntl",
".",
"F_GETFL",
")",
"fcntl",
".",
"fcntl",
"(",
"self",
".",
"process",
".",
"stdout",
",",
"fcntl",
".",
"F_SETFL",
",",
"flags",
"|",
"os",
".",
"O_NONBLOCK",
")",
"if",
"print_matlab_welcome",
":",
"self",
".",
"_sync_output",
"(",
")",
"else",
":",
"self",
".",
"_sync_output",
"(",
"None",
")"
] | Opens the matlab process. | [
"Opens",
"the",
"matlab",
"process",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L148-L162 | train |
ewiger/mlab | src/mlab/matlabpipe.py | MatlabPipe.eval | def eval(self,
expression,
identify_errors=True,
print_expression=True,
on_new_output=sys.stdout.write):
""" Evaluates a matlab expression synchronously.
If identify_erros is true, and the last output line after evaluating the
expressions begins with '???' and excpetion is thrown with the matlab error
following the '???'.
If on_new_output is not None, it will be called whenever a new output is
encountered. The default value prints the new output to the screen.
The return value of the function is the matlab output following the call.
"""
self._check_open()
if print_expression:
print expression
self.process.stdin.write(expression)
self.process.stdin.write('\n')
ret = self._sync_output(on_new_output)
# TODO(dani): Use stderr to identify errors.
if identify_errors and ret.rfind('???') != -1:
begin = ret.rfind('???') + 4
end = ret.find('\n', begin)
raise MatlabError(ret[begin:end])
return ret | python | def eval(self,
expression,
identify_errors=True,
print_expression=True,
on_new_output=sys.stdout.write):
""" Evaluates a matlab expression synchronously.
If identify_erros is true, and the last output line after evaluating the
expressions begins with '???' and excpetion is thrown with the matlab error
following the '???'.
If on_new_output is not None, it will be called whenever a new output is
encountered. The default value prints the new output to the screen.
The return value of the function is the matlab output following the call.
"""
self._check_open()
if print_expression:
print expression
self.process.stdin.write(expression)
self.process.stdin.write('\n')
ret = self._sync_output(on_new_output)
# TODO(dani): Use stderr to identify errors.
if identify_errors and ret.rfind('???') != -1:
begin = ret.rfind('???') + 4
end = ret.find('\n', begin)
raise MatlabError(ret[begin:end])
return ret | [
"def",
"eval",
"(",
"self",
",",
"expression",
",",
"identify_errors",
"=",
"True",
",",
"print_expression",
"=",
"True",
",",
"on_new_output",
"=",
"sys",
".",
"stdout",
".",
"write",
")",
":",
"self",
".",
"_check_open",
"(",
")",
"if",
"print_expression",
":",
"print",
"expression",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"expression",
")",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"'\\n'",
")",
"ret",
"=",
"self",
".",
"_sync_output",
"(",
"on_new_output",
")",
"# TODO(dani): Use stderr to identify errors.",
"if",
"identify_errors",
"and",
"ret",
".",
"rfind",
"(",
"'???'",
")",
"!=",
"-",
"1",
":",
"begin",
"=",
"ret",
".",
"rfind",
"(",
"'???'",
")",
"+",
"4",
"end",
"=",
"ret",
".",
"find",
"(",
"'\\n'",
",",
"begin",
")",
"raise",
"MatlabError",
"(",
"ret",
"[",
"begin",
":",
"end",
"]",
")",
"return",
"ret"
] | Evaluates a matlab expression synchronously.
If identify_erros is true, and the last output line after evaluating the
expressions begins with '???' and excpetion is thrown with the matlab error
following the '???'.
If on_new_output is not None, it will be called whenever a new output is
encountered. The default value prints the new output to the screen.
The return value of the function is the matlab output following the call. | [
"Evaluates",
"a",
"matlab",
"expression",
"synchronously",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L170-L195 | train |
ewiger/mlab | src/mlab/matlabpipe.py | MatlabPipe.put | def put(self, name_to_val, oned_as='row', on_new_output=None):
""" Loads a dictionary of variable names into the matlab shell.
oned_as is the same as in scipy.io.matlab.savemat function:
oned_as : {'column', 'row'}, optional
If 'column', write 1-D numpy arrays as column vectors.
If 'row', write 1D numpy arrays as row vectors.
"""
self._check_open()
# We can't give stdin to mlabio.savemat because it needs random access :(
temp = StringIO()
mlabio.savemat(temp, name_to_val, oned_as=oned_as)
temp.seek(0)
temp_str = temp.read()
temp.close()
self.process.stdin.write('load stdio;\n')
self._read_until('ack load stdio\n', on_new_output=on_new_output)
self.process.stdin.write(temp_str)
#print 'sent %d kb' % (len(temp_str) / 1024)
self._read_until('ack load finished\n', on_new_output=on_new_output)
self._sync_output(on_new_output=on_new_output) | python | def put(self, name_to_val, oned_as='row', on_new_output=None):
""" Loads a dictionary of variable names into the matlab shell.
oned_as is the same as in scipy.io.matlab.savemat function:
oned_as : {'column', 'row'}, optional
If 'column', write 1-D numpy arrays as column vectors.
If 'row', write 1D numpy arrays as row vectors.
"""
self._check_open()
# We can't give stdin to mlabio.savemat because it needs random access :(
temp = StringIO()
mlabio.savemat(temp, name_to_val, oned_as=oned_as)
temp.seek(0)
temp_str = temp.read()
temp.close()
self.process.stdin.write('load stdio;\n')
self._read_until('ack load stdio\n', on_new_output=on_new_output)
self.process.stdin.write(temp_str)
#print 'sent %d kb' % (len(temp_str) / 1024)
self._read_until('ack load finished\n', on_new_output=on_new_output)
self._sync_output(on_new_output=on_new_output) | [
"def",
"put",
"(",
"self",
",",
"name_to_val",
",",
"oned_as",
"=",
"'row'",
",",
"on_new_output",
"=",
"None",
")",
":",
"self",
".",
"_check_open",
"(",
")",
"# We can't give stdin to mlabio.savemat because it needs random access :(",
"temp",
"=",
"StringIO",
"(",
")",
"mlabio",
".",
"savemat",
"(",
"temp",
",",
"name_to_val",
",",
"oned_as",
"=",
"oned_as",
")",
"temp",
".",
"seek",
"(",
"0",
")",
"temp_str",
"=",
"temp",
".",
"read",
"(",
")",
"temp",
".",
"close",
"(",
")",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"'load stdio;\\n'",
")",
"self",
".",
"_read_until",
"(",
"'ack load stdio\\n'",
",",
"on_new_output",
"=",
"on_new_output",
")",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"temp_str",
")",
"#print 'sent %d kb' % (len(temp_str) / 1024)",
"self",
".",
"_read_until",
"(",
"'ack load finished\\n'",
",",
"on_new_output",
"=",
"on_new_output",
")",
"self",
".",
"_sync_output",
"(",
"on_new_output",
"=",
"on_new_output",
")"
] | Loads a dictionary of variable names into the matlab shell.
oned_as is the same as in scipy.io.matlab.savemat function:
oned_as : {'column', 'row'}, optional
If 'column', write 1-D numpy arrays as column vectors.
If 'row', write 1D numpy arrays as row vectors. | [
"Loads",
"a",
"dictionary",
"of",
"variable",
"names",
"into",
"the",
"matlab",
"shell",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L198-L218 | train |
ewiger/mlab | src/mlab/matlabpipe.py | MatlabPipe.get | def get(self,
names_to_get,
extract_numpy_scalars=True,
on_new_output=None):
""" Loads the requested variables from the matlab shell.
names_to_get can be either a variable name, a list of variable names, or
None.
If it is a variable name, the values is returned.
If it is a list, a dictionary of variable_name -> value is returned.
If it is None, a dictionary with all variables is returned.
If extract_numpy_scalars is true, the method will convert numpy scalars
(0-dimension arrays) to a regular python variable.
"""
self._check_open()
single_item = isinstance(names_to_get, (unicode, str))
if single_item:
names_to_get = [names_to_get]
if names_to_get == None:
self.process.stdin.write('save stdio;\n')
else:
# Make sure that we throw an excpetion if the names are not defined.
for name in names_to_get:
self.eval('%s;' % name, print_expression=False, on_new_output=on_new_output)
#print 'save(\'stdio\', \'%s\');\n' % '\', \''.join(names_to_get)
self.process.stdin.write(
"save('stdio', '%s', '-v7');\n" % '\', \''.join(names_to_get))
# We have to read to a temp buffer because mlabio.loadmat needs
# random access :(
self._read_until('start_binary\n', on_new_output=on_new_output)
#print 'got start_binary'
temp_str = self._sync_output(on_new_output=on_new_output)
#print 'got all outout'
# Remove expected output and "\n>>"
# TODO(dani): Get rid of the unecessary copy.
# MATLAB 2010a adds an extra >> so we need to remove more spaces.
if self.matlab_version == (2010, 'a'):
temp_str = temp_str[:-len(self.expected_output_end)-6]
else:
temp_str = temp_str[:-len(self.expected_output_end)-3]
temp = StringIO(temp_str)
#print ('____')
#print len(temp_str)
#print ('____')
ret = mlabio.loadmat(temp, chars_as_strings=True, squeeze_me=True)
#print '******'
#print ret
#print '******'
temp.close()
if single_item:
return ret.values()[0]
for key in ret.iterkeys():
while ret[key].shape and ret[key].shape[-1] == 1:
ret[key] = ret[key][0]
if extract_numpy_scalars:
if isinstance(ret[key], np.ndarray) and not ret[key].shape:
ret[key] = ret[key].tolist()
#print 'done'
return ret | python | def get(self,
names_to_get,
extract_numpy_scalars=True,
on_new_output=None):
""" Loads the requested variables from the matlab shell.
names_to_get can be either a variable name, a list of variable names, or
None.
If it is a variable name, the values is returned.
If it is a list, a dictionary of variable_name -> value is returned.
If it is None, a dictionary with all variables is returned.
If extract_numpy_scalars is true, the method will convert numpy scalars
(0-dimension arrays) to a regular python variable.
"""
self._check_open()
single_item = isinstance(names_to_get, (unicode, str))
if single_item:
names_to_get = [names_to_get]
if names_to_get == None:
self.process.stdin.write('save stdio;\n')
else:
# Make sure that we throw an excpetion if the names are not defined.
for name in names_to_get:
self.eval('%s;' % name, print_expression=False, on_new_output=on_new_output)
#print 'save(\'stdio\', \'%s\');\n' % '\', \''.join(names_to_get)
self.process.stdin.write(
"save('stdio', '%s', '-v7');\n" % '\', \''.join(names_to_get))
# We have to read to a temp buffer because mlabio.loadmat needs
# random access :(
self._read_until('start_binary\n', on_new_output=on_new_output)
#print 'got start_binary'
temp_str = self._sync_output(on_new_output=on_new_output)
#print 'got all outout'
# Remove expected output and "\n>>"
# TODO(dani): Get rid of the unecessary copy.
# MATLAB 2010a adds an extra >> so we need to remove more spaces.
if self.matlab_version == (2010, 'a'):
temp_str = temp_str[:-len(self.expected_output_end)-6]
else:
temp_str = temp_str[:-len(self.expected_output_end)-3]
temp = StringIO(temp_str)
#print ('____')
#print len(temp_str)
#print ('____')
ret = mlabio.loadmat(temp, chars_as_strings=True, squeeze_me=True)
#print '******'
#print ret
#print '******'
temp.close()
if single_item:
return ret.values()[0]
for key in ret.iterkeys():
while ret[key].shape and ret[key].shape[-1] == 1:
ret[key] = ret[key][0]
if extract_numpy_scalars:
if isinstance(ret[key], np.ndarray) and not ret[key].shape:
ret[key] = ret[key].tolist()
#print 'done'
return ret | [
"def",
"get",
"(",
"self",
",",
"names_to_get",
",",
"extract_numpy_scalars",
"=",
"True",
",",
"on_new_output",
"=",
"None",
")",
":",
"self",
".",
"_check_open",
"(",
")",
"single_item",
"=",
"isinstance",
"(",
"names_to_get",
",",
"(",
"unicode",
",",
"str",
")",
")",
"if",
"single_item",
":",
"names_to_get",
"=",
"[",
"names_to_get",
"]",
"if",
"names_to_get",
"==",
"None",
":",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"'save stdio;\\n'",
")",
"else",
":",
"# Make sure that we throw an excpetion if the names are not defined.",
"for",
"name",
"in",
"names_to_get",
":",
"self",
".",
"eval",
"(",
"'%s;'",
"%",
"name",
",",
"print_expression",
"=",
"False",
",",
"on_new_output",
"=",
"on_new_output",
")",
"#print 'save(\\'stdio\\', \\'%s\\');\\n' % '\\', \\''.join(names_to_get)",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"\"save('stdio', '%s', '-v7');\\n\"",
"%",
"'\\', \\''",
".",
"join",
"(",
"names_to_get",
")",
")",
"# We have to read to a temp buffer because mlabio.loadmat needs",
"# random access :(",
"self",
".",
"_read_until",
"(",
"'start_binary\\n'",
",",
"on_new_output",
"=",
"on_new_output",
")",
"#print 'got start_binary'",
"temp_str",
"=",
"self",
".",
"_sync_output",
"(",
"on_new_output",
"=",
"on_new_output",
")",
"#print 'got all outout'",
"# Remove expected output and \"\\n>>\"",
"# TODO(dani): Get rid of the unecessary copy.",
"# MATLAB 2010a adds an extra >> so we need to remove more spaces.",
"if",
"self",
".",
"matlab_version",
"==",
"(",
"2010",
",",
"'a'",
")",
":",
"temp_str",
"=",
"temp_str",
"[",
":",
"-",
"len",
"(",
"self",
".",
"expected_output_end",
")",
"-",
"6",
"]",
"else",
":",
"temp_str",
"=",
"temp_str",
"[",
":",
"-",
"len",
"(",
"self",
".",
"expected_output_end",
")",
"-",
"3",
"]",
"temp",
"=",
"StringIO",
"(",
"temp_str",
")",
"#print ('____')",
"#print len(temp_str)",
"#print ('____')",
"ret",
"=",
"mlabio",
".",
"loadmat",
"(",
"temp",
",",
"chars_as_strings",
"=",
"True",
",",
"squeeze_me",
"=",
"True",
")",
"#print '******'",
"#print ret",
"#print '******'",
"temp",
".",
"close",
"(",
")",
"if",
"single_item",
":",
"return",
"ret",
".",
"values",
"(",
")",
"[",
"0",
"]",
"for",
"key",
"in",
"ret",
".",
"iterkeys",
"(",
")",
":",
"while",
"ret",
"[",
"key",
"]",
".",
"shape",
"and",
"ret",
"[",
"key",
"]",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"1",
":",
"ret",
"[",
"key",
"]",
"=",
"ret",
"[",
"key",
"]",
"[",
"0",
"]",
"if",
"extract_numpy_scalars",
":",
"if",
"isinstance",
"(",
"ret",
"[",
"key",
"]",
",",
"np",
".",
"ndarray",
")",
"and",
"not",
"ret",
"[",
"key",
"]",
".",
"shape",
":",
"ret",
"[",
"key",
"]",
"=",
"ret",
"[",
"key",
"]",
".",
"tolist",
"(",
")",
"#print 'done'",
"return",
"ret"
] | Loads the requested variables from the matlab shell.
names_to_get can be either a variable name, a list of variable names, or
None.
If it is a variable name, the values is returned.
If it is a list, a dictionary of variable_name -> value is returned.
If it is None, a dictionary with all variables is returned.
If extract_numpy_scalars is true, the method will convert numpy scalars
(0-dimension arrays) to a regular python variable. | [
"Loads",
"the",
"requested",
"variables",
"from",
"the",
"matlab",
"shell",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L220-L279 | train |
ewiger/mlab | src/mlab/awmstools.py | rexGroups | def rexGroups(rex):
"""Return the named groups in a regular expression (compiled or as string)
in occuring order.
>>> rexGroups(r'(?P<name>\w+) +(?P<surname>\w+)')
('name', 'surname')
"""
if isinstance(rex,basestring): rex = re.compile(rex)
return zip(*sorted([(n,g) for (g,n) in rex.groupindex.items()]))[1] | python | def rexGroups(rex):
"""Return the named groups in a regular expression (compiled or as string)
in occuring order.
>>> rexGroups(r'(?P<name>\w+) +(?P<surname>\w+)')
('name', 'surname')
"""
if isinstance(rex,basestring): rex = re.compile(rex)
return zip(*sorted([(n,g) for (g,n) in rex.groupindex.items()]))[1] | [
"def",
"rexGroups",
"(",
"rex",
")",
":",
"if",
"isinstance",
"(",
"rex",
",",
"basestring",
")",
":",
"rex",
"=",
"re",
".",
"compile",
"(",
"rex",
")",
"return",
"zip",
"(",
"*",
"sorted",
"(",
"[",
"(",
"n",
",",
"g",
")",
"for",
"(",
"g",
",",
"n",
")",
"in",
"rex",
".",
"groupindex",
".",
"items",
"(",
")",
"]",
")",
")",
"[",
"1",
"]"
] | Return the named groups in a regular expression (compiled or as string)
in occuring order.
>>> rexGroups(r'(?P<name>\w+) +(?P<surname>\w+)')
('name', 'surname') | [
"Return",
"the",
"named",
"groups",
"in",
"a",
"regular",
"expression",
"(",
"compiled",
"or",
"as",
"string",
")",
"in",
"occuring",
"order",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L140-L149 | train |
ewiger/mlab | src/mlab/awmstools.py | div | def div(a,b):
"""``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise
an `ValueError` is raised.
>>> div(10,2)
5
>>> div(10,3)
Traceback (most recent call last):
...
ValueError: 3 does not divide 10
"""
res, fail = divmod(a,b)
if fail:
raise ValueError("%r does not divide %r" % (b,a))
else:
return res | python | def div(a,b):
"""``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise
an `ValueError` is raised.
>>> div(10,2)
5
>>> div(10,3)
Traceback (most recent call last):
...
ValueError: 3 does not divide 10
"""
res, fail = divmod(a,b)
if fail:
raise ValueError("%r does not divide %r" % (b,a))
else:
return res | [
"def",
"div",
"(",
"a",
",",
"b",
")",
":",
"res",
",",
"fail",
"=",
"divmod",
"(",
"a",
",",
"b",
")",
"if",
"fail",
":",
"raise",
"ValueError",
"(",
"\"%r does not divide %r\"",
"%",
"(",
"b",
",",
"a",
")",
")",
"else",
":",
"return",
"res"
] | ``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise
an `ValueError` is raised.
>>> div(10,2)
5
>>> div(10,3)
Traceback (most recent call last):
...
ValueError: 3 does not divide 10 | [
"div",
"(",
"a",
"b",
")",
"is",
"like",
"a",
"//",
"b",
"if",
"b",
"devides",
"a",
"otherwise",
"an",
"ValueError",
"is",
"raised",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L243-L258 | train |
ewiger/mlab | src/mlab/awmstools.py | ipshuffle | def ipshuffle(l, random=None):
r"""Shuffle list `l` inplace and return it."""
import random as _random
_random.shuffle(l, random)
return l | python | def ipshuffle(l, random=None):
r"""Shuffle list `l` inplace and return it."""
import random as _random
_random.shuffle(l, random)
return l | [
"def",
"ipshuffle",
"(",
"l",
",",
"random",
"=",
"None",
")",
":",
"import",
"random",
"as",
"_random",
"_random",
".",
"shuffle",
"(",
"l",
",",
"random",
")",
"return",
"l"
] | r"""Shuffle list `l` inplace and return it. | [
"r",
"Shuffle",
"list",
"l",
"inplace",
"and",
"return",
"it",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L261-L265 | train |
ewiger/mlab | src/mlab/awmstools.py | shuffle | def shuffle(seq, random=None):
r"""Return shuffled *copy* of `seq`."""
if isinstance(seq, list):
return ipshuffle(seq[:], random)
elif isString(seq):
# seq[0:0] == "" or u""
return seq[0:0].join(ipshuffle(list(seq)),random)
else:
return type(seq)(ipshuffle(list(seq),random)) | python | def shuffle(seq, random=None):
r"""Return shuffled *copy* of `seq`."""
if isinstance(seq, list):
return ipshuffle(seq[:], random)
elif isString(seq):
# seq[0:0] == "" or u""
return seq[0:0].join(ipshuffle(list(seq)),random)
else:
return type(seq)(ipshuffle(list(seq),random)) | [
"def",
"shuffle",
"(",
"seq",
",",
"random",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"seq",
",",
"list",
")",
":",
"return",
"ipshuffle",
"(",
"seq",
"[",
":",
"]",
",",
"random",
")",
"elif",
"isString",
"(",
"seq",
")",
":",
"# seq[0:0] == \"\" or u\"\"",
"return",
"seq",
"[",
"0",
":",
"0",
"]",
".",
"join",
"(",
"ipshuffle",
"(",
"list",
"(",
"seq",
")",
")",
",",
"random",
")",
"else",
":",
"return",
"type",
"(",
"seq",
")",
"(",
"ipshuffle",
"(",
"list",
"(",
"seq",
")",
",",
"random",
")",
")"
] | r"""Return shuffled *copy* of `seq`. | [
"r",
"Return",
"shuffled",
"*",
"copy",
"*",
"of",
"seq",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L281-L289 | train |
ewiger/mlab | src/mlab/awmstools.py | slurp | def slurp(file, binary=False, expand=False):
r"""Read in a complete file `file` as a string
Parameters:
- `file`: a file handle or a string (`str` or `unicode`).
- `binary`: whether to read in the file in binary mode (default: False).
"""
mode = "r" + ["b",""][not binary]
file = _normalizeToFile(file, mode=mode, expand=expand)
try: return file.read()
finally: file.close() | python | def slurp(file, binary=False, expand=False):
r"""Read in a complete file `file` as a string
Parameters:
- `file`: a file handle or a string (`str` or `unicode`).
- `binary`: whether to read in the file in binary mode (default: False).
"""
mode = "r" + ["b",""][not binary]
file = _normalizeToFile(file, mode=mode, expand=expand)
try: return file.read()
finally: file.close() | [
"def",
"slurp",
"(",
"file",
",",
"binary",
"=",
"False",
",",
"expand",
"=",
"False",
")",
":",
"mode",
"=",
"\"r\"",
"+",
"[",
"\"b\"",
",",
"\"\"",
"]",
"[",
"not",
"binary",
"]",
"file",
"=",
"_normalizeToFile",
"(",
"file",
",",
"mode",
"=",
"mode",
",",
"expand",
"=",
"expand",
")",
"try",
":",
"return",
"file",
".",
"read",
"(",
")",
"finally",
":",
"file",
".",
"close",
"(",
")"
] | r"""Read in a complete file `file` as a string
Parameters:
- `file`: a file handle or a string (`str` or `unicode`).
- `binary`: whether to read in the file in binary mode (default: False). | [
"r",
"Read",
"in",
"a",
"complete",
"file",
"file",
"as",
"a",
"string",
"Parameters",
":"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L322-L332 | train |
ewiger/mlab | src/mlab/awmstools.py | withFile | def withFile(file, func, mode='r', expand=False):
"""Pass `file` to `func` and ensure the file is closed afterwards. If
`file` is a string, open according to `mode`; if `expand` is true also
expand user and vars.
"""
file = _normalizeToFile(file, mode=mode, expand=expand)
try: return func(file)
finally: file.close() | python | def withFile(file, func, mode='r', expand=False):
"""Pass `file` to `func` and ensure the file is closed afterwards. If
`file` is a string, open according to `mode`; if `expand` is true also
expand user and vars.
"""
file = _normalizeToFile(file, mode=mode, expand=expand)
try: return func(file)
finally: file.close() | [
"def",
"withFile",
"(",
"file",
",",
"func",
",",
"mode",
"=",
"'r'",
",",
"expand",
"=",
"False",
")",
":",
"file",
"=",
"_normalizeToFile",
"(",
"file",
",",
"mode",
"=",
"mode",
",",
"expand",
"=",
"expand",
")",
"try",
":",
"return",
"func",
"(",
"file",
")",
"finally",
":",
"file",
".",
"close",
"(",
")"
] | Pass `file` to `func` and ensure the file is closed afterwards. If
`file` is a string, open according to `mode`; if `expand` is true also
expand user and vars. | [
"Pass",
"file",
"to",
"func",
"and",
"ensure",
"the",
"file",
"is",
"closed",
"afterwards",
".",
"If",
"file",
"is",
"a",
"string",
"open",
"according",
"to",
"mode",
";",
"if",
"expand",
"is",
"true",
"also",
"expand",
"user",
"and",
"vars",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L335-L342 | train |
ewiger/mlab | src/mlab/awmstools.py | slurpLines | def slurpLines(file, expand=False):
r"""Read in a complete file (specified by a file handler or a filename
string/unicode string) as list of lines"""
file = _normalizeToFile(file, "r", expand)
try: return file.readlines()
finally: file.close() | python | def slurpLines(file, expand=False):
r"""Read in a complete file (specified by a file handler or a filename
string/unicode string) as list of lines"""
file = _normalizeToFile(file, "r", expand)
try: return file.readlines()
finally: file.close() | [
"def",
"slurpLines",
"(",
"file",
",",
"expand",
"=",
"False",
")",
":",
"file",
"=",
"_normalizeToFile",
"(",
"file",
",",
"\"r\"",
",",
"expand",
")",
"try",
":",
"return",
"file",
".",
"readlines",
"(",
")",
"finally",
":",
"file",
".",
"close",
"(",
")"
] | r"""Read in a complete file (specified by a file handler or a filename
string/unicode string) as list of lines | [
"r",
"Read",
"in",
"a",
"complete",
"file",
"(",
"specified",
"by",
"a",
"file",
"handler",
"or",
"a",
"filename",
"string",
"/",
"unicode",
"string",
")",
"as",
"list",
"of",
"lines"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L345-L350 | train |
ewiger/mlab | src/mlab/awmstools.py | slurpChompedLines | def slurpChompedLines(file, expand=False):
r"""Return ``file`` a list of chomped lines. See `slurpLines`."""
f=_normalizeToFile(file, "r", expand)
try: return list(chompLines(f))
finally: f.close() | python | def slurpChompedLines(file, expand=False):
r"""Return ``file`` a list of chomped lines. See `slurpLines`."""
f=_normalizeToFile(file, "r", expand)
try: return list(chompLines(f))
finally: f.close() | [
"def",
"slurpChompedLines",
"(",
"file",
",",
"expand",
"=",
"False",
")",
":",
"f",
"=",
"_normalizeToFile",
"(",
"file",
",",
"\"r\"",
",",
"expand",
")",
"try",
":",
"return",
"list",
"(",
"chompLines",
"(",
"f",
")",
")",
"finally",
":",
"f",
".",
"close",
"(",
")"
] | r"""Return ``file`` a list of chomped lines. See `slurpLines`. | [
"r",
"Return",
"file",
"a",
"list",
"of",
"chomped",
"lines",
".",
"See",
"slurpLines",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L352-L356 | train |
ewiger/mlab | src/mlab/awmstools.py | strToTempfile | def strToTempfile(s, suffix=None, prefix=None, dir=None, binary=False):
"""Create a new tempfile, write ``s`` to it and return the filename.
`suffix`, `prefix` and `dir` are like in `tempfile.mkstemp`.
"""
fd, filename = tempfile.mkstemp(**dict((k,v) for (k,v) in
[('suffix',suffix),('prefix',prefix),('dir', dir)]
if v is not None))
spitOut(s, fd, binary)
return filename | python | def strToTempfile(s, suffix=None, prefix=None, dir=None, binary=False):
"""Create a new tempfile, write ``s`` to it and return the filename.
`suffix`, `prefix` and `dir` are like in `tempfile.mkstemp`.
"""
fd, filename = tempfile.mkstemp(**dict((k,v) for (k,v) in
[('suffix',suffix),('prefix',prefix),('dir', dir)]
if v is not None))
spitOut(s, fd, binary)
return filename | [
"def",
"strToTempfile",
"(",
"s",
",",
"suffix",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"binary",
"=",
"False",
")",
":",
"fd",
",",
"filename",
"=",
"tempfile",
".",
"mkstemp",
"(",
"*",
"*",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"[",
"(",
"'suffix'",
",",
"suffix",
")",
",",
"(",
"'prefix'",
",",
"prefix",
")",
",",
"(",
"'dir'",
",",
"dir",
")",
"]",
"if",
"v",
"is",
"not",
"None",
")",
")",
"spitOut",
"(",
"s",
",",
"fd",
",",
"binary",
")",
"return",
"filename"
] | Create a new tempfile, write ``s`` to it and return the filename.
`suffix`, `prefix` and `dir` are like in `tempfile.mkstemp`. | [
"Create",
"a",
"new",
"tempfile",
"write",
"s",
"to",
"it",
"and",
"return",
"the",
"filename",
".",
"suffix",
"prefix",
"and",
"dir",
"are",
"like",
"in",
"tempfile",
".",
"mkstemp",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L358-L366 | train |
ewiger/mlab | src/mlab/awmstools.py | spitOut | def spitOut(s, file, binary=False, expand=False):
r"""Write string `s` into `file` (which can be a string (`str` or
`unicode`) or a `file` instance)."""
mode = "w" + ["b",""][not binary]
file = _normalizeToFile(file, mode=mode, expand=expand)
try: file.write(s)
finally: file.close() | python | def spitOut(s, file, binary=False, expand=False):
r"""Write string `s` into `file` (which can be a string (`str` or
`unicode`) or a `file` instance)."""
mode = "w" + ["b",""][not binary]
file = _normalizeToFile(file, mode=mode, expand=expand)
try: file.write(s)
finally: file.close() | [
"def",
"spitOut",
"(",
"s",
",",
"file",
",",
"binary",
"=",
"False",
",",
"expand",
"=",
"False",
")",
":",
"mode",
"=",
"\"w\"",
"+",
"[",
"\"b\"",
",",
"\"\"",
"]",
"[",
"not",
"binary",
"]",
"file",
"=",
"_normalizeToFile",
"(",
"file",
",",
"mode",
"=",
"mode",
",",
"expand",
"=",
"expand",
")",
"try",
":",
"file",
".",
"write",
"(",
"s",
")",
"finally",
":",
"file",
".",
"close",
"(",
")"
] | r"""Write string `s` into `file` (which can be a string (`str` or
`unicode`) or a `file` instance). | [
"r",
"Write",
"string",
"s",
"into",
"file",
"(",
"which",
"can",
"be",
"a",
"string",
"(",
"str",
"or",
"unicode",
")",
"or",
"a",
"file",
"instance",
")",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L369-L375 | train |
ewiger/mlab | src/mlab/awmstools.py | spitOutLines | def spitOutLines(lines, file, expand=False):
r"""Write all the `lines` to `file` (which can be a string/unicode or a
file handler)."""
file = _normalizeToFile(file, mode="w", expand=expand)
try: file.writelines(lines)
finally: file.close() | python | def spitOutLines(lines, file, expand=False):
r"""Write all the `lines` to `file` (which can be a string/unicode or a
file handler)."""
file = _normalizeToFile(file, mode="w", expand=expand)
try: file.writelines(lines)
finally: file.close() | [
"def",
"spitOutLines",
"(",
"lines",
",",
"file",
",",
"expand",
"=",
"False",
")",
":",
"file",
"=",
"_normalizeToFile",
"(",
"file",
",",
"mode",
"=",
"\"w\"",
",",
"expand",
"=",
"expand",
")",
"try",
":",
"file",
".",
"writelines",
"(",
"lines",
")",
"finally",
":",
"file",
".",
"close",
"(",
")"
] | r"""Write all the `lines` to `file` (which can be a string/unicode or a
file handler). | [
"r",
"Write",
"all",
"the",
"lines",
"to",
"file",
"(",
"which",
"can",
"be",
"a",
"string",
"/",
"unicode",
"or",
"a",
"file",
"handler",
")",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L377-L382 | train |
ewiger/mlab | src/mlab/awmstools.py | readProcess | def readProcess(cmd, *args):
r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the
exit code (unlike popen2, exit is 0 if no problems occured (for some
bizarre reason popen2 returns None... <sigh>).
FIXME: only works for UNIX; handling of signalled processes.
"""
import popen2
BUFSIZE=1024
import select
popen = popen2.Popen3((cmd,) + args, capturestderr=True)
which = {id(popen.fromchild): [],
id(popen.childerr): []}
select = Result(select.select)
read = Result(os.read)
try:
popen.tochild.close() # XXX make sure we're not waiting forever
while select([popen.fromchild, popen.childerr], [], []):
readSomething = False
for f in select.result[0]:
while read(f.fileno(), BUFSIZE):
which[id(f)].append(read.result)
readSomething = True
if not readSomething:
break
out, err = ["".join(which[id(f)])
for f in [popen.fromchild, popen.childerr]]
returncode = popen.wait()
if os.WIFEXITED(returncode):
exit = os.WEXITSTATUS(returncode)
else:
exit = returncode or 1 # HACK: ensure non-zero
finally:
try:
popen.fromchild.close()
finally:
popen.childerr.close()
return out or "", err or "", exit | python | def readProcess(cmd, *args):
r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the
exit code (unlike popen2, exit is 0 if no problems occured (for some
bizarre reason popen2 returns None... <sigh>).
FIXME: only works for UNIX; handling of signalled processes.
"""
import popen2
BUFSIZE=1024
import select
popen = popen2.Popen3((cmd,) + args, capturestderr=True)
which = {id(popen.fromchild): [],
id(popen.childerr): []}
select = Result(select.select)
read = Result(os.read)
try:
popen.tochild.close() # XXX make sure we're not waiting forever
while select([popen.fromchild, popen.childerr], [], []):
readSomething = False
for f in select.result[0]:
while read(f.fileno(), BUFSIZE):
which[id(f)].append(read.result)
readSomething = True
if not readSomething:
break
out, err = ["".join(which[id(f)])
for f in [popen.fromchild, popen.childerr]]
returncode = popen.wait()
if os.WIFEXITED(returncode):
exit = os.WEXITSTATUS(returncode)
else:
exit = returncode or 1 # HACK: ensure non-zero
finally:
try:
popen.fromchild.close()
finally:
popen.childerr.close()
return out or "", err or "", exit | [
"def",
"readProcess",
"(",
"cmd",
",",
"*",
"args",
")",
":",
"import",
"popen2",
"BUFSIZE",
"=",
"1024",
"import",
"select",
"popen",
"=",
"popen2",
".",
"Popen3",
"(",
"(",
"cmd",
",",
")",
"+",
"args",
",",
"capturestderr",
"=",
"True",
")",
"which",
"=",
"{",
"id",
"(",
"popen",
".",
"fromchild",
")",
":",
"[",
"]",
",",
"id",
"(",
"popen",
".",
"childerr",
")",
":",
"[",
"]",
"}",
"select",
"=",
"Result",
"(",
"select",
".",
"select",
")",
"read",
"=",
"Result",
"(",
"os",
".",
"read",
")",
"try",
":",
"popen",
".",
"tochild",
".",
"close",
"(",
")",
"# XXX make sure we're not waiting forever",
"while",
"select",
"(",
"[",
"popen",
".",
"fromchild",
",",
"popen",
".",
"childerr",
"]",
",",
"[",
"]",
",",
"[",
"]",
")",
":",
"readSomething",
"=",
"False",
"for",
"f",
"in",
"select",
".",
"result",
"[",
"0",
"]",
":",
"while",
"read",
"(",
"f",
".",
"fileno",
"(",
")",
",",
"BUFSIZE",
")",
":",
"which",
"[",
"id",
"(",
"f",
")",
"]",
".",
"append",
"(",
"read",
".",
"result",
")",
"readSomething",
"=",
"True",
"if",
"not",
"readSomething",
":",
"break",
"out",
",",
"err",
"=",
"[",
"\"\"",
".",
"join",
"(",
"which",
"[",
"id",
"(",
"f",
")",
"]",
")",
"for",
"f",
"in",
"[",
"popen",
".",
"fromchild",
",",
"popen",
".",
"childerr",
"]",
"]",
"returncode",
"=",
"popen",
".",
"wait",
"(",
")",
"if",
"os",
".",
"WIFEXITED",
"(",
"returncode",
")",
":",
"exit",
"=",
"os",
".",
"WEXITSTATUS",
"(",
"returncode",
")",
"else",
":",
"exit",
"=",
"returncode",
"or",
"1",
"# HACK: ensure non-zero",
"finally",
":",
"try",
":",
"popen",
".",
"fromchild",
".",
"close",
"(",
")",
"finally",
":",
"popen",
".",
"childerr",
".",
"close",
"(",
")",
"return",
"out",
"or",
"\"\"",
",",
"err",
"or",
"\"\"",
",",
"exit"
] | r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the
exit code (unlike popen2, exit is 0 if no problems occured (for some
bizarre reason popen2 returns None... <sigh>).
FIXME: only works for UNIX; handling of signalled processes. | [
"r",
"Similar",
"to",
"os",
".",
"popen3",
"but",
"returns",
"2",
"strings",
"(",
"stdin",
"stdout",
")",
"and",
"the",
"exit",
"code",
"(",
"unlike",
"popen2",
"exit",
"is",
"0",
"if",
"no",
"problems",
"occured",
"(",
"for",
"some",
"bizarre",
"reason",
"popen2",
"returns",
"None",
"...",
"<sigh",
">",
")",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L386-L424 | train |
ewiger/mlab | src/mlab/awmstools.py | runProcess | def runProcess(cmd, *args):
"""Run `cmd` (which is searched for in the executable path) with `args` and
return the exit status.
In general (unless you know what you're doing) use::
runProcess('program', filename)
rather than::
os.system('program %s' % filename)
because the latter will not work as expected if `filename` contains
spaces or shell-metacharacters.
If you need more fine-grained control look at ``os.spawn*``.
"""
from os import spawnvp, P_WAIT
return spawnvp(P_WAIT, cmd, (cmd,) + args) | python | def runProcess(cmd, *args):
"""Run `cmd` (which is searched for in the executable path) with `args` and
return the exit status.
In general (unless you know what you're doing) use::
runProcess('program', filename)
rather than::
os.system('program %s' % filename)
because the latter will not work as expected if `filename` contains
spaces or shell-metacharacters.
If you need more fine-grained control look at ``os.spawn*``.
"""
from os import spawnvp, P_WAIT
return spawnvp(P_WAIT, cmd, (cmd,) + args) | [
"def",
"runProcess",
"(",
"cmd",
",",
"*",
"args",
")",
":",
"from",
"os",
"import",
"spawnvp",
",",
"P_WAIT",
"return",
"spawnvp",
"(",
"P_WAIT",
",",
"cmd",
",",
"(",
"cmd",
",",
")",
"+",
"args",
")"
] | Run `cmd` (which is searched for in the executable path) with `args` and
return the exit status.
In general (unless you know what you're doing) use::
runProcess('program', filename)
rather than::
os.system('program %s' % filename)
because the latter will not work as expected if `filename` contains
spaces or shell-metacharacters.
If you need more fine-grained control look at ``os.spawn*``. | [
"Run",
"cmd",
"(",
"which",
"is",
"searched",
"for",
"in",
"the",
"executable",
"path",
")",
"with",
"args",
"and",
"return",
"the",
"exit",
"status",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L432-L450 | train |
ewiger/mlab | src/mlab/awmstools.py | splitext | def splitext(p):
r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles
(e.g. .emacs) as extensions. Also uses os.sep instead of '/'."""
root, ext = os.path.splitext(p)
# check for dotfiles
if (not root or root[-1] == os.sep): # XXX: use '/' or os.sep here???
return (root + ext, "")
else:
return root, ext | python | def splitext(p):
r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles
(e.g. .emacs) as extensions. Also uses os.sep instead of '/'."""
root, ext = os.path.splitext(p)
# check for dotfiles
if (not root or root[-1] == os.sep): # XXX: use '/' or os.sep here???
return (root + ext, "")
else:
return root, ext | [
"def",
"splitext",
"(",
"p",
")",
":",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"p",
")",
"# check for dotfiles",
"if",
"(",
"not",
"root",
"or",
"root",
"[",
"-",
"1",
"]",
"==",
"os",
".",
"sep",
")",
":",
"# XXX: use '/' or os.sep here???",
"return",
"(",
"root",
"+",
"ext",
",",
"\"\"",
")",
"else",
":",
"return",
"root",
",",
"ext"
] | r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles
(e.g. .emacs) as extensions. Also uses os.sep instead of '/'. | [
"r",
"Like",
"the",
"normal",
"splitext",
"(",
"in",
"posixpath",
")",
"but",
"doesn",
"t",
"treat",
"dotfiles",
"(",
"e",
".",
"g",
".",
".",
"emacs",
")",
"as",
"extensions",
".",
"Also",
"uses",
"os",
".",
"sep",
"instead",
"of",
"/",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L463-L472 | train |
ewiger/mlab | src/mlab/awmstools.py | bipart | def bipart(func, seq):
r"""Like a partitioning version of `filter`. Returns
``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``.
Example:
>>> bipart(bool, [1,None,2,3,0,[],[0]])
[[None, 0, []], [1, 2, 3, [0]]]
"""
if func is None: func = bool
res = [[],[]]
for i in seq: res[not not func(i)].append(i)
return res | python | def bipart(func, seq):
r"""Like a partitioning version of `filter`. Returns
``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``.
Example:
>>> bipart(bool, [1,None,2,3,0,[],[0]])
[[None, 0, []], [1, 2, 3, [0]]]
"""
if func is None: func = bool
res = [[],[]]
for i in seq: res[not not func(i)].append(i)
return res | [
"def",
"bipart",
"(",
"func",
",",
"seq",
")",
":",
"if",
"func",
"is",
"None",
":",
"func",
"=",
"bool",
"res",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"for",
"i",
"in",
"seq",
":",
"res",
"[",
"not",
"not",
"func",
"(",
"i",
")",
"]",
".",
"append",
"(",
"i",
")",
"return",
"res"
] | r"""Like a partitioning version of `filter`. Returns
``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``.
Example:
>>> bipart(bool, [1,None,2,3,0,[],[0]])
[[None, 0, []], [1, 2, 3, [0]]] | [
"r",
"Like",
"a",
"partitioning",
"version",
"of",
"filter",
".",
"Returns",
"[",
"itemsForWhichFuncReturnedFalse",
"itemsForWhichFuncReturnedTrue",
"]",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L478-L491 | train |
ewiger/mlab | src/mlab/awmstools.py | binarySearchPos | def binarySearchPos(seq, item, cmpfunc=cmp):
r"""Return the position of `item` in ordered sequence `seq`, using comparison
function `cmpfunc` (defaults to ``cmp``) and return the first found
position of `item`, or -1 if `item` is not in `seq`. The returned position
is NOT guaranteed to be the first occurence of `item` in `seq`."""
if not seq: return -1
left, right = 0, len(seq) - 1
if cmpfunc(seq[left], item) == 1 and \
cmpfunc(seq[right], item) == -1:
return -1
while left <= right:
halfPoint = (left + right) // 2
comp = cmpfunc(seq[halfPoint], item)
if comp > 0: right = halfPoint - 1
elif comp < 0: left = halfPoint + 1
else: return halfPoint
return -1 | python | def binarySearchPos(seq, item, cmpfunc=cmp):
r"""Return the position of `item` in ordered sequence `seq`, using comparison
function `cmpfunc` (defaults to ``cmp``) and return the first found
position of `item`, or -1 if `item` is not in `seq`. The returned position
is NOT guaranteed to be the first occurence of `item` in `seq`."""
if not seq: return -1
left, right = 0, len(seq) - 1
if cmpfunc(seq[left], item) == 1 and \
cmpfunc(seq[right], item) == -1:
return -1
while left <= right:
halfPoint = (left + right) // 2
comp = cmpfunc(seq[halfPoint], item)
if comp > 0: right = halfPoint - 1
elif comp < 0: left = halfPoint + 1
else: return halfPoint
return -1 | [
"def",
"binarySearchPos",
"(",
"seq",
",",
"item",
",",
"cmpfunc",
"=",
"cmp",
")",
":",
"if",
"not",
"seq",
":",
"return",
"-",
"1",
"left",
",",
"right",
"=",
"0",
",",
"len",
"(",
"seq",
")",
"-",
"1",
"if",
"cmpfunc",
"(",
"seq",
"[",
"left",
"]",
",",
"item",
")",
"==",
"1",
"and",
"cmpfunc",
"(",
"seq",
"[",
"right",
"]",
",",
"item",
")",
"==",
"-",
"1",
":",
"return",
"-",
"1",
"while",
"left",
"<=",
"right",
":",
"halfPoint",
"=",
"(",
"left",
"+",
"right",
")",
"//",
"2",
"comp",
"=",
"cmpfunc",
"(",
"seq",
"[",
"halfPoint",
"]",
",",
"item",
")",
"if",
"comp",
">",
"0",
":",
"right",
"=",
"halfPoint",
"-",
"1",
"elif",
"comp",
"<",
"0",
":",
"left",
"=",
"halfPoint",
"+",
"1",
"else",
":",
"return",
"halfPoint",
"return",
"-",
"1"
] | r"""Return the position of `item` in ordered sequence `seq`, using comparison
function `cmpfunc` (defaults to ``cmp``) and return the first found
position of `item`, or -1 if `item` is not in `seq`. The returned position
is NOT guaranteed to be the first occurence of `item` in `seq`. | [
"r",
"Return",
"the",
"position",
"of",
"item",
"in",
"ordered",
"sequence",
"seq",
"using",
"comparison",
"function",
"cmpfunc",
"(",
"defaults",
"to",
"cmp",
")",
"and",
"return",
"the",
"first",
"found",
"position",
"of",
"item",
"or",
"-",
"1",
"if",
"item",
"is",
"not",
"in",
"seq",
".",
"The",
"returned",
"position",
"is",
"NOT",
"guaranteed",
"to",
"be",
"the",
"first",
"occurence",
"of",
"item",
"in",
"seq",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L499-L516 | train |
ewiger/mlab | src/mlab/awmstools.py | binarySearchItem | def binarySearchItem(seq, item, cmpfunc=cmp):
r""" Search an ordered sequence `seq` for `item`, using comparison function
`cmpfunc` (defaults to ``cmp``) and return the first found instance of
`item`, or `None` if item is not in `seq`. The returned item is NOT
guaranteed to be the first occurrence of item in `seq`."""
pos = binarySearchPos(seq, item, cmpfunc)
if pos == -1: raise KeyError("Item not in seq")
else: return seq[pos] | python | def binarySearchItem(seq, item, cmpfunc=cmp):
r""" Search an ordered sequence `seq` for `item`, using comparison function
`cmpfunc` (defaults to ``cmp``) and return the first found instance of
`item`, or `None` if item is not in `seq`. The returned item is NOT
guaranteed to be the first occurrence of item in `seq`."""
pos = binarySearchPos(seq, item, cmpfunc)
if pos == -1: raise KeyError("Item not in seq")
else: return seq[pos] | [
"def",
"binarySearchItem",
"(",
"seq",
",",
"item",
",",
"cmpfunc",
"=",
"cmp",
")",
":",
"pos",
"=",
"binarySearchPos",
"(",
"seq",
",",
"item",
",",
"cmpfunc",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"raise",
"KeyError",
"(",
"\"Item not in seq\"",
")",
"else",
":",
"return",
"seq",
"[",
"pos",
"]"
] | r""" Search an ordered sequence `seq` for `item`, using comparison function
`cmpfunc` (defaults to ``cmp``) and return the first found instance of
`item`, or `None` if item is not in `seq`. The returned item is NOT
guaranteed to be the first occurrence of item in `seq`. | [
"r",
"Search",
"an",
"ordered",
"sequence",
"seq",
"for",
"item",
"using",
"comparison",
"function",
"cmpfunc",
"(",
"defaults",
"to",
"cmp",
")",
"and",
"return",
"the",
"first",
"found",
"instance",
"of",
"item",
"or",
"None",
"if",
"item",
"is",
"not",
"in",
"seq",
".",
"The",
"returned",
"item",
"is",
"NOT",
"guaranteed",
"to",
"be",
"the",
"first",
"occurrence",
"of",
"item",
"in",
"seq",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L536-L543 | train |
ewiger/mlab | src/mlab/awmstools.py | rotate | def rotate(l, steps=1):
r"""Rotates a list `l` `steps` to the left. Accepts
`steps` > `len(l)` or < 0.
>>> rotate([1,2,3])
[2, 3, 1]
>>> rotate([1,2,3,4],-2)
[3, 4, 1, 2]
>>> rotate([1,2,3,4],-5)
[4, 1, 2, 3]
>>> rotate([1,2,3,4],1)
[2, 3, 4, 1]
>>> l = [1,2,3]; rotate(l) is not l
True
"""
if len(l):
steps %= len(l)
if steps:
res = l[steps:]
res.extend(l[:steps])
return res | python | def rotate(l, steps=1):
r"""Rotates a list `l` `steps` to the left. Accepts
`steps` > `len(l)` or < 0.
>>> rotate([1,2,3])
[2, 3, 1]
>>> rotate([1,2,3,4],-2)
[3, 4, 1, 2]
>>> rotate([1,2,3,4],-5)
[4, 1, 2, 3]
>>> rotate([1,2,3,4],1)
[2, 3, 4, 1]
>>> l = [1,2,3]; rotate(l) is not l
True
"""
if len(l):
steps %= len(l)
if steps:
res = l[steps:]
res.extend(l[:steps])
return res | [
"def",
"rotate",
"(",
"l",
",",
"steps",
"=",
"1",
")",
":",
"if",
"len",
"(",
"l",
")",
":",
"steps",
"%=",
"len",
"(",
"l",
")",
"if",
"steps",
":",
"res",
"=",
"l",
"[",
"steps",
":",
"]",
"res",
".",
"extend",
"(",
"l",
"[",
":",
"steps",
"]",
")",
"return",
"res"
] | r"""Rotates a list `l` `steps` to the left. Accepts
`steps` > `len(l)` or < 0.
>>> rotate([1,2,3])
[2, 3, 1]
>>> rotate([1,2,3,4],-2)
[3, 4, 1, 2]
>>> rotate([1,2,3,4],-5)
[4, 1, 2, 3]
>>> rotate([1,2,3,4],1)
[2, 3, 4, 1]
>>> l = [1,2,3]; rotate(l) is not l
True | [
"r",
"Rotates",
"a",
"list",
"l",
"steps",
"to",
"the",
"left",
".",
"Accepts",
"steps",
">",
"len",
"(",
"l",
")",
"or",
"<",
"0",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L546-L566 | train |
ewiger/mlab | src/mlab/awmstools.py | iprotate | def iprotate(l, steps=1):
r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2, 3, 1]
>>> iprotate(iprotate(l, 2), -3)
[1, 2, 3]
"""
if len(l):
steps %= len(l)
if steps:
firstPart = l[:steps]
del l[:steps]
l.extend(firstPart)
return l | python | def iprotate(l, steps=1):
r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2, 3, 1]
>>> iprotate(iprotate(l, 2), -3)
[1, 2, 3]
"""
if len(l):
steps %= len(l)
if steps:
firstPart = l[:steps]
del l[:steps]
l.extend(firstPart)
return l | [
"def",
"iprotate",
"(",
"l",
",",
"steps",
"=",
"1",
")",
":",
"if",
"len",
"(",
"l",
")",
":",
"steps",
"%=",
"len",
"(",
"l",
")",
"if",
"steps",
":",
"firstPart",
"=",
"l",
"[",
":",
"steps",
"]",
"del",
"l",
"[",
":",
"steps",
"]",
"l",
".",
"extend",
"(",
"firstPart",
")",
"return",
"l"
] | r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2, 3, 1]
>>> iprotate(iprotate(l, 2), -3)
[1, 2, 3] | [
"r",
"Like",
"rotate",
"but",
"modifies",
"l",
"in",
"-",
"place",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L568-L586 | train |
ewiger/mlab | src/mlab/awmstools.py | unique | def unique(iterable):
r"""Returns all unique items in `iterable` in the *same* order (only works
if items in `seq` are hashable).
"""
d = {}
return (d.setdefault(x,x) for x in iterable if x not in d) | python | def unique(iterable):
r"""Returns all unique items in `iterable` in the *same* order (only works
if items in `seq` are hashable).
"""
d = {}
return (d.setdefault(x,x) for x in iterable if x not in d) | [
"def",
"unique",
"(",
"iterable",
")",
":",
"d",
"=",
"{",
"}",
"return",
"(",
"d",
".",
"setdefault",
"(",
"x",
",",
"x",
")",
"for",
"x",
"in",
"iterable",
"if",
"x",
"not",
"in",
"d",
")"
] | r"""Returns all unique items in `iterable` in the *same* order (only works
if items in `seq` are hashable). | [
"r",
"Returns",
"all",
"unique",
"items",
"in",
"iterable",
"in",
"the",
"*",
"same",
"*",
"order",
"(",
"only",
"works",
"if",
"items",
"in",
"seq",
"are",
"hashable",
")",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L594-L599 | train |
ewiger/mlab | src/mlab/awmstools.py | notUnique | def notUnique(iterable, reportMax=INF):
"""Returns the elements in `iterable` that aren't unique; stops after it found
`reportMax` non-unique elements.
Examples:
>>> list(notUnique([1,1,2,2,3,3]))
[1, 2, 3]
>>> list(notUnique([1,1,2,2,3,3], 1))
[1]
"""
hash = {}
n=0
if reportMax < 1:
raise ValueError("`reportMax` must be >= 1 and is %r" % reportMax)
for item in iterable:
count = hash[item] = hash.get(item, 0) + 1
if count > 1:
yield item
n += 1
if n >= reportMax:
return | python | def notUnique(iterable, reportMax=INF):
"""Returns the elements in `iterable` that aren't unique; stops after it found
`reportMax` non-unique elements.
Examples:
>>> list(notUnique([1,1,2,2,3,3]))
[1, 2, 3]
>>> list(notUnique([1,1,2,2,3,3], 1))
[1]
"""
hash = {}
n=0
if reportMax < 1:
raise ValueError("`reportMax` must be >= 1 and is %r" % reportMax)
for item in iterable:
count = hash[item] = hash.get(item, 0) + 1
if count > 1:
yield item
n += 1
if n >= reportMax:
return | [
"def",
"notUnique",
"(",
"iterable",
",",
"reportMax",
"=",
"INF",
")",
":",
"hash",
"=",
"{",
"}",
"n",
"=",
"0",
"if",
"reportMax",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"`reportMax` must be >= 1 and is %r\"",
"%",
"reportMax",
")",
"for",
"item",
"in",
"iterable",
":",
"count",
"=",
"hash",
"[",
"item",
"]",
"=",
"hash",
".",
"get",
"(",
"item",
",",
"0",
")",
"+",
"1",
"if",
"count",
">",
"1",
":",
"yield",
"item",
"n",
"+=",
"1",
"if",
"n",
">=",
"reportMax",
":",
"return"
] | Returns the elements in `iterable` that aren't unique; stops after it found
`reportMax` non-unique elements.
Examples:
>>> list(notUnique([1,1,2,2,3,3]))
[1, 2, 3]
>>> list(notUnique([1,1,2,2,3,3], 1))
[1] | [
"Returns",
"the",
"elements",
"in",
"iterable",
"that",
"aren",
"t",
"unique",
";",
"stops",
"after",
"it",
"found",
"reportMax",
"non",
"-",
"unique",
"elements",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L614-L635 | train |
ewiger/mlab | src/mlab/awmstools.py | unweave | def unweave(iterable, n=2):
r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to
list `n`.
Example:
>>> unweave((1,2,3,4,5), 3)
[[1, 4], [2, 5], [3]]
"""
res = [[] for i in range(n)]
i = 0
for x in iterable:
res[i % n].append(x)
i += 1
return res | python | def unweave(iterable, n=2):
r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to
list `n`.
Example:
>>> unweave((1,2,3,4,5), 3)
[[1, 4], [2, 5], [3]]
"""
res = [[] for i in range(n)]
i = 0
for x in iterable:
res[i % n].append(x)
i += 1
return res | [
"def",
"unweave",
"(",
"iterable",
",",
"n",
"=",
"2",
")",
":",
"res",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"i",
"=",
"0",
"for",
"x",
"in",
"iterable",
":",
"res",
"[",
"i",
"%",
"n",
"]",
".",
"append",
"(",
"x",
")",
"i",
"+=",
"1",
"return",
"res"
] | r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to
list `n`.
Example:
>>> unweave((1,2,3,4,5), 3)
[[1, 4], [2, 5], [3]] | [
"r",
"Divide",
"iterable",
"in",
"n",
"lists",
"so",
"that",
"every",
"n",
"th",
"element",
"belongs",
"to",
"list",
"n",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L655-L669 | train |
ewiger/mlab | src/mlab/awmstools.py | weave | def weave(*iterables):
r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]).
>>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C']))
[1, 4, 6, 2, 5, 7, 3, 6, 8]
Any iterable will work. The first exhausted iterable determines when to
stop. FIXME rethink stopping semantics.
>>> list(weave(iter(('is','psu')), ('there','no', 'censorship')))
['is', 'there', 'psu', 'no']
>>> list(weave(('there','no', 'censorship'), iter(('is','psu'))))
['there', 'is', 'no', 'psu', 'censorship']
"""
iterables = map(iter, iterables)
while True:
for it in iterables: yield it.next() | python | def weave(*iterables):
r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]).
>>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C']))
[1, 4, 6, 2, 5, 7, 3, 6, 8]
Any iterable will work. The first exhausted iterable determines when to
stop. FIXME rethink stopping semantics.
>>> list(weave(iter(('is','psu')), ('there','no', 'censorship')))
['is', 'there', 'psu', 'no']
>>> list(weave(('there','no', 'censorship'), iter(('is','psu'))))
['there', 'is', 'no', 'psu', 'censorship']
"""
iterables = map(iter, iterables)
while True:
for it in iterables: yield it.next() | [
"def",
"weave",
"(",
"*",
"iterables",
")",
":",
"iterables",
"=",
"map",
"(",
"iter",
",",
"iterables",
")",
"while",
"True",
":",
"for",
"it",
"in",
"iterables",
":",
"yield",
"it",
".",
"next",
"(",
")"
] | r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]).
>>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C']))
[1, 4, 6, 2, 5, 7, 3, 6, 8]
Any iterable will work. The first exhausted iterable determines when to
stop. FIXME rethink stopping semantics.
>>> list(weave(iter(('is','psu')), ('there','no', 'censorship')))
['is', 'there', 'psu', 'no']
>>> list(weave(('there','no', 'censorship'), iter(('is','psu'))))
['there', 'is', 'no', 'psu', 'censorship'] | [
"r",
"weave",
"(",
"seq1",
"[",
"seq2",
"]",
"[",
"...",
"]",
")",
"-",
">",
"iter",
"(",
"[",
"seq1",
"[",
"0",
"]",
"seq2",
"[",
"0",
"]",
"...",
"]",
")",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L674-L690 | train |
ewiger/mlab | src/mlab/awmstools.py | atIndices | def atIndices(indexable, indices, default=__unique):
r"""Return a list of items in `indexable` at positions `indices`.
Examples:
>>> atIndices([1,2,3], [1,1,0])
[2, 2, 1]
>>> atIndices([1,2,3], [1,1,0,4], 'default')
[2, 2, 1, 'default']
>>> atIndices({'a':3, 'b':0}, ['a'])
[3]
"""
if default is __unique:
return [indexable[i] for i in indices]
else:
res = []
for i in indices:
try:
res.append(indexable[i])
except (IndexError, KeyError):
res.append(default)
return res | python | def atIndices(indexable, indices, default=__unique):
r"""Return a list of items in `indexable` at positions `indices`.
Examples:
>>> atIndices([1,2,3], [1,1,0])
[2, 2, 1]
>>> atIndices([1,2,3], [1,1,0,4], 'default')
[2, 2, 1, 'default']
>>> atIndices({'a':3, 'b':0}, ['a'])
[3]
"""
if default is __unique:
return [indexable[i] for i in indices]
else:
res = []
for i in indices:
try:
res.append(indexable[i])
except (IndexError, KeyError):
res.append(default)
return res | [
"def",
"atIndices",
"(",
"indexable",
",",
"indices",
",",
"default",
"=",
"__unique",
")",
":",
"if",
"default",
"is",
"__unique",
":",
"return",
"[",
"indexable",
"[",
"i",
"]",
"for",
"i",
"in",
"indices",
"]",
"else",
":",
"res",
"=",
"[",
"]",
"for",
"i",
"in",
"indices",
":",
"try",
":",
"res",
".",
"append",
"(",
"indexable",
"[",
"i",
"]",
")",
"except",
"(",
"IndexError",
",",
"KeyError",
")",
":",
"res",
".",
"append",
"(",
"default",
")",
"return",
"res"
] | r"""Return a list of items in `indexable` at positions `indices`.
Examples:
>>> atIndices([1,2,3], [1,1,0])
[2, 2, 1]
>>> atIndices([1,2,3], [1,1,0,4], 'default')
[2, 2, 1, 'default']
>>> atIndices({'a':3, 'b':0}, ['a'])
[3] | [
"r",
"Return",
"a",
"list",
"of",
"items",
"in",
"indexable",
"at",
"positions",
"indices",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L692-L713 | train |
ewiger/mlab | src/mlab/awmstools.py | window | def window(iterable, n=2, s=1):
r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time
over `iterable`.
Examples:
>>> list(window(range(6),2))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> list(window(range(6),3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
>>> list(window(range(6),3, 2))
[(0, 1, 2), (2, 3, 4)]
>>> list(window(range(5),3,2)) == list(window(range(6),3,2))
True
"""
assert n >= s
last = []
for elt in iterable:
last.append(elt)
if len(last) == n: yield tuple(last); last=last[s:] | python | def window(iterable, n=2, s=1):
r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time
over `iterable`.
Examples:
>>> list(window(range(6),2))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> list(window(range(6),3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
>>> list(window(range(6),3, 2))
[(0, 1, 2), (2, 3, 4)]
>>> list(window(range(5),3,2)) == list(window(range(6),3,2))
True
"""
assert n >= s
last = []
for elt in iterable:
last.append(elt)
if len(last) == n: yield tuple(last); last=last[s:] | [
"def",
"window",
"(",
"iterable",
",",
"n",
"=",
"2",
",",
"s",
"=",
"1",
")",
":",
"assert",
"n",
">=",
"s",
"last",
"=",
"[",
"]",
"for",
"elt",
"in",
"iterable",
":",
"last",
".",
"append",
"(",
"elt",
")",
"if",
"len",
"(",
"last",
")",
"==",
"n",
":",
"yield",
"tuple",
"(",
"last",
")",
"last",
"=",
"last",
"[",
"s",
":",
"]"
] | r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time
over `iterable`.
Examples:
>>> list(window(range(6),2))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> list(window(range(6),3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
>>> list(window(range(6),3, 2))
[(0, 1, 2), (2, 3, 4)]
>>> list(window(range(5),3,2)) == list(window(range(6),3,2))
True | [
"r",
"Move",
"an",
"n",
"-",
"item",
"(",
"default",
"2",
")",
"windows",
"s",
"steps",
"(",
"default",
"1",
")",
"at",
"a",
"time",
"over",
"iterable",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L733-L752 | train |
ewiger/mlab | src/mlab/awmstools.py | group | def group(iterable, n=2, pad=__unique):
r"""Iterate `n`-wise (default pairwise) over `iter`.
Examples:
>>> for (first, last) in group("Akira Kurosawa John Ford".split()):
... print "given name: %s surname: %s" % (first, last)
...
given name: Akira surname: Kurosawa
given name: John surname: Ford
>>>
>>> # both contain the same number of pairs
>>> list(group(range(9))) == list(group(range(8)))
True
>>> # with n=3
>>> list(group(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(group(range(10), 3, pad=0))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 0, 0)]
"""
assert n>0 # ensure it doesn't loop forever
if pad is not __unique: it = chain(iterable, (pad,)*(n-1))
else: it = iter(iterable)
perTuple = xrange(n)
while True:
yield tuple([it.next() for i in perTuple]) | python | def group(iterable, n=2, pad=__unique):
r"""Iterate `n`-wise (default pairwise) over `iter`.
Examples:
>>> for (first, last) in group("Akira Kurosawa John Ford".split()):
... print "given name: %s surname: %s" % (first, last)
...
given name: Akira surname: Kurosawa
given name: John surname: Ford
>>>
>>> # both contain the same number of pairs
>>> list(group(range(9))) == list(group(range(8)))
True
>>> # with n=3
>>> list(group(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(group(range(10), 3, pad=0))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 0, 0)]
"""
assert n>0 # ensure it doesn't loop forever
if pad is not __unique: it = chain(iterable, (pad,)*(n-1))
else: it = iter(iterable)
perTuple = xrange(n)
while True:
yield tuple([it.next() for i in perTuple]) | [
"def",
"group",
"(",
"iterable",
",",
"n",
"=",
"2",
",",
"pad",
"=",
"__unique",
")",
":",
"assert",
"n",
">",
"0",
"# ensure it doesn't loop forever",
"if",
"pad",
"is",
"not",
"__unique",
":",
"it",
"=",
"chain",
"(",
"iterable",
",",
"(",
"pad",
",",
")",
"*",
"(",
"n",
"-",
"1",
")",
")",
"else",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"perTuple",
"=",
"xrange",
"(",
"n",
")",
"while",
"True",
":",
"yield",
"tuple",
"(",
"[",
"it",
".",
"next",
"(",
")",
"for",
"i",
"in",
"perTuple",
"]",
")"
] | r"""Iterate `n`-wise (default pairwise) over `iter`.
Examples:
>>> for (first, last) in group("Akira Kurosawa John Ford".split()):
... print "given name: %s surname: %s" % (first, last)
...
given name: Akira surname: Kurosawa
given name: John surname: Ford
>>>
>>> # both contain the same number of pairs
>>> list(group(range(9))) == list(group(range(8)))
True
>>> # with n=3
>>> list(group(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(group(range(10), 3, pad=0))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 0, 0)] | [
"r",
"Iterate",
"n",
"-",
"wise",
"(",
"default",
"pairwise",
")",
"over",
"iter",
".",
"Examples",
":"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L756-L780 | train |
ewiger/mlab | src/mlab/awmstools.py | iterate | def iterate(f, n=None, last=__unique):
"""
>>> list(iterate(lambda x:x//2)(128))
[128, 64, 32, 16, 8, 4, 2, 1, 0]
>>> list(iterate(lambda x:x//2, n=2)(128))
[128, 64]
"""
if n is not None:
def funciter(start):
for i in xrange(n): yield start; start = f(start)
else:
def funciter(start):
while True:
yield start
last = f(start)
if last == start: return
last, start = start, last
return funciter | python | def iterate(f, n=None, last=__unique):
"""
>>> list(iterate(lambda x:x//2)(128))
[128, 64, 32, 16, 8, 4, 2, 1, 0]
>>> list(iterate(lambda x:x//2, n=2)(128))
[128, 64]
"""
if n is not None:
def funciter(start):
for i in xrange(n): yield start; start = f(start)
else:
def funciter(start):
while True:
yield start
last = f(start)
if last == start: return
last, start = start, last
return funciter | [
"def",
"iterate",
"(",
"f",
",",
"n",
"=",
"None",
",",
"last",
"=",
"__unique",
")",
":",
"if",
"n",
"is",
"not",
"None",
":",
"def",
"funciter",
"(",
"start",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"n",
")",
":",
"yield",
"start",
"start",
"=",
"f",
"(",
"start",
")",
"else",
":",
"def",
"funciter",
"(",
"start",
")",
":",
"while",
"True",
":",
"yield",
"start",
"last",
"=",
"f",
"(",
"start",
")",
"if",
"last",
"==",
"start",
":",
"return",
"last",
",",
"start",
"=",
"start",
",",
"last",
"return",
"funciter"
] | >>> list(iterate(lambda x:x//2)(128))
[128, 64, 32, 16, 8, 4, 2, 1, 0]
>>> list(iterate(lambda x:x//2, n=2)(128))
[128, 64] | [
">>>",
"list",
"(",
"iterate",
"(",
"lambda",
"x",
":",
"x",
"//",
"2",
")",
"(",
"128",
"))",
"[",
"128",
"64",
"32",
"16",
"8",
"4",
"2",
"1",
"0",
"]",
">>>",
"list",
"(",
"iterate",
"(",
"lambda",
"x",
":",
"x",
"//",
"2",
"n",
"=",
"2",
")",
"(",
"128",
"))",
"[",
"128",
"64",
"]"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L782-L799 | train |
ewiger/mlab | src/mlab/awmstools.py | dropwhilenot | def dropwhilenot(func, iterable):
"""
>>> list(dropwhilenot(lambda x:x==3, range(10)))
[3, 4, 5, 6, 7, 8, 9]
"""
iterable = iter(iterable)
for x in iterable:
if func(x): break
else: return
yield x
for x in iterable:
yield x | python | def dropwhilenot(func, iterable):
"""
>>> list(dropwhilenot(lambda x:x==3, range(10)))
[3, 4, 5, 6, 7, 8, 9]
"""
iterable = iter(iterable)
for x in iterable:
if func(x): break
else: return
yield x
for x in iterable:
yield x | [
"def",
"dropwhilenot",
"(",
"func",
",",
"iterable",
")",
":",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"for",
"x",
"in",
"iterable",
":",
"if",
"func",
"(",
"x",
")",
":",
"break",
"else",
":",
"return",
"yield",
"x",
"for",
"x",
"in",
"iterable",
":",
"yield",
"x"
] | >>> list(dropwhilenot(lambda x:x==3, range(10)))
[3, 4, 5, 6, 7, 8, 9] | [
">>>",
"list",
"(",
"dropwhilenot",
"(",
"lambda",
"x",
":",
"x",
"==",
"3",
"range",
"(",
"10",
")))",
"[",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"]"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L802-L813 | train |
ewiger/mlab | src/mlab/awmstools.py | stretch | def stretch(iterable, n=2):
r"""Repeat each item in `iterable` `n` times.
Example:
>>> list(stretch(range(3), 2))
[0, 0, 1, 1, 2, 2]
"""
times = range(n)
for item in iterable:
for i in times: yield item | python | def stretch(iterable, n=2):
r"""Repeat each item in `iterable` `n` times.
Example:
>>> list(stretch(range(3), 2))
[0, 0, 1, 1, 2, 2]
"""
times = range(n)
for item in iterable:
for i in times: yield item | [
"def",
"stretch",
"(",
"iterable",
",",
"n",
"=",
"2",
")",
":",
"times",
"=",
"range",
"(",
"n",
")",
"for",
"item",
"in",
"iterable",
":",
"for",
"i",
"in",
"times",
":",
"yield",
"item"
] | r"""Repeat each item in `iterable` `n` times.
Example:
>>> list(stretch(range(3), 2))
[0, 0, 1, 1, 2, 2] | [
"r",
"Repeat",
"each",
"item",
"in",
"iterable",
"n",
"times",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L816-L826 | train |
ewiger/mlab | src/mlab/awmstools.py | splitAt | def splitAt(iterable, indices):
r"""Yield chunks of `iterable`, split at the points in `indices`:
>>> [l for l in splitAt(range(10), [2,5])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
splits past the length of `iterable` are ignored:
>>> [l for l in splitAt(range(10), [2,5,10])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
"""
iterable = iter(iterable)
now = 0
for to in indices:
try:
res = []
for i in range(now, to): res.append(iterable.next())
except StopIteration: yield res; return
yield res
now = to
res = list(iterable)
if res: yield res | python | def splitAt(iterable, indices):
r"""Yield chunks of `iterable`, split at the points in `indices`:
>>> [l for l in splitAt(range(10), [2,5])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
splits past the length of `iterable` are ignored:
>>> [l for l in splitAt(range(10), [2,5,10])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
"""
iterable = iter(iterable)
now = 0
for to in indices:
try:
res = []
for i in range(now, to): res.append(iterable.next())
except StopIteration: yield res; return
yield res
now = to
res = list(iterable)
if res: yield res | [
"def",
"splitAt",
"(",
"iterable",
",",
"indices",
")",
":",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"now",
"=",
"0",
"for",
"to",
"in",
"indices",
":",
"try",
":",
"res",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"now",
",",
"to",
")",
":",
"res",
".",
"append",
"(",
"iterable",
".",
"next",
"(",
")",
")",
"except",
"StopIteration",
":",
"yield",
"res",
"return",
"yield",
"res",
"now",
"=",
"to",
"res",
"=",
"list",
"(",
"iterable",
")",
"if",
"res",
":",
"yield",
"res"
] | r"""Yield chunks of `iterable`, split at the points in `indices`:
>>> [l for l in splitAt(range(10), [2,5])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
splits past the length of `iterable` are ignored:
>>> [l for l in splitAt(range(10), [2,5,10])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]] | [
"r",
"Yield",
"chunks",
"of",
"iterable",
"split",
"at",
"the",
"points",
"in",
"indices",
":"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L829-L852 | train |
ewiger/mlab | src/mlab/awmstools.py | update | def update(d, e):
"""Return a copy of dict `d` updated with dict `e`."""
res = copy.copy(d)
res.update(e)
return res | python | def update(d, e):
"""Return a copy of dict `d` updated with dict `e`."""
res = copy.copy(d)
res.update(e)
return res | [
"def",
"update",
"(",
"d",
",",
"e",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"d",
")",
"res",
".",
"update",
"(",
"e",
")",
"return",
"res"
] | Return a copy of dict `d` updated with dict `e`. | [
"Return",
"a",
"copy",
"of",
"dict",
"d",
"updated",
"with",
"dict",
"e",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L875-L879 | train |
ewiger/mlab | src/mlab/awmstools.py | invertDict | def invertDict(d, allowManyToOne=False):
r"""Return an inverted version of dict `d`, so that values become keys and
vice versa. If multiple keys in `d` have the same value an error is
raised, unless `allowManyToOne` is true, in which case one of those
key-value pairs is chosen at random for the inversion.
Examples:
>>> invertDict({1: 2, 3: 4}) == {2: 1, 4: 3}
True
>>> invertDict({1: 2, 3: 2})
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: d can't be inverted!
>>> invertDict({1: 2, 3: 2}, allowManyToOne=True).keys()
[2]
"""
res = dict(izip(d.itervalues(), d.iterkeys()))
if not allowManyToOne and len(res) != len(d):
raise ValueError("d can't be inverted!")
return res | python | def invertDict(d, allowManyToOne=False):
r"""Return an inverted version of dict `d`, so that values become keys and
vice versa. If multiple keys in `d` have the same value an error is
raised, unless `allowManyToOne` is true, in which case one of those
key-value pairs is chosen at random for the inversion.
Examples:
>>> invertDict({1: 2, 3: 4}) == {2: 1, 4: 3}
True
>>> invertDict({1: 2, 3: 2})
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: d can't be inverted!
>>> invertDict({1: 2, 3: 2}, allowManyToOne=True).keys()
[2]
"""
res = dict(izip(d.itervalues(), d.iterkeys()))
if not allowManyToOne and len(res) != len(d):
raise ValueError("d can't be inverted!")
return res | [
"def",
"invertDict",
"(",
"d",
",",
"allowManyToOne",
"=",
"False",
")",
":",
"res",
"=",
"dict",
"(",
"izip",
"(",
"d",
".",
"itervalues",
"(",
")",
",",
"d",
".",
"iterkeys",
"(",
")",
")",
")",
"if",
"not",
"allowManyToOne",
"and",
"len",
"(",
"res",
")",
"!=",
"len",
"(",
"d",
")",
":",
"raise",
"ValueError",
"(",
"\"d can't be inverted!\"",
")",
"return",
"res"
] | r"""Return an inverted version of dict `d`, so that values become keys and
vice versa. If multiple keys in `d` have the same value an error is
raised, unless `allowManyToOne` is true, in which case one of those
key-value pairs is chosen at random for the inversion.
Examples:
>>> invertDict({1: 2, 3: 4}) == {2: 1, 4: 3}
True
>>> invertDict({1: 2, 3: 2})
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: d can't be inverted!
>>> invertDict({1: 2, 3: 2}, allowManyToOne=True).keys()
[2] | [
"r",
"Return",
"an",
"inverted",
"version",
"of",
"dict",
"d",
"so",
"that",
"values",
"become",
"keys",
"and",
"vice",
"versa",
".",
"If",
"multiple",
"keys",
"in",
"d",
"have",
"the",
"same",
"value",
"an",
"error",
"is",
"raised",
"unless",
"allowManyToOne",
"is",
"true",
"in",
"which",
"case",
"one",
"of",
"those",
"key",
"-",
"value",
"pairs",
"is",
"chosen",
"at",
"random",
"for",
"the",
"inversion",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L881-L901 | train |
ewiger/mlab | src/mlab/awmstools.py | iflatten | def iflatten(seq, isSeq=isSeq):
r"""Like `flatten` but lazy."""
for elt in seq:
if isSeq(elt):
for x in iflatten(elt, isSeq):
yield x
else:
yield elt | python | def iflatten(seq, isSeq=isSeq):
r"""Like `flatten` but lazy."""
for elt in seq:
if isSeq(elt):
for x in iflatten(elt, isSeq):
yield x
else:
yield elt | [
"def",
"iflatten",
"(",
"seq",
",",
"isSeq",
"=",
"isSeq",
")",
":",
"for",
"elt",
"in",
"seq",
":",
"if",
"isSeq",
"(",
"elt",
")",
":",
"for",
"x",
"in",
"iflatten",
"(",
"elt",
",",
"isSeq",
")",
":",
"yield",
"x",
"else",
":",
"yield",
"elt"
] | r"""Like `flatten` but lazy. | [
"r",
"Like",
"flatten",
"but",
"lazy",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L907-L914 | train |
ewiger/mlab | src/mlab/awmstools.py | flatten | def flatten(seq, isSeq=isSeq):
r"""Returns a flattened version of a sequence `seq` as a `list`.
Parameters:
- `seq`: The sequence to be flattened (any iterable).
- `isSeq`: The function called to determine whether something is a
sequence (default: `isSeq`). *Beware that this function should
**never** test positive for strings, because they are no real
sequences and thus cause infinite recursion.*
Examples:
>>> flatten([1,[2,3,(4,[5,6]),7,8]])
[1, 2, 3, 4, 5, 6, 7, 8]
>>> # flaten only lists
>>> flatten([1,[2,3,(4,[5,6]),7,8]], isSeq=lambda x:isinstance(x, list))
[1, 2, 3, (4, [5, 6]), 7, 8]
>>> flatten([1,2])
[1, 2]
>>> flatten([])
[]
>>> flatten('123')
['1', '2', '3']
"""
return [a for elt in seq
for a in (isSeq(elt) and flatten(elt, isSeq) or
[elt])] | python | def flatten(seq, isSeq=isSeq):
r"""Returns a flattened version of a sequence `seq` as a `list`.
Parameters:
- `seq`: The sequence to be flattened (any iterable).
- `isSeq`: The function called to determine whether something is a
sequence (default: `isSeq`). *Beware that this function should
**never** test positive for strings, because they are no real
sequences and thus cause infinite recursion.*
Examples:
>>> flatten([1,[2,3,(4,[5,6]),7,8]])
[1, 2, 3, 4, 5, 6, 7, 8]
>>> # flaten only lists
>>> flatten([1,[2,3,(4,[5,6]),7,8]], isSeq=lambda x:isinstance(x, list))
[1, 2, 3, (4, [5, 6]), 7, 8]
>>> flatten([1,2])
[1, 2]
>>> flatten([])
[]
>>> flatten('123')
['1', '2', '3']
"""
return [a for elt in seq
for a in (isSeq(elt) and flatten(elt, isSeq) or
[elt])] | [
"def",
"flatten",
"(",
"seq",
",",
"isSeq",
"=",
"isSeq",
")",
":",
"return",
"[",
"a",
"for",
"elt",
"in",
"seq",
"for",
"a",
"in",
"(",
"isSeq",
"(",
"elt",
")",
"and",
"flatten",
"(",
"elt",
",",
"isSeq",
")",
"or",
"[",
"elt",
"]",
")",
"]"
] | r"""Returns a flattened version of a sequence `seq` as a `list`.
Parameters:
- `seq`: The sequence to be flattened (any iterable).
- `isSeq`: The function called to determine whether something is a
sequence (default: `isSeq`). *Beware that this function should
**never** test positive for strings, because they are no real
sequences and thus cause infinite recursion.*
Examples:
>>> flatten([1,[2,3,(4,[5,6]),7,8]])
[1, 2, 3, 4, 5, 6, 7, 8]
>>> # flaten only lists
>>> flatten([1,[2,3,(4,[5,6]),7,8]], isSeq=lambda x:isinstance(x, list))
[1, 2, 3, (4, [5, 6]), 7, 8]
>>> flatten([1,2])
[1, 2]
>>> flatten([])
[]
>>> flatten('123')
['1', '2', '3'] | [
"r",
"Returns",
"a",
"flattened",
"version",
"of",
"a",
"sequence",
"seq",
"as",
"a",
"list",
".",
"Parameters",
":"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L929-L955 | train |
ewiger/mlab | src/mlab/awmstools.py | positionIf | def positionIf(pred, seq):
"""
>>> positionIf(lambda x: x > 3, range(10))
4
"""
for i,e in enumerate(seq):
if pred(e):
return i
return -1 | python | def positionIf(pred, seq):
"""
>>> positionIf(lambda x: x > 3, range(10))
4
"""
for i,e in enumerate(seq):
if pred(e):
return i
return -1 | [
"def",
"positionIf",
"(",
"pred",
",",
"seq",
")",
":",
"for",
"i",
",",
"e",
"in",
"enumerate",
"(",
"seq",
")",
":",
"if",
"pred",
"(",
"e",
")",
":",
"return",
"i",
"return",
"-",
"1"
] | >>> positionIf(lambda x: x > 3, range(10))
4 | [
">>>",
"positionIf",
"(",
"lambda",
"x",
":",
"x",
">",
"3",
"range",
"(",
"10",
"))",
"4"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L969-L977 | train |
ewiger/mlab | src/mlab/awmstools.py | union | def union(seq1=(), *seqs):
r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random.
Examples:
>>> union()
[]
>>> union([1,2,3])
[1, 2, 3]
>>> union([1,2,3], {1:2, 5:1})
[1, 2, 3, 5]
>>> union((1,2,3), ['a'], "bcd")
['a', 1, 2, 3, 'd', 'b', 'c']
>>> union([1,2,3], iter([0,1,1,1]))
[0, 1, 2, 3]
"""
if not seqs: return list(seq1)
res = set(seq1)
for seq in seqs:
res.update(set(seq))
return list(res) | python | def union(seq1=(), *seqs):
r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random.
Examples:
>>> union()
[]
>>> union([1,2,3])
[1, 2, 3]
>>> union([1,2,3], {1:2, 5:1})
[1, 2, 3, 5]
>>> union((1,2,3), ['a'], "bcd")
['a', 1, 2, 3, 'd', 'b', 'c']
>>> union([1,2,3], iter([0,1,1,1]))
[0, 1, 2, 3]
"""
if not seqs: return list(seq1)
res = set(seq1)
for seq in seqs:
res.update(set(seq))
return list(res) | [
"def",
"union",
"(",
"seq1",
"=",
"(",
")",
",",
"*",
"seqs",
")",
":",
"if",
"not",
"seqs",
":",
"return",
"list",
"(",
"seq1",
")",
"res",
"=",
"set",
"(",
"seq1",
")",
"for",
"seq",
"in",
"seqs",
":",
"res",
".",
"update",
"(",
"set",
"(",
"seq",
")",
")",
"return",
"list",
"(",
"res",
")"
] | r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random.
Examples:
>>> union()
[]
>>> union([1,2,3])
[1, 2, 3]
>>> union([1,2,3], {1:2, 5:1})
[1, 2, 3, 5]
>>> union((1,2,3), ['a'], "bcd")
['a', 1, 2, 3, 'd', 'b', 'c']
>>> union([1,2,3], iter([0,1,1,1]))
[0, 1, 2, 3] | [
"r",
"Return",
"the",
"set",
"union",
"of",
"seq1",
"and",
"seqs",
"duplicates",
"removed",
"order",
"random",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L981-L1001 | train |
ewiger/mlab | src/mlab/awmstools.py | without | def without(seq1, seq2):
r"""Return a list with all elements in `seq2` removed from `seq1`, order
preserved.
Examples:
>>> without([1,2,3,1,2], [1])
[2, 3, 2]
"""
if isSet(seq2): d2 = seq2
else: d2 = set(seq2)
return [elt for elt in seq1 if elt not in d2] | python | def without(seq1, seq2):
r"""Return a list with all elements in `seq2` removed from `seq1`, order
preserved.
Examples:
>>> without([1,2,3,1,2], [1])
[2, 3, 2]
"""
if isSet(seq2): d2 = seq2
else: d2 = set(seq2)
return [elt for elt in seq1 if elt not in d2] | [
"def",
"without",
"(",
"seq1",
",",
"seq2",
")",
":",
"if",
"isSet",
"(",
"seq2",
")",
":",
"d2",
"=",
"seq2",
"else",
":",
"d2",
"=",
"set",
"(",
"seq2",
")",
"return",
"[",
"elt",
"for",
"elt",
"in",
"seq1",
"if",
"elt",
"not",
"in",
"d2",
"]"
] | r"""Return a list with all elements in `seq2` removed from `seq1`, order
preserved.
Examples:
>>> without([1,2,3,1,2], [1])
[2, 3, 2] | [
"r",
"Return",
"a",
"list",
"with",
"all",
"elements",
"in",
"seq2",
"removed",
"from",
"seq1",
"order",
"preserved",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1011-L1022 | train |
ewiger/mlab | src/mlab/awmstools.py | some | def some(predicate, *seqs):
"""
>>> some(lambda x: x, [0, False, None])
False
>>> some(lambda x: x, [None, 0, 2, 3])
2
>>> some(operator.eq, [0,1,2], [2,1,0])
True
>>> some(operator.eq, [1,2], [2,1])
False
"""
try:
if len(seqs) == 1: return ifilter(bool,imap(predicate, seqs[0])).next()
else: return ifilter(bool,starmap(predicate, izip(*seqs))).next()
except StopIteration: return False | python | def some(predicate, *seqs):
"""
>>> some(lambda x: x, [0, False, None])
False
>>> some(lambda x: x, [None, 0, 2, 3])
2
>>> some(operator.eq, [0,1,2], [2,1,0])
True
>>> some(operator.eq, [1,2], [2,1])
False
"""
try:
if len(seqs) == 1: return ifilter(bool,imap(predicate, seqs[0])).next()
else: return ifilter(bool,starmap(predicate, izip(*seqs))).next()
except StopIteration: return False | [
"def",
"some",
"(",
"predicate",
",",
"*",
"seqs",
")",
":",
"try",
":",
"if",
"len",
"(",
"seqs",
")",
"==",
"1",
":",
"return",
"ifilter",
"(",
"bool",
",",
"imap",
"(",
"predicate",
",",
"seqs",
"[",
"0",
"]",
")",
")",
".",
"next",
"(",
")",
"else",
":",
"return",
"ifilter",
"(",
"bool",
",",
"starmap",
"(",
"predicate",
",",
"izip",
"(",
"*",
"seqs",
")",
")",
")",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"return",
"False"
] | >>> some(lambda x: x, [0, False, None])
False
>>> some(lambda x: x, [None, 0, 2, 3])
2
>>> some(operator.eq, [0,1,2], [2,1,0])
True
>>> some(operator.eq, [1,2], [2,1])
False | [
">>>",
"some",
"(",
"lambda",
"x",
":",
"x",
"[",
"0",
"False",
"None",
"]",
")",
"False",
">>>",
"some",
"(",
"lambda",
"x",
":",
"x",
"[",
"None",
"0",
"2",
"3",
"]",
")",
"2",
">>>",
"some",
"(",
"operator",
".",
"eq",
"[",
"0",
"1",
"2",
"]",
"[",
"2",
"1",
"0",
"]",
")",
"True",
">>>",
"some",
"(",
"operator",
".",
"eq",
"[",
"1",
"2",
"]",
"[",
"2",
"1",
"]",
")",
"False"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1037-L1051 | train |
ewiger/mlab | src/mlab/awmstools.py | every | def every(predicate, *iterables):
r"""Like `some`, but only returns `True` if all the elements of `iterables`
satisfy `predicate`.
Examples:
>>> every(bool, [])
True
>>> every(bool, [0])
False
>>> every(bool, [1,1])
True
>>> every(operator.eq, [1,2,3],[1,2])
True
>>> every(operator.eq, [1,2,3],[0,2])
False
"""
try:
if len(iterables) == 1: ifilterfalse(predicate, iterables[0]).next()
else: ifilterfalse(bool, starmap(predicate, izip(*iterables))).next()
except StopIteration: return True
else: return False | python | def every(predicate, *iterables):
r"""Like `some`, but only returns `True` if all the elements of `iterables`
satisfy `predicate`.
Examples:
>>> every(bool, [])
True
>>> every(bool, [0])
False
>>> every(bool, [1,1])
True
>>> every(operator.eq, [1,2,3],[1,2])
True
>>> every(operator.eq, [1,2,3],[0,2])
False
"""
try:
if len(iterables) == 1: ifilterfalse(predicate, iterables[0]).next()
else: ifilterfalse(bool, starmap(predicate, izip(*iterables))).next()
except StopIteration: return True
else: return False | [
"def",
"every",
"(",
"predicate",
",",
"*",
"iterables",
")",
":",
"try",
":",
"if",
"len",
"(",
"iterables",
")",
"==",
"1",
":",
"ifilterfalse",
"(",
"predicate",
",",
"iterables",
"[",
"0",
"]",
")",
".",
"next",
"(",
")",
"else",
":",
"ifilterfalse",
"(",
"bool",
",",
"starmap",
"(",
"predicate",
",",
"izip",
"(",
"*",
"iterables",
")",
")",
")",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | r"""Like `some`, but only returns `True` if all the elements of `iterables`
satisfy `predicate`.
Examples:
>>> every(bool, [])
True
>>> every(bool, [0])
False
>>> every(bool, [1,1])
True
>>> every(operator.eq, [1,2,3],[1,2])
True
>>> every(operator.eq, [1,2,3],[0,2])
False | [
"r",
"Like",
"some",
"but",
"only",
"returns",
"True",
"if",
"all",
"the",
"elements",
"of",
"iterables",
"satisfy",
"predicate",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1053-L1073 | train |
ewiger/mlab | src/mlab/awmstools.py | nTimes | def nTimes(n, f, *args, **kwargs):
r"""Call `f` `n` times with `args` and `kwargs`.
Useful e.g. for simplistic timing.
Examples:
>>> nTimes(3, sys.stdout.write, 'hallo\n')
hallo
hallo
hallo
"""
for i in xrange(n): f(*args, **kwargs) | python | def nTimes(n, f, *args, **kwargs):
r"""Call `f` `n` times with `args` and `kwargs`.
Useful e.g. for simplistic timing.
Examples:
>>> nTimes(3, sys.stdout.write, 'hallo\n')
hallo
hallo
hallo
"""
for i in xrange(n): f(*args, **kwargs) | [
"def",
"nTimes",
"(",
"n",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"n",
")",
":",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | r"""Call `f` `n` times with `args` and `kwargs`.
Useful e.g. for simplistic timing.
Examples:
>>> nTimes(3, sys.stdout.write, 'hallo\n')
hallo
hallo
hallo | [
"r",
"Call",
"f",
"n",
"times",
"with",
"args",
"and",
"kwargs",
".",
"Useful",
"e",
".",
"g",
".",
"for",
"simplistic",
"timing",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1082-L1094 | train |
ewiger/mlab | src/mlab/awmstools.py | timeCall | def timeCall(*funcAndArgs, **kwargs):
r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)``
"""
func, args = funcAndArgs[0], funcAndArgs[1:]
start = time.time()
func(*args, **kwargs)
return time.time() - start | python | def timeCall(*funcAndArgs, **kwargs):
r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)``
"""
func, args = funcAndArgs[0], funcAndArgs[1:]
start = time.time()
func(*args, **kwargs)
return time.time() - start | [
"def",
"timeCall",
"(",
"*",
"funcAndArgs",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
",",
"args",
"=",
"funcAndArgs",
"[",
"0",
"]",
",",
"funcAndArgs",
"[",
"1",
":",
"]",
"start",
"=",
"time",
".",
"time",
"(",
")",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"time",
".",
"time",
"(",
")",
"-",
"start"
] | r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)`` | [
"r",
"Return",
"the",
"time",
"(",
"in",
"ms",
")",
"it",
"takes",
"to",
"call",
"a",
"function",
"(",
"the",
"first",
"argument",
")",
"with",
"the",
"remaining",
"arguments",
"and",
"kwargs",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1097-L1111 | train |
ewiger/mlab | src/mlab/awmstools.py | replaceStrs | def replaceStrs(s, *args):
r"""Replace all ``(frm, to)`` tuples in `args` in string `s`.
>>> replaceStrs("nothing is better than warm beer",
... ('nothing','warm beer'), ('warm beer','nothing'))
'warm beer is better than nothing'
"""
if args == (): return s
mapping = dict((frm, to) for frm, to in args)
return re.sub("|".join(map(re.escape, mapping.keys())),
lambda match:mapping[match.group(0)], s) | python | def replaceStrs(s, *args):
r"""Replace all ``(frm, to)`` tuples in `args` in string `s`.
>>> replaceStrs("nothing is better than warm beer",
... ('nothing','warm beer'), ('warm beer','nothing'))
'warm beer is better than nothing'
"""
if args == (): return s
mapping = dict((frm, to) for frm, to in args)
return re.sub("|".join(map(re.escape, mapping.keys())),
lambda match:mapping[match.group(0)], s) | [
"def",
"replaceStrs",
"(",
"s",
",",
"*",
"args",
")",
":",
"if",
"args",
"==",
"(",
")",
":",
"return",
"s",
"mapping",
"=",
"dict",
"(",
"(",
"frm",
",",
"to",
")",
"for",
"frm",
",",
"to",
"in",
"args",
")",
"return",
"re",
".",
"sub",
"(",
"\"|\"",
".",
"join",
"(",
"map",
"(",
"re",
".",
"escape",
",",
"mapping",
".",
"keys",
"(",
")",
")",
")",
",",
"lambda",
"match",
":",
"mapping",
"[",
"match",
".",
"group",
"(",
"0",
")",
"]",
",",
"s",
")"
] | r"""Replace all ``(frm, to)`` tuples in `args` in string `s`.
>>> replaceStrs("nothing is better than warm beer",
... ('nothing','warm beer'), ('warm beer','nothing'))
'warm beer is better than nothing' | [
"r",
"Replace",
"all",
"(",
"frm",
"to",
")",
"tuples",
"in",
"args",
"in",
"string",
"s",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1148-L1159 | train |
ewiger/mlab | src/mlab/awmstools.py | unescape | def unescape(s):
r"""Inverse of `escape`.
>>> unescape(r'\x41\n\x42\n\x43')
'A\nB\nC'
>>> unescape(r'\u86c7')
u'\u86c7'
>>> unescape(u'ah')
u'ah'
"""
if re.search(r'(?<!\\)\\(\\\\)*[uU]', s) or isinstance(s, unicode):
return unescapeUnicode(s)
else:
return unescapeAscii(s) | python | def unescape(s):
r"""Inverse of `escape`.
>>> unescape(r'\x41\n\x42\n\x43')
'A\nB\nC'
>>> unescape(r'\u86c7')
u'\u86c7'
>>> unescape(u'ah')
u'ah'
"""
if re.search(r'(?<!\\)\\(\\\\)*[uU]', s) or isinstance(s, unicode):
return unescapeUnicode(s)
else:
return unescapeAscii(s) | [
"def",
"unescape",
"(",
"s",
")",
":",
"if",
"re",
".",
"search",
"(",
"r'(?<!\\\\)\\\\(\\\\\\\\)*[uU]'",
",",
"s",
")",
"or",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"return",
"unescapeUnicode",
"(",
"s",
")",
"else",
":",
"return",
"unescapeAscii",
"(",
"s",
")"
] | r"""Inverse of `escape`.
>>> unescape(r'\x41\n\x42\n\x43')
'A\nB\nC'
>>> unescape(r'\u86c7')
u'\u86c7'
>>> unescape(u'ah')
u'ah' | [
"r",
"Inverse",
"of",
"escape",
".",
">>>",
"unescape",
"(",
"r",
"\\",
"x41",
"\\",
"n",
"\\",
"x42",
"\\",
"n",
"\\",
"x43",
")",
"A",
"\\",
"nB",
"\\",
"nC",
">>>",
"unescape",
"(",
"r",
"\\",
"u86c7",
")",
"u",
"\\",
"u86c7",
">>>",
"unescape",
"(",
"u",
"ah",
")",
"u",
"ah"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1178-L1190 | train |
ewiger/mlab | src/mlab/awmstools.py | lineAndColumnAt | def lineAndColumnAt(s, pos):
r"""Return line and column of `pos` (0-based!) in `s`. Lines start with
1, columns with 0.
Examples:
>>> lineAndColumnAt("0123\n56", 5)
(2, 0)
>>> lineAndColumnAt("0123\n56", 6)
(2, 1)
>>> lineAndColumnAt("0123\n56", 0)
(1, 0)
"""
if pos >= len(s):
raise IndexError("`pos` %d not in string" % pos)
# *don't* count last '\n', if it is at pos!
line = s.count('\n',0,pos)
if line:
return line + 1, pos - s.rfind('\n',0,pos) - 1
else:
return 1, pos | python | def lineAndColumnAt(s, pos):
r"""Return line and column of `pos` (0-based!) in `s`. Lines start with
1, columns with 0.
Examples:
>>> lineAndColumnAt("0123\n56", 5)
(2, 0)
>>> lineAndColumnAt("0123\n56", 6)
(2, 1)
>>> lineAndColumnAt("0123\n56", 0)
(1, 0)
"""
if pos >= len(s):
raise IndexError("`pos` %d not in string" % pos)
# *don't* count last '\n', if it is at pos!
line = s.count('\n',0,pos)
if line:
return line + 1, pos - s.rfind('\n',0,pos) - 1
else:
return 1, pos | [
"def",
"lineAndColumnAt",
"(",
"s",
",",
"pos",
")",
":",
"if",
"pos",
">=",
"len",
"(",
"s",
")",
":",
"raise",
"IndexError",
"(",
"\"`pos` %d not in string\"",
"%",
"pos",
")",
"# *don't* count last '\\n', if it is at pos!",
"line",
"=",
"s",
".",
"count",
"(",
"'\\n'",
",",
"0",
",",
"pos",
")",
"if",
"line",
":",
"return",
"line",
"+",
"1",
",",
"pos",
"-",
"s",
".",
"rfind",
"(",
"'\\n'",
",",
"0",
",",
"pos",
")",
"-",
"1",
"else",
":",
"return",
"1",
",",
"pos"
] | r"""Return line and column of `pos` (0-based!) in `s`. Lines start with
1, columns with 0.
Examples:
>>> lineAndColumnAt("0123\n56", 5)
(2, 0)
>>> lineAndColumnAt("0123\n56", 6)
(2, 1)
>>> lineAndColumnAt("0123\n56", 0)
(1, 0) | [
"r",
"Return",
"line",
"and",
"column",
"of",
"pos",
"(",
"0",
"-",
"based!",
")",
"in",
"s",
".",
"Lines",
"start",
"with",
"1",
"columns",
"with",
"0",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1198-L1218 | train |
ewiger/mlab | src/mlab/awmstools.py | prin | def prin(*args, **kwargs):
r"""Like ``print``, but a function. I.e. prints out all arguments as
``print`` would do. Specify output stream like this::
print('ERROR', `out="sys.stderr"``).
"""
print >> kwargs.get('out',None), " ".join([str(arg) for arg in args]) | python | def prin(*args, **kwargs):
r"""Like ``print``, but a function. I.e. prints out all arguments as
``print`` would do. Specify output stream like this::
print('ERROR', `out="sys.stderr"``).
"""
print >> kwargs.get('out',None), " ".join([str(arg) for arg in args]) | [
"def",
"prin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
">>",
"kwargs",
".",
"get",
"(",
"'out'",
",",
"None",
")",
",",
"\" \"",
".",
"join",
"(",
"[",
"str",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
")"
] | r"""Like ``print``, but a function. I.e. prints out all arguments as
``print`` would do. Specify output stream like this::
print('ERROR', `out="sys.stderr"``). | [
"r",
"Like",
"print",
"but",
"a",
"function",
".",
"I",
".",
"e",
".",
"prints",
"out",
"all",
"arguments",
"as",
"print",
"would",
"do",
".",
"Specify",
"output",
"stream",
"like",
"this",
"::"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1222-L1229 | train |
ewiger/mlab | src/mlab/awmstools.py | fitString | def fitString(s, maxCol=79, newlineReplacement=None):
r"""Truncate `s` if necessary to fit into a line of width `maxCol`
(default: 79), also replacing newlines with `newlineReplacement` (default
`None`: in which case everything after the first newline is simply
discarded).
Examples:
>>> fitString('12345', maxCol=5)
'12345'
>>> fitString('123456', maxCol=5)
'12...'
>>> fitString('a line\na second line')
'a line'
>>> fitString('a line\na second line', newlineReplacement='\\n')
'a line\\na second line'
"""
assert isString(s)
if '\n' in s:
if newlineReplacement is None:
s = s[:s.index('\n')]
else:
s = s.replace("\n", newlineReplacement)
if maxCol is not None and len(s) > maxCol:
s = "%s..." % s[:maxCol-3]
return s | python | def fitString(s, maxCol=79, newlineReplacement=None):
r"""Truncate `s` if necessary to fit into a line of width `maxCol`
(default: 79), also replacing newlines with `newlineReplacement` (default
`None`: in which case everything after the first newline is simply
discarded).
Examples:
>>> fitString('12345', maxCol=5)
'12345'
>>> fitString('123456', maxCol=5)
'12...'
>>> fitString('a line\na second line')
'a line'
>>> fitString('a line\na second line', newlineReplacement='\\n')
'a line\\na second line'
"""
assert isString(s)
if '\n' in s:
if newlineReplacement is None:
s = s[:s.index('\n')]
else:
s = s.replace("\n", newlineReplacement)
if maxCol is not None and len(s) > maxCol:
s = "%s..." % s[:maxCol-3]
return s | [
"def",
"fitString",
"(",
"s",
",",
"maxCol",
"=",
"79",
",",
"newlineReplacement",
"=",
"None",
")",
":",
"assert",
"isString",
"(",
"s",
")",
"if",
"'\\n'",
"in",
"s",
":",
"if",
"newlineReplacement",
"is",
"None",
":",
"s",
"=",
"s",
"[",
":",
"s",
".",
"index",
"(",
"'\\n'",
")",
"]",
"else",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"\"\\n\"",
",",
"newlineReplacement",
")",
"if",
"maxCol",
"is",
"not",
"None",
"and",
"len",
"(",
"s",
")",
">",
"maxCol",
":",
"s",
"=",
"\"%s...\"",
"%",
"s",
"[",
":",
"maxCol",
"-",
"3",
"]",
"return",
"s"
] | r"""Truncate `s` if necessary to fit into a line of width `maxCol`
(default: 79), also replacing newlines with `newlineReplacement` (default
`None`: in which case everything after the first newline is simply
discarded).
Examples:
>>> fitString('12345', maxCol=5)
'12345'
>>> fitString('123456', maxCol=5)
'12...'
>>> fitString('a line\na second line')
'a line'
>>> fitString('a line\na second line', newlineReplacement='\\n')
'a line\\na second line' | [
"r",
"Truncate",
"s",
"if",
"necessary",
"to",
"fit",
"into",
"a",
"line",
"of",
"width",
"maxCol",
"(",
"default",
":",
"79",
")",
"also",
"replacing",
"newlines",
"with",
"newlineReplacement",
"(",
"default",
"None",
":",
"in",
"which",
"case",
"everything",
"after",
"the",
"first",
"newline",
"is",
"simply",
"discarded",
")",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1249-L1274 | train |
ewiger/mlab | src/mlab/awmstools.py | saveVars | def saveVars(filename, varNamesStr, outOf=None, **opts):
r"""Pickle name and value of all those variables in `outOf` (default: all
global variables (as seen from the caller)) that are named in
`varNamesStr` into a file called `filename` (if no extension is given,
'.bpickle' is appended). Overwrites file without asking, unless you
specify `overwrite=0`. Load again with `loadVars`.
Thus, to save the global variables ``bar``, ``foo`` and ``baz`` in the
file 'savedVars' do::
saveVars('savedVars', 'bar foo baz')
"""
filename, varnames, outOf = __saveVarsHelper(
filename, varNamesStr, outOf, **opts)
print "pickling:\n", "\n".join(sorted(varnames))
try:
f = None
f = open(filename, "wb")
cPickle.dump(dict(zip(varnames, atIndices(outOf, varnames))),
f, 1) # UGH: cPickle, unlike pickle doesn't accept bin=1
finally:
if f: f.close() | python | def saveVars(filename, varNamesStr, outOf=None, **opts):
r"""Pickle name and value of all those variables in `outOf` (default: all
global variables (as seen from the caller)) that are named in
`varNamesStr` into a file called `filename` (if no extension is given,
'.bpickle' is appended). Overwrites file without asking, unless you
specify `overwrite=0`. Load again with `loadVars`.
Thus, to save the global variables ``bar``, ``foo`` and ``baz`` in the
file 'savedVars' do::
saveVars('savedVars', 'bar foo baz')
"""
filename, varnames, outOf = __saveVarsHelper(
filename, varNamesStr, outOf, **opts)
print "pickling:\n", "\n".join(sorted(varnames))
try:
f = None
f = open(filename, "wb")
cPickle.dump(dict(zip(varnames, atIndices(outOf, varnames))),
f, 1) # UGH: cPickle, unlike pickle doesn't accept bin=1
finally:
if f: f.close() | [
"def",
"saveVars",
"(",
"filename",
",",
"varNamesStr",
",",
"outOf",
"=",
"None",
",",
"*",
"*",
"opts",
")",
":",
"filename",
",",
"varnames",
",",
"outOf",
"=",
"__saveVarsHelper",
"(",
"filename",
",",
"varNamesStr",
",",
"outOf",
",",
"*",
"*",
"opts",
")",
"print",
"\"pickling:\\n\"",
",",
"\"\\n\"",
".",
"join",
"(",
"sorted",
"(",
"varnames",
")",
")",
"try",
":",
"f",
"=",
"None",
"f",
"=",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"cPickle",
".",
"dump",
"(",
"dict",
"(",
"zip",
"(",
"varnames",
",",
"atIndices",
"(",
"outOf",
",",
"varnames",
")",
")",
")",
",",
"f",
",",
"1",
")",
"# UGH: cPickle, unlike pickle doesn't accept bin=1",
"finally",
":",
"if",
"f",
":",
"f",
".",
"close",
"(",
")"
] | r"""Pickle name and value of all those variables in `outOf` (default: all
global variables (as seen from the caller)) that are named in
`varNamesStr` into a file called `filename` (if no extension is given,
'.bpickle' is appended). Overwrites file without asking, unless you
specify `overwrite=0`. Load again with `loadVars`.
Thus, to save the global variables ``bar``, ``foo`` and ``baz`` in the
file 'savedVars' do::
saveVars('savedVars', 'bar foo baz') | [
"r",
"Pickle",
"name",
"and",
"value",
"of",
"all",
"those",
"variables",
"in",
"outOf",
"(",
"default",
":",
"all",
"global",
"variables",
"(",
"as",
"seen",
"from",
"the",
"caller",
"))",
"that",
"are",
"named",
"in",
"varNamesStr",
"into",
"a",
"file",
"called",
"filename",
"(",
"if",
"no",
"extension",
"is",
"given",
".",
"bpickle",
"is",
"appended",
")",
".",
"Overwrites",
"file",
"without",
"asking",
"unless",
"you",
"specify",
"overwrite",
"=",
"0",
".",
"Load",
"again",
"with",
"loadVars",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1305-L1328 | train |
ewiger/mlab | src/mlab/awmstools.py | addVars | def addVars(filename, varNamesStr, outOf=None):
r"""Like `saveVars`, but appends additional variables to file."""
filename, varnames, outOf = __saveVarsHelper(filename, varNamesStr, outOf)
f = None
try:
f = open(filename, "rb")
h = cPickle.load(f)
f.close()
h.update(dict(zip(varnames, atIndices(outOf, varnames))))
f = open(filename, "wb")
cPickle.dump( h, f , 1 )
finally:
if f: f.close() | python | def addVars(filename, varNamesStr, outOf=None):
r"""Like `saveVars`, but appends additional variables to file."""
filename, varnames, outOf = __saveVarsHelper(filename, varNamesStr, outOf)
f = None
try:
f = open(filename, "rb")
h = cPickle.load(f)
f.close()
h.update(dict(zip(varnames, atIndices(outOf, varnames))))
f = open(filename, "wb")
cPickle.dump( h, f , 1 )
finally:
if f: f.close() | [
"def",
"addVars",
"(",
"filename",
",",
"varNamesStr",
",",
"outOf",
"=",
"None",
")",
":",
"filename",
",",
"varnames",
",",
"outOf",
"=",
"__saveVarsHelper",
"(",
"filename",
",",
"varNamesStr",
",",
"outOf",
")",
"f",
"=",
"None",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"h",
"=",
"cPickle",
".",
"load",
"(",
"f",
")",
"f",
".",
"close",
"(",
")",
"h",
".",
"update",
"(",
"dict",
"(",
"zip",
"(",
"varnames",
",",
"atIndices",
"(",
"outOf",
",",
"varnames",
")",
")",
")",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"cPickle",
".",
"dump",
"(",
"h",
",",
"f",
",",
"1",
")",
"finally",
":",
"if",
"f",
":",
"f",
".",
"close",
"(",
")"
] | r"""Like `saveVars`, but appends additional variables to file. | [
"r",
"Like",
"saveVars",
"but",
"appends",
"additional",
"variables",
"to",
"file",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1336-L1349 | train |
ewiger/mlab | src/mlab/awmstools.py | loadDict | def loadDict(filename):
"""Return the variables pickled pickled into `filename` with `saveVars`
as a dict."""
filename = os.path.expanduser(filename)
if not splitext(filename)[1]: filename += ".bpickle"
f = None
try:
f = open(filename, "rb")
varH = cPickle.load(f)
finally:
if f: f.close()
return varH | python | def loadDict(filename):
"""Return the variables pickled pickled into `filename` with `saveVars`
as a dict."""
filename = os.path.expanduser(filename)
if not splitext(filename)[1]: filename += ".bpickle"
f = None
try:
f = open(filename, "rb")
varH = cPickle.load(f)
finally:
if f: f.close()
return varH | [
"def",
"loadDict",
"(",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"not",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
":",
"filename",
"+=",
"\".bpickle\"",
"f",
"=",
"None",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"varH",
"=",
"cPickle",
".",
"load",
"(",
"f",
")",
"finally",
":",
"if",
"f",
":",
"f",
".",
"close",
"(",
")",
"return",
"varH"
] | Return the variables pickled pickled into `filename` with `saveVars`
as a dict. | [
"Return",
"the",
"variables",
"pickled",
"pickled",
"into",
"filename",
"with",
"saveVars",
"as",
"a",
"dict",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1351-L1362 | train |
ewiger/mlab | src/mlab/awmstools.py | loadVars | def loadVars(filename, ask=True, into=None, only=None):
r"""Load variables pickled with `saveVars`.
Parameters:
- `ask`: If `True` then don't overwrite existing variables without
asking.
- `only`: A list to limit the variables to or `None`.
- `into`: The dictionary the variables should be loaded into (defaults
to global dictionary).
"""
filename = os.path.expanduser(filename)
if into is None: into = magicGlobals()
varH = loadDict(filename)
toUnpickle = only or varH.keys()
alreadyDefined = filter(into.has_key, toUnpickle)
if alreadyDefined and ask:
print "The following vars already exist; overwrite (yes/NO)?\n",\
"\n".join(alreadyDefined)
if raw_input() != "yes":
toUnpickle = without(toUnpickle, alreadyDefined)
if not toUnpickle:
print "nothing to unpickle"
return None
print "unpickling:\n",\
"\n".join(sorted(toUnpickle))
for k in varH.keys():
if k not in toUnpickle:
del varH[k]
into.update(varH) | python | def loadVars(filename, ask=True, into=None, only=None):
r"""Load variables pickled with `saveVars`.
Parameters:
- `ask`: If `True` then don't overwrite existing variables without
asking.
- `only`: A list to limit the variables to or `None`.
- `into`: The dictionary the variables should be loaded into (defaults
to global dictionary).
"""
filename = os.path.expanduser(filename)
if into is None: into = magicGlobals()
varH = loadDict(filename)
toUnpickle = only or varH.keys()
alreadyDefined = filter(into.has_key, toUnpickle)
if alreadyDefined and ask:
print "The following vars already exist; overwrite (yes/NO)?\n",\
"\n".join(alreadyDefined)
if raw_input() != "yes":
toUnpickle = without(toUnpickle, alreadyDefined)
if not toUnpickle:
print "nothing to unpickle"
return None
print "unpickling:\n",\
"\n".join(sorted(toUnpickle))
for k in varH.keys():
if k not in toUnpickle:
del varH[k]
into.update(varH) | [
"def",
"loadVars",
"(",
"filename",
",",
"ask",
"=",
"True",
",",
"into",
"=",
"None",
",",
"only",
"=",
"None",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"into",
"is",
"None",
":",
"into",
"=",
"magicGlobals",
"(",
")",
"varH",
"=",
"loadDict",
"(",
"filename",
")",
"toUnpickle",
"=",
"only",
"or",
"varH",
".",
"keys",
"(",
")",
"alreadyDefined",
"=",
"filter",
"(",
"into",
".",
"has_key",
",",
"toUnpickle",
")",
"if",
"alreadyDefined",
"and",
"ask",
":",
"print",
"\"The following vars already exist; overwrite (yes/NO)?\\n\"",
",",
"\"\\n\"",
".",
"join",
"(",
"alreadyDefined",
")",
"if",
"raw_input",
"(",
")",
"!=",
"\"yes\"",
":",
"toUnpickle",
"=",
"without",
"(",
"toUnpickle",
",",
"alreadyDefined",
")",
"if",
"not",
"toUnpickle",
":",
"print",
"\"nothing to unpickle\"",
"return",
"None",
"print",
"\"unpickling:\\n\"",
",",
"\"\\n\"",
".",
"join",
"(",
"sorted",
"(",
"toUnpickle",
")",
")",
"for",
"k",
"in",
"varH",
".",
"keys",
"(",
")",
":",
"if",
"k",
"not",
"in",
"toUnpickle",
":",
"del",
"varH",
"[",
"k",
"]",
"into",
".",
"update",
"(",
"varH",
")"
] | r"""Load variables pickled with `saveVars`.
Parameters:
- `ask`: If `True` then don't overwrite existing variables without
asking.
- `only`: A list to limit the variables to or `None`.
- `into`: The dictionary the variables should be loaded into (defaults
to global dictionary). | [
"r",
"Load",
"variables",
"pickled",
"with",
"saveVars",
".",
"Parameters",
":"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1364-L1393 | train |
ewiger/mlab | src/mlab/awmstools.py | runInfo | def runInfo(prog=None,vers=None,date=None,user=None,dir=None,args=None):
r"""Create a short info string detailing how a program was invoked. This is
meant to be added to a history comment field of a data file were it is
important to keep track of what programs modified it and how.
!!!:`args` should be a **``list``** not a ``str``."""
return "%(prog)s %(vers)s;" \
" run %(date)s by %(usr)s in %(dir)s with: %(args)s'n" % \
mkDict(prog=prog or sys.argv[0],
vers=vers or magicGlobals().get("__version__", ""),
date=date or isoDateTimeStr(),
usr=user or getpass.getuser(),
dir=dir or os.getcwd(),
args=" ".join(args or sys.argv)) | python | def runInfo(prog=None,vers=None,date=None,user=None,dir=None,args=None):
r"""Create a short info string detailing how a program was invoked. This is
meant to be added to a history comment field of a data file were it is
important to keep track of what programs modified it and how.
!!!:`args` should be a **``list``** not a ``str``."""
return "%(prog)s %(vers)s;" \
" run %(date)s by %(usr)s in %(dir)s with: %(args)s'n" % \
mkDict(prog=prog or sys.argv[0],
vers=vers or magicGlobals().get("__version__", ""),
date=date or isoDateTimeStr(),
usr=user or getpass.getuser(),
dir=dir or os.getcwd(),
args=" ".join(args or sys.argv)) | [
"def",
"runInfo",
"(",
"prog",
"=",
"None",
",",
"vers",
"=",
"None",
",",
"date",
"=",
"None",
",",
"user",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"return",
"\"%(prog)s %(vers)s;\"",
"\" run %(date)s by %(usr)s in %(dir)s with: %(args)s'n\"",
"%",
"mkDict",
"(",
"prog",
"=",
"prog",
"or",
"sys",
".",
"argv",
"[",
"0",
"]",
",",
"vers",
"=",
"vers",
"or",
"magicGlobals",
"(",
")",
".",
"get",
"(",
"\"__version__\"",
",",
"\"\"",
")",
",",
"date",
"=",
"date",
"or",
"isoDateTimeStr",
"(",
")",
",",
"usr",
"=",
"user",
"or",
"getpass",
".",
"getuser",
"(",
")",
",",
"dir",
"=",
"dir",
"or",
"os",
".",
"getcwd",
"(",
")",
",",
"args",
"=",
"\" \"",
".",
"join",
"(",
"args",
"or",
"sys",
".",
"argv",
")",
")"
] | r"""Create a short info string detailing how a program was invoked. This is
meant to be added to a history comment field of a data file were it is
important to keep track of what programs modified it and how.
!!!:`args` should be a **``list``** not a ``str``. | [
"r",
"Create",
"a",
"short",
"info",
"string",
"detailing",
"how",
"a",
"program",
"was",
"invoked",
".",
"This",
"is",
"meant",
"to",
"be",
"added",
"to",
"a",
"history",
"comment",
"field",
"of",
"a",
"data",
"file",
"were",
"it",
"is",
"important",
"to",
"keep",
"track",
"of",
"what",
"programs",
"modified",
"it",
"and",
"how",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1401-L1415 | train |
ewiger/mlab | src/mlab/awmstools.py | makePrintReturner | def makePrintReturner(pre="", post="" ,out=None):
r"""Creates functions that print out their argument, (between optional
`pre` and `post` strings) and return it unmodified. This is usefull for
debugging e.g. parts of expressions, without having to modify the behavior
of the program.
Example:
>>> makePrintReturner(pre="The value is:", post="[returning]")(3)
The value is: 3 [returning]
3
>>>
"""
def printReturner(arg):
myArgs = [pre, arg, post]
prin(*myArgs, **{'out':out})
return arg
return printReturner | python | def makePrintReturner(pre="", post="" ,out=None):
r"""Creates functions that print out their argument, (between optional
`pre` and `post` strings) and return it unmodified. This is usefull for
debugging e.g. parts of expressions, without having to modify the behavior
of the program.
Example:
>>> makePrintReturner(pre="The value is:", post="[returning]")(3)
The value is: 3 [returning]
3
>>>
"""
def printReturner(arg):
myArgs = [pre, arg, post]
prin(*myArgs, **{'out':out})
return arg
return printReturner | [
"def",
"makePrintReturner",
"(",
"pre",
"=",
"\"\"",
",",
"post",
"=",
"\"\"",
",",
"out",
"=",
"None",
")",
":",
"def",
"printReturner",
"(",
"arg",
")",
":",
"myArgs",
"=",
"[",
"pre",
",",
"arg",
",",
"post",
"]",
"prin",
"(",
"*",
"myArgs",
",",
"*",
"*",
"{",
"'out'",
":",
"out",
"}",
")",
"return",
"arg",
"return",
"printReturner"
] | r"""Creates functions that print out their argument, (between optional
`pre` and `post` strings) and return it unmodified. This is usefull for
debugging e.g. parts of expressions, without having to modify the behavior
of the program.
Example:
>>> makePrintReturner(pre="The value is:", post="[returning]")(3)
The value is: 3 [returning]
3
>>> | [
"r",
"Creates",
"functions",
"that",
"print",
"out",
"their",
"argument",
"(",
"between",
"optional",
"pre",
"and",
"post",
"strings",
")",
"and",
"return",
"it",
"unmodified",
".",
"This",
"is",
"usefull",
"for",
"debugging",
"e",
".",
"g",
".",
"parts",
"of",
"expressions",
"without",
"having",
"to",
"modify",
"the",
"behavior",
"of",
"the",
"program",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1543-L1560 | train |
ewiger/mlab | src/mlab/awmstools.py | asVerboseContainer | def asVerboseContainer(cont, onGet=None, onSet=None, onDel=None):
"""Returns a 'verbose' version of container instance `cont`, that will
execute `onGet`, `onSet` and `onDel` (if not `None`) every time
__getitem__, __setitem__ and __delitem__ are called, passing `self`, `key`
(and `value` in the case of set). E.g:
>>> l = [1,2,3]
>>> l = asVerboseContainer(l,
... onGet=lambda s,k:k==2 and prin('Got two:', k),
... onSet=lambda s,k,v:k == v and prin('k == v:', k, v),
... onDel=lambda s,k:k == 1 and prin('Deleting one:', k))
>>> l
[1, 2, 3]
>>> l[1]
2
>>> l[2]
Got two: 2
3
>>> l[2] = 22
>>> l[2] = 2
k == v: 2 2
>>> del l[2]
>>> del l[1]
Deleting one: 1
"""
class VerboseContainer(type(cont)):
if onGet:
def __getitem__(self, key):
onGet(self, key)
return super(VerboseContainer, self).__getitem__(key)
if onSet:
def __setitem__(self, key, value):
onSet(self, key, value)
return super(VerboseContainer, self).__setitem__(key, value)
if onDel:
def __delitem__(self, key):
onDel(self, key)
return super(VerboseContainer, self).__delitem__(key)
return VerboseContainer(cont) | python | def asVerboseContainer(cont, onGet=None, onSet=None, onDel=None):
"""Returns a 'verbose' version of container instance `cont`, that will
execute `onGet`, `onSet` and `onDel` (if not `None`) every time
__getitem__, __setitem__ and __delitem__ are called, passing `self`, `key`
(and `value` in the case of set). E.g:
>>> l = [1,2,3]
>>> l = asVerboseContainer(l,
... onGet=lambda s,k:k==2 and prin('Got two:', k),
... onSet=lambda s,k,v:k == v and prin('k == v:', k, v),
... onDel=lambda s,k:k == 1 and prin('Deleting one:', k))
>>> l
[1, 2, 3]
>>> l[1]
2
>>> l[2]
Got two: 2
3
>>> l[2] = 22
>>> l[2] = 2
k == v: 2 2
>>> del l[2]
>>> del l[1]
Deleting one: 1
"""
class VerboseContainer(type(cont)):
if onGet:
def __getitem__(self, key):
onGet(self, key)
return super(VerboseContainer, self).__getitem__(key)
if onSet:
def __setitem__(self, key, value):
onSet(self, key, value)
return super(VerboseContainer, self).__setitem__(key, value)
if onDel:
def __delitem__(self, key):
onDel(self, key)
return super(VerboseContainer, self).__delitem__(key)
return VerboseContainer(cont) | [
"def",
"asVerboseContainer",
"(",
"cont",
",",
"onGet",
"=",
"None",
",",
"onSet",
"=",
"None",
",",
"onDel",
"=",
"None",
")",
":",
"class",
"VerboseContainer",
"(",
"type",
"(",
"cont",
")",
")",
":",
"if",
"onGet",
":",
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"onGet",
"(",
"self",
",",
"key",
")",
"return",
"super",
"(",
"VerboseContainer",
",",
"self",
")",
".",
"__getitem__",
"(",
"key",
")",
"if",
"onSet",
":",
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"onSet",
"(",
"self",
",",
"key",
",",
"value",
")",
"return",
"super",
"(",
"VerboseContainer",
",",
"self",
")",
".",
"__setitem__",
"(",
"key",
",",
"value",
")",
"if",
"onDel",
":",
"def",
"__delitem__",
"(",
"self",
",",
"key",
")",
":",
"onDel",
"(",
"self",
",",
"key",
")",
"return",
"super",
"(",
"VerboseContainer",
",",
"self",
")",
".",
"__delitem__",
"(",
"key",
")",
"return",
"VerboseContainer",
"(",
"cont",
")"
] | Returns a 'verbose' version of container instance `cont`, that will
execute `onGet`, `onSet` and `onDel` (if not `None`) every time
__getitem__, __setitem__ and __delitem__ are called, passing `self`, `key`
(and `value` in the case of set). E.g:
>>> l = [1,2,3]
>>> l = asVerboseContainer(l,
... onGet=lambda s,k:k==2 and prin('Got two:', k),
... onSet=lambda s,k,v:k == v and prin('k == v:', k, v),
... onDel=lambda s,k:k == 1 and prin('Deleting one:', k))
>>> l
[1, 2, 3]
>>> l[1]
2
>>> l[2]
Got two: 2
3
>>> l[2] = 22
>>> l[2] = 2
k == v: 2 2
>>> del l[2]
>>> del l[1]
Deleting one: 1 | [
"Returns",
"a",
"verbose",
"version",
"of",
"container",
"instance",
"cont",
"that",
"will",
"execute",
"onGet",
"onSet",
"and",
"onDel",
"(",
"if",
"not",
"None",
")",
"every",
"time",
"__getitem__",
"__setitem__",
"and",
"__delitem__",
"are",
"called",
"passing",
"self",
"key",
"(",
"and",
"value",
"in",
"the",
"case",
"of",
"set",
")",
".",
"E",
".",
"g",
":"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1599-L1638 | train |
ewiger/mlab | src/mlab/awmstools.py | mkRepr | def mkRepr(instance, *argls, **kwargs):
r"""Convinience function to implement ``__repr__``. `kwargs` values are
``repr`` ed. Special behavior for ``instance=None``: just the
arguments are formatted.
Example:
>>> class Thing:
... def __init__(self, color, shape, taste=None):
... self.color, self.shape, self.taste = color, shape, taste
... def __repr__(self):
... return mkRepr(self, self.color, self.shape, taste=self.taste)
...
>>> maggot = Thing('white', 'cylindrical', 'chicken')
>>> maggot
Thing('white', 'cylindrical', taste='chicken')
>>> Thing('Color # 132942430-214809804-412430988081-241234', 'unkown', taste=maggot)
Thing('Color # 132942430-214809804-412430988081-241234',
'unkown',
taste=Thing('white', 'cylindrical', taste='chicken'))
"""
width=79
maxIndent=15
minIndent=2
args = (map(repr, argls) + ["%s=%r" % (k, v)
for (k,v) in sorted(kwargs.items())]) or [""]
if instance is not None:
start = "%s(" % instance.__class__.__name__
args[-1] += ")"
else:
start = ""
if len(start) <= maxIndent and len(start) + len(args[0]) <= width and \
max(map(len,args)) <= width: # XXX mag of last condition bit arbitrary
indent = len(start)
args[0] = start + args[0]
if sum(map(len, args)) + 2*(len(args) - 1) <= width:
return ", ".join(args)
else:
indent = minIndent
args[0] = start + "\n" + " " * indent + args[0]
return (",\n" + " " * indent).join(args) | python | def mkRepr(instance, *argls, **kwargs):
r"""Convinience function to implement ``__repr__``. `kwargs` values are
``repr`` ed. Special behavior for ``instance=None``: just the
arguments are formatted.
Example:
>>> class Thing:
... def __init__(self, color, shape, taste=None):
... self.color, self.shape, self.taste = color, shape, taste
... def __repr__(self):
... return mkRepr(self, self.color, self.shape, taste=self.taste)
...
>>> maggot = Thing('white', 'cylindrical', 'chicken')
>>> maggot
Thing('white', 'cylindrical', taste='chicken')
>>> Thing('Color # 132942430-214809804-412430988081-241234', 'unkown', taste=maggot)
Thing('Color # 132942430-214809804-412430988081-241234',
'unkown',
taste=Thing('white', 'cylindrical', taste='chicken'))
"""
width=79
maxIndent=15
minIndent=2
args = (map(repr, argls) + ["%s=%r" % (k, v)
for (k,v) in sorted(kwargs.items())]) or [""]
if instance is not None:
start = "%s(" % instance.__class__.__name__
args[-1] += ")"
else:
start = ""
if len(start) <= maxIndent and len(start) + len(args[0]) <= width and \
max(map(len,args)) <= width: # XXX mag of last condition bit arbitrary
indent = len(start)
args[0] = start + args[0]
if sum(map(len, args)) + 2*(len(args) - 1) <= width:
return ", ".join(args)
else:
indent = minIndent
args[0] = start + "\n" + " " * indent + args[0]
return (",\n" + " " * indent).join(args) | [
"def",
"mkRepr",
"(",
"instance",
",",
"*",
"argls",
",",
"*",
"*",
"kwargs",
")",
":",
"width",
"=",
"79",
"maxIndent",
"=",
"15",
"minIndent",
"=",
"2",
"args",
"=",
"(",
"map",
"(",
"repr",
",",
"argls",
")",
"+",
"[",
"\"%s=%r\"",
"%",
"(",
"k",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"sorted",
"(",
"kwargs",
".",
"items",
"(",
")",
")",
"]",
")",
"or",
"[",
"\"\"",
"]",
"if",
"instance",
"is",
"not",
"None",
":",
"start",
"=",
"\"%s(\"",
"%",
"instance",
".",
"__class__",
".",
"__name__",
"args",
"[",
"-",
"1",
"]",
"+=",
"\")\"",
"else",
":",
"start",
"=",
"\"\"",
"if",
"len",
"(",
"start",
")",
"<=",
"maxIndent",
"and",
"len",
"(",
"start",
")",
"+",
"len",
"(",
"args",
"[",
"0",
"]",
")",
"<=",
"width",
"and",
"max",
"(",
"map",
"(",
"len",
",",
"args",
")",
")",
"<=",
"width",
":",
"# XXX mag of last condition bit arbitrary",
"indent",
"=",
"len",
"(",
"start",
")",
"args",
"[",
"0",
"]",
"=",
"start",
"+",
"args",
"[",
"0",
"]",
"if",
"sum",
"(",
"map",
"(",
"len",
",",
"args",
")",
")",
"+",
"2",
"*",
"(",
"len",
"(",
"args",
")",
"-",
"1",
")",
"<=",
"width",
":",
"return",
"\", \"",
".",
"join",
"(",
"args",
")",
"else",
":",
"indent",
"=",
"minIndent",
"args",
"[",
"0",
"]",
"=",
"start",
"+",
"\"\\n\"",
"+",
"\" \"",
"*",
"indent",
"+",
"args",
"[",
"0",
"]",
"return",
"(",
"\",\\n\"",
"+",
"\" \"",
"*",
"indent",
")",
".",
"join",
"(",
"args",
")"
] | r"""Convinience function to implement ``__repr__``. `kwargs` values are
``repr`` ed. Special behavior for ``instance=None``: just the
arguments are formatted.
Example:
>>> class Thing:
... def __init__(self, color, shape, taste=None):
... self.color, self.shape, self.taste = color, shape, taste
... def __repr__(self):
... return mkRepr(self, self.color, self.shape, taste=self.taste)
...
>>> maggot = Thing('white', 'cylindrical', 'chicken')
>>> maggot
Thing('white', 'cylindrical', taste='chicken')
>>> Thing('Color # 132942430-214809804-412430988081-241234', 'unkown', taste=maggot)
Thing('Color # 132942430-214809804-412430988081-241234',
'unkown',
taste=Thing('white', 'cylindrical', taste='chicken')) | [
"r",
"Convinience",
"function",
"to",
"implement",
"__repr__",
".",
"kwargs",
"values",
"are",
"repr",
"ed",
".",
"Special",
"behavior",
"for",
"instance",
"=",
"None",
":",
"just",
"the",
"arguments",
"are",
"formatted",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1724-L1764 | train |
ewiger/mlab | src/mlab/awmstools.py | d2attrs | def d2attrs(*args, **kwargs):
"""Utility function to remove ``**kwargs`` parsing boiler-plate in
``__init__``:
>>> kwargs = dict(name='Bill', age=51, income=1e7)
>>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self
ezstruct(income=10000000.0, name='Bill')
>>> self = ezstruct(); d2attrs(kwargs, self, 'income', age=0, bloodType='A'); self
ezstruct(age=51, bloodType='A', income=10000000.0)
To set all keys from ``kwargs`` use:
>>> self = ezstruct(); d2attrs(kwargs, self, 'all!'); self
ezstruct(age=51, income=10000000.0, name='Bill')
"""
(d, self), args = args[:2], args[2:]
if args[0] == 'all!':
assert len(args) == 1
for k in d: setattr(self, k, d[k])
else:
if len(args) != len(set(args)) or set(kwargs) & set(args):
raise ValueError('Duplicate keys: %s' %
list(notUnique(args)) + list(set(kwargs) & set(args)))
for k in args:
if k in kwargs: raise ValueError('%s specified twice' % k)
setattr(self, k, d[k])
for dk in kwargs:
setattr(self, dk, d.get(dk, kwargs[dk])) | python | def d2attrs(*args, **kwargs):
"""Utility function to remove ``**kwargs`` parsing boiler-plate in
``__init__``:
>>> kwargs = dict(name='Bill', age=51, income=1e7)
>>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self
ezstruct(income=10000000.0, name='Bill')
>>> self = ezstruct(); d2attrs(kwargs, self, 'income', age=0, bloodType='A'); self
ezstruct(age=51, bloodType='A', income=10000000.0)
To set all keys from ``kwargs`` use:
>>> self = ezstruct(); d2attrs(kwargs, self, 'all!'); self
ezstruct(age=51, income=10000000.0, name='Bill')
"""
(d, self), args = args[:2], args[2:]
if args[0] == 'all!':
assert len(args) == 1
for k in d: setattr(self, k, d[k])
else:
if len(args) != len(set(args)) or set(kwargs) & set(args):
raise ValueError('Duplicate keys: %s' %
list(notUnique(args)) + list(set(kwargs) & set(args)))
for k in args:
if k in kwargs: raise ValueError('%s specified twice' % k)
setattr(self, k, d[k])
for dk in kwargs:
setattr(self, dk, d.get(dk, kwargs[dk])) | [
"def",
"d2attrs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"(",
"d",
",",
"self",
")",
",",
"args",
"=",
"args",
"[",
":",
"2",
"]",
",",
"args",
"[",
"2",
":",
"]",
"if",
"args",
"[",
"0",
"]",
"==",
"'all!'",
":",
"assert",
"len",
"(",
"args",
")",
"==",
"1",
"for",
"k",
"in",
"d",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"d",
"[",
"k",
"]",
")",
"else",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"len",
"(",
"set",
"(",
"args",
")",
")",
"or",
"set",
"(",
"kwargs",
")",
"&",
"set",
"(",
"args",
")",
":",
"raise",
"ValueError",
"(",
"'Duplicate keys: %s'",
"%",
"list",
"(",
"notUnique",
"(",
"args",
")",
")",
"+",
"list",
"(",
"set",
"(",
"kwargs",
")",
"&",
"set",
"(",
"args",
")",
")",
")",
"for",
"k",
"in",
"args",
":",
"if",
"k",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'%s specified twice'",
"%",
"k",
")",
"setattr",
"(",
"self",
",",
"k",
",",
"d",
"[",
"k",
"]",
")",
"for",
"dk",
"in",
"kwargs",
":",
"setattr",
"(",
"self",
",",
"dk",
",",
"d",
".",
"get",
"(",
"dk",
",",
"kwargs",
"[",
"dk",
"]",
")",
")"
] | Utility function to remove ``**kwargs`` parsing boiler-plate in
``__init__``:
>>> kwargs = dict(name='Bill', age=51, income=1e7)
>>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self
ezstruct(income=10000000.0, name='Bill')
>>> self = ezstruct(); d2attrs(kwargs, self, 'income', age=0, bloodType='A'); self
ezstruct(age=51, bloodType='A', income=10000000.0)
To set all keys from ``kwargs`` use:
>>> self = ezstruct(); d2attrs(kwargs, self, 'all!'); self
ezstruct(age=51, income=10000000.0, name='Bill') | [
"Utility",
"function",
"to",
"remove",
"**",
"kwargs",
"parsing",
"boiler",
"-",
"plate",
"in",
"__init__",
":"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1787-L1814 | train |
ewiger/mlab | src/mlab/awmstools.py | pairwise | def pairwise(fun, v):
"""
>>> pairwise(operator.sub, [4,3,2,1,-10])
[1, 1, 1, 11]
>>> import numpy
>>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10]))
array([ 1, 1, 1, 11])
"""
if not hasattr(v, 'shape'):
return list(ipairwise(fun,v))
else:
return fun(v[:-1],v[1:]) | python | def pairwise(fun, v):
"""
>>> pairwise(operator.sub, [4,3,2,1,-10])
[1, 1, 1, 11]
>>> import numpy
>>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10]))
array([ 1, 1, 1, 11])
"""
if not hasattr(v, 'shape'):
return list(ipairwise(fun,v))
else:
return fun(v[:-1],v[1:]) | [
"def",
"pairwise",
"(",
"fun",
",",
"v",
")",
":",
"if",
"not",
"hasattr",
"(",
"v",
",",
"'shape'",
")",
":",
"return",
"list",
"(",
"ipairwise",
"(",
"fun",
",",
"v",
")",
")",
"else",
":",
"return",
"fun",
"(",
"v",
"[",
":",
"-",
"1",
"]",
",",
"v",
"[",
"1",
":",
"]",
")"
] | >>> pairwise(operator.sub, [4,3,2,1,-10])
[1, 1, 1, 11]
>>> import numpy
>>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10]))
array([ 1, 1, 1, 11]) | [
">>>",
"pairwise",
"(",
"operator",
".",
"sub",
"[",
"4",
"3",
"2",
"1",
"-",
"10",
"]",
")",
"[",
"1",
"1",
"1",
"11",
"]",
">>>",
"import",
"numpy",
">>>",
"pairwise",
"(",
"numpy",
".",
"subtract",
"numpy",
".",
"array",
"(",
"[",
"4",
"3",
"2",
"1",
"-",
"10",
"]",
"))",
"array",
"(",
"[",
"1",
"1",
"1",
"11",
"]",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1819-L1830 | train |
ewiger/mlab | src/mlab/awmstools.py | argmax | def argmax(iterable, key=None, both=False):
"""
>>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5)
"""
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmax = reduce(max, izip(it, count()))
if both:
return argmax, score
return argmax | python | def argmax(iterable, key=None, both=False):
"""
>>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5)
"""
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmax = reduce(max, izip(it, count()))
if both:
return argmax, score
return argmax | [
"def",
"argmax",
"(",
"iterable",
",",
"key",
"=",
"None",
",",
"both",
"=",
"False",
")",
":",
"if",
"key",
"is",
"not",
"None",
":",
"it",
"=",
"imap",
"(",
"key",
",",
"iterable",
")",
"else",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"score",
",",
"argmax",
"=",
"reduce",
"(",
"max",
",",
"izip",
"(",
"it",
",",
"count",
"(",
")",
")",
")",
"if",
"both",
":",
"return",
"argmax",
",",
"score",
"return",
"argmax"
] | >>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5) | [
">>>",
"argmax",
"(",
"[",
"4",
"2",
"-",
"5",
"]",
")",
"0",
">>>",
"argmax",
"(",
"[",
"4",
"2",
"-",
"5",
"]",
"key",
"=",
"abs",
")",
"2",
">>>",
"argmax",
"(",
"[",
"4",
"2",
"-",
"5",
"]",
"key",
"=",
"abs",
"both",
"=",
"True",
")",
"(",
"2",
"5",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1846-L1862 | train |
ewiger/mlab | src/mlab/awmstools.py | argmin | def argmin(iterable, key=None, both=False):
"""See `argmax`.
"""
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmin = reduce(min, izip(it, count()))
if both:
return argmin, score
return argmin | python | def argmin(iterable, key=None, both=False):
"""See `argmax`.
"""
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmin = reduce(min, izip(it, count()))
if both:
return argmin, score
return argmin | [
"def",
"argmin",
"(",
"iterable",
",",
"key",
"=",
"None",
",",
"both",
"=",
"False",
")",
":",
"if",
"key",
"is",
"not",
"None",
":",
"it",
"=",
"imap",
"(",
"key",
",",
"iterable",
")",
"else",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"score",
",",
"argmin",
"=",
"reduce",
"(",
"min",
",",
"izip",
"(",
"it",
",",
"count",
"(",
")",
")",
")",
"if",
"both",
":",
"return",
"argmin",
",",
"score",
"return",
"argmin"
] | See `argmax`. | [
"See",
"argmax",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1864-L1874 | train |
ewiger/mlab | src/mlab/awmstools.py | isInt | def isInt(num):
"""Returns true if `num` is (sort of) an integer.
>>> isInt(3) == isInt(3.0) == 1
True
>>> isInt(3.2)
False
>>> import numpy
>>> isInt(numpy.array(1))
True
>>> isInt(numpy.array([1]))
False
"""
try:
len(num) # FIXME fails for Numeric but Numeric is obsolete
except:
try:
return (num - math.floor(num) == 0) == True
except: return False
else: return False | python | def isInt(num):
"""Returns true if `num` is (sort of) an integer.
>>> isInt(3) == isInt(3.0) == 1
True
>>> isInt(3.2)
False
>>> import numpy
>>> isInt(numpy.array(1))
True
>>> isInt(numpy.array([1]))
False
"""
try:
len(num) # FIXME fails for Numeric but Numeric is obsolete
except:
try:
return (num - math.floor(num) == 0) == True
except: return False
else: return False | [
"def",
"isInt",
"(",
"num",
")",
":",
"try",
":",
"len",
"(",
"num",
")",
"# FIXME fails for Numeric but Numeric is obsolete",
"except",
":",
"try",
":",
"return",
"(",
"num",
"-",
"math",
".",
"floor",
"(",
"num",
")",
"==",
"0",
")",
"==",
"True",
"except",
":",
"return",
"False",
"else",
":",
"return",
"False"
] | Returns true if `num` is (sort of) an integer.
>>> isInt(3) == isInt(3.0) == 1
True
>>> isInt(3.2)
False
>>> import numpy
>>> isInt(numpy.array(1))
True
>>> isInt(numpy.array([1]))
False | [
"Returns",
"true",
"if",
"num",
"is",
"(",
"sort",
"of",
")",
"an",
"integer",
".",
">>>",
"isInt",
"(",
"3",
")",
"==",
"isInt",
"(",
"3",
".",
"0",
")",
"==",
"1",
"True",
">>>",
"isInt",
"(",
"3",
".",
"2",
")",
"False",
">>>",
"import",
"numpy",
">>>",
"isInt",
"(",
"numpy",
".",
"array",
"(",
"1",
"))",
"True",
">>>",
"isInt",
"(",
"numpy",
".",
"array",
"(",
"[",
"1",
"]",
"))",
"False"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1881-L1899 | train |
ewiger/mlab | src/mlab/awmstools.py | mapConcat | def mapConcat(func, *iterables):
"""Similar to `map` but the instead of collecting the return values of
`func` in a list, the items of each return value are instaed collected
(so `func` must return an iterable type).
Examples:
>>> mapConcat(lambda x:[x], [1,2,3])
[1, 2, 3]
>>> mapConcat(lambda x: [x,str(x)], [1,2,3])
[1, '1', 2, '2', 3, '3']
"""
return [e for l in imap(func, *iterables) for e in l] | python | def mapConcat(func, *iterables):
"""Similar to `map` but the instead of collecting the return values of
`func` in a list, the items of each return value are instaed collected
(so `func` must return an iterable type).
Examples:
>>> mapConcat(lambda x:[x], [1,2,3])
[1, 2, 3]
>>> mapConcat(lambda x: [x,str(x)], [1,2,3])
[1, '1', 2, '2', 3, '3']
"""
return [e for l in imap(func, *iterables) for e in l] | [
"def",
"mapConcat",
"(",
"func",
",",
"*",
"iterables",
")",
":",
"return",
"[",
"e",
"for",
"l",
"in",
"imap",
"(",
"func",
",",
"*",
"iterables",
")",
"for",
"e",
"in",
"l",
"]"
] | Similar to `map` but the instead of collecting the return values of
`func` in a list, the items of each return value are instaed collected
(so `func` must return an iterable type).
Examples:
>>> mapConcat(lambda x:[x], [1,2,3])
[1, 2, 3]
>>> mapConcat(lambda x: [x,str(x)], [1,2,3])
[1, '1', 2, '2', 3, '3'] | [
"Similar",
"to",
"map",
"but",
"the",
"instead",
"of",
"collecting",
"the",
"return",
"values",
"of",
"func",
"in",
"a",
"list",
"the",
"items",
"of",
"each",
"return",
"value",
"are",
"instaed",
"collected",
"(",
"so",
"func",
"must",
"return",
"an",
"iterable",
"type",
")",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1917-L1929 | train |
ewiger/mlab | src/mlab/awmstools.py | unfold | def unfold(seed, by, last = __unique):
"""
>>> list(unfold(1234, lambda x: divmod(x,10)))[::-1]
[1, 2, 3, 4]
>>> sum(imap(operator.mul,unfold(1234, lambda x:divmod(x,10)), iterate(lambda x:x*10)(1)))
1234
>>> g = unfold(1234, lambda x:divmod(x,10))
>>> reduce((lambda (total,pow),digit:(total+pow*digit, 10*pow)), g, (0,1))
(1234, 10000)
"""
while True:
seed, val = by(seed);
if last == seed: return
last = seed; yield val | python | def unfold(seed, by, last = __unique):
"""
>>> list(unfold(1234, lambda x: divmod(x,10)))[::-1]
[1, 2, 3, 4]
>>> sum(imap(operator.mul,unfold(1234, lambda x:divmod(x,10)), iterate(lambda x:x*10)(1)))
1234
>>> g = unfold(1234, lambda x:divmod(x,10))
>>> reduce((lambda (total,pow),digit:(total+pow*digit, 10*pow)), g, (0,1))
(1234, 10000)
"""
while True:
seed, val = by(seed);
if last == seed: return
last = seed; yield val | [
"def",
"unfold",
"(",
"seed",
",",
"by",
",",
"last",
"=",
"__unique",
")",
":",
"while",
"True",
":",
"seed",
",",
"val",
"=",
"by",
"(",
"seed",
")",
"if",
"last",
"==",
"seed",
":",
"return",
"last",
"=",
"seed",
"yield",
"val"
] | >>> list(unfold(1234, lambda x: divmod(x,10)))[::-1]
[1, 2, 3, 4]
>>> sum(imap(operator.mul,unfold(1234, lambda x:divmod(x,10)), iterate(lambda x:x*10)(1)))
1234
>>> g = unfold(1234, lambda x:divmod(x,10))
>>> reduce((lambda (total,pow),digit:(total+pow*digit, 10*pow)), g, (0,1))
(1234, 10000) | [
">>>",
"list",
"(",
"unfold",
"(",
"1234",
"lambda",
"x",
":",
"divmod",
"(",
"x",
"10",
")))",
"[",
"::",
"-",
"1",
"]",
"[",
"1",
"2",
"3",
"4",
"]",
">>>",
"sum",
"(",
"imap",
"(",
"operator",
".",
"mul",
"unfold",
"(",
"1234",
"lambda",
"x",
":",
"divmod",
"(",
"x",
"10",
"))",
"iterate",
"(",
"lambda",
"x",
":",
"x",
"*",
"10",
")",
"(",
"1",
")))",
"1234",
">>>",
"g",
"=",
"unfold",
"(",
"1234",
"lambda",
"x",
":",
"divmod",
"(",
"x",
"10",
"))",
">>>",
"reduce",
"((",
"lambda",
"(",
"total",
"pow",
")",
"digit",
":",
"(",
"total",
"+",
"pow",
"*",
"digit",
"10",
"*",
"pow",
"))",
"g",
"(",
"0",
"1",
"))",
"(",
"1234",
"10000",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1935-L1949 | train |
ewiger/mlab | src/mlab/awmstools.py | reduceR | def reduceR(f, sequence, initial=__unique):
"""*R*ight reduce.
>>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2./(3./4.)) == (1./2.)*(3./4.)
True
>>> reduceR(lambda x,y:x-y, iter([1,2,3]),4) == 1-(2-(3-4)) == (1-2)+(3-4)
True
"""
try: rev = reversed(sequence)
except TypeError: rev = reversed(list(sequence))
if initial is __unique: return reduce(lambda x,y:f(y,x), rev)
else: return reduce(lambda x,y:f(y,x), rev, initial) | python | def reduceR(f, sequence, initial=__unique):
"""*R*ight reduce.
>>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2./(3./4.)) == (1./2.)*(3./4.)
True
>>> reduceR(lambda x,y:x-y, iter([1,2,3]),4) == 1-(2-(3-4)) == (1-2)+(3-4)
True
"""
try: rev = reversed(sequence)
except TypeError: rev = reversed(list(sequence))
if initial is __unique: return reduce(lambda x,y:f(y,x), rev)
else: return reduce(lambda x,y:f(y,x), rev, initial) | [
"def",
"reduceR",
"(",
"f",
",",
"sequence",
",",
"initial",
"=",
"__unique",
")",
":",
"try",
":",
"rev",
"=",
"reversed",
"(",
"sequence",
")",
"except",
"TypeError",
":",
"rev",
"=",
"reversed",
"(",
"list",
"(",
"sequence",
")",
")",
"if",
"initial",
"is",
"__unique",
":",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"f",
"(",
"y",
",",
"x",
")",
",",
"rev",
")",
"else",
":",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"f",
"(",
"y",
",",
"x",
")",
",",
"rev",
",",
"initial",
")"
] | *R*ight reduce.
>>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2./(3./4.)) == (1./2.)*(3./4.)
True
>>> reduceR(lambda x,y:x-y, iter([1,2,3]),4) == 1-(2-(3-4)) == (1-2)+(3-4)
True | [
"*",
"R",
"*",
"ight",
"reduce",
".",
">>>",
"reduceR",
"(",
"lambda",
"x",
"y",
":",
"x",
"/",
"y",
"[",
"1",
".",
"2",
".",
"3",
".",
"4",
"]",
")",
"==",
"1",
".",
"/",
"(",
"2",
".",
"/",
"(",
"3",
".",
"/",
"4",
".",
"))",
"==",
"(",
"1",
".",
"/",
"2",
".",
")",
"*",
"(",
"3",
".",
"/",
"4",
".",
")",
"True",
">>>",
"reduceR",
"(",
"lambda",
"x",
"y",
":",
"x",
"-",
"y",
"iter",
"(",
"[",
"1",
"2",
"3",
"]",
")",
"4",
")",
"==",
"1",
"-",
"(",
"2",
"-",
"(",
"3",
"-",
"4",
"))",
"==",
"(",
"1",
"-",
"2",
")",
"+",
"(",
"3",
"-",
"4",
")",
"True"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1951-L1961 | train |
ewiger/mlab | src/mlab/awmstools.py | compose | def compose(*funcs):
"""Compose `funcs` to a single function.
>>> compose(operator.abs, operator.add)(-2,-3)
5
>>> compose()('nada')
'nada'
>>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2)
[1, 2]
"""
# slightly optimized for most common cases and hence verbose
if len(funcs) == 2: f0,f1=funcs; return lambda *a,**kw: f0(f1(*a,**kw))
elif len(funcs) == 3: f0,f1,f2=funcs; return lambda *a,**kw: f0(f1(f2(*a,**kw)))
elif len(funcs) == 0: return lambda x:x # XXX single kwarg
elif len(funcs) == 1: return funcs[0]
else:
def composed(*args,**kwargs):
y = funcs[-1](*args,**kwargs)
for f in funcs[:0:-1]: y = f(y)
return y
return composed | python | def compose(*funcs):
"""Compose `funcs` to a single function.
>>> compose(operator.abs, operator.add)(-2,-3)
5
>>> compose()('nada')
'nada'
>>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2)
[1, 2]
"""
# slightly optimized for most common cases and hence verbose
if len(funcs) == 2: f0,f1=funcs; return lambda *a,**kw: f0(f1(*a,**kw))
elif len(funcs) == 3: f0,f1,f2=funcs; return lambda *a,**kw: f0(f1(f2(*a,**kw)))
elif len(funcs) == 0: return lambda x:x # XXX single kwarg
elif len(funcs) == 1: return funcs[0]
else:
def composed(*args,**kwargs):
y = funcs[-1](*args,**kwargs)
for f in funcs[:0:-1]: y = f(y)
return y
return composed | [
"def",
"compose",
"(",
"*",
"funcs",
")",
":",
"# slightly optimized for most common cases and hence verbose",
"if",
"len",
"(",
"funcs",
")",
"==",
"2",
":",
"f0",
",",
"f1",
"=",
"funcs",
"return",
"lambda",
"*",
"a",
",",
"*",
"*",
"kw",
":",
"f0",
"(",
"f1",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
")",
"elif",
"len",
"(",
"funcs",
")",
"==",
"3",
":",
"f0",
",",
"f1",
",",
"f2",
"=",
"funcs",
"return",
"lambda",
"*",
"a",
",",
"*",
"*",
"kw",
":",
"f0",
"(",
"f1",
"(",
"f2",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
")",
")",
"elif",
"len",
"(",
"funcs",
")",
"==",
"0",
":",
"return",
"lambda",
"x",
":",
"x",
"# XXX single kwarg",
"elif",
"len",
"(",
"funcs",
")",
"==",
"1",
":",
"return",
"funcs",
"[",
"0",
"]",
"else",
":",
"def",
"composed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"y",
"=",
"funcs",
"[",
"-",
"1",
"]",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"f",
"in",
"funcs",
"[",
":",
"0",
":",
"-",
"1",
"]",
":",
"y",
"=",
"f",
"(",
"y",
")",
"return",
"y",
"return",
"composed"
] | Compose `funcs` to a single function.
>>> compose(operator.abs, operator.add)(-2,-3)
5
>>> compose()('nada')
'nada'
>>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2)
[1, 2] | [
"Compose",
"funcs",
"to",
"a",
"single",
"function",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1964-L1984 | train |
ewiger/mlab | src/mlab/awmstools.py | romanNumeral | def romanNumeral(n):
"""
>>> romanNumeral(13)
'XIII'
>>> romanNumeral(2944)
'MMCMXLIV'
"""
if 0 > n > 4000: raise ValueError('``n`` must lie between 1 and 3999: %d' % n)
roman = 'I IV V IX X XL L XC C CD D CM M'.split()
arabic = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
res = []
while n>0:
pos = bisect.bisect_right(arabic, n)-1
fit = n//arabic[pos]
res.append(roman[pos]*fit); n -= fit * arabic[pos]
return "".join(res) | python | def romanNumeral(n):
"""
>>> romanNumeral(13)
'XIII'
>>> romanNumeral(2944)
'MMCMXLIV'
"""
if 0 > n > 4000: raise ValueError('``n`` must lie between 1 and 3999: %d' % n)
roman = 'I IV V IX X XL L XC C CD D CM M'.split()
arabic = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
res = []
while n>0:
pos = bisect.bisect_right(arabic, n)-1
fit = n//arabic[pos]
res.append(roman[pos]*fit); n -= fit * arabic[pos]
return "".join(res) | [
"def",
"romanNumeral",
"(",
"n",
")",
":",
"if",
"0",
">",
"n",
">",
"4000",
":",
"raise",
"ValueError",
"(",
"'``n`` must lie between 1 and 3999: %d'",
"%",
"n",
")",
"roman",
"=",
"'I IV V IX X XL L XC C CD D CM M'",
".",
"split",
"(",
")",
"arabic",
"=",
"[",
"1",
",",
"4",
",",
"5",
",",
"9",
",",
"10",
",",
"40",
",",
"50",
",",
"90",
",",
"100",
",",
"400",
",",
"500",
",",
"900",
",",
"1000",
"]",
"res",
"=",
"[",
"]",
"while",
"n",
">",
"0",
":",
"pos",
"=",
"bisect",
".",
"bisect_right",
"(",
"arabic",
",",
"n",
")",
"-",
"1",
"fit",
"=",
"n",
"//",
"arabic",
"[",
"pos",
"]",
"res",
".",
"append",
"(",
"roman",
"[",
"pos",
"]",
"*",
"fit",
")",
"n",
"-=",
"fit",
"*",
"arabic",
"[",
"pos",
"]",
"return",
"\"\"",
".",
"join",
"(",
"res",
")"
] | >>> romanNumeral(13)
'XIII'
>>> romanNumeral(2944)
'MMCMXLIV' | [
">>>",
"romanNumeral",
"(",
"13",
")",
"XIII",
">>>",
"romanNumeral",
"(",
"2944",
")",
"MMCMXLIV"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1987-L2002 | train |
ewiger/mlab | src/mlab/awmstools.py | first | def first(n, it, constructor=list):
"""
>>> first(3,iter([1,2,3,4]))
[1, 2, 3]
>>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS
<itertools.islice object at ...>
>>> first(3,iter([1,2,3,4]), tuple)
(1, 2, 3)
"""
return constructor(itertools.islice(it,n)) | python | def first(n, it, constructor=list):
"""
>>> first(3,iter([1,2,3,4]))
[1, 2, 3]
>>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS
<itertools.islice object at ...>
>>> first(3,iter([1,2,3,4]), tuple)
(1, 2, 3)
"""
return constructor(itertools.islice(it,n)) | [
"def",
"first",
"(",
"n",
",",
"it",
",",
"constructor",
"=",
"list",
")",
":",
"return",
"constructor",
"(",
"itertools",
".",
"islice",
"(",
"it",
",",
"n",
")",
")"
] | >>> first(3,iter([1,2,3,4]))
[1, 2, 3]
>>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS
<itertools.islice object at ...>
>>> first(3,iter([1,2,3,4]), tuple)
(1, 2, 3) | [
">>>",
"first",
"(",
"3",
"iter",
"(",
"[",
"1",
"2",
"3",
"4",
"]",
"))",
"[",
"1",
"2",
"3",
"]",
">>>",
"first",
"(",
"3",
"iter",
"(",
"[",
"1",
"2",
"3",
"4",
"]",
")",
"iter",
")",
"#doctest",
":",
"+",
"ELLIPSIS",
"<itertools",
".",
"islice",
"object",
"at",
"...",
">",
">>>",
"first",
"(",
"3",
"iter",
"(",
"[",
"1",
"2",
"3",
"4",
"]",
")",
"tuple",
")",
"(",
"1",
"2",
"3",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L2011-L2020 | train |
ewiger/mlab | src/mlab/awmstools.py | drop | def drop(n, it, constructor=list):
"""
>>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
"""
return constructor(itertools.islice(it,n,None)) | python | def drop(n, it, constructor=list):
"""
>>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
"""
return constructor(itertools.islice(it,n,None)) | [
"def",
"drop",
"(",
"n",
",",
"it",
",",
"constructor",
"=",
"list",
")",
":",
"return",
"constructor",
"(",
"itertools",
".",
"islice",
"(",
"it",
",",
"n",
",",
"None",
")",
")"
] | >>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] | [
">>>",
"first",
"(",
"10",
"drop",
"(",
"10",
"xrange",
"(",
"sys",
".",
"maxint",
")",
"iter",
"))",
"[",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"]"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L2021-L2026 | train |
ewiger/mlab | src/mlab/awmstools.py | DryRun.run | def run(self, func, *args, **kwargs):
"""Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``."""
if self.dry:
return self.dryRun(func, *args, **kwargs)
else:
return self.wetRun(func, *args, **kwargs) | python | def run(self, func, *args, **kwargs):
"""Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``."""
if self.dry:
return self.dryRun(func, *args, **kwargs)
else:
return self.wetRun(func, *args, **kwargs) | [
"def",
"run",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"dry",
":",
"return",
"self",
".",
"dryRun",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"self",
".",
"wetRun",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``. | [
"Same",
"as",
"self",
".",
"dryRun",
"if",
"self",
".",
"dry",
"else",
"same",
"as",
"self",
".",
"wetRun",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1516-L1521 | train |
ewiger/mlab | src/mlab/awmstools.py | DryRun.dryRun | def dryRun(self, func, *args, **kwargs):
"""Instead of running function with `*args` and `**kwargs`, just print
out the function call."""
print >> self.out, \
self.formatterDict.get(func, self.defaultFormatter)(func, *args, **kwargs) | python | def dryRun(self, func, *args, **kwargs):
"""Instead of running function with `*args` and `**kwargs`, just print
out the function call."""
print >> self.out, \
self.formatterDict.get(func, self.defaultFormatter)(func, *args, **kwargs) | [
"def",
"dryRun",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
">>",
"self",
".",
"out",
",",
"self",
".",
"formatterDict",
".",
"get",
"(",
"func",
",",
"self",
".",
"defaultFormatter",
")",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Instead of running function with `*args` and `**kwargs`, just print
out the function call. | [
"Instead",
"of",
"running",
"function",
"with",
"*",
"args",
"and",
"**",
"kwargs",
"just",
"print",
"out",
"the",
"function",
"call",
"."
] | 72a98adf6499f548848ad44c604f74d68f07fe4f | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1528-L1533 | train |
rlisagor/pynetlinux | pynetlinux/brctl.py | iterbridges | def iterbridges():
''' Iterate over all the bridges in the system. '''
net_files = os.listdir(SYSFS_NET_PATH)
for d in net_files:
path = os.path.join(SYSFS_NET_PATH, d)
if not os.path.isdir(path):
continue
if os.path.exists(os.path.join(path, b"bridge")):
yield Bridge(d) | python | def iterbridges():
''' Iterate over all the bridges in the system. '''
net_files = os.listdir(SYSFS_NET_PATH)
for d in net_files:
path = os.path.join(SYSFS_NET_PATH, d)
if not os.path.isdir(path):
continue
if os.path.exists(os.path.join(path, b"bridge")):
yield Bridge(d) | [
"def",
"iterbridges",
"(",
")",
":",
"net_files",
"=",
"os",
".",
"listdir",
"(",
"SYSFS_NET_PATH",
")",
"for",
"d",
"in",
"net_files",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SYSFS_NET_PATH",
",",
"d",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"continue",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"b\"bridge\"",
")",
")",
":",
"yield",
"Bridge",
"(",
"d",
")"
] | Iterate over all the bridges in the system. | [
"Iterate",
"over",
"all",
"the",
"bridges",
"in",
"the",
"system",
"."
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L97-L105 | train |
rlisagor/pynetlinux | pynetlinux/brctl.py | addbr | def addbr(name):
''' Create new bridge with the given name '''
fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name)
return Bridge(name) | python | def addbr(name):
''' Create new bridge with the given name '''
fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name)
return Bridge(name) | [
"def",
"addbr",
"(",
"name",
")",
":",
"fcntl",
".",
"ioctl",
"(",
"ifconfig",
".",
"sockfd",
",",
"SIOCBRADDBR",
",",
"name",
")",
"return",
"Bridge",
"(",
"name",
")"
] | Create new bridge with the given name | [
"Create",
"new",
"bridge",
"with",
"the",
"given",
"name"
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L113-L116 | train |
rlisagor/pynetlinux | pynetlinux/brctl.py | Bridge.iterifs | def iterifs(self):
''' Iterate over all the interfaces in this bridge. '''
if_path = os.path.join(SYSFS_NET_PATH, self.name, b"brif")
net_files = os.listdir(if_path)
for iface in net_files:
yield iface | python | def iterifs(self):
''' Iterate over all the interfaces in this bridge. '''
if_path = os.path.join(SYSFS_NET_PATH, self.name, b"brif")
net_files = os.listdir(if_path)
for iface in net_files:
yield iface | [
"def",
"iterifs",
"(",
"self",
")",
":",
"if_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SYSFS_NET_PATH",
",",
"self",
".",
"name",
",",
"b\"brif\"",
")",
"net_files",
"=",
"os",
".",
"listdir",
"(",
"if_path",
")",
"for",
"iface",
"in",
"net_files",
":",
"yield",
"iface"
] | Iterate over all the interfaces in this bridge. | [
"Iterate",
"over",
"all",
"the",
"interfaces",
"in",
"this",
"bridge",
"."
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L32-L37 | train |
rlisagor/pynetlinux | pynetlinux/brctl.py | Bridge.addif | def addif(self, iface):
''' Add the interface with the given name to this bridge. Equivalent to
brctl addif [bridge] [interface]. '''
if type(iface) == ifconfig.Interface:
devindex = iface.index
else:
devindex = ifconfig.Interface(iface).index
ifreq = struct.pack('16si', self.name, devindex)
fcntl.ioctl(ifconfig.sockfd, SIOCBRADDIF, ifreq)
return self | python | def addif(self, iface):
''' Add the interface with the given name to this bridge. Equivalent to
brctl addif [bridge] [interface]. '''
if type(iface) == ifconfig.Interface:
devindex = iface.index
else:
devindex = ifconfig.Interface(iface).index
ifreq = struct.pack('16si', self.name, devindex)
fcntl.ioctl(ifconfig.sockfd, SIOCBRADDIF, ifreq)
return self | [
"def",
"addif",
"(",
"self",
",",
"iface",
")",
":",
"if",
"type",
"(",
"iface",
")",
"==",
"ifconfig",
".",
"Interface",
":",
"devindex",
"=",
"iface",
".",
"index",
"else",
":",
"devindex",
"=",
"ifconfig",
".",
"Interface",
"(",
"iface",
")",
".",
"index",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16si'",
",",
"self",
".",
"name",
",",
"devindex",
")",
"fcntl",
".",
"ioctl",
"(",
"ifconfig",
".",
"sockfd",
",",
"SIOCBRADDIF",
",",
"ifreq",
")",
"return",
"self"
] | Add the interface with the given name to this bridge. Equivalent to
brctl addif [bridge] [interface]. | [
"Add",
"the",
"interface",
"with",
"the",
"given",
"name",
"to",
"this",
"bridge",
".",
"Equivalent",
"to",
"brctl",
"addif",
"[",
"bridge",
"]",
"[",
"interface",
"]",
"."
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L45-L54 | train |
rlisagor/pynetlinux | pynetlinux/brctl.py | Bridge.delif | def delif(self, iface):
''' Remove the interface with the given name from this bridge.
Equivalent to brctl delif [bridge] [interface]'''
if type(iface) == ifconfig.Interface:
devindex = iface.index
else:
devindex = ifconfig.Interface(iface).index
ifreq = struct.pack('16si', self.name, devindex)
fcntl.ioctl(ifconfig.sockfd, SIOCBRDELIF, ifreq)
return self | python | def delif(self, iface):
''' Remove the interface with the given name from this bridge.
Equivalent to brctl delif [bridge] [interface]'''
if type(iface) == ifconfig.Interface:
devindex = iface.index
else:
devindex = ifconfig.Interface(iface).index
ifreq = struct.pack('16si', self.name, devindex)
fcntl.ioctl(ifconfig.sockfd, SIOCBRDELIF, ifreq)
return self | [
"def",
"delif",
"(",
"self",
",",
"iface",
")",
":",
"if",
"type",
"(",
"iface",
")",
"==",
"ifconfig",
".",
"Interface",
":",
"devindex",
"=",
"iface",
".",
"index",
"else",
":",
"devindex",
"=",
"ifconfig",
".",
"Interface",
"(",
"iface",
")",
".",
"index",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16si'",
",",
"self",
".",
"name",
",",
"devindex",
")",
"fcntl",
".",
"ioctl",
"(",
"ifconfig",
".",
"sockfd",
",",
"SIOCBRDELIF",
",",
"ifreq",
")",
"return",
"self"
] | Remove the interface with the given name from this bridge.
Equivalent to brctl delif [bridge] [interface] | [
"Remove",
"the",
"interface",
"with",
"the",
"given",
"name",
"from",
"this",
"bridge",
".",
"Equivalent",
"to",
"brctl",
"delif",
"[",
"bridge",
"]",
"[",
"interface",
"]"
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L57-L66 | train |
rlisagor/pynetlinux | pynetlinux/brctl.py | Bridge.delete | def delete(self):
''' Brings down the bridge interface, and removes it. Equivalent to
ifconfig [bridge] down && brctl delbr [bridge]. '''
self.down()
fcntl.ioctl(ifconfig.sockfd, SIOCBRDELBR, self.name)
return self | python | def delete(self):
''' Brings down the bridge interface, and removes it. Equivalent to
ifconfig [bridge] down && brctl delbr [bridge]. '''
self.down()
fcntl.ioctl(ifconfig.sockfd, SIOCBRDELBR, self.name)
return self | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"down",
"(",
")",
"fcntl",
".",
"ioctl",
"(",
"ifconfig",
".",
"sockfd",
",",
"SIOCBRDELBR",
",",
"self",
".",
"name",
")",
"return",
"self"
] | Brings down the bridge interface, and removes it. Equivalent to
ifconfig [bridge] down && brctl delbr [bridge]. | [
"Brings",
"down",
"the",
"bridge",
"interface",
"and",
"removes",
"it",
".",
"Equivalent",
"to",
"ifconfig",
"[",
"bridge",
"]",
"down",
"&&",
"brctl",
"delbr",
"[",
"bridge",
"]",
"."
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L76-L81 | train |
jluttine/d3py | d3py/core.py | _get_random_id | def _get_random_id():
""" Get a random (i.e., unique) string identifier"""
symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(symbols) for _ in range(15)) | python | def _get_random_id():
""" Get a random (i.e., unique) string identifier"""
symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(symbols) for _ in range(15)) | [
"def",
"_get_random_id",
"(",
")",
":",
"symbols",
"=",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"ascii_lowercase",
"+",
"string",
".",
"digits",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"symbols",
")",
"for",
"_",
"in",
"range",
"(",
"15",
")",
")"
] | Get a random (i.e., unique) string identifier | [
"Get",
"a",
"random",
"(",
"i",
".",
"e",
".",
"unique",
")",
"string",
"identifier"
] | 2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0 | https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L16-L19 | train |
jluttine/d3py | d3py/core.py | get_lib_filename | def get_lib_filename(category, name):
""" Get a filename of a built-in library file. """
base_dir = os.path.dirname(os.path.abspath(__file__))
if category == 'js':
filename = os.path.join('js', '{0}.js'.format(name))
elif category == 'css':
filename = os.path.join('css', '{0}.css'.format(name))
elif category == 'html':
filename = os.path.join('html', '{0}.html'.format(name))
else:
raise ValueError("Unknown category")
return os.path.join(base_dir, 'lib', filename) | python | def get_lib_filename(category, name):
""" Get a filename of a built-in library file. """
base_dir = os.path.dirname(os.path.abspath(__file__))
if category == 'js':
filename = os.path.join('js', '{0}.js'.format(name))
elif category == 'css':
filename = os.path.join('css', '{0}.css'.format(name))
elif category == 'html':
filename = os.path.join('html', '{0}.html'.format(name))
else:
raise ValueError("Unknown category")
return os.path.join(base_dir, 'lib', filename) | [
"def",
"get_lib_filename",
"(",
"category",
",",
"name",
")",
":",
"base_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"if",
"category",
"==",
"'js'",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'js'",
",",
"'{0}.js'",
".",
"format",
"(",
"name",
")",
")",
"elif",
"category",
"==",
"'css'",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'css'",
",",
"'{0}.css'",
".",
"format",
"(",
"name",
")",
")",
"elif",
"category",
"==",
"'html'",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'html'",
",",
"'{0}.html'",
".",
"format",
"(",
"name",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown category\"",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"'lib'",
",",
"filename",
")"
] | Get a filename of a built-in library file. | [
"Get",
"a",
"filename",
"of",
"a",
"built",
"-",
"in",
"library",
"file",
"."
] | 2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0 | https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L29-L40 | train |
jluttine/d3py | d3py/core.py | output_notebook | def output_notebook(
d3js_url="//d3js.org/d3.v3.min",
requirejs_url="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js",
html_template=None
):
""" Import required Javascript libraries to Jupyter Notebook. """
if html_template is None:
html_template = read_lib('html', 'setup')
setup_html = populate_template(
html_template,
d3js=d3js_url,
requirejs=requirejs_url
)
display_html(setup_html)
return | python | def output_notebook(
d3js_url="//d3js.org/d3.v3.min",
requirejs_url="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js",
html_template=None
):
""" Import required Javascript libraries to Jupyter Notebook. """
if html_template is None:
html_template = read_lib('html', 'setup')
setup_html = populate_template(
html_template,
d3js=d3js_url,
requirejs=requirejs_url
)
display_html(setup_html)
return | [
"def",
"output_notebook",
"(",
"d3js_url",
"=",
"\"//d3js.org/d3.v3.min\"",
",",
"requirejs_url",
"=",
"\"//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js\"",
",",
"html_template",
"=",
"None",
")",
":",
"if",
"html_template",
"is",
"None",
":",
"html_template",
"=",
"read_lib",
"(",
"'html'",
",",
"'setup'",
")",
"setup_html",
"=",
"populate_template",
"(",
"html_template",
",",
"d3js",
"=",
"d3js_url",
",",
"requirejs",
"=",
"requirejs_url",
")",
"display_html",
"(",
"setup_html",
")",
"return"
] | Import required Javascript libraries to Jupyter Notebook. | [
"Import",
"required",
"Javascript",
"libraries",
"to",
"Jupyter",
"Notebook",
"."
] | 2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0 | https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L59-L76 | train |
jluttine/d3py | d3py/core.py | create_graph_html | def create_graph_html(js_template, css_template, html_template=None):
""" Create HTML code block given the graph Javascript and CSS. """
if html_template is None:
html_template = read_lib('html', 'graph')
# Create div ID for the graph and give it to the JS and CSS templates so
# they can reference the graph.
graph_id = 'graph-{0}'.format(_get_random_id())
js = populate_template(js_template, graph_id=graph_id)
css = populate_template(css_template, graph_id=graph_id)
return populate_template(
html_template,
graph_id=graph_id,
css=css,
js=js
) | python | def create_graph_html(js_template, css_template, html_template=None):
""" Create HTML code block given the graph Javascript and CSS. """
if html_template is None:
html_template = read_lib('html', 'graph')
# Create div ID for the graph and give it to the JS and CSS templates so
# they can reference the graph.
graph_id = 'graph-{0}'.format(_get_random_id())
js = populate_template(js_template, graph_id=graph_id)
css = populate_template(css_template, graph_id=graph_id)
return populate_template(
html_template,
graph_id=graph_id,
css=css,
js=js
) | [
"def",
"create_graph_html",
"(",
"js_template",
",",
"css_template",
",",
"html_template",
"=",
"None",
")",
":",
"if",
"html_template",
"is",
"None",
":",
"html_template",
"=",
"read_lib",
"(",
"'html'",
",",
"'graph'",
")",
"# Create div ID for the graph and give it to the JS and CSS templates so",
"# they can reference the graph.",
"graph_id",
"=",
"'graph-{0}'",
".",
"format",
"(",
"_get_random_id",
"(",
")",
")",
"js",
"=",
"populate_template",
"(",
"js_template",
",",
"graph_id",
"=",
"graph_id",
")",
"css",
"=",
"populate_template",
"(",
"css_template",
",",
"graph_id",
"=",
"graph_id",
")",
"return",
"populate_template",
"(",
"html_template",
",",
"graph_id",
"=",
"graph_id",
",",
"css",
"=",
"css",
",",
"js",
"=",
"js",
")"
] | Create HTML code block given the graph Javascript and CSS. | [
"Create",
"HTML",
"code",
"block",
"given",
"the",
"graph",
"Javascript",
"and",
"CSS",
"."
] | 2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0 | https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L79-L95 | train |
viraja1/grammar-check | download_lt.py | get_newest_possible_languagetool_version | def get_newest_possible_languagetool_version():
"""Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True
"""
java_path = find_executable('java')
if not java_path:
# Just ignore this and assume an old version of Java. It might not be
# found because of a PATHEXT-related issue
# (https://bugs.python.org/issue2200).
return JAVA_6_COMPATIBLE_VERSION
output = subprocess.check_output([java_path, '-version'],
stderr=subprocess.STDOUT,
universal_newlines=True)
# https://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
match = re.search(
r'^java version "(?P<major1>\d+)\.(?P<major2>\d+)\.[^"]+"$',
output,
re.MULTILINE)
if not match:
raise SystemExit(
'Could not parse Java version from """{}""".'.format(output))
java_version = (int(match.group('major1')), int(match.group('major2')))
if java_version >= (1, 7):
return LATEST_VERSION
elif java_version >= (1, 6):
warn('grammar-check would be able to use a newer version of '
'LanguageTool if you had Java 7 or newer installed')
return JAVA_6_COMPATIBLE_VERSION
else:
raise SystemExit(
'You need at least Java 6 to use grammar-check') | python | def get_newest_possible_languagetool_version():
"""Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True
"""
java_path = find_executable('java')
if not java_path:
# Just ignore this and assume an old version of Java. It might not be
# found because of a PATHEXT-related issue
# (https://bugs.python.org/issue2200).
return JAVA_6_COMPATIBLE_VERSION
output = subprocess.check_output([java_path, '-version'],
stderr=subprocess.STDOUT,
universal_newlines=True)
# https://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
match = re.search(
r'^java version "(?P<major1>\d+)\.(?P<major2>\d+)\.[^"]+"$',
output,
re.MULTILINE)
if not match:
raise SystemExit(
'Could not parse Java version from """{}""".'.format(output))
java_version = (int(match.group('major1')), int(match.group('major2')))
if java_version >= (1, 7):
return LATEST_VERSION
elif java_version >= (1, 6):
warn('grammar-check would be able to use a newer version of '
'LanguageTool if you had Java 7 or newer installed')
return JAVA_6_COMPATIBLE_VERSION
else:
raise SystemExit(
'You need at least Java 6 to use grammar-check') | [
"def",
"get_newest_possible_languagetool_version",
"(",
")",
":",
"java_path",
"=",
"find_executable",
"(",
"'java'",
")",
"if",
"not",
"java_path",
":",
"# Just ignore this and assume an old version of Java. It might not be",
"# found because of a PATHEXT-related issue",
"# (https://bugs.python.org/issue2200).",
"return",
"JAVA_6_COMPATIBLE_VERSION",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"java_path",
",",
"'-version'",
"]",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"universal_newlines",
"=",
"True",
")",
"# https://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html",
"match",
"=",
"re",
".",
"search",
"(",
"r'^java version \"(?P<major1>\\d+)\\.(?P<major2>\\d+)\\.[^\"]+\"$'",
",",
"output",
",",
"re",
".",
"MULTILINE",
")",
"if",
"not",
"match",
":",
"raise",
"SystemExit",
"(",
"'Could not parse Java version from \"\"\"{}\"\"\".'",
".",
"format",
"(",
"output",
")",
")",
"java_version",
"=",
"(",
"int",
"(",
"match",
".",
"group",
"(",
"'major1'",
")",
")",
",",
"int",
"(",
"match",
".",
"group",
"(",
"'major2'",
")",
")",
")",
"if",
"java_version",
">=",
"(",
"1",
",",
"7",
")",
":",
"return",
"LATEST_VERSION",
"elif",
"java_version",
">=",
"(",
"1",
",",
"6",
")",
":",
"warn",
"(",
"'grammar-check would be able to use a newer version of '",
"'LanguageTool if you had Java 7 or newer installed'",
")",
"return",
"JAVA_6_COMPATIBLE_VERSION",
"else",
":",
"raise",
"SystemExit",
"(",
"'You need at least Java 6 to use grammar-check'",
")"
] | Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True | [
"Return",
"newest",
"compatible",
"version",
"."
] | 103bf27119b85b4ef26c8f8d4089b6c882cabe5c | https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/download_lt.py#L33-L69 | train |
rlisagor/pynetlinux | pynetlinux/ifconfig.py | iterifs | def iterifs(physical=True):
''' Iterate over all the interfaces in the system. If physical is
true, then return only real physical interfaces (not 'lo', etc).'''
net_files = os.listdir(SYSFS_NET_PATH)
interfaces = set()
virtual = set()
for d in net_files:
path = os.path.join(SYSFS_NET_PATH, d)
if not os.path.isdir(path):
continue
if not os.path.exists(os.path.join(path, b"device")):
virtual.add(d)
interfaces.add(d)
# Some virtual interfaces don't show up in the above search, for example,
# subinterfaces (e.g. eth0:1). To find those, we have to do an ioctl
if not physical:
# ifconfig gets a max of 30 interfaces. Good enough for us too.
ifreqs = array.array("B", b"\x00" * SIZE_OF_IFREQ * 30)
buf_addr, _buf_len = ifreqs.buffer_info()
ifconf = struct.pack("iP", SIZE_OF_IFREQ * 30, buf_addr)
ifconf_res = fcntl.ioctl(sockfd, SIOCGIFCONF, ifconf)
ifreqs_len, _ = struct.unpack("iP", ifconf_res)
assert ifreqs_len % SIZE_OF_IFREQ == 0, (
"Unexpected amount of data returned from ioctl. "
"You're probably running on an unexpected architecture")
res = ifreqs.tostring()
for i in range(0, ifreqs_len, SIZE_OF_IFREQ):
d = res[i:i+16].strip(b'\0')
interfaces.add(d)
results = interfaces - virtual if physical else interfaces
for d in results:
yield Interface(d) | python | def iterifs(physical=True):
''' Iterate over all the interfaces in the system. If physical is
true, then return only real physical interfaces (not 'lo', etc).'''
net_files = os.listdir(SYSFS_NET_PATH)
interfaces = set()
virtual = set()
for d in net_files:
path = os.path.join(SYSFS_NET_PATH, d)
if not os.path.isdir(path):
continue
if not os.path.exists(os.path.join(path, b"device")):
virtual.add(d)
interfaces.add(d)
# Some virtual interfaces don't show up in the above search, for example,
# subinterfaces (e.g. eth0:1). To find those, we have to do an ioctl
if not physical:
# ifconfig gets a max of 30 interfaces. Good enough for us too.
ifreqs = array.array("B", b"\x00" * SIZE_OF_IFREQ * 30)
buf_addr, _buf_len = ifreqs.buffer_info()
ifconf = struct.pack("iP", SIZE_OF_IFREQ * 30, buf_addr)
ifconf_res = fcntl.ioctl(sockfd, SIOCGIFCONF, ifconf)
ifreqs_len, _ = struct.unpack("iP", ifconf_res)
assert ifreqs_len % SIZE_OF_IFREQ == 0, (
"Unexpected amount of data returned from ioctl. "
"You're probably running on an unexpected architecture")
res = ifreqs.tostring()
for i in range(0, ifreqs_len, SIZE_OF_IFREQ):
d = res[i:i+16].strip(b'\0')
interfaces.add(d)
results = interfaces - virtual if physical else interfaces
for d in results:
yield Interface(d) | [
"def",
"iterifs",
"(",
"physical",
"=",
"True",
")",
":",
"net_files",
"=",
"os",
".",
"listdir",
"(",
"SYSFS_NET_PATH",
")",
"interfaces",
"=",
"set",
"(",
")",
"virtual",
"=",
"set",
"(",
")",
"for",
"d",
"in",
"net_files",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SYSFS_NET_PATH",
",",
"d",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"continue",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"b\"device\"",
")",
")",
":",
"virtual",
".",
"add",
"(",
"d",
")",
"interfaces",
".",
"add",
"(",
"d",
")",
"# Some virtual interfaces don't show up in the above search, for example,",
"# subinterfaces (e.g. eth0:1). To find those, we have to do an ioctl",
"if",
"not",
"physical",
":",
"# ifconfig gets a max of 30 interfaces. Good enough for us too.",
"ifreqs",
"=",
"array",
".",
"array",
"(",
"\"B\"",
",",
"b\"\\x00\"",
"*",
"SIZE_OF_IFREQ",
"*",
"30",
")",
"buf_addr",
",",
"_buf_len",
"=",
"ifreqs",
".",
"buffer_info",
"(",
")",
"ifconf",
"=",
"struct",
".",
"pack",
"(",
"\"iP\"",
",",
"SIZE_OF_IFREQ",
"*",
"30",
",",
"buf_addr",
")",
"ifconf_res",
"=",
"fcntl",
".",
"ioctl",
"(",
"sockfd",
",",
"SIOCGIFCONF",
",",
"ifconf",
")",
"ifreqs_len",
",",
"_",
"=",
"struct",
".",
"unpack",
"(",
"\"iP\"",
",",
"ifconf_res",
")",
"assert",
"ifreqs_len",
"%",
"SIZE_OF_IFREQ",
"==",
"0",
",",
"(",
"\"Unexpected amount of data returned from ioctl. \"",
"\"You're probably running on an unexpected architecture\"",
")",
"res",
"=",
"ifreqs",
".",
"tostring",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"ifreqs_len",
",",
"SIZE_OF_IFREQ",
")",
":",
"d",
"=",
"res",
"[",
"i",
":",
"i",
"+",
"16",
"]",
".",
"strip",
"(",
"b'\\0'",
")",
"interfaces",
".",
"add",
"(",
"d",
")",
"results",
"=",
"interfaces",
"-",
"virtual",
"if",
"physical",
"else",
"interfaces",
"for",
"d",
"in",
"results",
":",
"yield",
"Interface",
"(",
"d",
")"
] | Iterate over all the interfaces in the system. If physical is
true, then return only real physical interfaces (not 'lo', etc). | [
"Iterate",
"over",
"all",
"the",
"interfaces",
"in",
"the",
"system",
".",
"If",
"physical",
"is",
"true",
"then",
"return",
"only",
"real",
"physical",
"interfaces",
"(",
"not",
"lo",
"etc",
")",
"."
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L353-L388 | train |
rlisagor/pynetlinux | pynetlinux/ifconfig.py | init | def init():
''' Initialize the library '''
globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
globals()["sockfd"] = globals()["sock"].fileno() | python | def init():
''' Initialize the library '''
globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
globals()["sockfd"] = globals()["sock"].fileno() | [
"def",
"init",
"(",
")",
":",
"globals",
"(",
")",
"[",
"\"sock\"",
"]",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"globals",
"(",
")",
"[",
"\"sockfd\"",
"]",
"=",
"globals",
"(",
")",
"[",
"\"sock\"",
"]",
".",
"fileno",
"(",
")"
] | Initialize the library | [
"Initialize",
"the",
"library"
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L403-L406 | train |
rlisagor/pynetlinux | pynetlinux/ifconfig.py | Interface.up | def up(self):
''' Bring up the bridge interface. Equivalent to ifconfig [iface] up. '''
# Get existing device flags
ifreq = struct.pack('16sh', self.name, 0)
flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]
# Set new flags
flags = flags | IFF_UP
ifreq = struct.pack('16sh', self.name, flags)
fcntl.ioctl(sockfd, SIOCSIFFLAGS, ifreq) | python | def up(self):
''' Bring up the bridge interface. Equivalent to ifconfig [iface] up. '''
# Get existing device flags
ifreq = struct.pack('16sh', self.name, 0)
flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]
# Set new flags
flags = flags | IFF_UP
ifreq = struct.pack('16sh', self.name, flags)
fcntl.ioctl(sockfd, SIOCSIFFLAGS, ifreq) | [
"def",
"up",
"(",
"self",
")",
":",
"# Get existing device flags",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16sh'",
",",
"self",
".",
"name",
",",
"0",
")",
"flags",
"=",
"struct",
".",
"unpack",
"(",
"'16sh'",
",",
"fcntl",
".",
"ioctl",
"(",
"sockfd",
",",
"SIOCGIFFLAGS",
",",
"ifreq",
")",
")",
"[",
"1",
"]",
"# Set new flags",
"flags",
"=",
"flags",
"|",
"IFF_UP",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16sh'",
",",
"self",
".",
"name",
",",
"flags",
")",
"fcntl",
".",
"ioctl",
"(",
"sockfd",
",",
"SIOCSIFFLAGS",
",",
"ifreq",
")"
] | Bring up the bridge interface. Equivalent to ifconfig [iface] up. | [
"Bring",
"up",
"the",
"bridge",
"interface",
".",
"Equivalent",
"to",
"ifconfig",
"[",
"iface",
"]",
"up",
"."
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L142-L152 | train |
rlisagor/pynetlinux | pynetlinux/ifconfig.py | Interface.is_up | def is_up(self):
''' Return True if the interface is up, False otherwise. '''
# Get existing device flags
ifreq = struct.pack('16sh', self.name, 0)
flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]
# Set new flags
if flags & IFF_UP:
return True
else:
return False | python | def is_up(self):
''' Return True if the interface is up, False otherwise. '''
# Get existing device flags
ifreq = struct.pack('16sh', self.name, 0)
flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]
# Set new flags
if flags & IFF_UP:
return True
else:
return False | [
"def",
"is_up",
"(",
"self",
")",
":",
"# Get existing device flags",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16sh'",
",",
"self",
".",
"name",
",",
"0",
")",
"flags",
"=",
"struct",
".",
"unpack",
"(",
"'16sh'",
",",
"fcntl",
".",
"ioctl",
"(",
"sockfd",
",",
"SIOCGIFFLAGS",
",",
"ifreq",
")",
")",
"[",
"1",
"]",
"# Set new flags",
"if",
"flags",
"&",
"IFF_UP",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Return True if the interface is up, False otherwise. | [
"Return",
"True",
"if",
"the",
"interface",
"is",
"up",
"False",
"otherwise",
"."
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L166-L177 | train |
rlisagor/pynetlinux | pynetlinux/ifconfig.py | Interface.get_mac | def get_mac(self):
''' Obtain the device's mac address. '''
ifreq = struct.pack('16sH14s', self.name, AF_UNIX, b'\x00'*14)
res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq)
address = struct.unpack('16sH14s', res)[2]
mac = struct.unpack('6B8x', address)
return ":".join(['%02X' % i for i in mac]) | python | def get_mac(self):
''' Obtain the device's mac address. '''
ifreq = struct.pack('16sH14s', self.name, AF_UNIX, b'\x00'*14)
res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq)
address = struct.unpack('16sH14s', res)[2]
mac = struct.unpack('6B8x', address)
return ":".join(['%02X' % i for i in mac]) | [
"def",
"get_mac",
"(",
"self",
")",
":",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16sH14s'",
",",
"self",
".",
"name",
",",
"AF_UNIX",
",",
"b'\\x00'",
"*",
"14",
")",
"res",
"=",
"fcntl",
".",
"ioctl",
"(",
"sockfd",
",",
"SIOCGIFHWADDR",
",",
"ifreq",
")",
"address",
"=",
"struct",
".",
"unpack",
"(",
"'16sH14s'",
",",
"res",
")",
"[",
"2",
"]",
"mac",
"=",
"struct",
".",
"unpack",
"(",
"'6B8x'",
",",
"address",
")",
"return",
"\":\"",
".",
"join",
"(",
"[",
"'%02X'",
"%",
"i",
"for",
"i",
"in",
"mac",
"]",
")"
] | Obtain the device's mac address. | [
"Obtain",
"the",
"device",
"s",
"mac",
"address",
"."
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L179-L186 | train |
rlisagor/pynetlinux | pynetlinux/ifconfig.py | Interface.set_mac | def set_mac(self, newmac):
''' Set the device's mac address. Device must be down for this to
succeed. '''
macbytes = [int(i, 16) for i in newmac.split(':')]
ifreq = struct.pack('16sH6B8x', self.name, AF_UNIX, *macbytes)
fcntl.ioctl(sockfd, SIOCSIFHWADDR, ifreq) | python | def set_mac(self, newmac):
''' Set the device's mac address. Device must be down for this to
succeed. '''
macbytes = [int(i, 16) for i in newmac.split(':')]
ifreq = struct.pack('16sH6B8x', self.name, AF_UNIX, *macbytes)
fcntl.ioctl(sockfd, SIOCSIFHWADDR, ifreq) | [
"def",
"set_mac",
"(",
"self",
",",
"newmac",
")",
":",
"macbytes",
"=",
"[",
"int",
"(",
"i",
",",
"16",
")",
"for",
"i",
"in",
"newmac",
".",
"split",
"(",
"':'",
")",
"]",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16sH6B8x'",
",",
"self",
".",
"name",
",",
"AF_UNIX",
",",
"*",
"macbytes",
")",
"fcntl",
".",
"ioctl",
"(",
"sockfd",
",",
"SIOCSIFHWADDR",
",",
"ifreq",
")"
] | Set the device's mac address. Device must be down for this to
succeed. | [
"Set",
"the",
"device",
"s",
"mac",
"address",
".",
"Device",
"must",
"be",
"down",
"for",
"this",
"to",
"succeed",
"."
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L189-L194 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.