repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
adrn/gala
gala/dynamics/plot.py
plot_projections
def plot_projections(x, relative_to=None, autolim=True, axes=None, subplots_kwargs=dict(), labels=None, plot_function=None, **kwargs): """ Given N-dimensional quantity, ``x``, make a figure containing 2D projections of all combinations of the axes. Parameters ---------- x : array_like Array of values. ``axis=0`` is assumed to be the dimensionality, ``axis=1`` is the time axis. See :ref:`shape-conventions` for more information. relative_to : bool (optional) Plot the values relative to this value or values. autolim : bool (optional) Automatically set the plot limits to be something sensible. axes : array_like (optional) Array of matplotlib Axes objects. subplots_kwargs : dict (optional) Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`. labels : iterable (optional) List or iterable of axis labels as strings. They should correspond to the dimensions of the input orbit. plot_function : callable (optional) The ``matplotlib`` plot function to use. By default, this is :func:`~matplotlib.pyplot.scatter`, but can also be, e.g., :func:`~matplotlib.pyplot.plot`. **kwargs All other keyword arguments are passed to the ``plot_function``. You can pass in any of the usual style kwargs like ``color=...``, ``marker=...``, etc. Returns ------- fig : `~matplotlib.Figure` """ # don't propagate changes back... x = np.array(x, copy=True) ndim = x.shape[0] # get axes object from arguments if axes is None: axes = _get_axes(dim=ndim, subplots_kwargs=subplots_kwargs) # if the quantities are relative if relative_to is not None: x -= relative_to # name of the plotting function plot_fn_name = plot_function.__name__ # automatically determine limits if autolim: lims = [] for i in range(ndim): max_,min_ = np.max(x[i]), np.min(x[i]) delta = max_ - min_ if delta == 0.: delta = 1. lims.append([min_ - delta*0.02, max_ + delta*0.02]) k = 0 for i in range(ndim): for j in range(ndim): if i >= j: continue # skip diagonal, upper triangle plot_func = getattr(axes[k], plot_fn_name) plot_func(x[i], x[j], **kwargs) if labels is not None: axes[k].set_xlabel(labels[i]) axes[k].set_ylabel(labels[j]) if autolim: axes[k].set_xlim(lims[i]) axes[k].set_ylim(lims[j]) k += 1 axes[0].figure.tight_layout() return axes[0].figure
python
def plot_projections(x, relative_to=None, autolim=True, axes=None, subplots_kwargs=dict(), labels=None, plot_function=None, **kwargs): """ Given N-dimensional quantity, ``x``, make a figure containing 2D projections of all combinations of the axes. Parameters ---------- x : array_like Array of values. ``axis=0`` is assumed to be the dimensionality, ``axis=1`` is the time axis. See :ref:`shape-conventions` for more information. relative_to : bool (optional) Plot the values relative to this value or values. autolim : bool (optional) Automatically set the plot limits to be something sensible. axes : array_like (optional) Array of matplotlib Axes objects. subplots_kwargs : dict (optional) Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`. labels : iterable (optional) List or iterable of axis labels as strings. They should correspond to the dimensions of the input orbit. plot_function : callable (optional) The ``matplotlib`` plot function to use. By default, this is :func:`~matplotlib.pyplot.scatter`, but can also be, e.g., :func:`~matplotlib.pyplot.plot`. **kwargs All other keyword arguments are passed to the ``plot_function``. You can pass in any of the usual style kwargs like ``color=...``, ``marker=...``, etc. Returns ------- fig : `~matplotlib.Figure` """ # don't propagate changes back... x = np.array(x, copy=True) ndim = x.shape[0] # get axes object from arguments if axes is None: axes = _get_axes(dim=ndim, subplots_kwargs=subplots_kwargs) # if the quantities are relative if relative_to is not None: x -= relative_to # name of the plotting function plot_fn_name = plot_function.__name__ # automatically determine limits if autolim: lims = [] for i in range(ndim): max_,min_ = np.max(x[i]), np.min(x[i]) delta = max_ - min_ if delta == 0.: delta = 1. lims.append([min_ - delta*0.02, max_ + delta*0.02]) k = 0 for i in range(ndim): for j in range(ndim): if i >= j: continue # skip diagonal, upper triangle plot_func = getattr(axes[k], plot_fn_name) plot_func(x[i], x[j], **kwargs) if labels is not None: axes[k].set_xlabel(labels[i]) axes[k].set_ylabel(labels[j]) if autolim: axes[k].set_xlim(lims[i]) axes[k].set_ylim(lims[j]) k += 1 axes[0].figure.tight_layout() return axes[0].figure
[ "def", "plot_projections", "(", "x", ",", "relative_to", "=", "None", ",", "autolim", "=", "True", ",", "axes", "=", "None", ",", "subplots_kwargs", "=", "dict", "(", ")", ",", "labels", "=", "None", ",", "plot_function", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# don't propagate changes back...", "x", "=", "np", ".", "array", "(", "x", ",", "copy", "=", "True", ")", "ndim", "=", "x", ".", "shape", "[", "0", "]", "# get axes object from arguments", "if", "axes", "is", "None", ":", "axes", "=", "_get_axes", "(", "dim", "=", "ndim", ",", "subplots_kwargs", "=", "subplots_kwargs", ")", "# if the quantities are relative", "if", "relative_to", "is", "not", "None", ":", "x", "-=", "relative_to", "# name of the plotting function", "plot_fn_name", "=", "plot_function", ".", "__name__", "# automatically determine limits", "if", "autolim", ":", "lims", "=", "[", "]", "for", "i", "in", "range", "(", "ndim", ")", ":", "max_", ",", "min_", "=", "np", ".", "max", "(", "x", "[", "i", "]", ")", ",", "np", ".", "min", "(", "x", "[", "i", "]", ")", "delta", "=", "max_", "-", "min_", "if", "delta", "==", "0.", ":", "delta", "=", "1.", "lims", ".", "append", "(", "[", "min_", "-", "delta", "*", "0.02", ",", "max_", "+", "delta", "*", "0.02", "]", ")", "k", "=", "0", "for", "i", "in", "range", "(", "ndim", ")", ":", "for", "j", "in", "range", "(", "ndim", ")", ":", "if", "i", ">=", "j", ":", "continue", "# skip diagonal, upper triangle", "plot_func", "=", "getattr", "(", "axes", "[", "k", "]", ",", "plot_fn_name", ")", "plot_func", "(", "x", "[", "i", "]", ",", "x", "[", "j", "]", ",", "*", "*", "kwargs", ")", "if", "labels", "is", "not", "None", ":", "axes", "[", "k", "]", ".", "set_xlabel", "(", "labels", "[", "i", "]", ")", "axes", "[", "k", "]", ".", "set_ylabel", "(", "labels", "[", "j", "]", ")", "if", "autolim", ":", "axes", "[", "k", "]", ".", "set_xlim", "(", "lims", "[", "i", "]", ")", "axes", "[", "k", "]", ".", "set_ylim", "(", "lims", "[", "j", "]", ")", "k", "+=", "1", "axes", "[", "0", "]", ".", "figure", ".", "tight_layout", "(", ")", "return", "axes", "[", "0", "]", ".", "figure" ]
Given N-dimensional quantity, ``x``, make a figure containing 2D projections of all combinations of the axes. Parameters ---------- x : array_like Array of values. ``axis=0`` is assumed to be the dimensionality, ``axis=1`` is the time axis. See :ref:`shape-conventions` for more information. relative_to : bool (optional) Plot the values relative to this value or values. autolim : bool (optional) Automatically set the plot limits to be something sensible. axes : array_like (optional) Array of matplotlib Axes objects. subplots_kwargs : dict (optional) Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`. labels : iterable (optional) List or iterable of axis labels as strings. They should correspond to the dimensions of the input orbit. plot_function : callable (optional) The ``matplotlib`` plot function to use. By default, this is :func:`~matplotlib.pyplot.scatter`, but can also be, e.g., :func:`~matplotlib.pyplot.plot`. **kwargs All other keyword arguments are passed to the ``plot_function``. You can pass in any of the usual style kwargs like ``color=...``, ``marker=...``, etc. Returns ------- fig : `~matplotlib.Figure`
[ "Given", "N", "-", "dimensional", "quantity", "x", "make", "a", "figure", "containing", "2D", "projections", "of", "all", "combinations", "of", "the", "axes", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/plot.py#L34-L120
train
adrn/gala
gala/dynamics/_genfunc/genfunc_3d.py
angmom
def angmom(x): """ returns angular momentum vector of phase-space point x""" return np.array([x[1]*x[5]-x[2]*x[4],x[2]*x[3]-x[0]*x[5],x[0]*x[4]-x[1]*x[3]])
python
def angmom(x): """ returns angular momentum vector of phase-space point x""" return np.array([x[1]*x[5]-x[2]*x[4],x[2]*x[3]-x[0]*x[5],x[0]*x[4]-x[1]*x[3]])
[ "def", "angmom", "(", "x", ")", ":", "return", "np", ".", "array", "(", "[", "x", "[", "1", "]", "*", "x", "[", "5", "]", "-", "x", "[", "2", "]", "*", "x", "[", "4", "]", ",", "x", "[", "2", "]", "*", "x", "[", "3", "]", "-", "x", "[", "0", "]", "*", "x", "[", "5", "]", ",", "x", "[", "0", "]", "*", "x", "[", "4", "]", "-", "x", "[", "1", "]", "*", "x", "[", "3", "]", "]", ")" ]
returns angular momentum vector of phase-space point x
[ "returns", "angular", "momentum", "vector", "of", "phase", "-", "space", "point", "x" ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/_genfunc/genfunc_3d.py#L186-L188
train
adrn/gala
gala/dynamics/_genfunc/genfunc_3d.py
flip_coords
def flip_coords(X,loop): """ Align circulation with z-axis """ if(loop[0]==1): return np.array(map(lambda i: np.array([i[2],i[1],i[0],i[5],i[4],i[3]]),X)) else: return X
python
def flip_coords(X,loop): """ Align circulation with z-axis """ if(loop[0]==1): return np.array(map(lambda i: np.array([i[2],i[1],i[0],i[5],i[4],i[3]]),X)) else: return X
[ "def", "flip_coords", "(", "X", ",", "loop", ")", ":", "if", "(", "loop", "[", "0", "]", "==", "1", ")", ":", "return", "np", ".", "array", "(", "map", "(", "lambda", "i", ":", "np", ".", "array", "(", "[", "i", "[", "2", "]", ",", "i", "[", "1", "]", ",", "i", "[", "0", "]", ",", "i", "[", "5", "]", ",", "i", "[", "4", "]", ",", "i", "[", "3", "]", "]", ")", ",", "X", ")", ")", "else", ":", "return", "X" ]
Align circulation with z-axis
[ "Align", "circulation", "with", "z", "-", "axis" ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/_genfunc/genfunc_3d.py#L213-L218
train
adrn/gala
gala/dynamics/analyticactionangle.py
harmonic_oscillator_to_aa
def harmonic_oscillator_to_aa(w, potential): """ Transform the input cartesian position and velocity to action-angle coordinates for the Harmonic Oscillator potential. This transformation is analytic and can be used as a "toy potential" in the Sanders & Binney (2014) formalism for computing action-angle coordinates in any potential. .. note:: This function is included as a method of the :class:`~gala.potential.HarmonicOscillatorPotential` and it is recommended to call :meth:`~gala.potential.HarmonicOscillatorPotential.action_angle()` instead. Parameters ---------- w : :class:`gala.dynamics.PhaseSpacePosition`, :class:`gala.dynamics.Orbit` potential : Potential """ usys = potential.units if usys is not None: x = w.xyz.decompose(usys).value v = w.v_xyz.decompose(usys).value else: x = w.xyz.value v = w.v_xyz.value _new_omega_shape = (3,) + tuple([1]*(len(x.shape)-1)) # compute actions -- just energy (hamiltonian) over frequency if usys is None: usys = [] try: omega = potential.parameters['omega'].reshape(_new_omega_shape).decompose(usys).value except AttributeError: # not a Quantity omega = potential.parameters['omega'].reshape(_new_omega_shape) action = (v**2 + (omega*x)**2)/(2.*omega) angle = np.arctan(-v / omega / x) angle[x == 0] = -np.sign(v[x == 0])*np.pi/2. angle[x < 0] += np.pi freq = potential.parameters['omega'].decompose(usys).value if usys is not None and usys: a_unit = (1*usys['angular momentum']/usys['mass']).decompose(usys).unit f_unit = (1*usys['frequency']).decompose(usys).unit return action*a_unit, (angle % (2.*np.pi))*u.radian, freq*f_unit else: return action*u.one, (angle % (2.*np.pi))*u.one, freq*u.one
python
def harmonic_oscillator_to_aa(w, potential): """ Transform the input cartesian position and velocity to action-angle coordinates for the Harmonic Oscillator potential. This transformation is analytic and can be used as a "toy potential" in the Sanders & Binney (2014) formalism for computing action-angle coordinates in any potential. .. note:: This function is included as a method of the :class:`~gala.potential.HarmonicOscillatorPotential` and it is recommended to call :meth:`~gala.potential.HarmonicOscillatorPotential.action_angle()` instead. Parameters ---------- w : :class:`gala.dynamics.PhaseSpacePosition`, :class:`gala.dynamics.Orbit` potential : Potential """ usys = potential.units if usys is not None: x = w.xyz.decompose(usys).value v = w.v_xyz.decompose(usys).value else: x = w.xyz.value v = w.v_xyz.value _new_omega_shape = (3,) + tuple([1]*(len(x.shape)-1)) # compute actions -- just energy (hamiltonian) over frequency if usys is None: usys = [] try: omega = potential.parameters['omega'].reshape(_new_omega_shape).decompose(usys).value except AttributeError: # not a Quantity omega = potential.parameters['omega'].reshape(_new_omega_shape) action = (v**2 + (omega*x)**2)/(2.*omega) angle = np.arctan(-v / omega / x) angle[x == 0] = -np.sign(v[x == 0])*np.pi/2. angle[x < 0] += np.pi freq = potential.parameters['omega'].decompose(usys).value if usys is not None and usys: a_unit = (1*usys['angular momentum']/usys['mass']).decompose(usys).unit f_unit = (1*usys['frequency']).decompose(usys).unit return action*a_unit, (angle % (2.*np.pi))*u.radian, freq*f_unit else: return action*u.one, (angle % (2.*np.pi))*u.one, freq*u.one
[ "def", "harmonic_oscillator_to_aa", "(", "w", ",", "potential", ")", ":", "usys", "=", "potential", ".", "units", "if", "usys", "is", "not", "None", ":", "x", "=", "w", ".", "xyz", ".", "decompose", "(", "usys", ")", ".", "value", "v", "=", "w", ".", "v_xyz", ".", "decompose", "(", "usys", ")", ".", "value", "else", ":", "x", "=", "w", ".", "xyz", ".", "value", "v", "=", "w", ".", "v_xyz", ".", "value", "_new_omega_shape", "=", "(", "3", ",", ")", "+", "tuple", "(", "[", "1", "]", "*", "(", "len", "(", "x", ".", "shape", ")", "-", "1", ")", ")", "# compute actions -- just energy (hamiltonian) over frequency", "if", "usys", "is", "None", ":", "usys", "=", "[", "]", "try", ":", "omega", "=", "potential", ".", "parameters", "[", "'omega'", "]", ".", "reshape", "(", "_new_omega_shape", ")", ".", "decompose", "(", "usys", ")", ".", "value", "except", "AttributeError", ":", "# not a Quantity", "omega", "=", "potential", ".", "parameters", "[", "'omega'", "]", ".", "reshape", "(", "_new_omega_shape", ")", "action", "=", "(", "v", "**", "2", "+", "(", "omega", "*", "x", ")", "**", "2", ")", "/", "(", "2.", "*", "omega", ")", "angle", "=", "np", ".", "arctan", "(", "-", "v", "/", "omega", "/", "x", ")", "angle", "[", "x", "==", "0", "]", "=", "-", "np", ".", "sign", "(", "v", "[", "x", "==", "0", "]", ")", "*", "np", ".", "pi", "/", "2.", "angle", "[", "x", "<", "0", "]", "+=", "np", ".", "pi", "freq", "=", "potential", ".", "parameters", "[", "'omega'", "]", ".", "decompose", "(", "usys", ")", ".", "value", "if", "usys", "is", "not", "None", "and", "usys", ":", "a_unit", "=", "(", "1", "*", "usys", "[", "'angular momentum'", "]", "/", "usys", "[", "'mass'", "]", ")", ".", "decompose", "(", "usys", ")", ".", "unit", "f_unit", "=", "(", "1", "*", "usys", "[", "'frequency'", "]", ")", ".", "decompose", "(", "usys", ")", ".", "unit", "return", "action", "*", "a_unit", ",", "(", "angle", "%", "(", "2.", "*", "np", ".", "pi", ")", ")", "*", "u", ".", "radian", ",", "freq", "*", "f_unit", "else", ":", "return", "action", "*", "u", ".", "one", ",", "(", "angle", "%", "(", "2.", "*", "np", ".", "pi", ")", ")", "*", "u", ".", "one", ",", "freq", "*", "u", ".", "one" ]
Transform the input cartesian position and velocity to action-angle coordinates for the Harmonic Oscillator potential. This transformation is analytic and can be used as a "toy potential" in the Sanders & Binney (2014) formalism for computing action-angle coordinates in any potential. .. note:: This function is included as a method of the :class:`~gala.potential.HarmonicOscillatorPotential` and it is recommended to call :meth:`~gala.potential.HarmonicOscillatorPotential.action_angle()` instead. Parameters ---------- w : :class:`gala.dynamics.PhaseSpacePosition`, :class:`gala.dynamics.Orbit` potential : Potential
[ "Transform", "the", "input", "cartesian", "position", "and", "velocity", "to", "action", "-", "angle", "coordinates", "for", "the", "Harmonic", "Oscillator", "potential", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/analyticactionangle.py#L299-L352
train
adrn/gala
gala/integrate/pyintegrators/rk5.py
RK5Integrator.step
def step(self, t, w, dt): """ Step forward the vector w by the given timestep. Parameters ---------- dt : numeric The timestep to move forward. """ # Runge-Kutta Fehlberg formulas (see: Numerical Recipes) F = lambda t, w: self.F(t, w, *self._func_args) K = np.zeros((6,)+w.shape) K[0] = dt * F(t, w) K[1] = dt * F(t + A[1]*dt, w + B[1][0]*K[0]) K[2] = dt * F(t + A[2]*dt, w + B[2][0]*K[0] + B[2][1]*K[1]) K[3] = dt * F(t + A[3]*dt, w + B[3][0]*K[0] + B[3][1]*K[1] + B[3][2]*K[2]) K[4] = dt * F(t + A[4]*dt, w + B[4][0]*K[0] + B[4][1]*K[1] + B[4][2]*K[2] + B[4][3]*K[3]) K[5] = dt * F(t + A[5]*dt, w + B[5][0]*K[0] + B[5][1]*K[1] + B[5][2]*K[2] + B[5][3]*K[3] + B[5][4]*K[4]) # shift dw = np.zeros_like(w) for i in range(6): dw = dw + C[i]*K[i] return w + dw
python
def step(self, t, w, dt): """ Step forward the vector w by the given timestep. Parameters ---------- dt : numeric The timestep to move forward. """ # Runge-Kutta Fehlberg formulas (see: Numerical Recipes) F = lambda t, w: self.F(t, w, *self._func_args) K = np.zeros((6,)+w.shape) K[0] = dt * F(t, w) K[1] = dt * F(t + A[1]*dt, w + B[1][0]*K[0]) K[2] = dt * F(t + A[2]*dt, w + B[2][0]*K[0] + B[2][1]*K[1]) K[3] = dt * F(t + A[3]*dt, w + B[3][0]*K[0] + B[3][1]*K[1] + B[3][2]*K[2]) K[4] = dt * F(t + A[4]*dt, w + B[4][0]*K[0] + B[4][1]*K[1] + B[4][2]*K[2] + B[4][3]*K[3]) K[5] = dt * F(t + A[5]*dt, w + B[5][0]*K[0] + B[5][1]*K[1] + B[5][2]*K[2] + B[5][3]*K[3] + B[5][4]*K[4]) # shift dw = np.zeros_like(w) for i in range(6): dw = dw + C[i]*K[i] return w + dw
[ "def", "step", "(", "self", ",", "t", ",", "w", ",", "dt", ")", ":", "# Runge-Kutta Fehlberg formulas (see: Numerical Recipes)", "F", "=", "lambda", "t", ",", "w", ":", "self", ".", "F", "(", "t", ",", "w", ",", "*", "self", ".", "_func_args", ")", "K", "=", "np", ".", "zeros", "(", "(", "6", ",", ")", "+", "w", ".", "shape", ")", "K", "[", "0", "]", "=", "dt", "*", "F", "(", "t", ",", "w", ")", "K", "[", "1", "]", "=", "dt", "*", "F", "(", "t", "+", "A", "[", "1", "]", "*", "dt", ",", "w", "+", "B", "[", "1", "]", "[", "0", "]", "*", "K", "[", "0", "]", ")", "K", "[", "2", "]", "=", "dt", "*", "F", "(", "t", "+", "A", "[", "2", "]", "*", "dt", ",", "w", "+", "B", "[", "2", "]", "[", "0", "]", "*", "K", "[", "0", "]", "+", "B", "[", "2", "]", "[", "1", "]", "*", "K", "[", "1", "]", ")", "K", "[", "3", "]", "=", "dt", "*", "F", "(", "t", "+", "A", "[", "3", "]", "*", "dt", ",", "w", "+", "B", "[", "3", "]", "[", "0", "]", "*", "K", "[", "0", "]", "+", "B", "[", "3", "]", "[", "1", "]", "*", "K", "[", "1", "]", "+", "B", "[", "3", "]", "[", "2", "]", "*", "K", "[", "2", "]", ")", "K", "[", "4", "]", "=", "dt", "*", "F", "(", "t", "+", "A", "[", "4", "]", "*", "dt", ",", "w", "+", "B", "[", "4", "]", "[", "0", "]", "*", "K", "[", "0", "]", "+", "B", "[", "4", "]", "[", "1", "]", "*", "K", "[", "1", "]", "+", "B", "[", "4", "]", "[", "2", "]", "*", "K", "[", "2", "]", "+", "B", "[", "4", "]", "[", "3", "]", "*", "K", "[", "3", "]", ")", "K", "[", "5", "]", "=", "dt", "*", "F", "(", "t", "+", "A", "[", "5", "]", "*", "dt", ",", "w", "+", "B", "[", "5", "]", "[", "0", "]", "*", "K", "[", "0", "]", "+", "B", "[", "5", "]", "[", "1", "]", "*", "K", "[", "1", "]", "+", "B", "[", "5", "]", "[", "2", "]", "*", "K", "[", "2", "]", "+", "B", "[", "5", "]", "[", "3", "]", "*", "K", "[", "3", "]", "+", "B", "[", "5", "]", "[", "4", "]", "*", "K", "[", "4", "]", ")", "# shift", "dw", "=", "np", ".", "zeros_like", "(", "w", ")", "for", "i", "in", "range", "(", "6", ")", ":", "dw", "=", "dw", "+", "C", "[", "i", "]", "*", "K", "[", "i", "]", "return", "w", "+", "dw" ]
Step forward the vector w by the given timestep. Parameters ---------- dt : numeric The timestep to move forward.
[ "Step", "forward", "the", "vector", "w", "by", "the", "given", "timestep", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/integrate/pyintegrators/rk5.py#L52-L77
train
adrn/gala
gala/dynamics/_genfunc/solver.py
check_each_direction
def check_each_direction(n,angs,ifprint=True): """ returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n """ checks = np.array([]) P = np.array([]) if(ifprint): print("\nChecking modes:\n====") for k,i in enumerate(n): N_matrix = np.linalg.norm(i) X = np.dot(angs,i) if(np.abs(np.max(X)-np.min(X))<2.*np.pi): if(ifprint): print("Need a longer integration window for mode ", i) checks=np.append(checks,i) P = np.append(P,(2.*np.pi-np.abs(np.max(X)-np.min(X)))) elif(np.abs(np.max(X)-np.min(X))/len(X)>np.pi): if(ifprint): print("Need a finer sampling for mode ", i) checks=np.append(checks,i) P = np.append(P,(2.*np.pi-np.abs(np.max(X)-np.min(X)))) if(ifprint): print("====\n") return checks,P
python
def check_each_direction(n,angs,ifprint=True): """ returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n """ checks = np.array([]) P = np.array([]) if(ifprint): print("\nChecking modes:\n====") for k,i in enumerate(n): N_matrix = np.linalg.norm(i) X = np.dot(angs,i) if(np.abs(np.max(X)-np.min(X))<2.*np.pi): if(ifprint): print("Need a longer integration window for mode ", i) checks=np.append(checks,i) P = np.append(P,(2.*np.pi-np.abs(np.max(X)-np.min(X)))) elif(np.abs(np.max(X)-np.min(X))/len(X)>np.pi): if(ifprint): print("Need a finer sampling for mode ", i) checks=np.append(checks,i) P = np.append(P,(2.*np.pi-np.abs(np.max(X)-np.min(X)))) if(ifprint): print("====\n") return checks,P
[ "def", "check_each_direction", "(", "n", ",", "angs", ",", "ifprint", "=", "True", ")", ":", "checks", "=", "np", ".", "array", "(", "[", "]", ")", "P", "=", "np", ".", "array", "(", "[", "]", ")", "if", "(", "ifprint", ")", ":", "print", "(", "\"\\nChecking modes:\\n====\"", ")", "for", "k", ",", "i", "in", "enumerate", "(", "n", ")", ":", "N_matrix", "=", "np", ".", "linalg", ".", "norm", "(", "i", ")", "X", "=", "np", ".", "dot", "(", "angs", ",", "i", ")", "if", "(", "np", ".", "abs", "(", "np", ".", "max", "(", "X", ")", "-", "np", ".", "min", "(", "X", ")", ")", "<", "2.", "*", "np", ".", "pi", ")", ":", "if", "(", "ifprint", ")", ":", "print", "(", "\"Need a longer integration window for mode \"", ",", "i", ")", "checks", "=", "np", ".", "append", "(", "checks", ",", "i", ")", "P", "=", "np", ".", "append", "(", "P", ",", "(", "2.", "*", "np", ".", "pi", "-", "np", ".", "abs", "(", "np", ".", "max", "(", "X", ")", "-", "np", ".", "min", "(", "X", ")", ")", ")", ")", "elif", "(", "np", ".", "abs", "(", "np", ".", "max", "(", "X", ")", "-", "np", ".", "min", "(", "X", ")", ")", "/", "len", "(", "X", ")", ">", "np", ".", "pi", ")", ":", "if", "(", "ifprint", ")", ":", "print", "(", "\"Need a finer sampling for mode \"", ",", "i", ")", "checks", "=", "np", ".", "append", "(", "checks", ",", "i", ")", "P", "=", "np", ".", "append", "(", "P", ",", "(", "2.", "*", "np", ".", "pi", "-", "np", ".", "abs", "(", "np", ".", "max", "(", "X", ")", "-", "np", ".", "min", "(", "X", ")", ")", ")", ")", "if", "(", "ifprint", ")", ":", "print", "(", "\"====\\n\"", ")", "return", "checks", ",", "P" ]
returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n
[ "returns", "a", "list", "of", "the", "index", "of", "elements", "of", "n", "which", "do", "not", "have", "adequate", "toy", "angle", "coverage", ".", "The", "criterion", "is", "that", "we", "must", "have", "at", "least", "one", "sample", "in", "each", "Nyquist", "box", "when", "we", "project", "the", "toy", "angles", "along", "the", "vector", "n" ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/_genfunc/solver.py#L10-L33
train
adrn/gala
gala/dynamics/_genfunc/solver.py
unroll_angles
def unroll_angles(A,sign): """ Unrolls the angles, A, so they increase continuously """ n = np.array([0,0,0]) P = np.zeros(np.shape(A)) P[0]=A[0] for i in range(1,len(A)): n = n+((A[i]-A[i-1]+0.5*sign*np.pi)*sign<0)*np.ones(3)*2.*np.pi P[i] = A[i]+sign*n return P
python
def unroll_angles(A,sign): """ Unrolls the angles, A, so they increase continuously """ n = np.array([0,0,0]) P = np.zeros(np.shape(A)) P[0]=A[0] for i in range(1,len(A)): n = n+((A[i]-A[i-1]+0.5*sign*np.pi)*sign<0)*np.ones(3)*2.*np.pi P[i] = A[i]+sign*n return P
[ "def", "unroll_angles", "(", "A", ",", "sign", ")", ":", "n", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "0", "]", ")", "P", "=", "np", ".", "zeros", "(", "np", ".", "shape", "(", "A", ")", ")", "P", "[", "0", "]", "=", "A", "[", "0", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "A", ")", ")", ":", "n", "=", "n", "+", "(", "(", "A", "[", "i", "]", "-", "A", "[", "i", "-", "1", "]", "+", "0.5", "*", "sign", "*", "np", ".", "pi", ")", "*", "sign", "<", "0", ")", "*", "np", ".", "ones", "(", "3", ")", "*", "2.", "*", "np", ".", "pi", "P", "[", "i", "]", "=", "A", "[", "i", "]", "+", "sign", "*", "n", "return", "P" ]
Unrolls the angles, A, so they increase continuously
[ "Unrolls", "the", "angles", "A", "so", "they", "increase", "continuously" ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/_genfunc/solver.py#L81-L89
train
adrn/gala
gala/potential/scf/core.py
compute_coeffs
def compute_coeffs(density_func, nmax, lmax, M, r_s, args=(), skip_odd=False, skip_even=False, skip_m=False, S_only=False, progress=False, **nquad_opts): """ Compute the expansion coefficients for representing the input density function using a basis function expansion. Computing the coefficients involves computing triple integrals which are computationally expensive. For an example of how to parallelize the computation of the coefficients, see ``examples/parallel_compute_Anlm.py``. Parameters ---------- density_func : function, callable A function or callable object that evaluates the density at a given position. The call format must be of the form: ``density_func(x, y, z, M, r_s, args)`` where ``x,y,z`` are cartesian coordinates, ``M`` is a scale mass, ``r_s`` a scale radius, and ``args`` is an iterable containing any other arguments needed by the density function. nmax : int Maximum value of ``n`` for the radial expansion. lmax : int Maximum value of ``l`` for the spherical harmonics. M : numeric Scale mass. r_s : numeric Scale radius. args : iterable (optional) A list or iterable of any other arguments needed by the density function. skip_odd : bool (optional) Skip the odd terms in the angular portion of the expansion. For example, only take :math:`l=0,2,4,...` skip_even : bool (optional) Skip the even terms in the angular portion of the expansion. For example, only take :math:`l=1,3,5,...` skip_m : bool (optional) Ignore terms with :math:`m > 0`. S_only : bool (optional) Only compute the S coefficients. progress : bool (optional) If ``tqdm`` is installed, display a progress bar. **nquad_opts Any additional keyword arguments are passed through to `~scipy.integrate.nquad` as options, `opts`. Returns ------- Snlm : float, `~numpy.ndarray` The value of the cosine expansion coefficient. Snlm_err : , `~numpy.ndarray` An estimate of the uncertainty in the coefficient value (from `~scipy.integrate.nquad`). Tnlm : , `~numpy.ndarray` The value of the sine expansion coefficient. Tnlm_err : , `~numpy.ndarray` An estimate of the uncertainty in the coefficient value. (from `~scipy.integrate.nquad`). """ from gala._cconfig import GSL_ENABLED if not GSL_ENABLED: raise ValueError("Gala was compiled without GSL and so this function " "will not work. See the gala documentation for more " "information about installing and using GSL with " "gala: http://gala.adrian.pw/en/latest/install.html") lmin = 0 lstride = 1 if skip_odd or skip_even: lstride = 2 if skip_even: lmin = 1 Snlm = np.zeros((nmax+1, lmax+1, lmax+1)) Snlm_e = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm_e = np.zeros((nmax+1, lmax+1, lmax+1)) nquad_opts.setdefault('limit', 256) nquad_opts.setdefault('epsrel', 1E-10) limits = [[0, 2*np.pi], # phi [-1, 1.], # X (cos(theta)) [-1, 1.]] # xsi nlms = [] for n in range(nmax+1): for l in range(lmin, lmax+1, lstride): for m in range(l+1): if skip_m and m > 0: continue nlms.append((n, l, m)) if progress: try: from tqdm import tqdm except ImportError as e: raise ImportError('tqdm is not installed - you can install it ' 'with `pip install tqdm`.\n' + str(e)) iterfunc = tqdm else: iterfunc = lambda x: x for n, l, m in iterfunc(nlms): Snlm[n, l, m], Snlm_e[n, l, m] = si.nquad( Snlm_integrand, ranges=limits, args=(density_func, n, l, m, M, r_s, args), opts=nquad_opts) if not S_only: Tnlm[n, l, m], Tnlm_e[n, l, m] = si.nquad( Tnlm_integrand, ranges=limits, args=(density_func, n, l, m, M, r_s, args), opts=nquad_opts) return (Snlm, Snlm_e), (Tnlm, Tnlm_e)
python
def compute_coeffs(density_func, nmax, lmax, M, r_s, args=(), skip_odd=False, skip_even=False, skip_m=False, S_only=False, progress=False, **nquad_opts): """ Compute the expansion coefficients for representing the input density function using a basis function expansion. Computing the coefficients involves computing triple integrals which are computationally expensive. For an example of how to parallelize the computation of the coefficients, see ``examples/parallel_compute_Anlm.py``. Parameters ---------- density_func : function, callable A function or callable object that evaluates the density at a given position. The call format must be of the form: ``density_func(x, y, z, M, r_s, args)`` where ``x,y,z`` are cartesian coordinates, ``M`` is a scale mass, ``r_s`` a scale radius, and ``args`` is an iterable containing any other arguments needed by the density function. nmax : int Maximum value of ``n`` for the radial expansion. lmax : int Maximum value of ``l`` for the spherical harmonics. M : numeric Scale mass. r_s : numeric Scale radius. args : iterable (optional) A list or iterable of any other arguments needed by the density function. skip_odd : bool (optional) Skip the odd terms in the angular portion of the expansion. For example, only take :math:`l=0,2,4,...` skip_even : bool (optional) Skip the even terms in the angular portion of the expansion. For example, only take :math:`l=1,3,5,...` skip_m : bool (optional) Ignore terms with :math:`m > 0`. S_only : bool (optional) Only compute the S coefficients. progress : bool (optional) If ``tqdm`` is installed, display a progress bar. **nquad_opts Any additional keyword arguments are passed through to `~scipy.integrate.nquad` as options, `opts`. Returns ------- Snlm : float, `~numpy.ndarray` The value of the cosine expansion coefficient. Snlm_err : , `~numpy.ndarray` An estimate of the uncertainty in the coefficient value (from `~scipy.integrate.nquad`). Tnlm : , `~numpy.ndarray` The value of the sine expansion coefficient. Tnlm_err : , `~numpy.ndarray` An estimate of the uncertainty in the coefficient value. (from `~scipy.integrate.nquad`). """ from gala._cconfig import GSL_ENABLED if not GSL_ENABLED: raise ValueError("Gala was compiled without GSL and so this function " "will not work. See the gala documentation for more " "information about installing and using GSL with " "gala: http://gala.adrian.pw/en/latest/install.html") lmin = 0 lstride = 1 if skip_odd or skip_even: lstride = 2 if skip_even: lmin = 1 Snlm = np.zeros((nmax+1, lmax+1, lmax+1)) Snlm_e = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm_e = np.zeros((nmax+1, lmax+1, lmax+1)) nquad_opts.setdefault('limit', 256) nquad_opts.setdefault('epsrel', 1E-10) limits = [[0, 2*np.pi], # phi [-1, 1.], # X (cos(theta)) [-1, 1.]] # xsi nlms = [] for n in range(nmax+1): for l in range(lmin, lmax+1, lstride): for m in range(l+1): if skip_m and m > 0: continue nlms.append((n, l, m)) if progress: try: from tqdm import tqdm except ImportError as e: raise ImportError('tqdm is not installed - you can install it ' 'with `pip install tqdm`.\n' + str(e)) iterfunc = tqdm else: iterfunc = lambda x: x for n, l, m in iterfunc(nlms): Snlm[n, l, m], Snlm_e[n, l, m] = si.nquad( Snlm_integrand, ranges=limits, args=(density_func, n, l, m, M, r_s, args), opts=nquad_opts) if not S_only: Tnlm[n, l, m], Tnlm_e[n, l, m] = si.nquad( Tnlm_integrand, ranges=limits, args=(density_func, n, l, m, M, r_s, args), opts=nquad_opts) return (Snlm, Snlm_e), (Tnlm, Tnlm_e)
[ "def", "compute_coeffs", "(", "density_func", ",", "nmax", ",", "lmax", ",", "M", ",", "r_s", ",", "args", "=", "(", ")", ",", "skip_odd", "=", "False", ",", "skip_even", "=", "False", ",", "skip_m", "=", "False", ",", "S_only", "=", "False", ",", "progress", "=", "False", ",", "*", "*", "nquad_opts", ")", ":", "from", "gala", ".", "_cconfig", "import", "GSL_ENABLED", "if", "not", "GSL_ENABLED", ":", "raise", "ValueError", "(", "\"Gala was compiled without GSL and so this function \"", "\"will not work. See the gala documentation for more \"", "\"information about installing and using GSL with \"", "\"gala: http://gala.adrian.pw/en/latest/install.html\"", ")", "lmin", "=", "0", "lstride", "=", "1", "if", "skip_odd", "or", "skip_even", ":", "lstride", "=", "2", "if", "skip_even", ":", "lmin", "=", "1", "Snlm", "=", "np", ".", "zeros", "(", "(", "nmax", "+", "1", ",", "lmax", "+", "1", ",", "lmax", "+", "1", ")", ")", "Snlm_e", "=", "np", ".", "zeros", "(", "(", "nmax", "+", "1", ",", "lmax", "+", "1", ",", "lmax", "+", "1", ")", ")", "Tnlm", "=", "np", ".", "zeros", "(", "(", "nmax", "+", "1", ",", "lmax", "+", "1", ",", "lmax", "+", "1", ")", ")", "Tnlm_e", "=", "np", ".", "zeros", "(", "(", "nmax", "+", "1", ",", "lmax", "+", "1", ",", "lmax", "+", "1", ")", ")", "nquad_opts", ".", "setdefault", "(", "'limit'", ",", "256", ")", "nquad_opts", ".", "setdefault", "(", "'epsrel'", ",", "1E-10", ")", "limits", "=", "[", "[", "0", ",", "2", "*", "np", ".", "pi", "]", ",", "# phi", "[", "-", "1", ",", "1.", "]", ",", "# X (cos(theta))", "[", "-", "1", ",", "1.", "]", "]", "# xsi", "nlms", "=", "[", "]", "for", "n", "in", "range", "(", "nmax", "+", "1", ")", ":", "for", "l", "in", "range", "(", "lmin", ",", "lmax", "+", "1", ",", "lstride", ")", ":", "for", "m", "in", "range", "(", "l", "+", "1", ")", ":", "if", "skip_m", "and", "m", ">", "0", ":", "continue", "nlms", ".", "append", "(", "(", "n", ",", "l", ",", "m", ")", ")", "if", "progress", ":", "try", ":", "from", "tqdm", "import", "tqdm", "except", "ImportError", "as", "e", ":", "raise", "ImportError", "(", "'tqdm is not installed - you can install it '", "'with `pip install tqdm`.\\n'", "+", "str", "(", "e", ")", ")", "iterfunc", "=", "tqdm", "else", ":", "iterfunc", "=", "lambda", "x", ":", "x", "for", "n", ",", "l", ",", "m", "in", "iterfunc", "(", "nlms", ")", ":", "Snlm", "[", "n", ",", "l", ",", "m", "]", ",", "Snlm_e", "[", "n", ",", "l", ",", "m", "]", "=", "si", ".", "nquad", "(", "Snlm_integrand", ",", "ranges", "=", "limits", ",", "args", "=", "(", "density_func", ",", "n", ",", "l", ",", "m", ",", "M", ",", "r_s", ",", "args", ")", ",", "opts", "=", "nquad_opts", ")", "if", "not", "S_only", ":", "Tnlm", "[", "n", ",", "l", ",", "m", "]", ",", "Tnlm_e", "[", "n", ",", "l", ",", "m", "]", "=", "si", ".", "nquad", "(", "Tnlm_integrand", ",", "ranges", "=", "limits", ",", "args", "=", "(", "density_func", ",", "n", ",", "l", ",", "m", ",", "M", ",", "r_s", ",", "args", ")", ",", "opts", "=", "nquad_opts", ")", "return", "(", "Snlm", ",", "Snlm_e", ")", ",", "(", "Tnlm", ",", "Tnlm_e", ")" ]
Compute the expansion coefficients for representing the input density function using a basis function expansion. Computing the coefficients involves computing triple integrals which are computationally expensive. For an example of how to parallelize the computation of the coefficients, see ``examples/parallel_compute_Anlm.py``. Parameters ---------- density_func : function, callable A function or callable object that evaluates the density at a given position. The call format must be of the form: ``density_func(x, y, z, M, r_s, args)`` where ``x,y,z`` are cartesian coordinates, ``M`` is a scale mass, ``r_s`` a scale radius, and ``args`` is an iterable containing any other arguments needed by the density function. nmax : int Maximum value of ``n`` for the radial expansion. lmax : int Maximum value of ``l`` for the spherical harmonics. M : numeric Scale mass. r_s : numeric Scale radius. args : iterable (optional) A list or iterable of any other arguments needed by the density function. skip_odd : bool (optional) Skip the odd terms in the angular portion of the expansion. For example, only take :math:`l=0,2,4,...` skip_even : bool (optional) Skip the even terms in the angular portion of the expansion. For example, only take :math:`l=1,3,5,...` skip_m : bool (optional) Ignore terms with :math:`m > 0`. S_only : bool (optional) Only compute the S coefficients. progress : bool (optional) If ``tqdm`` is installed, display a progress bar. **nquad_opts Any additional keyword arguments are passed through to `~scipy.integrate.nquad` as options, `opts`. Returns ------- Snlm : float, `~numpy.ndarray` The value of the cosine expansion coefficient. Snlm_err : , `~numpy.ndarray` An estimate of the uncertainty in the coefficient value (from `~scipy.integrate.nquad`). Tnlm : , `~numpy.ndarray` The value of the sine expansion coefficient. Tnlm_err : , `~numpy.ndarray` An estimate of the uncertainty in the coefficient value. (from `~scipy.integrate.nquad`).
[ "Compute", "the", "expansion", "coefficients", "for", "representing", "the", "input", "density", "function", "using", "a", "basis", "function", "expansion", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/scf/core.py#L13-L129
train
adrn/gala
gala/potential/scf/core.py
compute_coeffs_discrete
def compute_coeffs_discrete(xyz, mass, nmax, lmax, r_s, skip_odd=False, skip_even=False, skip_m=False, compute_var=False): """ Compute the expansion coefficients for representing the density distribution of input points as a basis function expansion. The points, ``xyz``, are assumed to be samples from the density distribution. Computing the coefficients involves computing triple integrals which are computationally expensive. For an example of how to parallelize the computation of the coefficients, see ``examples/parallel_compute_Anlm.py``. Parameters ---------- xyz : array_like Samples from the density distribution. Should have shape ``(n_samples,3)``. mass : array_like Mass of each sample. Should have shape ``(n_samples,)``. nmax : int Maximum value of ``n`` for the radial expansion. lmax : int Maximum value of ``l`` for the spherical harmonics. r_s : numeric Scale radius. skip_odd : bool (optional) Skip the odd terms in the angular portion of the expansion. For example, only take :math:`l=0,2,4,...` skip_even : bool (optional) Skip the even terms in the angular portion of the expansion. For example, only take :math:`l=1,3,5,...` skip_m : bool (optional) Ignore terms with :math:`m > 0`. compute_var : bool (optional) Also compute the variances of the coefficients. This does not compute the full covariance matrix of the coefficients, just the individual variances. TODO: separate function to compute full covariance matrix? Returns ------- Snlm : float The value of the cosine expansion coefficient. Tnlm : float The value of the sine expansion coefficient. """ lmin = 0 lstride = 1 if skip_odd or skip_even: lstride = 2 if skip_even: lmin = 1 Snlm = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm = np.zeros((nmax+1, lmax+1, lmax+1)) if compute_var: Snlm_var = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm_var = np.zeros((nmax+1, lmax+1, lmax+1)) # positions and masses of point masses xyz = np.ascontiguousarray(np.atleast_2d(xyz)) mass = np.ascontiguousarray(np.atleast_1d(mass)) r = np.sqrt(np.sum(xyz**2, axis=-1)) s = r / r_s phi = np.arctan2(xyz[:,1], xyz[:,0]) X = xyz[:,2] / r for n in range(nmax+1): for l in range(lmin, lmax+1, lstride): for m in range(l+1): if skip_m and m > 0: continue # logger.debug("Computing coefficients (n,l,m)=({},{},{})".format(n,l,m)) Snlm[n,l,m], Tnlm[n,l,m] = STnlm_discrete(s, phi, X, mass, n, l, m) if compute_var: Snlm_var[n,l,m], Tnlm_var[n,l,m] = STnlm_var_discrete(s, phi, X, mass, n, l, m) if compute_var: return (Snlm,Snlm_var), (Tnlm,Tnlm_var) else: return Snlm, Tnlm
python
def compute_coeffs_discrete(xyz, mass, nmax, lmax, r_s, skip_odd=False, skip_even=False, skip_m=False, compute_var=False): """ Compute the expansion coefficients for representing the density distribution of input points as a basis function expansion. The points, ``xyz``, are assumed to be samples from the density distribution. Computing the coefficients involves computing triple integrals which are computationally expensive. For an example of how to parallelize the computation of the coefficients, see ``examples/parallel_compute_Anlm.py``. Parameters ---------- xyz : array_like Samples from the density distribution. Should have shape ``(n_samples,3)``. mass : array_like Mass of each sample. Should have shape ``(n_samples,)``. nmax : int Maximum value of ``n`` for the radial expansion. lmax : int Maximum value of ``l`` for the spherical harmonics. r_s : numeric Scale radius. skip_odd : bool (optional) Skip the odd terms in the angular portion of the expansion. For example, only take :math:`l=0,2,4,...` skip_even : bool (optional) Skip the even terms in the angular portion of the expansion. For example, only take :math:`l=1,3,5,...` skip_m : bool (optional) Ignore terms with :math:`m > 0`. compute_var : bool (optional) Also compute the variances of the coefficients. This does not compute the full covariance matrix of the coefficients, just the individual variances. TODO: separate function to compute full covariance matrix? Returns ------- Snlm : float The value of the cosine expansion coefficient. Tnlm : float The value of the sine expansion coefficient. """ lmin = 0 lstride = 1 if skip_odd or skip_even: lstride = 2 if skip_even: lmin = 1 Snlm = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm = np.zeros((nmax+1, lmax+1, lmax+1)) if compute_var: Snlm_var = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm_var = np.zeros((nmax+1, lmax+1, lmax+1)) # positions and masses of point masses xyz = np.ascontiguousarray(np.atleast_2d(xyz)) mass = np.ascontiguousarray(np.atleast_1d(mass)) r = np.sqrt(np.sum(xyz**2, axis=-1)) s = r / r_s phi = np.arctan2(xyz[:,1], xyz[:,0]) X = xyz[:,2] / r for n in range(nmax+1): for l in range(lmin, lmax+1, lstride): for m in range(l+1): if skip_m and m > 0: continue # logger.debug("Computing coefficients (n,l,m)=({},{},{})".format(n,l,m)) Snlm[n,l,m], Tnlm[n,l,m] = STnlm_discrete(s, phi, X, mass, n, l, m) if compute_var: Snlm_var[n,l,m], Tnlm_var[n,l,m] = STnlm_var_discrete(s, phi, X, mass, n, l, m) if compute_var: return (Snlm,Snlm_var), (Tnlm,Tnlm_var) else: return Snlm, Tnlm
[ "def", "compute_coeffs_discrete", "(", "xyz", ",", "mass", ",", "nmax", ",", "lmax", ",", "r_s", ",", "skip_odd", "=", "False", ",", "skip_even", "=", "False", ",", "skip_m", "=", "False", ",", "compute_var", "=", "False", ")", ":", "lmin", "=", "0", "lstride", "=", "1", "if", "skip_odd", "or", "skip_even", ":", "lstride", "=", "2", "if", "skip_even", ":", "lmin", "=", "1", "Snlm", "=", "np", ".", "zeros", "(", "(", "nmax", "+", "1", ",", "lmax", "+", "1", ",", "lmax", "+", "1", ")", ")", "Tnlm", "=", "np", ".", "zeros", "(", "(", "nmax", "+", "1", ",", "lmax", "+", "1", ",", "lmax", "+", "1", ")", ")", "if", "compute_var", ":", "Snlm_var", "=", "np", ".", "zeros", "(", "(", "nmax", "+", "1", ",", "lmax", "+", "1", ",", "lmax", "+", "1", ")", ")", "Tnlm_var", "=", "np", ".", "zeros", "(", "(", "nmax", "+", "1", ",", "lmax", "+", "1", ",", "lmax", "+", "1", ")", ")", "# positions and masses of point masses", "xyz", "=", "np", ".", "ascontiguousarray", "(", "np", ".", "atleast_2d", "(", "xyz", ")", ")", "mass", "=", "np", ".", "ascontiguousarray", "(", "np", ".", "atleast_1d", "(", "mass", ")", ")", "r", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "xyz", "**", "2", ",", "axis", "=", "-", "1", ")", ")", "s", "=", "r", "/", "r_s", "phi", "=", "np", ".", "arctan2", "(", "xyz", "[", ":", ",", "1", "]", ",", "xyz", "[", ":", ",", "0", "]", ")", "X", "=", "xyz", "[", ":", ",", "2", "]", "/", "r", "for", "n", "in", "range", "(", "nmax", "+", "1", ")", ":", "for", "l", "in", "range", "(", "lmin", ",", "lmax", "+", "1", ",", "lstride", ")", ":", "for", "m", "in", "range", "(", "l", "+", "1", ")", ":", "if", "skip_m", "and", "m", ">", "0", ":", "continue", "# logger.debug(\"Computing coefficients (n,l,m)=({},{},{})\".format(n,l,m))", "Snlm", "[", "n", ",", "l", ",", "m", "]", ",", "Tnlm", "[", "n", ",", "l", ",", "m", "]", "=", "STnlm_discrete", "(", "s", ",", "phi", ",", "X", ",", "mass", ",", "n", ",", "l", ",", "m", ")", "if", "compute_var", ":", "Snlm_var", "[", "n", ",", "l", ",", "m", "]", ",", "Tnlm_var", "[", "n", ",", "l", ",", "m", "]", "=", "STnlm_var_discrete", "(", "s", ",", "phi", ",", "X", ",", "mass", ",", "n", ",", "l", ",", "m", ")", "if", "compute_var", ":", "return", "(", "Snlm", ",", "Snlm_var", ")", ",", "(", "Tnlm", ",", "Tnlm_var", ")", "else", ":", "return", "Snlm", ",", "Tnlm" ]
Compute the expansion coefficients for representing the density distribution of input points as a basis function expansion. The points, ``xyz``, are assumed to be samples from the density distribution. Computing the coefficients involves computing triple integrals which are computationally expensive. For an example of how to parallelize the computation of the coefficients, see ``examples/parallel_compute_Anlm.py``. Parameters ---------- xyz : array_like Samples from the density distribution. Should have shape ``(n_samples,3)``. mass : array_like Mass of each sample. Should have shape ``(n_samples,)``. nmax : int Maximum value of ``n`` for the radial expansion. lmax : int Maximum value of ``l`` for the spherical harmonics. r_s : numeric Scale radius. skip_odd : bool (optional) Skip the odd terms in the angular portion of the expansion. For example, only take :math:`l=0,2,4,...` skip_even : bool (optional) Skip the even terms in the angular portion of the expansion. For example, only take :math:`l=1,3,5,...` skip_m : bool (optional) Ignore terms with :math:`m > 0`. compute_var : bool (optional) Also compute the variances of the coefficients. This does not compute the full covariance matrix of the coefficients, just the individual variances. TODO: separate function to compute full covariance matrix? Returns ------- Snlm : float The value of the cosine expansion coefficient. Tnlm : float The value of the sine expansion coefficient.
[ "Compute", "the", "expansion", "coefficients", "for", "representing", "the", "density", "distribution", "of", "input", "points", "as", "a", "basis", "function", "expansion", ".", "The", "points", "xyz", "are", "assumed", "to", "be", "samples", "from", "the", "density", "distribution", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/scf/core.py#L132-L216
train
adrn/gala
gala/dynamics/nbody/core.py
DirectNBody.integrate_orbit
def integrate_orbit(self, **time_spec): """ Integrate the initial conditions in the combined external potential plus N-body forces. This integration uses the `~gala.integrate.DOPRI853Integrator`. Parameters ---------- **time_spec Specification of how long to integrate. See documentation for `~gala.integrate.parse_time_specification`. Returns ------- orbit : `~gala.dynamics.Orbit` The orbits of the particles. """ # Prepare the initial conditions pos = self.w0.xyz.decompose(self.units).value vel = self.w0.v_xyz.decompose(self.units).value w0 = np.ascontiguousarray(np.vstack((pos, vel)).T) # Prepare the time-stepping array t = parse_time_specification(self.units, **time_spec) ws = _direct_nbody_dop853(w0, t, self._ext_ham, self.particle_potentials) pos = np.rollaxis(np.array(ws[..., :3]), axis=2) vel = np.rollaxis(np.array(ws[..., 3:]), axis=2) orbits = Orbit( pos=pos * self.units['length'], vel=vel * self.units['length'] / self.units['time'], t=t * self.units['time']) return orbits
python
def integrate_orbit(self, **time_spec): """ Integrate the initial conditions in the combined external potential plus N-body forces. This integration uses the `~gala.integrate.DOPRI853Integrator`. Parameters ---------- **time_spec Specification of how long to integrate. See documentation for `~gala.integrate.parse_time_specification`. Returns ------- orbit : `~gala.dynamics.Orbit` The orbits of the particles. """ # Prepare the initial conditions pos = self.w0.xyz.decompose(self.units).value vel = self.w0.v_xyz.decompose(self.units).value w0 = np.ascontiguousarray(np.vstack((pos, vel)).T) # Prepare the time-stepping array t = parse_time_specification(self.units, **time_spec) ws = _direct_nbody_dop853(w0, t, self._ext_ham, self.particle_potentials) pos = np.rollaxis(np.array(ws[..., :3]), axis=2) vel = np.rollaxis(np.array(ws[..., 3:]), axis=2) orbits = Orbit( pos=pos * self.units['length'], vel=vel * self.units['length'] / self.units['time'], t=t * self.units['time']) return orbits
[ "def", "integrate_orbit", "(", "self", ",", "*", "*", "time_spec", ")", ":", "# Prepare the initial conditions", "pos", "=", "self", ".", "w0", ".", "xyz", ".", "decompose", "(", "self", ".", "units", ")", ".", "value", "vel", "=", "self", ".", "w0", ".", "v_xyz", ".", "decompose", "(", "self", ".", "units", ")", ".", "value", "w0", "=", "np", ".", "ascontiguousarray", "(", "np", ".", "vstack", "(", "(", "pos", ",", "vel", ")", ")", ".", "T", ")", "# Prepare the time-stepping array", "t", "=", "parse_time_specification", "(", "self", ".", "units", ",", "*", "*", "time_spec", ")", "ws", "=", "_direct_nbody_dop853", "(", "w0", ",", "t", ",", "self", ".", "_ext_ham", ",", "self", ".", "particle_potentials", ")", "pos", "=", "np", ".", "rollaxis", "(", "np", ".", "array", "(", "ws", "[", "...", ",", ":", "3", "]", ")", ",", "axis", "=", "2", ")", "vel", "=", "np", ".", "rollaxis", "(", "np", ".", "array", "(", "ws", "[", "...", ",", "3", ":", "]", ")", ",", "axis", "=", "2", ")", "orbits", "=", "Orbit", "(", "pos", "=", "pos", "*", "self", ".", "units", "[", "'length'", "]", ",", "vel", "=", "vel", "*", "self", ".", "units", "[", "'length'", "]", "/", "self", ".", "units", "[", "'time'", "]", ",", "t", "=", "t", "*", "self", ".", "units", "[", "'time'", "]", ")", "return", "orbits" ]
Integrate the initial conditions in the combined external potential plus N-body forces. This integration uses the `~gala.integrate.DOPRI853Integrator`. Parameters ---------- **time_spec Specification of how long to integrate. See documentation for `~gala.integrate.parse_time_specification`. Returns ------- orbit : `~gala.dynamics.Orbit` The orbits of the particles.
[ "Integrate", "the", "initial", "conditions", "in", "the", "combined", "external", "potential", "plus", "N", "-", "body", "forces", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/nbody/core.py#L115-L153
train
adrn/gala
gala/dynamics/representation_nd.py
NDMixin._apply
def _apply(self, method, *args, **kwargs): """Create a new representation with ``method`` applied to the arrays. In typical usage, the method is any of the shape-changing methods for `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those picking particular elements (``__getitem__``, ``take``, etc.), which are all defined in `~astropy.utils.misc.ShapedLikeNDArray`. It will be applied to the underlying arrays (e.g., ``x``, ``y``, and ``z`` for `~astropy.coordinates.CartesianRepresentation`), with the results used to create a new instance. Internally, it is also used to apply functions to the components (in particular, `~numpy.broadcast_to`). Parameters ---------- method : str or callable If str, it is the name of a method that is applied to the internal ``components``. If callable, the function is applied. args : tuple Any positional arguments for ``method``. kwargs : dict Any keyword arguments for ``method``. """ if callable(method): apply_method = lambda array: method(array, *args, **kwargs) else: apply_method = operator.methodcaller(method, *args, **kwargs) return self.__class__([apply_method(getattr(self, component)) for component in self.components], copy=False)
python
def _apply(self, method, *args, **kwargs): """Create a new representation with ``method`` applied to the arrays. In typical usage, the method is any of the shape-changing methods for `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those picking particular elements (``__getitem__``, ``take``, etc.), which are all defined in `~astropy.utils.misc.ShapedLikeNDArray`. It will be applied to the underlying arrays (e.g., ``x``, ``y``, and ``z`` for `~astropy.coordinates.CartesianRepresentation`), with the results used to create a new instance. Internally, it is also used to apply functions to the components (in particular, `~numpy.broadcast_to`). Parameters ---------- method : str or callable If str, it is the name of a method that is applied to the internal ``components``. If callable, the function is applied. args : tuple Any positional arguments for ``method``. kwargs : dict Any keyword arguments for ``method``. """ if callable(method): apply_method = lambda array: method(array, *args, **kwargs) else: apply_method = operator.methodcaller(method, *args, **kwargs) return self.__class__([apply_method(getattr(self, component)) for component in self.components], copy=False)
[ "def", "_apply", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "callable", "(", "method", ")", ":", "apply_method", "=", "lambda", "array", ":", "method", "(", "array", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "apply_method", "=", "operator", ".", "methodcaller", "(", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "__class__", "(", "[", "apply_method", "(", "getattr", "(", "self", ",", "component", ")", ")", "for", "component", "in", "self", ".", "components", "]", ",", "copy", "=", "False", ")" ]
Create a new representation with ``method`` applied to the arrays. In typical usage, the method is any of the shape-changing methods for `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those picking particular elements (``__getitem__``, ``take``, etc.), which are all defined in `~astropy.utils.misc.ShapedLikeNDArray`. It will be applied to the underlying arrays (e.g., ``x``, ``y``, and ``z`` for `~astropy.coordinates.CartesianRepresentation`), with the results used to create a new instance. Internally, it is also used to apply functions to the components (in particular, `~numpy.broadcast_to`). Parameters ---------- method : str or callable If str, it is the name of a method that is applied to the internal ``components``. If callable, the function is applied. args : tuple Any positional arguments for ``method``. kwargs : dict Any keyword arguments for ``method``.
[ "Create", "a", "new", "representation", "with", "method", "applied", "to", "the", "arrays", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/representation_nd.py#L14-L43
train
adrn/gala
gala/dynamics/representation_nd.py
NDCartesianRepresentation.get_xyz
def get_xyz(self, xyz_axis=0): """Return a vector array of the x, y, and z coordinates. Parameters ---------- xyz_axis : int, optional The axis in the final array along which the x, y, z components should be stored (default: 0). Returns ------- xs : `~astropy.units.Quantity` With dimension 3 along ``xyz_axis``. """ # Add new axis in x, y, z so one can concatenate them around it. # NOTE: just use np.stack once our minimum numpy version is 1.10. result_ndim = self.ndim + 1 if not -result_ndim <= xyz_axis < result_ndim: raise IndexError('xyz_axis {0} out of bounds [-{1}, {1})' .format(xyz_axis, result_ndim)) if xyz_axis < 0: xyz_axis += result_ndim # Get components to the same units (very fast for identical units) # since np.concatenate cannot deal with quantity. unit = self._x1.unit sh = self.shape sh = sh[:xyz_axis] + (1,) + sh[xyz_axis:] components = [getattr(self, '_'+name).reshape(sh).to(unit).value for name in self.attr_classes] xs_value = np.concatenate(components, axis=xyz_axis) return u.Quantity(xs_value, unit=unit, copy=False)
python
def get_xyz(self, xyz_axis=0): """Return a vector array of the x, y, and z coordinates. Parameters ---------- xyz_axis : int, optional The axis in the final array along which the x, y, z components should be stored (default: 0). Returns ------- xs : `~astropy.units.Quantity` With dimension 3 along ``xyz_axis``. """ # Add new axis in x, y, z so one can concatenate them around it. # NOTE: just use np.stack once our minimum numpy version is 1.10. result_ndim = self.ndim + 1 if not -result_ndim <= xyz_axis < result_ndim: raise IndexError('xyz_axis {0} out of bounds [-{1}, {1})' .format(xyz_axis, result_ndim)) if xyz_axis < 0: xyz_axis += result_ndim # Get components to the same units (very fast for identical units) # since np.concatenate cannot deal with quantity. unit = self._x1.unit sh = self.shape sh = sh[:xyz_axis] + (1,) + sh[xyz_axis:] components = [getattr(self, '_'+name).reshape(sh).to(unit).value for name in self.attr_classes] xs_value = np.concatenate(components, axis=xyz_axis) return u.Quantity(xs_value, unit=unit, copy=False)
[ "def", "get_xyz", "(", "self", ",", "xyz_axis", "=", "0", ")", ":", "# Add new axis in x, y, z so one can concatenate them around it.", "# NOTE: just use np.stack once our minimum numpy version is 1.10.", "result_ndim", "=", "self", ".", "ndim", "+", "1", "if", "not", "-", "result_ndim", "<=", "xyz_axis", "<", "result_ndim", ":", "raise", "IndexError", "(", "'xyz_axis {0} out of bounds [-{1}, {1})'", ".", "format", "(", "xyz_axis", ",", "result_ndim", ")", ")", "if", "xyz_axis", "<", "0", ":", "xyz_axis", "+=", "result_ndim", "# Get components to the same units (very fast for identical units)", "# since np.concatenate cannot deal with quantity.", "unit", "=", "self", ".", "_x1", ".", "unit", "sh", "=", "self", ".", "shape", "sh", "=", "sh", "[", ":", "xyz_axis", "]", "+", "(", "1", ",", ")", "+", "sh", "[", "xyz_axis", ":", "]", "components", "=", "[", "getattr", "(", "self", ",", "'_'", "+", "name", ")", ".", "reshape", "(", "sh", ")", ".", "to", "(", "unit", ")", ".", "value", "for", "name", "in", "self", ".", "attr_classes", "]", "xs_value", "=", "np", ".", "concatenate", "(", "components", ",", "axis", "=", "xyz_axis", ")", "return", "u", ".", "Quantity", "(", "xs_value", ",", "unit", "=", "unit", ",", "copy", "=", "False", ")" ]
Return a vector array of the x, y, and z coordinates. Parameters ---------- xyz_axis : int, optional The axis in the final array along which the x, y, z components should be stored (default: 0). Returns ------- xs : `~astropy.units.Quantity` With dimension 3 along ``xyz_axis``.
[ "Return", "a", "vector", "array", "of", "the", "x", "y", "and", "z", "coordinates", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/representation_nd.py#L100-L132
train
adrn/gala
gala/potential/common.py
CommonBase._get_c_valid_arr
def _get_c_valid_arr(self, x): """ Warning! Interpretation of axes is different for C code. """ orig_shape = x.shape x = np.ascontiguousarray(x.reshape(orig_shape[0], -1).T) return orig_shape, x
python
def _get_c_valid_arr(self, x): """ Warning! Interpretation of axes is different for C code. """ orig_shape = x.shape x = np.ascontiguousarray(x.reshape(orig_shape[0], -1).T) return orig_shape, x
[ "def", "_get_c_valid_arr", "(", "self", ",", "x", ")", ":", "orig_shape", "=", "x", ".", "shape", "x", "=", "np", ".", "ascontiguousarray", "(", "x", ".", "reshape", "(", "orig_shape", "[", "0", "]", ",", "-", "1", ")", ".", "T", ")", "return", "orig_shape", ",", "x" ]
Warning! Interpretation of axes is different for C code.
[ "Warning!", "Interpretation", "of", "axes", "is", "different", "for", "C", "code", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/common.py#L60-L66
train
adrn/gala
gala/potential/common.py
CommonBase._validate_prepare_time
def _validate_prepare_time(self, t, pos_c): """ Make sure that t is a 1D array and compatible with the C position array. """ if hasattr(t, 'unit'): t = t.decompose(self.units).value if not isiterable(t): t = np.atleast_1d(t) t = np.ascontiguousarray(t.ravel()) if len(t) > 1: if len(t) != pos_c.shape[0]: raise ValueError("If passing in an array of times, it must have a shape " "compatible with the input position(s).") return t
python
def _validate_prepare_time(self, t, pos_c): """ Make sure that t is a 1D array and compatible with the C position array. """ if hasattr(t, 'unit'): t = t.decompose(self.units).value if not isiterable(t): t = np.atleast_1d(t) t = np.ascontiguousarray(t.ravel()) if len(t) > 1: if len(t) != pos_c.shape[0]: raise ValueError("If passing in an array of times, it must have a shape " "compatible with the input position(s).") return t
[ "def", "_validate_prepare_time", "(", "self", ",", "t", ",", "pos_c", ")", ":", "if", "hasattr", "(", "t", ",", "'unit'", ")", ":", "t", "=", "t", ".", "decompose", "(", "self", ".", "units", ")", ".", "value", "if", "not", "isiterable", "(", "t", ")", ":", "t", "=", "np", ".", "atleast_1d", "(", "t", ")", "t", "=", "np", ".", "ascontiguousarray", "(", "t", ".", "ravel", "(", ")", ")", "if", "len", "(", "t", ")", ">", "1", ":", "if", "len", "(", "t", ")", "!=", "pos_c", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "\"If passing in an array of times, it must have a shape \"", "\"compatible with the input position(s).\"", ")", "return", "t" ]
Make sure that t is a 1D array and compatible with the C position array.
[ "Make", "sure", "that", "t", "is", "a", "1D", "array", "and", "compatible", "with", "the", "C", "position", "array", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/common.py#L68-L85
train
adrn/gala
gala/dynamics/core.py
PhaseSpacePosition.get_components
def get_components(self, which): """ Get the component name dictionary for the desired object. The returned dictionary maps component names on this class to component names on the desired object. Parameters ---------- which : str Can either be ``'pos'`` or ``'vel'`` to get the components for the position or velocity object. """ mappings = self.representation_mappings.get( getattr(self, which).__class__, []) old_to_new = dict() for name in getattr(self, which).components: for m in mappings: if isinstance(m, RegexRepresentationMapping): pattr = re.match(m.repr_name, name) old_to_new[name] = m.new_name.format(*pattr.groups()) elif m.repr_name == name: old_to_new[name] = m.new_name mapping = OrderedDict() for name in getattr(self, which).components: mapping[old_to_new.get(name, name)] = name return mapping
python
def get_components(self, which): """ Get the component name dictionary for the desired object. The returned dictionary maps component names on this class to component names on the desired object. Parameters ---------- which : str Can either be ``'pos'`` or ``'vel'`` to get the components for the position or velocity object. """ mappings = self.representation_mappings.get( getattr(self, which).__class__, []) old_to_new = dict() for name in getattr(self, which).components: for m in mappings: if isinstance(m, RegexRepresentationMapping): pattr = re.match(m.repr_name, name) old_to_new[name] = m.new_name.format(*pattr.groups()) elif m.repr_name == name: old_to_new[name] = m.new_name mapping = OrderedDict() for name in getattr(self, which).components: mapping[old_to_new.get(name, name)] = name return mapping
[ "def", "get_components", "(", "self", ",", "which", ")", ":", "mappings", "=", "self", ".", "representation_mappings", ".", "get", "(", "getattr", "(", "self", ",", "which", ")", ".", "__class__", ",", "[", "]", ")", "old_to_new", "=", "dict", "(", ")", "for", "name", "in", "getattr", "(", "self", ",", "which", ")", ".", "components", ":", "for", "m", "in", "mappings", ":", "if", "isinstance", "(", "m", ",", "RegexRepresentationMapping", ")", ":", "pattr", "=", "re", ".", "match", "(", "m", ".", "repr_name", ",", "name", ")", "old_to_new", "[", "name", "]", "=", "m", ".", "new_name", ".", "format", "(", "*", "pattr", ".", "groups", "(", ")", ")", "elif", "m", ".", "repr_name", "==", "name", ":", "old_to_new", "[", "name", "]", "=", "m", ".", "new_name", "mapping", "=", "OrderedDict", "(", ")", "for", "name", "in", "getattr", "(", "self", ",", "which", ")", ".", "components", ":", "mapping", "[", "old_to_new", ".", "get", "(", "name", ",", "name", ")", "]", "=", "name", "return", "mapping" ]
Get the component name dictionary for the desired object. The returned dictionary maps component names on this class to component names on the desired object. Parameters ---------- which : str Can either be ``'pos'`` or ``'vel'`` to get the components for the position or velocity object.
[ "Get", "the", "component", "name", "dictionary", "for", "the", "desired", "object", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/core.py#L196-L226
train
adrn/gala
gala/dynamics/core.py
PhaseSpacePosition.to_frame
def to_frame(self, frame, current_frame=None, **kwargs): """ Transform to a new reference frame. Parameters ---------- frame : `~gala.potential.FrameBase` The frame to transform to. current_frame : `gala.potential.CFrameBase` The current frame the phase-space position is in. **kwargs Any additional arguments are passed through to the individual frame transformation functions (see: `~gala.potential.frame.builtin.transformations`). Returns ------- psp : `gala.dynamics.CartesianPhaseSpacePosition` The phase-space position in the new reference frame. """ from ..potential.frame.builtin import transformations as frame_trans if ((inspect.isclass(frame) and issubclass(frame, coord.BaseCoordinateFrame)) or isinstance(frame, coord.BaseCoordinateFrame)): import warnings warnings.warn("This function now expects a " "`gala.potential.FrameBase` instance. To transform to" " an Astropy coordinate frame, use the " "`.to_coord_frame()` method instead.", DeprecationWarning) return self.to_coord_frame(frame=frame, **kwargs) if self.frame is None and current_frame is None: raise ValueError("If no frame was specified when this {} was " "initialized, you must pass the current frame in " "via the current_frame argument to transform to a " "new frame.") elif self.frame is not None and current_frame is None: current_frame = self.frame name1 = current_frame.__class__.__name__.rstrip('Frame').lower() name2 = frame.__class__.__name__.rstrip('Frame').lower() func_name = "{}_to_{}".format(name1, name2) if not hasattr(frame_trans, func_name): raise ValueError("Unsupported frame transformation: {} to {}" .format(current_frame, frame)) else: trans_func = getattr(frame_trans, func_name) pos, vel = trans_func(current_frame, frame, self, **kwargs) return PhaseSpacePosition(pos=pos, vel=vel, frame=frame)
python
def to_frame(self, frame, current_frame=None, **kwargs): """ Transform to a new reference frame. Parameters ---------- frame : `~gala.potential.FrameBase` The frame to transform to. current_frame : `gala.potential.CFrameBase` The current frame the phase-space position is in. **kwargs Any additional arguments are passed through to the individual frame transformation functions (see: `~gala.potential.frame.builtin.transformations`). Returns ------- psp : `gala.dynamics.CartesianPhaseSpacePosition` The phase-space position in the new reference frame. """ from ..potential.frame.builtin import transformations as frame_trans if ((inspect.isclass(frame) and issubclass(frame, coord.BaseCoordinateFrame)) or isinstance(frame, coord.BaseCoordinateFrame)): import warnings warnings.warn("This function now expects a " "`gala.potential.FrameBase` instance. To transform to" " an Astropy coordinate frame, use the " "`.to_coord_frame()` method instead.", DeprecationWarning) return self.to_coord_frame(frame=frame, **kwargs) if self.frame is None and current_frame is None: raise ValueError("If no frame was specified when this {} was " "initialized, you must pass the current frame in " "via the current_frame argument to transform to a " "new frame.") elif self.frame is not None and current_frame is None: current_frame = self.frame name1 = current_frame.__class__.__name__.rstrip('Frame').lower() name2 = frame.__class__.__name__.rstrip('Frame').lower() func_name = "{}_to_{}".format(name1, name2) if not hasattr(frame_trans, func_name): raise ValueError("Unsupported frame transformation: {} to {}" .format(current_frame, frame)) else: trans_func = getattr(frame_trans, func_name) pos, vel = trans_func(current_frame, frame, self, **kwargs) return PhaseSpacePosition(pos=pos, vel=vel, frame=frame)
[ "def", "to_frame", "(", "self", ",", "frame", ",", "current_frame", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", "potential", ".", "frame", ".", "builtin", "import", "transformations", "as", "frame_trans", "if", "(", "(", "inspect", ".", "isclass", "(", "frame", ")", "and", "issubclass", "(", "frame", ",", "coord", ".", "BaseCoordinateFrame", ")", ")", "or", "isinstance", "(", "frame", ",", "coord", ".", "BaseCoordinateFrame", ")", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"This function now expects a \"", "\"`gala.potential.FrameBase` instance. To transform to\"", "\" an Astropy coordinate frame, use the \"", "\"`.to_coord_frame()` method instead.\"", ",", "DeprecationWarning", ")", "return", "self", ".", "to_coord_frame", "(", "frame", "=", "frame", ",", "*", "*", "kwargs", ")", "if", "self", ".", "frame", "is", "None", "and", "current_frame", "is", "None", ":", "raise", "ValueError", "(", "\"If no frame was specified when this {} was \"", "\"initialized, you must pass the current frame in \"", "\"via the current_frame argument to transform to a \"", "\"new frame.\"", ")", "elif", "self", ".", "frame", "is", "not", "None", "and", "current_frame", "is", "None", ":", "current_frame", "=", "self", ".", "frame", "name1", "=", "current_frame", ".", "__class__", ".", "__name__", ".", "rstrip", "(", "'Frame'", ")", ".", "lower", "(", ")", "name2", "=", "frame", ".", "__class__", ".", "__name__", ".", "rstrip", "(", "'Frame'", ")", ".", "lower", "(", ")", "func_name", "=", "\"{}_to_{}\"", ".", "format", "(", "name1", ",", "name2", ")", "if", "not", "hasattr", "(", "frame_trans", ",", "func_name", ")", ":", "raise", "ValueError", "(", "\"Unsupported frame transformation: {} to {}\"", ".", "format", "(", "current_frame", ",", "frame", ")", ")", "else", ":", "trans_func", "=", "getattr", "(", "frame_trans", ",", "func_name", ")", "pos", ",", "vel", "=", "trans_func", "(", "current_frame", ",", "frame", ",", "self", ",", "*", "*", "kwargs", ")", "return", "PhaseSpacePosition", "(", "pos", "=", "pos", ",", "vel", "=", "vel", ",", "frame", "=", "frame", ")" ]
Transform to a new reference frame. Parameters ---------- frame : `~gala.potential.FrameBase` The frame to transform to. current_frame : `gala.potential.CFrameBase` The current frame the phase-space position is in. **kwargs Any additional arguments are passed through to the individual frame transformation functions (see: `~gala.potential.frame.builtin.transformations`). Returns ------- psp : `gala.dynamics.CartesianPhaseSpacePosition` The phase-space position in the new reference frame.
[ "Transform", "to", "a", "new", "reference", "frame", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/core.py#L348-L402
train
adrn/gala
gala/dynamics/core.py
PhaseSpacePosition.to_coord_frame
def to_coord_frame(self, frame, galactocentric_frame=None, **kwargs): """ Transform the orbit from Galactocentric, cartesian coordinates to Heliocentric coordinates in the specified Astropy coordinate frame. Parameters ---------- frame : :class:`~astropy.coordinates.BaseCoordinateFrame` The class or frame instance specifying the desired output frame. For example, :class:`~astropy.coordinates.ICRS`. galactocentric_frame : :class:`~astropy.coordinates.Galactocentric` This is the assumed frame that the position and velocity of this object are in. The ``Galactocentric`` instand should have parameters specifying the position and motion of the sun in the Galactocentric frame, but no data. Returns ------- c : :class:`~astropy.coordinates.BaseCoordinateFrame` An instantiated coordinate frame containing the positions and velocities from this object transformed to the specified coordinate frame. """ if self.ndim != 3: raise ValueError("Can only change representation for " "ndim=3 instances.") if galactocentric_frame is None: galactocentric_frame = coord.Galactocentric() if 'vcirc' in kwargs or 'vlsr' in kwargs: import warnings warnings.warn("Instead of passing in 'vcirc' and 'vlsr', specify " "these parameters to the input Galactocentric frame " "using the `galcen_v_sun` argument.", DeprecationWarning) pos_keys = list(self.pos_components.keys()) vel_keys = list(self.vel_components.keys()) if (getattr(self, pos_keys[0]).unit == u.one or getattr(self, vel_keys[0]).unit == u.one): raise u.UnitConversionError("Position and velocity must have " "dimensioned units to convert to a " "coordinate frame.") # first we need to turn the position into a Galactocentric instance gc_c = galactocentric_frame.realize_frame( self.pos.with_differentials(self.vel)) c = gc_c.transform_to(frame) return c
python
def to_coord_frame(self, frame, galactocentric_frame=None, **kwargs): """ Transform the orbit from Galactocentric, cartesian coordinates to Heliocentric coordinates in the specified Astropy coordinate frame. Parameters ---------- frame : :class:`~astropy.coordinates.BaseCoordinateFrame` The class or frame instance specifying the desired output frame. For example, :class:`~astropy.coordinates.ICRS`. galactocentric_frame : :class:`~astropy.coordinates.Galactocentric` This is the assumed frame that the position and velocity of this object are in. The ``Galactocentric`` instand should have parameters specifying the position and motion of the sun in the Galactocentric frame, but no data. Returns ------- c : :class:`~astropy.coordinates.BaseCoordinateFrame` An instantiated coordinate frame containing the positions and velocities from this object transformed to the specified coordinate frame. """ if self.ndim != 3: raise ValueError("Can only change representation for " "ndim=3 instances.") if galactocentric_frame is None: galactocentric_frame = coord.Galactocentric() if 'vcirc' in kwargs or 'vlsr' in kwargs: import warnings warnings.warn("Instead of passing in 'vcirc' and 'vlsr', specify " "these parameters to the input Galactocentric frame " "using the `galcen_v_sun` argument.", DeprecationWarning) pos_keys = list(self.pos_components.keys()) vel_keys = list(self.vel_components.keys()) if (getattr(self, pos_keys[0]).unit == u.one or getattr(self, vel_keys[0]).unit == u.one): raise u.UnitConversionError("Position and velocity must have " "dimensioned units to convert to a " "coordinate frame.") # first we need to turn the position into a Galactocentric instance gc_c = galactocentric_frame.realize_frame( self.pos.with_differentials(self.vel)) c = gc_c.transform_to(frame) return c
[ "def", "to_coord_frame", "(", "self", ",", "frame", ",", "galactocentric_frame", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "ndim", "!=", "3", ":", "raise", "ValueError", "(", "\"Can only change representation for \"", "\"ndim=3 instances.\"", ")", "if", "galactocentric_frame", "is", "None", ":", "galactocentric_frame", "=", "coord", ".", "Galactocentric", "(", ")", "if", "'vcirc'", "in", "kwargs", "or", "'vlsr'", "in", "kwargs", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"Instead of passing in 'vcirc' and 'vlsr', specify \"", "\"these parameters to the input Galactocentric frame \"", "\"using the `galcen_v_sun` argument.\"", ",", "DeprecationWarning", ")", "pos_keys", "=", "list", "(", "self", ".", "pos_components", ".", "keys", "(", ")", ")", "vel_keys", "=", "list", "(", "self", ".", "vel_components", ".", "keys", "(", ")", ")", "if", "(", "getattr", "(", "self", ",", "pos_keys", "[", "0", "]", ")", ".", "unit", "==", "u", ".", "one", "or", "getattr", "(", "self", ",", "vel_keys", "[", "0", "]", ")", ".", "unit", "==", "u", ".", "one", ")", ":", "raise", "u", ".", "UnitConversionError", "(", "\"Position and velocity must have \"", "\"dimensioned units to convert to a \"", "\"coordinate frame.\"", ")", "# first we need to turn the position into a Galactocentric instance", "gc_c", "=", "galactocentric_frame", ".", "realize_frame", "(", "self", ".", "pos", ".", "with_differentials", "(", "self", ".", "vel", ")", ")", "c", "=", "gc_c", ".", "transform_to", "(", "frame", ")", "return", "c" ]
Transform the orbit from Galactocentric, cartesian coordinates to Heliocentric coordinates in the specified Astropy coordinate frame. Parameters ---------- frame : :class:`~astropy.coordinates.BaseCoordinateFrame` The class or frame instance specifying the desired output frame. For example, :class:`~astropy.coordinates.ICRS`. galactocentric_frame : :class:`~astropy.coordinates.Galactocentric` This is the assumed frame that the position and velocity of this object are in. The ``Galactocentric`` instand should have parameters specifying the position and motion of the sun in the Galactocentric frame, but no data. Returns ------- c : :class:`~astropy.coordinates.BaseCoordinateFrame` An instantiated coordinate frame containing the positions and velocities from this object transformed to the specified coordinate frame.
[ "Transform", "the", "orbit", "from", "Galactocentric", "cartesian", "coordinates", "to", "Heliocentric", "coordinates", "in", "the", "specified", "Astropy", "coordinate", "frame", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/core.py#L404-L455
train
adrn/gala
gala/dynamics/core.py
PhaseSpacePosition._plot_prepare
def _plot_prepare(self, components, units): """ Prepare the ``PhaseSpacePosition`` or subclass for passing to a plotting routine to plot all projections of the object. """ # components to plot if components is None: components = self.pos.components n_comps = len(components) # if units not specified, get units from the components if units is not None: if isinstance(units, u.UnitBase): units = [units]*n_comps # global unit elif len(units) != n_comps: raise ValueError('You must specify a unit for each axis, or a ' 'single unit for all axes.') labels = [] x = [] for i,name in enumerate(components): val = getattr(self, name) if units is not None: val = val.to(units[i]) unit = units[i] else: unit = val.unit if val.unit != u.one: uu = unit.to_string(format='latex_inline') unit_str = ' [{}]'.format(uu) else: unit_str = '' # Figure out how to fancy display the component name if name.startswith('d_'): dot = True name = name[2:] else: dot = False if name in _greek_letters: name = r"\{}".format(name) if dot: name = "\dot{{{}}}".format(name) labels.append('${}$'.format(name) + unit_str) x.append(val.value) return x, labels
python
def _plot_prepare(self, components, units): """ Prepare the ``PhaseSpacePosition`` or subclass for passing to a plotting routine to plot all projections of the object. """ # components to plot if components is None: components = self.pos.components n_comps = len(components) # if units not specified, get units from the components if units is not None: if isinstance(units, u.UnitBase): units = [units]*n_comps # global unit elif len(units) != n_comps: raise ValueError('You must specify a unit for each axis, or a ' 'single unit for all axes.') labels = [] x = [] for i,name in enumerate(components): val = getattr(self, name) if units is not None: val = val.to(units[i]) unit = units[i] else: unit = val.unit if val.unit != u.one: uu = unit.to_string(format='latex_inline') unit_str = ' [{}]'.format(uu) else: unit_str = '' # Figure out how to fancy display the component name if name.startswith('d_'): dot = True name = name[2:] else: dot = False if name in _greek_letters: name = r"\{}".format(name) if dot: name = "\dot{{{}}}".format(name) labels.append('${}$'.format(name) + unit_str) x.append(val.value) return x, labels
[ "def", "_plot_prepare", "(", "self", ",", "components", ",", "units", ")", ":", "# components to plot", "if", "components", "is", "None", ":", "components", "=", "self", ".", "pos", ".", "components", "n_comps", "=", "len", "(", "components", ")", "# if units not specified, get units from the components", "if", "units", "is", "not", "None", ":", "if", "isinstance", "(", "units", ",", "u", ".", "UnitBase", ")", ":", "units", "=", "[", "units", "]", "*", "n_comps", "# global unit", "elif", "len", "(", "units", ")", "!=", "n_comps", ":", "raise", "ValueError", "(", "'You must specify a unit for each axis, or a '", "'single unit for all axes.'", ")", "labels", "=", "[", "]", "x", "=", "[", "]", "for", "i", ",", "name", "in", "enumerate", "(", "components", ")", ":", "val", "=", "getattr", "(", "self", ",", "name", ")", "if", "units", "is", "not", "None", ":", "val", "=", "val", ".", "to", "(", "units", "[", "i", "]", ")", "unit", "=", "units", "[", "i", "]", "else", ":", "unit", "=", "val", ".", "unit", "if", "val", ".", "unit", "!=", "u", ".", "one", ":", "uu", "=", "unit", ".", "to_string", "(", "format", "=", "'latex_inline'", ")", "unit_str", "=", "' [{}]'", ".", "format", "(", "uu", ")", "else", ":", "unit_str", "=", "''", "# Figure out how to fancy display the component name", "if", "name", ".", "startswith", "(", "'d_'", ")", ":", "dot", "=", "True", "name", "=", "name", "[", "2", ":", "]", "else", ":", "dot", "=", "False", "if", "name", "in", "_greek_letters", ":", "name", "=", "r\"\\{}\"", ".", "format", "(", "name", ")", "if", "dot", ":", "name", "=", "\"\\dot{{{}}}\"", ".", "format", "(", "name", ")", "labels", ".", "append", "(", "'${}$'", ".", "format", "(", "name", ")", "+", "unit_str", ")", "x", ".", "append", "(", "val", ".", "value", ")", "return", "x", ",", "labels" ]
Prepare the ``PhaseSpacePosition`` or subclass for passing to a plotting routine to plot all projections of the object.
[ "Prepare", "the", "PhaseSpacePosition", "or", "subclass", "for", "passing", "to", "a", "plotting", "routine", "to", "plot", "all", "projections", "of", "the", "object", "." ]
ea95575a0df1581bb4b0986aebd6eea8438ab7eb
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/core.py#L723-L776
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.get_account_info
def get_account_info(self): ''' Get current account information The information then will be saved in `self.account` so that you can access the information like this: >>> hsclient = HSClient() >>> acct = hsclient.get_account_info() >>> print acct.email_address Returns: An Account object ''' request = self._get_request() response = request.get(self.ACCOUNT_INFO_URL) self.account.json_data = response["account"] return self.account
python
def get_account_info(self): ''' Get current account information The information then will be saved in `self.account` so that you can access the information like this: >>> hsclient = HSClient() >>> acct = hsclient.get_account_info() >>> print acct.email_address Returns: An Account object ''' request = self._get_request() response = request.get(self.ACCOUNT_INFO_URL) self.account.json_data = response["account"] return self.account
[ "def", "get_account_info", "(", "self", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "response", "=", "request", ".", "get", "(", "self", ".", "ACCOUNT_INFO_URL", ")", "self", ".", "account", ".", "json_data", "=", "response", "[", "\"account\"", "]", "return", "self", ".", "account" ]
Get current account information The information then will be saved in `self.account` so that you can access the information like this: >>> hsclient = HSClient() >>> acct = hsclient.get_account_info() >>> print acct.email_address Returns: An Account object
[ "Get", "current", "account", "information" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L210-L227
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.update_account_info
def update_account_info(self): ''' Update current account information At the moment you can only update your callback_url. Returns: An Account object ''' request = self._get_request() return request.post(self.ACCOUNT_UPDATE_URL, { 'callback_url': self.account.callback_url })
python
def update_account_info(self): ''' Update current account information At the moment you can only update your callback_url. Returns: An Account object ''' request = self._get_request() return request.post(self.ACCOUNT_UPDATE_URL, { 'callback_url': self.account.callback_url })
[ "def", "update_account_info", "(", "self", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "return", "request", ".", "post", "(", "self", ".", "ACCOUNT_UPDATE_URL", ",", "{", "'callback_url'", ":", "self", ".", "account", ".", "callback_url", "}", ")" ]
Update current account information At the moment you can only update your callback_url. Returns: An Account object
[ "Update", "current", "account", "information" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L231-L243
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.verify_account
def verify_account(self, email_address): ''' Verify whether a HelloSign Account exists Args: email_address (str): Email address for the account to verify Returns: True or False ''' request = self._get_request() resp = request.post(self.ACCOUNT_VERIFY_URL, { 'email_address': email_address }) return ('account' in resp)
python
def verify_account(self, email_address): ''' Verify whether a HelloSign Account exists Args: email_address (str): Email address for the account to verify Returns: True or False ''' request = self._get_request() resp = request.post(self.ACCOUNT_VERIFY_URL, { 'email_address': email_address }) return ('account' in resp)
[ "def", "verify_account", "(", "self", ",", "email_address", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "resp", "=", "request", ".", "post", "(", "self", ".", "ACCOUNT_VERIFY_URL", ",", "{", "'email_address'", ":", "email_address", "}", ")", "return", "(", "'account'", "in", "resp", ")" ]
Verify whether a HelloSign Account exists Args: email_address (str): Email address for the account to verify Returns: True or False
[ "Verify", "whether", "a", "HelloSign", "Account", "exists" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L245-L259
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.get_signature_request
def get_signature_request(self, signature_request_id, ux_version=None): ''' Get a signature request by its ID Args: signature_request_id (str): The id of the SignatureRequest to retrieve ux_version (int): UX version, either 1 (default) or 2. Returns: A SignatureRequest object ''' request = self._get_request() parameters = None if ux_version is not None: parameters = { 'ux_version': ux_version } return request.get(self.SIGNATURE_REQUEST_INFO_URL + signature_request_id, parameters=parameters)
python
def get_signature_request(self, signature_request_id, ux_version=None): ''' Get a signature request by its ID Args: signature_request_id (str): The id of the SignatureRequest to retrieve ux_version (int): UX version, either 1 (default) or 2. Returns: A SignatureRequest object ''' request = self._get_request() parameters = None if ux_version is not None: parameters = { 'ux_version': ux_version } return request.get(self.SIGNATURE_REQUEST_INFO_URL + signature_request_id, parameters=parameters)
[ "def", "get_signature_request", "(", "self", ",", "signature_request_id", ",", "ux_version", "=", "None", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "parameters", "=", "None", "if", "ux_version", "is", "not", "None", ":", "parameters", "=", "{", "'ux_version'", ":", "ux_version", "}", "return", "request", ".", "get", "(", "self", ".", "SIGNATURE_REQUEST_INFO_URL", "+", "signature_request_id", ",", "parameters", "=", "parameters", ")" ]
Get a signature request by its ID Args: signature_request_id (str): The id of the SignatureRequest to retrieve ux_version (int): UX version, either 1 (default) or 2. Returns: A SignatureRequest object
[ "Get", "a", "signature", "request", "by", "its", "ID" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L264-L286
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.get_signature_request_list
def get_signature_request_list(self, page=1, ux_version=None): ''' Get a list of SignatureRequest that you can access This includes SignatureRequests you have sent as well as received, but not ones that you have been CCed on. Args: page (int, optional): Which page number of the SignatureRequest list to return. Defaults to 1. ux_version (int): UX version, either 1 (default) or 2. Returns: A ResourceList object ''' request = self._get_request() parameters = { "page": page } if ux_version is not None: parameters['ux_version'] = ux_version return request.get(self.SIGNATURE_REQUEST_LIST_URL, parameters=parameters)
python
def get_signature_request_list(self, page=1, ux_version=None): ''' Get a list of SignatureRequest that you can access This includes SignatureRequests you have sent as well as received, but not ones that you have been CCed on. Args: page (int, optional): Which page number of the SignatureRequest list to return. Defaults to 1. ux_version (int): UX version, either 1 (default) or 2. Returns: A ResourceList object ''' request = self._get_request() parameters = { "page": page } if ux_version is not None: parameters['ux_version'] = ux_version return request.get(self.SIGNATURE_REQUEST_LIST_URL, parameters=parameters)
[ "def", "get_signature_request_list", "(", "self", ",", "page", "=", "1", ",", "ux_version", "=", "None", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "parameters", "=", "{", "\"page\"", ":", "page", "}", "if", "ux_version", "is", "not", "None", ":", "parameters", "[", "'ux_version'", "]", "=", "ux_version", "return", "request", ".", "get", "(", "self", ".", "SIGNATURE_REQUEST_LIST_URL", ",", "parameters", "=", "parameters", ")" ]
Get a list of SignatureRequest that you can access This includes SignatureRequests you have sent as well as received, but not ones that you have been CCed on. Args: page (int, optional): Which page number of the SignatureRequest list to return. Defaults to 1. ux_version (int): UX version, either 1 (default) or 2. Returns: A ResourceList object
[ "Get", "a", "list", "of", "SignatureRequest", "that", "you", "can", "access" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L289-L314
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.get_signature_request_file
def get_signature_request_file(self, signature_request_id, path_or_file=None, file_type=None, filename=None): ''' Download the PDF copy of the current documents Args: signature_request_id (str): Id of the signature request path_or_file (str or file): A writable File-like object or a full path to save the PDF file to. filename (str): [DEPRECATED] Filename to save the PDF file to. This should be a full path. file_type (str): Type of file to return. Either "pdf" for a single merged document or "zip" for a collection of individual documents. Defaults to "pdf" if not specified. Returns: True if file is downloaded and successfully written, False otherwise. ''' request = self._get_request() url = self.SIGNATURE_REQUEST_DOWNLOAD_PDF_URL + signature_request_id if file_type: url += '?file_type=%s' % file_type return request.get_file(url, path_or_file or filename)
python
def get_signature_request_file(self, signature_request_id, path_or_file=None, file_type=None, filename=None): ''' Download the PDF copy of the current documents Args: signature_request_id (str): Id of the signature request path_or_file (str or file): A writable File-like object or a full path to save the PDF file to. filename (str): [DEPRECATED] Filename to save the PDF file to. This should be a full path. file_type (str): Type of file to return. Either "pdf" for a single merged document or "zip" for a collection of individual documents. Defaults to "pdf" if not specified. Returns: True if file is downloaded and successfully written, False otherwise. ''' request = self._get_request() url = self.SIGNATURE_REQUEST_DOWNLOAD_PDF_URL + signature_request_id if file_type: url += '?file_type=%s' % file_type return request.get_file(url, path_or_file or filename)
[ "def", "get_signature_request_file", "(", "self", ",", "signature_request_id", ",", "path_or_file", "=", "None", ",", "file_type", "=", "None", ",", "filename", "=", "None", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "url", "=", "self", ".", "SIGNATURE_REQUEST_DOWNLOAD_PDF_URL", "+", "signature_request_id", "if", "file_type", ":", "url", "+=", "'?file_type=%s'", "%", "file_type", "return", "request", ".", "get_file", "(", "url", ",", "path_or_file", "or", "filename", ")" ]
Download the PDF copy of the current documents Args: signature_request_id (str): Id of the signature request path_or_file (str or file): A writable File-like object or a full path to save the PDF file to. filename (str): [DEPRECATED] Filename to save the PDF file to. This should be a full path. file_type (str): Type of file to return. Either "pdf" for a single merged document or "zip" for a collection of individual documents. Defaults to "pdf" if not specified. Returns: True if file is downloaded and successfully written, False otherwise.
[ "Download", "the", "PDF", "copy", "of", "the", "current", "documents" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L316-L337
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.send_signature_request
def send_signature_request(self, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, metadata=None, ux_version=None, allow_decline=False): ''' Creates and sends a new SignatureRequest with the submitted documents Creates and sends a new SignatureRequest with the submitted documents. If form_fields_per_document is not specified, a signature page will be affixed where all signers will be required to add their signature, signifying their agreement to all contained documents. Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. files (list of str): The uploaded file(s) to send for signature file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls` title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: name (str): The name of the signer email_address (str): Email address of the signer order (str, optional): The order the signer is required to sign in pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page cc_email_addresses (list, optional): A list of email addresses that should be CC'd form_fields_per_document (str): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest) use_text_tags (bool, optional): Use text tags in the provided file(s) to create form fields hide_text_tags (bool, optional): Hide text tag areas metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline(bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object ''' self._check_required_fields({ "signers": signers }, [{ "files": files, "file_urls": file_urls }] ) params = { 'test_mode': test_mode, 'files': files, 'file_urls': file_urls, 'title': title, 'subject': subject, 'message': message, 'signing_redirect_url': signing_redirect_url, 'signers': signers, 'cc_email_addresses': cc_email_addresses, 'form_fields_per_document': form_fields_per_document, 'use_text_tags': use_text_tags, 'hide_text_tags': hide_text_tags, 'metadata': metadata, 'allow_decline': allow_decline } if ux_version is not None: params['ux_version'] = ux_version return self._send_signature_request(**params)
python
def send_signature_request(self, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, metadata=None, ux_version=None, allow_decline=False): ''' Creates and sends a new SignatureRequest with the submitted documents Creates and sends a new SignatureRequest with the submitted documents. If form_fields_per_document is not specified, a signature page will be affixed where all signers will be required to add their signature, signifying their agreement to all contained documents. Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. files (list of str): The uploaded file(s) to send for signature file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls` title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: name (str): The name of the signer email_address (str): Email address of the signer order (str, optional): The order the signer is required to sign in pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page cc_email_addresses (list, optional): A list of email addresses that should be CC'd form_fields_per_document (str): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest) use_text_tags (bool, optional): Use text tags in the provided file(s) to create form fields hide_text_tags (bool, optional): Hide text tag areas metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline(bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object ''' self._check_required_fields({ "signers": signers }, [{ "files": files, "file_urls": file_urls }] ) params = { 'test_mode': test_mode, 'files': files, 'file_urls': file_urls, 'title': title, 'subject': subject, 'message': message, 'signing_redirect_url': signing_redirect_url, 'signers': signers, 'cc_email_addresses': cc_email_addresses, 'form_fields_per_document': form_fields_per_document, 'use_text_tags': use_text_tags, 'hide_text_tags': hide_text_tags, 'metadata': metadata, 'allow_decline': allow_decline } if ux_version is not None: params['ux_version'] = ux_version return self._send_signature_request(**params)
[ "def", "send_signature_request", "(", "self", ",", "test_mode", "=", "False", ",", "files", "=", "None", ",", "file_urls", "=", "None", ",", "title", "=", "None", ",", "subject", "=", "None", ",", "message", "=", "None", ",", "signing_redirect_url", "=", "None", ",", "signers", "=", "None", ",", "cc_email_addresses", "=", "None", ",", "form_fields_per_document", "=", "None", ",", "use_text_tags", "=", "False", ",", "hide_text_tags", "=", "False", ",", "metadata", "=", "None", ",", "ux_version", "=", "None", ",", "allow_decline", "=", "False", ")", ":", "self", ".", "_check_required_fields", "(", "{", "\"signers\"", ":", "signers", "}", ",", "[", "{", "\"files\"", ":", "files", ",", "\"file_urls\"", ":", "file_urls", "}", "]", ")", "params", "=", "{", "'test_mode'", ":", "test_mode", ",", "'files'", ":", "files", ",", "'file_urls'", ":", "file_urls", ",", "'title'", ":", "title", ",", "'subject'", ":", "subject", ",", "'message'", ":", "message", ",", "'signing_redirect_url'", ":", "signing_redirect_url", ",", "'signers'", ":", "signers", ",", "'cc_email_addresses'", ":", "cc_email_addresses", ",", "'form_fields_per_document'", ":", "form_fields_per_document", ",", "'use_text_tags'", ":", "use_text_tags", ",", "'hide_text_tags'", ":", "hide_text_tags", ",", "'metadata'", ":", "metadata", ",", "'allow_decline'", ":", "allow_decline", "}", "if", "ux_version", "is", "not", "None", ":", "params", "[", "'ux_version'", "]", "=", "ux_version", "return", "self", ".", "_send_signature_request", "(", "*", "*", "params", ")" ]
Creates and sends a new SignatureRequest with the submitted documents Creates and sends a new SignatureRequest with the submitted documents. If form_fields_per_document is not specified, a signature page will be affixed where all signers will be required to add their signature, signifying their agreement to all contained documents. Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. files (list of str): The uploaded file(s) to send for signature file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls` title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: name (str): The name of the signer email_address (str): Email address of the signer order (str, optional): The order the signer is required to sign in pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page cc_email_addresses (list, optional): A list of email addresses that should be CC'd form_fields_per_document (str): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest) use_text_tags (bool, optional): Use text tags in the provided file(s) to create form fields hide_text_tags (bool, optional): Hide text tag areas metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline(bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object
[ "Creates", "and", "sends", "a", "new", "SignatureRequest", "with", "the", "submitted", "documents" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L339-L417
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.send_signature_request_with_template
def send_signature_request_with_template(self, test_mode=False, template_id=None, template_ids=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, ccs=None, custom_fields=None, metadata=None, ux_version=None, allow_decline=False): ''' Creates and sends a new SignatureRequest based off of a Template Creates and sends a new SignatureRequest based off of the Template specified with the template_id parameter. Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. template_id (str): The id of the Template to use when creating the SignatureRequest. Mutually exclusive with template_ids. template_ids (list): The ids of the Templates to use when creating the SignatureRequest. Mutually exclusive with template_id. title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: role_name (str): Signer role name (str): The name of the signer email_address (str): Email address of the signer pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page ccs (list of str, optional): The email address of the CC filling the role of RoleName. Required when a CC role exists for the Template. Each dict has the following attributes: role_name (str): CC role name email_address (str): CC email address custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}` metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object ''' self._check_required_fields({ "signers": signers }, [{ "template_id": template_id, "template_ids": template_ids }] ) params = { 'test_mode': test_mode, 'template_id': template_id, 'template_ids': template_ids, 'title': title, 'subject': subject, 'message': message, 'signing_redirect_url': signing_redirect_url, 'signers': signers, 'ccs': ccs, 'custom_fields': custom_fields, 'metadata': metadata, 'allow_decline': allow_decline } if ux_version is not None: params['ux_version'] = ux_version return self._send_signature_request_with_template(**params)
python
def send_signature_request_with_template(self, test_mode=False, template_id=None, template_ids=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, ccs=None, custom_fields=None, metadata=None, ux_version=None, allow_decline=False): ''' Creates and sends a new SignatureRequest based off of a Template Creates and sends a new SignatureRequest based off of the Template specified with the template_id parameter. Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. template_id (str): The id of the Template to use when creating the SignatureRequest. Mutually exclusive with template_ids. template_ids (list): The ids of the Templates to use when creating the SignatureRequest. Mutually exclusive with template_id. title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: role_name (str): Signer role name (str): The name of the signer email_address (str): Email address of the signer pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page ccs (list of str, optional): The email address of the CC filling the role of RoleName. Required when a CC role exists for the Template. Each dict has the following attributes: role_name (str): CC role name email_address (str): CC email address custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}` metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object ''' self._check_required_fields({ "signers": signers }, [{ "template_id": template_id, "template_ids": template_ids }] ) params = { 'test_mode': test_mode, 'template_id': template_id, 'template_ids': template_ids, 'title': title, 'subject': subject, 'message': message, 'signing_redirect_url': signing_redirect_url, 'signers': signers, 'ccs': ccs, 'custom_fields': custom_fields, 'metadata': metadata, 'allow_decline': allow_decline } if ux_version is not None: params['ux_version'] = ux_version return self._send_signature_request_with_template(**params)
[ "def", "send_signature_request_with_template", "(", "self", ",", "test_mode", "=", "False", ",", "template_id", "=", "None", ",", "template_ids", "=", "None", ",", "title", "=", "None", ",", "subject", "=", "None", ",", "message", "=", "None", ",", "signing_redirect_url", "=", "None", ",", "signers", "=", "None", ",", "ccs", "=", "None", ",", "custom_fields", "=", "None", ",", "metadata", "=", "None", ",", "ux_version", "=", "None", ",", "allow_decline", "=", "False", ")", ":", "self", ".", "_check_required_fields", "(", "{", "\"signers\"", ":", "signers", "}", ",", "[", "{", "\"template_id\"", ":", "template_id", ",", "\"template_ids\"", ":", "template_ids", "}", "]", ")", "params", "=", "{", "'test_mode'", ":", "test_mode", ",", "'template_id'", ":", "template_id", ",", "'template_ids'", ":", "template_ids", ",", "'title'", ":", "title", ",", "'subject'", ":", "subject", ",", "'message'", ":", "message", ",", "'signing_redirect_url'", ":", "signing_redirect_url", ",", "'signers'", ":", "signers", ",", "'ccs'", ":", "ccs", ",", "'custom_fields'", ":", "custom_fields", ",", "'metadata'", ":", "metadata", ",", "'allow_decline'", ":", "allow_decline", "}", "if", "ux_version", "is", "not", "None", ":", "params", "[", "'ux_version'", "]", "=", "ux_version", "return", "self", ".", "_send_signature_request_with_template", "(", "*", "*", "params", ")" ]
Creates and sends a new SignatureRequest based off of a Template Creates and sends a new SignatureRequest based off of the Template specified with the template_id parameter. Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. template_id (str): The id of the Template to use when creating the SignatureRequest. Mutually exclusive with template_ids. template_ids (list): The ids of the Templates to use when creating the SignatureRequest. Mutually exclusive with template_id. title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: role_name (str): Signer role name (str): The name of the signer email_address (str): Email address of the signer pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page ccs (list of str, optional): The email address of the CC filling the role of RoleName. Required when a CC role exists for the Template. Each dict has the following attributes: role_name (str): CC role name email_address (str): CC email address custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}` metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object
[ "Creates", "and", "sends", "a", "new", "SignatureRequest", "based", "off", "of", "a", "Template" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L419-L492
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.remind_signature_request
def remind_signature_request(self, signature_request_id, email_address): ''' Sends an email to the signer reminding them to sign the signature request Sends an email to the signer reminding them to sign the signature request. You cannot send a reminder within 1 hours of the last reminder that was sent. This includes manual AND automatic reminders. Args: signature_request_id (str): The id of the SignatureRequest to send a reminder for email_address (str): The email address of the signer to send a reminder to Returns: A SignatureRequest object ''' request = self._get_request() return request.post(self.SIGNATURE_REQUEST_REMIND_URL + signature_request_id, data={ "email_address": email_address })
python
def remind_signature_request(self, signature_request_id, email_address): ''' Sends an email to the signer reminding them to sign the signature request Sends an email to the signer reminding them to sign the signature request. You cannot send a reminder within 1 hours of the last reminder that was sent. This includes manual AND automatic reminders. Args: signature_request_id (str): The id of the SignatureRequest to send a reminder for email_address (str): The email address of the signer to send a reminder to Returns: A SignatureRequest object ''' request = self._get_request() return request.post(self.SIGNATURE_REQUEST_REMIND_URL + signature_request_id, data={ "email_address": email_address })
[ "def", "remind_signature_request", "(", "self", ",", "signature_request_id", ",", "email_address", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "return", "request", ".", "post", "(", "self", ".", "SIGNATURE_REQUEST_REMIND_URL", "+", "signature_request_id", ",", "data", "=", "{", "\"email_address\"", ":", "email_address", "}", ")" ]
Sends an email to the signer reminding them to sign the signature request Sends an email to the signer reminding them to sign the signature request. You cannot send a reminder within 1 hours of the last reminder that was sent. This includes manual AND automatic reminders. Args: signature_request_id (str): The id of the SignatureRequest to send a reminder for email_address (str): The email address of the signer to send a reminder to Returns: A SignatureRequest object
[ "Sends", "an", "email", "to", "the", "signer", "reminding", "them", "to", "sign", "the", "signature", "request" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L495-L515
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.cancel_signature_request
def cancel_signature_request(self, signature_request_id): ''' Cancels a SignatureRequest Cancels a SignatureRequest. After canceling, no one will be able to sign or access the SignatureRequest or its documents. Only the requester can cancel and only before everyone has signed. Args: signing_request_id (str): The id of the signature request to cancel Returns: None ''' request = self._get_request() request.post(url=self.SIGNATURE_REQUEST_CANCEL_URL + signature_request_id, get_json=False)
python
def cancel_signature_request(self, signature_request_id): ''' Cancels a SignatureRequest Cancels a SignatureRequest. After canceling, no one will be able to sign or access the SignatureRequest or its documents. Only the requester can cancel and only before everyone has signed. Args: signing_request_id (str): The id of the signature request to cancel Returns: None ''' request = self._get_request() request.post(url=self.SIGNATURE_REQUEST_CANCEL_URL + signature_request_id, get_json=False)
[ "def", "cancel_signature_request", "(", "self", ",", "signature_request_id", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "request", ".", "post", "(", "url", "=", "self", ".", "SIGNATURE_REQUEST_CANCEL_URL", "+", "signature_request_id", ",", "get_json", "=", "False", ")" ]
Cancels a SignatureRequest Cancels a SignatureRequest. After canceling, no one will be able to sign or access the SignatureRequest or its documents. Only the requester can cancel and only before everyone has signed. Args: signing_request_id (str): The id of the signature request to cancel Returns: None
[ "Cancels", "a", "SignatureRequest" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L517-L533
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.get_template
def get_template(self, template_id): ''' Gets a Template which includes a list of Accounts that can access it Args: template_id (str): The id of the template to retrieve Returns: A Template object ''' request = self._get_request() return request.get(self.TEMPLATE_GET_URL + template_id)
python
def get_template(self, template_id): ''' Gets a Template which includes a list of Accounts that can access it Args: template_id (str): The id of the template to retrieve Returns: A Template object ''' request = self._get_request() return request.get(self.TEMPLATE_GET_URL + template_id)
[ "def", "get_template", "(", "self", ",", "template_id", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "return", "request", ".", "get", "(", "self", ".", "TEMPLATE_GET_URL", "+", "template_id", ")" ]
Gets a Template which includes a list of Accounts that can access it Args: template_id (str): The id of the template to retrieve Returns: A Template object
[ "Gets", "a", "Template", "which", "includes", "a", "list", "of", "Accounts", "that", "can", "access", "it" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L705-L717
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.get_template_list
def get_template_list(self, page=1, page_size=None, account_id=None, query=None): ''' Lists your Templates Args: page (int, optional): Page number of the template List to return. Defaults to 1. page_size (int, optional): Number of objects to be returned per page, must be between 1 and 100, default is 20. account_id (str, optional): Which account to return Templates for. Must be a team member. Use "all" to indicate all team members. Defaults to your account. query (str, optional): String that includes search terms and/or fields to be used to filter the Template objects. Returns: A ResourceList object ''' request = self._get_request() parameters = { 'page': page, 'page_size': page_size, 'account_id': account_id, 'query': query } return request.get(self.TEMPLATE_GET_LIST_URL, parameters=parameters)
python
def get_template_list(self, page=1, page_size=None, account_id=None, query=None): ''' Lists your Templates Args: page (int, optional): Page number of the template List to return. Defaults to 1. page_size (int, optional): Number of objects to be returned per page, must be between 1 and 100, default is 20. account_id (str, optional): Which account to return Templates for. Must be a team member. Use "all" to indicate all team members. Defaults to your account. query (str, optional): String that includes search terms and/or fields to be used to filter the Template objects. Returns: A ResourceList object ''' request = self._get_request() parameters = { 'page': page, 'page_size': page_size, 'account_id': account_id, 'query': query } return request.get(self.TEMPLATE_GET_LIST_URL, parameters=parameters)
[ "def", "get_template_list", "(", "self", ",", "page", "=", "1", ",", "page_size", "=", "None", ",", "account_id", "=", "None", ",", "query", "=", "None", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "parameters", "=", "{", "'page'", ":", "page", ",", "'page_size'", ":", "page_size", ",", "'account_id'", ":", "account_id", ",", "'query'", ":", "query", "}", "return", "request", ".", "get", "(", "self", ".", "TEMPLATE_GET_LIST_URL", ",", "parameters", "=", "parameters", ")" ]
Lists your Templates Args: page (int, optional): Page number of the template List to return. Defaults to 1. page_size (int, optional): Number of objects to be returned per page, must be between 1 and 100, default is 20. account_id (str, optional): Which account to return Templates for. Must be a team member. Use "all" to indicate all team members. Defaults to your account. query (str, optional): String that includes search terms and/or fields to be used to filter the Template objects. Returns: A ResourceList object
[ "Lists", "your", "Templates" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L720-L741
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.add_user_to_template
def add_user_to_template(self, template_id, account_id=None, email_address=None): ''' Gives the specified Account access to the specified Template Args: template_id (str): The id of the template to give the account access to account_id (str): The id of the account to give access to the template. The account id prevails if both account_id and email_address are provided. email_address (str): The email address of the account to give access to. Returns: A Template object ''' return self._add_remove_user_template(self.TEMPLATE_ADD_USER_URL, template_id, account_id, email_address)
python
def add_user_to_template(self, template_id, account_id=None, email_address=None): ''' Gives the specified Account access to the specified Template Args: template_id (str): The id of the template to give the account access to account_id (str): The id of the account to give access to the template. The account id prevails if both account_id and email_address are provided. email_address (str): The email address of the account to give access to. Returns: A Template object ''' return self._add_remove_user_template(self.TEMPLATE_ADD_USER_URL, template_id, account_id, email_address)
[ "def", "add_user_to_template", "(", "self", ",", "template_id", ",", "account_id", "=", "None", ",", "email_address", "=", "None", ")", ":", "return", "self", ".", "_add_remove_user_template", "(", "self", ".", "TEMPLATE_ADD_USER_URL", ",", "template_id", ",", "account_id", ",", "email_address", ")" ]
Gives the specified Account access to the specified Template Args: template_id (str): The id of the template to give the account access to account_id (str): The id of the account to give access to the template. The account id prevails if both account_id and email_address are provided. email_address (str): The email address of the account to give access to. Returns: A Template object
[ "Gives", "the", "specified", "Account", "access", "to", "the", "specified", "Template" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L744-L759
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.remove_user_from_template
def remove_user_from_template(self, template_id, account_id=None, email_address=None): ''' Removes the specified Account's access to the specified Template Args: template_id (str): The id of the template to remove the account's access from. account_id (str): The id of the account to remove access from the template. The account id prevails if both account_id and email_address are provided. email_address (str): The email address of the account to remove access from. Returns: An Template object ''' return self._add_remove_user_template(self.TEMPLATE_REMOVE_USER_URL, template_id, account_id, email_address)
python
def remove_user_from_template(self, template_id, account_id=None, email_address=None): ''' Removes the specified Account's access to the specified Template Args: template_id (str): The id of the template to remove the account's access from. account_id (str): The id of the account to remove access from the template. The account id prevails if both account_id and email_address are provided. email_address (str): The email address of the account to remove access from. Returns: An Template object ''' return self._add_remove_user_template(self.TEMPLATE_REMOVE_USER_URL, template_id, account_id, email_address)
[ "def", "remove_user_from_template", "(", "self", ",", "template_id", ",", "account_id", "=", "None", ",", "email_address", "=", "None", ")", ":", "return", "self", ".", "_add_remove_user_template", "(", "self", ".", "TEMPLATE_REMOVE_USER_URL", ",", "template_id", ",", "account_id", ",", "email_address", ")" ]
Removes the specified Account's access to the specified Template Args: template_id (str): The id of the template to remove the account's access from. account_id (str): The id of the account to remove access from the template. The account id prevails if both account_id and email_address are provided. email_address (str): The email address of the account to remove access from. Returns: An Template object
[ "Removes", "the", "specified", "Account", "s", "access", "to", "the", "specified", "Template" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L761-L776
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.delete_template
def delete_template(self, template_id): ''' Deletes the specified template Args: template_id (str): The id of the template to delete Returns: A status code ''' url = self.TEMPLATE_DELETE_URL request = self._get_request() response = request.post(url + template_id, get_json=False) return response
python
def delete_template(self, template_id): ''' Deletes the specified template Args: template_id (str): The id of the template to delete Returns: A status code ''' url = self.TEMPLATE_DELETE_URL request = self._get_request() response = request.post(url + template_id, get_json=False) return response
[ "def", "delete_template", "(", "self", ",", "template_id", ")", ":", "url", "=", "self", ".", "TEMPLATE_DELETE_URL", "request", "=", "self", ".", "_get_request", "(", ")", "response", "=", "request", ".", "post", "(", "url", "+", "template_id", ",", "get_json", "=", "False", ")", "return", "response" ]
Deletes the specified template Args: template_id (str): The id of the template to delete Returns: A status code
[ "Deletes", "the", "specified", "template" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L778-L795
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.get_template_files
def get_template_files(self, template_id, filename): ''' Download a PDF copy of a template's original files Args: template_id (str): The id of the template to retrieve. filename (str): Filename to save the PDF file to. This should be a full path. Returns: Returns a PDF file ''' url = self.TEMPLATE_GET_FILES_URL + template_id request = self._get_request() return request.get_file(url, filename)
python
def get_template_files(self, template_id, filename): ''' Download a PDF copy of a template's original files Args: template_id (str): The id of the template to retrieve. filename (str): Filename to save the PDF file to. This should be a full path. Returns: Returns a PDF file ''' url = self.TEMPLATE_GET_FILES_URL + template_id request = self._get_request() return request.get_file(url, filename)
[ "def", "get_template_files", "(", "self", ",", "template_id", ",", "filename", ")", ":", "url", "=", "self", ".", "TEMPLATE_GET_FILES_URL", "+", "template_id", "request", "=", "self", ".", "_get_request", "(", ")", "return", "request", ".", "get_file", "(", "url", ",", "filename", ")" ]
Download a PDF copy of a template's original files Args: template_id (str): The id of the template to retrieve. filename (str): Filename to save the PDF file to. This should be a full path. Returns: Returns a PDF file
[ "Download", "a", "PDF", "copy", "of", "a", "template", "s", "original", "files" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L798-L815
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.create_embedded_template_draft
def create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False): ''' Creates an embedded Template draft for further editing. Args: test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to 1. Defaults to 0. client_id (str): Client id of the app you're using to create this draft. files (list of str): The file(s) to use for the template. file_urls (list of str): URLs of the file for HelloSign to use for the template. Use either `files` or `file_urls`, but not both. title (str, optional): The template title subject (str, optional): The default template email subject message (str, optional): The default template email message signer_roles (list of dict): A list of signer roles, each of which has the following attributes: name (str): The role name of the signer that will be displayed when the template is used to create a signature request. order (str, optional): The order in which this signer role is required to sign. cc_roles (list of str, optional): The CC roles that must be assigned when using the template to send a signature request merge_fields (list of dict, optional): The merge fields that can be placed on the template's document(s) by the user claiming the template draft. Each must have the following two parameters: name (str): The name of the merge field. Must be unique. type (str): Can only be "text" or "checkbox". use_preexisting_fields (bool): Whether to use preexisting PDF fields Returns: A Template object specifying the Id of the draft ''' params = { 'test_mode': test_mode, 'client_id': client_id, 'files': files, 'file_urls': file_urls, 'title': title, 'subject': subject, 'message': message, 'signer_roles': signer_roles, 'cc_roles': cc_roles, 'merge_fields': merge_fields, 'use_preexisting_fields': use_preexisting_fields } return self._create_embedded_template_draft(**params)
python
def create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False): ''' Creates an embedded Template draft for further editing. Args: test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to 1. Defaults to 0. client_id (str): Client id of the app you're using to create this draft. files (list of str): The file(s) to use for the template. file_urls (list of str): URLs of the file for HelloSign to use for the template. Use either `files` or `file_urls`, but not both. title (str, optional): The template title subject (str, optional): The default template email subject message (str, optional): The default template email message signer_roles (list of dict): A list of signer roles, each of which has the following attributes: name (str): The role name of the signer that will be displayed when the template is used to create a signature request. order (str, optional): The order in which this signer role is required to sign. cc_roles (list of str, optional): The CC roles that must be assigned when using the template to send a signature request merge_fields (list of dict, optional): The merge fields that can be placed on the template's document(s) by the user claiming the template draft. Each must have the following two parameters: name (str): The name of the merge field. Must be unique. type (str): Can only be "text" or "checkbox". use_preexisting_fields (bool): Whether to use preexisting PDF fields Returns: A Template object specifying the Id of the draft ''' params = { 'test_mode': test_mode, 'client_id': client_id, 'files': files, 'file_urls': file_urls, 'title': title, 'subject': subject, 'message': message, 'signer_roles': signer_roles, 'cc_roles': cc_roles, 'merge_fields': merge_fields, 'use_preexisting_fields': use_preexisting_fields } return self._create_embedded_template_draft(**params)
[ "def", "create_embedded_template_draft", "(", "self", ",", "client_id", ",", "signer_roles", ",", "test_mode", "=", "False", ",", "files", "=", "None", ",", "file_urls", "=", "None", ",", "title", "=", "None", ",", "subject", "=", "None", ",", "message", "=", "None", ",", "cc_roles", "=", "None", ",", "merge_fields", "=", "None", ",", "use_preexisting_fields", "=", "False", ")", ":", "params", "=", "{", "'test_mode'", ":", "test_mode", ",", "'client_id'", ":", "client_id", ",", "'files'", ":", "files", ",", "'file_urls'", ":", "file_urls", ",", "'title'", ":", "title", ",", "'subject'", ":", "subject", ",", "'message'", ":", "message", ",", "'signer_roles'", ":", "signer_roles", ",", "'cc_roles'", ":", "cc_roles", ",", "'merge_fields'", ":", "merge_fields", ",", "'use_preexisting_fields'", ":", "use_preexisting_fields", "}", "return", "self", ".", "_create_embedded_template_draft", "(", "*", "*", "params", ")" ]
Creates an embedded Template draft for further editing. Args: test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to 1. Defaults to 0. client_id (str): Client id of the app you're using to create this draft. files (list of str): The file(s) to use for the template. file_urls (list of str): URLs of the file for HelloSign to use for the template. Use either `files` or `file_urls`, but not both. title (str, optional): The template title subject (str, optional): The default template email subject message (str, optional): The default template email message signer_roles (list of dict): A list of signer roles, each of which has the following attributes: name (str): The role name of the signer that will be displayed when the template is used to create a signature request. order (str, optional): The order in which this signer role is required to sign. cc_roles (list of str, optional): The CC roles that must be assigned when using the template to send a signature request merge_fields (list of dict, optional): The merge fields that can be placed on the template's document(s) by the user claiming the template draft. Each must have the following two parameters: name (str): The name of the merge field. Must be unique. type (str): Can only be "text" or "checkbox". use_preexisting_fields (bool): Whether to use preexisting PDF fields Returns: A Template object specifying the Id of the draft
[ "Creates", "an", "embedded", "Template", "draft", "for", "further", "editing", "." ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L817-L868
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.create_team
def create_team(self, name): ''' Creates a new Team Creates a new Team and makes you a member. You must not currently belong to a team to invoke. Args: name (str): The name of your team Returns: A Team object ''' request = self._get_request() return request.post(self.TEAM_CREATE_URL, {"name": name})
python
def create_team(self, name): ''' Creates a new Team Creates a new Team and makes you a member. You must not currently belong to a team to invoke. Args: name (str): The name of your team Returns: A Team object ''' request = self._get_request() return request.post(self.TEAM_CREATE_URL, {"name": name})
[ "def", "create_team", "(", "self", ",", "name", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "return", "request", ".", "post", "(", "self", ".", "TEAM_CREATE_URL", ",", "{", "\"name\"", ":", "name", "}", ")" ]
Creates a new Team Creates a new Team and makes you a member. You must not currently belong to a team to invoke. Args: name (str): The name of your team Returns: A Team object
[ "Creates", "a", "new", "Team" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L888-L902
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.update_team_name
def update_team_name(self, name): ''' Updates a Team's name Args: name (str): The new name of your team Returns: A Team object ''' request = self._get_request() return request.post(self.TEAM_UPDATE_URL, {"name": name})
python
def update_team_name(self, name): ''' Updates a Team's name Args: name (str): The new name of your team Returns: A Team object ''' request = self._get_request() return request.post(self.TEAM_UPDATE_URL, {"name": name})
[ "def", "update_team_name", "(", "self", ",", "name", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "return", "request", ".", "post", "(", "self", ".", "TEAM_UPDATE_URL", ",", "{", "\"name\"", ":", "name", "}", ")" ]
Updates a Team's name Args: name (str): The new name of your team Returns: A Team object
[ "Updates", "a", "Team", "s", "name" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L906-L918
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.destroy_team
def destroy_team(self): ''' Delete your Team Deletes your Team. Can only be invoked when you have a team with only one member left (yourself). Returns: None ''' request = self._get_request() request.post(url=self.TEAM_DESTROY_URL, get_json=False)
python
def destroy_team(self): ''' Delete your Team Deletes your Team. Can only be invoked when you have a team with only one member left (yourself). Returns: None ''' request = self._get_request() request.post(url=self.TEAM_DESTROY_URL, get_json=False)
[ "def", "destroy_team", "(", "self", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "request", ".", "post", "(", "url", "=", "self", ".", "TEAM_DESTROY_URL", ",", "get_json", "=", "False", ")" ]
Delete your Team Deletes your Team. Can only be invoked when you have a team with only one member left (yourself). Returns: None
[ "Delete", "your", "Team" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L920-L930
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.add_team_member
def add_team_member(self, account_id=None, email_address=None): ''' Add or invite a user to your Team Args: account_id (str): The id of the account of the user to invite to your team. email_address (str): The email address of the account to invite to your team. The account id prevails if both account_id and email_address are provided. Returns: A Team object ''' return self._add_remove_team_member(self.TEAM_ADD_MEMBER_URL, email_address, account_id)
python
def add_team_member(self, account_id=None, email_address=None): ''' Add or invite a user to your Team Args: account_id (str): The id of the account of the user to invite to your team. email_address (str): The email address of the account to invite to your team. The account id prevails if both account_id and email_address are provided. Returns: A Team object ''' return self._add_remove_team_member(self.TEAM_ADD_MEMBER_URL, email_address, account_id)
[ "def", "add_team_member", "(", "self", ",", "account_id", "=", "None", ",", "email_address", "=", "None", ")", ":", "return", "self", ".", "_add_remove_team_member", "(", "self", ".", "TEAM_ADD_MEMBER_URL", ",", "email_address", ",", "account_id", ")" ]
Add or invite a user to your Team Args: account_id (str): The id of the account of the user to invite to your team. email_address (str): The email address of the account to invite to your team. The account id prevails if both account_id and email_address are provided. Returns: A Team object
[ "Add", "or", "invite", "a", "user", "to", "your", "Team" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L932-L945
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.remove_team_member
def remove_team_member(self, account_id=None, email_address=None): ''' Remove a user from your Team Args: account_id (str): The id of the account of the user to remove from your team. email_address (str): The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided. Returns: A Team object ''' return self._add_remove_team_member(self.TEAM_REMOVE_MEMBER_URL, email_address, account_id)
python
def remove_team_member(self, account_id=None, email_address=None): ''' Remove a user from your Team Args: account_id (str): The id of the account of the user to remove from your team. email_address (str): The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided. Returns: A Team object ''' return self._add_remove_team_member(self.TEAM_REMOVE_MEMBER_URL, email_address, account_id)
[ "def", "remove_team_member", "(", "self", ",", "account_id", "=", "None", ",", "email_address", "=", "None", ")", ":", "return", "self", ".", "_add_remove_team_member", "(", "self", ".", "TEAM_REMOVE_MEMBER_URL", ",", "email_address", ",", "account_id", ")" ]
Remove a user from your Team Args: account_id (str): The id of the account of the user to remove from your team. email_address (str): The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided. Returns: A Team object
[ "Remove", "a", "user", "from", "your", "Team" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L948-L961
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.get_embedded_object
def get_embedded_object(self, signature_id): ''' Retrieves a embedded signing object Retrieves an embedded object containing a signature url that can be opened in an iFrame. Args: signature_id (str): The id of the signature to get a signature url for Returns: An Embedded object ''' request = self._get_request() return request.get(self.EMBEDDED_OBJECT_GET_URL + signature_id)
python
def get_embedded_object(self, signature_id): ''' Retrieves a embedded signing object Retrieves an embedded object containing a signature url that can be opened in an iFrame. Args: signature_id (str): The id of the signature to get a signature url for Returns: An Embedded object ''' request = self._get_request() return request.get(self.EMBEDDED_OBJECT_GET_URL + signature_id)
[ "def", "get_embedded_object", "(", "self", ",", "signature_id", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "return", "request", ".", "get", "(", "self", ".", "EMBEDDED_OBJECT_GET_URL", "+", "signature_id", ")" ]
Retrieves a embedded signing object Retrieves an embedded object containing a signature url that can be opened in an iFrame. Args: signature_id (str): The id of the signature to get a signature url for Returns: An Embedded object
[ "Retrieves", "a", "embedded", "signing", "object" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L966-L980
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.get_template_edit_url
def get_template_edit_url(self, template_id): ''' Retrieves a embedded template for editing Retrieves an embedded object containing a template url that can be opened in an iFrame. Args: template_id (str): The id of the template to get a signature url for Returns: An Embedded object ''' request = self._get_request() return request.get(self.EMBEDDED_TEMPLATE_EDIT_URL + template_id)
python
def get_template_edit_url(self, template_id): ''' Retrieves a embedded template for editing Retrieves an embedded object containing a template url that can be opened in an iFrame. Args: template_id (str): The id of the template to get a signature url for Returns: An Embedded object ''' request = self._get_request() return request.get(self.EMBEDDED_TEMPLATE_EDIT_URL + template_id)
[ "def", "get_template_edit_url", "(", "self", ",", "template_id", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "return", "request", ".", "get", "(", "self", ".", "EMBEDDED_TEMPLATE_EDIT_URL", "+", "template_id", ")" ]
Retrieves a embedded template for editing Retrieves an embedded object containing a template url that can be opened in an iFrame. Args: template_id (str): The id of the template to get a signature url for Returns: An Embedded object
[ "Retrieves", "a", "embedded", "template", "for", "editing" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L983-L997
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.get_oauth_data
def get_oauth_data(self, code, client_id, client_secret, state): ''' Get Oauth data from HelloSign Args: code (str): Code returned by HelloSign for our callback url client_id (str): Client id of the associated app client_secret (str): Secret token of the associated app Returns: A HSAccessTokenAuth object ''' request = self._get_request() response = request.post(self.OAUTH_TOKEN_URL, { "state": state, "code": code, "grant_type": "authorization_code", "client_id": client_id, "client_secret": client_secret }) return HSAccessTokenAuth.from_response(response)
python
def get_oauth_data(self, code, client_id, client_secret, state): ''' Get Oauth data from HelloSign Args: code (str): Code returned by HelloSign for our callback url client_id (str): Client id of the associated app client_secret (str): Secret token of the associated app Returns: A HSAccessTokenAuth object ''' request = self._get_request() response = request.post(self.OAUTH_TOKEN_URL, { "state": state, "code": code, "grant_type": "authorization_code", "client_id": client_id, "client_secret": client_secret }) return HSAccessTokenAuth.from_response(response)
[ "def", "get_oauth_data", "(", "self", ",", "code", ",", "client_id", ",", "client_secret", ",", "state", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "response", "=", "request", ".", "post", "(", "self", ".", "OAUTH_TOKEN_URL", ",", "{", "\"state\"", ":", "state", ",", "\"code\"", ":", "code", ",", "\"grant_type\"", ":", "\"authorization_code\"", ",", "\"client_id\"", ":", "client_id", ",", "\"client_secret\"", ":", "client_secret", "}", ")", "return", "HSAccessTokenAuth", ".", "from_response", "(", "response", ")" ]
Get Oauth data from HelloSign Args: code (str): Code returned by HelloSign for our callback url client_id (str): Client id of the associated app client_secret (str): Secret token of the associated app Returns: A HSAccessTokenAuth object
[ "Get", "Oauth", "data", "from", "HelloSign" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1230-L1253
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient.refresh_access_token
def refresh_access_token(self, refresh_token): ''' Refreshes the current access token. Gets a new access token, updates client auth and returns it. Args: refresh_token (str): Refresh token to use Returns: The new access token ''' request = self._get_request() response = request.post(self.OAUTH_TOKEN_URL, { "grant_type": "refresh_token", "refresh_token": refresh_token }) self.auth = HSAccessTokenAuth.from_response(response) return self.auth.access_token
python
def refresh_access_token(self, refresh_token): ''' Refreshes the current access token. Gets a new access token, updates client auth and returns it. Args: refresh_token (str): Refresh token to use Returns: The new access token ''' request = self._get_request() response = request.post(self.OAUTH_TOKEN_URL, { "grant_type": "refresh_token", "refresh_token": refresh_token }) self.auth = HSAccessTokenAuth.from_response(response) return self.auth.access_token
[ "def", "refresh_access_token", "(", "self", ",", "refresh_token", ")", ":", "request", "=", "self", ".", "_get_request", "(", ")", "response", "=", "request", ".", "post", "(", "self", ".", "OAUTH_TOKEN_URL", ",", "{", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"refresh_token\"", ":", "refresh_token", "}", ")", "self", ".", "auth", "=", "HSAccessTokenAuth", ".", "from_response", "(", "response", ")", "return", "self", ".", "auth", ".", "access_token" ]
Refreshes the current access token. Gets a new access token, updates client auth and returns it. Args: refresh_token (str): Refresh token to use Returns: The new access token
[ "Refreshes", "the", "current", "access", "token", "." ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1255-L1273
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient._get_request
def _get_request(self, auth=None): ''' Return an http request object auth: Auth data to use Returns: A HSRequest object ''' self.request = HSRequest(auth or self.auth, self.env) self.request.response_callback = self.response_callback return self.request
python
def _get_request(self, auth=None): ''' Return an http request object auth: Auth data to use Returns: A HSRequest object ''' self.request = HSRequest(auth or self.auth, self.env) self.request.response_callback = self.response_callback return self.request
[ "def", "_get_request", "(", "self", ",", "auth", "=", "None", ")", ":", "self", ".", "request", "=", "HSRequest", "(", "auth", "or", "self", ".", "auth", ",", "self", ".", "env", ")", "self", ".", "request", ".", "response_callback", "=", "self", ".", "response_callback", "return", "self", ".", "request" ]
Return an http request object auth: Auth data to use Returns: A HSRequest object
[ "Return", "an", "http", "request", "object" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1286-L1296
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient._authenticate
def _authenticate(self, email_address=None, password=None, api_key=None, access_token=None, access_token_type=None): ''' Create authentication object to send requests Args: email_address (str): Email address of the account to make the requests password (str): Password of the account used with email address api_key (str): API Key. You can find your API key in https://www.hellosign.com/home/myAccount/current_tab/integrations access_token (str): OAuth access token access_token_type (str): Type of OAuth access token Raises: NoAuthMethod: If no authentication information found Returns: A HTTPBasicAuth or HSAccessTokenAuth object ''' if access_token_type and access_token: return HSAccessTokenAuth(access_token, access_token_type) elif api_key: return HTTPBasicAuth(api_key, '') elif email_address and password: return HTTPBasicAuth(email_address, password) else: raise NoAuthMethod("No authentication information found!")
python
def _authenticate(self, email_address=None, password=None, api_key=None, access_token=None, access_token_type=None): ''' Create authentication object to send requests Args: email_address (str): Email address of the account to make the requests password (str): Password of the account used with email address api_key (str): API Key. You can find your API key in https://www.hellosign.com/home/myAccount/current_tab/integrations access_token (str): OAuth access token access_token_type (str): Type of OAuth access token Raises: NoAuthMethod: If no authentication information found Returns: A HTTPBasicAuth or HSAccessTokenAuth object ''' if access_token_type and access_token: return HSAccessTokenAuth(access_token, access_token_type) elif api_key: return HTTPBasicAuth(api_key, '') elif email_address and password: return HTTPBasicAuth(email_address, password) else: raise NoAuthMethod("No authentication information found!")
[ "def", "_authenticate", "(", "self", ",", "email_address", "=", "None", ",", "password", "=", "None", ",", "api_key", "=", "None", ",", "access_token", "=", "None", ",", "access_token_type", "=", "None", ")", ":", "if", "access_token_type", "and", "access_token", ":", "return", "HSAccessTokenAuth", "(", "access_token", ",", "access_token_type", ")", "elif", "api_key", ":", "return", "HTTPBasicAuth", "(", "api_key", ",", "''", ")", "elif", "email_address", "and", "password", ":", "return", "HTTPBasicAuth", "(", "email_address", ",", "password", ")", "else", ":", "raise", "NoAuthMethod", "(", "\"No authentication information found!\"", ")" ]
Create authentication object to send requests Args: email_address (str): Email address of the account to make the requests password (str): Password of the account used with email address api_key (str): API Key. You can find your API key in https://www.hellosign.com/home/myAccount/current_tab/integrations access_token (str): OAuth access token access_token_type (str): Type of OAuth access token Raises: NoAuthMethod: If no authentication information found Returns: A HTTPBasicAuth or HSAccessTokenAuth object
[ "Create", "authentication", "object", "to", "send", "requests" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1298-L1328
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient._check_required_fields
def _check_required_fields(self, fields=None, either_fields=None): ''' Check the values of the fields If no value found in `fields`, an exception will be raised. `either_fields` are the fields that one of them must have a value Raises: HSException: If no value found in at least one item of`fields`, or no value found in one of the items of `either_fields` Returns: None ''' for (key, value) in fields.items(): # If value is a dict, one of the fields in the dict is required -> # exception if all are None if not value: raise HSException("Field '%s' is required." % key) if either_fields is not None: for field in either_fields: if not any(field.values()): raise HSException("One of the following fields is required: %s" % ", ".join(field.keys()))
python
def _check_required_fields(self, fields=None, either_fields=None): ''' Check the values of the fields If no value found in `fields`, an exception will be raised. `either_fields` are the fields that one of them must have a value Raises: HSException: If no value found in at least one item of`fields`, or no value found in one of the items of `either_fields` Returns: None ''' for (key, value) in fields.items(): # If value is a dict, one of the fields in the dict is required -> # exception if all are None if not value: raise HSException("Field '%s' is required." % key) if either_fields is not None: for field in either_fields: if not any(field.values()): raise HSException("One of the following fields is required: %s" % ", ".join(field.keys()))
[ "def", "_check_required_fields", "(", "self", ",", "fields", "=", "None", ",", "either_fields", "=", "None", ")", ":", "for", "(", "key", ",", "value", ")", "in", "fields", ".", "items", "(", ")", ":", "# If value is a dict, one of the fields in the dict is required ->", "# exception if all are None", "if", "not", "value", ":", "raise", "HSException", "(", "\"Field '%s' is required.\"", "%", "key", ")", "if", "either_fields", "is", "not", "None", ":", "for", "field", "in", "either_fields", ":", "if", "not", "any", "(", "field", ".", "values", "(", ")", ")", ":", "raise", "HSException", "(", "\"One of the following fields is required: %s\"", "%", "\", \"", ".", "join", "(", "field", ".", "keys", "(", ")", ")", ")" ]
Check the values of the fields If no value found in `fields`, an exception will be raised. `either_fields` are the fields that one of them must have a value Raises: HSException: If no value found in at least one item of`fields`, or no value found in one of the items of `either_fields` Returns: None
[ "Check", "the", "values", "of", "the", "fields" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1330-L1353
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient._send_signature_request
def _send_signature_request(self, test_mode=False, client_id=None, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, metadata=None, ux_version=None, allow_decline=False): ''' To share the same logic between send_signature_request & send_signature_request_embedded functions Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. client_id (str): Client id of the app you're using to create this embedded signature request. Visit the embedded page to learn more about this parameter (https://www.hellosign.com/api/embeddedSigningWalkthrough) files (list of str): The uploaded file(s) to send for signature file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls` title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign signers (list of dict): A list of signers, which each has the following attributes: name (str): The name of the signer email_address (str): Email address of the signer order (str, optional): The order the signer is required to sign in pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page cc_email_addresses (list, optional): A list of email addresses that should be CCed form_fields_per_document (str): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest) use_text_tags (bool, optional): Use text tags in the provided file(s) to create form fields hide_text_tags (bool, optional): Hide text tag areas metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline (bool, optional); Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object ''' # Files files_payload = HSFormat.format_file_params(files) # File URLs file_urls_payload = HSFormat.format_file_url_params(file_urls) # Signers signers_payload = HSFormat.format_dict_list(signers, 'signers') # CCs cc_email_addresses_payload = HSFormat.format_param_list(cc_email_addresses, 'cc_email_addresses') # Metadata metadata_payload = HSFormat.format_single_dict(metadata, 'metadata') payload = { "test_mode": self._boolean(test_mode), "client_id": client_id, "title": title, "subject": subject, "message": message, "signing_redirect_url": signing_redirect_url, "form_fields_per_document": form_fields_per_document, "use_text_tags": self._boolean(use_text_tags), "hide_text_tags": self._boolean(hide_text_tags), "allow_decline": self._boolean(allow_decline) } if ux_version is not None: payload['ux_version'] = ux_version # remove attributes with none value payload = HSFormat.strip_none_values(payload) url = self.SIGNATURE_REQUEST_CREATE_URL if client_id: url = self.SIGNATURE_REQUEST_CREATE_EMBEDDED_URL data = {} data.update(payload) data.update(signers_payload) data.update(cc_email_addresses_payload) data.update(file_urls_payload) data.update(metadata_payload) request = self._get_request() response = request.post(url, data=data, files=files_payload) return response
python
def _send_signature_request(self, test_mode=False, client_id=None, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, metadata=None, ux_version=None, allow_decline=False): ''' To share the same logic between send_signature_request & send_signature_request_embedded functions Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. client_id (str): Client id of the app you're using to create this embedded signature request. Visit the embedded page to learn more about this parameter (https://www.hellosign.com/api/embeddedSigningWalkthrough) files (list of str): The uploaded file(s) to send for signature file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls` title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign signers (list of dict): A list of signers, which each has the following attributes: name (str): The name of the signer email_address (str): Email address of the signer order (str, optional): The order the signer is required to sign in pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page cc_email_addresses (list, optional): A list of email addresses that should be CCed form_fields_per_document (str): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest) use_text_tags (bool, optional): Use text tags in the provided file(s) to create form fields hide_text_tags (bool, optional): Hide text tag areas metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline (bool, optional); Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object ''' # Files files_payload = HSFormat.format_file_params(files) # File URLs file_urls_payload = HSFormat.format_file_url_params(file_urls) # Signers signers_payload = HSFormat.format_dict_list(signers, 'signers') # CCs cc_email_addresses_payload = HSFormat.format_param_list(cc_email_addresses, 'cc_email_addresses') # Metadata metadata_payload = HSFormat.format_single_dict(metadata, 'metadata') payload = { "test_mode": self._boolean(test_mode), "client_id": client_id, "title": title, "subject": subject, "message": message, "signing_redirect_url": signing_redirect_url, "form_fields_per_document": form_fields_per_document, "use_text_tags": self._boolean(use_text_tags), "hide_text_tags": self._boolean(hide_text_tags), "allow_decline": self._boolean(allow_decline) } if ux_version is not None: payload['ux_version'] = ux_version # remove attributes with none value payload = HSFormat.strip_none_values(payload) url = self.SIGNATURE_REQUEST_CREATE_URL if client_id: url = self.SIGNATURE_REQUEST_CREATE_EMBEDDED_URL data = {} data.update(payload) data.update(signers_payload) data.update(cc_email_addresses_payload) data.update(file_urls_payload) data.update(metadata_payload) request = self._get_request() response = request.post(url, data=data, files=files_payload) return response
[ "def", "_send_signature_request", "(", "self", ",", "test_mode", "=", "False", ",", "client_id", "=", "None", ",", "files", "=", "None", ",", "file_urls", "=", "None", ",", "title", "=", "None", ",", "subject", "=", "None", ",", "message", "=", "None", ",", "signing_redirect_url", "=", "None", ",", "signers", "=", "None", ",", "cc_email_addresses", "=", "None", ",", "form_fields_per_document", "=", "None", ",", "use_text_tags", "=", "False", ",", "hide_text_tags", "=", "False", ",", "metadata", "=", "None", ",", "ux_version", "=", "None", ",", "allow_decline", "=", "False", ")", ":", "# Files", "files_payload", "=", "HSFormat", ".", "format_file_params", "(", "files", ")", "# File URLs", "file_urls_payload", "=", "HSFormat", ".", "format_file_url_params", "(", "file_urls", ")", "# Signers", "signers_payload", "=", "HSFormat", ".", "format_dict_list", "(", "signers", ",", "'signers'", ")", "# CCs", "cc_email_addresses_payload", "=", "HSFormat", ".", "format_param_list", "(", "cc_email_addresses", ",", "'cc_email_addresses'", ")", "# Metadata", "metadata_payload", "=", "HSFormat", ".", "format_single_dict", "(", "metadata", ",", "'metadata'", ")", "payload", "=", "{", "\"test_mode\"", ":", "self", ".", "_boolean", "(", "test_mode", ")", ",", "\"client_id\"", ":", "client_id", ",", "\"title\"", ":", "title", ",", "\"subject\"", ":", "subject", ",", "\"message\"", ":", "message", ",", "\"signing_redirect_url\"", ":", "signing_redirect_url", ",", "\"form_fields_per_document\"", ":", "form_fields_per_document", ",", "\"use_text_tags\"", ":", "self", ".", "_boolean", "(", "use_text_tags", ")", ",", "\"hide_text_tags\"", ":", "self", ".", "_boolean", "(", "hide_text_tags", ")", ",", "\"allow_decline\"", ":", "self", ".", "_boolean", "(", "allow_decline", ")", "}", "if", "ux_version", "is", "not", "None", ":", "payload", "[", "'ux_version'", "]", "=", "ux_version", "# remove attributes with none value", "payload", "=", "HSFormat", ".", "strip_none_values", "(", "payload", ")", "url", "=", "self", ".", "SIGNATURE_REQUEST_CREATE_URL", "if", "client_id", ":", "url", "=", "self", ".", "SIGNATURE_REQUEST_CREATE_EMBEDDED_URL", "data", "=", "{", "}", "data", ".", "update", "(", "payload", ")", "data", ".", "update", "(", "signers_payload", ")", "data", ".", "update", "(", "cc_email_addresses_payload", ")", "data", ".", "update", "(", "file_urls_payload", ")", "data", ".", "update", "(", "metadata_payload", ")", "request", "=", "self", ".", "_get_request", "(", ")", "response", "=", "request", ".", "post", "(", "url", ",", "data", "=", "data", ",", "files", "=", "files_payload", ")", "return", "response" ]
To share the same logic between send_signature_request & send_signature_request_embedded functions Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. client_id (str): Client id of the app you're using to create this embedded signature request. Visit the embedded page to learn more about this parameter (https://www.hellosign.com/api/embeddedSigningWalkthrough) files (list of str): The uploaded file(s) to send for signature file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls` title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign signers (list of dict): A list of signers, which each has the following attributes: name (str): The name of the signer email_address (str): Email address of the signer order (str, optional): The order the signer is required to sign in pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page cc_email_addresses (list, optional): A list of email addresses that should be CCed form_fields_per_document (str): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest) use_text_tags (bool, optional): Use text tags in the provided file(s) to create form fields hide_text_tags (bool, optional): Hide text tag areas metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline (bool, optional); Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object
[ "To", "share", "the", "same", "logic", "between", "send_signature_request", "&", "send_signature_request_embedded", "functions" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1356-L1451
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient._send_signature_request_with_template
def _send_signature_request_with_template(self, test_mode=False, client_id=None, template_id=None, template_ids=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, ccs=None, custom_fields=None, metadata=None, ux_version=None, allow_decline=False): ''' To share the same logic between send_signature_request_with_template and send_signature_request_embedded_with_template Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. client_id (str): Client id of the app you're using to create this embedded signature request. Visit the embedded page to learn more about this parameter (https://www.hellosign.com/api/embeddedSigningWalkthrough) template_id (str): The id of the Template to use when creating the SignatureRequest. Mutually exclusive with template_ids. template_ids (list): The ids of the Templates to use when creating the SignatureRequest. Mutually exclusive with template_id. title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: role_name (str): Role the signer is assigned to name (str): The name of the signer email_address (str): Email address of the signer pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page ccs (list of dict, optional): The email address of the CC filling the role of RoleName. Required when a CC role exists for the Template. Each dict has the following attributes: role_name (str): CC role name email_address (str): CC email address custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}` metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object ''' # Signers signers_payload = HSFormat.format_dict_list(signers, 'signers', 'role_name') # CCs ccs_payload = HSFormat.format_dict_list(ccs, 'ccs', 'role_name') # Custom fields custom_fields_payload = HSFormat.format_custom_fields(custom_fields) # Metadata metadata_payload = HSFormat.format_single_dict(metadata, 'metadata') # Template ids template_ids_payload = {} if template_ids: for i in range(len(template_ids)): template_ids_payload["template_ids[%s]" % i] = template_ids[i] payload = { "test_mode": self._boolean(test_mode), "client_id": client_id, "template_id": template_id, "title": title, "subject": subject, "message": message, "signing_redirect_url": signing_redirect_url, "allow_decline": self._boolean(allow_decline) } if ux_version is not None: payload['ux_version'] = ux_version # remove attributes with empty value payload = HSFormat.strip_none_values(payload) url = self.SIGNATURE_REQUEST_CREATE_WITH_TEMPLATE_URL if client_id: url = self.SIGNATURE_REQUEST_CREATE_EMBEDDED_WITH_TEMPLATE_URL data = payload.copy() data.update(signers_payload) data.update(ccs_payload) data.update(custom_fields_payload) data.update(metadata_payload) data.update(template_ids_payload) request = self._get_request() response = request.post(url, data=data) return response
python
def _send_signature_request_with_template(self, test_mode=False, client_id=None, template_id=None, template_ids=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, ccs=None, custom_fields=None, metadata=None, ux_version=None, allow_decline=False): ''' To share the same logic between send_signature_request_with_template and send_signature_request_embedded_with_template Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. client_id (str): Client id of the app you're using to create this embedded signature request. Visit the embedded page to learn more about this parameter (https://www.hellosign.com/api/embeddedSigningWalkthrough) template_id (str): The id of the Template to use when creating the SignatureRequest. Mutually exclusive with template_ids. template_ids (list): The ids of the Templates to use when creating the SignatureRequest. Mutually exclusive with template_id. title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: role_name (str): Role the signer is assigned to name (str): The name of the signer email_address (str): Email address of the signer pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page ccs (list of dict, optional): The email address of the CC filling the role of RoleName. Required when a CC role exists for the Template. Each dict has the following attributes: role_name (str): CC role name email_address (str): CC email address custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}` metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object ''' # Signers signers_payload = HSFormat.format_dict_list(signers, 'signers', 'role_name') # CCs ccs_payload = HSFormat.format_dict_list(ccs, 'ccs', 'role_name') # Custom fields custom_fields_payload = HSFormat.format_custom_fields(custom_fields) # Metadata metadata_payload = HSFormat.format_single_dict(metadata, 'metadata') # Template ids template_ids_payload = {} if template_ids: for i in range(len(template_ids)): template_ids_payload["template_ids[%s]" % i] = template_ids[i] payload = { "test_mode": self._boolean(test_mode), "client_id": client_id, "template_id": template_id, "title": title, "subject": subject, "message": message, "signing_redirect_url": signing_redirect_url, "allow_decline": self._boolean(allow_decline) } if ux_version is not None: payload['ux_version'] = ux_version # remove attributes with empty value payload = HSFormat.strip_none_values(payload) url = self.SIGNATURE_REQUEST_CREATE_WITH_TEMPLATE_URL if client_id: url = self.SIGNATURE_REQUEST_CREATE_EMBEDDED_WITH_TEMPLATE_URL data = payload.copy() data.update(signers_payload) data.update(ccs_payload) data.update(custom_fields_payload) data.update(metadata_payload) data.update(template_ids_payload) request = self._get_request() response = request.post(url, data=data) return response
[ "def", "_send_signature_request_with_template", "(", "self", ",", "test_mode", "=", "False", ",", "client_id", "=", "None", ",", "template_id", "=", "None", ",", "template_ids", "=", "None", ",", "title", "=", "None", ",", "subject", "=", "None", ",", "message", "=", "None", ",", "signing_redirect_url", "=", "None", ",", "signers", "=", "None", ",", "ccs", "=", "None", ",", "custom_fields", "=", "None", ",", "metadata", "=", "None", ",", "ux_version", "=", "None", ",", "allow_decline", "=", "False", ")", ":", "# Signers", "signers_payload", "=", "HSFormat", ".", "format_dict_list", "(", "signers", ",", "'signers'", ",", "'role_name'", ")", "# CCs", "ccs_payload", "=", "HSFormat", ".", "format_dict_list", "(", "ccs", ",", "'ccs'", ",", "'role_name'", ")", "# Custom fields", "custom_fields_payload", "=", "HSFormat", ".", "format_custom_fields", "(", "custom_fields", ")", "# Metadata", "metadata_payload", "=", "HSFormat", ".", "format_single_dict", "(", "metadata", ",", "'metadata'", ")", "# Template ids", "template_ids_payload", "=", "{", "}", "if", "template_ids", ":", "for", "i", "in", "range", "(", "len", "(", "template_ids", ")", ")", ":", "template_ids_payload", "[", "\"template_ids[%s]\"", "%", "i", "]", "=", "template_ids", "[", "i", "]", "payload", "=", "{", "\"test_mode\"", ":", "self", ".", "_boolean", "(", "test_mode", ")", ",", "\"client_id\"", ":", "client_id", ",", "\"template_id\"", ":", "template_id", ",", "\"title\"", ":", "title", ",", "\"subject\"", ":", "subject", ",", "\"message\"", ":", "message", ",", "\"signing_redirect_url\"", ":", "signing_redirect_url", ",", "\"allow_decline\"", ":", "self", ".", "_boolean", "(", "allow_decline", ")", "}", "if", "ux_version", "is", "not", "None", ":", "payload", "[", "'ux_version'", "]", "=", "ux_version", "# remove attributes with empty value", "payload", "=", "HSFormat", ".", "strip_none_values", "(", "payload", ")", "url", "=", "self", ".", "SIGNATURE_REQUEST_CREATE_WITH_TEMPLATE_URL", "if", "client_id", ":", "url", "=", "self", ".", "SIGNATURE_REQUEST_CREATE_EMBEDDED_WITH_TEMPLATE_URL", "data", "=", "payload", ".", "copy", "(", ")", "data", ".", "update", "(", "signers_payload", ")", "data", ".", "update", "(", "ccs_payload", ")", "data", ".", "update", "(", "custom_fields_payload", ")", "data", ".", "update", "(", "metadata_payload", ")", "data", ".", "update", "(", "template_ids_payload", ")", "request", "=", "self", ".", "_get_request", "(", ")", "response", "=", "request", ".", "post", "(", "url", ",", "data", "=", "data", ")", "return", "response" ]
To share the same logic between send_signature_request_with_template and send_signature_request_embedded_with_template Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. client_id (str): Client id of the app you're using to create this embedded signature request. Visit the embedded page to learn more about this parameter (https://www.hellosign.com/api/embeddedSigningWalkthrough) template_id (str): The id of the Template to use when creating the SignatureRequest. Mutually exclusive with template_ids. template_ids (list): The ids of the Templates to use when creating the SignatureRequest. Mutually exclusive with template_id. title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: role_name (str): Role the signer is assigned to name (str): The name of the signer email_address (str): Email address of the signer pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page ccs (list of dict, optional): The email address of the CC filling the role of RoleName. Required when a CC role exists for the Template. Each dict has the following attributes: role_name (str): CC role name email_address (str): CC email address custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}` metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object
[ "To", "share", "the", "same", "logic", "between", "send_signature_request_with_template", "and", "send_signature_request_embedded_with_template" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1454-L1550
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient._add_remove_user_template
def _add_remove_user_template(self, url, template_id, account_id=None, email_address=None): ''' Add or Remove user from a Template We use this function for two tasks because they have the same API call Args: template_id (str): The id of the template account_id (str): ID of the account to add/remove access to/from email_address (str): The email_address of the account to add/remove access to/from Raises: HSException: If no email address or account_id specified Returns: A Template object ''' if not email_address and not account_id: raise HSException("No email address or account_id specified") data = {} if account_id is not None: data = { "account_id": account_id } else: data = { "email_address": email_address } request = self._get_request() response = request.post(url + template_id, data) return response
python
def _add_remove_user_template(self, url, template_id, account_id=None, email_address=None): ''' Add or Remove user from a Template We use this function for two tasks because they have the same API call Args: template_id (str): The id of the template account_id (str): ID of the account to add/remove access to/from email_address (str): The email_address of the account to add/remove access to/from Raises: HSException: If no email address or account_id specified Returns: A Template object ''' if not email_address and not account_id: raise HSException("No email address or account_id specified") data = {} if account_id is not None: data = { "account_id": account_id } else: data = { "email_address": email_address } request = self._get_request() response = request.post(url + template_id, data) return response
[ "def", "_add_remove_user_template", "(", "self", ",", "url", ",", "template_id", ",", "account_id", "=", "None", ",", "email_address", "=", "None", ")", ":", "if", "not", "email_address", "and", "not", "account_id", ":", "raise", "HSException", "(", "\"No email address or account_id specified\"", ")", "data", "=", "{", "}", "if", "account_id", "is", "not", "None", ":", "data", "=", "{", "\"account_id\"", ":", "account_id", "}", "else", ":", "data", "=", "{", "\"email_address\"", ":", "email_address", "}", "request", "=", "self", ".", "_get_request", "(", ")", "response", "=", "request", ".", "post", "(", "url", "+", "template_id", ",", "data", ")", "return", "response" ]
Add or Remove user from a Template We use this function for two tasks because they have the same API call Args: template_id (str): The id of the template account_id (str): ID of the account to add/remove access to/from email_address (str): The email_address of the account to add/remove access to/from Raises: HSException: If no email address or account_id specified Returns: A Template object
[ "Add", "or", "Remove", "user", "from", "a", "Template" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1659-L1696
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient._add_remove_team_member
def _add_remove_team_member(self, url, email_address=None, account_id=None): ''' Add or Remove a team member We use this function for two different tasks because they have the same API call Args: email_address (str): Email address of the Account to add/remove account_id (str): ID of the Account to add/remove Returns: A Team object ''' if not email_address and not account_id: raise HSException("No email address or account_id specified") data = {} if account_id is not None: data = { "account_id": account_id } else: data = { "email_address": email_address } request = self._get_request() response = request.post(url, data) return response
python
def _add_remove_team_member(self, url, email_address=None, account_id=None): ''' Add or Remove a team member We use this function for two different tasks because they have the same API call Args: email_address (str): Email address of the Account to add/remove account_id (str): ID of the Account to add/remove Returns: A Team object ''' if not email_address and not account_id: raise HSException("No email address or account_id specified") data = {} if account_id is not None: data = { "account_id": account_id } else: data = { "email_address": email_address } request = self._get_request() response = request.post(url, data) return response
[ "def", "_add_remove_team_member", "(", "self", ",", "url", ",", "email_address", "=", "None", ",", "account_id", "=", "None", ")", ":", "if", "not", "email_address", "and", "not", "account_id", ":", "raise", "HSException", "(", "\"No email address or account_id specified\"", ")", "data", "=", "{", "}", "if", "account_id", "is", "not", "None", ":", "data", "=", "{", "\"account_id\"", ":", "account_id", "}", "else", ":", "data", "=", "{", "\"email_address\"", ":", "email_address", "}", "request", "=", "self", ".", "_get_request", "(", ")", "response", "=", "request", ".", "post", "(", "url", ",", "data", ")", "return", "response" ]
Add or Remove a team member We use this function for two different tasks because they have the same API call Args: email_address (str): Email address of the Account to add/remove account_id (str): ID of the Account to add/remove Returns: A Team object
[ "Add", "or", "Remove", "a", "team", "member" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1699-L1732
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient._create_embedded_template_draft
def _create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False): ''' Helper method for creating embedded template drafts. See public function for params. ''' url = self.TEMPLATE_CREATE_EMBEDDED_DRAFT_URL payload = { 'test_mode': self._boolean(test_mode), 'client_id': client_id, 'title': title, 'subject': subject, 'message': message, 'use_preexisting_fields': self._boolean(use_preexisting_fields) } # Prep files files_payload = HSFormat.format_file_params(files) file_urls_payload = HSFormat.format_file_url_params(file_urls) # Prep Signer Roles signer_roles_payload = HSFormat.format_dict_list(signer_roles, 'signer_roles') # Prep CCs ccs_payload = HSFormat.format_param_list(cc_roles, 'cc_roles') # Prep Merge Fields merge_fields_payload = { 'merge_fields': json.dumps(merge_fields) } # Assemble data for sending data = {} data.update(payload) data.update(file_urls_payload) data.update(signer_roles_payload) data.update(ccs_payload) if (merge_fields is not None): data.update(merge_fields_payload) data = HSFormat.strip_none_values(data) request = self._get_request() response = request.post(url, data=data, files=files_payload) return response
python
def _create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False): ''' Helper method for creating embedded template drafts. See public function for params. ''' url = self.TEMPLATE_CREATE_EMBEDDED_DRAFT_URL payload = { 'test_mode': self._boolean(test_mode), 'client_id': client_id, 'title': title, 'subject': subject, 'message': message, 'use_preexisting_fields': self._boolean(use_preexisting_fields) } # Prep files files_payload = HSFormat.format_file_params(files) file_urls_payload = HSFormat.format_file_url_params(file_urls) # Prep Signer Roles signer_roles_payload = HSFormat.format_dict_list(signer_roles, 'signer_roles') # Prep CCs ccs_payload = HSFormat.format_param_list(cc_roles, 'cc_roles') # Prep Merge Fields merge_fields_payload = { 'merge_fields': json.dumps(merge_fields) } # Assemble data for sending data = {} data.update(payload) data.update(file_urls_payload) data.update(signer_roles_payload) data.update(ccs_payload) if (merge_fields is not None): data.update(merge_fields_payload) data = HSFormat.strip_none_values(data) request = self._get_request() response = request.post(url, data=data, files=files_payload) return response
[ "def", "_create_embedded_template_draft", "(", "self", ",", "client_id", ",", "signer_roles", ",", "test_mode", "=", "False", ",", "files", "=", "None", ",", "file_urls", "=", "None", ",", "title", "=", "None", ",", "subject", "=", "None", ",", "message", "=", "None", ",", "cc_roles", "=", "None", ",", "merge_fields", "=", "None", ",", "use_preexisting_fields", "=", "False", ")", ":", "url", "=", "self", ".", "TEMPLATE_CREATE_EMBEDDED_DRAFT_URL", "payload", "=", "{", "'test_mode'", ":", "self", ".", "_boolean", "(", "test_mode", ")", ",", "'client_id'", ":", "client_id", ",", "'title'", ":", "title", ",", "'subject'", ":", "subject", ",", "'message'", ":", "message", ",", "'use_preexisting_fields'", ":", "self", ".", "_boolean", "(", "use_preexisting_fields", ")", "}", "# Prep files", "files_payload", "=", "HSFormat", ".", "format_file_params", "(", "files", ")", "file_urls_payload", "=", "HSFormat", ".", "format_file_url_params", "(", "file_urls", ")", "# Prep Signer Roles", "signer_roles_payload", "=", "HSFormat", ".", "format_dict_list", "(", "signer_roles", ",", "'signer_roles'", ")", "# Prep CCs", "ccs_payload", "=", "HSFormat", ".", "format_param_list", "(", "cc_roles", ",", "'cc_roles'", ")", "# Prep Merge Fields", "merge_fields_payload", "=", "{", "'merge_fields'", ":", "json", ".", "dumps", "(", "merge_fields", ")", "}", "# Assemble data for sending", "data", "=", "{", "}", "data", ".", "update", "(", "payload", ")", "data", ".", "update", "(", "file_urls_payload", ")", "data", ".", "update", "(", "signer_roles_payload", ")", "data", ".", "update", "(", "ccs_payload", ")", "if", "(", "merge_fields", "is", "not", "None", ")", ":", "data", ".", "update", "(", "merge_fields_payload", ")", "data", "=", "HSFormat", ".", "strip_none_values", "(", "data", ")", "request", "=", "self", ".", "_get_request", "(", ")", "response", "=", "request", ".", "post", "(", "url", ",", "data", "=", "data", ",", "files", "=", "files_payload", ")", "return", "response" ]
Helper method for creating embedded template drafts. See public function for params.
[ "Helper", "method", "for", "creating", "embedded", "template", "drafts", ".", "See", "public", "function", "for", "params", "." ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1735-L1778
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
HSClient._create_embedded_unclaimed_draft_with_template
def _create_embedded_unclaimed_draft_with_template(self, test_mode=False, client_id=None, is_for_embedded_signing=False, template_id=None, template_ids=None, requester_email_address=None, title=None, subject=None, message=None, signers=None, ccs=None, signing_redirect_url=None, requesting_redirect_url=None, metadata=None, custom_fields=None, allow_decline=False): ''' Helper method for creating unclaimed drafts from templates See public function for params. ''' #single params payload = { "test_mode": self._boolean(test_mode), "client_id": client_id, "is_for_embedded_signing": self._boolean(is_for_embedded_signing), "template_id": template_id, "requester_email_address": requester_email_address, "title": title, "subject": subject, "message": message, "signing_redirect_url": signing_redirect_url, "requesting_redirect_url": requesting_redirect_url, "allow_decline": self._boolean(allow_decline) } #format multi params template_ids_payload = HSFormat.format_param_list(template_ids, 'template_ids') signers_payload = HSFormat.format_dict_list(signers, 'signers', 'role_name') ccs_payload = HSFormat.format_dict_list(ccs, 'ccs', 'role_name') metadata_payload = HSFormat.format_single_dict(metadata, 'metadata') custom_fields_payload = HSFormat.format_custom_fields(custom_fields) #assemble payload data = {} data.update(payload) data.update(template_ids_payload) data.update(signers_payload) data.update(ccs_payload) data.update(metadata_payload) data.update(custom_fields_payload) data = HSFormat.strip_none_values(data) #send call url = self.UNCLAIMED_DRAFT_CREATE_EMBEDDED_WITH_TEMPLATE_URL request = self._get_request() response = request.post(url, data=data) return response
python
def _create_embedded_unclaimed_draft_with_template(self, test_mode=False, client_id=None, is_for_embedded_signing=False, template_id=None, template_ids=None, requester_email_address=None, title=None, subject=None, message=None, signers=None, ccs=None, signing_redirect_url=None, requesting_redirect_url=None, metadata=None, custom_fields=None, allow_decline=False): ''' Helper method for creating unclaimed drafts from templates See public function for params. ''' #single params payload = { "test_mode": self._boolean(test_mode), "client_id": client_id, "is_for_embedded_signing": self._boolean(is_for_embedded_signing), "template_id": template_id, "requester_email_address": requester_email_address, "title": title, "subject": subject, "message": message, "signing_redirect_url": signing_redirect_url, "requesting_redirect_url": requesting_redirect_url, "allow_decline": self._boolean(allow_decline) } #format multi params template_ids_payload = HSFormat.format_param_list(template_ids, 'template_ids') signers_payload = HSFormat.format_dict_list(signers, 'signers', 'role_name') ccs_payload = HSFormat.format_dict_list(ccs, 'ccs', 'role_name') metadata_payload = HSFormat.format_single_dict(metadata, 'metadata') custom_fields_payload = HSFormat.format_custom_fields(custom_fields) #assemble payload data = {} data.update(payload) data.update(template_ids_payload) data.update(signers_payload) data.update(ccs_payload) data.update(metadata_payload) data.update(custom_fields_payload) data = HSFormat.strip_none_values(data) #send call url = self.UNCLAIMED_DRAFT_CREATE_EMBEDDED_WITH_TEMPLATE_URL request = self._get_request() response = request.post(url, data=data) return response
[ "def", "_create_embedded_unclaimed_draft_with_template", "(", "self", ",", "test_mode", "=", "False", ",", "client_id", "=", "None", ",", "is_for_embedded_signing", "=", "False", ",", "template_id", "=", "None", ",", "template_ids", "=", "None", ",", "requester_email_address", "=", "None", ",", "title", "=", "None", ",", "subject", "=", "None", ",", "message", "=", "None", ",", "signers", "=", "None", ",", "ccs", "=", "None", ",", "signing_redirect_url", "=", "None", ",", "requesting_redirect_url", "=", "None", ",", "metadata", "=", "None", ",", "custom_fields", "=", "None", ",", "allow_decline", "=", "False", ")", ":", "#single params", "payload", "=", "{", "\"test_mode\"", ":", "self", ".", "_boolean", "(", "test_mode", ")", ",", "\"client_id\"", ":", "client_id", ",", "\"is_for_embedded_signing\"", ":", "self", ".", "_boolean", "(", "is_for_embedded_signing", ")", ",", "\"template_id\"", ":", "template_id", ",", "\"requester_email_address\"", ":", "requester_email_address", ",", "\"title\"", ":", "title", ",", "\"subject\"", ":", "subject", ",", "\"message\"", ":", "message", ",", "\"signing_redirect_url\"", ":", "signing_redirect_url", ",", "\"requesting_redirect_url\"", ":", "requesting_redirect_url", ",", "\"allow_decline\"", ":", "self", ".", "_boolean", "(", "allow_decline", ")", "}", "#format multi params", "template_ids_payload", "=", "HSFormat", ".", "format_param_list", "(", "template_ids", ",", "'template_ids'", ")", "signers_payload", "=", "HSFormat", ".", "format_dict_list", "(", "signers", ",", "'signers'", ",", "'role_name'", ")", "ccs_payload", "=", "HSFormat", ".", "format_dict_list", "(", "ccs", ",", "'ccs'", ",", "'role_name'", ")", "metadata_payload", "=", "HSFormat", ".", "format_single_dict", "(", "metadata", ",", "'metadata'", ")", "custom_fields_payload", "=", "HSFormat", ".", "format_custom_fields", "(", "custom_fields", ")", "#assemble payload", "data", "=", "{", "}", "data", ".", "update", "(", "payload", ")", "data", ".", "update", "(", "template_ids_payload", ")", "data", ".", "update", "(", "signers_payload", ")", "data", ".", "update", "(", "ccs_payload", ")", "data", ".", "update", "(", "metadata_payload", ")", "data", ".", "update", "(", "custom_fields_payload", ")", "data", "=", "HSFormat", ".", "strip_none_values", "(", "data", ")", "#send call", "url", "=", "self", ".", "UNCLAIMED_DRAFT_CREATE_EMBEDDED_WITH_TEMPLATE_URL", "request", "=", "self", ".", "_get_request", "(", ")", "response", "=", "request", ".", "post", "(", "url", ",", "data", "=", "data", ")", "return", "response" ]
Helper method for creating unclaimed drafts from templates See public function for params.
[ "Helper", "method", "for", "creating", "unclaimed", "drafts", "from", "templates", "See", "public", "function", "for", "params", "." ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1781-L1823
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/request.py
HSRequest.get_file
def get_file(self, url, path_or_file=None, headers=None, filename=None): ''' Get a file from a url and save it as `filename` Args: url (str): URL to send the request to path_or_file (str or file): A writable File-like object or a path to save the file to. filename (str): [DEPRECATED] File name to save the file as, this can be either a full path or a relative path headers (str, optional): custom headers Returns: True if file is downloaded and written successfully, False otherwise. ''' path_or_file = path_or_file or filename if self.debug: print("GET FILE: %s, headers=%s" % (url, headers)) self.headers = self._get_default_headers() if headers is not None: self.headers.update(headers) response = requests.get(url, headers=self.headers, auth=self.auth, verify=self.verify_ssl) self.http_status_code = response.status_code try: # No need to check for warnings here self._check_error(response) try: path_or_file.write(response.content) except AttributeError: fd = os.open(path_or_file, os.O_CREAT | os.O_RDWR) with os.fdopen(fd, "w+b") as f: f.write(response.content) except: return False return True
python
def get_file(self, url, path_or_file=None, headers=None, filename=None): ''' Get a file from a url and save it as `filename` Args: url (str): URL to send the request to path_or_file (str or file): A writable File-like object or a path to save the file to. filename (str): [DEPRECATED] File name to save the file as, this can be either a full path or a relative path headers (str, optional): custom headers Returns: True if file is downloaded and written successfully, False otherwise. ''' path_or_file = path_or_file or filename if self.debug: print("GET FILE: %s, headers=%s" % (url, headers)) self.headers = self._get_default_headers() if headers is not None: self.headers.update(headers) response = requests.get(url, headers=self.headers, auth=self.auth, verify=self.verify_ssl) self.http_status_code = response.status_code try: # No need to check for warnings here self._check_error(response) try: path_or_file.write(response.content) except AttributeError: fd = os.open(path_or_file, os.O_CREAT | os.O_RDWR) with os.fdopen(fd, "w+b") as f: f.write(response.content) except: return False return True
[ "def", "get_file", "(", "self", ",", "url", ",", "path_or_file", "=", "None", ",", "headers", "=", "None", ",", "filename", "=", "None", ")", ":", "path_or_file", "=", "path_or_file", "or", "filename", "if", "self", ".", "debug", ":", "print", "(", "\"GET FILE: %s, headers=%s\"", "%", "(", "url", ",", "headers", ")", ")", "self", ".", "headers", "=", "self", ".", "_get_default_headers", "(", ")", "if", "headers", "is", "not", "None", ":", "self", ".", "headers", ".", "update", "(", "headers", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "headers", ",", "auth", "=", "self", ".", "auth", ",", "verify", "=", "self", ".", "verify_ssl", ")", "self", ".", "http_status_code", "=", "response", ".", "status_code", "try", ":", "# No need to check for warnings here", "self", ".", "_check_error", "(", "response", ")", "try", ":", "path_or_file", ".", "write", "(", "response", ".", "content", ")", "except", "AttributeError", ":", "fd", "=", "os", ".", "open", "(", "path_or_file", ",", "os", ".", "O_CREAT", "|", "os", ".", "O_RDWR", ")", "with", "os", ".", "fdopen", "(", "fd", ",", "\"w+b\"", ")", "as", "f", ":", "f", ".", "write", "(", "response", ".", "content", ")", "except", ":", "return", "False", "return", "True" ]
Get a file from a url and save it as `filename` Args: url (str): URL to send the request to path_or_file (str or file): A writable File-like object or a path to save the file to. filename (str): [DEPRECATED] File name to save the file as, this can be either a full path or a relative path headers (str, optional): custom headers Returns: True if file is downloaded and written successfully, False otherwise.
[ "Get", "a", "file", "from", "a", "url", "and", "save", "it", "as", "filename" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/request.py#L69-L111
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/request.py
HSRequest.get
def get(self, url, headers=None, parameters=None, get_json=True): ''' Send a GET request with custome headers and parameters Args: url (str): URL to send the request to headers (str, optional): custom headers parameters (str, optional): optional parameters Returns: A JSON object of the returned response if `get_json` is True, Requests' response object otherwise ''' if self.debug: print("GET: %s, headers=%s" % (url, headers)) self.headers = self._get_default_headers() get_parameters = self.parameters if get_parameters is None: # In case self.parameters is still empty get_parameters = {} if headers is not None: self.headers.update(headers) if parameters is not None: get_parameters.update(parameters) response = requests.get(url, headers=self.headers, params=get_parameters, auth=self.auth, verify=self.verify_ssl) json_response = self._process_json_response(response) return json_response if get_json is True else response
python
def get(self, url, headers=None, parameters=None, get_json=True): ''' Send a GET request with custome headers and parameters Args: url (str): URL to send the request to headers (str, optional): custom headers parameters (str, optional): optional parameters Returns: A JSON object of the returned response if `get_json` is True, Requests' response object otherwise ''' if self.debug: print("GET: %s, headers=%s" % (url, headers)) self.headers = self._get_default_headers() get_parameters = self.parameters if get_parameters is None: # In case self.parameters is still empty get_parameters = {} if headers is not None: self.headers.update(headers) if parameters is not None: get_parameters.update(parameters) response = requests.get(url, headers=self.headers, params=get_parameters, auth=self.auth, verify=self.verify_ssl) json_response = self._process_json_response(response) return json_response if get_json is True else response
[ "def", "get", "(", "self", ",", "url", ",", "headers", "=", "None", ",", "parameters", "=", "None", ",", "get_json", "=", "True", ")", ":", "if", "self", ".", "debug", ":", "print", "(", "\"GET: %s, headers=%s\"", "%", "(", "url", ",", "headers", ")", ")", "self", ".", "headers", "=", "self", ".", "_get_default_headers", "(", ")", "get_parameters", "=", "self", ".", "parameters", "if", "get_parameters", "is", "None", ":", "# In case self.parameters is still empty", "get_parameters", "=", "{", "}", "if", "headers", "is", "not", "None", ":", "self", ".", "headers", ".", "update", "(", "headers", ")", "if", "parameters", "is", "not", "None", ":", "get_parameters", ".", "update", "(", "parameters", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "headers", ",", "params", "=", "get_parameters", ",", "auth", "=", "self", ".", "auth", ",", "verify", "=", "self", ".", "verify_ssl", ")", "json_response", "=", "self", ".", "_process_json_response", "(", "response", ")", "return", "json_response", "if", "get_json", "is", "True", "else", "response" ]
Send a GET request with custome headers and parameters Args: url (str): URL to send the request to headers (str, optional): custom headers parameters (str, optional): optional parameters Returns: A JSON object of the returned response if `get_json` is True, Requests' response object otherwise
[ "Send", "a", "GET", "request", "with", "custome", "headers", "and", "parameters" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/request.py#L113-L143
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/request.py
HSRequest.post
def post(self, url, data=None, files=None, headers=None, get_json=True): ''' Make POST request to a url Args: url (str): URL to send the request to data (dict, optional): Data to send files (dict, optional): Files to send with the request headers (str, optional): custom headers Returns: A JSON object of the returned response if `get_json` is True, Requests' response object otherwise ''' if self.debug: print("POST: %s, headers=%s" % (url, headers)) self.headers = self._get_default_headers() if headers is not None: self.headers.update(headers) response = requests.post(url, headers=self.headers, data=data, auth=self.auth, files=files, verify=self.verify_ssl) json_response = self._process_json_response(response) return json_response if get_json is True else response
python
def post(self, url, data=None, files=None, headers=None, get_json=True): ''' Make POST request to a url Args: url (str): URL to send the request to data (dict, optional): Data to send files (dict, optional): Files to send with the request headers (str, optional): custom headers Returns: A JSON object of the returned response if `get_json` is True, Requests' response object otherwise ''' if self.debug: print("POST: %s, headers=%s" % (url, headers)) self.headers = self._get_default_headers() if headers is not None: self.headers.update(headers) response = requests.post(url, headers=self.headers, data=data, auth=self.auth, files=files, verify=self.verify_ssl) json_response = self._process_json_response(response) return json_response if get_json is True else response
[ "def", "post", "(", "self", ",", "url", ",", "data", "=", "None", ",", "files", "=", "None", ",", "headers", "=", "None", ",", "get_json", "=", "True", ")", ":", "if", "self", ".", "debug", ":", "print", "(", "\"POST: %s, headers=%s\"", "%", "(", "url", ",", "headers", ")", ")", "self", ".", "headers", "=", "self", ".", "_get_default_headers", "(", ")", "if", "headers", "is", "not", "None", ":", "self", ".", "headers", ".", "update", "(", "headers", ")", "response", "=", "requests", ".", "post", "(", "url", ",", "headers", "=", "self", ".", "headers", ",", "data", "=", "data", ",", "auth", "=", "self", ".", "auth", ",", "files", "=", "files", ",", "verify", "=", "self", ".", "verify_ssl", ")", "json_response", "=", "self", ".", "_process_json_response", "(", "response", ")", "return", "json_response", "if", "get_json", "is", "True", "else", "response" ]
Make POST request to a url Args: url (str): URL to send the request to data (dict, optional): Data to send files (dict, optional): Files to send with the request headers (str, optional): custom headers Returns: A JSON object of the returned response if `get_json` is True, Requests' response object otherwise
[ "Make", "POST", "request", "to", "a", "url" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/request.py#L145-L170
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/request.py
HSRequest._get_json_response
def _get_json_response(self, resp): ''' Parse a JSON response ''' if resp is not None and resp.text is not None: try: text = resp.text.strip('\n') if len(text) > 0: return json.loads(text) except ValueError as e: if self.debug: print("Could not decode JSON response: \"%s\"" % resp.text) raise e
python
def _get_json_response(self, resp): ''' Parse a JSON response ''' if resp is not None and resp.text is not None: try: text = resp.text.strip('\n') if len(text) > 0: return json.loads(text) except ValueError as e: if self.debug: print("Could not decode JSON response: \"%s\"" % resp.text) raise e
[ "def", "_get_json_response", "(", "self", ",", "resp", ")", ":", "if", "resp", "is", "not", "None", "and", "resp", ".", "text", "is", "not", "None", ":", "try", ":", "text", "=", "resp", ".", "text", ".", "strip", "(", "'\\n'", ")", "if", "len", "(", "text", ")", ">", "0", ":", "return", "json", ".", "loads", "(", "text", ")", "except", "ValueError", "as", "e", ":", "if", "self", ".", "debug", ":", "print", "(", "\"Could not decode JSON response: \\\"%s\\\"\"", "%", "resp", ".", "text", ")", "raise", "e" ]
Parse a JSON response
[ "Parse", "a", "JSON", "response" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/request.py#L175-L185
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/request.py
HSRequest._process_json_response
def _process_json_response(self, response): ''' Process a given response ''' json_response = self._get_json_response(response) if self.response_callback is not None: json_response = self.response_callback(json_response) response._content = json.dumps(json_response) self.http_status_code = response.status_code self._check_error(response, json_response) self._check_warnings(json_response) return json_response
python
def _process_json_response(self, response): ''' Process a given response ''' json_response = self._get_json_response(response) if self.response_callback is not None: json_response = self.response_callback(json_response) response._content = json.dumps(json_response) self.http_status_code = response.status_code self._check_error(response, json_response) self._check_warnings(json_response) return json_response
[ "def", "_process_json_response", "(", "self", ",", "response", ")", ":", "json_response", "=", "self", ".", "_get_json_response", "(", "response", ")", "if", "self", ".", "response_callback", "is", "not", "None", ":", "json_response", "=", "self", ".", "response_callback", "(", "json_response", ")", "response", ".", "_content", "=", "json", ".", "dumps", "(", "json_response", ")", "self", ".", "http_status_code", "=", "response", ".", "status_code", "self", ".", "_check_error", "(", "response", ",", "json_response", ")", "self", ".", "_check_warnings", "(", "json_response", ")", "return", "json_response" ]
Process a given response
[ "Process", "a", "given", "response" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/request.py#L199-L212
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/request.py
HSRequest._check_error
def _check_error(self, response, json_response=None): ''' Check for HTTP error code from the response, raise exception if there's any Args: response (object): Object returned by requests' `get` and `post` methods json_response (dict): JSON response, if applicable Raises: HTTPError: If the status code of response is either 4xx or 5xx Returns: True if status code is not error code ''' # If status code is 4xx or 5xx, that should be an error if response.status_code >= 400: json_response = json_response or self._get_json_response(response) err_cls = self._check_http_error_code(response.status_code) try: raise err_cls("%s error: %s" % (response.status_code, json_response["error"]["error_msg"]), response.status_code) # This is to catch error when we post get oauth data except TypeError: raise err_cls("%s error: %s" % (response.status_code, json_response["error_description"]), response.status_code) # Return True if everything is OK return True
python
def _check_error(self, response, json_response=None): ''' Check for HTTP error code from the response, raise exception if there's any Args: response (object): Object returned by requests' `get` and `post` methods json_response (dict): JSON response, if applicable Raises: HTTPError: If the status code of response is either 4xx or 5xx Returns: True if status code is not error code ''' # If status code is 4xx or 5xx, that should be an error if response.status_code >= 400: json_response = json_response or self._get_json_response(response) err_cls = self._check_http_error_code(response.status_code) try: raise err_cls("%s error: %s" % (response.status_code, json_response["error"]["error_msg"]), response.status_code) # This is to catch error when we post get oauth data except TypeError: raise err_cls("%s error: %s" % (response.status_code, json_response["error_description"]), response.status_code) # Return True if everything is OK return True
[ "def", "_check_error", "(", "self", ",", "response", ",", "json_response", "=", "None", ")", ":", "# If status code is 4xx or 5xx, that should be an error", "if", "response", ".", "status_code", ">=", "400", ":", "json_response", "=", "json_response", "or", "self", ".", "_get_json_response", "(", "response", ")", "err_cls", "=", "self", ".", "_check_http_error_code", "(", "response", ".", "status_code", ")", "try", ":", "raise", "err_cls", "(", "\"%s error: %s\"", "%", "(", "response", ".", "status_code", ",", "json_response", "[", "\"error\"", "]", "[", "\"error_msg\"", "]", ")", ",", "response", ".", "status_code", ")", "# This is to catch error when we post get oauth data", "except", "TypeError", ":", "raise", "err_cls", "(", "\"%s error: %s\"", "%", "(", "response", ".", "status_code", ",", "json_response", "[", "\"error_description\"", "]", ")", ",", "response", ".", "status_code", ")", "# Return True if everything is OK", "return", "True" ]
Check for HTTP error code from the response, raise exception if there's any Args: response (object): Object returned by requests' `get` and `post` methods json_response (dict): JSON response, if applicable Raises: HTTPError: If the status code of response is either 4xx or 5xx Returns: True if status code is not error code
[ "Check", "for", "HTTP", "error", "code", "from", "the", "response", "raise", "exception", "if", "there", "s", "any" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/request.py#L214-L242
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/request.py
HSRequest._check_warnings
def _check_warnings(self, json_response): ''' Extract warnings from the response to make them accessible Args: json_response (dict): JSON response ''' self.warnings = None if json_response: self.warnings = json_response.get('warnings') if self.debug and self.warnings: for w in self.warnings: print("WARNING: %s - %s" % (w['warning_name'], w['warning_msg']))
python
def _check_warnings(self, json_response): ''' Extract warnings from the response to make them accessible Args: json_response (dict): JSON response ''' self.warnings = None if json_response: self.warnings = json_response.get('warnings') if self.debug and self.warnings: for w in self.warnings: print("WARNING: %s - %s" % (w['warning_name'], w['warning_msg']))
[ "def", "_check_warnings", "(", "self", ",", "json_response", ")", ":", "self", ".", "warnings", "=", "None", "if", "json_response", ":", "self", ".", "warnings", "=", "json_response", ".", "get", "(", "'warnings'", ")", "if", "self", ".", "debug", "and", "self", ".", "warnings", ":", "for", "w", "in", "self", ".", "warnings", ":", "print", "(", "\"WARNING: %s - %s\"", "%", "(", "w", "[", "'warning_name'", "]", ",", "w", "[", "'warning_msg'", "]", ")", ")" ]
Extract warnings from the response to make them accessible Args: json_response (dict): JSON response
[ "Extract", "warnings", "from", "the", "response", "to", "make", "them", "accessible" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/request.py#L244-L258
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/hsaccesstokenauth.py
HSAccessTokenAuth.from_response
def from_response(self, response_data): ''' Builds a new HSAccessTokenAuth straight from response data Args: response_data (dict): Response data to use Returns: A HSAccessTokenAuth objet ''' return HSAccessTokenAuth( response_data['access_token'], response_data['token_type'], response_data['refresh_token'], response_data['expires_in'], response_data.get('state') # Not always here )
python
def from_response(self, response_data): ''' Builds a new HSAccessTokenAuth straight from response data Args: response_data (dict): Response data to use Returns: A HSAccessTokenAuth objet ''' return HSAccessTokenAuth( response_data['access_token'], response_data['token_type'], response_data['refresh_token'], response_data['expires_in'], response_data.get('state') # Not always here )
[ "def", "from_response", "(", "self", ",", "response_data", ")", ":", "return", "HSAccessTokenAuth", "(", "response_data", "[", "'access_token'", "]", ",", "response_data", "[", "'token_type'", "]", ",", "response_data", "[", "'refresh_token'", "]", ",", "response_data", "[", "'expires_in'", "]", ",", "response_data", ".", "get", "(", "'state'", ")", "# Not always here", ")" ]
Builds a new HSAccessTokenAuth straight from response data Args: response_data (dict): Response data to use Returns: A HSAccessTokenAuth objet
[ "Builds", "a", "new", "HSAccessTokenAuth", "straight", "from", "response", "data" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/hsaccesstokenauth.py#L53-L69
train
hellosign/hellosign-python-sdk
hellosign_sdk/resource/signature_request.py
SignatureRequest.find_response_component
def find_response_component(self, api_id=None, signature_id=None): ''' Find one or many repsonse components. Args: api_id (str): Api id associated with the component(s) to be retrieved. signature_id (str): Signature id associated with the component(s) to be retrieved. Returns: A list of dictionaries containing component data ''' if not api_id and not signature_id: raise ValueError('At least one of api_id and signature_id is required') components = list() if self.response_data: for component in self.response_data: if (api_id and component['api_id']) == api_id or (signature_id and component['signature_id'] == signature_id): components.append(component) return components
python
def find_response_component(self, api_id=None, signature_id=None): ''' Find one or many repsonse components. Args: api_id (str): Api id associated with the component(s) to be retrieved. signature_id (str): Signature id associated with the component(s) to be retrieved. Returns: A list of dictionaries containing component data ''' if not api_id and not signature_id: raise ValueError('At least one of api_id and signature_id is required') components = list() if self.response_data: for component in self.response_data: if (api_id and component['api_id']) == api_id or (signature_id and component['signature_id'] == signature_id): components.append(component) return components
[ "def", "find_response_component", "(", "self", ",", "api_id", "=", "None", ",", "signature_id", "=", "None", ")", ":", "if", "not", "api_id", "and", "not", "signature_id", ":", "raise", "ValueError", "(", "'At least one of api_id and signature_id is required'", ")", "components", "=", "list", "(", ")", "if", "self", ".", "response_data", ":", "for", "component", "in", "self", ".", "response_data", ":", "if", "(", "api_id", "and", "component", "[", "'api_id'", "]", ")", "==", "api_id", "or", "(", "signature_id", "and", "component", "[", "'signature_id'", "]", "==", "signature_id", ")", ":", "components", ".", "append", "(", "component", ")", "return", "components" ]
Find one or many repsonse components. Args: api_id (str): Api id associated with the component(s) to be retrieved. signature_id (str): Signature id associated with the component(s) to be retrieved. Returns: A list of dictionaries containing component data
[ "Find", "one", "or", "many", "repsonse", "components", "." ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/resource/signature_request.py#L114-L137
train
hellosign/hellosign-python-sdk
hellosign_sdk/resource/signature_request.py
SignatureRequest.find_signature
def find_signature(self, signature_id=None, signer_email_address=None): ''' Return a signature for the given parameters Args: signature_id (str): Id of the signature to retrieve. signer_email_address (str): Email address of the associated signer for the signature to retrieve. Returns: A Signature object or None ''' if self.signatures: for signature in self.signatures: if signature.signature_id == signature_id or signature.signer_email_address == signer_email_address: return signature
python
def find_signature(self, signature_id=None, signer_email_address=None): ''' Return a signature for the given parameters Args: signature_id (str): Id of the signature to retrieve. signer_email_address (str): Email address of the associated signer for the signature to retrieve. Returns: A Signature object or None ''' if self.signatures: for signature in self.signatures: if signature.signature_id == signature_id or signature.signer_email_address == signer_email_address: return signature
[ "def", "find_signature", "(", "self", ",", "signature_id", "=", "None", ",", "signer_email_address", "=", "None", ")", ":", "if", "self", ".", "signatures", ":", "for", "signature", "in", "self", ".", "signatures", ":", "if", "signature", ".", "signature_id", "==", "signature_id", "or", "signature", ".", "signer_email_address", "==", "signer_email_address", ":", "return", "signature" ]
Return a signature for the given parameters Args: signature_id (str): Id of the signature to retrieve. signer_email_address (str): Email address of the associated signer for the signature to retrieve. Returns: A Signature object or None
[ "Return", "a", "signature", "for", "the", "given", "parameters" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/resource/signature_request.py#L139-L154
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/__init__.py
api_resource._uncamelize
def _uncamelize(self, s): ''' Convert a camel-cased string to using underscores ''' res = '' if s: for i in range(len(s)): if i > 0 and s[i].lower() != s[i]: res += '_' res += s[i].lower() return res
python
def _uncamelize(self, s): ''' Convert a camel-cased string to using underscores ''' res = '' if s: for i in range(len(s)): if i > 0 and s[i].lower() != s[i]: res += '_' res += s[i].lower() return res
[ "def", "_uncamelize", "(", "self", ",", "s", ")", ":", "res", "=", "''", "if", "s", ":", "for", "i", "in", "range", "(", "len", "(", "s", ")", ")", ":", "if", "i", ">", "0", "and", "s", "[", "i", "]", ".", "lower", "(", ")", "!=", "s", "[", "i", "]", ":", "res", "+=", "'_'", "res", "+=", "s", "[", "i", "]", ".", "lower", "(", ")", "return", "res" ]
Convert a camel-cased string to using underscores
[ "Convert", "a", "camel", "-", "cased", "string", "to", "using", "underscores" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/__init__.py#L53-L61
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/hsformat.py
HSFormat.format_file_params
def format_file_params(files): ''' Utility method for formatting file parameters for transmission ''' files_payload = {} if files: for idx, filename in enumerate(files): files_payload["file[" + str(idx) + "]"] = open(filename, 'rb') return files_payload
python
def format_file_params(files): ''' Utility method for formatting file parameters for transmission ''' files_payload = {} if files: for idx, filename in enumerate(files): files_payload["file[" + str(idx) + "]"] = open(filename, 'rb') return files_payload
[ "def", "format_file_params", "(", "files", ")", ":", "files_payload", "=", "{", "}", "if", "files", ":", "for", "idx", ",", "filename", "in", "enumerate", "(", "files", ")", ":", "files_payload", "[", "\"file[\"", "+", "str", "(", "idx", ")", "+", "\"]\"", "]", "=", "open", "(", "filename", ",", "'rb'", ")", "return", "files_payload" ]
Utility method for formatting file parameters for transmission
[ "Utility", "method", "for", "formatting", "file", "parameters", "for", "transmission" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/hsformat.py#L41-L49
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/hsformat.py
HSFormat.format_file_url_params
def format_file_url_params(file_urls): ''' Utility method for formatting file URL parameters for transmission ''' file_urls_payload = {} if file_urls: for idx, fileurl in enumerate(file_urls): file_urls_payload["file_url[" + str(idx) + "]"] = fileurl return file_urls_payload
python
def format_file_url_params(file_urls): ''' Utility method for formatting file URL parameters for transmission ''' file_urls_payload = {} if file_urls: for idx, fileurl in enumerate(file_urls): file_urls_payload["file_url[" + str(idx) + "]"] = fileurl return file_urls_payload
[ "def", "format_file_url_params", "(", "file_urls", ")", ":", "file_urls_payload", "=", "{", "}", "if", "file_urls", ":", "for", "idx", ",", "fileurl", "in", "enumerate", "(", "file_urls", ")", ":", "file_urls_payload", "[", "\"file_url[\"", "+", "str", "(", "idx", ")", "+", "\"]\"", "]", "=", "fileurl", "return", "file_urls_payload" ]
Utility method for formatting file URL parameters for transmission
[ "Utility", "method", "for", "formatting", "file", "URL", "parameters", "for", "transmission" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/hsformat.py#L52-L60
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/hsformat.py
HSFormat.format_single_dict
def format_single_dict(dictionary, output_name): ''' Currently used for metadata fields ''' output_payload = {} if dictionary: for (k, v) in dictionary.items(): output_payload[output_name + '[' + k + ']'] = v return output_payload
python
def format_single_dict(dictionary, output_name): ''' Currently used for metadata fields ''' output_payload = {} if dictionary: for (k, v) in dictionary.items(): output_payload[output_name + '[' + k + ']'] = v return output_payload
[ "def", "format_single_dict", "(", "dictionary", ",", "output_name", ")", ":", "output_payload", "=", "{", "}", "if", "dictionary", ":", "for", "(", "k", ",", "v", ")", "in", "dictionary", ".", "items", "(", ")", ":", "output_payload", "[", "output_name", "+", "'['", "+", "k", "+", "']'", "]", "=", "v", "return", "output_payload" ]
Currently used for metadata fields
[ "Currently", "used", "for", "metadata", "fields" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/hsformat.py#L106-L114
train
hellosign/hellosign-python-sdk
hellosign_sdk/utils/hsformat.py
HSFormat.format_custom_fields
def format_custom_fields(list_of_custom_fields): ''' Custom fields formatting for submission ''' output_payload = {} if list_of_custom_fields: # custom_field: {"name": value} for custom_field in list_of_custom_fields: for key, value in custom_field.items(): output_payload["custom_fields[" + key + "]"] = value return output_payload
python
def format_custom_fields(list_of_custom_fields): ''' Custom fields formatting for submission ''' output_payload = {} if list_of_custom_fields: # custom_field: {"name": value} for custom_field in list_of_custom_fields: for key, value in custom_field.items(): output_payload["custom_fields[" + key + "]"] = value return output_payload
[ "def", "format_custom_fields", "(", "list_of_custom_fields", ")", ":", "output_payload", "=", "{", "}", "if", "list_of_custom_fields", ":", "# custom_field: {\"name\": value}", "for", "custom_field", "in", "list_of_custom_fields", ":", "for", "key", ",", "value", "in", "custom_field", ".", "items", "(", ")", ":", "output_payload", "[", "\"custom_fields[\"", "+", "key", "+", "\"]\"", "]", "=", "value", "return", "output_payload" ]
Custom fields formatting for submission
[ "Custom", "fields", "formatting", "for", "submission" ]
4325a29ad5766380a214eac3914511f62f7ecba4
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/hsformat.py#L117-L127
train
GaretJax/django-click
setup.py
Setup.read
def read(fname, fail_silently=False): """ Read the content of the given file. The path is evaluated from the directory containing this file. """ try: filepath = os.path.join(os.path.dirname(__file__), fname) with io.open(filepath, 'rt', encoding='utf8') as f: return f.read() except: if not fail_silently: raise return ''
python
def read(fname, fail_silently=False): """ Read the content of the given file. The path is evaluated from the directory containing this file. """ try: filepath = os.path.join(os.path.dirname(__file__), fname) with io.open(filepath, 'rt', encoding='utf8') as f: return f.read() except: if not fail_silently: raise return ''
[ "def", "read", "(", "fname", ",", "fail_silently", "=", "False", ")", ":", "try", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "fname", ")", "with", "io", ".", "open", "(", "filepath", ",", "'rt'", ",", "encoding", "=", "'utf8'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", "except", ":", "if", "not", "fail_silently", ":", "raise", "return", "''" ]
Read the content of the given file. The path is evaluated from the directory containing this file.
[ "Read", "the", "content", "of", "the", "given", "file", ".", "The", "path", "is", "evaluated", "from", "the", "directory", "containing", "this", "file", "." ]
3584bff81cb7891a1aa2d7fe49c1db501f5b0e84
https://github.com/GaretJax/django-click/blob/3584bff81cb7891a1aa2d7fe49c1db501f5b0e84/setup.py#L35-L47
train
GaretJax/django-click
djclick/adapter.py
pass_verbosity
def pass_verbosity(f): """ Marks a callback as wanting to receive the verbosity as a keyword argument. """ def new_func(*args, **kwargs): kwargs['verbosity'] = click.get_current_context().verbosity return f(*args, **kwargs) return update_wrapper(new_func, f)
python
def pass_verbosity(f): """ Marks a callback as wanting to receive the verbosity as a keyword argument. """ def new_func(*args, **kwargs): kwargs['verbosity'] = click.get_current_context().verbosity return f(*args, **kwargs) return update_wrapper(new_func, f)
[ "def", "pass_verbosity", "(", "f", ")", ":", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'verbosity'", "]", "=", "click", ".", "get_current_context", "(", ")", ".", "verbosity", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "update_wrapper", "(", "new_func", ",", "f", ")" ]
Marks a callback as wanting to receive the verbosity as a keyword argument.
[ "Marks", "a", "callback", "as", "wanting", "to", "receive", "the", "verbosity", "as", "a", "keyword", "argument", "." ]
3584bff81cb7891a1aa2d7fe49c1db501f5b0e84
https://github.com/GaretJax/django-click/blob/3584bff81cb7891a1aa2d7fe49c1db501f5b0e84/djclick/adapter.py#L232-L239
train
GaretJax/django-click
djclick/adapter.py
DjangoCommandMixin.run_from_argv
def run_from_argv(self, argv): """ Called when run from the command line. """ try: return self.main(args=argv[2:], standalone_mode=False) except click.ClickException as e: if getattr(e.ctx, 'traceback', False): raise e.show() sys.exit(e.exit_code)
python
def run_from_argv(self, argv): """ Called when run from the command line. """ try: return self.main(args=argv[2:], standalone_mode=False) except click.ClickException as e: if getattr(e.ctx, 'traceback', False): raise e.show() sys.exit(e.exit_code)
[ "def", "run_from_argv", "(", "self", ",", "argv", ")", ":", "try", ":", "return", "self", ".", "main", "(", "args", "=", "argv", "[", "2", ":", "]", ",", "standalone_mode", "=", "False", ")", "except", "click", ".", "ClickException", "as", "e", ":", "if", "getattr", "(", "e", ".", "ctx", ",", "'traceback'", ",", "False", ")", ":", "raise", "e", ".", "show", "(", ")", "sys", ".", "exit", "(", "e", ".", "exit_code", ")" ]
Called when run from the command line.
[ "Called", "when", "run", "from", "the", "command", "line", "." ]
3584bff81cb7891a1aa2d7fe49c1db501f5b0e84
https://github.com/GaretJax/django-click/blob/3584bff81cb7891a1aa2d7fe49c1db501f5b0e84/djclick/adapter.py#L57-L67
train
xxtea/xxtea-python
xxtea/__init__.py
encrypt
def encrypt(data, key): '''encrypt the data with the key''' data = __tobytes(data) data_len = len(data) data = ffi.from_buffer(data) key = ffi.from_buffer(__tobytes(key)) out_len = ffi.new('size_t *') result = lib.xxtea_encrypt(data, data_len, key, out_len) ret = ffi.buffer(result, out_len[0])[:] lib.free(result) return ret
python
def encrypt(data, key): '''encrypt the data with the key''' data = __tobytes(data) data_len = len(data) data = ffi.from_buffer(data) key = ffi.from_buffer(__tobytes(key)) out_len = ffi.new('size_t *') result = lib.xxtea_encrypt(data, data_len, key, out_len) ret = ffi.buffer(result, out_len[0])[:] lib.free(result) return ret
[ "def", "encrypt", "(", "data", ",", "key", ")", ":", "data", "=", "__tobytes", "(", "data", ")", "data_len", "=", "len", "(", "data", ")", "data", "=", "ffi", ".", "from_buffer", "(", "data", ")", "key", "=", "ffi", ".", "from_buffer", "(", "__tobytes", "(", "key", ")", ")", "out_len", "=", "ffi", ".", "new", "(", "'size_t *'", ")", "result", "=", "lib", ".", "xxtea_encrypt", "(", "data", ",", "data_len", ",", "key", ",", "out_len", ")", "ret", "=", "ffi", ".", "buffer", "(", "result", ",", "out_len", "[", "0", "]", ")", "[", ":", "]", "lib", ".", "free", "(", "result", ")", "return", "ret" ]
encrypt the data with the key
[ "encrypt", "the", "data", "with", "the", "key" ]
35bd893cb42dce338631d051be9302fcbc21b7fc
https://github.com/xxtea/xxtea-python/blob/35bd893cb42dce338631d051be9302fcbc21b7fc/xxtea/__init__.py#L30-L40
train
xxtea/xxtea-python
xxtea/__init__.py
decrypt
def decrypt(data, key): '''decrypt the data with the key''' data_len = len(data) data = ffi.from_buffer(data) key = ffi.from_buffer(__tobytes(key)) out_len = ffi.new('size_t *') result = lib.xxtea_decrypt(data, data_len, key, out_len) ret = ffi.buffer(result, out_len[0])[:] lib.free(result) return ret
python
def decrypt(data, key): '''decrypt the data with the key''' data_len = len(data) data = ffi.from_buffer(data) key = ffi.from_buffer(__tobytes(key)) out_len = ffi.new('size_t *') result = lib.xxtea_decrypt(data, data_len, key, out_len) ret = ffi.buffer(result, out_len[0])[:] lib.free(result) return ret
[ "def", "decrypt", "(", "data", ",", "key", ")", ":", "data_len", "=", "len", "(", "data", ")", "data", "=", "ffi", ".", "from_buffer", "(", "data", ")", "key", "=", "ffi", ".", "from_buffer", "(", "__tobytes", "(", "key", ")", ")", "out_len", "=", "ffi", ".", "new", "(", "'size_t *'", ")", "result", "=", "lib", ".", "xxtea_decrypt", "(", "data", ",", "data_len", ",", "key", ",", "out_len", ")", "ret", "=", "ffi", ".", "buffer", "(", "result", ",", "out_len", "[", "0", "]", ")", "[", ":", "]", "lib", ".", "free", "(", "result", ")", "return", "ret" ]
decrypt the data with the key
[ "decrypt", "the", "data", "with", "the", "key" ]
35bd893cb42dce338631d051be9302fcbc21b7fc
https://github.com/xxtea/xxtea-python/blob/35bd893cb42dce338631d051be9302fcbc21b7fc/xxtea/__init__.py#L42-L51
train
mozilla/taar
taar/flask_app.py
flaskrun
def flaskrun(app, default_host="127.0.0.1", default_port="8000"): """ Takes a flask.Flask instance and runs it. Parses command-line flags to configure the app. """ # Set up the command-line options parser = optparse.OptionParser() parser.add_option( "-H", "--host", help="Hostname of the Flask app " + "[default %s]" % default_host, default=default_host, ) parser.add_option( "-P", "--port", help="Port for the Flask app " + "[default %s]" % default_port, default=default_port, ) # Two options useful for debugging purposes, but # a bit dangerous so not exposed in the help message. parser.add_option( "-d", "--debug", action="store_true", dest="debug", help=optparse.SUPPRESS_HELP ) parser.add_option( "-p", "--profile", action="store_true", dest="profile", help=optparse.SUPPRESS_HELP, ) options, _ = parser.parse_args() # If the user selects the profiling option, then we need # to do a little extra setup if options.profile: from werkzeug.contrib.profiler import ProfilerMiddleware app.config["PROFILE"] = True app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) options.debug = True app.run(debug=options.debug, host=options.host, port=int(options.port))
python
def flaskrun(app, default_host="127.0.0.1", default_port="8000"): """ Takes a flask.Flask instance and runs it. Parses command-line flags to configure the app. """ # Set up the command-line options parser = optparse.OptionParser() parser.add_option( "-H", "--host", help="Hostname of the Flask app " + "[default %s]" % default_host, default=default_host, ) parser.add_option( "-P", "--port", help="Port for the Flask app " + "[default %s]" % default_port, default=default_port, ) # Two options useful for debugging purposes, but # a bit dangerous so not exposed in the help message. parser.add_option( "-d", "--debug", action="store_true", dest="debug", help=optparse.SUPPRESS_HELP ) parser.add_option( "-p", "--profile", action="store_true", dest="profile", help=optparse.SUPPRESS_HELP, ) options, _ = parser.parse_args() # If the user selects the profiling option, then we need # to do a little extra setup if options.profile: from werkzeug.contrib.profiler import ProfilerMiddleware app.config["PROFILE"] = True app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) options.debug = True app.run(debug=options.debug, host=options.host, port=int(options.port))
[ "def", "flaskrun", "(", "app", ",", "default_host", "=", "\"127.0.0.1\"", ",", "default_port", "=", "\"8000\"", ")", ":", "# Set up the command-line options", "parser", "=", "optparse", ".", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "\"-H\"", ",", "\"--host\"", ",", "help", "=", "\"Hostname of the Flask app \"", "+", "\"[default %s]\"", "%", "default_host", ",", "default", "=", "default_host", ",", ")", "parser", ".", "add_option", "(", "\"-P\"", ",", "\"--port\"", ",", "help", "=", "\"Port for the Flask app \"", "+", "\"[default %s]\"", "%", "default_port", ",", "default", "=", "default_port", ",", ")", "# Two options useful for debugging purposes, but", "# a bit dangerous so not exposed in the help message.", "parser", ".", "add_option", "(", "\"-d\"", ",", "\"--debug\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"debug\"", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "parser", ".", "add_option", "(", "\"-p\"", ",", "\"--profile\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"profile\"", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ",", ")", "options", ",", "_", "=", "parser", ".", "parse_args", "(", ")", "# If the user selects the profiling option, then we need", "# to do a little extra setup", "if", "options", ".", "profile", ":", "from", "werkzeug", ".", "contrib", ".", "profiler", "import", "ProfilerMiddleware", "app", ".", "config", "[", "\"PROFILE\"", "]", "=", "True", "app", ".", "wsgi_app", "=", "ProfilerMiddleware", "(", "app", ".", "wsgi_app", ",", "restrictions", "=", "[", "30", "]", ")", "options", ".", "debug", "=", "True", "app", ".", "run", "(", "debug", "=", "options", ".", "debug", ",", "host", "=", "options", ".", "host", ",", "port", "=", "int", "(", "options", ".", "port", ")", ")" ]
Takes a flask.Flask instance and runs it. Parses command-line flags to configure the app.
[ "Takes", "a", "flask", ".", "Flask", "instance", "and", "runs", "it", ".", "Parses", "command", "-", "line", "flags", "to", "configure", "the", "app", "." ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/flask_app.py#L41-L86
train
mozilla/taar
taar/recommenders/hybrid_recommender.py
CuratedWhitelistCache.get_randomized_guid_sample
def get_randomized_guid_sample(self, item_count): """ Fetch a subset of randomzied GUIDs from the whitelist """ dataset = self.get_whitelist() random.shuffle(dataset) return dataset[:item_count]
python
def get_randomized_guid_sample(self, item_count): """ Fetch a subset of randomzied GUIDs from the whitelist """ dataset = self.get_whitelist() random.shuffle(dataset) return dataset[:item_count]
[ "def", "get_randomized_guid_sample", "(", "self", ",", "item_count", ")", ":", "dataset", "=", "self", ".", "get_whitelist", "(", ")", "random", ".", "shuffle", "(", "dataset", ")", "return", "dataset", "[", ":", "item_count", "]" ]
Fetch a subset of randomzied GUIDs from the whitelist
[ "Fetch", "a", "subset", "of", "randomzied", "GUIDs", "from", "the", "whitelist" ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/hybrid_recommender.py#L28-L32
train
mozilla/taar
taar/recommenders/hybrid_recommender.py
CuratedRecommender.can_recommend
def can_recommend(self, client_data, extra_data={}): """The Curated recommender will always be able to recommend something""" self.logger.info("Curated can_recommend: {}".format(True)) return True
python
def can_recommend(self, client_data, extra_data={}): """The Curated recommender will always be able to recommend something""" self.logger.info("Curated can_recommend: {}".format(True)) return True
[ "def", "can_recommend", "(", "self", ",", "client_data", ",", "extra_data", "=", "{", "}", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Curated can_recommend: {}\"", ".", "format", "(", "True", ")", ")", "return", "True" ]
The Curated recommender will always be able to recommend something
[ "The", "Curated", "recommender", "will", "always", "be", "able", "to", "recommend", "something" ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/hybrid_recommender.py#L52-L56
train
mozilla/taar
taar/recommenders/hybrid_recommender.py
CuratedRecommender.recommend
def recommend(self, client_data, limit, extra_data={}): """ Curated recommendations are just random selections """ guids = self._curated_wl.get_randomized_guid_sample(limit) results = [(guid, 1.0) for guid in guids] log_data = (client_data["client_id"], str(guids)) self.logger.info( "Curated recommendations client_id: [%s], guids: [%s]" % log_data ) return results
python
def recommend(self, client_data, limit, extra_data={}): """ Curated recommendations are just random selections """ guids = self._curated_wl.get_randomized_guid_sample(limit) results = [(guid, 1.0) for guid in guids] log_data = (client_data["client_id"], str(guids)) self.logger.info( "Curated recommendations client_id: [%s], guids: [%s]" % log_data ) return results
[ "def", "recommend", "(", "self", ",", "client_data", ",", "limit", ",", "extra_data", "=", "{", "}", ")", ":", "guids", "=", "self", ".", "_curated_wl", ".", "get_randomized_guid_sample", "(", "limit", ")", "results", "=", "[", "(", "guid", ",", "1.0", ")", "for", "guid", "in", "guids", "]", "log_data", "=", "(", "client_data", "[", "\"client_id\"", "]", ",", "str", "(", "guids", ")", ")", "self", ".", "logger", ".", "info", "(", "\"Curated recommendations client_id: [%s], guids: [%s]\"", "%", "log_data", ")", "return", "results" ]
Curated recommendations are just random selections
[ "Curated", "recommendations", "are", "just", "random", "selections" ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/hybrid_recommender.py#L58-L70
train
mozilla/taar
taar/recommenders/hybrid_recommender.py
HybridRecommender.recommend
def recommend(self, client_data, limit, extra_data={}): """ Hybrid recommendations simply select half recommendations from the ensemble recommender, and half from the curated one. Duplicate recommendations are accomodated by rank ordering by weight. """ preinstalled_addon_ids = client_data.get("installed_addons", []) # Compute an extended limit by adding the length of # the list of any preinstalled addons. extended_limit = limit + len(preinstalled_addon_ids) ensemble_suggestions = self._ensemble_recommender.recommend( client_data, extended_limit, extra_data ) curated_suggestions = self._curated_recommender.recommend( client_data, extended_limit, extra_data ) # Generate a set of results from each of the composite # recommenders. We select one item from each recommender # sequentially so that we do not bias one recommender over the # other. merged_results = set() while ( len(merged_results) < limit and len(ensemble_suggestions) > 0 and len(curated_suggestions) > 0 ): r1 = ensemble_suggestions.pop() if r1[0] not in [temp[0] for temp in merged_results]: merged_results.add(r1) # Terminate early if we have an odd number for the limit if not ( len(merged_results) < limit and len(ensemble_suggestions) > 0 and len(curated_suggestions) > 0 ): break r2 = curated_suggestions.pop() if r2[0] not in [temp[0] for temp in merged_results]: merged_results.add(r2) if len(merged_results) < limit: msg = ( "Defaulting to empty results. Insufficient recommendations found for client: %s" % client_data["client_id"] ) self.logger.info(msg) return [] sorted_results = sorted( list(merged_results), key=op.itemgetter(1), reverse=True ) log_data = (client_data["client_id"], str([r[0] for r in sorted_results])) self.logger.info( "Hybrid recommendations client_id: [%s], guids: [%s]" % log_data ) return sorted_results
python
def recommend(self, client_data, limit, extra_data={}): """ Hybrid recommendations simply select half recommendations from the ensemble recommender, and half from the curated one. Duplicate recommendations are accomodated by rank ordering by weight. """ preinstalled_addon_ids = client_data.get("installed_addons", []) # Compute an extended limit by adding the length of # the list of any preinstalled addons. extended_limit = limit + len(preinstalled_addon_ids) ensemble_suggestions = self._ensemble_recommender.recommend( client_data, extended_limit, extra_data ) curated_suggestions = self._curated_recommender.recommend( client_data, extended_limit, extra_data ) # Generate a set of results from each of the composite # recommenders. We select one item from each recommender # sequentially so that we do not bias one recommender over the # other. merged_results = set() while ( len(merged_results) < limit and len(ensemble_suggestions) > 0 and len(curated_suggestions) > 0 ): r1 = ensemble_suggestions.pop() if r1[0] not in [temp[0] for temp in merged_results]: merged_results.add(r1) # Terminate early if we have an odd number for the limit if not ( len(merged_results) < limit and len(ensemble_suggestions) > 0 and len(curated_suggestions) > 0 ): break r2 = curated_suggestions.pop() if r2[0] not in [temp[0] for temp in merged_results]: merged_results.add(r2) if len(merged_results) < limit: msg = ( "Defaulting to empty results. Insufficient recommendations found for client: %s" % client_data["client_id"] ) self.logger.info(msg) return [] sorted_results = sorted( list(merged_results), key=op.itemgetter(1), reverse=True ) log_data = (client_data["client_id"], str([r[0] for r in sorted_results])) self.logger.info( "Hybrid recommendations client_id: [%s], guids: [%s]" % log_data ) return sorted_results
[ "def", "recommend", "(", "self", ",", "client_data", ",", "limit", ",", "extra_data", "=", "{", "}", ")", ":", "preinstalled_addon_ids", "=", "client_data", ".", "get", "(", "\"installed_addons\"", ",", "[", "]", ")", "# Compute an extended limit by adding the length of", "# the list of any preinstalled addons.", "extended_limit", "=", "limit", "+", "len", "(", "preinstalled_addon_ids", ")", "ensemble_suggestions", "=", "self", ".", "_ensemble_recommender", ".", "recommend", "(", "client_data", ",", "extended_limit", ",", "extra_data", ")", "curated_suggestions", "=", "self", ".", "_curated_recommender", ".", "recommend", "(", "client_data", ",", "extended_limit", ",", "extra_data", ")", "# Generate a set of results from each of the composite", "# recommenders. We select one item from each recommender", "# sequentially so that we do not bias one recommender over the", "# other.", "merged_results", "=", "set", "(", ")", "while", "(", "len", "(", "merged_results", ")", "<", "limit", "and", "len", "(", "ensemble_suggestions", ")", ">", "0", "and", "len", "(", "curated_suggestions", ")", ">", "0", ")", ":", "r1", "=", "ensemble_suggestions", ".", "pop", "(", ")", "if", "r1", "[", "0", "]", "not", "in", "[", "temp", "[", "0", "]", "for", "temp", "in", "merged_results", "]", ":", "merged_results", ".", "add", "(", "r1", ")", "# Terminate early if we have an odd number for the limit", "if", "not", "(", "len", "(", "merged_results", ")", "<", "limit", "and", "len", "(", "ensemble_suggestions", ")", ">", "0", "and", "len", "(", "curated_suggestions", ")", ">", "0", ")", ":", "break", "r2", "=", "curated_suggestions", ".", "pop", "(", ")", "if", "r2", "[", "0", "]", "not", "in", "[", "temp", "[", "0", "]", "for", "temp", "in", "merged_results", "]", ":", "merged_results", ".", "add", "(", "r2", ")", "if", "len", "(", "merged_results", ")", "<", "limit", ":", "msg", "=", "(", "\"Defaulting to empty results. Insufficient recommendations found for client: %s\"", "%", "client_data", "[", "\"client_id\"", "]", ")", "self", ".", "logger", ".", "info", "(", "msg", ")", "return", "[", "]", "sorted_results", "=", "sorted", "(", "list", "(", "merged_results", ")", ",", "key", "=", "op", ".", "itemgetter", "(", "1", ")", ",", "reverse", "=", "True", ")", "log_data", "=", "(", "client_data", "[", "\"client_id\"", "]", ",", "str", "(", "[", "r", "[", "0", "]", "for", "r", "in", "sorted_results", "]", ")", ")", "self", ".", "logger", ".", "info", "(", "\"Hybrid recommendations client_id: [%s], guids: [%s]\"", "%", "log_data", ")", "return", "sorted_results" ]
Hybrid recommendations simply select half recommendations from the ensemble recommender, and half from the curated one. Duplicate recommendations are accomodated by rank ordering by weight.
[ "Hybrid", "recommendations", "simply", "select", "half", "recommendations", "from", "the", "ensemble", "recommender", "and", "half", "from", "the", "curated", "one", "." ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/hybrid_recommender.py#L102-L169
train
mozilla/taar
taar/recommenders/ensemble_recommender.py
EnsembleRecommender._recommend
def _recommend(self, client_data, limit, extra_data={}): """ Ensemble recommendations are aggregated from individual recommenders. The ensemble recommender applies a weight to the recommendation outputs of each recommender to reorder the recommendations to be a better fit. The intuitive understanding is that the total space of recommended addons across all recommenders will include the 'true' addons that should be recommended better than any individual recommender. The ensemble method simply needs to weight each recommender appropriate so that the ordering is correct. """ self.logger.info("Ensemble recommend invoked") preinstalled_addon_ids = client_data.get("installed_addons", []) # Compute an extended limit by adding the length of # the list of any preinstalled addons. extended_limit = limit + len(preinstalled_addon_ids) flattened_results = [] ensemble_weights = self._weight_cache.getWeights() for rkey in self.RECOMMENDER_KEYS: recommender = self._recommender_map[rkey] if recommender.can_recommend(client_data): raw_results = recommender.recommend( client_data, extended_limit, extra_data ) reweighted_results = [] for guid, weight in raw_results: item = (guid, weight * ensemble_weights[rkey]) reweighted_results.append(item) flattened_results.extend(reweighted_results) # Sort the results by the GUID flattened_results.sort(key=lambda item: item[0]) # group by the guid, sum up the weights for recurring GUID # suggestions across all recommenders guid_grouper = itertools.groupby(flattened_results, lambda item: item[0]) ensemble_suggestions = [] for (guid, guid_group) in guid_grouper: weight_sum = sum([v for (g, v) in guid_group]) item = (guid, weight_sum) ensemble_suggestions.append(item) # Sort in reverse order (greatest weight to least) ensemble_suggestions.sort(key=lambda x: -x[1]) filtered_ensemble_suggestions = [ (guid, weight) for (guid, weight) in ensemble_suggestions if guid not in preinstalled_addon_ids ] results = filtered_ensemble_suggestions[:limit] log_data = ( client_data["client_id"], str(ensemble_weights), str([r[0] for r in results]), ) self.logger.info( "client_id: [%s], ensemble_weight: [%s], guids: [%s]" % log_data ) return results
python
def _recommend(self, client_data, limit, extra_data={}): """ Ensemble recommendations are aggregated from individual recommenders. The ensemble recommender applies a weight to the recommendation outputs of each recommender to reorder the recommendations to be a better fit. The intuitive understanding is that the total space of recommended addons across all recommenders will include the 'true' addons that should be recommended better than any individual recommender. The ensemble method simply needs to weight each recommender appropriate so that the ordering is correct. """ self.logger.info("Ensemble recommend invoked") preinstalled_addon_ids = client_data.get("installed_addons", []) # Compute an extended limit by adding the length of # the list of any preinstalled addons. extended_limit = limit + len(preinstalled_addon_ids) flattened_results = [] ensemble_weights = self._weight_cache.getWeights() for rkey in self.RECOMMENDER_KEYS: recommender = self._recommender_map[rkey] if recommender.can_recommend(client_data): raw_results = recommender.recommend( client_data, extended_limit, extra_data ) reweighted_results = [] for guid, weight in raw_results: item = (guid, weight * ensemble_weights[rkey]) reweighted_results.append(item) flattened_results.extend(reweighted_results) # Sort the results by the GUID flattened_results.sort(key=lambda item: item[0]) # group by the guid, sum up the weights for recurring GUID # suggestions across all recommenders guid_grouper = itertools.groupby(flattened_results, lambda item: item[0]) ensemble_suggestions = [] for (guid, guid_group) in guid_grouper: weight_sum = sum([v for (g, v) in guid_group]) item = (guid, weight_sum) ensemble_suggestions.append(item) # Sort in reverse order (greatest weight to least) ensemble_suggestions.sort(key=lambda x: -x[1]) filtered_ensemble_suggestions = [ (guid, weight) for (guid, weight) in ensemble_suggestions if guid not in preinstalled_addon_ids ] results = filtered_ensemble_suggestions[:limit] log_data = ( client_data["client_id"], str(ensemble_weights), str([r[0] for r in results]), ) self.logger.info( "client_id: [%s], ensemble_weight: [%s], guids: [%s]" % log_data ) return results
[ "def", "_recommend", "(", "self", ",", "client_data", ",", "limit", ",", "extra_data", "=", "{", "}", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Ensemble recommend invoked\"", ")", "preinstalled_addon_ids", "=", "client_data", ".", "get", "(", "\"installed_addons\"", ",", "[", "]", ")", "# Compute an extended limit by adding the length of", "# the list of any preinstalled addons.", "extended_limit", "=", "limit", "+", "len", "(", "preinstalled_addon_ids", ")", "flattened_results", "=", "[", "]", "ensemble_weights", "=", "self", ".", "_weight_cache", ".", "getWeights", "(", ")", "for", "rkey", "in", "self", ".", "RECOMMENDER_KEYS", ":", "recommender", "=", "self", ".", "_recommender_map", "[", "rkey", "]", "if", "recommender", ".", "can_recommend", "(", "client_data", ")", ":", "raw_results", "=", "recommender", ".", "recommend", "(", "client_data", ",", "extended_limit", ",", "extra_data", ")", "reweighted_results", "=", "[", "]", "for", "guid", ",", "weight", "in", "raw_results", ":", "item", "=", "(", "guid", ",", "weight", "*", "ensemble_weights", "[", "rkey", "]", ")", "reweighted_results", ".", "append", "(", "item", ")", "flattened_results", ".", "extend", "(", "reweighted_results", ")", "# Sort the results by the GUID", "flattened_results", ".", "sort", "(", "key", "=", "lambda", "item", ":", "item", "[", "0", "]", ")", "# group by the guid, sum up the weights for recurring GUID", "# suggestions across all recommenders", "guid_grouper", "=", "itertools", ".", "groupby", "(", "flattened_results", ",", "lambda", "item", ":", "item", "[", "0", "]", ")", "ensemble_suggestions", "=", "[", "]", "for", "(", "guid", ",", "guid_group", ")", "in", "guid_grouper", ":", "weight_sum", "=", "sum", "(", "[", "v", "for", "(", "g", ",", "v", ")", "in", "guid_group", "]", ")", "item", "=", "(", "guid", ",", "weight_sum", ")", "ensemble_suggestions", ".", "append", "(", "item", ")", "# Sort in reverse order (greatest weight to least)", "ensemble_suggestions", ".", "sort", "(", "key", "=", "lambda", "x", ":", "-", "x", "[", "1", "]", ")", "filtered_ensemble_suggestions", "=", "[", "(", "guid", ",", "weight", ")", "for", "(", "guid", ",", "weight", ")", "in", "ensemble_suggestions", "if", "guid", "not", "in", "preinstalled_addon_ids", "]", "results", "=", "filtered_ensemble_suggestions", "[", ":", "limit", "]", "log_data", "=", "(", "client_data", "[", "\"client_id\"", "]", ",", "str", "(", "ensemble_weights", ")", ",", "str", "(", "[", "r", "[", "0", "]", "for", "r", "in", "results", "]", ")", ",", ")", "self", ".", "logger", ".", "info", "(", "\"client_id: [%s], ensemble_weight: [%s], guids: [%s]\"", "%", "log_data", ")", "return", "results" ]
Ensemble recommendations are aggregated from individual recommenders. The ensemble recommender applies a weight to the recommendation outputs of each recommender to reorder the recommendations to be a better fit. The intuitive understanding is that the total space of recommended addons across all recommenders will include the 'true' addons that should be recommended better than any individual recommender. The ensemble method simply needs to weight each recommender appropriate so that the ordering is correct.
[ "Ensemble", "recommendations", "are", "aggregated", "from", "individual", "recommenders", ".", "The", "ensemble", "recommender", "applies", "a", "weight", "to", "the", "recommendation", "outputs", "of", "each", "recommender", "to", "reorder", "the", "recommendations", "to", "be", "a", "better", "fit", "." ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/ensemble_recommender.py#L81-L150
train
mozilla/taar
taar/recommenders/lazys3.py
LazyJSONLoader.get
def get(self, transform=None): """ Return the JSON defined at the S3 location in the constructor. The get method will reload the S3 object after the TTL has expired. Fetch the JSON object from cache or S3 if necessary """ if not self.has_expired() and self._cached_copy is not None: return self._cached_copy, False return self._refresh_cache(transform), True
python
def get(self, transform=None): """ Return the JSON defined at the S3 location in the constructor. The get method will reload the S3 object after the TTL has expired. Fetch the JSON object from cache or S3 if necessary """ if not self.has_expired() and self._cached_copy is not None: return self._cached_copy, False return self._refresh_cache(transform), True
[ "def", "get", "(", "self", ",", "transform", "=", "None", ")", ":", "if", "not", "self", ".", "has_expired", "(", ")", "and", "self", ".", "_cached_copy", "is", "not", "None", ":", "return", "self", ".", "_cached_copy", ",", "False", "return", "self", ".", "_refresh_cache", "(", "transform", ")", ",", "True" ]
Return the JSON defined at the S3 location in the constructor. The get method will reload the S3 object after the TTL has expired. Fetch the JSON object from cache or S3 if necessary
[ "Return", "the", "JSON", "defined", "at", "the", "S3", "location", "in", "the", "constructor", "." ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/lazys3.py#L43-L54
train
mozilla/taar
bin/pipstrap.py
hashed_download
def hashed_download(url, temp, digest): """Download ``url`` to ``temp``, make sure it has the SHA-256 ``digest``, and return its path.""" # Based on pip 1.4.1's URLOpener but with cert verification removed def opener(): opener = build_opener(HTTPSHandler()) # Strip out HTTPHandler to prevent MITM spoof: for handler in opener.handlers: if isinstance(handler, HTTPHandler): opener.handlers.remove(handler) return opener def read_chunks(response, chunk_size): while True: chunk = response.read(chunk_size) if not chunk: break yield chunk response = opener().open(url) path = join(temp, urlparse(url).path.split('/')[-1]) actual_hash = sha256() with open(path, 'wb') as file: for chunk in read_chunks(response, 4096): file.write(chunk) actual_hash.update(chunk) actual_digest = actual_hash.hexdigest() if actual_digest != digest: raise HashError(url, path, actual_digest, digest) return path
python
def hashed_download(url, temp, digest): """Download ``url`` to ``temp``, make sure it has the SHA-256 ``digest``, and return its path.""" # Based on pip 1.4.1's URLOpener but with cert verification removed def opener(): opener = build_opener(HTTPSHandler()) # Strip out HTTPHandler to prevent MITM spoof: for handler in opener.handlers: if isinstance(handler, HTTPHandler): opener.handlers.remove(handler) return opener def read_chunks(response, chunk_size): while True: chunk = response.read(chunk_size) if not chunk: break yield chunk response = opener().open(url) path = join(temp, urlparse(url).path.split('/')[-1]) actual_hash = sha256() with open(path, 'wb') as file: for chunk in read_chunks(response, 4096): file.write(chunk) actual_hash.update(chunk) actual_digest = actual_hash.hexdigest() if actual_digest != digest: raise HashError(url, path, actual_digest, digest) return path
[ "def", "hashed_download", "(", "url", ",", "temp", ",", "digest", ")", ":", "# Based on pip 1.4.1's URLOpener but with cert verification removed", "def", "opener", "(", ")", ":", "opener", "=", "build_opener", "(", "HTTPSHandler", "(", ")", ")", "# Strip out HTTPHandler to prevent MITM spoof:", "for", "handler", "in", "opener", ".", "handlers", ":", "if", "isinstance", "(", "handler", ",", "HTTPHandler", ")", ":", "opener", ".", "handlers", ".", "remove", "(", "handler", ")", "return", "opener", "def", "read_chunks", "(", "response", ",", "chunk_size", ")", ":", "while", "True", ":", "chunk", "=", "response", ".", "read", "(", "chunk_size", ")", "if", "not", "chunk", ":", "break", "yield", "chunk", "response", "=", "opener", "(", ")", ".", "open", "(", "url", ")", "path", "=", "join", "(", "temp", ",", "urlparse", "(", "url", ")", ".", "path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "actual_hash", "=", "sha256", "(", ")", "with", "open", "(", "path", ",", "'wb'", ")", "as", "file", ":", "for", "chunk", "in", "read_chunks", "(", "response", ",", "4096", ")", ":", "file", ".", "write", "(", "chunk", ")", "actual_hash", ".", "update", "(", "chunk", ")", "actual_digest", "=", "actual_hash", ".", "hexdigest", "(", ")", "if", "actual_digest", "!=", "digest", ":", "raise", "HashError", "(", "url", ",", "path", ",", "actual_digest", ",", "digest", ")", "return", "path" ]
Download ``url`` to ``temp``, make sure it has the SHA-256 ``digest``, and return its path.
[ "Download", "url", "to", "temp", "make", "sure", "it", "has", "the", "SHA", "-", "256", "digest", "and", "return", "its", "path", "." ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/bin/pipstrap.py#L65-L95
train
mozilla/taar
taar/recommenders/similarity_recommender.py
SimilarityRecommender._build_features_caches
def _build_features_caches(self): """This function build two feature cache matrices. That's the self.categorical_features and self.continuous_features attributes. One matrix is for the continuous features and the other is for the categorical features. This is needed to speed up the similarity recommendation process.""" _donors_pool = self._donors_pool.get()[0] _lr_curves = self._lr_curves.get()[0] if _donors_pool is None or _lr_curves is None: # We need to have both donors_pool and lr_curves defined # to reconstruct the matrices return None self.num_donors = len(_donors_pool) # Build a numpy matrix cache for the continuous features. self.continuous_features = np.zeros((self.num_donors, len(CONTINUOUS_FEATURES))) for idx, d in enumerate(_donors_pool): features = [d.get(specified_key) for specified_key in CONTINUOUS_FEATURES] self.continuous_features[idx] = features # Build the cache for categorical features. self.categorical_features = np.zeros( (self.num_donors, len(CATEGORICAL_FEATURES)), dtype="object" ) for idx, d in enumerate(_donors_pool): features = [d.get(specified_key) for specified_key in CATEGORICAL_FEATURES] self.categorical_features[idx] = np.array([features], dtype="object") self.logger.info("Reconstructed matrices for similarity recommender")
python
def _build_features_caches(self): """This function build two feature cache matrices. That's the self.categorical_features and self.continuous_features attributes. One matrix is for the continuous features and the other is for the categorical features. This is needed to speed up the similarity recommendation process.""" _donors_pool = self._donors_pool.get()[0] _lr_curves = self._lr_curves.get()[0] if _donors_pool is None or _lr_curves is None: # We need to have both donors_pool and lr_curves defined # to reconstruct the matrices return None self.num_donors = len(_donors_pool) # Build a numpy matrix cache for the continuous features. self.continuous_features = np.zeros((self.num_donors, len(CONTINUOUS_FEATURES))) for idx, d in enumerate(_donors_pool): features = [d.get(specified_key) for specified_key in CONTINUOUS_FEATURES] self.continuous_features[idx] = features # Build the cache for categorical features. self.categorical_features = np.zeros( (self.num_donors, len(CATEGORICAL_FEATURES)), dtype="object" ) for idx, d in enumerate(_donors_pool): features = [d.get(specified_key) for specified_key in CATEGORICAL_FEATURES] self.categorical_features[idx] = np.array([features], dtype="object") self.logger.info("Reconstructed matrices for similarity recommender")
[ "def", "_build_features_caches", "(", "self", ")", ":", "_donors_pool", "=", "self", ".", "_donors_pool", ".", "get", "(", ")", "[", "0", "]", "_lr_curves", "=", "self", ".", "_lr_curves", ".", "get", "(", ")", "[", "0", "]", "if", "_donors_pool", "is", "None", "or", "_lr_curves", "is", "None", ":", "# We need to have both donors_pool and lr_curves defined", "# to reconstruct the matrices", "return", "None", "self", ".", "num_donors", "=", "len", "(", "_donors_pool", ")", "# Build a numpy matrix cache for the continuous features.", "self", ".", "continuous_features", "=", "np", ".", "zeros", "(", "(", "self", ".", "num_donors", ",", "len", "(", "CONTINUOUS_FEATURES", ")", ")", ")", "for", "idx", ",", "d", "in", "enumerate", "(", "_donors_pool", ")", ":", "features", "=", "[", "d", ".", "get", "(", "specified_key", ")", "for", "specified_key", "in", "CONTINUOUS_FEATURES", "]", "self", ".", "continuous_features", "[", "idx", "]", "=", "features", "# Build the cache for categorical features.", "self", ".", "categorical_features", "=", "np", ".", "zeros", "(", "(", "self", ".", "num_donors", ",", "len", "(", "CATEGORICAL_FEATURES", ")", ")", ",", "dtype", "=", "\"object\"", ")", "for", "idx", ",", "d", "in", "enumerate", "(", "_donors_pool", ")", ":", "features", "=", "[", "d", ".", "get", "(", "specified_key", ")", "for", "specified_key", "in", "CATEGORICAL_FEATURES", "]", "self", ".", "categorical_features", "[", "idx", "]", "=", "np", ".", "array", "(", "[", "features", "]", ",", "dtype", "=", "\"object\"", ")", "self", ".", "logger", ".", "info", "(", "\"Reconstructed matrices for similarity recommender\"", ")" ]
This function build two feature cache matrices. That's the self.categorical_features and self.continuous_features attributes. One matrix is for the continuous features and the other is for the categorical features. This is needed to speed up the similarity recommendation process.
[ "This", "function", "build", "two", "feature", "cache", "matrices", "." ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/similarity_recommender.py#L103-L136
train
mozilla/taar
taar/recommenders/recommendation_manager.py
RecommendationManager.recommend
def recommend(self, client_id, limit, extra_data={}): """Return recommendations for the given client. The recommendation logic will go through each recommender and pick the first one that "can_recommend". :param client_id: the client unique id. :param limit: the maximum number of recommendations to return. :param extra_data: a dictionary with extra client data. """ if client_id in TEST_CLIENT_IDS: data = self._whitelist_data.get()[0] random.shuffle(data) samples = data[:limit] self.logger.info("Test ID detected [{}]".format(client_id)) return [(s, 1.1) for s in samples] if client_id in EMPTY_TEST_CLIENT_IDS: self.logger.info("Empty Test ID detected [{}]".format(client_id)) return [] client_info = self.profile_fetcher.get(client_id) if client_info is None: self.logger.info( "Defaulting to empty results. No client info fetched from dynamo." ) return [] results = self._ensemble_recommender.recommend(client_info, limit, extra_data) return results
python
def recommend(self, client_id, limit, extra_data={}): """Return recommendations for the given client. The recommendation logic will go through each recommender and pick the first one that "can_recommend". :param client_id: the client unique id. :param limit: the maximum number of recommendations to return. :param extra_data: a dictionary with extra client data. """ if client_id in TEST_CLIENT_IDS: data = self._whitelist_data.get()[0] random.shuffle(data) samples = data[:limit] self.logger.info("Test ID detected [{}]".format(client_id)) return [(s, 1.1) for s in samples] if client_id in EMPTY_TEST_CLIENT_IDS: self.logger.info("Empty Test ID detected [{}]".format(client_id)) return [] client_info = self.profile_fetcher.get(client_id) if client_info is None: self.logger.info( "Defaulting to empty results. No client info fetched from dynamo." ) return [] results = self._ensemble_recommender.recommend(client_info, limit, extra_data) return results
[ "def", "recommend", "(", "self", ",", "client_id", ",", "limit", ",", "extra_data", "=", "{", "}", ")", ":", "if", "client_id", "in", "TEST_CLIENT_IDS", ":", "data", "=", "self", ".", "_whitelist_data", ".", "get", "(", ")", "[", "0", "]", "random", ".", "shuffle", "(", "data", ")", "samples", "=", "data", "[", ":", "limit", "]", "self", ".", "logger", ".", "info", "(", "\"Test ID detected [{}]\"", ".", "format", "(", "client_id", ")", ")", "return", "[", "(", "s", ",", "1.1", ")", "for", "s", "in", "samples", "]", "if", "client_id", "in", "EMPTY_TEST_CLIENT_IDS", ":", "self", ".", "logger", ".", "info", "(", "\"Empty Test ID detected [{}]\"", ".", "format", "(", "client_id", ")", ")", "return", "[", "]", "client_info", "=", "self", ".", "profile_fetcher", ".", "get", "(", "client_id", ")", "if", "client_info", "is", "None", ":", "self", ".", "logger", ".", "info", "(", "\"Defaulting to empty results. No client info fetched from dynamo.\"", ")", "return", "[", "]", "results", "=", "self", ".", "_ensemble_recommender", ".", "recommend", "(", "client_info", ",", "limit", ",", "extra_data", ")", "return", "results" ]
Return recommendations for the given client. The recommendation logic will go through each recommender and pick the first one that "can_recommend". :param client_id: the client unique id. :param limit: the maximum number of recommendations to return. :param extra_data: a dictionary with extra client data.
[ "Return", "recommendations", "for", "the", "given", "client", "." ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/recommendation_manager.py#L85-L116
train
mozilla/taar
taar/profile_fetcher.py
ProfileController.get_client_profile
def get_client_profile(self, client_id): """This fetches a single client record out of DynamoDB """ try: response = self._table.get_item(Key={'client_id': client_id}) compressed_bytes = response['Item']['json_payload'].value json_byte_data = zlib.decompress(compressed_bytes) json_str_data = json_byte_data.decode('utf8') return json.loads(json_str_data) except KeyError: # No client ID found - not really an error return None except Exception as e: # Return None on error. The caller in ProfileFetcher will # handle error logging msg = "Error loading client data for {}. Error: {}" self.logger.debug(msg.format(client_id, str(e))) return None
python
def get_client_profile(self, client_id): """This fetches a single client record out of DynamoDB """ try: response = self._table.get_item(Key={'client_id': client_id}) compressed_bytes = response['Item']['json_payload'].value json_byte_data = zlib.decompress(compressed_bytes) json_str_data = json_byte_data.decode('utf8') return json.loads(json_str_data) except KeyError: # No client ID found - not really an error return None except Exception as e: # Return None on error. The caller in ProfileFetcher will # handle error logging msg = "Error loading client data for {}. Error: {}" self.logger.debug(msg.format(client_id, str(e))) return None
[ "def", "get_client_profile", "(", "self", ",", "client_id", ")", ":", "try", ":", "response", "=", "self", ".", "_table", ".", "get_item", "(", "Key", "=", "{", "'client_id'", ":", "client_id", "}", ")", "compressed_bytes", "=", "response", "[", "'Item'", "]", "[", "'json_payload'", "]", ".", "value", "json_byte_data", "=", "zlib", ".", "decompress", "(", "compressed_bytes", ")", "json_str_data", "=", "json_byte_data", ".", "decode", "(", "'utf8'", ")", "return", "json", ".", "loads", "(", "json_str_data", ")", "except", "KeyError", ":", "# No client ID found - not really an error", "return", "None", "except", "Exception", "as", "e", ":", "# Return None on error. The caller in ProfileFetcher will", "# handle error logging", "msg", "=", "\"Error loading client data for {}. Error: {}\"", "self", ".", "logger", ".", "debug", "(", "msg", ".", "format", "(", "client_id", ",", "str", "(", "e", ")", ")", ")", "return", "None" ]
This fetches a single client record out of DynamoDB
[ "This", "fetches", "a", "single", "client", "record", "out", "of", "DynamoDB" ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/profile_fetcher.py#L33-L50
train
mozilla/taar
taar/plugin.py
clean_promoted_guids
def clean_promoted_guids(raw_promoted_guids): """ Verify that the promoted GUIDs are formatted correctly, otherwise strip it down into an empty list. """ valid = True for row in raw_promoted_guids: if len(row) != 2: valid = False break if not ( (isinstance(row[0], str) or isinstance(row[0], unicode)) and (isinstance(row[1], int) or isinstance(row[1], float)) # noqa ): valid = False break if valid: return raw_promoted_guids return []
python
def clean_promoted_guids(raw_promoted_guids): """ Verify that the promoted GUIDs are formatted correctly, otherwise strip it down into an empty list. """ valid = True for row in raw_promoted_guids: if len(row) != 2: valid = False break if not ( (isinstance(row[0], str) or isinstance(row[0], unicode)) and (isinstance(row[1], int) or isinstance(row[1], float)) # noqa ): valid = False break if valid: return raw_promoted_guids return []
[ "def", "clean_promoted_guids", "(", "raw_promoted_guids", ")", ":", "valid", "=", "True", "for", "row", "in", "raw_promoted_guids", ":", "if", "len", "(", "row", ")", "!=", "2", ":", "valid", "=", "False", "break", "if", "not", "(", "(", "isinstance", "(", "row", "[", "0", "]", ",", "str", ")", "or", "isinstance", "(", "row", "[", "0", "]", ",", "unicode", ")", ")", "and", "(", "isinstance", "(", "row", "[", "1", "]", ",", "int", ")", "or", "isinstance", "(", "row", "[", "1", "]", ",", "float", ")", ")", "# noqa", ")", ":", "valid", "=", "False", "break", "if", "valid", ":", "return", "raw_promoted_guids", "return", "[", "]" ]
Verify that the promoted GUIDs are formatted correctly, otherwise strip it down into an empty list.
[ "Verify", "that", "the", "promoted", "GUIDs", "are", "formatted", "correctly", "otherwise", "strip", "it", "down", "into", "an", "empty", "list", "." ]
4002eb395f0b7ad837f1578e92d590e2cf82bdca
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/plugin.py#L32-L52
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi.login
def login(self): """Login to Tahoma API.""" if self.__logged_in: return login = {'userId': self.__username, 'userPassword': self.__password} header = BASE_HEADERS.copy() request = requests.post(BASE_URL + 'login', data=login, headers=header, timeout=10) try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for login, " + "protocol error: " + request.status_code + ' - ' + request.reason + "(" + str(error) + ")") if 'error' in result.keys(): raise Exception("Could not login: " + result['error']) if request.status_code != 200: raise Exception( "Could not login, HTTP code: " + str(request.status_code) + ' - ' + request.reason) if 'success' not in result.keys() or not result['success']: raise Exception("Could not login, no success") cookie = request.headers.get("set-cookie") if cookie is None: raise Exception("Could not login, no cookie set") self.__cookie = cookie self.__logged_in = True return self.__logged_in
python
def login(self): """Login to Tahoma API.""" if self.__logged_in: return login = {'userId': self.__username, 'userPassword': self.__password} header = BASE_HEADERS.copy() request = requests.post(BASE_URL + 'login', data=login, headers=header, timeout=10) try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for login, " + "protocol error: " + request.status_code + ' - ' + request.reason + "(" + str(error) + ")") if 'error' in result.keys(): raise Exception("Could not login: " + result['error']) if request.status_code != 200: raise Exception( "Could not login, HTTP code: " + str(request.status_code) + ' - ' + request.reason) if 'success' not in result.keys() or not result['success']: raise Exception("Could not login, no success") cookie = request.headers.get("set-cookie") if cookie is None: raise Exception("Could not login, no cookie set") self.__cookie = cookie self.__logged_in = True return self.__logged_in
[ "def", "login", "(", "self", ")", ":", "if", "self", ".", "__logged_in", ":", "return", "login", "=", "{", "'userId'", ":", "self", ".", "__username", ",", "'userPassword'", ":", "self", ".", "__password", "}", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "request", "=", "requests", ".", "post", "(", "BASE_URL", "+", "'login'", ",", "data", "=", "login", ",", "headers", "=", "header", ",", "timeout", "=", "10", ")", "try", ":", "result", "=", "request", ".", "json", "(", ")", "except", "ValueError", "as", "error", ":", "raise", "Exception", "(", "\"Not a valid result for login, \"", "+", "\"protocol error: \"", "+", "request", ".", "status_code", "+", "' - '", "+", "request", ".", "reason", "+", "\"(\"", "+", "str", "(", "error", ")", "+", "\")\"", ")", "if", "'error'", "in", "result", ".", "keys", "(", ")", ":", "raise", "Exception", "(", "\"Could not login: \"", "+", "result", "[", "'error'", "]", ")", "if", "request", ".", "status_code", "!=", "200", ":", "raise", "Exception", "(", "\"Could not login, HTTP code: \"", "+", "str", "(", "request", ".", "status_code", ")", "+", "' - '", "+", "request", ".", "reason", ")", "if", "'success'", "not", "in", "result", ".", "keys", "(", ")", "or", "not", "result", "[", "'success'", "]", ":", "raise", "Exception", "(", "\"Could not login, no success\"", ")", "cookie", "=", "request", ".", "headers", ".", "get", "(", "\"set-cookie\"", ")", "if", "cookie", "is", "None", ":", "raise", "Exception", "(", "\"Could not login, no cookie set\"", ")", "self", ".", "__cookie", "=", "cookie", "self", ".", "__logged_in", "=", "True", "return", "self", ".", "__logged_in" ]
Login to Tahoma API.
[ "Login", "to", "Tahoma", "API", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L32-L68
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi.get_user
def get_user(self): """Get the user informations from the server. :return: a dict with all the informations :rtype: dict raises ValueError in case of protocol issues :Example: >>> "creationTime": <time>, >>> "lastUpdateTime": <time>, >>> "userId": "<email for login>", >>> "title": 0, >>> "firstName": "<First>", >>> "lastName": "<Last>", >>> "email": "<contact email>", >>> "phoneNumber": "<phone>", >>> "mobilePhone": "<mobile>", >>> "locale": "<two char country code>" :Warning: The type and amount of values in the dictionary can change any time. """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get(BASE_URL + 'getEndUser', headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_user() return try: result = request.json() except ValueError: raise Exception( "Not a valid result for getEndUser, protocol error!") return result['endUser']
python
def get_user(self): """Get the user informations from the server. :return: a dict with all the informations :rtype: dict raises ValueError in case of protocol issues :Example: >>> "creationTime": <time>, >>> "lastUpdateTime": <time>, >>> "userId": "<email for login>", >>> "title": 0, >>> "firstName": "<First>", >>> "lastName": "<Last>", >>> "email": "<contact email>", >>> "phoneNumber": "<phone>", >>> "mobilePhone": "<mobile>", >>> "locale": "<two char country code>" :Warning: The type and amount of values in the dictionary can change any time. """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get(BASE_URL + 'getEndUser', headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_user() return try: result = request.json() except ValueError: raise Exception( "Not a valid result for getEndUser, protocol error!") return result['endUser']
[ "def", "get_user", "(", "self", ")", ":", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "header", "[", "'Cookie'", "]", "=", "self", ".", "__cookie", "request", "=", "requests", ".", "get", "(", "BASE_URL", "+", "'getEndUser'", ",", "headers", "=", "header", ",", "timeout", "=", "10", ")", "if", "request", ".", "status_code", "!=", "200", ":", "self", ".", "__logged_in", "=", "False", "self", ".", "login", "(", ")", "self", ".", "get_user", "(", ")", "return", "try", ":", "result", "=", "request", ".", "json", "(", ")", "except", "ValueError", ":", "raise", "Exception", "(", "\"Not a valid result for getEndUser, protocol error!\"", ")", "return", "result", "[", "'endUser'", "]" ]
Get the user informations from the server. :return: a dict with all the informations :rtype: dict raises ValueError in case of protocol issues :Example: >>> "creationTime": <time>, >>> "lastUpdateTime": <time>, >>> "userId": "<email for login>", >>> "title": 0, >>> "firstName": "<First>", >>> "lastName": "<Last>", >>> "email": "<contact email>", >>> "phoneNumber": "<phone>", >>> "mobilePhone": "<mobile>", >>> "locale": "<two char country code>" :Warning: The type and amount of values in the dictionary can change any time.
[ "Get", "the", "user", "informations", "from", "the", "server", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L70-L114
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi._get_setup
def _get_setup(self, result): """Internal method which process the results from the server.""" self.__devices = {} if ('setup' not in result.keys() or 'devices' not in result['setup'].keys()): raise Exception( "Did not find device definition.") for device_data in result['setup']['devices']: device = Device(self, device_data) self.__devices[device.url] = device self.__location = result['setup']['location'] self.__gateway = result['setup']['gateways']
python
def _get_setup(self, result): """Internal method which process the results from the server.""" self.__devices = {} if ('setup' not in result.keys() or 'devices' not in result['setup'].keys()): raise Exception( "Did not find device definition.") for device_data in result['setup']['devices']: device = Device(self, device_data) self.__devices[device.url] = device self.__location = result['setup']['location'] self.__gateway = result['setup']['gateways']
[ "def", "_get_setup", "(", "self", ",", "result", ")", ":", "self", ".", "__devices", "=", "{", "}", "if", "(", "'setup'", "not", "in", "result", ".", "keys", "(", ")", "or", "'devices'", "not", "in", "result", "[", "'setup'", "]", ".", "keys", "(", ")", ")", ":", "raise", "Exception", "(", "\"Did not find device definition.\"", ")", "for", "device_data", "in", "result", "[", "'setup'", "]", "[", "'devices'", "]", ":", "device", "=", "Device", "(", "self", ",", "device_data", ")", "self", ".", "__devices", "[", "device", ".", "url", "]", "=", "device", "self", ".", "__location", "=", "result", "[", "'setup'", "]", "[", "'location'", "]", "self", ".", "__gateway", "=", "result", "[", "'setup'", "]", "[", "'gateways'", "]" ]
Internal method which process the results from the server.
[ "Internal", "method", "which", "process", "the", "results", "from", "the", "server", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L156-L170
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi.apply_actions
def apply_actions(self, name_of_action, actions): """Start to execute an action or a group of actions. This method takes a bunch of actions and runs them on your Tahoma box. :param name_of_action: the label/name for the action :param actions: an array of Action objects :return: the execution identifier ************** what if it fails :rtype: string raises ValueError in case of protocol issues :Seealso: - get_events - get_current_executions """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie actions_serialized = [] for action in actions: actions_serialized.append(action.serialize()) data = {"label": name_of_action, "actions": actions_serialized} json_data = json.dumps(data, indent=None, sort_keys=True) request = requests.post( BASE_URL + "apply", headers=header, data=json_data, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.apply_actions(name_of_action, actions) return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for applying an " + "action, protocol error: " + request.status_code + ' - ' + request.reason + " (" + error + ")") if 'execId' not in result.keys(): raise Exception("Could not run actions, missing execId.") return result['execId']
python
def apply_actions(self, name_of_action, actions): """Start to execute an action or a group of actions. This method takes a bunch of actions and runs them on your Tahoma box. :param name_of_action: the label/name for the action :param actions: an array of Action objects :return: the execution identifier ************** what if it fails :rtype: string raises ValueError in case of protocol issues :Seealso: - get_events - get_current_executions """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie actions_serialized = [] for action in actions: actions_serialized.append(action.serialize()) data = {"label": name_of_action, "actions": actions_serialized} json_data = json.dumps(data, indent=None, sort_keys=True) request = requests.post( BASE_URL + "apply", headers=header, data=json_data, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.apply_actions(name_of_action, actions) return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for applying an " + "action, protocol error: " + request.status_code + ' - ' + request.reason + " (" + error + ")") if 'execId' not in result.keys(): raise Exception("Could not run actions, missing execId.") return result['execId']
[ "def", "apply_actions", "(", "self", ",", "name_of_action", ",", "actions", ")", ":", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "header", "[", "'Cookie'", "]", "=", "self", ".", "__cookie", "actions_serialized", "=", "[", "]", "for", "action", "in", "actions", ":", "actions_serialized", ".", "append", "(", "action", ".", "serialize", "(", ")", ")", "data", "=", "{", "\"label\"", ":", "name_of_action", ",", "\"actions\"", ":", "actions_serialized", "}", "json_data", "=", "json", ".", "dumps", "(", "data", ",", "indent", "=", "None", ",", "sort_keys", "=", "True", ")", "request", "=", "requests", ".", "post", "(", "BASE_URL", "+", "\"apply\"", ",", "headers", "=", "header", ",", "data", "=", "json_data", ",", "timeout", "=", "10", ")", "if", "request", ".", "status_code", "!=", "200", ":", "self", ".", "__logged_in", "=", "False", "self", ".", "login", "(", ")", "self", ".", "apply_actions", "(", "name_of_action", ",", "actions", ")", "return", "try", ":", "result", "=", "request", ".", "json", "(", ")", "except", "ValueError", "as", "error", ":", "raise", "Exception", "(", "\"Not a valid result for applying an \"", "+", "\"action, protocol error: \"", "+", "request", ".", "status_code", "+", "' - '", "+", "request", ".", "reason", "+", "\" (\"", "+", "error", "+", "\")\"", ")", "if", "'execId'", "not", "in", "result", ".", "keys", "(", ")", ":", "raise", "Exception", "(", "\"Could not run actions, missing execId.\"", ")", "return", "result", "[", "'execId'", "]" ]
Start to execute an action or a group of actions. This method takes a bunch of actions and runs them on your Tahoma box. :param name_of_action: the label/name for the action :param actions: an array of Action objects :return: the execution identifier ************** what if it fails :rtype: string raises ValueError in case of protocol issues :Seealso: - get_events - get_current_executions
[ "Start", "to", "execute", "an", "action", "or", "a", "group", "of", "actions", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L281-L333
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi.get_events
def get_events(self): """Return a set of events. Which have been occured since the last call of this method. This method should be called regulary to get all occuring Events. There are three different Event types/classes which can be returned: - DeviceStateChangedEvent, if any device changed it's state due to an applied action or just because of other reasons - CommandExecutionStateChangedEvent, a executed command goes through several phases which can be followed - ExecutionStateChangedEvent, ******** todo :return: an array of Events or empty array :rtype: list raises ValueError in case of protocol issues :Seealso: - apply_actions - launch_action_group - get_history """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.post(BASE_URL + 'getEvents', headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_events() return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for getEvent," + " protocol error: " + error) return self._get_events(result)
python
def get_events(self): """Return a set of events. Which have been occured since the last call of this method. This method should be called regulary to get all occuring Events. There are three different Event types/classes which can be returned: - DeviceStateChangedEvent, if any device changed it's state due to an applied action or just because of other reasons - CommandExecutionStateChangedEvent, a executed command goes through several phases which can be followed - ExecutionStateChangedEvent, ******** todo :return: an array of Events or empty array :rtype: list raises ValueError in case of protocol issues :Seealso: - apply_actions - launch_action_group - get_history """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.post(BASE_URL + 'getEvents', headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_events() return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for getEvent," + " protocol error: " + error) return self._get_events(result)
[ "def", "get_events", "(", "self", ")", ":", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "header", "[", "'Cookie'", "]", "=", "self", ".", "__cookie", "request", "=", "requests", ".", "post", "(", "BASE_URL", "+", "'getEvents'", ",", "headers", "=", "header", ",", "timeout", "=", "10", ")", "if", "request", ".", "status_code", "!=", "200", ":", "self", ".", "__logged_in", "=", "False", "self", ".", "login", "(", ")", "self", ".", "get_events", "(", ")", "return", "try", ":", "result", "=", "request", ".", "json", "(", ")", "except", "ValueError", "as", "error", ":", "raise", "Exception", "(", "\"Not a valid result for getEvent,\"", "+", "\" protocol error: \"", "+", "error", ")", "return", "self", ".", "_get_events", "(", "result", ")" ]
Return a set of events. Which have been occured since the last call of this method. This method should be called regulary to get all occuring Events. There are three different Event types/classes which can be returned: - DeviceStateChangedEvent, if any device changed it's state due to an applied action or just because of other reasons - CommandExecutionStateChangedEvent, a executed command goes through several phases which can be followed - ExecutionStateChangedEvent, ******** todo :return: an array of Events or empty array :rtype: list raises ValueError in case of protocol issues :Seealso: - apply_actions - launch_action_group - get_history
[ "Return", "a", "set", "of", "events", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L335-L381
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi._get_events
def _get_events(self, result): """"Internal method for being able to run unit tests.""" events = [] for event_data in result: event = Event.factory(event_data) if event is not None: events.append(event) if isinstance(event, DeviceStateChangedEvent): # change device state if self.__devices[event.device_url] is None: raise Exception( "Received device change " + "state for unknown device '" + event.device_url + "'") self.__devices[event.device_url].set_active_states( event.states) return events
python
def _get_events(self, result): """"Internal method for being able to run unit tests.""" events = [] for event_data in result: event = Event.factory(event_data) if event is not None: events.append(event) if isinstance(event, DeviceStateChangedEvent): # change device state if self.__devices[event.device_url] is None: raise Exception( "Received device change " + "state for unknown device '" + event.device_url + "'") self.__devices[event.device_url].set_active_states( event.states) return events
[ "def", "_get_events", "(", "self", ",", "result", ")", ":", "events", "=", "[", "]", "for", "event_data", "in", "result", ":", "event", "=", "Event", ".", "factory", "(", "event_data", ")", "if", "event", "is", "not", "None", ":", "events", ".", "append", "(", "event", ")", "if", "isinstance", "(", "event", ",", "DeviceStateChangedEvent", ")", ":", "# change device state", "if", "self", ".", "__devices", "[", "event", ".", "device_url", "]", "is", "None", ":", "raise", "Exception", "(", "\"Received device change \"", "+", "\"state for unknown device '\"", "+", "event", ".", "device_url", "+", "\"'\"", ")", "self", ".", "__devices", "[", "event", ".", "device_url", "]", ".", "set_active_states", "(", "event", ".", "states", ")", "return", "events" ]
Internal method for being able to run unit tests.
[ "Internal", "method", "for", "being", "able", "to", "run", "unit", "tests", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L383-L404
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi.get_current_executions
def get_current_executions(self): """Get all current running executions. :return: Returns a set of running Executions or empty list. :rtype: list raises ValueError in case of protocol issues :Seealso: - apply_actions - launch_action_group - get_history """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get( BASE_URL + 'getCurrentExecutions', headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_current_executions() return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for" + "get_current_executions, protocol error: " + error) if 'executions' not in result.keys(): return None executions = [] for execution_data in result['executions']: exe = Execution(execution_data) executions.append(exe) return executions
python
def get_current_executions(self): """Get all current running executions. :return: Returns a set of running Executions or empty list. :rtype: list raises ValueError in case of protocol issues :Seealso: - apply_actions - launch_action_group - get_history """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get( BASE_URL + 'getCurrentExecutions', headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_current_executions() return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for" + "get_current_executions, protocol error: " + error) if 'executions' not in result.keys(): return None executions = [] for execution_data in result['executions']: exe = Execution(execution_data) executions.append(exe) return executions
[ "def", "get_current_executions", "(", "self", ")", ":", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "header", "[", "'Cookie'", "]", "=", "self", ".", "__cookie", "request", "=", "requests", ".", "get", "(", "BASE_URL", "+", "'getCurrentExecutions'", ",", "headers", "=", "header", ",", "timeout", "=", "10", ")", "if", "request", ".", "status_code", "!=", "200", ":", "self", ".", "__logged_in", "=", "False", "self", ".", "login", "(", ")", "self", ".", "get_current_executions", "(", ")", "return", "try", ":", "result", "=", "request", ".", "json", "(", ")", "except", "ValueError", "as", "error", ":", "raise", "Exception", "(", "\"Not a valid result for\"", "+", "\"get_current_executions, protocol error: \"", "+", "error", ")", "if", "'executions'", "not", "in", "result", ".", "keys", "(", ")", ":", "return", "None", "executions", "=", "[", "]", "for", "execution_data", "in", "result", "[", "'executions'", "]", ":", "exe", "=", "Execution", "(", "execution_data", ")", "executions", ".", "append", "(", "exe", ")", "return", "executions" ]
Get all current running executions. :return: Returns a set of running Executions or empty list. :rtype: list raises ValueError in case of protocol issues :Seealso: - apply_actions - launch_action_group - get_history
[ "Get", "all", "current", "running", "executions", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L406-L451
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi.get_action_groups
def get_action_groups(self): """Get all Action Groups. :return: List of Action Groups """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get(BASE_URL + "getActionGroups", headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_action_groups() return try: result = request.json() except ValueError: raise Exception( "get_action_groups: Not a valid result for ") if 'actionGroups' not in result.keys(): return None groups = [] for group_data in result['actionGroups']: group = ActionGroup(group_data) groups.append(group) return groups
python
def get_action_groups(self): """Get all Action Groups. :return: List of Action Groups """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get(BASE_URL + "getActionGroups", headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_action_groups() return try: result = request.json() except ValueError: raise Exception( "get_action_groups: Not a valid result for ") if 'actionGroups' not in result.keys(): return None groups = [] for group_data in result['actionGroups']: group = ActionGroup(group_data) groups.append(group) return groups
[ "def", "get_action_groups", "(", "self", ")", ":", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "header", "[", "'Cookie'", "]", "=", "self", ".", "__cookie", "request", "=", "requests", ".", "get", "(", "BASE_URL", "+", "\"getActionGroups\"", ",", "headers", "=", "header", ",", "timeout", "=", "10", ")", "if", "request", ".", "status_code", "!=", "200", ":", "self", ".", "__logged_in", "=", "False", "self", ".", "login", "(", ")", "self", ".", "get_action_groups", "(", ")", "return", "try", ":", "result", "=", "request", ".", "json", "(", ")", "except", "ValueError", ":", "raise", "Exception", "(", "\"get_action_groups: Not a valid result for \"", ")", "if", "'actionGroups'", "not", "in", "result", ".", "keys", "(", ")", ":", "return", "None", "groups", "=", "[", "]", "for", "group_data", "in", "result", "[", "'actionGroups'", "]", ":", "group", "=", "ActionGroup", "(", "group_data", ")", "groups", ".", "append", "(", "group", ")", "return", "groups" ]
Get all Action Groups. :return: List of Action Groups
[ "Get", "all", "Action", "Groups", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L494-L527
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi.launch_action_group
def launch_action_group(self, action_id): """Start action group.""" header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get( BASE_URL + 'launchActionGroup?oid=' + action_id, headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.launch_action_group(action_id) return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for launch" + "action group, protocol error: " + request.status_code + ' - ' + request.reason + " (" + error + ")") if 'actionGroup' not in result.keys(): raise Exception( "Could not launch action" + "group, missing execId.") return result['actionGroup'][0]['execId']
python
def launch_action_group(self, action_id): """Start action group.""" header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get( BASE_URL + 'launchActionGroup?oid=' + action_id, headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.launch_action_group(action_id) return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for launch" + "action group, protocol error: " + request.status_code + ' - ' + request.reason + " (" + error + ")") if 'actionGroup' not in result.keys(): raise Exception( "Could not launch action" + "group, missing execId.") return result['actionGroup'][0]['execId']
[ "def", "launch_action_group", "(", "self", ",", "action_id", ")", ":", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "header", "[", "'Cookie'", "]", "=", "self", ".", "__cookie", "request", "=", "requests", ".", "get", "(", "BASE_URL", "+", "'launchActionGroup?oid='", "+", "action_id", ",", "headers", "=", "header", ",", "timeout", "=", "10", ")", "if", "request", ".", "status_code", "!=", "200", ":", "self", ".", "__logged_in", "=", "False", "self", ".", "login", "(", ")", "self", ".", "launch_action_group", "(", "action_id", ")", "return", "try", ":", "result", "=", "request", ".", "json", "(", ")", "except", "ValueError", "as", "error", ":", "raise", "Exception", "(", "\"Not a valid result for launch\"", "+", "\"action group, protocol error: \"", "+", "request", ".", "status_code", "+", "' - '", "+", "request", ".", "reason", "+", "\" (\"", "+", "error", "+", "\")\"", ")", "if", "'actionGroup'", "not", "in", "result", ".", "keys", "(", ")", ":", "raise", "Exception", "(", "\"Could not launch action\"", "+", "\"group, missing execId.\"", ")", "return", "result", "[", "'actionGroup'", "]", "[", "0", "]", "[", "'execId'", "]" ]
Start action group.
[ "Start", "action", "group", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L529-L560
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi.get_states
def get_states(self, devices): """Get States of Devices.""" header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie json_data = self._create_get_state_request(devices) request = requests.post( BASE_URL + 'getStates', headers=header, data=json_data, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_states(devices) return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for" + "getStates, protocol error:" + error) self._get_states(result)
python
def get_states(self, devices): """Get States of Devices.""" header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie json_data = self._create_get_state_request(devices) request = requests.post( BASE_URL + 'getStates', headers=header, data=json_data, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_states(devices) return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for" + "getStates, protocol error:" + error) self._get_states(result)
[ "def", "get_states", "(", "self", ",", "devices", ")", ":", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "header", "[", "'Cookie'", "]", "=", "self", ".", "__cookie", "json_data", "=", "self", ".", "_create_get_state_request", "(", "devices", ")", "request", "=", "requests", ".", "post", "(", "BASE_URL", "+", "'getStates'", ",", "headers", "=", "header", ",", "data", "=", "json_data", ",", "timeout", "=", "10", ")", "if", "request", ".", "status_code", "!=", "200", ":", "self", ".", "__logged_in", "=", "False", "self", ".", "login", "(", ")", "self", ".", "get_states", "(", "devices", ")", "return", "try", ":", "result", "=", "request", ".", "json", "(", ")", "except", "ValueError", "as", "error", ":", "raise", "Exception", "(", "\"Not a valid result for\"", "+", "\"getStates, protocol error:\"", "+", "error", ")", "self", ".", "_get_states", "(", "result", ")" ]
Get States of Devices.
[ "Get", "States", "of", "Devices", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L562-L588
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi._create_get_state_request
def _create_get_state_request(self, given_devices): """Create state request.""" dev_list = [] if isinstance(given_devices, list): devices = given_devices else: devices = [] for dev_name, item in self.__devices.items(): if item: devices.append(self.__devices[dev_name]) for device in devices: states = [] for state_name in sorted(device.active_states.keys()): states.append({'name': state_name}) dev_list.append({'deviceURL': device.url, 'states': states}) return json.dumps( dev_list, indent=None, sort_keys=True, separators=(',', ': '))
python
def _create_get_state_request(self, given_devices): """Create state request.""" dev_list = [] if isinstance(given_devices, list): devices = given_devices else: devices = [] for dev_name, item in self.__devices.items(): if item: devices.append(self.__devices[dev_name]) for device in devices: states = [] for state_name in sorted(device.active_states.keys()): states.append({'name': state_name}) dev_list.append({'deviceURL': device.url, 'states': states}) return json.dumps( dev_list, indent=None, sort_keys=True, separators=(',', ': '))
[ "def", "_create_get_state_request", "(", "self", ",", "given_devices", ")", ":", "dev_list", "=", "[", "]", "if", "isinstance", "(", "given_devices", ",", "list", ")", ":", "devices", "=", "given_devices", "else", ":", "devices", "=", "[", "]", "for", "dev_name", ",", "item", "in", "self", ".", "__devices", ".", "items", "(", ")", ":", "if", "item", ":", "devices", ".", "append", "(", "self", ".", "__devices", "[", "dev_name", "]", ")", "for", "device", "in", "devices", ":", "states", "=", "[", "]", "for", "state_name", "in", "sorted", "(", "device", ".", "active_states", ".", "keys", "(", ")", ")", ":", "states", ".", "append", "(", "{", "'name'", ":", "state_name", "}", ")", "dev_list", ".", "append", "(", "{", "'deviceURL'", ":", "device", ".", "url", ",", "'states'", ":", "states", "}", ")", "return", "json", ".", "dumps", "(", "dev_list", ",", "indent", "=", "None", ",", "sort_keys", "=", "True", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
Create state request.
[ "Create", "state", "request", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L590-L612
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi._get_states
def _get_states(self, result): """Get states of devices.""" if 'devices' not in result.keys(): return for device_states in result['devices']: device = self.__devices[device_states['deviceURL']] try: device.set_active_states(device_states['states']) except KeyError: pass
python
def _get_states(self, result): """Get states of devices.""" if 'devices' not in result.keys(): return for device_states in result['devices']: device = self.__devices[device_states['deviceURL']] try: device.set_active_states(device_states['states']) except KeyError: pass
[ "def", "_get_states", "(", "self", ",", "result", ")", ":", "if", "'devices'", "not", "in", "result", ".", "keys", "(", ")", ":", "return", "for", "device_states", "in", "result", "[", "'devices'", "]", ":", "device", "=", "self", ".", "__devices", "[", "device_states", "[", "'deviceURL'", "]", "]", "try", ":", "device", ".", "set_active_states", "(", "device_states", "[", "'states'", "]", ")", "except", "KeyError", ":", "pass" ]
Get states of devices.
[ "Get", "states", "of", "devices", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L614-L624
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
TahomaApi.refresh_all_states
def refresh_all_states(self): """Update all states.""" header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get( BASE_URL + "refreshAllStates", headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.refresh_all_states() return
python
def refresh_all_states(self): """Update all states.""" header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get( BASE_URL + "refreshAllStates", headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.refresh_all_states() return
[ "def", "refresh_all_states", "(", "self", ")", ":", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "header", "[", "'Cookie'", "]", "=", "self", ".", "__cookie", "request", "=", "requests", ".", "get", "(", "BASE_URL", "+", "\"refreshAllStates\"", ",", "headers", "=", "header", ",", "timeout", "=", "10", ")", "if", "request", ".", "status_code", "!=", "200", ":", "self", ".", "__logged_in", "=", "False", "self", ".", "login", "(", ")", "self", ".", "refresh_all_states", "(", ")", "return" ]
Update all states.
[ "Update", "all", "states", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L626-L638
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
Device.set_active_state
def set_active_state(self, name, value): """Set active state.""" if name not in self.__active_states.keys(): raise ValueError("Can not set unknown state '" + name + "'") if (isinstance(self.__active_states[name], int) and isinstance(value, str)): # we get an update as str but current value is # an int, try to convert self.__active_states[name] = int(value) elif (isinstance(self.__active_states[name], float) and isinstance(value, str)): # we get an update as str but current value is # a float, try to convert self.__active_states[name] = float(value) else: self.__active_states[name] = value
python
def set_active_state(self, name, value): """Set active state.""" if name not in self.__active_states.keys(): raise ValueError("Can not set unknown state '" + name + "'") if (isinstance(self.__active_states[name], int) and isinstance(value, str)): # we get an update as str but current value is # an int, try to convert self.__active_states[name] = int(value) elif (isinstance(self.__active_states[name], float) and isinstance(value, str)): # we get an update as str but current value is # a float, try to convert self.__active_states[name] = float(value) else: self.__active_states[name] = value
[ "def", "set_active_state", "(", "self", ",", "name", ",", "value", ")", ":", "if", "name", "not", "in", "self", ".", "__active_states", ".", "keys", "(", ")", ":", "raise", "ValueError", "(", "\"Can not set unknown state '\"", "+", "name", "+", "\"'\"", ")", "if", "(", "isinstance", "(", "self", ".", "__active_states", "[", "name", "]", ",", "int", ")", "and", "isinstance", "(", "value", ",", "str", ")", ")", ":", "# we get an update as str but current value is", "# an int, try to convert", "self", ".", "__active_states", "[", "name", "]", "=", "int", "(", "value", ")", "elif", "(", "isinstance", "(", "self", ".", "__active_states", "[", "name", "]", ",", "float", ")", "and", "isinstance", "(", "value", ",", "str", ")", ")", ":", "# we get an update as str but current value is", "# a float, try to convert", "self", ".", "__active_states", "[", "name", "]", "=", "float", "(", "value", ")", "else", ":", "self", ".", "__active_states", "[", "name", "]", "=", "value" ]
Set active state.
[ "Set", "active", "state", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L749-L765
train
philklei/tahoma-api
tahoma_api/tahoma_api.py
Action.add_command
def add_command(self, cmd_name, *args): """Add command to action.""" self.__commands.append(Command(cmd_name, args))
python
def add_command(self, cmd_name, *args): """Add command to action.""" self.__commands.append(Command(cmd_name, args))
[ "def", "add_command", "(", "self", ",", "cmd_name", ",", "*", "args", ")", ":", "self", ".", "__commands", ".", "append", "(", "Command", "(", "cmd_name", ",", "args", ")", ")" ]
Add command to action.
[ "Add", "command", "to", "action", "." ]
fc84f6ba3b673d0cd0e9e618777834a74a3c7b64
https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L818-L820
train