_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q29000
Bivariate.fit
train
def fit(self, X): """Fit a model to the data updating the parameters. Args: X: `np.ndarray` of shape (,2). Return: None """ U, V = self.split_matrix(X) self.tau = stats.kendalltau(U, V)[0] self.theta = self.compute_theta() self.check_theta()
python
{ "resource": "" }
q29001
Bivariate.from_dict
train
def from_dict(cls, copula_dict): """Create a new instance from the given parameters. Args: copula_dict: `dict` with the parameters to replicate the copula. Like the output of `Bivariate.to_dict` Returns: Bivariate: Instance of the copula defined on the parameters. """ instance = cls(copula_dict['copula_type']) instance.theta = copula_dict['theta'] instance.tau = copula_dict['tau'] return instance
python
{ "resource": "" }
q29002
Bivariate.check_theta
train
def check_theta(self): """Validate the computed theta against the copula specification. This method is used to assert the computed theta is in the valid range for the copula.""" lower, upper = self.theta_interval if (not lower <= self.theta <= upper) or (self.theta in self.invalid_thetas): message = 'The computed theta value {} is out of limits for the given {} copula.' raise ValueError(message.format(self.theta, self.copula_type.name))
python
{ "resource": "" }
q29003
Bivariate.compute_empirical
train
def compute_empirical(cls, X): """Compute empirical distribution.""" z_left = [] z_right = [] L = [] R = [] U, V = cls.split_matrix(X) N = len(U) base = np.linspace(EPSILON, 1.0 - EPSILON, COMPUTE_EMPIRICAL_STEPS) # See https://github.com/DAI-Lab/Copulas/issues/45 for k in range(COMPUTE_EMPIRICAL_STEPS): left = sum(np.logical_and(U <= base[k], V <= base[k])) / N right = sum(np.logical_and(U >= base[k], V >= base[k])) / N if left > 0: z_left.append(base[k]) L.append(left / base[k] ** 2) if right > 0: z_right.append(base[k]) R.append(right / (1 - z_right[k]) ** 2) return z_left, L, z_right, R
python
{ "resource": "" }
q29004
Bivariate.select_copula
train
def select_copula(cls, X): """Select best copula function based on likelihood. Args: X: 2-dimensional `np.ndarray` Returns: tuple: `tuple(CopulaType, float)` best fit and model param. """ frank = Bivariate(CopulaTypes.FRANK) frank.fit(X) if frank.tau <= 0: selected_theta = frank.theta selected_copula = CopulaTypes.FRANK return selected_copula, selected_theta copula_candidates = [frank] theta_candidates = [frank.theta] try: clayton = Bivariate(CopulaTypes.CLAYTON) clayton.fit(X) copula_candidates.append(clayton) theta_candidates.append(clayton.theta) except ValueError: # Invalid theta, copula ignored pass try: gumbel = Bivariate(CopulaTypes.GUMBEL) gumbel.fit(X) copula_candidates.append(gumbel) theta_candidates.append(gumbel.theta) except ValueError: # Invalid theta, copula ignored pass z_left, L, z_right, R = cls.compute_empirical(X) left_dependence, right_dependence = cls.get_dependencies( copula_candidates, z_left, z_right) # compute L2 distance from empirical distribution cost_L = [np.sum((L - l) ** 2) for l in left_dependence] cost_R = [np.sum((R - r) ** 2) for r in right_dependence] cost_LR = np.add(cost_L, cost_R) selected_copula = np.argmax(cost_LR) selected_theta = theta_candidates[selected_copula] return CopulaTypes(selected_copula), selected_theta
python
{ "resource": "" }
q29005
import_object
train
def import_object(object_name): """Import an object from its Fully Qualified Name.""" package, name = object_name.rsplit('.', 1) return getattr(importlib.import_module(package), name)
python
{ "resource": "" }
q29006
get_qualified_name
train
def get_qualified_name(_object): """Return the Fully Qualified Name from an instance or class.""" module = _object.__module__ if hasattr(_object, '__name__'): _class = _object.__name__ else: _class = _object.__class__.__name__ return module + '.' + _class
python
{ "resource": "" }
q29007
vectorize
train
def vectorize(function): """Allow a method that only accepts scalars to accept vectors too. This decorator has two different behaviors depending on the dimensionality of the array passed as an argument: **1-d array** It will work under the assumption that the `function` argument is a callable with signature:: function(self, X, *args, **kwargs) where X is an scalar magnitude. In this case the arguments of the input array will be given one at a time, and both the input and output of the decorated function will have shape (n,). **2-d array** It will work under the assumption that the `function` argument is a callable with signature:: function(self, X0, ..., Xj, *args, **kwargs) where `Xi` are scalar magnitudes. It will pass the contents of each row unpacked on each call. The input is espected to have shape (n, j), the output a shape of (n,) It will return a function that is guaranteed to return a `numpy.array`. Args: function(callable): Function that only accept and return scalars. Returns: callable: Decorated function that can accept and return :attr:`numpy.array`. """ def decorated(self, X, *args, **kwargs): if not isinstance(X, np.ndarray): return function(self, X, *args, **kwargs) if len(X.shape) == 1: X = X.reshape([-1, 1]) if len(X.shape) == 2: return np.fromiter( (function(self, *x, *args, **kwargs) for x in X), np.dtype('float64') ) else: raise ValueError('Arrays of dimensionality higher than 2 are not supported.') decorated.__doc__ = function.__doc__ return decorated
python
{ "resource": "" }
q29008
scalarize
train
def scalarize(function): """Allow methods that only accepts 1-d vectors to work with scalars. Args: function(callable): Function that accepts and returns vectors. Returns: callable: Decorated function that accepts and returns scalars. """ def decorated(self, X, *args, **kwargs): scalar = not isinstance(X, np.ndarray) if scalar: X = np.array([X]) result = function(self, X, *args, **kwargs) if scalar: result = result[0] return result decorated.__doc__ = function.__doc__ return decorated
python
{ "resource": "" }
q29009
check_valid_values
train
def check_valid_values(function): """Raises an exception if the given values are not supported. Args: function(callable): Method whose unique argument is a numpy.array-like object. Returns: callable: Decorated function Raises: ValueError: If there are missing or invalid values or if the dataset is empty. """ def decorated(self, X, *args, **kwargs): if isinstance(X, pd.DataFrame): W = X.values else: W = X if not len(W): raise ValueError('Your dataset is empty.') if W.dtype not in [np.dtype('float64'), np.dtype('int64')]: raise ValueError('There are non-numerical values in your data.') if np.isnan(W).any().any(): raise ValueError('There are nan values in your data.') return function(self, X, *args, **kwargs) return decorated
python
{ "resource": "" }
q29010
missing_method_scipy_wrapper
train
def missing_method_scipy_wrapper(function): """Raises a detailed exception when a method is not available.""" def decorated(self, *args, **kwargs): message = ( 'Your tried to access `{method_name}` from {class_name}, but its not available.\n ' 'There can be multiple factors causing this, please feel free to open an issue in ' 'https://github.com/DAI-Lab/Copulas/issues/new' ) params = { 'method_name': function.__name__, 'class_name': get_qualified_name(function.__self__.__class__) } raise NotImplementedError(message.format(**params)) return decorated
python
{ "resource": "" }
q29011
Frank._g
train
def _g(self, z): """Helper function to solve Frank copula. This functions encapsulates :math:`g_z = e^{-\\theta z} - 1` used on Frank copulas. Argument: z: np.ndarray Returns: np.ndarray """ return np.exp(np.multiply(-self.theta, z)) - 1
python
{ "resource": "" }
q29012
Frank._frank_help
train
def _frank_help(alpha, tau): """Compute first order debye function to estimate theta.""" def debye(t): return t / (np.exp(t) - 1) debye_value = integrate.quad(debye, EPSILON, alpha)[0] / alpha return 4 * (debye_value - 1) / alpha + 1 - tau
python
{ "resource": "" }
q29013
Univariate.to_dict
train
def to_dict(self): """Returns parameters to replicate the distribution.""" result = { 'type': get_qualified_name(self), 'fitted': self.fitted, 'constant_value': self.constant_value } if not self.fitted: return result result.update(self._fit_params()) return result
python
{ "resource": "" }
q29014
Univariate._constant_cumulative_distribution
train
def _constant_cumulative_distribution(self, X): """Cumulative distribution for the degenerate case of constant distribution. Note that the output of this method will be an array whose unique values are 0 and 1. More information can be found here: https://en.wikipedia.org/wiki/Degenerate_distribution Args: X (numpy.ndarray): Values to compute cdf to. Returns: numpy.ndarray: Cumulative distribution for the given values. """ result = np.ones(X.shape) result[np.nonzero(X < self.constant_value)] = 0 return result
python
{ "resource": "" }
q29015
Univariate._constant_probability_density
train
def _constant_probability_density(self, X): """Probability density for the degenerate case of constant distribution. Note that the output of this method will be an array whose unique values are 0 and 1. More information can be found here: https://en.wikipedia.org/wiki/Degenerate_distribution Args: X(numpy.ndarray): Values to compute pdf. Returns: numpy.ndarray: Probability densisty for the given values """ result = np.zeros(X.shape) result[np.nonzero(X == self.constant_value)] = 1 return result
python
{ "resource": "" }
q29016
Univariate._replace_constant_methods
train
def _replace_constant_methods(self): """Replaces conventional distribution methods by its constant counterparts.""" self.cumulative_distribution = self._constant_cumulative_distribution self.percent_point = self._constant_percent_point self.probability_density = self._constant_probability_density self.sample = self._constant_sample
python
{ "resource": "" }
q29017
ScipyWrapper.fit
train
def fit(self, X, *args, **kwargs): """Fit scipy model to an array of values. Args: X(`np.ndarray` or `pd.DataFrame`): Datapoints to be estimated from. Must be 1-d Returns: None """ self.constant_value = self._get_constant_value(X) if self.constant_value is None: if self.unfittable_model: self.model = getattr(scipy.stats, self.model_class)(*args, **kwargs) else: self.model = getattr(scipy.stats, self.model_class)(X, *args, **kwargs) for name in self.METHOD_NAMES: attribute = getattr(self.__class__, name) if isinstance(attribute, str): setattr(self, name, getattr(self.model, attribute)) elif attribute is None: setattr(self, name, missing_method_scipy_wrapper(lambda x: x)) else: self._replace_constant_methods() self.fitted = True
python
{ "resource": "" }
q29018
main
train
def main(data, utype, ctype): """Create a Vine from the data, utype and ctype""" copula = CopulaModel(data, utype, ctype) print(copula.sampling(1, plot=True)) print(copula.model.vine_model[-1].tree_data)
python
{ "resource": "" }
q29019
Clayton.compute_theta
train
def compute_theta(self): """Compute theta parameter using Kendall's tau. On Clayton copula this is :math:`τ = θ/(θ + 2) \\implies θ = 2τ/(1-τ)` with :math:`θ ∈ (0, ∞)`. On the corner case of :math:`τ = 1`, a big enough number is returned instead of infinity. """ if self.tau == 1: theta = 10000 else: theta = 2 * self.tau / (1 - self.tau) return theta
python
{ "resource": "" }
q29020
VineCopula.fit
train
def fit(self, X, truncated=3): """Fit a vine model to the data. Args: X(numpy.ndarray): data to be fitted. truncated(int): max level to build the vine. """ self.n_sample, self.n_var = X.shape self.columns = X.columns self.tau_mat = X.corr(method='kendall').values self.u_matrix = np.empty([self.n_sample, self.n_var]) self.truncated = truncated self.depth = self.n_var - 1 self.trees = [] self.unis, self.ppfs = [], [] for i, col in enumerate(X): uni = self.model() uni.fit(X[col]) self.u_matrix[:, i] = uni.cumulative_distribution(X[col]) self.unis.append(uni) self.ppfs.append(uni.percent_point) self.train_vine(self.vine_type) self.fitted = True
python
{ "resource": "" }
q29021
VineCopula.train_vine
train
def train_vine(self, tree_type): """Train vine.""" LOGGER.debug('start building tree : 0') tree_1 = Tree(tree_type) tree_1.fit(0, self.n_var, self.tau_mat, self.u_matrix) self.trees.append(tree_1) LOGGER.debug('finish building tree : 0') for k in range(1, min(self.n_var - 1, self.truncated)): # get constraints from previous tree self.trees[k - 1]._get_constraints() tau = self.trees[k - 1].get_tau_matrix() LOGGER.debug('start building tree: {0}'.format(k)) tree_k = Tree(tree_type) tree_k.fit(k, self.n_var - k, tau, self.trees[k - 1]) self.trees.append(tree_k) LOGGER.debug('finish building tree: {0}'.format(k))
python
{ "resource": "" }
q29022
VineCopula.get_likelihood
train
def get_likelihood(self, uni_matrix): """Compute likelihood of the vine.""" num_tree = len(self.trees) values = np.empty([1, num_tree]) for i in range(num_tree): value, new_uni_matrix = self.trees[i].get_likelihood(uni_matrix) uni_matrix = new_uni_matrix values[0, i] = value return np.sum(values)
python
{ "resource": "" }
q29023
VineCopula._sample_row
train
def _sample_row(self): """Generate a single sampled row from vine model. Returns: numpy.ndarray """ unis = np.random.uniform(0, 1, self.n_var) # randomly select a node to start with first_ind = np.random.randint(0, self.n_var) adj = self.trees[0].get_adjacent_matrix() visited = [] explore = [first_ind] sampled = np.zeros(self.n_var) itr = 0 while explore: current = explore.pop(0) neighbors = np.where(adj[current, :] == 1)[0].tolist() if itr == 0: new_x = self.ppfs[current](unis[current]) else: for i in range(itr - 1, -1, -1): current_ind = -1 if i >= self.truncated: continue current_tree = self.trees[i].edges # get index of edge to retrieve for edge in current_tree: if i == 0: if (edge.L == current and edge.R == visited[0]) or\ (edge.R == current and edge.L == visited[0]): current_ind = edge.index break else: if edge.L == current or edge.R == current: condition = set(edge.D) condition.add(edge.L) condition.add(edge.R) visit_set = set(visited) visit_set.add(current) if condition.issubset(visit_set): current_ind = edge.index break if current_ind != -1: # the node is not indepedent contional on visited node copula_type = current_tree[current_ind].name copula = Bivariate(CopulaTypes(copula_type)) copula.theta = current_tree[current_ind].theta derivative = copula.partial_derivative_scalar if i == itr - 1: tmp = optimize.fminbound( derivative, EPSILON, 1.0, args=(unis[visited[0]], unis[current]) ) else: tmp = optimize.fminbound( derivative, EPSILON, 1.0, args=(unis[visited[0]], tmp) ) tmp = min(max(tmp, EPSILON), 0.99) new_x = self.ppfs[current](tmp) sampled[current] = new_x for s in neighbors: if s not in visited: explore.insert(0, s) itr += 1 visited.insert(0, current) return sampled
python
{ "resource": "" }
q29024
VineCopula.sample
train
def sample(self, num_rows): """Sample new rows. Args: num_rows(int): Number of rows to sample Returns: pandas.DataFrame """ sampled_values = [] for i in range(num_rows): sampled_values.append(self._sample_row()) return pd.DataFrame(sampled_values, columns=self.columns)
python
{ "resource": "" }
q29025
Tree.fit
train
def fit(self, index, n_nodes, tau_matrix, previous_tree, edges=None): """Fits tree object. Args: :param index: index of the tree :param n_nodes: number of nodes in the tree :tau_matrix: kendall's tau matrix of the data :previous_tree: tree object of previous level :type index: int :type n_nodes: int :type tau_matrix: np.ndarray of size n_nodes*n_nodes """ self.level = index + 1 self.n_nodes = n_nodes self.tau_matrix = tau_matrix self.previous_tree = previous_tree self.edges = edges or [] if not self.edges: if self.level == 1: self.u_matrix = previous_tree self._build_first_tree() else: self._build_kth_tree() self.prepare_next_tree() self.fitted = True
python
{ "resource": "" }
q29026
Tree._check_contraint
train
def _check_contraint(self, edge1, edge2): """Check if two edges satisfy vine constraint. Args: :param edge1: edge object representing edge1 :param edge2: edge object representing edge2 :type edge1: Edge object :type edge2: Edge object Returns: Boolean True if the two edges satisfy vine constraints """ full_node = set([edge1.L, edge1.R, edge2.L, edge2.R]) full_node.update(edge1.D) full_node.update(edge2.D) return len(full_node) == (self.level + 1)
python
{ "resource": "" }
q29027
Tree._get_constraints
train
def _get_constraints(self): """Get neighboring edges for each edge in the edges.""" num_edges = len(self.edges) for k in range(num_edges): for i in range(num_edges): # add to constraints if i shared an edge with k if k != i and self.edges[k].is_adjacent(self.edges[i]): self.edges[k].neighbors.append(i)
python
{ "resource": "" }
q29028
Tree._sort_tau_by_y
train
def _sort_tau_by_y(self, y): """Sort tau matrix by dependece with variable y. Args: :param y: index of variable of intrest :type y: int """ # first column is the variable of interest tau_y = self.tau_matrix[:, y] tau_y[y] = np.NaN temp = np.empty([self.n_nodes, 3]) temp[:, 0] = np.arange(self.n_nodes) temp[:, 1] = tau_y temp[:, 2] = abs(tau_y) temp[np.isnan(temp)] = -10 tau_sorted = temp[temp[:, 2].argsort()[::-1]] return tau_sorted
python
{ "resource": "" }
q29029
Tree.get_tau_matrix
train
def get_tau_matrix(self): """Get tau matrix for adjacent pairs. Returns: :param tau: tau matrix for the current tree :type tau: np.ndarray """ num_edges = len(self.edges) tau = np.empty([num_edges, num_edges]) for i in range(num_edges): edge = self.edges[i] for j in edge.neighbors: if self.level == 1: left_u = self.u_matrix[:, edge.L] right_u = self.u_matrix[:, edge.R] else: left_parent, right_parent = edge.parents left_u, right_u = Edge.get_conditional_uni(left_parent, right_parent) tau[i, j], pvalue = scipy.stats.kendalltau(left_u, right_u) return tau
python
{ "resource": "" }
q29030
Tree.get_adjacent_matrix
train
def get_adjacent_matrix(self): """Get adjacency matrix. Returns: :param adj: adjacency matrix :type adj: np.ndarray """ edges = self.edges num_edges = len(edges) + 1 adj = np.zeros([num_edges, num_edges]) for k in range(num_edges - 1): adj[edges[k].L, edges[k].R] = 1 adj[edges[k].R, edges[k].L] = 1 return adj
python
{ "resource": "" }
q29031
Tree.prepare_next_tree
train
def prepare_next_tree(self): """Prepare conditional U matrix for next tree.""" for edge in self.edges: copula_theta = edge.theta if self.level == 1: left_u = self.u_matrix[:, edge.L] right_u = self.u_matrix[:, edge.R] else: left_parent, right_parent = edge.parents left_u, right_u = Edge.get_conditional_uni(left_parent, right_parent) # compute conditional cdfs C(i|j) = dC(i,j)/duj and dC(i,j)/du left_u = [x for x in left_u if x is not None] right_u = [x for x in right_u if x is not None] X_left_right = np.array([[x, y] for x, y in zip(left_u, right_u)]) X_right_left = np.array([[x, y] for x, y in zip(right_u, left_u)]) copula = Bivariate(edge.name) copula.theta = copula_theta left_given_right = copula.partial_derivative(X_left_right) right_given_left = copula.partial_derivative(X_right_left) # correction of 0 or 1 left_given_right[left_given_right == 0] = EPSILON right_given_left[right_given_left == 0] = EPSILON left_given_right[left_given_right == 1] = 1 - EPSILON right_given_left[right_given_left == 1] = 1 - EPSILON edge.U = np.array([left_given_right, right_given_left])
python
{ "resource": "" }
q29032
Tree.get_likelihood
train
def get_likelihood(self, uni_matrix): """Compute likelihood of the tree given an U matrix. Args: uni_matrix(numpy.array): univariate matrix to evaluate likelihood on. Returns: tuple[float, numpy.array]: likelihood of the current tree, next level conditional univariate matrix """ uni_dim = uni_matrix.shape[1] num_edge = len(self.edges) values = np.zeros([1, num_edge]) new_uni_matrix = np.empty([uni_dim, uni_dim]) for i in range(num_edge): edge = self.edges[i] value, left_u, right_u = edge.get_likelihood(uni_matrix) new_uni_matrix[edge.L, edge.R] = left_u new_uni_matrix[edge.R, edge.L] = right_u values[0, i] = np.log(value) return np.sum(values), new_uni_matrix
python
{ "resource": "" }
q29033
Tree.from_dict
train
def from_dict(cls, tree_dict, previous=None): """Create a new instance from a dictionary.""" instance = cls(tree_dict['tree_type']) fitted = tree_dict['fitted'] instance.fitted = fitted if fitted: instance.level = tree_dict['level'] instance.n_nodes = tree_dict['n_nodes'] instance.tau_matrix = np.array(tree_dict['tau_matrix']) instance.previous_tree = cls._deserialize_previous_tree(tree_dict, previous) instance.edges = [Edge.from_dict(edge) for edge in tree_dict['edges']] return instance
python
{ "resource": "" }
q29034
CenterTree._build_first_tree
train
def _build_first_tree(self): """Build first level tree.""" tau_sorted = self._sort_tau_by_y(0) for itr in range(self.n_nodes - 1): ind = int(tau_sorted[itr, 0]) name, theta = Bivariate.select_copula(self.u_matrix[:, (0, ind)]) new_edge = Edge(itr, 0, ind, name, theta) new_edge.tau = self.tau_matrix[0, ind] self.edges.append(new_edge)
python
{ "resource": "" }
q29035
CenterTree._build_kth_tree
train
def _build_kth_tree(self): """Build k-th level tree.""" anchor = self.get_anchor() aux_sorted = self._sort_tau_by_y(anchor) edges = self.previous_tree.edges for itr in range(self.n_nodes - 1): right = int(aux_sorted[itr, 0]) left_parent, right_parent = Edge.sort_edge([edges[anchor], edges[right]]) new_edge = Edge.get_child_edge(itr, left_parent, right_parent) new_edge.tau = aux_sorted[itr, 1] self.edges.append(new_edge)
python
{ "resource": "" }
q29036
CenterTree.get_anchor
train
def get_anchor(self): """Find anchor variable with highest sum of dependence with the rest.""" temp = np.empty([self.n_nodes, 2]) temp[:, 0] = np.arange(self.n_nodes, dtype=int) temp[:, 1] = np.sum(abs(self.tau_matrix), 1) anchor = int(temp[0, 0]) return anchor
python
{ "resource": "" }
q29037
RegularTree._build_first_tree
train
def _build_first_tree(self): """Build the first tree with n-1 variable.""" # Prim's algorithm neg_tau = -1.0 * abs(self.tau_matrix) X = {0} while len(X) != self.n_nodes: adj_set = set() for x in X: for k in range(self.n_nodes): if k not in X and k != x: adj_set.add((x, k)) # find edge with maximum edge = sorted(adj_set, key=lambda e: neg_tau[e[0]][e[1]])[0] name, theta = Bivariate.select_copula(self.u_matrix[:, (edge[0], edge[1])]) left, right = sorted([edge[0], edge[1]]) new_edge = Edge(len(X) - 1, left, right, name, theta) new_edge.tau = self.tau_matrix[edge[0], edge[1]] self.edges.append(new_edge) X.add(edge[1])
python
{ "resource": "" }
q29038
RegularTree._build_kth_tree
train
def _build_kth_tree(self): """Build tree for level k.""" neg_tau = -1.0 * abs(self.tau_matrix) edges = self.previous_tree.edges visited = set([0]) unvisited = set(range(self.n_nodes)) while len(visited) != self.n_nodes: adj_set = set() for x in visited: for k in range(self.n_nodes): # check if (x,k) is a valid edge in the vine if k not in visited and k != x and self._check_contraint(edges[x], edges[k]): adj_set.add((x, k)) # find edge with maximum tau if len(adj_set) == 0: visited.add(list(unvisited)[0]) continue pairs = sorted(adj_set, key=lambda e: neg_tau[e[0]][e[1]])[0] left_parent, right_parent = Edge.sort_edge([edges[pairs[0]], edges[pairs[1]]]) new_edge = Edge.get_child_edge(len(visited) - 1, left_parent, right_parent) new_edge.tau = self.tau_matrix[pairs[0], pairs[1]] self.edges.append(new_edge) visited.add(pairs[1]) unvisited.remove(pairs[1])
python
{ "resource": "" }
q29039
Edge._identify_eds_ing
train
def _identify_eds_ing(first, second): """Find nodes connecting adjacent edges. Args: first(Edge): Edge object representing the first edge. second(Edge): Edge object representing the second edge. Returns: tuple[int, int, set[int]]: The first two values represent left and right node indicies of the new edge. The third value is the new dependence set. """ A = set([first.L, first.R]) A.update(first.D) B = set([second.L, second.R]) B.update(second.D) depend_set = A & B left, right = sorted(list(A ^ B)) return left, right, depend_set
python
{ "resource": "" }
q29040
Edge.is_adjacent
train
def is_adjacent(self, another_edge): """Check if two edges are adjacent. Args: :param another_edge: edge object of another edge :type another_edge: edge object This function will return true if the two edges are adjacent. """ return ( self.L == another_edge.L or self.L == another_edge.R or self.R == another_edge.L or self.R == another_edge.R )
python
{ "resource": "" }
q29041
Edge.sort_edge
train
def sort_edge(edges): """Sort iterable of edges first by left node indices then right. Args: edges(list[Edge]): List of edges to be sorted. Returns: list[Edge]: Sorted list by left and right node indices. """ return sorted(edges, key=lambda x: (x.L, x.R))
python
{ "resource": "" }
q29042
Edge.get_conditional_uni
train
def get_conditional_uni(cls, left_parent, right_parent): """Identify pair univariate value from parents. Args: left_parent(Edge): left parent right_parent(Edge): right parent Returns: tuple[np.ndarray, np.ndarray]: left and right parents univariate. """ left, right, _ = cls._identify_eds_ing(left_parent, right_parent) left_u = left_parent.U[0] if left_parent.L == left else left_parent.U[1] right_u = right_parent.U[0] if right_parent.L == right else right_parent.U[1] return left_u, right_u
python
{ "resource": "" }
q29043
Edge.get_child_edge
train
def get_child_edge(cls, index, left_parent, right_parent): """Construct a child edge from two parent edges.""" [ed1, ed2, depend_set] = cls._identify_eds_ing(left_parent, right_parent) left_u, right_u = cls.get_conditional_uni(left_parent, right_parent) X = np.array([[x, y] for x, y in zip(left_u, right_u)]) name, theta = Bivariate.select_copula(X) new_edge = Edge(index, ed1, ed2, name, theta) new_edge.D = depend_set new_edge.parents = [left_parent, right_parent] return new_edge
python
{ "resource": "" }
q29044
Edge.get_likelihood
train
def get_likelihood(self, uni_matrix): """Compute likelihood given a U matrix. Args: uni_matrix(numpy.array): Matrix to compute the likelihood. Return: tuple(np.ndarray, np.ndarray, np.array): likelihood and conditional values. """ if self.parents is None: left_u = uni_matrix[:, self.L] right_u = uni_matrix[:, self.R] else: left_ing = list(self.D - self.parents[0].D)[0] right_ing = list(self.D - self.parents[1].D)[0] left_u = uni_matrix[self.L, left_ing] right_u = uni_matrix[self.R, right_ing] copula = Bivariate(self.name) copula.theta = self.theta X_left_right = np.array([[left_u, right_u]]) X_right_left = np.array([[right_u, left_u]]) value = np.sum(copula.probability_density(X_left_right)) left_given_right = copula.partial_derivative(X_left_right) right_given_left = copula.partial_derivative(X_right_left) return value, left_given_right, right_given_left
python
{ "resource": "" }
q29045
KDEUnivariate.fit
train
def fit(self, X): """Fit Kernel density estimation to an list of values. Args: X: 1-d `np.ndarray` or `pd.Series` or `list` datapoints to be estimated from. This function will fit a gaussian_kde model to a list of datapoints and store it as a class attribute. """ self.constant_value = self._get_constant_value(X) if self.constant_value is None: self.model = scipy.stats.gaussian_kde(X) else: self._replace_constant_methods() self.fitted = True
python
{ "resource": "" }
q29046
KDEUnivariate.probability_density
train
def probability_density(self, X): """Evaluate the estimated pdf on a point. Args: X: `float` a datapoint. :type X: float Returns: pdf: int or float with the value of estimated pdf """ self.check_fit() if type(X) not in (int, float): raise ValueError('x must be int or float') return self.model.evaluate(X)[0]
python
{ "resource": "" }
q29047
GaussianKDE._brentq_cdf
train
def _brentq_cdf(self, value): """Helper function to compute percent_point. As scipy.stats.gaussian_kde doesn't provide this functionality out of the box we need to make a numerical approach: - First we scalarize and bound cumulative_distribution. - Then we define a function `f(x) = cdf(x) - value`, where value is the given argument. - As value will be called from ppf we can assume value = cdf(z) for some z that is the value we are searching for. Therefore the zeros of the function will be x such that: cdf(x) - cdf(z) = 0 => (becasue cdf is monotonous and continous) x = z Args: value(float): cdf value, that is, in [0,1] Returns: callable: function whose zero is the ppf of value. """ # The decorator expects an instance method, but usually are decorated before being bounded bound_cdf = partial(scalarize(GaussianKDE.cumulative_distribution), self) def f(x): return bound_cdf(x) - value return f
python
{ "resource": "" }
q29048
mp1.check_power_raw
train
def check_power_raw(self): """Returns the power state of the smart power strip in raw format.""" packet = bytearray(16) packet[0x00] = 0x0a packet[0x02] = 0xa5 packet[0x03] = 0xa5 packet[0x04] = 0x5a packet[0x05] = 0x5a packet[0x06] = 0xae packet[0x07] = 0xc0 packet[0x08] = 0x01 response = self.send_packet(0x6a, packet) err = response[0x22] | (response[0x23] << 8) if err == 0: payload = self.decrypt(bytes(response[0x38:])) if type(payload[0x4]) == int: state = payload[0x0e] else: state = ord(payload[0x0e]) return state
python
{ "resource": "" }
q29049
mp1.check_power
train
def check_power(self): """Returns the power state of the smart power strip.""" state = self.check_power_raw() data = {} data['s1'] = bool(state & 0x01) data['s2'] = bool(state & 0x02) data['s3'] = bool(state & 0x04) data['s4'] = bool(state & 0x08) return data
python
{ "resource": "" }
q29050
sp2.set_power
train
def set_power(self, state): """Sets the power state of the smart plug.""" packet = bytearray(16) packet[0] = 2 if self.check_nightlight(): packet[4] = 3 if state else 2 else: packet[4] = 1 if state else 0 self.send_packet(0x6a, packet)
python
{ "resource": "" }
q29051
sp2.set_nightlight
train
def set_nightlight(self, state): """Sets the night light state of the smart plug""" packet = bytearray(16) packet[0] = 2 if self.check_power(): packet[4] = 3 if state else 1 else: packet[4] = 2 if state else 0 self.send_packet(0x6a, packet)
python
{ "resource": "" }
q29052
sp2.check_power
train
def check_power(self): """Returns the power state of the smart plug.""" packet = bytearray(16) packet[0] = 1 response = self.send_packet(0x6a, packet) err = response[0x22] | (response[0x23] << 8) if err == 0: payload = self.decrypt(bytes(response[0x38:])) if type(payload[0x4]) == int: if payload[0x4] == 1 or payload[0x4] == 3 or payload[0x4] == 0xFD: state = True else: state = False else: if ord(payload[0x4]) == 1 or ord(payload[0x4]) == 3 or ord(payload[0x4]) == 0xFD: state = True else: state = False return state
python
{ "resource": "" }
q29053
ChallengeList.create
train
def create(self, expiration_date=values.unset, details=values.unset, hidden_details=values.unset): """ Create a new ChallengeInstance :param datetime expiration_date: The future date in which this Challenge will expire :param unicode details: Public details provided to contextualize the Challenge :param unicode hidden_details: Hidden details provided to contextualize the Challenge :returns: Newly created ChallengeInstance :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance """ data = values.of({ 'ExpirationDate': serialize.iso8601_datetime(expiration_date), 'Details': details, 'HiddenDetails': hidden_details, }) payload = self._version.create( 'POST', self._uri, data=data, ) return ChallengeInstance( self._version, payload, service_sid=self._solution['service_sid'], identity=self._solution['identity'], factor_sid=self._solution['factor_sid'], )
python
{ "resource": "" }
q29054
ChallengeList.get
train
def get(self, sid): """ Constructs a ChallengeContext :param sid: A string that uniquely identifies this Challenge, or `latest`. :returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeContext """ return ChallengeContext( self._version, service_sid=self._solution['service_sid'], identity=self._solution['identity'], factor_sid=self._solution['factor_sid'], sid=sid, )
python
{ "resource": "" }
q29055
ChallengePage.get_instance
train
def get_instance(self, payload): """ Build an instance of ChallengeInstance :param dict payload: Payload response from the API :returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance """ return ChallengeInstance( self._version, payload, service_sid=self._solution['service_sid'], identity=self._solution['identity'], factor_sid=self._solution['factor_sid'], )
python
{ "resource": "" }
q29056
ChallengeContext.fetch
train
def fetch(self): """ Fetch a ChallengeInstance :returns: Fetched ChallengeInstance :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, params=params, ) return ChallengeInstance( self._version, payload, service_sid=self._solution['service_sid'], identity=self._solution['identity'], factor_sid=self._solution['factor_sid'], sid=self._solution['sid'], )
python
{ "resource": "" }
q29057
TaskChannelList.create
train
def create(self, friendly_name, unique_name): """ Create a new TaskChannelInstance :param unicode friendly_name: String representing user-friendly name for the TaskChannel :param unicode unique_name: String representing unique name for the TaskChannel :returns: Newly created TaskChannelInstance :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance """ data = values.of({'FriendlyName': friendly_name, 'UniqueName': unique_name, }) payload = self._version.create( 'POST', self._uri, data=data, ) return TaskChannelInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], )
python
{ "resource": "" }
q29058
TaskChannelList.get
train
def get(self, sid): """ Constructs a TaskChannelContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext """ return TaskChannelContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, )
python
{ "resource": "" }
q29059
TaskChannelPage.get_instance
train
def get_instance(self, payload): """ Build an instance of TaskChannelInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance """ return TaskChannelInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], )
python
{ "resource": "" }
q29060
VariableList.create
train
def create(self, key, value): """ Create a new VariableInstance :param unicode key: The key :param unicode value: The value :returns: Newly created VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance """ data = values.of({'Key': key, 'Value': value, }) payload = self._version.create( 'POST', self._uri, data=data, ) return VariableInstance( self._version, payload, service_sid=self._solution['service_sid'], environment_sid=self._solution['environment_sid'], )
python
{ "resource": "" }
q29061
VariableList.get
train
def get(self, sid): """ Constructs a VariableContext :param sid: The sid :returns: twilio.rest.serverless.v1.service.environment.variable.VariableContext :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext """ return VariableContext( self._version, service_sid=self._solution['service_sid'], environment_sid=self._solution['environment_sid'], sid=sid, )
python
{ "resource": "" }
q29062
VariablePage.get_instance
train
def get_instance(self, payload): """ Build an instance of VariableInstance :param dict payload: Payload response from the API :returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance """ return VariableInstance( self._version, payload, service_sid=self._solution['service_sid'], environment_sid=self._solution['environment_sid'], )
python
{ "resource": "" }
q29063
VariableContext.fetch
train
def fetch(self): """ Fetch a VariableInstance :returns: Fetched VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, params=params, ) return VariableInstance( self._version, payload, service_sid=self._solution['service_sid'], environment_sid=self._solution['environment_sid'], sid=self._solution['sid'], )
python
{ "resource": "" }
q29064
RecordList.all_time
train
def all_time(self): """ Access the all_time :returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList """ if self._all_time is None: self._all_time = AllTimeList(self._version, account_sid=self._solution['account_sid'], ) return self._all_time
python
{ "resource": "" }
q29065
RecordList.daily
train
def daily(self): """ Access the daily :returns: twilio.rest.api.v2010.account.usage.record.daily.DailyList :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyList """ if self._daily is None: self._daily = DailyList(self._version, account_sid=self._solution['account_sid'], ) return self._daily
python
{ "resource": "" }
q29066
RecordList.last_month
train
def last_month(self): """ Access the last_month :returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList """ if self._last_month is None: self._last_month = LastMonthList(self._version, account_sid=self._solution['account_sid'], ) return self._last_month
python
{ "resource": "" }
q29067
RecordList.monthly
train
def monthly(self): """ Access the monthly :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList """ if self._monthly is None: self._monthly = MonthlyList(self._version, account_sid=self._solution['account_sid'], ) return self._monthly
python
{ "resource": "" }
q29068
RecordList.this_month
train
def this_month(self): """ Access the this_month :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList """ if self._this_month is None: self._this_month = ThisMonthList(self._version, account_sid=self._solution['account_sid'], ) return self._this_month
python
{ "resource": "" }
q29069
RecordList.today
train
def today(self): """ Access the today :returns: twilio.rest.api.v2010.account.usage.record.today.TodayList :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayList """ if self._today is None: self._today = TodayList(self._version, account_sid=self._solution['account_sid'], ) return self._today
python
{ "resource": "" }
q29070
RecordList.yearly
train
def yearly(self): """ Access the yearly :returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList """ if self._yearly is None: self._yearly = YearlyList(self._version, account_sid=self._solution['account_sid'], ) return self._yearly
python
{ "resource": "" }
q29071
RecordList.yesterday
train
def yesterday(self): """ Access the yesterday :returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList """ if self._yesterday is None: self._yesterday = YesterdayList(self._version, account_sid=self._solution['account_sid'], ) return self._yesterday
python
{ "resource": "" }
q29072
RecordPage.get_instance
train
def get_instance(self, payload): """ Build an instance of RecordInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.RecordInstance :rtype: twilio.rest.api.v2010.account.usage.record.RecordInstance """ return RecordInstance(self._version, payload, account_sid=self._solution['account_sid'], )
python
{ "resource": "" }
q29073
BulkCountryUpdateList.create
train
def create(self, update_request): """ Create a new BulkCountryUpdateInstance :param unicode update_request: URL encoded JSON array of update objects :returns: Newly created BulkCountryUpdateInstance :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateInstance """ data = values.of({'UpdateRequest': update_request, }) payload = self._version.create( 'POST', self._uri, data=data, ) return BulkCountryUpdateInstance(self._version, payload, )
python
{ "resource": "" }
q29074
WorkersCumulativeStatisticsPage.get_instance
train
def get_instance(self, payload): """ Build an instance of WorkersCumulativeStatisticsInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance """ return WorkersCumulativeStatisticsInstance( self._version, payload, workspace_sid=self._solution['workspace_sid'], )
python
{ "resource": "" }
q29075
WorkersCumulativeStatisticsContext.fetch
train
def fetch(self, end_date=values.unset, minutes=values.unset, start_date=values.unset, task_channel=values.unset): """ Fetch a WorkersCumulativeStatisticsInstance :param datetime end_date: Filter cumulative statistics by a end date. :param unicode minutes: Filter cumulative statistics by up to 'x' minutes in the past. :param datetime start_date: Filter cumulative statistics by a start date. :param unicode task_channel: Filter cumulative statistics by TaskChannel. :returns: Fetched WorkersCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance """ params = values.of({ 'EndDate': serialize.iso8601_datetime(end_date), 'Minutes': minutes, 'StartDate': serialize.iso8601_datetime(start_date), 'TaskChannel': task_channel, }) payload = self._version.fetch( 'GET', self._uri, params=params, ) return WorkersCumulativeStatisticsInstance( self._version, payload, workspace_sid=self._solution['workspace_sid'], )
python
{ "resource": "" }
q29076
WorkspaceRealTimeStatisticsPage.get_instance
train
def get_instance(self, payload): """ Build an instance of WorkspaceRealTimeStatisticsInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance """ return WorkspaceRealTimeStatisticsInstance( self._version, payload, workspace_sid=self._solution['workspace_sid'], )
python
{ "resource": "" }
q29077
WorkspaceRealTimeStatisticsInstance.fetch
train
def fetch(self, task_channel=values.unset): """ Fetch a WorkspaceRealTimeStatisticsInstance :param unicode task_channel: Filter real-time and cumulative statistics by TaskChannel. :returns: Fetched WorkspaceRealTimeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance """ return self._proxy.fetch(task_channel=task_channel, )
python
{ "resource": "" }
q29078
UsageRecordPage.get_instance
train
def get_instance(self, payload): """ Build an instance of UsageRecordInstance :param dict payload: Payload response from the API :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance """ return UsageRecordInstance(self._version, payload, sim_sid=self._solution['sim_sid'], )
python
{ "resource": "" }
q29079
CompositionHookList.page
train
def page(self, enabled=values.unset, date_created_after=values.unset, date_created_before=values.unset, friendly_name=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of CompositionHookInstance records from the API. Request is executed immediately :param bool enabled: Only show Composition Hooks enabled or disabled. :param datetime date_created_after: Only show Composition Hooks created on or after this ISO8601 date-time with timezone. :param datetime date_created_before: Only show Composition Hooks created before this ISO8601 date-time with timezone. :param unicode friendly_name: Only show Composition Hooks with friendly name that match this name. :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simply for client state :param int page_size: Number of records to return, defaults to 50 :returns: Page of CompositionHookInstance :rtype: twilio.rest.video.v1.composition_hook.CompositionHookPage """ params = values.of({ 'Enabled': enabled, 'DateCreatedAfter': serialize.iso8601_datetime(date_created_after), 'DateCreatedBefore': serialize.iso8601_datetime(date_created_before), 'FriendlyName': friendly_name, 'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) response = self._version.page( 'GET', self._uri, params=params, ) return CompositionHookPage(self._version, response, self._solution)
python
{ "resource": "" }
q29080
TokenList.create
train
def create(self, ttl=values.unset): """ Create a new TokenInstance :param unicode ttl: The duration in seconds the credentials are valid :returns: Newly created TokenInstance :rtype: twilio.rest.api.v2010.account.token.TokenInstance """ data = values.of({'Ttl': ttl, }) payload = self._version.create( 'POST', self._uri, data=data, ) return TokenInstance(self._version, payload, account_sid=self._solution['account_sid'], )
python
{ "resource": "" }
q29081
TokenPage.get_instance
train
def get_instance(self, payload): """ Build an instance of TokenInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.token.TokenInstance :rtype: twilio.rest.api.v2010.account.token.TokenInstance """ return TokenInstance(self._version, payload, account_sid=self._solution['account_sid'], )
python
{ "resource": "" }
q29082
VerificationCheckPage.get_instance
train
def get_instance(self, payload): """ Build an instance of VerificationCheckInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckInstance :rtype: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckInstance """ return VerificationCheckInstance(self._version, payload, service_sid=self._solution['service_sid'], )
python
{ "resource": "" }
q29083
EngagementList.get
train
def get(self, sid): """ Constructs a EngagementContext :param sid: Engagement Sid. :returns: twilio.rest.studio.v1.flow.engagement.EngagementContext :rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext """ return EngagementContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, )
python
{ "resource": "" }
q29084
EngagementPage.get_instance
train
def get_instance(self, payload): """ Build an instance of EngagementInstance :param dict payload: Payload response from the API :returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance """ return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], )
python
{ "resource": "" }
q29085
EngagementContext.engagement_context
train
def engagement_context(self): """ Access the engagement_context :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList """ if self._engagement_context is None: self._engagement_context = EngagementContextList( self._version, flow_sid=self._solution['flow_sid'], engagement_sid=self._solution['sid'], ) return self._engagement_context
python
{ "resource": "" }
q29086
DialogueList.get
train
def get(self, sid): """ Constructs a DialogueContext :param sid: The unique string that identifies the resource :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueContext :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueContext """ return DialogueContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, )
python
{ "resource": "" }
q29087
DialoguePage.get_instance
train
def get_instance(self, payload): """ Build an instance of DialogueInstance :param dict payload: Payload response from the API :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueInstance :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueInstance """ return DialogueInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], )
python
{ "resource": "" }
q29088
WorkspaceList.create
train
def create(self, friendly_name, event_callback_url=values.unset, events_filter=values.unset, multi_task_enabled=values.unset, template=values.unset, prioritize_queue_order=values.unset): """ Create a new WorkspaceInstance :param unicode friendly_name: Human readable description of this workspace :param unicode event_callback_url: If provided, the Workspace will publish events to this URL. :param unicode events_filter: Use this parameter to receive webhooks on EventCallbackUrl for specific events on a workspace. :param bool multi_task_enabled: Multi tasking allows workers to handle multiple tasks simultaneously. :param unicode template: One of the available template names. :param WorkspaceInstance.QueueOrder prioritize_queue_order: Use this parameter to configure whether to prioritize LIFO or FIFO when workers are receiving Tasks from combination of LIFO and FIFO TaskQueues. :returns: Newly created WorkspaceInstance :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance """ data = values.of({ 'FriendlyName': friendly_name, 'EventCallbackUrl': event_callback_url, 'EventsFilter': events_filter, 'MultiTaskEnabled': multi_task_enabled, 'Template': template, 'PrioritizeQueueOrder': prioritize_queue_order, }) payload = self._version.create( 'POST', self._uri, data=data, ) return WorkspaceInstance(self._version, payload, )
python
{ "resource": "" }
q29089
WorkspaceContext.activities
train
def activities(self): """ Access the activities :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityList :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityList """ if self._activities is None: self._activities = ActivityList(self._version, workspace_sid=self._solution['sid'], ) return self._activities
python
{ "resource": "" }
q29090
WorkspaceContext.events
train
def events(self): """ Access the events :returns: twilio.rest.taskrouter.v1.workspace.event.EventList :rtype: twilio.rest.taskrouter.v1.workspace.event.EventList """ if self._events is None: self._events = EventList(self._version, workspace_sid=self._solution['sid'], ) return self._events
python
{ "resource": "" }
q29091
WorkspaceContext.task_queues
train
def task_queues(self): """ Access the task_queues :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList """ if self._task_queues is None: self._task_queues = TaskQueueList(self._version, workspace_sid=self._solution['sid'], ) return self._task_queues
python
{ "resource": "" }
q29092
WorkspaceContext.workers
train
def workers(self): """ Access the workers :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerList :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerList """ if self._workers is None: self._workers = WorkerList(self._version, workspace_sid=self._solution['sid'], ) return self._workers
python
{ "resource": "" }
q29093
WorkspaceContext.workflows
train
def workflows(self): """ Access the workflows :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList """ if self._workflows is None: self._workflows = WorkflowList(self._version, workspace_sid=self._solution['sid'], ) return self._workflows
python
{ "resource": "" }
q29094
WorkspaceContext.task_channels
train
def task_channels(self): """ Access the task_channels :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList """ if self._task_channels is None: self._task_channels = TaskChannelList(self._version, workspace_sid=self._solution['sid'], ) return self._task_channels
python
{ "resource": "" }
q29095
SigningKeyList.get
train
def get(self, sid): """ Constructs a SigningKeyContext :param sid: The sid :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext """ return SigningKeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )
python
{ "resource": "" }
q29096
SigningKeyPage.get_instance
train
def get_instance(self, payload): """ Build an instance of SigningKeyInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance """ return SigningKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], )
python
{ "resource": "" }
q29097
SigningKeyContext.update
train
def update(self, friendly_name=values.unset): """ Update the SigningKeyInstance :param unicode friendly_name: The friendly_name :returns: Updated SigningKeyInstance :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance """ data = values.of({'FriendlyName': friendly_name, }) payload = self._version.update( 'POST', self._uri, data=data, ) return SigningKeyInstance( self._version, payload, account_sid=self._solution['account_sid'], sid=self._solution['sid'], )
python
{ "resource": "" }
q29098
DayPage.get_instance
train
def get_instance(self, payload): """ Build an instance of DayInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.bulk_exports.export.day.DayInstance :rtype: twilio.rest.preview.bulk_exports.export.day.DayInstance """ return DayInstance(self._version, payload, resource_type=self._solution['resource_type'], )
python
{ "resource": "" }
q29099
ThisMonthPage.get_instance
train
def get_instance(self, payload): """ Build an instance of ThisMonthInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance """ return ThisMonthInstance(self._version, payload, account_sid=self._solution['account_sid'], )
python
{ "resource": "" }